WebAssembly from the Ground Up – learn WASM by building a compiler

57 points by marianoguerra


Hi!

We (pdubroy & marianoguerra) just launched an online book called WebAssembly from the Ground Up. It’s an online book to learn Wasm by building a simple compiler in JavaScript.

This is the book we wish we’d had 3 years ago. Unlike many WebAssembly resources that focus on use cases and tooling, we wanted a deep dive into how Wasm actually works.

We focus on the core of WebAssembly: the module format and the instruction set. We think the low-level details — the “virtual ISA” — are the most interesting part, and we had the crazy idea that writing a compiler is the best way to learn it.

Over the course of the book, you’ll build up two things:

1: An “assembler library”, that can be used to produce WebAssembly modules. Here’s an example:

const mod = module([
  typesec([functype([], [])]),
  funcsec([typeidx(0)]),
  exportsec([export_('main', exportdesc.func(0))]),
  codesec([code(func([], [instr.end]))]),
]);
return Uint8Array.from(mod.flat(Infinity));

2: A very simple compiler for a language called Wafer, which looks like this:

extern func setPixel(x, y, r, g, b, a);

func draw(width, height, t) {
  let y = 0;
  while y < height {
    let x = 0;
    while x < width {
      let r = t;
      let g = x;
      let b = y;
      let a = 255;
      setPixel(x, y, r, g, b, a);
      x := x + 1;
    }
    y := y + 1;
  }
  0
}

In case you’re not a fan of JavaScript, we’ve already heard of readers who’ve worked through the book in F# and Haskell. :-D

You can check out a sample here: https://wasmgroundup.com/book/contents-sample/ — we’d love to hear what you think! There’s also a 25% discount for Lobsters readers — just use the code LOBSTERS25 at checkout.

bruxisma

The PDF version of the site/book has some issues. Code splitting across pages, poor line spacing between the end of code samples and text from the next paragraph, copying the code does not save newlines either and this differs from the website.

Also, maybe I’m a stickler for media, but if I get a book I expect there to be an “end” and not a code sample section named “exports” 😅

I’d very much like to see at least the page breaks improved. 🙂

WilhelmVonWeiner

So this is an ad for a paid book?

marianoguerra

The library is here: @wasmgroundup/emit

you can play with the code right in the browser here: stackblitz.com/github/wasmgroundup/code

The code repo is here: https://github.com/Wasmgroundup/code