iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🛠️

Build Your Own WebAssembly Compiler

に公開1件

This article is a translation and paraphrase of Build your own WebAssembly Compiler. I have also added some original explanations.

Preface

If you haven't heard of WebAssembly and want a truly thorough introduction, I recommend reading Lin Clark's Cartoon Guide.

In this blog post, you can learn "what" WebAssembly is, but I'd also like to briefly touch upon "why" it exists.

From my perspective, this diagram summarizes it very concisely.

execution

The diagram above shows a simplified timeline of JavaScript code execution in a browser. From left to right, the code (typically delivered in a minified state) is parsed into an AST, initially executed by an interpreter, and gradually optimized/re-optimized to finally run very fast. Modern JavaScript is fast, but it takes time to speed up.

The diagram below represents the equivalent for WebAssembly. Code written in various languages (Rust, C, C#, etc.) is compiled into WebAssembly and delivered in binary format. This is decoded, compiled, and executed very easily, providing fast and predictable performance.

Why Build Your Own?

Last year, WebAssembly received a huge response. It was even voted the 5th "most loved" language in the Stack Overflow developer survey.

love

This is an interesting result considering that for most people, WebAssembly is a compilation target rather than a language used directly.

The technical aspects of WebAssembly are very fascinating, but most people won't have the chance to touch WebAssembly itself.

Writing a compiler is a great opportunity to dive into the details of WebAssembly to learn what it is and how it works. And, it's also fun.

Finally, my goal was not to create a fully featured programming language or a truly excellent one.

My goal was to create a language "sufficient" enough to write a program that renders the Mandelbrot set. This language is compiled into WebAssembly using a browser-based compiler I developed in TypeScript.

mandelbrot

I named this language "chasm". You can also try it out here!

Minimal Wasm Module

Before we dive into the compiler, let's create a simpler, minimal WebAssembly module.

Here is an emitter that creates the smallest valid WebAssembly module. (Emitter: a term used for the part of a compiler that outputs instructions for the target system)

const magicModuleHeader = [0x00, 0x61, 0x73, 0x6d];
const moduleVersion = [0x01, 0x00, 0x00, 0x00];

export const emitter: Emitter = () => {
    return Uint8Array.from([
        ...magicModuleHeader,
        ...moduleVersion
    ]);
}

This consists of two parts: a magic header representing 0asm in ASCII strings, and a version number.

These 8 bytes form a valid WebAssembly module. More generally, these are delivered to the browser as .wasm files.

To run a WebAssembly module, you need to instantiate it as follows:

const wasm = emitter();
const instance = await WebAssembly.instantiate(wasm);

When you run the code above, you'll notice that the instance doesn't actually do anything. This is because the wasm module contains no instructions.

If you want to try this code yourself, there are commits for every step on GitHub.

Add Function

Let's make the wasm module do something more useful by implementing a function that adds two floating-point numbers.

Since WebAssembly is a binary format and not very readable (at least to humans), it is usually written in WebAssembly Text Format (WAT).

Below is a module in WAT format that defines an exported function named $add which takes two floating-point parameters, adds them, and returns the result.

(module
 (func $add (param f32) (param f32) (result f32)
   get_local 0
   get_local 1
   f32.add)
 (export "add" (func 0))
)

If you want to try WAT, you can use the wat2wasm tool from the WebAssembly Binary Toolkit to compile WAT files into wasm modules.

The code above shows several interesting details about WebAssembly:

  • WebAssembly is a low-level language with a small instruction set (about 60), where many instructions closely resemble CPU instructions. This makes it easy to compile wasm modules into CPU-specific machine code.
  • There is no built-in I/O. There are no instructions for writing to a terminal, screen, or network. For a wasm module to interact with the outside world, it must do so through the host environment (JavaScript in the case of a browser).
  • WebAssembly is a stack machine. In the example above, get_local 0 gets the local variable at index 0 (the function parameter in this case) and pushes it onto the stack, similar to subsequent instructions. The f32.add instruction pops two values from the stack, adds them, and pushes the result back onto the stack.
  • WebAssembly has only four numeric types: two integer types and two floating-point types. I will explain this more later.

Let's update the emitter to output this hardcoded WebAssembly module.

WebAssembly modules consist of predefined optional sections, each preceded by a numeric identifier.

These include a type section that encodes type signatures and a function section that indicates the type of each function.

A wasm module consists of a few bytes of header followed by a series of areas called "sections."

The start of a wasm module always begins with the 4 bytes 0x00 0x61 0x73 0x6D. This is the so-called magic number, which represents "\0asm" in ASCII code. The next 4 bytes represent the version. At the time of writing, the version is only 1, which is 0x01 0x00 0x00 0x00.

These were implemented in the minimal wasm module earlier.

After that, areas called "sections" continue until the end. The structure looks roughly like this:

module_structure

The interesting part is the code section. Here is how the add function above is created in binary:

const code = [
 Opcodes.get_local /** 0x20 */,
 ...unsignedLEB128(0),
 Opcodes.get_local /** 0x20 */,
 ...unsignedLEB128(1),
 Opcodes.f32_add   /** 0x92 */
];

const functionBody = encodeVector([
 ...encodeVector([]) /** locals */,
 ...code,
 Opcodes.end /** 0x0b */
]);

const codeSection = createSection(
  Section.code, /** 0x0a */
  encodeVector([functionBody])
);

Here we have defined an Opcodes enum in TypeScript. This contains all the wasm instructions. The unsignedLEB128 function is a standard variable-length encoding used to encode instruction parameters.

The function's instructions combine the local variables of that function (none in this case) with the opcode named end to signal the end of the function.

Finally, all functions are encoded into the section. The encodeVector function simply prefixes a collection of byte arrays with their total length.

With this, a module of about 30 bytes in total is complete.

The JavaScript host code can be updated to include this exported function.

const { instance } = await WebAssembly.instantiate(wasm);
console.log(instance.exports.add(5, 6));

Interestingly, when you inspect the exported add function in Chrome Dev Tools, it is identified as a "native function."

The complete code for this step, including unit tests, can be found on GitHub.

Let's Build a Compiler

Now that we've seen how to dynamically create a Wasm module, let's turn our attention to the task of building a compiler.

First, let's start with an explanation of terminology.

Here is the chasm code annotated to show the main components of the language.

term

Instead of giving textbook definitions for each, you will become familiar with them as the compiler evolves.

The compiler itself consists of three parts:

  • A tokenizer that splits the input program (string) into tokens
  • A parser that converts these tokens into an Abstract Syntax Tree (AST)
  • And finally, an emitter that converts the AST into a Wasm binary module

This is a very standard compiler architecture.

arch

Instead of aiming for a complete implementation of a Wasm compiler, we will work on implementing a small subset.

Our goal this time is to create a compiler that only supports print statements displaying simple numeric literals in the chasm language.

print 22
print 45

Tokenizer

The tokenizer moves through the input string character by character and matches patterns representing specific token types.

The following code uses simple regular expressions to create three matches (number, keyword, and whitespace).

const keywords = ["print"];

 // returns a token if the given regex matches at the current index
const regexMatcher = (regex: string, type: TokenType): Matcher => {
    return (input: string, index: number) => {
        const match = input.substring(index).match(regex);
        return (
        match && {
            type,
            value: match[0]
        }
        );
    };
}

const matchers = [
    regexMatcher("^[.0-9]+", "number"),
    regexMatcher(`^(${keywords.join("|")})`, "keyword"),
    regexMatcher("^\\s+", "whitespace")
];

(These regular expressions are somewhat loose.)

The Matcher interface defines a function that, given an input string input and an index, returns a token if a match is found.

The main body of the tokenizer iterates through the characters of the string, finds the first match, and adds the provided token to the output array.

export const tokenize: Tokenizer = input => {
  const tokens: Token[] = [];

  let index = 0;
  while (index < input.length) {
    const matches = matchers.map(m => m(input, index)).filter(f => f)
    const match = matches[0];
    if (match.type !== "whitespace") {
      tokens.push(match);
    }
    index += match.value.length;
  }

  return tokens;
};

If we feed the string print 23.1 to this tokenizer, we get the following output.

[
 {
   "type": "keyword",
   "value": "print",
   "index": 1
 },
 {
   "type": "number",
   "value": "23.1",
   "index": 7
 }
]

As seen from the input above, the tokenizer removes meaningless whitespace (in this case) and ensures that everything in the input string is a valid token.

However, there is no guarantee that the input is grammatically correct.

For example, the tokenizer we implemented here would happily handle "print print", which is clearly incorrect grammatically.

The resulting array of tokens is then passed to the parser.

Parser

The purpose of the parser is to create an Abstract Syntax Tree (AST), which is a tree structure encoding the relationships between tokens. As a result, a form is created that could be sent to an interpreter and executed directly.

The parser iterates through the given tokens and consumes them with the eatToken function.

export const parse: Parser = tokens => {
  const iterator = tokens[Symbol.iterator]();
  let currentToken = iterator.next().value;
 
  const eatToken = () => {
      currentToken = iterator.next().value;
      return currentToken;
  };

  [...]

  const nodes: StatementNode[] = [];
  while (index < tokens.length) {
     nodes.push(parseStatement());
  }

  return nodes;
};

I don't know where the concept of "eating" tokens in the eatToken naming comes from, but it seems to be standard parser terminology.

The goal of the parser above is to turn an array of tokens into an array of statements.

A statement is the core building block of this language. We expect the given tokens to fit this pattern, and if they don't, we throw an error (not shown above).

The parseStatement function expects each statement to begin with a keyword and switches processing based on the keyword.

const parseStatement = () => {
  if (currentToken.type === "keyword") {
  switch (currentToken.value) {
    case "print":
      eatToken();
      return {
        type: "printStatement",
        expression: parseExpression()
      };
    }
  }
};

Currently, the only supported keyword is print, and in this case, it returns a printStatement type AST node with the associated expression parsed.

And here is the expression parser.

const parseExpression = () => {
  let node: ExpressionNode;
  switch (currentToken.type) {
    case "number":
      node = {
        type: "numberLiteral",
        value: Number(currentToken.value)
      };
      eatToken();
      return node;
  }
};

In its current form, this language only accepts expressions consisting of a single number, i.e., numeric literals.

Therefore, the expression parser implemented above expects the next token to be a number, and if it matches, it returns a numberLiteral type node.

When executed on "print 23.1", the parser outputs the following AST.

[
  {
    "type": "printStatement",
    "expression": {
      "type": "numberLiteral",
      "value": 23.1
    }
  }
]

You can see that the AST for this language is an array of statement nodes.

Note that syntax analysis (the process of generating an AST with a parser) ensures that the input program is grammatically correct—meaning it's properly constructed—but it doesn't guarantee that the program will execute successfully. In other words, runtime errors might occur.

We are finally entering the last step!

Emitter

Currently, the emitter is outputting a hardcoded add function. From now on, it needs to take this AST and output appropriate instructions like this:

const codeFromAst = ast => {
  const code = [];

  const emitExpression = node => {
    switch (node.type) {
      case "numberLiteral":
        code.push(Opcodes.f32_const);
        code.push(...ieee754(node.value));
        break;
    }
  };

  ast.forEach(statement => {
    switch (statement.type) {
      case "printStatement":
        emitExpression(statement.expression);
        code.push(Opcodes.call);
        code.push(...unsignedLEB128(0));
        break;
    }
  });

  return code;
};

The emitter iterates through the statements forming the root of the AST and matches the only statement type, print.

Recall that since WebAssembly is a stack machine, expression instructions are processed first, and the result remains on the stack.

The print function is implemented by a call operation, calling the function at index 0.

Previously, we saw how a Wasm module can export functions, but conversely, we can also import functions into a Wasm module when instantiating it. Here, we provide an env.print function that outputs a log to the console.

const instance = await WebAssembly.instantiate(wasm, {
  env: {
    print: console.log
  }
});

This function can be addressed by index, which means call 0.

The complete code for the compiler at this point can be found on GitHub. You can also try this example in the online chasm compiler playground.

Also, for better understanding, here is how the program progresses through the various stages of the compiler.

print_program

So far, we have introduced quite a few data structures, but their effects haven't been strongly felt yet. At this point, providing a separate tokenizer, parser, and emitter is overkill for a language that only displays simple numbers.

However, as the complexity of the language increases, this architecture will prove to be very effective!

Implementing Expressions

Next, let's look at the implementation of binary expressions.

This will allow the language to perform simple numeric operations. For example, it will be possible to execute ((42 + 10) / 2) and display the result.

The changes to the tokenizer are very minor, involving adding a few regular expression matchers for parentheses and operators. I'll omit those code snippets here and just show the resulting output.

[
  { "type": "keyword", "value": "print" },
  { "type": "parens", "value": "(" },
  { "type": "parens", "value": "(" },
  { "type": "number", "value": "42" },
  { "type": "operator", "value": "+" },
  { "type": "number", "value": "10" },
  { "type": "parens", "value": ")" },
  { "type": "operator", "value": "/" },
  { "type": "number", "value": "2" },
  { "type": "parens", "value": ")" }
]

Next, let's look at the changes to the parser. Since the expression parser can now encounter either a number or a parens token, we need to add code to handle parens.

const parseExpression = () => {
  let node: ExpressionNode;
  switch (currentToken.type) {
    case "number":
      [...]
    case "parens":
      eatToken();
      const left = parseExpression();
      const operator = currentToken.value;
      eatToken();
      const right = parseExpression();
      eatToken();
      return {
        type: "binaryExpression",
        left, right, operator
      };
  }
};

This parser employs recursive descent parsing. Note that the parsing of parens expressions is done recursively, with the left and right nodes calling the parseExpression function again.

The AST for the program print ((42 + 10) / 2) is as follows:

[{
 type: "printStatement",
 expression: {
   type: "binaryExpression",
   left: {
     type: "binaryExpression",
     left: {
       type: "numberLiteral",
       value: 42
     },
     right: {
       type: "numberLiteral",
       value: 10
     },
     operator: "+"
   },
   right: {
     type: "numberLiteral",
     value: 2
   },
   operator: "/"
 }
}];

In this example, the tree structure is clearer.

Finally, the emitter is updated to handle the binaryExpression node type as follows:

const emitExpression = (node) =>
  traverse(node, (node) => {
    switch (node.type) {
      case "numberLiteral":
        code.push(Opcodes.f32_const);
        code.push(...ieee754(node.value));
        break;
      case "binaryExpression":
        code.push(binaryOpcode[node.operator]);
        break;
   }
});

The traverse function in the code above traverses the tree structure, invoking the given visitor for each node.

While linear structures can logically only be traversed in one way, tree structures can be traversed in several different ways.

Specifically, when a node is encountered, its left child is visited, then its right child, and finally the root itself. This sequence ensures Wasm instructions are output in the correct order for a stack machine—operands followed by the operator.

With that, all the necessary changes to support expressions are complete. Give it a try online.

The compiler's architecture is beginning to prove its worth.

Variables

Next, let's add variables.

By adding variables, more interesting chasm programs like the following become possible:

var f = 2
print (f + 1)

Variables are declared with the var keyword and can be used as identifiers within expressions.

I won't go into detail about the changes to the tokenizer here, as it's just a matter of adding a few regular expressions.

The main loop of the parser, which reads consecutive statements from the token array, determines the type of statement based on the keywords it encounters.

const parseVariableDeclarationStatement = () => {
  eatToken(); // var
  const name = currentToken.value;
  eatToken();
  eatToken(); // =
  return {
    type: "variableDeclaration",
    name,
    initializer: parseExpression()
  };
};

const parseStatement: ParserStep<StatementNode> = () => {
  if (currentToken.type === "keyword") {
    switch (currentToken.value) {
      case "print":
        return parsePrintStatement();
      case "var":
        return parseVariableDeclarationStatement();
    }
  }
};

Parsing variable declarations is quite straightforward. The parseVariableDeclarationStatement function also utilizes the expression parser, allowing for variables to be declared and assigned initial values from expressions such as var f = (1 + 4).

Next is the emitter. WebAssembly functions can have local variables; these are declared at the beginning of the function definition and accessed via get_local and set_local functions that retrieve and set values.

While variables in the AST are referenced by their identifier names, Wasm identifies local variables by their index.

The emitter needs to maintain this information in a symbol table, which is a simple map from symbol names to indices.

const symbols = new Map<string, number>();

const localIndexForSymbol = (name: string) => {
  if (!symbols.has(name)) {
    symbols.set(name, symbols.size);
  }
  return symbols.get(name);
};

Within the node traversal, when a variable declaration is encountered, its expression is emitted, and set_local is used to assign the value to the respective local variable.

  case "variableDeclaration":
    emitExpression(statement.initializer);
    code.push(Opcodes.set_local);
    code.push(...unsignedLEB128(localIndexForSymbol(statement.name)));
    break;

When an identifier is found within an expression, its value is retrieved using get_local.

  case "identifier":
    code.push(Opcodes.get_local);
    code.push(...unsignedLEB128(localIndexForSymbol(node.value)));
    break;

Additionally, the function encoding we saw at the beginning is updated to include the locals for the function that the emitter builds. The chasm language has only one type for variables: they are all floating-point numbers.

Let's try defining a variable and using it in a print statement. As always, you can try it online!

While Loops

One of the final language constructs needed to achieve the goal of rendering the Mandelbrot set is some kind of loop.

In chasm, I chose the while loop, as demonstrated by this simple program that prints numbers from 0 to 9.

var f = 0
while (f < 10)
  print f
  f = (f + 1)
endwhile

WebAssembly has various control flow instructions (branch, if, else, loop, block). The following WAT shows how a while loop is constructed.

(block
 (loop
   [loop condition]
   i32.eqz
   [nested statements]
   br_if 1
   br 0)
)

Branching in WebAssembly is based on stack depth. The outer block and loop instructions push entries onto the control-flow stack. The br_if 1 instruction performs a conditional branch to stack depth 1, and br 0 performs an unconditional branch to stack depth 0, repeating the loop.

Here is how the emitter generates the same thing in binary format.

  case "whileStatement":
    // outer block
    code.push(Opcodes.block);
    code.push(Blocktype.void);
    // inner loop
    code.push(Opcodes.loop);
    code.push(Blocktype.void);
    // compute the while expression
    emitExpression(statement.expression);
    code.push(Opcodes.i32_eqz);
    // br_if $label0
    code.push(Opcodes.br_if);
    code.push(...signedLEB128(1));
    // the nested logic
    emitStatements(statement.statements);
    // br $label1
    code.push(Opcodes.br);
    code.push(...signedLEB128(0));
    // end loop
    code.push(Opcodes.end);
    // end block
    code.push(Opcodes.end);
    break;

Screen Rendering

We are almost at the finish line!

Currently, the only way for us to see output from a chasm program is by using the print statement, which is connected to the console via a function imported by the WebAssembly module.

For the Mandelbrot set, we need to display an image on the screen rather than text.

To achieve this, we will use another very important component of WebAssembly modules: linear memory.

linear_memory

As mentioned earlier, WebAssembly has only four numeric data types.

You might wonder how languages with rich type systems (strings, structs, arrays, etc.) can be compiled into WebAssembly.

WebAssembly modules can optionally define (or import) a block of linear memory.

This is a contiguous block of memory shared between the Wasm module and its host JavaScript. Therefore, if you want to pass a string to a WebAssembly module, you do so by writing the string into linear memory.

In chasm, since we just want to have some kind of display, we use linear memory as a form of Video RAM.

The chasm language supports a simple set-pixel command that takes three expressions: x-position, y-position, and color. For example, the following program fills the screen with a horizontal gradient.

var y  = 0
while (y < 100)
  var x  = 0
  while (x < 100)
    setpixel x y (x * 2)
    x = (x + 1)
  endwhile
  y = (y + 1)
endwhile

The setpixel command is implemented using Wasm's store instruction, which writes to linear memory. On the JavaScript hosting side, this same linear memory is read and copied to an HTML canvas. I won't explain the code changes here, but as always, they can be seen on GitHub.

With that, the chasm language is complete and can now render the Mandelbrot set!

mandelbrot_render

Summary

I hope you enjoyed this tutorial and gained some understanding of how WebAssembly and compilers work.

For me, this project was a lot of fun. I had never written a compiler before, but I've always wanted to.

In the future, I'd like to explore more complex topics such as memory management. For instance, I'm considering introducing memory allocators for storing strings, arrays, and other data within linear memory.

I hope to cover all these topics in future articles.

References

Discussion