Interpreter represents the grammar of a small language as a class hierarchy, one class per grammar rule, and gives every class an interpret(context) operation. A sentence in the language then becomes a tree of those objects, an abstract syntax tree (AST), that evaluates itself: each node computes its value from its children's values and the context. It is the classic way to evaluate formulas, rules and filters that users or configuration supply as data. The Gang of Four pattern covers representing and evaluating sentences; turning text into the tree (parsing) is a separate job.
Think of it like
A tax form
A tax form is a small program written in a small language. Line 3 says "enter your salary", line 5 says "enter your interest", line 7 says "add lines 3 and 5", and line 8 says "multiply line 7 by the rate in table B". Some lines just read a value (terminals); others combine the results of other lines (nonterminals). The form is printed once and filled in by millions of people, each bringing their own numbers: the context. Working out line 8 means working out line 7 first, which means reading lines 3 and 5. Nobody rewrites the form for each taxpayer; they evaluate the same form against different numbers.
The problem
A delivery app lets its operations team set shipping fees as formulas, such as base + 3 * kg, stored as configuration and changed without a release. Each order supplies the variables (base = 5, kg = 2), and the app must evaluate the formula: 11. Suppose a parser already turns the text into a tree. How should the tree be represented and evaluated? A common first version uses one generic node record and one evaluator that switches on the node's kind. This is the Before version in the visualizer above.
type Arg = Node | number | string;
class Node {
constructor(
readonly kind: string, // "num", "var", "add", "mul"
readonly args: Arg[]) {}
}
class Evaluator {
constructor(private vars: Map<string, number>) {}
calc(n: Node): number {
const [a, b] = n.args;
switch (n.kind) {
case "num": return a as number;
case "var": return this.lookup(a as string);
case "add":
return this.calc(a as Node) + this.calc(b as Node);
case "mul":
return this.calc(a as Node) * this.calc(b as Node);
default: throw new Error(n.kind);
}
}
lookup(name: string): number {
const v = this.vars.get(name);
if (v !== undefined) return v;
throw new Error("no " + name);
}
}- Stringly typed nodes.
kindis any string andargsis any list, so the types give up: every case casts (a as Node). A"mul"with one argument, or a typo like"mull", is only caught when the evaluator reaches it. - One class knows every rule. Each new operator is another
caseinEvaluator.calc(), and the rules of the language have no home of their own: the meaning of+lives in a switch, not in anAdd. - Every walk repeats the switch. Printing the formula, checking it, or translating it to SQL each need their own function with the same
switch (n.kind), and a new operator must be added to all of them. - The nodes are passive. In the visualizer, the nodes never receive a message; only
evdoes. Nothing on a node can enforce its own shape.
The pattern
Intent (GoF): "Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language." Each grammar rule becomes a class; a sentence becomes a tree of instances; evaluation is a recursive interpret(context) call on the root.
- Abstract expression (
Expr) - Declares
interpret(ctx). Every node of the tree implements it, so a parent never needs to know what kind of child it has. - Terminal expression (
Num,Var) - A grammar rule with no sub-expressions: a literal or a variable name. These are the leaves.
Numreturns its own value;Varasks the context for its value. - Nonterminal expression (
Add,Mul,Max) - A rule built from other expressions. It holds its sub-expressions as fields and implements
interpretby interpreting them and combining the results. - Context (
Context) - Information from outside the sentence: here the variables of one order. The same tree is evaluated against many contexts.
- Client
- Builds the tree (usually via a parser) or receives it, then calls
interpret(ctx)on the root.
From grammar to classes
| Grammar rule | Class | Kind | interpret(ctx) returns |
|---|---|---|---|
expr := number | Num | Terminal | Its own value; the context is not needed |
| name | Var | Terminal | ctx.lookup(name) |
| expr "+" expr | Add | Nonterminal | left.interpret(ctx) + right.interpret(ctx) |
| expr "*" expr | Mul | Nonterminal | left.interpret(ctx) * right.interpret(ctx) |
| "max" "(" expr "," expr ")" | Max (the change request) | Nonterminal | Math.max(left…, right…) |
* binds tighter than + because the parser put the Mul below the Add; once the tree exists, its shape is its meaning. The sentence base + 3 * kg is the tree below. Add interpret = 5 + 6 = 11
/ \
Var "base" Mul interpret = 3 * 2 = 6
/ \
Num 3 Var "kg" (ctx: base = 5, kg = 2)Structurally this is a Composite: terminals are leaves, nonterminals are containers, and interpret is the operation that recurses. Evaluation is a post-order walk (Tree Traversals): a node can only combine its children's values after they have been computed, which is why postfix notation evaluates so easily with a stack (Stacks).
What the visualizer shows
- Class diagram:
Expron top with four implementations.AddandMulalso hold twoExprs each (the aggregation labeled2), andVardepends onContext. A call lights the class whose code runs and the violetExprinterface that declaresinterpret. - Objects at runtime: the tree itself, root on top:
fee(anAdd) points tobaseandprod;prod(aMul) points tothreeandkg. The contextctxsits beside the tree, holdingvars = Map{base: 5, kg: 2}. - Sequence of calls: the strongest moment. One
interpret(ctx)from the client becomes nested activation bars:feeasksbase, which asksctx.lookup("base")(5); thenfeeasksprod, which asksthree(3, no context needed) andkg, which asksctx.lookup("kg")(2). The returns carry5,3,2, then6and finally11: values combining on the way back up. - Controls: Play or the arrow buttons step through the run (the classes in the code panel really execute); Before / With Interpreter switches versions; Add max applies the change request, badges the touched classes and fills the Change request panel beside the code.
- Before: the same tree as
Noderecords. After the client's first call, every message goes fromevto itself (calc(base),calc(prod),lookup("kg")): the nodes never get one.
Walkthrough
- 1
Build the tree, leaves first
With With Interpreter selected, the client creates what a parser would produce for
base + 3 * kg:base(Var),three(Num),kg(Var), thenprod = new Mul(three, kg)andfee = new Add(base, prod). Constructors only store children; nothing is evaluated yet. - 2
Create the context
ctx = new Context(new Map([["base", 5], ["kg", 2]])). The tree is the program, the context is its input. Another order would be another context for the same tree. - 3
One call on the root
fee.interpret(ctx).feeis anAdd, soAdd.interpretruns and first asks itsleftchild. - 4
A terminal asks the context
baseis aVar: it holds only a name, so it callsctx.lookup("base")and returns 5 tofee. The value was never in the tree. - 5
Recurse into the nonterminal
feeasks itsrightchild,prod.prodasksthree, which returns its own 3 without touching the context, andkg, which looks up 2. - 6
Combine on the way up
prodreturns3 * 2 = 6;feereturns5 + 6 = 11to the client. In the Sequence view each activation bar closes only after its children's bars have closed. - 7
Add an operator
Apply Add max. The formula becomes
max(12, base + 3 * kg): a minimum fee. One new class,Max, implementsExpr;Num,Var,Add,MulandContextare untouched. The run returnsmax(12, 11) = 12.
Before and after
One evaluator switching on kind
- Generic
Noderecords: any kind string, any arguments, casts everywhere - The meaning of every operator lives in one growing switch
- Each new operation (print, check, translate) repeats the switch
- Compact, and a new operation is one new function in one place
With Interpreter
- One small, typed class per grammar rule; nodes enforce their own shape
- A new grammar rule is a new class; existing classes stay closed
- The tree is an object you can evaluate against many contexts, print or inspect
- Many small classes, and a new operation must be added to every class
Change request: add max(a, b) | Before | With Interpreter |
|---|---|---|
| Existing classes edited | 1 (Evaluator) | 0 |
| New classes | 0 | 1 (Max) |
| Lines changed in existing classes | 4 (+4 −0) | 0 |
Adding an operation instead (say show()) | 1 new function with its own switch | 1 new method in each of the 5 classes |
Variations
What goes in the context
The context is everything a sentence needs that is not part of the sentence: variable bindings, a table of allowed functions, the current user, an output buffer, or a stack of scopes for a language with blocks. Keep the tree immutable and put per-evaluation state in the context: then one tree can be evaluated against thousands of contexts, even concurrently, and parsing happens once. Nor does interpret have to return a number: a boolean rule language returns true or false ((age >= 18) and (country == "IN")), and a template language appends text to an output buffer in the context. GoF's own motivating example is a regular-expression language whose sentences match strings.
Sharing terminals (Flyweight)
Immutable nodes can be shared. A parser can hand out one Var("kg") and one Num(1) for every occurrence, which is the Flyweight idea applied to terminal symbols, and a subtree can appear inside several trees: the first implementation wraps the existing fee tree in new Max(new Num(12), fee) without copying it. Shared subtrees turn the tree into a DAG, which is fine as long as nothing mutates a node.
Building the tree: parsing is a separate job
- By hand, or with a builder API. GoF Interpreter says nothing about how the tree is built; in the visualizer the client builds it directly. Combinators in the host language, such as
premium.and(inStock)in Specification, need no text at all. - A hand-written recursive-descent parser: one method per grammar rule, with precedence encoded by which method calls which (
exprcallsterm,termcallsfactor). The second implementation below is one: about 100 lines including the tokenizer. Operator-precedence parsing and Dijkstra's shunting-yard algorithm (Stacks) are alternatives for expressions. - A parser generator such as ANTLR or yacc/Bison, which produces the parser from a grammar file. Worth it once the grammar has dozens of rules or will keep growing.
More operations than interpret: enter Visitor
Real languages need more than evaluation: pretty-printing, type checking, constant folding (2 * 3 becomes 6), translation to SQL. Put each one on the node classes and every class grows a method per operation. Visitor moves each operation into its own class with one visit method per node type, which flips the trade-off:
| Design | Add a grammar rule | Add an operation |
|---|---|---|
| Interpreter (operations on the nodes) | Cheap: one new class | Expensive: a method in every class |
| Visitor (operations in visitor classes) | Expensive: a method in every visitor | Cheap: one new visitor |
| Switch or pattern match over node kinds | Expensive: a case in every function | Cheap: one new function |
Performance and safety
A tree-walking interpreter pays for its simplicity: every node is an object on the heap and every evaluation step is a virtual call plus a pointer to follow. For a fee formula evaluated a few thousand times a second that cost is invisible. When the same expressions run millions of times, the usual next steps are:
- Parse once, interpret many times. Cache the tree per formula; parsing is usually the expensive part.
- Compile the tree to closures: walk the AST once and return a nested function (
(ctx) => l(ctx) + r(ctx)), removing the per-node dispatch on the hot path. - Compile to bytecode for a virtual machine. CPython compiles source to bytecode and runs it on a virtual machine loop. Ruby's reference implementation walked the AST up to version 1.8, and version 1.9 replaced that with the YARV bytecode VM, largely for speed. SQLite compiles every SQL statement to bytecode for its own virtual machine.
In real code
| Where | What it is | Interpreter idea |
|---|---|---|
Java java.util.regex.Pattern | Pattern.compile turns the regular expression into a structure of linked Pattern.Node objects (private nested classes in the OpenJDK source), one per construct; a Matcher runs them against the input | A regular-expression language interpreted by node objects, which is GoF's own motivating example |
SQL WHERE clauses | A database parses price * qty > 100 into an expression tree and evaluates it for each candidate row; engines differ in how (tree walking, SQLite's bytecode VM, PostgreSQL's optional JIT compilation of expressions) | The same expression evaluated against many contexts (rows) |
| Spring Expression Language (SpEL) | SpelExpressionParser parses strings such as order.total > 100 into an AST of node classes (OpPlus, OpGT, PropertyOrFieldReference and others) evaluated against an EvaluationContext; a SimpleEvaluationContext restricts what an expression can reach | An embeddable expression language; similar ones include Google's Common Expression Language (CEL) and OGNL |
| Template engines | Many engines parse a template into a tree of text, variable, condition and loop nodes and render it against a data context; some (Jinja, for example) compile the tree to code first | interpret that writes output instead of returning a number |
| Specification | Leaf specs and AndSpec / NotSpec combinators answer isSatisfiedBy(candidate) | A tiny fixed boolean language: leaves are terminals, combinators are nonterminals, the candidate is the context |
When to use it, and when not to
Reach for Interpreter when
- The language is small and stable: a handful of rules (formulas, filters, eligibility rules, feature-flag targeting)
- Sentences change more often than code: users or configuration supply them
- The same sentence is evaluated against many contexts
- You want to inspect sentences too: print them, explain a result, translate them to SQL
Look elsewhere when
- The grammar is large or growing: use a parser generator (ANTLR) and visitors over its tree
- Evaluation is a hot path: compile to closures or bytecode
- An existing language fits: embed CEL, SpEL or a sandboxed Lua instead of growing a JSON rule format into a language one request at a time
- The "formula" never changes at run time: just write the code
Interpreter vs similar patterns
| Pattern | How it differs | Example |
|---|---|---|
| Composite | Composite is the structure (leaves and containers behind one interface); Interpreter is that structure where the classes are grammar rules and the operation is evaluation | Folder.size() vs Add.interpret(ctx) |
| Visitor | Visitor moves operations out of the node classes, so new operations are cheap and new node types are expensive; Interpreter keeps interpret on the nodes, the other way round. Compilers often combine them: an AST plus visitors | expr.accept(new PrintVisitor()) vs expr.interpret(ctx) |
| Specification | Specification is a tiny fixed boolean language for business rules (leaves plus and, or, not); Interpreter is the general technique for any grammar | premium.and(inStock) vs a parsed fee formula |
| Command | A command is a request executed for its effect, often queued or undone; an expression is evaluated for a value. A statement node in a scripting language looks a lot like a command | PlaceOrderCommand.execute() vs Mul.interpret(ctx) |
| Flyweight | Flyweight shares immutable objects to save memory; Interpreter can use it to share terminal symbols and subtrees | One Var("kg") instance for every kg in the formula |
Implementation
The scenario as a complete program: a Context with the variables of one order, terminal expressions Num and Var, nonterminal expressions Add, Mul and Max (the change request), each with interpret and a second operation, show, to make the cost of adding operations visible. The demo evaluates the same tree against two orders, reuses it inside a max(12, ...) formula, and shows the error for an unknown variable. Java uses records, Python abstract base classes, and C++ shared pointers to const nodes.
from abc import ABC, abstractmethod
# Grammar of the fee language, one class per rule:
# expr := number | name | expr "+" expr | expr "*" expr
# | "max" "(" expr "," expr ")"
class Context:
"""What the sentence is evaluated against."""
def __init__(self, variables: dict[str, int]) -> None:
self._vars = dict(variables)
def lookup(self, name: str) -> int:
if name not in self._vars:
raise LookupError(f"unknown variable: {name}")
return self._vars[name]
class Expr(ABC):
@abstractmethod
def interpret(self, ctx: Context) -> int: ...
@abstractmethod
def show(self) -> str: ... # a second operation: every class needs it
# Terminal expressions: the leaves of the tree.
class Num(Expr):
def __init__(self, value: int) -> None:
self._value = value
def interpret(self, ctx: Context) -> int:
return self._value # a literal never needs the context
def show(self) -> str:
return str(self._value)
class Var(Expr):
def __init__(self, name: str) -> None:
self._name = name
def interpret(self, ctx: Context) -> int:
return ctx.lookup(self._name)
def show(self) -> str:
return self._name
# Nonterminal expressions: hold sub-expressions and recurse into them.
class Add(Expr):
def __init__(self, left: Expr, right: Expr) -> None:
self._left, self._right = left, right
def interpret(self, ctx: Context) -> int:
return self._left.interpret(ctx) + self._right.interpret(ctx)
def show(self) -> str:
return f"({self._left.show()} + {self._right.show()})"
class Mul(Expr):
def __init__(self, left: Expr, right: Expr) -> None:
self._left, self._right = left, right
def interpret(self, ctx: Context) -> int:
return self._left.interpret(ctx) * self._right.interpret(ctx)
def show(self) -> str:
return f"({self._left.show()} * {self._right.show()})"
# The change request: a new grammar rule is one new class.
class Max(Expr):
def __init__(self, left: Expr, right: Expr) -> None:
self._left, self._right = left, right
def interpret(self, ctx: Context) -> int:
return max(self._left.interpret(ctx), self._right.interpret(ctx))
def show(self) -> str:
return f"max({self._left.show()}, {self._right.show()})"
if __name__ == "__main__":
# The tree a parser would build for "base + 3 * kg".
fee = Add(Var("base"), Mul(Num(3), Var("kg")))
order1 = Context({"base": 5, "kg": 2})
order2 = Context({"base": 5, "kg": 4})
print(fee.show()) # (base + (3 * kg))
print(fee.interpret(order1)) # 11
print(fee.interpret(order2)) # 17: same tree, another context
# A minimum fee: max(12, base + 3 * kg). The old tree is reused.
with_floor = Max(Num(12), fee)
print(with_floor.show()) # max(12, (base + (3 * kg)))
print(with_floor.interpret(order1)) # 12
print(with_floor.interpret(order2)) # 17
try:
fee.interpret(Context({"kg": 1}))
except LookupError as e:
print(e) # unknown variable: baseKey takeaways
- Interpreter maps a grammar to classes: one class per rule, terminals for literals and variables, nonterminals that hold sub-expressions.
- A sentence is a tree of those objects (an AST), and
interpret(ctx)evaluates it recursively: children first, then the parent combines their values. - The context carries what the sentence does not: variables, functions, output. Keep the tree immutable and evaluate it against many contexts.
- Parsing is a separate job: build the tree by hand, with a recursive-descent parser, or with a parser generator for big grammars.
- New grammar rules are cheap (the visualizer's
maxis one new class); new operations touch every class, which is what Visitor fixes. - Fits small, stable languages. Never
evaluser input; for hot paths compile the tree to closures or bytecode.
Common pitfalls
- Using Interpreter for a large grammar: dozens of node classes, each with every operation. Use a parser generator and visitors.
- Mixing parsing into the node classes, or re-parsing the text on every evaluation instead of caching the tree.
- Storing per-evaluation state (a running total, the current row) in the nodes, which breaks sharing and concurrent evaluation. Put it in the context.
- Silently treating an unknown variable as 0 (or letting a missing value flow into the arithmetic) instead of failing, so a typo in a formula becomes a wrong price.
- Evaluating untrusted input without limits: no cap on length or nesting depth, no timeout for languages with loops, or falling back to the host language's
eval.
Interview tips
- Start from the grammar: write three or four BNF rules, then map each to a class and mark terminals and nonterminals.
- Draw the AST for a concrete sentence and trace
interpretdown and back up; say that precedence lives in the tree's shape, decided by the parser. - Bring up the trade-off with Visitor (rules vs operations) and the expression problem by name.
- Mention production concerns: parse once and cache, never
eval, limits on depth and length, and compiling to bytecode when evaluation is hot.
Real-world applications
- Pricing, fee and tax formulas stored as configuration.
- Business rule engines and eligibility checks (discounts, fraud rules, feature-flag targeting).
- Search and query filters typed by users (
status:open AND assignee:me). - Expression languages embedded in frameworks and configuration (SpEL, CEL in Kubernetes validation rules).
- Regular-expression engines and template engines.
- Calculators, spreadsheet formulas and small domain-specific languages for tests or game scripting.
Test yourself
In the visualizer, which object finds out that kg is 2?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.