Platform
Docs
Solutions
ContactLog In

Start Routing Notifications Today!

Courier is a notification service that centralizes all of your templates and messaging channels in one place which increases visibility and reduces engineering time.

Sign-up

webassembly-language-lexing-header
ENGINEERING

Build a WebAssembly Language for Fun and Profit: Lexing

Drew Youngwerth

August 18, 2022

WebAssembly (wasm) is a high performance assembly-like format optimized for the web. Code targeting WebAssembly can run at near-native speeds while still benefiting from the safe environment of a browser VM. Wasm has opened up a whole new world of demanding desktop-class apps that can comfortably run in the browser. For example, AutoCAD was able to port decades of code to the web using wasm. Cases like AutoCAD’s have made it clear that wasm will be a major disruptive force in how web apps are developed.

To facilitate the adoption of wasm, WebAssembly team developed a powerful compiler toolchain library called binaryen. Binaryen does a huge amount of heavy lifting for compiler authors. It offers dead code removal, code size reduction, and various performance optimizations out of the box.

As someone who has long been interested in programming languages, this piqued my interest. Writing compiled languages has always been a daunting task. What I found is binaryen made it incredibly fun and easy to build new languages that are shockingly speedy.

That's why I decided to create this guide and provide a simple overview designed to help get your feet wet in building languages and exploring the inner workings of wasm.

Here's a quick taste of the lisp inspired language we'll build, wispy:

1
(fn fib:i32 [val:i32]
2
(if (lt_i32 val 2)
3
val
4
(add_i32 (fib (sub_i32 val 1)) (fib (sub_i32 val 2)))))
5
6
(fn main:i32 [] (fib 15))

This simple function calculates values of the fibonacci sequence, a sequence of numbers that appears in surprising places through mathematics and nature. It's one of my favorite illustrations of how elegantly patterns of the universe can be described in code.

This guide is designed for intermediate to advanced software developers looking for a fun side project to challenge themselves with. By the end, we’ll have built a working compiler and runtime for wispy.

The guide will be broken down into three articles:

  • Setup and Lexing (this article): the process of converting the characters of code into meaningful units called tokens
  • Parsing: the process of converting the tokens into a logical tree known as an AST.
  • Compiling (or code generation): the process of converting the AST into the binary instructions run by our computer

Setup

In this guide, we will be using TypeScript and NodeJS. The concepts are highly portable, so feel free to use the environment you're most comfortable with. Our only major dependency, binaryen, has a simple C API. You are welcome to skip ahead to the next section if you're using a different language.

Requirements:

  • NodeJS v16+
  • Git

Quick Start

1
git clone git@github.com:drew-y/wispy.git
2
cd wispy
3
git checkout quickstart
4
npm i

Manual Setup

I've included manual setup instructions as an alternative to the quick start, in case you want to know exactly how the project was set up or just like doing things from scratch. If you've already done the quick start, skip to the next section.

  1. Open a terminal window and make a new directory:
1
mkdir wispy
2
cd wispy
  1. Initialize package.json:
1
npm init -y # Be sure to have NodeJS 16+ installed
  1. Install the project dependencies:
1
npm i @types/node binaryen typescript
  1. Add these two fields to the package.json
1
"type": "module", // Binaryen uses the new module format so we must follow suit
2
"bin": {
3
"wispy": "dist/index.mjs" // This will allow us to easily run the compiler from our terminal
4
},
  1. Create a tsconfig file:
1
npx tsc init .
  1. Set the following fields in tsconfig.json:
1
"module": "ES2022",
2
"rootDir": "./src",
3
"moduleResolution": "node",
4
"outDir": "./dist"

Lexing

Lexing is the process of digesting each individual character of our program into a set of tokens. A token is a group of characters that take on a special meaning when put together. Take the following snippet of wispy:

1
(add 1 2)

There are five unique tokens in that snippet (, add, 1, 2 and ). The lexer's job is simply to identify and list those tokens in order.Lexing is typically the first step in turning human readable code into something closer to what a computer can understand.

Defining Our Tokens

We'll start by defining our tokens in a new file:

1
# mts extension is important, it tells typescript to create a corresponding mjs file, so Node knows to use modules
2
3
mkdirp -p src/types/token.mts

First up is the IntToken. This token represents whole numbers like 1045:

1
// src/types/token.mts
2
export type IntToken = { type: "int"; value: number };

Next up is the FloatToken. This token represents numbers that may have a decimal, like 1.8:

1
// src/types/token.mts
2
export type FloatToken = { type: "float"; value: number };
3
4
/** Previously defined tokens omitted for brevity */

Now, let's define some identifier tokens. In wispy, an identifier can represent either the name of a function, or the name of a function parameter. We have two types of identifier tokens, a standard IdentifierToken and a TypedIdentifierToken.

