🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Text Format: Read WAT

WebAssembly Text Format is the readable form of a WebAssembly module. Each line names one part of the module, and the lines nest inside each other.

The module line

This line opens the module.

(module

The function line

This line opens the function and lists its inputs and output.

(func (export "add") (param i32 i32) (result i32)

The body lines

These lines are the three steps of add.

local.get 0
local.get 1
i32.add

Read it as a call

This call runs the function just read.

console.log(instance.exports.add(4, 6));

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log('4 + 6 =', instance.exports.add(4, 6));
  console.log('10 + 20 =', instance.exports.add(10, 20));
})();

Key points

  • WAT: the readable text form of WebAssembly.
  • Module: the outer wrapper that holds a whole WebAssembly program.
  • Func: one function inside the module.
  • Param: one input a function takes in.
  • Result: one output a function gives back.
  • Use the line order to read a module from the outside in.
  • Use the closing parenthesis to find where one part ends.

In this example, the first line holds the module bytes as text. The next line turns that text into bytes. Then the code builds the module and waits for it. Then it calls add with 4 and 6. Then it calls add with 10 and 20. The two lines print 10 and 30. Reading the lines tells you what the module does before you run it.

Note

Extra spaces and line breaks do not change what the module does.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

In the line (func (export "add") (param i32 i32) (result i32), what does (result i32) say?