Part III — Advanced Systems · Chapter 12 · Lesson 2 of 7 · 5 min read
Lesson 2: Tree-Walking Interpretation
Lesson level: Advanced
Purpose: Understand how the interpreter executes a checked syntax tree directly, how environments and control flow are represented at runtime, and what this design costs and offers.
Release note: internal names and inspection commands in this lesson are illustrative. Verify them against your installed v0.63 release before relying on them.
Learning objectives
By the end of this lesson, you should be able to:
- Explain how a tree-walking interpreter evaluates expressions and executes statements.
- Describe how environments, calls, and returns are modelled at runtime.
- Explain how break, continue, return, and exceptions unwind the tree walk.
- Compare the strengths and costs of tree walking with bytecode execution.
- Trace a short program through the interpreter by hand.
2.1 The core idea
A tree-walking interpreter visits each node of the syntax tree and performs its meaning immediately. Expression nodes return values. Statement nodes change state or control flow. There is no separate translation step.
2.2 Evaluating expressions
Evaluation is recursive. To evaluate a binary node, the interpreter evaluates the left child, then the right child, then applies the operator. Literal nodes return their value; name nodes look the name up in the current environment.
evaluate(Binary op=+ (Name a) (Binary op=* (Name b) (Name c)))
evaluate(Name a) -> 2
evaluate(Binary op=*)
evaluate(Name b) -> 3
evaluate(Name c) -> 4
apply * -> 12
apply + -> 14
2.3 Short-circuit nodes
and and or nodes are special: the interpreter evaluates the left child, checks its truthiness, and only then decides whether to visit the right child. This is exactly the behavior described in Chapter 2.
2.4 Executing statements
| Statement node | Interpreter action |
|---|---|
| LetDecl / ConstDecl | Evaluate the initializer, then define the name in the current environment |
| Assign | Evaluate the value, locate the existing binding, check it is not constant, update it |
| Evaluate the expression, convert to text, send to the output handler | |
| If | Evaluate the condition; execute the first matching block in a new nested environment |
| While | Repeat: evaluate condition, execute body, until the condition is false-like |
| Block | Create a child environment, execute each statement, discard the environment |
2.5 Environments at runtime
Each environment holds its bindings and a link to its parent. Entering a block or calling a function creates a new environment; leaving it drops the reference. Lookup walks the parent chain, which is why deeply nested scopes cost slightly more per lookup.
2.6 Functions and calls
A function declaration produces a function value that remembers the environment where it was defined. A call evaluates the callee and arguments, creates a new environment whose parent is that remembered environment, binds the parameters, and executes the body.
function bulk_reason(qty) {
if qty >= 10 { return "BULK" }
return "NONE"
}
print bulk_reason(12)
Remembering the defining environment, not the calling one, is what makes closures from Chapter 4 work.
2.7 Non-local control flow
return, break, continue, and thrown exceptions must leave several nested node visits at once. A common technique is to raise an internal signal that unwinds the recursive calls until the matching function, loop, or try node catches it. Treat this as a model of behavior rather than a description of exact internals.
| Signal | Caught by | Effect |
|---|---|---|
| Return | Enclosing function call | Call produces the returned value |
| Break | Nearest loop | Loop stops |
| Continue | Nearest loop | Next iteration begins |
| Exception | Nearest matching try/catch | Handler runs; otherwise the error reaches the host |
2.8 Resource limits in the interpreter
Because every node visit passes through the interpreter, it is a natural place to count steps, check deadlines, and bound recursion depth. Chapter 14 covers these limits in detail; here, note that runaway loops and deep recursion are stopped by the runtime rather than by the operating system.
2.9 Strengths and costs
| Aspect | Tree walking | Bytecode VM (Lessons 3 to 5) |
|---|---|---|
| Start-up | Immediate after parsing | Needs a compile step |
| Per-operation cost | Higher: recursive visits and node dispatch | Lower: flat instruction loop |
| Debuggability | Maps directly to source nodes | Needs position tables |
| Portability of artifacts | Source only | Serialized bytecode can be shipped |
| Best fit | Development, REPL, short scripts | Repeated execution, distribution |
2.10 Worked trace
Trace print bulk_reason(12) from section 2.6:
- Visit Print; evaluate its expression.
- Visit Call; evaluate callee bulk_reason to a function value.
- Evaluate argument 12.
- Create a call environment with qty = 12, parent = global.
- Visit If; evaluate qty >= 10 to true.
- Visit Return; raise a return signal carrying "BULK".
- The Call node catches the signal and produces "BULK".
- Print converts "BULK" to text and outputs it.
2.11 Running with the interpreter
pea run order_rules.pea
In v0.63 the ordinary run command uses the source interpreter; later lessons show how to select VM execution. Confirm the default engine in your release.
2.12 Common mistakes
- Assuming calls use the caller's environment: closures capture the defining environment.
- Expecting the right side of and/or always to run: short-circuit nodes may skip it.
- Treating deep recursion as free: each call adds an environment and interpreter frames, and limits apply.
- Benchmarking tree walking against the VM with a single run: include start-up and repeated-run costs separately.
2.13 Guided practice
- Write the visit order for (a + b) * c.
- Trace a while loop that sums 1 to 3, listing environment changes.
- Explain which node catches a break inside an if inside a loop.
- Show how a closure keeps access to a variable after its defining function returns.
2.14 Hands-on lab
Pick one function from order_rules that uses a loop and an early return. Produce a full node-visit trace for one input, including environment creation and each control-flow signal. Then run the function under the debugger and confirm the order of steps matches your trace.
Deliverable: the annotated trace and a note on any step where the debugger output differed from your prediction.
2.15 Review questions
- What does a tree-walking interpreter do at each node?
- How are block environments created and discarded?
- Why does a function value remember its defining environment?
- How do return and break leave several nested visits?
- When is tree walking preferable to bytecode execution?
2.16 Applied challenge
Design an instruction-count limit for the interpreter. State which node visits count, where the check runs, what error is raised, and how the host can tell a limit failure from an ordinary exception.
Lesson summary
- The interpreter executes the checked tree directly, node by node.
- Environments model scope; calls create environments linked to the defining scope.
- Non-local control flow unwinds nested visits to the right handler.
- Tree walking is simple and debuggable but slower for repeated execution.
Transition to Lesson 3
To run code faster and ship it without source, PeaLang can compile the tree into a flat list of stack instructions. Lesson 3 introduces stack bytecode, constants, code objects, and instructions.
Lesson status: Ready for review.