An IdentifierToken is used in the body of a function to refer to the function's parameters or to call another function.

A TypedIdentifierToken is used when defining a function or a parameter. Typed identifiers take the form identifier:type. For example, val:i32 defines a parameter that is a 32-bit integer. When defining a function, the type represents the function's return type. For example, fib:i32 is a function that returns a 32-bit integer.

Here are the definitions:

1
// src/types/token.mts
2
export type IdentifierToken = { type: "identifier"; value: string };
3
export type TypedIdentifierToken = { type: "typed-identifier"; value: string };
4
5
/** Previously defined tokens omitted for brevity */

Up next is BracketToken. Wispy uses S-expression syntax, like lisp. So brackets are very important. To keep things simple we allow two kinds of brackets () and []. To keep things even more simple the compiler will treat () and [] as interchangeable. In actual use we will only use [] to define parameters.

1
// src/types/token.mts
2
export type BracketToken = { type: "bracket"; value: Bracket };
3
export type Bracket = "(" | ")" | "[" | "]";
4
5
/** Previously defined tokens omitted for brevity */

Finally we define the top level Token type:

1
// src/types/token.mts
2
export type Token = BracketToken | IntToken | FloatToken | IdentifierToken | TypedIdentifierToken;
3
/** Previously defined tokens omitted for brevity */

Token is a discriminated union. Discriminated Unions are an incredibly powerful programming language construct. They represent a value that can be one of many types. In our case, a Token can be any one of the more specific token types we defined earlier, such as IntToken or FloatToken. You'll notice that each of these tokens have a unique type field, such as type: "int" in the case of IntToken. This is the discriminator. Down the line you can pass a Token to a function and that function can use the type field to figure out which specific token it's working with.

At this point src/types/token.mts is finished and should look like a file.

To make our new types easily accessible, export them from a new index.mts file:

1
// src/types/index.mts
2
export * from "./token.mjs";

The Lex Function

Now that we have our tokens defined we can write the actual lex function. The lex function will take a string (i.e. a .wispy file) and output an array of tokens (Token[]):

Make a new lex file:

1
mkdirp -p src/lexer.mts

Define the lex function:

1
// src/lexer.mts
2
import { Bracket, Token } from "./types/index.mjs";
3
4
export const lex = (input: string): Token[] => {
5
const chars = input
6
// Remove any leading or trailing whitespace for simplicity
7
.trim()
8
// Break up the file into single characters
9
.split("");
10
11
// This array stores our tokens
12
const tokens: Token[] = [];
13
14
// The loop continues as long as we have characters to consume
15
while (chars.length) {
16
// Here, a word is an unidentified token. It is usually any single group of non-whitespace
17
// characters such as 123 or 123.4 or im_a_function
18
const word = consumeNextWord(chars); // We'll define this function later
19
20
// We ran out of tokens. Break out of the loop.
21
if (word === undefined) break;
22
23
const token = identifyToken(word); // We'll define this function later
24
25
// Add the token to our store
26
tokens.push(token);
27
}
28
29
// Return the tokens
30
return tokens;
31
};

Next we define the consumeNextWord function:

1
// src/lexer.mts
2
3
/** previous function(s) omitted for brevity */
4
5
const consumeNextWord = (chars: string[]): string | undefined => {
6
const token: string[] = [];
7
8
while (chars.length) {
9
// Save a preview of the current character without modifying the array
10
const char = chars[0];
11
12
// No more characters to read
13
if (char === undefined) break;
14
15
// Whitespace characters terminate the token (we'll define the isWhitespace function later)
16
if (isWhitespace(char) && token.length) {
17
chars.shift(); // Remove the whitespace so it doesn't get included in the next token
18
break;
19
}
20
21
// Discard leading whitespace characters
22
if (isWhitespace(char)) {
23
chars.shift();
24
continue;
25
}
26
27
// Terminator tokens signify the end of the current token (if any). (we'll define the isTerminatorToken function later)
28
if (isTerminatorToken(char) && token.length) break;
29
30
// Add the character to the token and discard it from the input
31
token.push(char);
32
chars.shift();
33
34
// If the only token we've received so far is a single character token, that's our whole token.
35
if (isTerminatorToken(char)) break;
36
}
37
38
// If we have characters for our token, join them into a single word. Otherwise, return undefined to signal to the lexer
39
// that we are finished processing tokens.
40
return token.length ? token.join("") : undefined;
41
};

Now we'll define our identifyToken function. As the name suggests, this function takes a word and figures out what token that word represents.

