Sikau

WebAssembly · Day 6 · about 40 min

An assembler for wasm text

Turn readable instructions into bytecode, then write a loop in it.

Nobody writes hex by hand

Wasm has a text format (WAT). Write a small assembler for its instructions — look each one up in an opcode table and encode its argument as LEB128 — then use it to program a loop with block, loop and br_if.

Structured control flow

const FACT_TEXT = `
  i32.const 1  local.set 1        ;; acc = 1
  block
    loop
      local.get 0  i32.const 1  i32.le_s  br_if 1   ;; if n <= 1: leave the block
      local.get 1  local.get 0  i32.mul  local.set 1 ;; acc = acc * n
      local.get 0  i32.const 1  i32.sub  local.set 0 ;; n = n - 1
      br 0                                           ;; back to the loop
    end
  end
  local.get 1`;

Wasm has no goto: only branches to enclosing blocks and loops, which keeps it easy to validate and compile.

The rest of this lesson

  • An assembler is a lookup tableexplain
  • Labels count outwardsexplain
  • Branch targetmatch
  • Factorial by handpredict
  • Assemble and programwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 8 lessons of WebAssembly