Lesson 4 of 9 · 26m
Tree-Walking Interpreters: Evaluation as a Recursive Walk
Implement direct AST evaluation with explicit values, control flow, and predictable failure behavior before worrying about speed.
The fastest way to make a language real is not to compile it. Walk the tree and execute it. A tree-walking interpreter is slow in the grand scheme, but it exposes semantics with brutal clarity: values flow through the program structure with no instruction encoding in the way.
Evaluation is a big recursion
def evaluate(node, env):
if isinstance(node, Number):
return node.value
if isinstance(node, Binary):
left = evaluate(node.left, env)
right = evaluate(node.right, env)
return apply_binary(node.op, left, right, node.span)
if isinstance(node, Variable):
return env.get(node.name, node.span)
if isinstance(node, Assign):
value = evaluate(node.value, env)
env.assign(node.name, value, node.span)
return valueOne rule per node, no hidden state. Pattern matching makes this prettier in some host languages, but the discipline matters more than the syntax.
Define your values explicitly
Decide what values exist — numbers, strings, booleans, nil, functions, objects — and define operations over them. Do not let the host language accidentally define your language:
def apply_binary(op, left, right, span):
if op == "+" and isinstance(left, str) and isinstance(right, str):
return left + right
if op in {"+", "-", "*", "/"} and is_number(left) and is_number(right):
return numeric_binary(op, left, right, span)
raise RuntimeErrorAt(span, f"operator {op} not defined for these operands")If Python, JavaScript, or Ruby would coerce something your language should reject, the interpreter must reject it. Accidental semantics become backward compatibility debt.
Control flow is not a value
return, break, and continue need a channel separate from ordinary evaluation. Exceptions are a pragmatic implementation technique:
class ReturnSignal(Exception):
def __init__(self, value):
self.value = valueA return node raises the signal; the function call catches it and unwraps the value. This is not sloppy if intentional and isolated — it is a straightforward model of non-local control flow.
Field notes
- Division by zero, missing variables, and arity mismatch are errors in your language; never leak raw host exceptions to users.
- Implement equality deliberately. Is
1 == 1.0true? Isnilequal to itself? Does object identity matter? - Route printing, file access, and networking through explicit native functions. Pure evaluation becomes much easier to test.
- Add a trace flag early. Logging node kind, result, and environment depth turns impossible bugs into five-minute bugs.
Was this lesson helpful?