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 ρ\rho. 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


eval⁡(Let⁡(x,a,b),ρ)=eval⁡(b,ρ[x↦eval⁡(a,ρ)]).\operatorname{eval}(\operatorname{Let}(x,a,b),\rho) =\operatorname{eval}\bigl(b,\rho[x\mapsto\operatorname{eval}(a,\rho)]\bigr).


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.



An expression tree and an environment enter an evaluator that produces an integer value or a runtime error.


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.


Python
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:


Python
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


8+3=11.8+3=11.


The inner body receives a new local environment where rate is ________. Its multiplication returns


11×2=22.11\times 2=22.


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


22+8=30.22+8=30.


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?


Python
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


11×2=22.11\times 2=22.


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


22+8=30.22+8=30.


The capacity remains 30 items, and no unbound-name error occurs. The caller's binding also remains unchanged.

A configuration interpreter receives an expression tree containing variable references and a separate environment of integer bindings. Which description correctly assigns their responsibilities during evaluation?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A team is constructing a small programming language and documenting its implementation. Match each concept to the description of its role.

Match each term
A.

Represents a program using structured nodes for its constructs, omitting punctuation used only for grouping.

B.

Specifies how executing a program produces values, changes state, or encounters runtime errors.

C.

Translates a convenient construct into simpler constructs while preserving its specified observable behavior.

D.

Specifies program restrictions checked without executing the program, such as operand type requirements.

Desugaring

Abstract syntax tree

Dynamic semantics

Static semantics

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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:


Python
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.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice