5. Tree-Walking Interpreters
Evaluating an AST directly
You have a parser that turns source text into an AST. The most direct way to run that AST is to walk it recursively: visit each node, do what it says, return the result. This is a tree-walking interpreter — and it's how many real languages start their lives (Ruby's MRI, early Python, most Lisps).
The interpreter loop
At its core, a tree-walking interpreter is a big recursive function — the same
evaluate function from the AST article, extended to handle every node type:
function evaluate(node, env) {
switch (node.type) {
case 'NumberLiteral': return node.value;
case 'StringLiteral': return node.value;
case 'BoolLiteral': return node.value;
case 'Identifier':
return env.get(node.name);
case 'BinaryExpr': {
const l = evaluate(node.left, env);
const r = evaluate(node.right, env);
switch (node.op) {
case '+': return l + r;
case '-': return l - r;
case '*': return l * r;
case '/': return l / r;
case '<': return l < r;
case '>': return l > r;
case '==': return l === r;
}
}
case 'UnaryExpr': {
const val = evaluate(node.operand, env);
if (node.op === '-') return -val;
if (node.op === '!') return !val;
}
}
}
The env parameter is the environment — a mapping from variable names to values.
It's where we store and look up variables.
Environments and scope
Variables live in environments. When a new scope opens (a function body, a block), we create a new environment that chains to the enclosing one:
class Environment {
constructor(parent = null) {
this.vars = new Map();
this.parent = parent;
}
get(name) {
if (this.vars.has(name)) return this.vars.get(name);
if (this.parent) return this.parent.get(name);
throw new Error(`Undefined variable: ${name}`);
}
set(name, value) {
this.vars.set(name, value);
}
}
Looking up a variable walks the chain outward until it finds a match. This gives you lexical scoping for free — inner scopes see outer variables, but not vice versa.
Statements
Expressions produce values. Statements produce effects — they bind variables,
branch, loop, or return. We handle them in a separate execute function:
function execute(stmt, env) {
switch (stmt.type) {
case 'ExprStmt':
evaluate(stmt.expr, env);
break;
case 'LetStmt':
env.set(stmt.name, evaluate(stmt.init, env));
break;
case 'IfStmt': {
const cond = evaluate(stmt.condition, env);
if (cond) {
executeBlock(stmt.then, env);
} else if (stmt.else_) {
executeBlock(stmt.else_, env);
}
break;
}
case 'WhileStmt':
while (evaluate(stmt.condition, env)) {
executeBlock(stmt.body, env);
}
break;
case 'ReturnStmt':
throw new ReturnValue(stmt.value ? evaluate(stmt.value, env) : null);
}
}
function executeBlock(stmts, parentEnv) {
const env = new Environment(parentEnv);
for (const stmt of stmts) {
execute(stmt, env);
}
}
Notice the ReturnStmt case: we throw a special ReturnValue object to unwind
the call stack back to the function call site. This is a common trick — return
needs to exit from arbitrarily deep nesting (inside ifs, inside loops), and an
exception does that naturally.
Functions
A function declaration stores the function's AST node along with the environment that was active when it was defined (this is the closure):
case 'FnDecl':
env.set(stmt.name, {
type: 'function',
params: stmt.params,
body: stmt.body,
closure: env, // capture the defining environment
});
break;
A function call creates a new environment chained to the closure environment, binds the arguments to the parameter names, and executes the body:
case 'CallExpr': {
const callee = evaluate(node.callee, env);
const args = node.args.map(a => evaluate(a, env));
if (callee.type !== 'function') throw new Error('Not callable');
const callEnv = new Environment(callee.closure);
for (let i = 0; i < callee.params.length; i++) {
callEnv.set(callee.params[i], args[i]);
}
try {
executeBlock(callee.body, callEnv);
return null;
} catch (e) {
if (e instanceof ReturnValue) return e.value;
throw e;
}
}
The closure chain is what makes this work correctly for cases like:
fn makeCounter() {
let n = 0;
fn inc() { n = n + 1; return n; }
return inc;
}
let c = makeCounter();
c(); // 1
c(); // 2
inc closes over the environment containing n. Each call to inc sees (and
modifies) the same n because they share the same closure environment.
Putting it all together
A complete tree-walking interpreter is surprisingly small. The full pipeline:
source text → tokenize → parse → AST → evaluate/execute → result
For a language with numbers, strings, booleans, variables, arithmetic, comparisons, if/else, while, functions, and closures, the entire interpreter (tokenizer, parser, evaluator) fits comfortably in a few hundred lines.
The tradeoff: simplicity vs. speed
Tree-walking is the simplest interpreter architecture, but it's also the slowest.
Every time you evaluate 2 + 3, you:
- Check the node type (
BinaryExpr) - Recursively evaluate the left child
- Check its node type (
NumberLiteral) - Return the value
- Recursively evaluate the right child
- Check its node type
- Return the value
- Check the operator (
+) - Add and return
That's a lot of overhead for adding two numbers — especially the recursive calls and the type-checking switches. The tree's pointer-heavy structure also thrashes the CPU cache.
For scripts that run once and finish, this is fine. For hot loops that execute millions of times, it's not. The next article introduces bytecode VMs — a flat, compact representation that eliminates the tree overhead entirely.
Try It Yourself — Live Interpreter
Type a program using let, if/else,
while, and print. Watch it execute and see the
evaluation trace and final variable state.