Search code examples
webassembly

Why can't I use constant expressions in some Wasm instructions that require numeric literals?


Why can't I use constant expressions in some Wasm instructions that require numeric literals? Because it seems to me that they have the same effect, but constant expressions would be more flexible during the compilation.

The correct usage:

(i32.load8_u (local.get 0)))  ;; Correct usage.

The wrong usage with an error:

error: unexpected token "(", expected a numeric index or a name (e.g. 12 or $foo).

(i32.load8_u (local.get (i32.const 0)))) ;; Wrong usage.

Why does WebAssembly design it like this? One reason I can come up with is for simplicity, any else?


Solution

  • (i32.const 0) is a separate instruction that produces a stack operand. The local index 0 to local.get is an immediate of that instruction itself (just like 0 is an immediate to i32.const). It wouldn't be useful to make it a stack operand, since the value has to be statically known anyway, otherwise it wouldn't be possible to validate the instruction nor to compile it to machine code or know its resulting type.