wabt icon indicating copy to clipboard operation
wabt copied to clipboard

How wasm is converted to S-expression form in wasm2wat?

Open abc767234318 opened this issue 2 years ago • 2 comments

I would like to ask how wasm is converted to S-expression form in wasm2wat. I know the concept of S-expressions, but I can't relate S-expressions to wasm instructions.

abc767234318 avatar Sep 21 '22 09:09 abc767234318

I'm not quite sure what you are asking, but wasm2wat (one of the tools which is part of wabt) does indeed convert from the wasm binary format into the wat format which is a S-expression (or at least something like one. For example:

$ ./bin/wasm2wat ./wasm2c/examples/fac/fac.wasm
(module
  (type (;0;) (func (param i32) (result i32)))
  (func (;0;) (type 0) (param i32) (result i32)
    local.get 0
    i32.const 0
    i32.eq
    if (result i32)  ;; label = @1
      i32.const 1
    else
      local.get 0
      local.get 0
      i32.const 1
      i32.sub
      call 0
      i32.mul
    end)
  (export "fac" (func 0)))

If you are literally asking for an explanation of exactly how the tool performs this action, there are several way to answer that. wabt is a C++ library that is capable of parsing the binary forrmat, building an intermediate representation (IR) in memory, and then using the IR to produce a text file in the .wat format. Are there more specific details you are interested in?

sbc100 avatar Sep 21 '22 21:09 sbc100

I want to know if the wasm instructions fold according to the change in the operand stack or whether it uses the value on the operand stack?

abc767234318 avatar Sep 22 '22 02:09 abc767234318

There is a folded format for the instruction section, but IIRC it cannot present all of the stack ways operations can be ordered WRT the value stack, so wabt uses the flat format when output instruction sections.

For more information see: https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format And: https://webassembly.github.io/spec/core/text/instructions.html#folded-instructions

sbc100 avatar Sep 22 '22 09:09 sbc100

There is a folded format for the instruction section, but IIRC it cannot present all of the stack ways operations can be ordered WRT the value stack, so wabt uses the flat format when output instruction sections.

For more information see: https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format And: https://webassembly.github.io/spec/core/text/instructions.html#folded-instructions

Thank you very much for your answers.

abc767234318 avatar Sep 23 '22 01:09 abc767234318