4.3 ASTs and Tree-Walking Evaluation
An evaluator that walks the abstract syntax tree is the simplest execution engine, and usually the slowest of the common designs. The reasons are in where the time goes.
4.3.1 Motivation
Once you have an AST, you must execute it. The simplest execution engine is a function that recursively visits each node, examines its type, and runs the corresponding action. This is called tree-walking evaluation, and it is the baseline the other designs are measured against.
Tree-walking is easy to understand and implement. The correspondence between the tree structure and the code that executes it is direct: a function for evaluating expressions calls itself on child nodes, with no code generation step between parsing and evaluation. The cost of that simplicity is speed.
4.3.2 Mental model
An evaluator needs three things:
- A representation of a value
- An environment for name lookup
- A function that consumes an AST node and produces a value
The function has a dispatch: examine the node type, then run the handler. Constants evaluate to themselves. Symbols become lookups in an environment. Calls apply functions to arguments.
The dispatch happens on every single node every single time that code runs. A loop that executes one thousand times dispatches one thousand times through the same nodes. A compiled system decodes once and optimizes the path. A tree-walker decodes one thousand times.
4.3.3 Pseudocode for tree-walking eval
Here is the core logic of a tree-walking evaluator, handling three node types:
function eval(node, env):
if node is a constant:
return node
else if node is a symbol:
return lookup(node.name, env)
else if node is a call:
func <- eval(node.function, env)
args <- eval each argument in node.args
return apply(func, args, env)
else
error("unknown node type")This recursion is the whole interpreter. Everything else is machinery around it. Environments handle nested scopes. A closure captures its enclosing environment. A special form such as if or quote receives the unevaluated tree so it can decide what to evaluate.
4.3.4 A worked example
Consider evaluating 1 + 2 * x where x = 10 in the current environment.
The AST is:
+
/ \
1 *
/ \
2 xThe evaluator begins:
eval(+_call, env):
func = eval(+, env) # symbol lookup, returns builtin +
args = [eval(1, env), # constant, returns 1
eval(*_call, env)] # recursive call
eval(*_call, env):
func = eval(*, env) # symbol lookup, returns builtin *
args = [eval(2, env), # constant, returns 2
eval(x, env)] # symbol lookup, returns 10
return 2 * 10 = 20
return 1 + 20 = 21The evaluator walked the tree depth-first, left to right. Each node triggered a dispatch and a recursive call (or a lookup).
4.3.5 Environments for name lookup
Names must resolve to values. An environment is a table of name-to-value bindings. When evaluation reaches a symbol, it searches this table. If nothing matches, it searches the enclosing environment, then up the chain. It continues until it finds the binding or runs out of environments and raises an error.
This chain traversal happens on every symbol lookup. A name that is not local climbs frame by frame, and from the global environment a lookup of a base function passes every attached package on the search path. GNU R shortens that last stretch with a global cache (USE_GLOBAL_CACHE in envir.c) for lookups from the global environment, but each local frame is still searched in turn. This repeated traversal is one source of tree-walking slowness.
4.3.6 The cost of tree-walking
Three costs dominate:
Dispatch overhead
Each node causes a type check and jump. A simple expression like a + b is a call node and three symbols: the evaluator dispatches on the call, looks up + in the function position, looks up a and b, and then applies the function. One machine addition hides inside all of that machinery.
Pointer chasing
Nodes are scattered in memory. Walking the tree means following pointers from one node to its children. The CPU cannot predict where the next pointer points. This causes cache misses and memory stalls. Modern CPUs are fast at arithmetic but poor at following arbitrary pointers.
Branch misprediction
The type dispatch is a branch instruction. A CPU has limited branch prediction hardware. A sequence of unpredictable branches (different node types in different order) causes mispredicts. Each mispredict stalls the pipeline and shows up as lower instructions per cycle. Hardware counters measure it directly: perf stat on Linux reports branch misses.
A plain tree-walker pays all three costs on every node it visits. Bytecode interpretation and JIT compilation remove different pieces of this overhead. Self-specializing AST interpreters, such as those built on GraalVM’s Truffle, cut the dispatch cost by rewriting nodes in place, but that is a different design from the plain recursive eval above.
4.3.7 Call frames and stack depth
Each function call pushes a stack frame. The frame holds the function’s local variables, or in R a pointer to a new environment on the heap that holds them, plus a pointer to the enclosing environment. The evaluator then evaluates the function body with this frame on top of the stack.
Deeply nested calls exhaust stack memory. Tail-call optimization removes this hazard for recursive functions. A tail call is one where the return value of the recursive call is returned immediately without modification. The calling frame can be discarded instead of waiting for the recursive call to return. The language can reuse the same stack frame for many recursive calls, enabling unbounded recursion in space.
Tail-call optimization requires compiler or interpreter support. Spotting a tail position in the AST is easy. The hard part for a tree-walker written in C is that eval recurses on C’s own stack, so reusing a frame needs a trampoline or a loop inside the evaluator. Some interpreters do it anyway.
4.3.8 Failure modes
A common mistake is assuming that all recursive calls are equivalent. They are not. A tail call can reuse the stack frame. A non-tail call cannot. This matters when the recursion is deep.
# Tail-recursive: the recursive call is the last thing the function does
sum_to_n <- function(n, acc = 0) {
if (n <= 0) acc else sum_to_n(n - 1, acc + n)
}
# Not tail-recursive: n + ... runs after the recursive call returns
sum_to_n_naive <- function(n) {
if (n <= 0) 0 else n + sum_to_n_naive(n - 1)
}
sum_to_n(1e4) # Error: evaluation nested too deeply
sum_to_n_naive(1e4) # Error: evaluation nested too deeplyR does not optimize tail calls on its own, so in R 4.6.1 both fail with “evaluation nested too deeply: infinite recursion / options(expressions=)?”, the naive one just under depth 5000. The tail-recursive one fails sooner, near depth 2500, and laziness is the reason: acc + n is passed as a promise that is never forced on the way down, so the base case forces a chain of nested promises as deep as the recursion. Since R 4.4.0 the experimental Tailcall() reuses the current call’s context, and with acc forced it runs to any depth:
sum_tc <- function(n, acc = 0) {
force(acc)
if (n <= 0) acc else Tailcall(sum_tc, n - 1, acc + n)
}
sum_tc(1e6) # 5000005000004.3.9 R’s approach
How R Executes Code shows the eval function at the C level. R’s eval is a straightforward tree-walker. It uses SEXP for values and chains environments for scope, and the pseudocode above matches the overall shape of the C code, except that a closure’s arguments become promises instead of being evaluated before the call. The other large difference is that when a closure’s body has been byte-compiled, eval hands it to bcEval instead of walking it.
R’s tree-walker is the baseline for everything that follows. The byte-code engine, which R’s documentation calls its JIT, removes part of the dispatch cost; the costs of environments and lazy arguments remain.
Where this appears
- r-in-rust (rrs) Implements a tree-walking evaluator as its primary execution engine.
- threaded-r Must isolate tree-walker state to enable multithreaded execution.