Programming Search⌘K

Conceptcore

Tree-walking interpreter

Also called tree-walk interpreter, AST-walking interpreter.

A tree-walking interpreter runs a program by visiting the nodes of its syntax tree. It evaluates the children of each node first, and keeps the values of variables in a chain of environments.

Applies to
core-languages

Idea

A parser turns the text of a program into an Abstract syntax tree. A tree-walking interpreter runs the program directly from that tree. It has one case for each kind of node. To evaluate a * b, it evaluates a, evaluates b, and multiplies the two values. To run a while loop, it evaluates the condition and runs the body until the condition is false. The interpreter is a recursive function over the tree, and the language it is written in, the host language, does the real work.

Variables need a place to live. The interpreter keeps them in an environment, a map from names to values.4 A block opens a new environment that points to the environment around it. The interpreter looks up a name in the innermost environment first and then follows the parent links outward.5

The method is the shortest path from a parser to a running language. The structure at run time is the structure of the syntax, so there is no second representation to design or debug.10 The price is speed: each step of the program costs a dynamic dispatch on a node and a chase of pointers through the heap.10

How it works

Expressions are evaluated bottom-up

A node can compute its value only when it has the values of its children. The interpreter therefore evaluates the operands of a node before it applies the operator. This order is a post-order traversal of the tree.3 The recursion of the evaluator follows the nesting of the expression, so it is a direct case of Recursion over a sum type.

Statements change the state

An expression gives a value. A statement has an effect: it binds a variable, changes one, or prints. The interpreter has a second function for statements, and the two functions call each other. Control flow in the guest language becomes control flow in the host: the guest while is a host while around a call that runs the body.

Environments form a chain

LISP's eval[e; a] already worked this way in 1960. Its second argument is a list of pairs of names and values. A variable is looked up with assoc, and a call of a lambda adds the pairs of parameters and arguments to the front of the list with pair.2 Crafting Interpreters uses one hash map for each scope, and each map has a reference to the enclosing one. A lookup walks from the innermost map outward until it finds the name.5 Shadowing falls out of this order. An inner let x hides the outer x because the walk finds the inner one first.

The whole interpreter

The program below computes 5 factorial with a loop. It builds the tree by hand, so that the page shows only the interpreter. The Recursive descent parsing page shows how a parser builds such a tree. The interpreter counts the nodes that it visits, the variable lookups, and the parent links that the lookups follow.

from dataclasses import dataclass


@dataclass
class Num:
    value: int


@dataclass
class Var:
    name: str


@dataclass
class Bin:
    op: str
    left: object
    right: object


@dataclass
class Let:
    name: str
    init: object


@dataclass
class Assign:
    name: str
    value: object


@dataclass
class Block:
    body: list


@dataclass
class While:
    cond: object
    body: object


@dataclass
class Print:
    value: object


class Env:
    def __init__(self, parent=None):
        self.vars = {}
        self.parent = parent


class Interpreter:
    def __init__(self):
        self.nodes = self.lookups = self.links = 0

    def find(self, env, name):
        self.lookups += 1
        while env is not None:
            if name in env.vars:
                return env
            self.links += 1
            env = env.parent
        raise NameError(f"undefined variable {name!r}")

    def evaluate(self, node, env):
        self.nodes += 1
        match node:
            case Num(value):
                return value
            case Var(name):
                return self.find(env, name).vars[name]
            case Bin(op, left, right):
                a = self.evaluate(left, env)
                b = self.evaluate(right, env)
                match op:
                    case "+":
                        return a + b
                    case "-":
                        return a - b
                    case "*":
                        return a * b
                    case "<":
                        return 1 if a < b else 0
        raise TypeError(f"unknown expression {node!r}")

    def execute(self, node, env):
        self.nodes += 1
        match node:
            case Let(name, init):
                env.vars[name] = self.evaluate(init, env)
            case Assign(name, value):
                result = self.evaluate(value, env)
                self.find(env, name).vars[name] = result
            case Block(body):
                inner = Env(env)
                for stmt in body:
                    self.execute(stmt, inner)
            case While(cond, body):
                while self.evaluate(cond, env) != 0:
                    self.execute(body, env)
            case Print(value):
                print(self.evaluate(value, env))
            case _:
                raise TypeError(f"unknown statement {node!r}")


# let n = 5; let acc = 1;
# while (0 < n) { let step = n; acc = acc * step; n = n - 1; }
# print acc;
program = Block([
    Let("n", Num(5)),
    Let("acc", Num(1)),
    While(Bin("<", Num(0), Var("n")), Block([
        Let("step", Var("n")),
        Assign("acc", Bin("*", Var("acc"), Var("step"))),
        Assign("n", Bin("-", Var("n"), Num(1))),
    ])),
    Print(Var("acc")),
])

interp = Interpreter()
interp.execute(program, Env())
print(f"nodes visited: {interp.nodes}")
print(f"variable lookups: {interp.lookups}, parent links followed: {interp.links}")
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25

The tree has 22 nodes, but the interpreter visits 81, because it visits the condition and the body of the loop again on each pass. The loop body is a block, so each pass makes a fresh environment. step is local to that environment. n and acc live one level out, so each lookup of them from inside the body follows one parent link.

Errors unwind the host stack

An error deep in the tree, such as an undefined variable, must stop the whole evaluation. The interpreter's state is the host call stack, so the natural tool is an exception of the host language. It unwinds every recursive call at once.6 The interpreter above raises NameError for an unknown name and TypeError for an unknown node.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiom
GoIdiom
RustIdiom
KotlinIdiom
SQLDoes not applyA query language is not a host for an evaluator over a tree of statements.
BashIdiomFunctions, recursion and associative arrays can hold a small tree and walk it, but every value is a string in a global variable, so the interpreter is slow and hard to read. Alternative: An interpreter written in a general language, called from the script.
PowerShellIdiomHashtables can stand for the nodes and a switch on a kind field can select the case; no example file because PowerShell is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no evaluation.
CSSDoes not applyStyle rules have no recursion over data.
Regular expressionsDoes not applyA pattern language has no data structures and no recursion over them.

Every general-purpose language can host a tree-walking interpreter. The languages differ in how the evaluator selects the case for a node. The examples run the same program and print the same three lines.

Language Verdict Form
Python idiom dataclasses for the nodes; match with class patterns in evaluate and execute
JavaScript idiom plain objects with a kind field; switch on the kind
TypeScript idiom a discriminated union; switch on the kind, checked for exhaustiveness
Java idiom a sealed interface and records; switch with record patterns
Kotlin idiom a sealed interface and data classes; when with is
C# idiom records; a switch expression with type patterns
Go idiom an interface for nodes; a type switch
Rust idiom an enum with Box children; match; environments in Rc<RefCell<...>>
C++ idiom std::variant nodes; std::visit or std::get_if
C idiom a tagged struct; switch on the tag; environments as linked lists
PowerShell idiom hashtables for nodes and a switch on the kind (no example: pwsh is not installed)
Bash idiom possible with associative arrays and recursion, but slow and hard to read
SQL n/a a query language, not a host for an evaluator
Regex n/a a pattern language, not a host for an evaluator
HTML/CSS n/a no recursion over data

