Skip to content

Commit 88a89f6

Browse files
committed
Add functions
1 parent dedeebb commit 88a89f6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/functions.wat

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
(module
2+
(memory $memory 1)
3+
4+
;; int si() {
5+
;; static int x;
6+
;; return ++x;
7+
;; }
8+
(func $si (result i32)
9+
(local $x i32)
10+
(i32.store offset=12
11+
(i32.const 0)
12+
(tee_local $x
13+
(i32.add
14+
(i32.load offset=12
15+
(i32.const 0))
16+
(i32.const 1))))
17+
(get_local $x))
18+
19+
;; int factorial(int n) {
20+
;; if (n == 0)
21+
;; return 1;
22+
;; else
23+
;; return n * factorial(n - 1);
24+
;; }
25+
(func $factorial (param $n i32) (result i32)
26+
(local $l0 i32) (local $l1 i32)
27+
(block $B0
28+
(br_if $B0
29+
(i32.eqz
30+
(get_local $n)))
31+
(set_local $l1
32+
(i32.const 1))
33+
(loop $L1
34+
(set_local $l1
35+
(i32.mul
36+
(get_local $n)
37+
(get_local $l1)))
38+
(set_local $n
39+
(tee_local $l0
40+
(i32.add
41+
(get_local $n)
42+
(i32.const -1))))
43+
(br_if $L1
44+
(get_local $l0)))
45+
(return
46+
(get_local $l1)))
47+
(i32.const 1))
48+
)

0 commit comments

Comments
 (0)