Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add return_call example for WASM #2693

Merged
merged 8 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions live-examples/wat-examples/statements/call.wat
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
(module
;; Import the `greet` function from the environment
(import "env" "greet" (func $greet))

(func
;; call the greet function
;; Call the imported `greet` function
call $greet
)

(start 1) ;; run the first function automatically
;; Automatically run the first function when the module starts
(start 1)
)
7 changes: 7 additions & 0 deletions live-examples/wat-examples/statements/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@
"title": "Wat Demo: return",
"type": "wat"
},
"return_call": {
"watExampleCode": "./live-examples/wat-examples/statements/return_call.wat",
"jsExampleCode": "./live-examples/wat-examples/statements/return_call.js",
"fileName": "return_call.html",
"title": "Wat Demo: return_call",
"type": "wat"
},
"select": {
"watExampleCode": "./live-examples/wat-examples/statements/select.wat",
"jsExampleCode": "./live-examples/wat-examples/statements/select.js",
Expand Down
6 changes: 6 additions & 0 deletions live-examples/wat-examples/statements/return_call.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const url = '{%wasm-url%}';
const { instance } = await WebAssembly.instantiateStreaming(fetch(url));
const result = instance.exports.fac(5n);

console.log(result);
// Expected output: 120n
22 changes: 22 additions & 0 deletions live-examples/wat-examples/statements/return_call.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
(module
;; Calculate the factorial of a number
(func $fac (export "fac") (param $x i64) (result i64)
;; Call the `fac-aux` function with $x and 1 parameters
(return_call $fac-aux (local.get $x) (i64.const 1))
)

;; Perform the factorial calculation
(func $fac-aux (param $x i64) (param $r i64) (result i64)
;; If $x is zero, return the accumulated result $r
(if (result i64) (i64.eqz (local.get $x))
(then (return (local.get $r)))
(else
;; Otherwise, recursively call `fac-aux` with $x-1 and $x*$r
(return_call $fac-aux
(i64.sub (local.get $x) (i64.const 1))
(i64.mul (local.get $x) (local.get $r))
)
)
)
)
)
Loading