In the object-oriented form, each node class has its own method that interprets the node. This is the Interpreter pattern. Crafting Interpreters builds its first interpreter, jlox, in Java with the Visitor pattern instead. The evaluator is one class that implements the visitor interface, with one visit method for each class of expression.12 Languages with Sum types and pattern matching put the cases in one function instead, as the Python example does. See Visitor pattern.

PythonGitHub
from dataclasses import dataclass


@dataclass
class Num:
    value: int


@dataclass
class Var:
    name: str


@dataclass
class Bin:
    op: str
    left: object
    right: object


@dataclass
class Let:
    name: str
    init: object


@dataclass
class Assign:
    name: str
    value: object


@dataclass
class Block:
    body: list


@dataclass
class While:
    cond: object
    body: object


@dataclass
class Print:
    value: object


class Env:
    def __init__(self, parent=None):
        self.vars = {}
        self.parent = parent


class Interpreter:
    """Dispatch by method name, in the style of ast.NodeVisitor."""

    OPS = {
        "+": lambda a, b: a + b,
        "-": lambda a, b: a - b,
        "*": lambda a, b: a * b,
        "<": lambda a, b: int(a < b),
    }

    def __init__(self):
        self.nodes = self.lookups = self.links = 0

    def visit(self, node, env):
        self.nodes += 1
        method = getattr(self, "visit_" + type(node).__name__)
        return method(node, env)

    def find(self, env, name):
        self.lookups += 1
        while env is not None:
            if name in env.vars:
                return env
            self.links += 1
            env = env.parent
        raise NameError(f"undefined variable {name!r}")

    def visit_Num(self, node, env):
        return node.value

    def visit_Var(self, node, env):
        return self.find(env, node.name).vars[node.name]

    def visit_Bin(self, node, env):
        a = self.visit(node.left, env)
        b = self.visit(node.right, env)
        return self.OPS[node.op](a, b)

    def visit_Let(self, node, env):
        env.vars[node.name] = self.visit(node.init, env)

    def visit_Assign(self, node, env):
        result = self.visit(node.value, env)
        self.find(env, node.name).vars[node.name] = result

    def visit_Block(self, node, env):
        inner = Env(env)
        for stmt in node.body:
            self.visit(stmt, inner)

    def visit_While(self, node, env):
        while self.visit(node.cond, env) != 0:
            self.visit(node.body, env)

    def visit_Print(self, node, env):
        print(self.visit(node.value, env))


program = Block([
    Let("n", Num(5)),
    Let("acc", Num(1)),
    While(Bin("<", Num(0), Var("n")), Block([
        Let("step", Var("n")),
        Assign("acc", Bin("*", Var("acc"), Var("step"))),
        Assign("n", Bin("-", Var("n"), Num(1))),
    ])),
    Print(Var("acc")),
])

interp = Interpreter()
interp.visit(program, Env())
print(f"nodes visited: {interp.nodes}")
print(f"variable lookups: {interp.lookups}, parent links followed: {interp.links}")
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. The main page dispatches with match. This version looks up a method named visit_ plus the class name of the node, which is how ast.NodeVisitor dispatches. One method per node type keeps each case short.
  • getattr raises AttributeError for a node type that has no method. Nothing checks the cases before the run.
  • The operators sit in a table of small functions. Adding an operator adds one entry, and the dispatch code does not change.
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <variant>
#include <vector>

struct Num;
struct Var;
struct Bin;
using Expr = std::variant<Num, Var, Bin>;

struct Num { long value; };
struct Var { std::string name; };
struct Bin {
    char op;
    std::unique_ptr<Expr> left, right;
};

struct Let;
struct Assign;
struct Block;
struct While;
struct Print;
using Stmt = std::variant<Let, Assign, Block, While, Print>;

struct Let { std::string name; Expr init; };
struct Assign { std::string name; Expr value; };
struct Block { std::vector<Stmt> body; };
struct While { Expr cond; std::unique_ptr<Stmt> body; };
struct Print { Expr value; };

struct Env {
    std::unordered_map<std::string, long> vars;
    Env* parent;
};

struct Interpreter {
    int nodes = 0, lookups = 0, links = 0;

    Env& find(Env& env, const std::string& name) {
        ++lookups;
        for (Env* e = &env; e != nullptr; e = e->parent) {
            if (e->vars.count(name)) return *e;
            ++links;
        }
        throw std::runtime_error("undefined variable '" + name + "'");
    }

    long evaluate(const Expr& node, Env& env) {
        ++nodes;
        if (auto* n = std::get_if<Num>(&node)) return n->value;
        if (auto* v = std::get_if<Var>(&node)) return find(env, v->name).vars[v->name];
        const Bin& b = std::get<Bin>(node);
        long x = evaluate(*b.left, env);
        long y = evaluate(*b.right, env);
        switch (b.op) {
            case '+': return x + y;
            case '-': return x - y;
            case '*': return x * y;
            case '<': return x < y ? 1 : 0;
        }
        throw std::runtime_error(std::string("unknown operator ") + b.op);
    }

    void execute(const Stmt& node, Env& env) {
        ++nodes;
        std::visit([&](const auto& s) { run(s, env); }, node);
    }

    void run(const Let& s, Env& env) { env.vars[s.name] = evaluate(s.init, env); }

    void run(const Assign& s, Env& env) {
        long result = evaluate(s.value, env);
        find(env, s.name).vars[s.name] = result;
    }

    void run(const Block& s, Env& env) {
        Env inner{{}, &env};  // lives on the C++ stack until the block ends
        for (const Stmt& stmt : s.body) execute(stmt, inner);
    }

    void run(const While& s, Env& env) {
        while (evaluate(s.cond, env) != 0) execute(*s.body, env);
    }

    void run(const Print& s, Env& env) { std::cout << evaluate(s.value, env) << '\n'; }
};

std::unique_ptr<Expr> box(Expr e) { return std::make_unique<Expr>(std::move(e)); }
Expr bin(char op, Expr l, Expr r) { return Bin{op, box(std::move(l)), box(std::move(r))}; }

