Programming Language Design and Construction
Building an Interpreter: From Trees to Results
Building an Interpreter means turning language rules into an executable procedure. Here, the program is already available as an abstract syntax tree. You will focus on evaluating that tree, carrying variable bindings into nested expressions, and reporting errors. Constructing the tree from source text is a separate task.
Specify the evaluation contract
An interpreter executes a program representation according to the language's rules. For this small language, every successful expression evaluation produces an integer. Assume all supplied trees are finite, well formed, and contain integer literals; there are no assignment statements or functions.
An environment maps variable names to their current values. Write it as ρ. Evaluating the same variable node in different environments can produce different results, even though the tree itself has not changed.
For readability, write nodes using constructor notation such as Num(4) and Add(left, right). The implementation below stores these as tuples, such as ("Num", 4) and ("Add", left, right).
Construct | Evaluation rule |
|---|---|
Num(n) | Return the stored integer. |
Var(x) | Look up the name; report an error if it is absent. |
Add(a, b) or Mul(a, b) | Evaluate the left child, then the right child, and combine their values. |
Let(x, a, b) | Evaluate the initializer, extend a local environment, and evaluate the body. |
IfZero(t, a, b) | Evaluate the test; evaluate the first branch for zero, otherwise the second. |
The governing rule for a local binding is
The notation inside the brackets means a new environment with a binding for the name. The initializer uses the incoming environment; the body uses the extended environment. If the name already exists, its previous value remains available outside this local expression.
Implement one case per construct
The evaluator follows the tree recursively: a parent delegates to the children required by its rule. A dictionary is sufficient for this language because every binding holds an integer.
def evaluate(expr, env):
tag = expr[0]
if tag == "Num":
return expr[1]
if tag == "Var":
name = expr[1]
if name not in env:
raise RuntimeError("unbound name: " + name)
return env[name]
if tag == "Add":
left = evaluate(expr[1], env)
right = evaluate(expr[2], env)
return left + right
if tag == "Mul":
left = evaluate(expr[1], env)
right = evaluate(expr[2], env)
return left * right
if tag == "Let":
value = evaluate(expr[2], env)
local = env.copy()
local[expr[1]] = value
return evaluate(expr[3], local)
if tag == "IfZero":
test = evaluate(expr[1], env)
branch = expr[2] if test == 0 else expr[3]
return evaluate(branch, env)
raise RuntimeError("unknown construct")Copying the dictionary prevents a local binding from changing the caller's bindings. This is adequate here because integers do not contain mutable state. It is an implementation choice, rather than a requirement that every interpreter copy dictionaries.
The conditional case deliberately evaluates one branch. Computing both branch values before checking the test would execute expressions the language says to skip. In contrast, addition and multiplication require both operand values. If a required evaluation raises an error, this implementation stops and propagates that error.
Test the language rules
Start with isolated tests for literals and arithmetic, then combine constructs. Check a variable that exists, one that is absent, a nested local binding that reuses a name, and a conditional whose unselected branch contains an absent name.
Also inspect the incoming environment after evaluation. A correct numeric result alone does not establish that local bindings stayed local. Reusing the same environment for a later expression can expose accidental changes that the first result concealed.
What to remember
- Give each construct an explicit evaluation rule.
- Pass the correct environment into every recursive call.
- Keep local bindings local and evaluate only the selected conditional branch.
- Test values, errors, and preservation of incoming bindings.
Example: Evaluating a capacity rule
A workshop uses a small integer interpreter to compute a capacity in items. When Building an Interpreter, you need to check how nested bindings affect each lookup. Here, shadowing means that a local binding temporarily takes precedence over an enclosing binding with the same name.
Num(n) returns an integer, Var(name) looks up the current binding, and Add and Mul perform ordinary arithmetic. Let(name, initializer, body) evaluates its initializer in the incoming environment, copies that environment, installs the local binding, and evaluates the body in the copy. The caller's environment initially contains rate = 5.
The supplied expression tree is written using constructor notation:
Let("rate", Num(8),
Add(Let("rate", Add(Var("rate"), Num(3)),
Mul(Var("rate"), Num(2))),
Var("rate")))Interpret the final integer as the capacity in items; intermediate values are dimensionless integers.
a) What integer does the inner Let expression return?
The outer initializer returns 8, so the outer body receives a local environment with rate = 8.
The inner initializer runs before its new binding is installed. Its lookup of rate therefore returns ________, and its addition computes
The inner body receives a new local environment where rate is ________. Its multiplication returns
The inner Let expression returns 22. Its initializer used the enclosing binding, while its body used the new binding.
b) What capacity does the entire expression return, and what value remains in the caller's environment?
The left operand of the outer addition is the completed inner Let, which returns ________. The right operand is outside that inner binding, so its lookup uses the outer local value of rate, which is ________.
The outer addition computes
The expression returns a capacity of 30 items. Each Let installed its binding in a copied environment, so the caller's original environment still contains rate = 5. Returning from the inner expression does not change the environment used by the outer addition.
c) Replace the inner multiplication with the following conditional. What capacity is returned, and does the missing name cause an error?
IfZero(Num(0),
Mul(Var("rate"), Num(2)),
Var("bonus"))IfZero(test, yes, no) evaluates its test and then only the first branch for zero, or only the second branch otherwise. No environment contains bonus.
The conditional runs inside the inner local environment, where rate is 11. Its test evaluates to ________, so the selected branch is the multiplication.
That branch computes
The unselected Var("bonus") branch is never evaluated. An absent name causes a lookup error only if that lookup executes.
The outer right operand still returns 8, so the complete expression returns
The capacity remains 30 items, and no unbound-name error occurs. The caller's binding also remains unchanged.
A team is constructing a small programming language and documenting its implementation. Match each concept to the description of its role.
Represents a program using structured nodes for its constructs, omitting punctuation used only for grouping.
Specifies how executing a program produces values, changes state, or encounters runtime errors.
Translates a convenient construct into simpler constructs while preserving its specified observable behavior.
Specifies program restrictions checked without executing the program, such as operand type requirements.
Desugaring
Abstract syntax tree
Dynamic semantics
Static semantics
A packaging configuration interpreter uses Num(n) for an integer, Var(name) for lookup, and Add and Mul for ordinary integer arithmetic. Let(name, initializer, body) evaluates its initializer in the incoming environment and evaluates its body with a local binding for that name.
The incoming environment binds batch to 4. Evaluate this supplied tree, whose result is the number of items to prepare:
Let("batch", Num(6),
Mul(Add(Var("batch"), Num(3)),
Add(Var("batch"), Num(2))))Enter the result in items, as an exact integer with zero decimal places.