WebAssembly: perform stack checks
[WebKit-https.git] / JSTests / wasm / function-tests / factorial.js
1 import * as assert from '../assert.js'
2 import Builder from '../Builder.js'
3
4 const b = new Builder();
5 b.Type().End()
6     .Import().End()
7     .Function().End()
8     .Export()
9         .Function("fac")
10     .End()
11     .Code()
12         .Function("fac", { params: ["i32"], ret: "i32" })
13             .GetLocal(0)
14             .I32Const(0)
15             .I32Eq()
16             .If("void", b =>
17                 b.I32Const(1)
18                 .Return()
19                )
20                 .GetLocal(0)
21             .GetLocal(0)
22             .I32Const(1)
23             .I32Sub()
24             .Call(0)
25             .I32Mul()
26             .Return()
27         .End()
28     .End()
29
30 const m = new WebAssembly.Module(b.WebAssembly().get());
31 const fac = (new WebAssembly.Instance(m)).exports.fac;
32 assert.eq(fac(0), 1);
33 assert.eq(fac(1), 1);
34 assert.eq(fac(2), 2);
35 assert.eq(fac(4), 24);
36 assert.throws(() => fac(1e7), RangeError, "Maximum call stack size exceeded.");