Patterncore
Interpreter pattern
Also called Interpreter, tree-walking interpreter, AST interpreter.
Represent each rule of a small language as a class, build a tree of those objects for a sentence, and evaluate the sentence by asking the root of the tree to interpret itself.
- Family
- behavioral-design
- Intent
- Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Intent
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.1
The language is small and belongs to the program: a filter that users type, a pricing rule, a query over a log, a template. Each rule of its grammar becomes a class. A sentence becomes a tree of objects of those classes, and the program evaluates the sentence by asking the root of the tree to interpret itself.
Problem
A shop lets staff write discount rules such as qty * (price + 2) into a settings page. The program must compute the rule for each order. The rules change every week, and the people who write them are not programmers.
A first design calls the host language's eval on the text. This runs. It also runs any other code that the text contains. The Python documentation says that eval "executes arbitrary code" and that calling it with untrusted input "will lead to security vulnerabilities".4 A formula field becomes a door into the server. See Code injection.
A second design writes the rules as if statements in the program. Each change of a rule is then a release of the program.
The forces are these. The sentences come from outside the program, so the program must accept only the language it defines. The program must evaluate the same sentence many times, with different values. And the program needs more than one operation on a sentence: evaluate it, show it, check that every variable is known.
Solution
Write a grammar for the language. Make one class for each rule. A sentence is then a tree of instances, and every class has an operation interpret that takes a context, which holds the values of the variables. Design Patterns names five participants.1
- AbstractExpression declares
interpret(context). - TerminalExpression implements it for a symbol with no parts: a number, a variable name.
- NonterminalExpression implements it for a rule with parts, such as
Add(left, right). It interprets its parts and joins the results. - Context holds the information that is global to the interpreter, such as the values of the variables.
- Client builds the tree for a sentence and calls
interpret.
grammar classes
expr := term ('+' term)* Expr (abstract): evaluate(env), show()
term := factor ('*' factor)* |- Num value terminal
factor := NUMBER |- Var name terminal
| NAME |- Add left, right nonterminal
| '(' expr ')' |- Mul left, right nonterminal
sentence: x * (y + 2)
tree: Mul
/ \
Var x Add
/ \
Var y Num 2
The tree is an abstract syntax tree. It keeps the structure of the sentence and drops the parentheses and the spaces. It is also an instance of Composite pattern: a nonterminal holds child expressions, and the client treats a leaf and a whole tree the same way.1 The evaluation is Recursion over that structure. Each node evaluates its children, then itself.
The pattern does not say how to build the tree. Design Patterns says that it does not address parsing.1 The client can build the tree by hand, as the example files do, or use a parser. A recursive-descent parser has one function for each rule of the grammar, so its shape follows the grammar too:
import re
from dataclasses import dataclass
class LanguageError(Exception):
pass
@dataclass(frozen=True)
class Num:
value: int
def evaluate(self, env):
return self.value
@dataclass(frozen=True)
class Var:
name: str
def evaluate(self, env):
if self.name not in env:
raise LanguageError(f"unknown variable {self.name}")
return env[self.name]
@dataclass(frozen=True)
class Add:
left: object
right: object
def evaluate(self, env):
return self.left.evaluate(env) + self.right.evaluate(env)
@dataclass(frozen=True)
class Mul:
left: object
right: object
def evaluate(self, env):
return self.left.evaluate(env) * self.right.evaluate(env)
TOKEN = re.compile(r"\s*(?:(\d+)|([a-z]+)|(.))")
def parse(text):
tokens = [m.groups() for m in TOKEN.finditer(text) if m.group(0).strip()]
pos = 0
def peek():
return tokens[pos][2] if pos < len(tokens) else None
def expr(): # expr := term ('+' term)*
nonlocal pos
node = term()
while peek() == "+":
pos += 1
node = Add(node, term())
return node
def term(): # term := factor ('*' factor)*
nonlocal pos
node = factor()
while peek() == "*":
pos += 1
node = Mul(node, factor())
return node
def factor(): # factor := NUMBER | NAME | '(' expr ')'
nonlocal pos
if pos == len(tokens):
raise LanguageError("unexpected end")
number, name, symbol = tokens[pos]
pos += 1
if number:
return Num(int(number))
if name:
return Var(name)
if symbol == "(":
node = expr()
if peek() != ")":
raise LanguageError("expected )")
pos += 1
return node
raise LanguageError(f"unexpected {symbol}")
tree = expr()
if pos != len(tokens):
raise LanguageError(f"unexpected {tokens[pos][2] or 'token'}")
return tree
env = {"qty": 3, "price": 4}
for text in ["qty * (price + 2)", "qty * price + 2", "qty + disc", "qty * (2", "__import__('os')"]:
try:
print(f"{text!r}: {parse(text).evaluate(env)}")
except LanguageError as err:
print(f"{text!r}: error: {err}")
print(parse("qty * (price + 2)"))
'qty * (price + 2)': 18
'qty * price + 2': 14
'qty + disc': error: unknown variable disc
'qty * (2': error: expected )
"__import__('os')": error: unexpected _
Mul(left=Var(name='qty'), right=Add(left=Var(name='price'), right=Num(value=2)))
The last input is not in the grammar, so the parser rejects it, and nothing runs. The language can only do what its classes do. That is the security property that eval cannot give.
The same text with eval runs whatever it contains:
This code runs but gives a wrong answer on purpose.
env = {"qty": 3, "price": 4}
rule = "print('this ran on the server') or qty * price"
print(eval(rule, {"__builtins__": {"print": print}}, env))
this ran on the server
12
The documentation also says that removing __builtins__ from the globals "is not a security mechanism".4 The block above gives print back on purpose, to make the call visible. ast.literal_eval is no answer here either: it accepts only literals, not operators or names.5
The parser of the host language as the front end
Python exposes its own parser through the ast module, which returns a tree of node objects.6 A program can use that parser and still define its own language, if its interpreter accepts only some node types. Every other node is an error:
import ast
def evaluate(node, env):
match node:
case ast.Expression(body=body):
return evaluate(body, env)
case ast.Constant(value=int() as value):
return value
case ast.Name(id=name) if name in env:
return env[name]
case ast.BinOp(left=left, op=ast.Add(), right=right):
return evaluate(left, env) + evaluate(right, env)
case ast.BinOp(left=left, op=ast.Mult(), right=right):
return evaluate(left, env) * evaluate(right, env)
case _:
raise ValueError(f"not allowed: {type(node).__name__}")
env = {"qty": 3, "price": 4}
for text in ["qty * (price + 2)", "qty ** 2", "__import__('os')"]:
try:
print(f"{text}: {evaluate(ast.parse(text, mode='eval'), env)}")
except ValueError as err:
print(f"{text}: {err}")
qty * (price + 2): 18
qty ** 2: not allowed: BinOp
__import__('os'): not allowed: Call
Here the classes of the tree come from the library, and the operations are one function with a match statement (see The match statement). The grammar of the language is now the set of case clauses.
Example
Each example file builds the tree for x * (y + 2) by hand, as the client. It evaluates the tree with two contexts, shows it as text, and evaluates z + 1, where z has no value. The files use the two forms of the pattern.
| Form | Languages | One more operation | One more node type |
|---|---|---|---|
| one class for each rule, one method for each operation | Python, JavaScript, Go, C# | a method in every class | one class |
| one type for each rule, one function for each operation | TypeScript, Java, Rust, C++, C | one function | a case in every function |
The second form uses a closed set of node types: a discriminated union in TypeScript, a sealed interface with records in Java, an enum in Rust, a std::variant in C++, and a tagged union in C. In TypeScript, Java and Rust, the compiler reports a switch or match that misses a node type.8910
from abc import ABC, abstractmethod
class UnknownVariable(Exception):
pass
class Expr(ABC):
"""AbstractExpression: every node of the tree can evaluate and show itself."""
@abstractmethod
def evaluate(self, env: dict[str, int]) -> int: ...
@abstractmethod
def show(self) -> str: ...
class Num(Expr): # TerminalExpression
def __init__(self, value: int) -> None:
self.value = value
def evaluate(self, env: dict[str, int]) -> int:
return self.value
def show(self) -> str:
return str(self.value)
class Var(Expr): # TerminalExpression
def __init__(self, name: str) -> None:
self.name = name
def evaluate(self, env: dict[str, int]) -> int:
if self.name not in env:
raise UnknownVariable(f"unknown variable {self.name}")
return env[self.name]
def show(self) -> str:
return self.name
class Add(Expr): # NonterminalExpression
def __init__(self, left: Expr, right: Expr) -> None:
self.left, self.right = left, right
def evaluate(self, env: dict[str, int]) -> int:
return self.left.evaluate(env) + self.right.evaluate(env)
def show(self) -> str:
return f"{self.left.show()} + {self.right.show()}"
class Mul(Expr): # NonterminalExpression
def __init__(self, left: Expr, right: Expr) -> None:
self.left, self.right = left, right
def evaluate(self, env: dict[str, int]) -> int:
return self.left.evaluate(env) * self.right.evaluate(env)
def show(self) -> str:
return f"{wrap(self.left)} * {wrap(self.right)}"
def wrap(e: Expr) -> str:
"""A sum inside a product needs parentheses."""
return f"({e.show()})" if isinstance(e, Add) else e.show()
def report(e: Expr, env: dict[str, int]) -> None:
label = " ".join(f"{k}={v}" for k, v in env.items())
try:
print(f"{label}: {e.evaluate(env)}")
except UnknownVariable as err:
print(f"{label}: error: {err}")
# The client builds the tree. Parsing is a separate job.
e = Mul(Var("x"), Add(Var("y"), Num(2)))
print("expression:", e.show())
report(e, {"x": 3, "y": 4})
report(e, {"x": 5, "y": 1})
f = Add(Var("z"), Num(1))
print("expression:", f.show())
report(f, {"x": 3, "y": 4})
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. Python has no construct for the pattern. A class for each rule of the grammar, with an abstract base class, is the classic form.
- Each class has one method for each operation,
evaluateandshow. A third operation means a third method in all four classes. - The
envdictionary is the Context of the pattern. It holds the values of the variables, and every node can read it. - Python can also write each operation as one function with a
matchstatement over dataclasses (see The match statement). The TypeScript, Rust and Java examples show that form.
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <variant>
// The grammar as a variant. unique_ptr gives the recursive cases a fixed size.
struct Expr;
using Ptr = std::unique_ptr<Expr>;
struct Num { int value; };
struct Var { std::string name; };
struct Add { Ptr left, right; };
struct Mul { Ptr left, right; };
struct Expr {
std::variant<Num, Var, Add, Mul> node;
};
Ptr num(int v) { return std::make_unique<Expr>(Expr{Num{v}}); }
Ptr var(std::string n) { return std::make_unique<Expr>(Expr{Var{std::move(n)}}); }
Ptr add(Ptr l, Ptr r) { return std::make_unique<Expr>(Expr{Add{std::move(l), std::move(r)}}); }
Ptr mul(Ptr l, Ptr r) { return std::make_unique<Expr>(Expr{Mul{std::move(l), std::move(r)}}); }
template <class... F> struct overloaded : F... { using F::operator()...; };
using Env = std::map<std::string, int>;
struct unknown_variable : std::runtime_error {
explicit unknown_variable(const std::string& name)
: std::runtime_error("unknown variable " + name) {}
};
int evaluate(const Expr& e, const Env& env) {
return std::visit(overloaded{
[](const Num& n) { return n.value; },
[&](const Var& v) {
auto it = env.find(v.name);
if (it == env.end()) throw unknown_variable(v.name);
return it->second;
},
[&](const Add& a) { return evaluate(*a.left, env) + evaluate(*a.right, env); },
[&](const Mul& m) { return evaluate(*m.left, env) * evaluate(*m.right, env); },
}, e.node);
}
std::string show(const Expr& e);
// A sum inside a product needs parentheses.
std::string wrap(const Expr& e) {
return std::holds_alternative<Add>(e.node) ? "(" + show(e) + ")" : show(e);
}
std::string show(const Expr& e) {
return std::visit(overloaded{
[](const Num& n) { return std::to_string(n.value); },
[](const Var& v) { return v.name; },
[](const Add& a) { return show(*a.left) + " + " + show(*a.right); },
[](const Mul& m) { return wrap(*m.left) + " * " + wrap(*m.right); },
}, e.node);
}
void report(const Expr& e, const Env& env) {
std::string label;
for (const auto& [k, v] : env) label += (label.empty() ? "" : " ") + k + "=" + std::to_string(v);
try {
int value = evaluate(e, env); // before any output, in case it throws
std::cout << label << ": " << value << "\n";
} catch (const unknown_variable& err) {
std::cout << label << ": error: " << err.what() << "\n";
}
}
int main() {
Ptr e = mul(var("x"), add(var("y"), num(2)));
std::cout << "expression: " << show(*e) << "\n";
report(*e, {{"x", 3}, {"y", 4}});
report(*e, {{"x", 5}, {"y", 1}});
Ptr f = add(var("z"), num(1));
std::cout << "expression: " << show(*f) << "\n";
report(*f, {{"x", 3}, {"y", 4}});
}
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. A
std::variantholds one node type, andstd::visitwith a set of lambdas gives each operation. The classic form with virtual functions is also valid C++. std::visitdoes not compile if a lambda for one of the alternatives is missing, so the compiler checks that each operation covers every node type.Exprwraps the variant in a struct so thatAddandMulcan hold aunique_ptrto a type that is not yet complete. The tree owns its children, and the destructor frees them.overloadedis the usual helper that joins the lambdas into one function object with an overloaded call operator.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
// The grammar: a sealed interface and one record for each rule.
sealed interface Expr permits Num, Var, Add, Mul {}
record Num(int value) implements Expr {}
record Var(String name) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
static class UnknownVariable extends RuntimeException {
UnknownVariable(String name) { super("unknown variable " + name); }
}
static int evaluate(Expr e, Map<String, Integer> env) {
return switch (e) {
case Num n -> n.value();
case Var v -> {
Integer value = env.get(v.name());
if (value == null) throw new UnknownVariable(v.name());
yield value;
}
case Add(Expr l, Expr r) -> evaluate(l, env) + evaluate(r, env);
case Mul(Expr l, Expr r) -> evaluate(l, env) * evaluate(r, env);
};
}
static String show(Expr e) {
return switch (e) {
case Num n -> Integer.toString(n.value());
case Var v -> v.name();
case Add(Expr l, Expr r) -> show(l) + " + " + show(r);
case Mul(Expr l, Expr r) -> wrap(l) + " * " + wrap(r);
};
}
// A sum inside a product needs parentheses.
static String wrap(Expr e) {
return e instanceof Add ? "(" + show(e) + ")" : show(e);
}
static void report(Expr e, Map<String, Integer> env) {
String label = env.entrySet().stream()
.map(kv -> kv.getKey() + "=" + kv.getValue())
.collect(Collectors.joining(" "));
try {
System.out.println(label + ": " + evaluate(e, env));
} catch (UnknownVariable err) {
System.out.println(label + ": error: " + err.getMessage());
}
}
static Map<String, Integer> env(String k1, int v1, String k2, int v2) {
Map<String, Integer> m = new LinkedHashMap<>();
m.put(k1, v1);
m.put(k2, v2);
return m;
}
public static void main(String[] args) {
Expr e = new Mul(new Var("x"), new Add(new Var("y"), new Num(2)));
System.out.println("expression: " + show(e));
report(e, env("x", 3, "y", 4));
report(e, env("x", 5, "y", 1));
Expr f = new Add(new Var("z"), new Num(1));
System.out.println("expression: " + show(f));
report(f, env("x", 3, "y", 4));
}
}
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. Records give the nodes, a sealed interface closes the set of node types, and a
switchwith record patterns gives each operation. - The
switchhas nodefault. The compiler accepts it because the interface is sealed and every permitted type has acase. A fifth record in thepermitslist makes both switches fail to compile. case Add(Expr l, Expr r)takes the record apart in the pattern, so the code names the children without calls to the accessors.- The classic form, with an abstract
evaluatemethod in each class, is also valid Java. The C# example shows it.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* The grammar as a tagged union. */
enum kind { NUM, VAR, ADD, MUL };
struct expr {
enum kind kind;
union {
int value; /* NUM */
const char *name; /* VAR */
struct { struct expr *left, *right; } op; /* ADD, MUL */
} as;
};
struct binding { const char *name; int value; };
struct env { const struct binding *items; size_t len; };
static struct expr *make(enum kind kind) {
struct expr *e = malloc(sizeof *e);
if (e == NULL) abort();
e->kind = kind;
return e;
}
static struct expr *num(int v) { struct expr *e = make(NUM); e->as.value = v; return e; }
static struct expr *var(const char *n) { struct expr *e = make(VAR); e->as.name = n; return e; }
static struct expr *binary(enum kind k, struct expr *l, struct expr *r) {
struct expr *e = make(k);
e->as.op.left = l;
e->as.op.right = r;
return e;
}
static void free_expr(struct expr *e) {
if (e->kind == ADD || e->kind == MUL) {
free_expr(e->as.op.left);
free_expr(e->as.op.right);
}
free(e);
}
/* Returns false and sets *missing if a variable has no value. */
static bool evaluate(const struct expr *e, struct env env, int *out, const char **missing) {
int l, r;
switch (e->kind) {
case NUM:
*out = e->as.value;
return true;
case VAR:
for (size_t i = 0; i < env.len; i++) {
if (strcmp(env.items[i].name, e->as.name) == 0) {
*out = env.items[i].value;
return true;
}
}
*missing = e->as.name;
return false;
case ADD:
case MUL:
if (!evaluate(e->as.op.left, env, &l, missing)) return false;
if (!evaluate(e->as.op.right, env, &r, missing)) return false;
*out = e->kind == ADD ? l + r : l * r;
return true;
}
abort();
}
static void show(const struct expr *e);
/* A sum inside a product needs parentheses. */
static void wrap(const struct expr *e) {
if (e->kind == ADD) { putchar('('); show(e); putchar(')'); }
else show(e);
}
static void show(const struct expr *e) {
switch (e->kind) {
case NUM: printf("%d", e->as.value); break;
case VAR: fputs(e->as.name, stdout); break;
case ADD: show(e->as.op.left); fputs(" + ", stdout); show(e->as.op.right); break;
case MUL: wrap(e->as.op.left); fputs(" * ", stdout); wrap(e->as.op.right); break;
}
}
static void report(const struct expr *e, struct env env) {
for (size_t i = 0; i < env.len; i++)
printf("%s%s=%d", i ? " " : "", env.items[i].name, env.items[i].value);
int value;
const char *missing;
if (evaluate(e, env, &value, &missing)) printf(": %d\n", value);
else printf(": error: unknown variable %s\n", missing);
}
int main(void) {
struct expr *e = binary(MUL, var("x"), binary(ADD, var("y"), num(2)));
const struct binding b1[] = {{"x", 3}, {"y", 4}};
const struct binding b2[] = {{"x", 5}, {"y", 1}};
fputs("expression: ", stdout); show(e); putchar('\n');
report(e, (struct env){b1, 2});
report(e, (struct env){b2, 2});
struct expr *f = binary(ADD, var("z"), num(1));
fputs("expression: ", stdout); show(f); putchar('\n');
report(f, (struct env){b1, 2});
free_expr(e);
free_expr(f);
return 0;
}
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. A tagged union holds the nodes, and a
switchon the tag gives each operation. C has no classes, so this is the function-per-operation form. - A
switchon anenumwith nodefaultlets the compiler warn (with-Wswitch, part of-Wallin GCC and Clang) when a case for one of the kinds is missing. evaluatereports failure through its return value and an output parameter, because C has no exceptions.- The client owns the tree and frees it with
free_expr, which walks the tree in the same way as the other operations.
var e = new Mul(new Var("x"), new Add(new Var("y"), new Num(2)));
Console.WriteLine($"expression: {e.Show()}");
Report(e, new() { ["x"] = 3, ["y"] = 4 });
Report(e, new() { ["x"] = 5, ["y"] = 1 });
var f = new Add(new Var("z"), new Num(1));
Console.WriteLine($"expression: {f.Show()}");
Report(f, new() { ["x"] = 3, ["y"] = 4 });
static void Report(Expr e, Dictionary<string, int> env)
{
var label = string.Join(" ", env.Select(kv => $"{kv.Key}={kv.Value}"));
try
{
Console.WriteLine($"{label}: {e.Evaluate(env)}");
}
catch (UnknownVariableException err)
{
Console.WriteLine($"{label}: error: {err.Message}");
}
}
// AbstractExpression: each node evaluates and shows itself.
abstract record Expr
{
public abstract int Evaluate(IReadOnlyDictionary<string, int> env);
public abstract string Show();
// A sum inside a product needs parentheses.
protected static string Wrap(Expr e) => e is Add ? $"({e.Show()})" : e.Show();
}
record Num(int Value) : Expr
{
public override int Evaluate(IReadOnlyDictionary<string, int> env) => Value;
public override string Show() => Value.ToString();
}
record Var(string Name) : Expr
{
public override int Evaluate(IReadOnlyDictionary<string, int> env) =>
env.TryGetValue(Name, out var value) ? value : throw new UnknownVariableException(Name);
public override string Show() => Name;
}
record Add(Expr Left, Expr Right) : Expr
{
public override int Evaluate(IReadOnlyDictionary<string, int> env) =>
Left.Evaluate(env) + Right.Evaluate(env);
public override string Show() => $"{Left.Show()} + {Right.Show()}";
}
record Mul(Expr Left, Expr Right) : Expr
{
public override int Evaluate(IReadOnlyDictionary<string, int> env) =>
Left.Evaluate(env) * Right.Evaluate(env);
public override string Show() => $"{Wrap(Left)} * {Wrap(Right)}";
}
class UnknownVariableException(string name) : Exception($"unknown variable {name}");
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. This is the classic form of the pattern: an abstract class with one abstract method for each operation, and one subclass for each rule.
- Records give the constructor, the properties and value equality, so two trees with the same shape compare equal with
==. - A
throwexpression letsVar.Evaluatestay one expression. - C# also has switch expressions with type patterns, which give the function-per-operation form of the TypeScript, Java and Rust examples. Without a sealed hierarchy, the compiler cannot check that such a switch covers every node type.
class UnknownVariable extends Error {}
// Each class is one rule of the grammar. Each one evaluates and shows itself.
class Num {
constructor(value) { this.value = value; }
evaluate(env) { return this.value; }
show() { return String(this.value); }
}
class Var {
constructor(name) { this.name = name; }
evaluate(env) {
if (!env.has(this.name)) throw new UnknownVariable(`unknown variable ${this.name}`);
return env.get(this.name);
}
show() { return this.name; }
}
class Add {
constructor(left, right) { this.left = left; this.right = right; }
evaluate(env) { return this.left.evaluate(env) + this.right.evaluate(env); }
show() { return `${this.left.show()} + ${this.right.show()}`; }
}
class Mul {
constructor(left, right) { this.left = left; this.right = right; }
evaluate(env) { return this.left.evaluate(env) * this.right.evaluate(env); }
show() { return `${wrap(this.left)} * ${wrap(this.right)}`; }
}
// A sum inside a product needs parentheses.
const wrap = (e) => (e instanceof Add ? `(${e.show()})` : e.show());
function report(e, env) {
const label = [...env].map(([k, v]) => `${k}=${v}`).join(" ");
try {
console.log(`${label}: ${e.evaluate(env)}`);
} catch (err) {
if (!(err instanceof UnknownVariable)) throw err;
console.log(`${label}: error: ${err.message}`);
}
}
const e = new Mul(new Var("x"), new Add(new Var("y"), new Num(2)));
console.log("expression:", e.show());
report(e, new Map([["x", 3], ["y", 4]]));
report(e, new Map([["x", 5], ["y", 1]]));
const f = new Add(new Var("z"), new Num(1));
console.log("expression:", f.show());
report(f, new Map([["x", 3], ["y", 4]]));
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. JavaScript has no construct for the pattern. The classes need no common base class, because the methods are found at run time.
- The
Mapis the Context. AMapis used, not a plain object, so that a variable calledconstructorortoStringis not found on the prototype. - The error class lets
reportcatch only the errors of the language and let real bugs pass.
// The grammar as a discriminated union. Each operation is one function.
type Expr =
| { kind: "num"; value: number }
| { kind: "var"; name: string }
| { kind: "add"; left: Expr; right: Expr }
| { kind: "mul"; left: Expr; right: Expr };
type Env = ReadonlyMap<string, number>;
type Result = { ok: true; value: number } | { ok: false; error: string };
const num = (value: number): Expr => ({ kind: "num", value });
const v = (name: string): Expr => ({ kind: "var", name });
const add = (left: Expr, right: Expr): Expr => ({ kind: "add", left, right });
const mul = (left: Expr, right: Expr): Expr => ({ kind: "mul", left, right });
function evaluate(e: Expr, env: Env): Result {
switch (e.kind) {
case "num":
return { ok: true, value: e.value };
case "var": {
const value = env.get(e.name);
return value === undefined
? { ok: false, error: `unknown variable ${e.name}` }
: { ok: true, value };
}
case "add":
case "mul": {
const l = evaluate(e.left, env);
if (!l.ok) return l;
const r = evaluate(e.right, env);
if (!r.ok) return r;
const value = e.kind === "add" ? l.value + r.value : l.value * r.value;
return { ok: true, value };
}
default: {
const unreachable: never = e;
return unreachable;
}
}
}
function show(e: Expr): string {
switch (e.kind) {
case "num":
return String(e.value);
case "var":
return e.name;
case "add":
return `${show(e.left)} + ${show(e.right)}`;
case "mul":
return `${wrap(e.left)} * ${wrap(e.right)}`;
}
}
const wrap = (e: Expr): string => (e.kind === "add" ? `(${show(e)})` : show(e));
function report(e: Expr, env: Env): void {
const label = [...env].map(([k, val]) => `${k}=${val}`).join(" ");
const r = evaluate(e, env);
console.log(r.ok ? `${label}: ${r.value}` : `${label}: error: ${r.error}`);
}
const e = mul(v("x"), add(v("y"), num(2)));
console.log("expression:", show(e));
report(e, new Map([["x", 3], ["y", 4]]));
report(e, new Map([["x", 5], ["y", 1]]));
const f = add(v("z"), num(1));
console.log("expression:", show(f));
report(f, new Map([["x", 3], ["y", 4]]));
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. The nodes are plain objects with a
kindtag. The compiler narrows the type in eachcase, soe.leftis only visible where the node has aleft. - The
nevercheck inevaluatemakes the compiler reject the function if a fifth kind joins the union and nocasehandles it.showgets the same check from its return type: a missingcasemeans a path that returns no string. - This form turns the pattern around. One more operation is one more function, and no node changes. One more kind of node means a change to every function. The Python and JavaScript examples have the opposite trade-off.
evaluatereturns a result object instead of throwing, so the type of the function shows that it can fail.
package main
import (
"fmt"
"strings"
)
// Expr is the AbstractExpression. Each node type below is one rule.
type Expr interface {
Eval(env map[string]int) (int, error)
String() string
}
type Num int
type Var string
type Add struct{ Left, Right Expr }
type Mul struct{ Left, Right Expr }
func (n Num) Eval(map[string]int) (int, error) { return int(n), nil }
func (n Num) String() string { return fmt.Sprint(int(n)) }
func (v Var) Eval(env map[string]int) (int, error) {
value, ok := env[string(v)]
if !ok {
return 0, fmt.Errorf("unknown variable %s", string(v))
}
return value, nil
}
func (v Var) String() string { return string(v) }
func (a Add) Eval(env map[string]int) (int, error) {
l, err := a.Left.Eval(env)
if err != nil {
return 0, err
}
r, err := a.Right.Eval(env)
if err != nil {
return 0, err
}
return l + r, nil
}
func (a Add) String() string { return a.Left.String() + " + " + a.Right.String() }
func (m Mul) Eval(env map[string]int) (int, error) {
l, err := m.Left.Eval(env)
if err != nil {
return 0, err
}
r, err := m.Right.Eval(env)
if err != nil {
return 0, err
}
return l * r, nil
}
func (m Mul) String() string { return wrap(m.Left) + " * " + wrap(m.Right) }
// wrap puts a sum inside a product in parentheses.
func wrap(e Expr) string {
if _, ok := e.(Add); ok {
return "(" + e.String() + ")"
}
return e.String()
}
type binding struct {
name string
value int
}
func report(e Expr, bindings ...binding) {
env := map[string]int{}
var label []string
for _, b := range bindings {
env[b.name] = b.value
label = append(label, fmt.Sprintf("%s=%d", b.name, b.value))
}
value, err := e.Eval(env)
if err != nil {
fmt.Printf("%s: error: %v\n", strings.Join(label, " "), err)
return
}
fmt.Printf("%s: %d\n", strings.Join(label, " "), value)
}
func main() {
e := Mul{Var("x"), Add{Var("y"), Num(2)}}
fmt.Println("expression:", e)
report(e, binding{"x", 3}, binding{"y", 4})
report(e, binding{"x", 5}, binding{"y", 1})
f := Add{Var("z"), Num(1)}
fmt.Println("expression:", f)
report(f, binding{"x", 3}, binding{"y", 4})
}
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. An interface with one method for each operation, and a type for each rule.
NumandVarare named basic types, so a leaf needs no struct. Stringis thefmt.Stringermethod, sofmt.Printlnshows the expression without a call toshow.- Each
Evalreturns an error as its second result. The error of the innermostVarpasses up through everyAddandMul. - The bindings are a slice, not a map, because the order of a Go map is not specified, and the label must print in a fixed order.
use std::collections::HashMap;
use std::fmt;
// The grammar as an enum. A Box gives the recursive variants a fixed size.
enum Expr {
Num(i64),
Var(&'static str),
Add(Box<Expr>, Box<Expr>),
Mul(Box<Expr>, Box<Expr>),
}
use Expr::*;
fn evaluate(e: &Expr, env: &HashMap<&str, i64>) -> Result<i64, String> {
match e {
Num(n) => Ok(*n),
Var(name) => env
.get(name)
.copied()
.ok_or_else(|| format!("unknown variable {name}")),
Add(l, r) => Ok(evaluate(l, env)? + evaluate(r, env)?),
Mul(l, r) => Ok(evaluate(l, env)? * evaluate(r, env)?),
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Num(n) => write!(f, "{n}"),
Var(name) => write!(f, "{name}"),
Add(l, r) => write!(f, "{l} + {r}"),
Mul(l, r) => write!(f, "{} * {}", Wrap(l), Wrap(r)),
}
}
}
// A sum inside a product needs parentheses.
struct Wrap<'a>(&'a Expr);
impl fmt::Display for Wrap<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Add(..) => write!(f, "({})", self.0),
other => write!(f, "{other}"),
}
}
}
fn report(e: &Expr, bindings: &[(&'static str, i64)]) {
let env: HashMap<&str, i64> = bindings.iter().copied().collect();
let label: Vec<String> = bindings.iter().map(|(k, v)| format!("{k}={v}")).collect();
match evaluate(e, &env) {
Ok(value) => println!("{}: {value}", label.join(" ")),
Err(error) => println!("{}: error: {error}", label.join(" ")),
}
}
fn main() {
let e = Mul(Box::new(Var("x")), Box::new(Add(Box::new(Var("y")), Box::new(Num(2)))));
println!("expression: {e}");
report(&e, &[("x", 3), ("y", 4)]);
report(&e, &[("x", 5), ("y", 1)]);
let f = Add(Box::new(Var("z")), Box::new(Num(1)));
println!("expression: {f}");
report(&f, &[("x", 3), ("y", 4)]);
}
expression: x * (y + 2)
x=3 y=4: 18
x=5 y=1: 15
expression: z + 1
x=3 y=4: error: unknown variable z
- Verdict: idiom. An enum gives the rules of the grammar and
matchgives each operation. The compiler rejects amatchthat misses a variant. Box<Expr>is needed because a value of a recursive enum would otherwise have no fixed size.- The
?operator returns the error ofVarfromevaluateat once, soAddandMulneed no explicit error checks. Displaymakes the second operation, soprintln!shows an expression. The smallWraptype adds parentheses around a sum inside a product.
Consequences
Design Patterns lists four consequences.1
- The grammar is straightforward to change and to extend. The rules are classes, so inheritance can change or extend them, and a rule that one sentence uses is the same class for every sentence.
- The grammar is straightforward to implement. The classes for the nodes have similar code, and each one is small.
- Complex grammars are hard to maintain. One class for each rule means hundreds of classes for a large grammar.
- Other ways to interpret expressions are possible, because the tree is data. A pretty-printer or a type checker is a second walk over the same tree.
The cost of the fourth point depends on the form. In the class form, each operation is a method in every class, so one more operation touches every class. In the function form, each node type is a case in every function, so one more node type touches every function. Wadler named this trade-off the expression problem: add both cases and functions to a data type without recompiling existing code, and keep static type safety.3 Crafting Interpreters calls the class form, with an abstract interpret() on each class, "literally" the Interpreter pattern, and says that it works for tiny projects but scales poorly, because the parser, the interpreter and later passes all work on the same tree classes.2
A tree walk is slow. Each evaluation visits every node again and makes a call for each one. Design Patterns says that the pattern works well when efficiency is not a critical concern, and that efficient interpreters usually translate the tree into another form first.1 A rule that runs once per order is fine. An inner loop over millions of rows is a reason to compile the tree.
Recursion has a depth limit. Both evaluate and a recursive-descent parser use one stack frame for each level of the tree. A machine-generated sentence with a deep nesting can exceed the limit, and Python raises RecursionError.7
This code raises RecursionError, on purpose.
class Num:
def __init__(self, value):
self.value = value
def evaluate(self):
return self.value
class Add:
def __init__(self, left, right):
self.left, self.right = left, right
def evaluate(self):
return self.left.evaluate() + self.right.evaluate()
tree = Num(0)
for _ in range(100_000): # 0 + 1 + 1 + ... as a left-deep tree
tree = Add(tree, Num(1))
print(tree.evaluate())
The fix keeps the work on an explicit stack in the heap. The walk pushes a node, and when the children of a node are done, it pops their values and joins them:
class Num:
def __init__(self, value):
self.value = value
class Add:
def __init__(self, left, right):
self.left, self.right = left, right
def evaluate(root):
values, work = [], [(root, False)]
while work:
node, children_done = work.pop()
if isinstance(node, Num):
values.append(node.value)
elif children_done:
right, left = values.pop(), values.pop()
values.append(left + right)
else:
work += [(node, True), (node.right, False), (node.left, False)]
return values.pop()
tree = Num(0)
for _ in range(100_000):
tree = Add(tree, Num(1))
print(evaluate(tree))
100000
The cost is clarity. The operation is no longer one method on each class. A program that accepts sentences from outside should also limit their length or depth before it evaluates them.
When not to use it
Do not invent a language when a data format is enough. A list of rules in JSON with fixed fields (a product, a minimum quantity, a percentage) needs no grammar and no tree.
Do not write an interpreter for a large grammar by hand. Design Patterns recommends tools such as parser generators for complex grammars.1 For a general-purpose scripting need, embed an existing language instead of growing a private one, one feature at a time.
Do not write your own interpreter for a language that already has one. Regular expressions, SQL and template languages come with a library. Use it.
Do not use eval of the host language as the interpreter of a language whose sentences come from users.4 The small interpreter on this page exists to avoid that.
Variants and related patterns
Composite. The abstract syntax tree is a composite. Design Patterns says so in the related patterns of Interpreter.1 Interpreter adds a grammar and an operation that gives a meaning to the tree. See Composite pattern.
Visitor. When the class form needs many operations, a visitor moves each operation into its own class, and the node classes get one accept method. Design Patterns suggests Visitor for this case, and Crafting Interpreters uses it for its tree-walking interpreter.12 In a language with sum types and exhaustive pattern matching, one function with a match does the same job with less code. See Visitor pattern and Sum types.
Flyweight. Terminal symbols, such as the variable x, can be shared. A sentence that names x ten times can use one Var("x") object.1 The objects of the Python example are frozen dataclasses, so sharing them is safe. See Flyweight pattern.
Iterator. An iterator can traverse the tree, for example to list every variable that a sentence uses.1 See Iterator pattern.
Compile to closures. A variant walks the tree once and returns a function for each node. Add returns lambda env: left(env) + right(env). The program then calls the function many times without the dispatch on node types. See Closure.
Known uses
- OpenJDK: Pattern.java at jdk-25+36 compiles a regular expression into a tree of node objects. Its comment says that each type of node "knows how to match its equivalent construct with the match() method".
Nodeis the AbstractExpression, and the regular expressions are the example that Design Patterns uses to motivate the pattern.111 - Go:
walkin text/template/exec.go at go1.23.0 interprets the parse tree of a template. It is the function form: oneswitchon the node type, with a case for actions,if,range, text and the other nodes.12
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Interpreter (Intent, Motivation, Applicability, Participants, Consequences, Implementation, Sample Code, Related Patterns)
- Robert Nystrom, Crafting Interpreters, Chapter 5, Representing Code, 5.3 Working with Trees; 5.3.1 The Expression Problem; 5.3.2 The Visitor pattern
- Philip Wadler, The Expression Problem, message to the java-genericity mailing list, 12 November 1998, first paragraph
- The Python Standard Library, Built-in Functions, Python 3.14, eval, Warning
- The Python Standard Library, ast, Abstract syntax trees, Python 3.14, ast.literal_eval
- The Python Standard Library, ast, Abstract syntax trees, Python 3.14, module introduction; ast.parse
- The Python Standard Library, Built-in Exceptions, Python 3.14, RecursionError
- JEP 441: Pattern Matching for switch, Summary; Exhaustiveness of switch expressions and statements
- TypeScript Handbook, Narrowing, Discriminated unions; Exhaustiveness checking
- The Rust Programming Language, 6.2 The match Control Flow Construct, Matches Are Exhaustive
- OpenJDK jdk-25+36 source, java/util/regex/Pattern.java, comment on the node classes and class Node, lines 3711 to 3748
- Go go1.23.0 source, src/text/template/exec.go, func (s *state) walk, lines 259 to 295
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag R6M6FX Edit this page History Report an error Markdown