Hello,
I've been trying to write a Jack to WebAssembly compiler, since WASM also is a stack based language like the Jack VM and this would allow Jack programs to be run inside a browser.
Basic expression evaluation and assigning variables works like a charm. Blocks such as while and if pose a challenge though that I don't know how to tackle. In Jack, these blocks allow you to return from the function at any time, in WASM however, it seems that you cannot do that so easily. Take for instance the following Jack code:
class Math {
/** Returns the absolute value of x. */
function int abs(int x) {
if (x < 0) {
return -x;
} else {
return x;
}
}
}
Using my compiler, I get the following WASM out:
(module $Math
(func $abs
(export "abs")
(param $p_x i32)
(result i32)
;; if (x < 0)
(block $ELSE0
(block $IF0
(br_if $IF0
(i32.eqz
(i32.lt_s
(local.get $p_x)
(i32.const 0)
)
)
)
)
;; return -x;
(return
(i32.sub
(i32.const 0)
(local.get $p_x)
)
)
(br $ELSE0)
;; return x;
(return
(local.get $p_x)
)
)
)
)
When trying to compile this in NodeJS, I get the following error:
CompileError: WebAssembly.instantiate(): Compiling function #0:"abs" failed: expected 1 elements on the stack for fallthru to @1, found 0 @+59
Anyone here with a bit more experience in compiler construction and/or WASM know how to solve this?
I've tried to find answers on google, but to no avail.