Reputation: 2127
Let's say I am writing the following C code in WebAssembly Text format:
if (a < 2) a = 5;
else a = 6;
WASM:
(if
(i32.eq (get_local $x) (i32.const 10))
(then (i32.local 5) (set_local $x))
(else (i32.const 7) (local.set $a))
)
This also works:
(
;; ....
get_local $a
i32.const 2
i32.lt_s ;; a < 2
(if
(then
i32.const 5
local.set $a
)
(else
i32.const 7
local.set $a
)
)
;; ...
)
Which one to follow? Why the difference over writing operations before and after the operands?
Upvotes: 0
Views: 306
Reputation: 86
Webassembly text format is a (virtual) stack machine, meaning you can only add and remove things from the end of a stack (think list).
i32.const 10 ;;stack=[10]
i32.const 6 ;;stack=[10, 6]
i32.const 2 ;;stack=[10, 6, 2]
i31.add ;;consume two from stack and then put result on stack. stack=[10, 8]
i32.add ;;consume two from stack and then put result on stack. stack=[18]
This is how webassembly text format behaves, however you are allowed to use parenthesis (S-expressions) to choose the order they are put on the stack.
(i32.const 98 (i32.const 3)) ;;stack=[3, 98]
Allowing for much easier (for humans) to read syntax eg:
(i32.add (i32.const 10) (i32.add (i32.const 6) (i32.const 2)) ;;stack=[18]
So to answer your question: It doesnt matter which you use but if you are writing .wat by hand its clearly easier to use s-expressions.
Upvotes: 0
Reputation: 17114
It is purely a matter of personal preference -- the assembled code is the same. Which style do you prefer? (But I must say, your WASM code doesn't do what your C code does!)
Upvotes: 1