v / examples / wasm_codegen / main.v
71 lines · 65 sloc · 1.64 KB · 1acfabe2e763c0e8edef113a3fe16d563365e9b0
Raw
1import os
2import wasm
3
4// Install Wasmer:
5// $ curl https://get.wasmer.io -sSfL | sh
6// $ wasmer --version
7//
8// Create `examples/wasm_codegen/math.wasm`:
9// $ v run examples/wasm_codegen/main.v
10//
11// Call entrypoints with the current Wasmer CLI:
12// $ wasmer run examples/wasm_codegen/math.wasm --invoke add 3 5
13// 8
14// $ wasmer run examples/wasm_codegen/math.wasm --invoke factorial 10
15// 3628800
16// $ wasmer run examples/wasm_codegen/math.wasm --invoke pythagoras 30 40
17// 50
18fn main() {
19 mut math := Math{}
20 math.function_add('add')
21 math.function_factorial('factorial')
22 math.function_pythagoras('pythagoras')
23 math.save(os.join_path(@DIR, 'math.wasm'))!
24}
25
26struct Math {
27 wasm.Module
28}
29
30fn (mut math Math) function_add(name string) {
31 mut func := math.new_function(name, [.i32_t, .i32_t], [.i32_t])
32 func.local_get(0)
33 func.local_get(1)
34 func.add(.i32_t)
35 math.commit(func, true)
36}
37
38fn (mut math Math) function_factorial(name string) {
39 mut func := math.new_function(name, [.i64_t], [.i64_t])
40 func.local_get(0)
41 func.eqz(.i64_t)
42 block := func.c_if([], [.i64_t])
43 func.i64_const(1)
44 func.c_else(block)
45 func.local_get(0)
46 func.local_get(0)
47 func.i64_const(1)
48 func.sub(.i64_t)
49 func.call(name)
50 func.mul(.i64_t)
51 func.c_end(block)
52 math.commit(func, true)
53}
54
55fn (mut math Math) function_pythagoras(name string) {
56 mut func := math.new_function(name, [.f32_t, .f32_t], [.f64_t])
57 func.local_get(0)
58 func.local_get(0)
59 func.mul(.f32_t)
60 func.local_get(1)
61 func.local_get(1)
62 func.mul(.f32_t)
63 func.add(.f32_t)
64 func.sqrt(.f32_t)
65 func.cast(.f32_t, true, .f64_t)
66 math.commit(func, true)
67}
68
69fn (mut math Math) save(path string) ! {
70 os.write_file_array(path, math.compile())!
71}
72