Interpreters
Interpreters are programs that directly execute source-code representations (AST or bytecode) by implementing the language's semantics at runtime, used for REPLs, scripting languages, debugging, teaching, and as a step toward JIT compilation.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Interpreters are used by engineers when they need rapid development, interactive REPLs, scripting, teaching language semantics, or a portable execution engine (virtual machine). Interpreters also appear inside compilers and virtual machines: parsing produces an AST (see Lexical analysis, Top-down parsing, Bottom-up parsing), then an interpreter either walks the AST or runs generated bytecode; JIT compilers and virtual machines (see Runtime support) build on interpreter design.
Key ideas
Interpreter — a program that directly executes source, AST, or bytecode of a language without producing a standalone native executable ahead of time (AOT).
Bytecode — a compact, linearized instruction sequence produced from the AST. Bytecode is an abstraction of machine code for a virtual machine. Define: bytecode instruction = an opcode (operation) plus zero or more operands (indexes, immediates).
AST-walking (tree-walking) interpreter — the interpreter executes by recursively visiting AST nodes and evaluating them. It is easy to write and maps closely to semantics.
Bytecode interpreter (virtual machine) — the interpreter executes a sequence of bytecode instructions in a fetch-decode-execute loop. Bytecode is often either stack-based or register-based.
Environment (or context) — a mapping from variable names to runtime values. When evaluating an expression or calling a function, the interpreter consults and updates the environment. Define mapping: environment ρ : Identifier → Value. For mutable variables, it is common to use an environment ρ : Identifier → Location and a separate store σ : Location → Value.
Closure — a pair of a function's code (its AST or bytecode) and the environment (variable bindings) that existed when the function was created. Closures implement lexical scoping: a function sees the variables of its defining environment.
Lexical vs dynamic scoping — lexical scoping: a variable reference is resolved using the environment where the function was defined; dynamic scoping: resolved using the environment where the function is called. State which is used by common modern languages (lexical) and mention dynamic scoping briefly.
Execution architectures to draw (diagram to describe): draw three horizontally stacked boxes labelled (left) "Source code → Lexer → Parser", (middle) "AST" producing an arrow to either "AST-walking Interpreter" (top-right) or to "Bytecode Compiler" → "Bytecode" → "Bytecode VM" (bottom-right). Label arrows: "AST" arrow to both consumers; annotate VM box with "stack/register, pc, call stack". This diagram shows the two main interpreter styles.
Operational semantics (big-step / natural semantics) for a tiny expression language. Use judgment form:
ρ ⊢ e ⇓ vmeaning "under environment ρ, expression e evaluates to value v." Define symbols when first used.Rules (exact statements universities expect):
- Constant rule: if n is a numeric literal then
ρ ⊢ n ⇓ n. - Variable rule: if ρ(x) = v then
ρ ⊢ x ⇓ v. - Binary op rule (for binary op op and expressions e1, e2): if
ρ ⊢ e1 ⇓ v1andρ ⊢ e2 ⇓ v2andv = apply_op(op, v1, v2)thenρ ⊢ (e1 op e2) ⇓ v. - Division-by-zero error rule (example): if op is
/andρ ⊢ e2 ⇓ 0thenρ ⊢ (e1 / e2) ⇓ error.
State assumptions explicitly: operations are total on the value domain used in the rule statements (or otherwise state errors like division-by-zero produce runtime error). Show you would add an error rule for division by zero.
- Constant rule: if n is a numeric literal then
Formulas
List of syntax / tiny APIs to remember (each on its own line):
eval(ast, env) -> value — evaluate AST node under environment env
eval_Const(n, env) -> n — constant node returns its literal
eval_Var(name, env) -> env[name] — lookup variable in environment
eval_Binop(op, left, right, env) -> apply_op(op, eval(left, env), eval(right, env)) — binary operator
while (pc < code.length) { instr = code[pc]; pc = pc + 1; dispatch(instr); } — bytecode fetch-decode-execute loop (VM main loop)
PUSH_CONST c, POP, PUSH_VAR name (or LOAD_VAR idx), STORE_VAR idx, ADD, SUB, MUL, DIV, CALL n, RET — example bytecode instruction names (stack VM)
closure = (code_pointer, captured_env) — closure representation
Note: these are syntax / pseudo-APIs you should memorise for designing or explaining an interpreter.
Worked examples
Example 1 — AST-walking evaluation (trace, exam style)
Language: integer literals, variables, binary +, -, *, /. Environment ρ0 = { x ↦ 4, y ↦ 7 }.
Expression: (x + 2) * (y - 3).
AST (draw this): root * with left child + whose children x and 2; right child - whose children y and 3.
Evaluation steps (big-step rules):
- Evaluate left subtree
x + 2:ρ0 ⊢ x ⇓ 4by Variable rule because ρ0(x) = 4.ρ0 ⊢ 2 ⇓ 2by Constant rule.- apply_op(+, 4, 2) = 6 ⇒
ρ0 ⊢ (x + 2) ⇓ 6.
- Evaluate right subtree
y - 3:ρ0 ⊢ y ⇓ 7.ρ0 ⊢ 3 ⇓ 3.- apply_op(-, 7, 3) = 4 ⇒
ρ0 ⊢ (y - 3) ⇓ 4.
- Apply multiply: apply_op(*, 6, 4) = 24 ⇒
ρ0 ⊢ (x + 2) * (y - 3) ⇓ 24. Final answer: 24.
Example 2 — Stack-based bytecode interpreter trace Compile the same expression to stack bytecode (one valid sequence): 1 PUSH_VAR x 2 PUSH_CONST 2 3 ADD 4 PUSH_VAR y 5 PUSH_CONST 3 6 SUB 7 MUL Start with empty stack S = []. Environment same as before. Step-by-step stack snapshot (value on top shown rightmost): After 1: S = [4] After 2: S = [4, 2] After 3 (ADD): pop 2 and 4, push 6 → S = [6] After 4: S = [6, 7] After 5: S = [6, 7, 3] After 6 (SUB): pop 3 and 7, push 4 → S = [6, 4] After 7 (MUL): pop 4 and 6, push 24 → S = [24] Final top of stack: 24.
(Exam note: in your trace show opcode, stack before and after, and concretely show values pushed and popped; label stack top.)
Common mistakes
- Forgetting to copy or capture environment when creating closures (causes late-binding bugs).
- In bytecode VMs, off-by-one errors with the program counter (pc increments before/after dispatch) and stack underflow/overflow are frequent. Write and test invariants: pc points to next instruction; stack has enough operands for each opcode.
- When tracing AST-walking evaluation, students sometimes mutate the AST nodes instead of using a separate environment, losing referential transparency.
- Not handling runtime errors in the semantics: e.g., division-by-zero must be explicitly shown as producing an error state.
For your exam
Kinds of questions you will be asked:
- Definitions and short notes: define interpreter, AST, bytecode, closure, environment, lexical vs dynamic scoping.
- Derivations / semantics: give big-step rules for a small language and use them to prove an example evaluates to a value (model answer must show each rule application and assumptions).
- Algorithms / pseudo-code: write a tree-walking eval function for arithmetic expressions, or a bytecode VM main loop and explain each opcode's effect on stack/pc/env.
- Traces / step-by-step: execute either AST evaluation or bytecode for a given input; show stack/pc and environment snapshots.
- Design questions: choose between AST-walker vs bytecode VM vs JIT for a use-case and justify (speed, portability, complexity).
What a full-marks answer includes:
- Precise definitions of terms used.
- For semantics: statement of inference rules with clear premises and conclusion, and explicit environment assumptions.
- Correct and labelled diagram when required (AST and VM boxes, arrows labelled).
- For code: correct pseudocode that maintains invariants (pc, stack depth), and a short complexity note if requested.
- Clear step-by-step trace matching your semantics or code.
Quick check
- What is a closure?
- Name two differences between AST-walking and bytecode interpreters.
- In big-step semantics, what does the judgment
ρ ⊢ e ⇓ vmean? Answers: 1) A closure is a pair of a function's code and the captured environment where it was defined. 2) AST-walking evaluates tree nodes recursively and maps closely to source; bytecode interpreters run a linear instruction stream in a fetch-decode-execute loop and typically use a stack or registers — bytecode is more compact and often faster. 3) Under environment ρ, expression e evaluates to value v.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?