1
// src/lexer.mts
2
3
/** previous function(s) omitted for brevity */
4
5
const identifyToken = (word: string): Token => {
6
// Don't worry we'll get to all the `is` helper functions in a bit
7
if (isInt(word)) return { type: "int", value: parseInt(word) };
8
if (isFloat(word)) return { type: "float", value: parseFloat(word) };
9
if (isIdentifier(word)) return { type: "identifier", value: word };
10
if (isBracket(word)) return { type: "bracket", value: word };
11
if (isTypedIdentifier(word)) return { type: "typed-identifier", value: word };
12
13
throw new Error(`Unknown token: ${word}`);
14
};

Finally, we define our helper functions. These functions all take a string and return true if the string passes their test, false otherwise. Most are written using regex. If you're unfamiliar with regex, I highly recommend regexone as a resource to learn more. In a nutshell, regex is an expression syntax that's used to extract meaningful information from text. In our case, we'll use it to match words against tokens.

1
const isInt = (word: string) => /^[0-9]+$/.test(word);
2
3
const isFloat = (word: string) => /^[0-9]+\.[0-9]+$/.test(word);
4
5
const isIdentifier = (word: string) => /^[a-zA-Z_][a-zA-Z0-9_\-]*$/.test(word);
6
7
const isTypedIdentifier = (word: string) =>
8
/^[a-zA-Z_][a-zA-Z0-9_\-]*:[a-zA-Z_][a-zA-Z0-9_\-]*$/.test(word);
9
10
const isBracket = (word: string): word is Bracket => /[\(\)\[\]]/.test(word);
11
12
/** Brackets are the only terminator tokens for now */
13
const isTerminatorToken = (word: string): word is Bracket => isBracket(word);
14
15
// Not sure why I didn't use regex here ¯\_(ツ)_/¯
16
const isWhitespace = (char: string) => char === " " || char === "\n" || char === "\t";

At this point, src/lexer.mts is finished and should look something like this file.

Running the Lexer

It's time to actually run the lexer. Start by making a new file src/index.mts:

1
#!/usr/bin/env node
2
3
// src/index.mts
4
5
import { readFileSync } from "fs";
6
const file = process.argv[2];
7
const input = readFileSync(file, "utf8");
8
const tokens = lex(input);
9
console.log(JSON.stringify(tokens, undefined, 2));

Next, create an example.wispy file in the project root to compile.

1
(fn fib:i32 [val:i32]
2
(if (lt_i32 val 2)
3
val
4
(add_i32 (fib (sub_i32 val 1)) (fib (sub_i32 val 2)))))
5
6
(fn main:i32 [] (fib 15))

Now build the lexer:

1
npx tsc
2
npm link # This will make wispy available to run as its own command

Finally, run the lexer:

1
wispy example.wispy
2
3
# Note, if npm link failed you can call our compiler directly with this as an alternative:
4
node dist/index.mjs example.wispy

If everything goes well, wispy should output something like this:

1
[
2
{
3
"type": "bracket",
4
"value": "("
5
},
6
{
7
"type": "identifier",
8
"value": "fn"
9
},
10
{
11
"type": "typed-identifier",
12
"value": "fib:i32"
13
},
14
{
15
"type": "bracket",
16
"value": "["
17
},
18
{
19
"type": "typed-identifier",
20
"value": "val:i32"
21
},
22
// Omitting the rest for brevity
23
]

With that we have a working lexer. We can break our code down into tokens. This is a good place to break for now. In the next article, we’ll move onto parsing these tokens into a logical tree that will ultimately be converted to wasm.

Start Routing Notifications Today!

Courier is a notification service that centralizes all of your templates and messaging channels in one place which increases visibility and reduces engineering time.

Sign-up

More from Engineering

APNS Update Thumbnail
ENGINEERING

Get Your iOS App Ready for the 2025 Apple Push Notification Service Server Certificate Update

Apple is updating its Push Notification Service (APNs) certificates in 2025. Learn how to prepare your app for these changes, ensure uninterrupted notifications, and get expert tips for a smooth transition.

Mike Miller

Mike Miller

December 13, 2024

courier-ios-thumbnail
PRODUCT NEWSENGINEERING

Simplifying notifications with the Courier iOS SDK

Push notifications are a valuable tool for keeping users informed and increasing their engagement with your app. You can use push notifications to alert users about promotions, new content, or any other important updates. While push notifications are a powerful tool, setting up push notifications in iOS can be a daunting task that requires a significant amount of effort and time. Fortunately, the Courier iOS Mobile Notifications Software Development Kit (SDK) simplifies this process.

Mike Miller

Mike Miller

March 23, 2023

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Platform

Users

Content

Channels

Sending

Workflows

Preferences

Inbox

Workspaces

Observability

API Status

Changelog

© 2024 Courier. All rights reserved.