int main() {
    std::vector<Stmt> loop_body;
    loop_body.push_back(Let{"step", Var{"n"}});
    loop_body.push_back(Assign{"acc", bin('*', Var{"acc"}, Var{"step"})});
    loop_body.push_back(Assign{"n", bin('-', Var{"n"}, Num{1})});

    std::vector<Stmt> body;
    body.push_back(Let{"n", Num{5}});
    body.push_back(Let{"acc", Num{1}});
    body.push_back(While{bin('<', Num{0}, Var{"n"}), std::make_unique<Stmt>(Block{std::move(loop_body)})});
    body.push_back(Print{Var{"acc"}});
    Stmt program = Block{std::move(body)};

    Interpreter interp;
    Env global{{}, nullptr};
    interp.execute(program, global);
    std::cout << "nodes visited: " << interp.nodes << '\n';
    std::cout << "variable lookups: " << interp.lookups << ", parent links followed: " << interp.links << '\n';
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. std::variant holds one of the node types, and std::unique_ptr breaks the recursion of a type that contains itself. evaluate uses std::get_if, and execute uses std::visit with one overload of run for each statement type.
  • The environment of a block is a local variable of run(const Block&, ...). It dies when the block ends, and no garbage collector is needed. This works only because nothing can keep a pointer to it after the block ends. With closures, an environment can outlive its block and must move to the heap.
  • The children are unique_ptr, so nodes cannot be copied. The program is built with push_back and std::move, because an initializer list copies its elements.
JavaGitHub
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    sealed interface Expr permits Num, Var, Bin {}
    record Num(long value) implements Expr {}
    record Var(String name) implements Expr {}
    record Bin(char op, Expr left, Expr right) implements Expr {}

    sealed interface Stmt permits Let, Assign, Block, While, Print {}
    record Let(String name, Expr init) implements Stmt {}
    record Assign(String name, Expr value) implements Stmt {}
    record Block(List<Stmt> body) implements Stmt {}
    record While(Expr cond, Stmt body) implements Stmt {}
    record Print(Expr value) implements Stmt {}

    static final class Env {
        final Map<String, Long> vars = new HashMap<>();
        final Env parent;

        Env(Env parent) { this.parent = parent; }
    }

    static final class Interpreter {
        int nodes, lookups, links;

        Env find(Env env, String name) {
            lookups++;
            for (Env e = env; e != null; e = e.parent) {
                if (e.vars.containsKey(name)) return e;
                links++;
            }
            throw new IllegalStateException("undefined variable '" + name + "'");
        }

        long evaluate(Expr node, Env env) {
            nodes++;
            return switch (node) {
                case Num(long value) -> value;
                case Var(String name) -> find(env, name).vars.get(name);
                case Bin(char op, Expr left, Expr right) -> {
                    long a = evaluate(left, env);
                    long b = evaluate(right, env);
                    yield switch (op) {
                        case '+' -> a + b;
                        case '-' -> a - b;
                        case '*' -> a * b;
                        case '<' -> a < b ? 1 : 0;
                        default -> throw new IllegalStateException("unknown operator " + op);
                    };
                }
            };
        }

        void execute(Stmt node, Env env) {
            nodes++;
            switch (node) {
                case Let(String name, Expr init) -> env.vars.put(name, evaluate(init, env));
                case Assign(String name, Expr value) -> {
                    long result = evaluate(value, env);
                    find(env, name).vars.put(name, result);
                }
                case Block(List<Stmt> body) -> {
                    Env inner = new Env(env);
                    for (Stmt stmt : body) execute(stmt, inner);
                }
                case While(Expr cond, Stmt body) -> {
                    while (evaluate(cond, env) != 0) execute(body, env);
                }
                case Print(Expr value) -> System.out.println(evaluate(value, env));
            }
        }
    }

    public static void main(String[] args) {
        Stmt program = new Block(List.of(
            new Let("n", new Num(5)),
            new Let("acc", new Num(1)),
            new While(new Bin('<', new Num(0), new Var("n")), new Block(List.of(
                new Let("step", new Var("n")),
                new Assign("acc", new Bin('*', new Var("acc"), new Var("step"))),
                new Assign("n", new Bin('-', new Var("n"), new Num(1)))))),
            new Print(new Var("acc"))));

        Interpreter interp = new Interpreter();
        interp.execute(program, new Env(null));
        System.out.println("nodes visited: " + interp.nodes);
        System.out.println("variable lookups: " + interp.lookups + ", parent links followed: " + interp.links);
    }
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Sealed interfaces and records model the tree, and switch with record patterns takes each node apart.
  • The switch over a sealed interface needs no default. The compiler knows every permitted record, and it rejects the switch if a case is missing.
  • Crafting Interpreters writes its Java interpreter, jlox, with the Visitor pattern instead. Record patterns put the same dispatch in one method, without an accept method on each class.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum { NUM, VAR, BIN, LET, ASSIGN, BLOCK, WHILE, PRINT } Kind;

typedef struct Node {
    Kind kind;
    long value;              /* NUM */
    const char *name;        /* VAR, LET, ASSIGN */
    char op;                 /* BIN */
    struct Node *a, *b;      /* BIN: operands; LET, ASSIGN, PRINT: a; WHILE: a = cond, b = body */
    struct Node **body;      /* BLOCK: NULL-terminated list */
} Node;

/* A binding is one cell of a linked list; an environment is a list plus a parent. */
typedef struct Binding {
    const char *name;
    long value;
    struct Binding *next;
} Binding;

typedef struct Env {
    Binding *first;
    struct Env *parent;
} Env;

static int nodes, lookups, links;

static Node *mk(Kind kind) {
    Node *n = calloc(1, sizeof *n);
    n->kind = kind;
    return n;
}
static Node *num(long v) { Node *n = mk(NUM); n->value = v; return n; }
static Node *var(const char *s) { Node *n = mk(VAR); n->name = s; return n; }
static Node *bin(char op, Node *a, Node *b) { Node *n = mk(BIN); n->op = op; n->a = a; n->b = b; return n; }
static Node *let(const char *s, Node *e) { Node *n = mk(LET); n->name = s; n->a = e; return n; }
static Node *assign(const char *s, Node *e) { Node *n = mk(ASSIGN); n->name = s; n->a = e; return n; }
static Node *loop(Node *c, Node *body) { Node *n = mk(WHILE); n->a = c; n->b = body; return n; }
static Node *print(Node *e) { Node *n = mk(PRINT); n->a = e; return n; }
static Node *block(Node **stmts, size_t count) {
    Node *n = mk(BLOCK);
    n->body = calloc(count + 1, sizeof *n->body);
    memcpy(n->body, stmts, count * sizeof *stmts);
    return n;
}

static Binding *find(Env *env, const char *name) {
    lookups++;
    for (Env *e = env; e != NULL; e = e->parent) {
        for (Binding *b = e->first; b != NULL; b = b->next)
            if (strcmp(b->name, name) == 0) return b;
        links++;
    }
    fprintf(stderr, "undefined variable '%s'\n", name);
    exit(1);
}

static long evaluate(Node *n, Env *env) {
    nodes++;
    switch (n->kind) {
    case NUM: return n->value;
    case VAR: return find(env, n->name)->value;
    case BIN: {
        long x = evaluate(n->a, env);
        long y = evaluate(n->b, env);
        switch (n->op) {
        case '+': return x + y;
        case '-': return x - y;
        case '*': return x * y;
        case '<': return x < y;
        }
    }
    default:
        fprintf(stderr, "unknown expression\n");
        exit(1);
    }
}

static void execute(Node *n, Env *env) {
    nodes++;
    switch (n->kind) {
    case LET: {
        Binding *b = malloc(sizeof *b);
        b->name = n->name;
        b->value = evaluate(n->a, env);
        b->next = env->first;
        env->first = b;
        break;
    }
    case ASSIGN: {
        long v = evaluate(n->a, env);
        find(env, n->name)->value = v;
        break;
    }
    case BLOCK: {
        Env inner = {NULL, env};
        for (Node **s = n->body; *s != NULL; s++) execute(*s, &inner);
        while (inner.first != NULL) { /* the block ends: free its bindings */
            Binding *next = inner.first->next;
            free(inner.first);
            inner.first = next;
        }
        break;
    }
    case WHILE:
        while (evaluate(n->a, env) != 0) execute(n->b, env);
        break;
    case PRINT:
        printf("%ld\n", evaluate(n->a, env));
        break;
    default:
        fprintf(stderr, "unknown statement\n");
        exit(1);
    }
}

int main(void) {
    Node *inner[] = {
        let("step", var("n")),
        assign("acc", bin('*', var("acc"), var("step"))),
        assign("n", bin('-', var("n"), num(1))),
    };
    Node *outer[] = {
        let("n", num(5)),
        let("acc", num(1)),
        loop(bin('<', num(0), var("n")), block(inner, 3)),
        print(var("acc")),
    };
    Node *program = block(outer, 4);

    Env global = {NULL, NULL};
    execute(program, &global);
    printf("nodes visited: %d\n", nodes);
    printf("variable lookups: %d, parent links followed: %d\n", lookups, links);
    return 0; /* the tree is freed when the process exits */
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. One struct with a kind tag stands for every node type, and switch on the tag selects the case. Unused fields waste a little memory; a union would save it at the cost of more syntax.
  • Each environment is a linked list of bindings with a pointer to its parent. A lookup compares names with strcmp, one binding at a time, so its cost grows with the number of names in each scope.
  • The interpreter frees the bindings of a block when the block ends. A language with closures could not do this, because a closure may still point to the environment. It would need reference counts or a garbage collector.
using System;
using System.Collections.Generic;

Stmt program = new Block([
    new Let("n", new Num(5)),
    new Let("acc", new Num(1)),
    new While(new Bin('<', new Num(0), new Var("n")), new Block([
        new Let("step", new Var("n")),
        new Assign("acc", new Bin('*', new Var("acc"), new Var("step"))),
        new Assign("n", new Bin('-', new Var("n"), new Num(1))),
    ])),
    new Print(new Var("acc")),
]);

var interp = new Interpreter();
interp.Execute(program, new Env(null));
Console.WriteLine($"nodes visited: {interp.Nodes}");
Console.WriteLine($"variable lookups: {interp.Lookups}, parent links followed: {interp.Links}");

abstract record Expr;
record Num(long Value) : Expr;
record Var(string Name) : Expr;
record Bin(char Op, Expr Left, Expr Right) : Expr;

abstract record Stmt;
record Let(string Name, Expr Init) : Stmt;
record Assign(string Name, Expr Value) : Stmt;
record Block(List<Stmt> Body) : Stmt;
record While(Expr Cond, Stmt Body) : Stmt;
record Print(Expr Value) : Stmt;

class Env(Env? parent)
{
    public Dictionary<string, long> Vars { get; } = new();
    public Env? Parent { get; } = parent;
}

class Interpreter
{
    public int Nodes, Lookups, Links;

    Env Find(Env env, string name)
    {
        Lookups++;
        for (Env? e = env; e != null; e = e.Parent)
        {
            if (e.Vars.ContainsKey(name)) return e;
            Links++;
        }
        throw new InvalidOperationException($"undefined variable '{name}'");
    }

    public long Evaluate(Expr node, Env env)
    {
        Nodes++;
        switch (node)
        {
            case Num(var value):
                return value;
            case Var(var name):
                return Find(env, name).Vars[name];
            case Bin(var op, var left, var right):
                long a = Evaluate(left, env);
                long b = Evaluate(right, env);
                return op switch
                {
                    '+' => a + b,
                    '-' => a - b,
                    '*' => a * b,
                    '<' => a < b ? 1 : 0,
                    _ => throw new InvalidOperationException($"unknown operator {op}"),
                };
            default:
                throw new InvalidOperationException($"unknown expression {node}");
        }
    }

    public void Execute(Stmt node, Env env)
    {
        Nodes++;
        switch (node)
        {
            case Let(var name, var init):
                env.Vars[name] = Evaluate(init, env);
                break;
            case Assign(var name, var value):
                long result = Evaluate(value, env);
                Find(env, name).Vars[name] = result;
                break;
            case Block(var body):
                var inner = new Env(env);
                foreach (var stmt in body) Execute(stmt, inner);
                break;
            case While(var cond, var body):
                while (Evaluate(cond, env) != 0) Execute(body, env);
                break;
            case Print(var value):
                Console.WriteLine(Evaluate(value, env));
                break;
            default:
                throw new InvalidOperationException($"unknown statement {node}");
        }
    }
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Positional records model the nodes, and positional patterns such as Bin(var op, var left, var right) take them apart in a switch.
  • C# has no closed hierarchy for records, so the compiler cannot prove that the cases are complete. Each switch ends with a default that throws.
  • Env uses a primary constructor. The Dictionary of each environment becomes garbage when its block ends.
JavaScriptGitHub
const num = (value) => ({ kind: "num", value });
const v = (name) => ({ kind: "var", name });
const bin = (op, left, right) => ({ kind: "bin", op, left, right });
const let_ = (name, init) => ({ kind: "let", name, init });
const assign = (name, value) => ({ kind: "assign", name, value });
const block = (...body) => ({ kind: "block", body });
const while_ = (cond, body) => ({ kind: "while", cond, body });
const print = (value) => ({ kind: "print", value });

class Env {
  constructor(parent = null) {
    this.vars = new Map();
    this.parent = parent;
  }
}

class Interpreter {
  nodes = 0;
  lookups = 0;
  links = 0;

  find(env, name) {
    this.lookups++;
    for (let e = env; e !== null; e = e.parent) {
      if (e.vars.has(name)) return e;
      this.links++;
    }
    throw new ReferenceError(`undefined variable '${name}'`);
  }

  evaluate(node, env) {
    this.nodes++;
    switch (node.kind) {
      case "num":
        return node.value;
      case "var":
        return this.find(env, node.name).vars.get(node.name);
      case "bin": {
        const a = this.evaluate(node.left, env);
        const b = this.evaluate(node.right, env);
        switch (node.op) {
          case "+": return a + b;
          case "-": return a - b;
          case "*": return a * b;
          case "<": return a < b ? 1 : 0;
        }
      }
    }
    throw new TypeError(`unknown expression ${node.kind}`);
  }

  execute(node, env) {
    this.nodes++;
    switch (node.kind) {
      case "let":
        env.vars.set(node.name, this.evaluate(node.init, env));
        return;
      case "assign": {
        const result = this.evaluate(node.value, env);
        this.find(env, node.name).vars.set(node.name, result);
        return;
      }
      case "block": {
        const inner = new Env(env);
        for (const stmt of node.body) this.execute(stmt, inner);
        return;
      }
      case "while":
        while (this.evaluate(node.cond, env) !== 0) this.execute(node.body, env);
        return;
      case "print":
        console.log(this.evaluate(node.value, env));
        return;
    }
    throw new TypeError(`unknown statement ${node.kind}`);
  }
}

const program = block(
  let_("n", num(5)),
  let_("acc", num(1)),
  while_(bin("<", num(0), v("n")), block(
    let_("step", v("n")),
    assign("acc", bin("*", v("acc"), v("step"))),
    assign("n", bin("-", v("n"), num(1))),
  )),
  print(v("acc")),
);

const interp = new Interpreter();
interp.execute(program, new Env());
console.log(`nodes visited: ${interp.nodes}`);
console.log(`variable lookups: ${interp.lookups}, parent links followed: ${interp.links}`);
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Nodes are plain objects with a kind field, and small factory functions keep the program tree readable.
  • switch on node.kind selects the case. Nothing checks that every kind has a case, so the functions end with a throw for an unknown node.
  • Each environment holds a Map and a reference to its parent. A block that ends drops its environment, and the garbage collector reclaims it.
TypeScriptGitHub
type Expr =
  | { kind: "num"; value: number }
  | { kind: "var"; name: string }
  | { kind: "bin"; op: "+" | "-" | "*" | "<"; left: Expr; right: Expr };

type Stmt =
  | { kind: "let"; name: string; init: Expr }
  | { kind: "assign"; name: string; value: Expr }
  | { kind: "block"; body: Stmt[] }
  | { kind: "while"; cond: Expr; body: Stmt }
  | { kind: "print"; value: Expr };

class Env {
  readonly vars = new Map<string, number>();
  readonly parent: Env | null;

  constructor(parent: Env | null = null) {
    this.parent = parent;
  }
}

class Interpreter {
  nodes = 0;
  lookups = 0;
  links = 0;

  private find(env: Env, name: string): Env {
    this.lookups++;
    for (let e: Env | null = env; e !== null; e = e.parent) {
      if (e.vars.has(name)) return e;
      this.links++;
    }
    throw new ReferenceError(`undefined variable '${name}'`);
  }

  evaluate(node: Expr, env: Env): number {
    this.nodes++;
    switch (node.kind) {
      case "num":
        return node.value;
      case "var":
        return this.find(env, node.name).vars.get(node.name)!;
      case "bin": {
        const a = this.evaluate(node.left, env);
        const b = this.evaluate(node.right, env);
        switch (node.op) {
          case "+": return a + b;
          case "-": return a - b;
          case "*": return a * b;
          case "<": return a < b ? 1 : 0;
        }
      }
    }
  }

  execute(node: Stmt, env: Env): void {
    this.nodes++;
    switch (node.kind) {
      case "let":
        env.vars.set(node.name, this.evaluate(node.init, env));
        break;
      case "assign": {
        const result = this.evaluate(node.value, env);
        this.find(env, node.name).vars.set(node.name, result);
        break;
      }
      case "block": {
        const inner = new Env(env);
        for (const stmt of node.body) this.execute(stmt, inner);
        break;
      }
      case "while":
        while (this.evaluate(node.cond, env) !== 0) this.execute(node.body, env);
        break;
      case "print":
        console.log(this.evaluate(node.value, env));
        break;
      default: {
        const unreachable: never = node;
        throw new TypeError(`unknown statement ${JSON.stringify(unreachable)}`);
      }
    }
  }
}

const program: Stmt = {
  kind: "block",
  body: [
    { kind: "let", name: "n", init: { kind: "num", value: 5 } },
    { kind: "let", name: "acc", init: { kind: "num", value: 1 } },
    {
      kind: "while",
      cond: { kind: "bin", op: "<", left: { kind: "num", value: 0 }, right: { kind: "var", name: "n" } },
      body: {
        kind: "block",
        body: [
          { kind: "let", name: "step", init: { kind: "var", name: "n" } },
          { kind: "assign", name: "acc", value: { kind: "bin", op: "*", left: { kind: "var", name: "acc" }, right: { kind: "var", name: "step" } } },
          { kind: "assign", name: "n", value: { kind: "bin", op: "-", left: { kind: "var", name: "n" }, right: { kind: "num", value: 1 } } },
        ],
      },
    },
    { kind: "print", value: { kind: "var", name: "acc" } },
  ],
};

const interp = new Interpreter();
interp.execute(program, new Env());
console.log(`nodes visited: ${interp.nodes}`);
console.log(`variable lookups: ${interp.lookups}, parent links followed: ${interp.links}`);
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Expr and Stmt are discriminated unions, and switch on kind narrows each case to the right fields.
  • In execute, the default branch assigns node to a variable of type never. If a new kind of statement is added to Stmt without a case, the type checker rejects that line.
  • In evaluate, the checker sees that the switches cover every case, so the function needs no final return. Node.js strips the types and does not check them, so these checks happen only under tsc. Type stripping also rejects syntax that needs code generation, such as parameter properties in a constructor, so Env assigns parent in the body.
package main

import "fmt"

type Expr interface{ isExpr() }
type Num struct{ Value int }
type Var struct{ Name string }
type Bin struct {
	Op          byte
	Left, Right Expr
}

func (Num) isExpr() {}
func (Var) isExpr() {}
func (Bin) isExpr() {}

type Stmt interface{ isStmt() }
type Let struct {
	Name string
	Init Expr
}
type Assign struct {
	Name  string
	Value Expr
}
type Block struct{ Body []Stmt }
type While struct {
	Cond Expr
	Body Stmt
}
type Print struct{ Value Expr }

func (Let) isStmt()    {}
func (Assign) isStmt() {}
func (Block) isStmt()  {}
func (While) isStmt()  {}
func (Print) isStmt()  {}

type Env struct {
	vars   map[string]int
	parent *Env
}

func newEnv(parent *Env) *Env { return &Env{vars: map[string]int{}, parent: parent} }

type Interpreter struct{ nodes, lookups, links int }

func (in *Interpreter) find(env *Env, name string) *Env {
	in.lookups++
	for e := env; e != nil; e = e.parent {
		if _, ok := e.vars[name]; ok {
			return e
		}
		in.links++
	}
	panic(fmt.Sprintf("undefined variable '%s'", name))
}

func (in *Interpreter) evaluate(node Expr, env *Env) int {
	in.nodes++
	switch n := node.(type) {
	case Num:
		return n.Value
	case Var:
		return in.find(env, n.Name).vars[n.Name]
	case Bin:
		a := in.evaluate(n.Left, env)
		b := in.evaluate(n.Right, env)
		switch n.Op {
		case '+':
			return a + b
		case '-':
			return a - b
		case '*':
			return a * b
		case '<':
			if a < b {
				return 1
			}
			return 0
		}
	}
	panic(fmt.Sprintf("unknown expression %#v", node))
}

func (in *Interpreter) execute(node Stmt, env *Env) {
	in.nodes++
	switch n := node.(type) {
	case Let:
		env.vars[n.Name] = in.evaluate(n.Init, env)
	case Assign:
		result := in.evaluate(n.Value, env)
		in.find(env, n.Name).vars[n.Name] = result
	case Block:
		inner := newEnv(env)
		for _, stmt := range n.Body {
			in.execute(stmt, inner)
		}
	case While:
		for in.evaluate(n.Cond, env) != 0 {
			in.execute(n.Body, env)
		}
	case Print:
		fmt.Println(in.evaluate(n.Value, env))
	default:
		panic(fmt.Sprintf("unknown statement %#v", node))
	}
}

func main() {
	program := Block{[]Stmt{
		Let{"n", Num{5}},
		Let{"acc", Num{1}},
		While{Bin{'<', Num{0}, Var{"n"}}, Block{[]Stmt{
			Let{"step", Var{"n"}},
			Assign{"acc", Bin{'*', Var{"acc"}, Var{"step"}}},
			Assign{"n", Bin{'-', Var{"n"}, Num{1}}},
		}}},
		Print{Var{"acc"}},
	}}

	in := &Interpreter{}
	in.execute(program, newEnv(nil))
	fmt.Println("nodes visited:", in.nodes)
	fmt.Printf("variable lookups: %d, parent links followed: %d\n", in.lookups, in.links)
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Each node is a struct, and an interface with an unexported marker method (isExpr, isStmt) closes the set of node types to this package.
  • A type switch selects the case and binds n to the concrete struct. The compiler does not check that the cases are complete, so each switch ends with a panic.
  • Env holds a map and a pointer to its parent. The garbage collector frees the environment of a block after the block ends.
RustGitHub
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

enum Expr {
    Num(i64),
    Var(&'static str),
    Bin(char, Box<Expr>, Box<Expr>),
}

enum Stmt {
    Let(&'static str, Expr),
    Assign(&'static str, Expr),
    Block(Vec<Stmt>),
    While(Expr, Box<Stmt>),
    Print(Expr),
}

struct Env {
    vars: RefCell<HashMap<&'static str, i64>>,
    parent: Option<Rc<Env>>,
}

impl Env {
    fn new(parent: Option<Rc<Env>>) -> Rc<Env> {
        Rc::new(Env { vars: RefCell::new(HashMap::new()), parent })
    }
}

#[derive(Default)]
struct Interpreter {
    nodes: u32,
    lookups: u32,
    links: u32,
}

impl Interpreter {
    fn find(&mut self, env: &Rc<Env>, name: &str) -> Rc<Env> {
        self.lookups += 1;
        let mut e = Rc::clone(env);
        loop {
            if e.vars.borrow().contains_key(name) {
                return e;
            }
            self.links += 1;
            e = match &e.parent {
                Some(p) => Rc::clone(p),
                None => panic!("undefined variable '{}'", name),
            };
        }
    }

    fn evaluate(&mut self, node: &Expr, env: &Rc<Env>) -> i64 {
        self.nodes += 1;
        match node {
            Expr::Num(value) => *value,
            Expr::Var(name) => {
                let found = self.find(env, name);
                let value = found.vars.borrow()[name];
                value
            }
            Expr::Bin(op, left, right) => {
                let a = self.evaluate(left, env);
                let b = self.evaluate(right, env);
                match op {
                    '+' => a + b,
                    '-' => a - b,
                    '*' => a * b,
                    '<' => (a < b) as i64,
                    _ => panic!("unknown operator {}", op),
                }
            }
        }
    }

    fn execute(&mut self, node: &Stmt, env: &Rc<Env>) {
        self.nodes += 1;
        match node {
            Stmt::Let(name, init) => {
                let value = self.evaluate(init, env);
                env.vars.borrow_mut().insert(*name, value);
            }
            Stmt::Assign(name, expr) => {
                let value = self.evaluate(expr, env);
                self.find(env, name).vars.borrow_mut().insert(*name, value);
            }
            Stmt::Block(body) => {
                let inner = Env::new(Some(Rc::clone(env)));
                for stmt in body {
                    self.execute(stmt, &inner);
                }
            }
            Stmt::While(cond, body) => {
                while self.evaluate(cond, env) != 0 {
                    self.execute(body, env);
                }
            }
            Stmt::Print(expr) => println!("{}", self.evaluate(expr, env)),
        }
    }
}

fn main() {
    use Expr::*;
    use Stmt::*;
    let program = Block(vec![
        Let("n", Num(5)),
        Let("acc", Num(1)),
        While(
            Bin('<', Box::new(Num(0)), Box::new(Var("n"))),
            Box::new(Block(vec![
                Let("step", Var("n")),
                Assign("acc", Bin('*', Box::new(Var("acc")), Box::new(Var("step")))),
                Assign("n", Bin('-', Box::new(Var("n")), Box::new(Num(1)))),
            ])),
        ),
        Print(Var("acc")),
    ]);

    let mut interp = Interpreter::default();
    interp.execute(&program, &Env::new(None));
    println!("nodes visited: {}", interp.nodes);
    println!("variable lookups: {}, parent links followed: {}", interp.lookups, interp.links);
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Two enums model the tree, and match must cover every variant, so a new node type is a compile error until the interpreter handles it.
  • An environment has several owners: the block that runs in it and every inner environment that points to it. Rc counts those owners and frees the environment when the last one goes. RefCell allows the map to change through a shared reference, and checks the borrows at run time.
  • A cycle of Rc pointers is never freed. Closures that capture their own environment create such cycles, so an interpreter with closures needs a weak pointer or a tracing garbage collector.
KotlinGitHub
sealed interface Expr
data class Num(val value: Long) : Expr
data class Var(val name: String) : Expr
data class Bin(val op: Char, val left: Expr, val right: Expr) : Expr

sealed interface Stmt
data class Let(val name: String, val init: Expr) : Stmt
data class Assign(val name: String, val value: Expr) : Stmt
data class Block(val body: List<Stmt>) : Stmt
data class While(val cond: Expr, val body: Stmt) : Stmt
data class Print(val value: Expr) : Stmt

class Env(val parent: Env? = null) {
    val vars = mutableMapOf<String, Long>()
}

class Interpreter {
    var nodes = 0
    var lookups = 0
    var links = 0

    private fun find(env: Env, name: String): Env {
        lookups++
        var e: Env? = env
        while (e != null) {
            if (name in e.vars) return e
            links++
            e = e.parent
        }
        error("undefined variable '$name'")
    }

    fun evaluate(node: Expr, env: Env): Long {
        nodes++
        return when (node) {
            is Num -> node.value
            is Var -> find(env, node.name).vars.getValue(node.name)
            is Bin -> {
                val a = evaluate(node.left, env)
                val b = evaluate(node.right, env)
                when (node.op) {
                    '+' -> a + b
                    '-' -> a - b
                    '*' -> a * b
                    '<' -> if (a < b) 1 else 0
                    else -> error("unknown operator ${node.op}")
                }
            }
        }
    }

    fun execute(node: Stmt, env: Env) {
        nodes++
        when (node) {
            is Let -> env.vars[node.name] = evaluate(node.init, env)
            is Assign -> {
                val result = evaluate(node.value, env)
                find(env, node.name).vars[node.name] = result
            }
            is Block -> {
                val inner = Env(env)
                for (stmt in node.body) execute(stmt, inner)
            }
            is While -> while (evaluate(node.cond, env) != 0L) execute(node.body, env)
            is Print -> println(evaluate(node.value, env))
        }
    }
}

fun main() {
    val program = Block(listOf(
        Let("n", Num(5)),
        Let("acc", Num(1)),
        While(Bin('<', Num(0), Var("n")), Block(listOf(
            Let("step", Var("n")),
            Assign("acc", Bin('*', Var("acc"), Var("step"))),
            Assign("n", Bin('-', Var("n"), Num(1))),
        ))),
        Print(Var("acc")),
    ))

    val interp = Interpreter()
    interp.execute(program, Env())
    println("nodes visited: ${interp.nodes}")
    println("variable lookups: ${interp.lookups}, parent links followed: ${interp.links}")
}
Output
120
nodes visited: 81
variable lookups: 37, parent links followed: 25
  • Verdict: idiom. Sealed interfaces and data classes model the tree. when with is checks the type, and smart casts give access to the fields of each case.
  • when used as an expression over a sealed interface must cover every subtype, or the compiler rejects it.
  • error(...) throws an IllegalStateException. Its return type is Nothing, so find needs no return after the loop.
  • A resolver pass. The interpreter above searches the chain of environments on every lookup, even though the answer for a given variable node never changes. A variable inside a loop that runs a thousand times is resolved a thousand times.7 A resolver walks the tree once before the run and records, for each variable node, how many environments lie between the use and the declaration. The interpreter then follows exactly that many parent links and does not search.8
  • Closures. A function value that keeps a pointer to the environment where it was created is a closure. The environment chain above is the data structure that makes Closure work, and it is why environments live on the heap and not on the host stack.
  • Memory. Each pass through a block allocates an environment. When a block ends, its environment becomes garbage unless a closure still points to it. An interpreter written in a host with Garbage collection gets this for free. An interpreter in C must free the environments itself.
  • Bytecode. A Bytecode interpreter compiles the tree once into a flat array of instructions and then runs a loop over the array. The Bytecode page compiles the same factorial program and counts its instructions.

Pitfalls

One flat environment for the whole program

An interpreter that stores every variable in one dictionary gives blocks no scope of their own. An inner let x overwrites the outer x, and the change is still visible after the block ends.

This code runs but gives a wrong answer on purpose.

env = {}


def run(node):
    match node:
        case ("let", name, value):
            env[name] = value
        case ("block", *body):
            for stmt in body:
                run(stmt)
        case ("print", name):
            print(name, "=", env[name])


# let x = 1; { let x = 2; print x; } print x;
run(("block", ("let", "x", 1), ("block", ("let", "x", 2), ("print", "x")), ("print", "x")))
Output
x = 2
x = 2

The second line should print x = 1. The fix is a new environment for each block, with a link to the enclosing one, as in the main example.

class Env:
    def __init__(self, parent=None):
        self.vars = {}
        self.parent = parent

    def get(self, name):
        env = self
        while name not in env.vars:
            env = env.parent
        return env.vars[name]


def run(node, env):
    match node:
        case ("let", name, value):
            env.vars[name] = value
        case ("block", *body):
            inner = Env(env)
            for stmt in body:
                run(stmt, inner)
        case ("print", name):
            print(name, "=", env.get(name))


run(("block", ("let", "x", 1), ("block", ("let", "x", 2), ("print", "x")), ("print", "x")), Env())
Output
x = 2
x = 1

Guest loops on the host stack

A while loop can be written as recursion: run the body once, then run the whole loop again. The code looks clean. Each pass, however, adds frames to the host stack, and the guest program now has a loop limit that has nothing to do with the guest language. Python raises RecursionError when the depth of the stack passes the recursion limit.13

This code raises RecursionError, on purpose.

def evaluate(node, env):
    match node:
        case ("num", value):
            return value
        case ("var", name):
            return env[name]
        case ("lt", a, b):
            return evaluate(a, env) < evaluate(b, env)
        case ("sub", a, b):
            return evaluate(a, env) - evaluate(b, env)


def execute(node, env):
    match node:
        case ("set", name, expr):
            env[name] = evaluate(expr, env)
        case ("print", expr):
            print(evaluate(expr, env))
        case ("while", cond, body):
            if evaluate(cond, env):
                execute(body, env)
                execute(node, env)


env = {"n": 10_000}
loop = ("while", ("lt", ("num", 0), ("var", "n")), ("set", "n", ("sub", ("var", "n"), ("num", 1))))
execute(loop, env)
execute(("print", ("var", "n")), env)

The fix uses a host loop for the guest loop. The stack stays at a constant depth, whatever the number of passes.

def evaluate(node, env):
    match node:
        case ("num", value):
            return value
        case ("var", name):
            return env[name]
        case ("lt", a, b):
            return evaluate(a, env) < evaluate(b, env)
        case ("sub", a, b):
            return evaluate(a, env) - evaluate(b, env)


def execute(node, env):
    match node:
        case ("set", name, expr):
            env[name] = evaluate(expr, env)
        case ("print", expr):
            print(evaluate(expr, env))
        case ("while", cond, body):
            while evaluate(cond, env):
                execute(body, env)


env = {"n": 10_000}
loop = ("while", ("lt", ("num", 0), ("var", "n")), ("set", "n", ("sub", ("var", "n"), ("num", 1))))
execute(loop, env)
execute(("print", ("var", "n")), env)
Output
0

The same limit applies to guest recursion. If each guest call becomes a host call, a deep guest recursion overflows the host stack.

Errors that wait for the code to run

A tree-walking interpreter looks up a name only when it evaluates the node. A typo in a branch that does not run is never reported. Crafting Interpreters makes this choice on purpose for Lox, because an error at the point of use, and not at the point of reference, lets mutually recursive functions refer to each other before both exist.4 The cost is that the program below runs and prints 0 with a misspelled name in it.

This code runs but gives a wrong answer on purpose.

def evaluate(node, env):
    match node:
        case ("num", value):
            return value
        case ("var", name):
            if name not in env:
                raise NameError(f"undefined variable {name!r}")
            return env[name]
        case ("lt", a, b):
            return evaluate(a, env) < evaluate(b, env)


def execute(node, env):
    match node:
        case ("let", name, expr):
            env[name] = evaluate(expr, env)
        case ("print", expr):
            print(evaluate(expr, env))
        case ("while", cond, body):
            while evaluate(cond, env):
                execute(body, env)
        case ("block", *body):
            for stmt in body:
                execute(stmt, env)


# let count = 0; while (count < 0) { print cuont; } print count;
program = ("block",
    ("let", "count", ("num", 0)),
    ("while", ("lt", ("var", "count"), ("num", 0)), ("print", ("var", "cuont"))),
    ("print", ("var", "count")),
)
execute(program, {})
Output
0

A static pass over the whole tree finds the name before the program starts. The pass visits both branches of every choice and every loop body once, whether or not they would run.

def check(node, scope):
    """Walk every node once before the program runs, in all branches."""
    match node:
        case ("num", _):
            pass
        case ("var", name):
            if name not in scope:
                raise NameError(f"undefined variable {name!r}")
        case ("lt", a, b):
            check(a, scope)
            check(b, scope)
        case ("let", name, expr):
            check(expr, scope)
            scope.add(name)
        case ("print", expr):
            check(expr, scope)
        case ("while", cond, body):
            check(cond, scope)
            check(body, scope)
        case ("block", *body):
            for stmt in body:
                check(stmt, scope)


program = ("block",
    ("let", "count", ("num", 0)),
    ("while", ("lt", ("var", "count"), ("num", 0)), ("print", ("var", "cuont"))),
    ("print", ("var", "count")),
)
try:
    check(program, set())
    print("no errors")
except NameError as e:
    print(f"error before the run: {e}")
Output
error before the run: undefined variable 'cuont'

This check is a small version of the resolver pass. A full one must also handle functions that refer to names declared later.

Cost

  • Dispatch on every node. Each node visit is a call plus a branch on the type of the node. In the example, 22 nodes cost 81 visits. A loop multiplies the visits of its body by the number of passes.
  • Pointers and locality. The tree is a web of separate objects on the heap. Each pointer takes 32 or 64 bits, each object carries a header, and the objects are scattered in memory. This is bad for the CPU caches, which load whole lines of adjacent bytes at a time.10
  • Variable lookups. A lookup through a chain of hash maps costs one hash lookup for each scope it passes. The example followed 25 parent links for 37 lookups. A resolver pass removes the search but still follows the links.8
  • Measured gap. Crafting Interpreters reports one measurement. A Fibonacci program took jlox, its tree-walking interpreter in Java, about 72 seconds on the author's laptop. An equivalent C program finished in half a second.9 The author's conclusion is that walking the AST is "fundamentally the wrong design" for a general-purpose language that must run fast.9
  • Startup. A tree-walker can start to run as soon as the parser finishes. It has no compile step.

Tree-walker or bytecode

Tree-walking interpreter Bytecode interpreter
Code at run time the AST: separate nodes linked by pointers a dense, linear array of instructions11
Dispatch a call and a type test for each node a loop that runs one instruction at a time11
Work before the run none after parsing a compiler pass over the tree
Effort to build the least: the runtime structure is the syntax10 a compiler and a virtual machine

Bytecode keeps the portability of a tree-walker, because the virtual machine is itself a program in a portable language. It gives up some simplicity for speed, but it is not as fast as native code.11

History

  • 1960. John McCarthy published the definition of LISP in Communications of the ACM. He described the universal function apply, which "plays the theoretical role of a universal Turing machine and the practical role of an interpreter".1 apply calls eval[e; a], a recursive function over the expression e with the environment a as a list of pairs of names and values.2

References

  1. John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, Communications of the ACM 3(4), 1960, section 1, Introduction (apply as an interpreter)
  2. John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, Communications of the ACM 3(4), 1960, section 3f, The Universal S-Function apply (eval, assoc, pair)
  3. Robert Nystrom, Crafting Interpreters, chapter 7, Evaluating Expressions, 7.2.3 Evaluating unary expressions (post-order traversal)
  4. Robert Nystrom, Crafting Interpreters, chapter 8, Statements and State, 8.3 Environments (bindings, undefined variables as runtime errors)
  5. Robert Nystrom, Crafting Interpreters, chapter 8, Statements and State, 8.5.1 Nesting and shadowing (chained environments)
  6. Robert Nystrom, Crafting Interpreters, chapter 7, Evaluating Expressions, 7.3.1 Detecting runtime errors (unwinding the recursive calls)
  7. Robert Nystrom, Crafting Interpreters, chapter 11, Resolving and Binding, 11.2 Semantic Analysis (a variable resolved each time it is evaluated)
  8. Robert Nystrom, Crafting Interpreters, chapter 11, Resolving and Binding, 11.4 Interpreting Resolved Variables (the number of environments to the declaration)
  9. Robert Nystrom, Crafting Interpreters, chapter 14, Chunks of Bytecode, chapter introduction (jlox and an equivalent C program on the same Fibonacci program)
  10. Robert Nystrom, Crafting Interpreters, chapter 14, Chunks of Bytecode, 14.1.1 Why not walk the AST?
  11. Robert Nystrom, Crafting Interpreters, chapter 14, Chunks of Bytecode, 14.1.3 What is bytecode?
  12. Robert Nystrom, Crafting Interpreters, chapter 7, Evaluating Expressions, 7.2 Evaluating Expressions (the Interpreter class as a visitor)
  13. The Python Standard Library, Built-in Exceptions, Python 3.14, RecursionError

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/X3BBA0/text.yaml