PeaBox Lab › PeaLang › Learn › Chapter 12 › Lesson 2

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:

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 nodeInterpreter action
LetDecl / ConstDeclEvaluate the initializer, then define the name in the current environment
AssignEvaluate the value, locate the existing binding, check it is not constant, update it
PrintEvaluate the expression, convert to text, send to the output handler
IfEvaluate the condition; execute the first matching block in a new nested environment
WhileRepeat: evaluate condition, execute body, until the condition is false-like
BlockCreate 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.

SignalCaught byEffect
ReturnEnclosing function callCall produces the returned value
BreakNearest loopLoop stops
ContinueNearest loopNext iteration begins
ExceptionNearest matching try/catchHandler 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

AspectTree walkingBytecode VM (Lessons 3 to 5)
Start-upImmediate after parsingNeeds a compile step
Per-operation costHigher: recursive visits and node dispatchLower: flat instruction loop
DebuggabilityMaps directly to source nodesNeeds position tables
Portability of artifactsSource onlySerialized bytecode can be shipped
Best fitDevelopment, REPL, short scriptsRepeated execution, distribution

2.10 Worked trace

Trace print bulk_reason(12) from section 2.6:

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

2.13 Guided practice

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

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

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.

← Previous Next →