如何在WebAssembly文本格式表示操作?



假设我正在用WebAssembly文本格式编写以下C代码:

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))
)

(
;; ....
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
)
)
;; ...
)

遵循哪一个?为什么在操作数之前和之后写操作会有不同?

这完全是个人偏好的问题——汇编的代码是相同的。你喜欢哪种风格?(但我必须说,你的WASM代码不做你的C代码做的!)

Webassembly文本格式是一个(虚拟)堆栈机,这意味着你只能从堆栈的末尾添加和删除东西(想想列表)。

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]

这是webassembly文本格式的行为,但是你可以使用括号(s表达式)来选择它们在堆栈上的顺序。

(i32.const 98 (i32.const 3)) ;;stack=[3, 98]

允许更容易(对人类)阅读语法例如:

(i32.add (i32.const 10) (i32.add (i32.const 6) (i32.const 2)) ;;stack=[18]

所以回答你的问题:不管你用什么,但如果你手写。wat,显然使用s表达式更容易。

相关内容

最新更新