4. AST Construction
Building and traversing syntax trees
In the last two articles, the parser returned plain JavaScript objects like
{ type: 'BinaryExpr', op: '+', left, right }. Those objects are an AST —
an Abstract Syntax Tree. This article looks at ASTs more carefully: what
makes them "abstract," how to design node types, and how to traverse them.
Concrete vs. abstract
The parse tree (or concrete syntax tree) mirrors the grammar exactly. It includes every token — parentheses, semicolons, commas, keywords — even ones that carry no semantic meaning. The abstract syntax tree strips those away and keeps only what matters for meaning.
For the input (1 + 2) * 3, the concrete tree has nodes for (, ), and
every grammar rule. The AST just has:
BinaryExpr *
BinaryExpr +
NumberLiteral 1
NumberLiteral 2
NumberLiteral 3
The parentheses are gone — their effect is captured by the tree's shape.
Designing AST nodes
Every language construct becomes a node type. For a small language you might have:
type Expr =
| { type: 'NumberLiteral'; value: number }
| { type: 'StringLiteral'; value: string }
| { type: 'BoolLiteral'; value: boolean }
| { type: 'Identifier'; name: string }
| { type: 'UnaryExpr'; op: string; operand: Expr }
| { type: 'BinaryExpr'; op: string; left: Expr; right: Expr }
| { type: 'CallExpr'; callee: Expr; args: Expr[] }
| { type: 'AssignExpr'; name: string; value: Expr };
type Stmt =
| { type: 'ExprStmt'; expr: Expr }
| { type: 'LetStmt'; name: string; init: Expr }
| { type: 'IfStmt'; condition: Expr; then: Stmt[]; else_: Stmt[] }
| { type: 'WhileStmt'; condition: Expr; body: Stmt[] }
| { type: 'FnDecl'; name: string; params: string[]; body: Stmt[] }
| { type: 'ReturnStmt'; value: Expr | null };
Each node carries exactly the data needed to interpret or compile that construct — nothing more.
Source locations
For error messages, warnings, and debugging tools, each node should carry its
position in the original source. A common approach is a span field holding the
start and end offsets:
type Span = { start: number; end: number };
type Expr =
| { type: 'NumberLiteral'; value: number; span: Span }
| ...
The parser fills these in as it builds nodes, typically from the first and last token consumed.
Building the tree during parsing
You've already seen this — the parser returns AST nodes from its parse functions. The key principle: every parse function returns a node (or a list of nodes). There's no separate "AST construction" pass; the parser builds the tree directly.
parseFactor() {
if (this.peek().type === 'NUMBER') {
const tok = this.advance();
return { type: 'NumberLiteral', value: tok.literal, span: tok.span };
}
// ...
}
The tree is fully formed by the time parsing finishes. The parser's return value is the AST.
Traversing the tree: the visitor pattern
Once you have a tree, you'll want to walk it — to interpret it, compile it, pretty-print it, or analyze it. The most common approach is the visitor pattern: define a function (or object with methods) that handles each node type.
The simplest version is a recursive function with a switch:
function evaluate(node) {
switch (node.type) {
case 'NumberLiteral':
return node.value;
case 'BinaryExpr': {
const l = evaluate(node.left);
const r = evaluate(node.right);
if (node.op === '+') return l + r;
if (node.op === '-') return l - r;
if (node.op === '*') return l * r;
if (node.op === '/') return l / r;
}
// ...
}
}
For a larger codebase, you might use an object with one method per node type:
interface Visitor<T> {
visitNumberLiteral(node: NumberLiteral): T;
visitBinaryExpr(node: BinaryExpr): T;
visitUnaryExpr(node: UnaryExpr): T;
// ...
}
Each node has an accept(visitor) method that dispatches to the right visit*
call. This is classic GoF visitor — useful when you have many independent passes
over the same tree (type checking, optimization, code generation) and want to
keep each pass in its own class.
Tree transformations
Sometimes you want to modify the AST rather than just read it — constant folding, desugaring, or optimization. A transformer is a visitor that returns a new (or modified) node:
function foldConstants(node) {
if (node.type !== 'BinaryExpr') return node;
const left = foldConstants(node.left);
const right = foldConstants(node.right);
if (left.type === 'NumberLiteral' && right.type === 'NumberLiteral') {
// Both sides are constants — fold at compile time
return {
type: 'NumberLiteral',
value: applyOp(node.op, left.value, right.value),
};
}
return { ...node, left, right };
}
foldConstants walks the tree bottom-up, replacing 2 + 3 with 5 wherever
both operands are known at compile time.
Pretty-printing
A pretty-printer walks the AST and emits formatted source text. It's the inverse of parsing — tree in, text out. This is how code formatters (Prettier, gofmt, rustfmt) work: parse the code into an AST, then print it back out with consistent formatting, ignoring whatever formatting the original had.
function prettyPrint(node) {
switch (node.type) {
case 'NumberLiteral': return String(node.value);
case 'BinaryExpr':
return `(${prettyPrint(node.left)} ${node.op} ${prettyPrint(node.right)})`;
case 'LetStmt':
return `let ${node.name} = ${prettyPrint(node.init)};`;
// ...
}
}
The AST is the center of everything
The AST is the most important data structure in a language implementation. Every stage after parsing consumes it:
- Type checkers walk the tree and annotate nodes with types
- Optimizers transform the tree (constant folding, dead code elimination)
- Interpreters evaluate the tree directly (next article)
- Compilers walk the tree and emit bytecode or machine code
Get the AST right and everything downstream becomes straightforward.
Try It Yourself — AST Explorer
Type code below and see the AST it produces. Hover over any node in the tree to highlight the corresponding source span.