Writing an interpreter
Turning text into tokens, tokens into an expression tree, and trees into values: a calculator language built from a tokenizer, a recursive parser, and the eval–apply cycle.
- CS61A
- Interpreters · Composing Programs 3.1–3.5
- Swift book
- Enumerations · Error Handling
Every program in this tutorial has been run by another program: the Swift compiler read your text, worked out what it meant, and produced something the machine could execute. An interpreter is a program that runs programs directly. Writing one is less mysterious than it sounds, and it is the best way to understand what every language you use is actually doing.
This lesson builds an interpreter for Calculator, the small language CS61A uses for the same purpose. Its programs look like this:
(+ 1 2) ; 3
(* 2 (+ 3 4)) ; 14
(- 10 1 2) ; 7
(/ (* 6 5) (+ 1 2)) ; 10
Every expression is either a number or a call: parentheses around an operator and its operands. The operator comes first, and there can be any number of operands. This prefix notation, borrowed from Scheme, makes the structure of the program visible in its text: every pair of parentheses is one node of a tree.
Three stages
An interpreter works in stages, each turning one representation into the next:
| Stage | Input | Output |
|---|---|---|
| Tokenize (lexical analysis) | the text (+ 1 (* 2 3)) |
the tokens (, +, 1, (, *, 2, 3, ), ) |
| Parse (syntactic analysis) | the tokens | an expression tree: a call to + with 1 and a call to * |
| Evaluate | the tree | the value 7 |
Each stage has one job, and each can report its own kind of mistake: a character that cannot start any token, parentheses that do not match, or an operator that does not exist.
Tokenizing
A token is the smallest meaningful piece of the text. Calculator has four kinds, which is exactly what an enum is for:
enum Token: Equatable {
case open
case close
case number(Int)
case symbol(String)
}
func tokenize(_ text: String) -> [Token] {
var tokens: [Token] = []
var current = ""
func finishWord() {
if current.isEmpty {
return
}
tokens.append(Int(current).map(Token.number) ?? .symbol(current))
current = ""
}
for character in text {
switch character {
case "(":
finishWord()
tokens.append(.open)
case ")":
finishWord()
tokens.append(.close)
case " ", "\n", "\t":
finishWord()
default:
current.append(character)
}
}
finishWord()
return tokens
}
print(tokenize("(+ 1 (* 2 3))").count) // 9
print(tokenize("(- -5 2)")[2]) // number(-5)
Characters accumulate in current until a parenthesis or a space ends the
word. finishWord then decides what the word was: Int(current) succeeds
for numbers (including negative ones, so -5 is a number while - alone
is a symbol), and everything else is a symbol. Token.number is used as a
function here, as in Lesson 11: an enum case with an associated value is a
function that makes the enum.
The nested finishWord changes tokens and current, variables of the
enclosing function. Lesson 5’s closures are what make this work.
What would Swift print?
enum Token: Equatable {
case open, close
case word(String)
}
func tokenize(_ text: String) -> [Token] {
var tokens: [Token] = []
var current = ""
for c in text {
if c == "(" || c == ")" || c == " " {
if !current.isEmpty {
tokens.append(.word(current))
current = ""
}
if c == "(" { tokens.append(.open) }
if c == ")" { tokens.append(.close) }
} else {
current.append(c)
}
}
return tokens
}
print(tokenize("(max 10 200)").count, tokenize("(f (g))").count)Show answer and explanation
Answer5 6
(max 10 200) has two parentheses and three words: 5 tokens. (f (g)) has
four parentheses and two words: 6. Spaces separate tokens but are not tokens
themselves.
Parsing
Tokens are still flat. The parser finds the tree in them. Calculator’s grammar is recursive, so the parser is too:
- A number token is a complete expression.
- An open parenthesis starts a call. The next token is the operator; then come operands, each of which is an expression, until the matching close parenthesis.
indirect enum Expr {
case number(Int)
case call(String, [Expr])
}
The parser has to report mistakes, like a missing ). Returning an optional
would lose the reason, so it throws an error instead. Here is just
enough about errors to read the code; Lesson 21 covers them properly:
- Any type that conforms to
Errorcan be thrown. - A function that can fail is marked
throws, andthrowleaves it immediately with an error, the wayreturnleaves with a value. - Every call to a throwing function is marked
try, and the error keeps travelling up to the caller until ado–catchhandles it.
struct CalcError: Error {
let message: String
init(_ message: String) { self.message = message }
}
func parse(_ tokens: [Token]) throws -> Expr {
var position = 0
func expression() throws -> Expr {
guard position < tokens.count else {
throw CalcError("unexpected end of input")
}
let token = tokens[position]
position += 1
switch token {
case .number(let n):
return .number(n)
case .symbol(let name):
throw CalcError("unexpected \(name)")
case .close:
throw CalcError("unexpected )")
case .open:
guard position < tokens.count, case .symbol(let op) = tokens[position] else {
throw CalcError("expected an operator after (")
}
position += 1
var operands: [Expr] = []
while position < tokens.count, tokens[position] != .close {
operands.append(try expression())
}
guard position < tokens.count else {
throw CalcError("missing )")
}
position += 1 // the )
return .call(op, operands)
}
}
let result = try expression()
guard position == tokens.count else {
throw CalcError("extra input after the expression")
}
return result
}
position is the parser’s place in the token array, shared by every call of
the nested expression function. Each call consumes exactly the tokens of
one expression and leaves position just after them, so the while loop in
the .open case can call it once per operand, however deeply nested each
operand is.
This technique is called recursive descent: one function per kind of
thing in the grammar, calling each other exactly as the grammar refers to
itself. The guard case .symbol(let op) = … is Lesson 19’s pattern matching
outside a switch.
Evaluating
Evaluation is two mutually recursive functions, the pair at the heart of every interpreter:
- eval takes an expression and returns its value. A number is its own
value. A call evaluates its operands, then asks
applyto combine them. - apply takes an operator and the operands’ values, and computes the result.
func evaluate(_ expr: Expr) throws -> Int {
switch expr {
case .number(let n):
return n
case .call(let op, let operands):
return try apply(op, operands.map(evaluate))
}
}
func apply(_ op: String, _ args: [Int]) throws -> Int {
switch op {
case "+":
return args.reduce(0, +)
case "*":
return args.reduce(1, *)
case "-":
guard let first = args.first else {
throw CalcError("- needs at least one operand")
}
return args.count == 1 ? -first : args.dropFirst().reduce(first, -)
case "/":
guard let first = args.first, args.count > 1 else {
throw CalcError("/ needs at least two operands")
}
guard !args.dropFirst().contains(0) else {
throw CalcError("division by zero")
}
return args.dropFirst().reduce(first, /)
default:
throw CalcError("unknown operator \(op)")
}
}
operands.map(evaluate) evaluates each operand with the same function, which
is where the recursion happens. map passes errors through: if any operand
throws, map throws the same error, and so the try in front of the whole
line covers both calls.
apply also shows the language’s design choices. (+) is 0 and (*) is 1,
the values that leave a sum or product unchanged. (- 5) negates. / is
integer division, and dividing by zero is a Calculator error instead of a
crash of the whole interpreter.
What would Swift print?
indirect enum Expr {
case number(Int)
case call(String, [Expr])
}
var applied = 0
func evaluate(_ e: Expr) -> Int {
switch e {
case .number(let n):
return n
case .call(let op, let operands):
let args = operands.map(evaluate)
applied += 1
return op == "+" ? args.reduce(0, +) : args.reduce(1, *)
}
}
let e = Expr.call("*", [.call("+", [.number(1), .number(2)]), .call("+", [.number(3)]), .number(4)])
print(evaluate(e), applied)Show answer and explanation
Answer36 3
(* (+ 1 2) (+ 3) 4) is 3 × 3 × 4 = 36. apply runs once for each call
node: two additions and one multiplication. Operands are always evaluated
before the call that uses them, so the additions run first.
The whole calculator
Here are the stages together, with a run function that goes from text to
a printed result, and turns any error into a message:
enum Token: Equatable {
case open, close
case number(Int)
case symbol(String)
}
indirect enum Expr {
case number(Int)
case call(String, [Expr])
}
struct CalcError: Error {
let message: String
init(_ message: String) { self.message = message }
}
func tokenize(_ text: String) -> [Token] {
var tokens: [Token] = []
var current = ""
func finishWord() {
if !current.isEmpty {
tokens.append(Int(current).map(Token.number) ?? .symbol(current))
current = ""
}
}
for character in text {
switch character {
case "(": finishWord(); tokens.append(.open)
case ")": finishWord(); tokens.append(.close)
case " ", "\n", "\t": finishWord()
default: current.append(character)
}
}
finishWord()
return tokens
}
func parse(_ tokens: [Token]) throws -> Expr {
var position = 0
func expression() throws -> Expr {
guard position < tokens.count else { throw CalcError("unexpected end of input") }
let token = tokens[position]
position += 1
switch token {
case .number(let n):
return .number(n)
case .symbol(let name):
throw CalcError("unexpected \(name)")
case .close:
throw CalcError("unexpected )")
case .open:
guard position < tokens.count, case .symbol(let op) = tokens[position] else {
throw CalcError("expected an operator after (")
}
position += 1
var operands: [Expr] = []
while position < tokens.count, tokens[position] != .close {
operands.append(try expression())
}
guard position < tokens.count else { throw CalcError("missing )") }
position += 1
return .call(op, operands)
}
}
let result = try expression()
guard position == tokens.count else { throw CalcError("extra input after the expression") }
return result
}
func evaluate(_ expr: Expr) throws -> Int {
switch expr {
case .number(let n):
return n
case .call(let op, let operands):
return try apply(op, operands.map(evaluate))
}
}
func apply(_ op: String, _ args: [Int]) throws -> Int {
switch op {
case "+":
return args.reduce(0, +)
case "*":
return args.reduce(1, *)
case "-":
guard let first = args.first else { throw CalcError("- needs at least one operand") }
return args.count == 1 ? -first : args.dropFirst().reduce(first, -)
case "/":
guard let first = args.first, args.count > 1 else { throw CalcError("/ needs at least two operands") }
guard !args.dropFirst().contains(0) else { throw CalcError("division by zero") }
return args.dropFirst().reduce(first, /)
default:
throw CalcError("unknown operator \(op)")
}
}
func run(_ text: String) -> String {
do {
return String(try evaluate(parse(tokenize(text))))
} catch let error as CalcError {
return "Error: \(error.message)"
} catch {
return "Error: \(error)"
}
}
for line in ["(+ 1 (* 2 3))", "(- 10 1 2)", "(/ (* 6 5) (+ 1 2))", "(+ 1 (* 2 3)", "(/ 1 0)", "(^ 2 3)"] {
print(line, "→", run(line))
}
// (+ 1 (* 2 3)) → 7
// (- 10 1 2) → 7
// (/ (* 6 5) (+ 1 2)) → 10
// (+ 1 (* 2 3) → Error: missing )
// (/ 1 0) → Error: division by zero
// (^ 2 3) → Error: unknown operator ^
catch let error as CalcError handles the errors we threw; the second
catch handles anything else, since Swift cannot know which errors a
throws function might produce. The three kinds of mistake show up in the
three stages: the missing ) in the parser, the division and the unknown
operator in apply.
The read–eval–print loop
Swift’s own swift repl, Python’s >>>, and the Scheme prompt in CS61A are
all the same loop: read a line, evaluate it, print the result,
repeat. With run, Calculator’s REPL is two lines:
while let line = readLine() {
print(run(line))
}
readLine() returns nil at the end of input (Control-D in a terminal),
which ends the loop.
Special forms and environments
Calculator evaluates every operand of every call. Real languages cannot
always do that. Consider an if expression:
(if (= n 0) 1 (/ 100 n))
If if were an ordinary operator, both branches would be evaluated before
apply ran, and (/ 100 n) would fail when n is 0, which is exactly the
case the if was guarding against. So if is a special form: evaluate
recognizes it and evaluates only the branch it needs. and and or are
special forms for the same reason: they stop as soon as the answer is known,
like Swift’s && and ||.
Names need one more piece. When a language lets you write
(define x 5)
(* x x)
the interpreter needs somewhere to remember that x is 5. That is an
environment, and Lesson 5’s environment diagrams are its blueprint: a
frame maps names to values, and has a parent frame to look in when a name is
not found. Calling a user-defined function creates a new frame whose parent
is the frame where the function was defined, which is exactly the rule
that made closures work in Lesson 5.
final class Frame {
var bindings: [String: Int] = [:]
let parent: Frame?
init(parent: Frame?) {
self.parent = parent
}
func lookup(_ name: String) -> Int? {
bindings[name] ?? parent?.lookup(name)
}
}
let global = Frame(parent: nil)
global.bindings["x"] = 5
let local = Frame(parent: global)
local.bindings["y"] = 2
print(local.lookup("x") ?? 0, local.lookup("y") ?? 0, global.lookup("y") == nil) // 5 2 true
Frame is a class because frames are shared: many closures can point at
the same frame, and a define in it must be visible to all of them. That is
the reference semantics of Lesson 14, used for exactly the reason it exists.
Lab 19: Interpreters
Q0: What would Swift print?
What would Swift print?
indirect enum Expr {
case number(Int)
case call(String, [Expr])
}
func depth(_ e: Expr) -> Int {
switch e {
case .number: 0
case .call(_, let operands): 1 + (operands.map(depth).max() ?? 0)
}
}
print(depth(.call("+", [.number(1), .call("*", [.call("-", [.number(2)])])])))Show answer and explanation
Answer3
The - call is inside the * call, which is inside the + call: three
levels of calls. Numbers add nothing, and ?? 0 covers a call with no
operands.
What would Swift print?
var log: [String] = []
func value(_ n: Int) -> Int {
log.append("eval \(n)")
return n
}
func apply(_ args: [Int]) -> Int {
log.append("apply")
return args.reduce(0, +)
}
_ = apply([value(1), apply([value(2), value(3)])])
print(log.joined(separator: ", "))Show answer and explanation
Answereval 1, eval 2, eval 3, apply, apply
Operands are evaluated left to right, and an inner call’s apply finishes
before the outer apply can start, because the outer call needs its value.
Q1: More operators
Add three operators to apply: max and min, which need at least one
operand, and abs, which needs exactly one. Report a CalcError otherwise.
Show solution
struct CalcError: Error {
let message: String
init(_ message: String) { self.message = message }
}
func apply(_ op: String, _ args: [Int]) throws -> Int {
switch op {
case "+":
return args.reduce(0, +)
case "*":
return args.reduce(1, *)
case "max", "min":
guard let best = op == "max" ? args.max() : args.min() else {
throw CalcError("\(op) needs at least one operand")
}
return best
case "abs":
guard args.count == 1 else {
throw CalcError("abs needs exactly one operand")
}
return abs(args[0])
default:
throw CalcError("unknown operator \(op)")
}
}
assert((try? apply("max", [3, 9, 2])) == 9)
assert((try? apply("min", [3, 9, 2])) == 2)
assert((try? apply("abs", [-4])) == 4)
assert((try? apply("abs", [1, 2])) == nil)
assert((try? apply("max", [])) == nil)args.max() is already optional, nil for an empty array, so the guard
turns “no operands” into an error in one step. try? in the tests turns an
error into nil, another tool from Lesson 21.
Q2: Back to text
Write show(_:), which turns an Expr back into Calculator source code.
Parsing the result should give the same tree.
Show solution
indirect enum Expr {
case number(Int)
case call(String, [Expr])
}
func show(_ expr: Expr) -> String {
switch expr {
case .number(let n):
return "\(n)"
case .call(let op, let operands):
return "(" + ([op] + operands.map(show)).joined(separator: " ") + ")"
}
}
assert(show(.call("+", [.number(1), .call("*", [.number(2), .number(3)])])) == "(+ 1 (* 2 3))")
assert(show(.call("+", [])) == "(+)")
assert(show(.number(-7)) == "-7")Putting the operator at the front of the list of parts makes the spacing come out right even for a call with no operands.
Q3: A special form
Add an if expression to this smaller language, where 0 means false and
any other number means true. Evaluate only the branch that is needed, and
add < and =, which return 1 or 0. Check that (if 0 (/ 1 0) 7) is 7
rather than an error.
indirect enum Expr {
case number(Int)
case call(String, [Expr])
case ifThen(Expr, Expr, Expr)
}
Show solution
indirect enum Expr {
case number(Int)
case call(String, [Expr])
case ifThen(Expr, Expr, Expr)
}
struct CalcError: Error {
let message: String
}
func evaluate(_ expr: Expr) throws -> Int {
switch expr {
case .number(let n):
return n
case .ifThen(let condition, let then, let otherwise):
return try evaluate(condition) != 0 ? evaluate(then) : evaluate(otherwise)
case .call(let op, let operands):
let args = try operands.map(evaluate)
switch (op, args.count) {
case ("+", _): return args.reduce(0, +)
case ("<", 2): return args[0] < args[1] ? 1 : 0
case ("=", 2): return args[0] == args[1] ? 1 : 0
case ("/", 2) where args[1] != 0: return args[0] / args[1]
default: throw CalcError(message: "cannot apply \(op) to \(args)")
}
}
}
assert((try? evaluate(.ifThen(.number(0), .call("/", [.number(1), .number(0)]), .number(7)))) == 7)
assert((try? evaluate(.ifThen(.call("<", [.number(1), .number(2)]), .number(10), .number(20)))) == 10)
assert((try? evaluate(.call("/", [.number(1), .number(0)]))) == nil)The .ifThen case is handled before anything evaluates its parts, and
then evaluates only two of its three. That is the whole difference between
a special form and a call. Matching on (op, args.count) checks the
operator and the number of operands in one pattern.
Q4: Names in scope
Add names and a let form, (let x 3 (* x x)), which evaluates 3, binds
it to x, and evaluates the body with that binding. Pass the bindings as a
dictionary argument, so an inner let can shadow an outer one without
changing it. An unknown name is an error.
indirect enum Expr {
case number(Int)
case name(String)
case call(String, [Expr])
case bind(String, Expr, body: Expr)
}
Show solution
indirect enum Expr {
case number(Int)
case name(String)
case call(String, [Expr])
case bind(String, Expr, body: Expr)
}
struct CalcError: Error {
let message: String
}
func evaluate(_ expr: Expr, _ env: [String: Int] = [:]) throws -> Int {
switch expr {
case .number(let n):
return n
case .name(let name):
guard let value = env[name] else {
throw CalcError(message: "unknown name \(name)")
}
return value
case .bind(let name, let valueExpr, let body):
var inner = env
inner[name] = try evaluate(valueExpr, env)
return try evaluate(body, inner)
case .call(let op, let operands):
let args = try operands.map { try evaluate($0, env) }
return op == "+" ? args.reduce(0, +) : args.reduce(1, *)
}
}
// (let x 3 (* x x))
assert((try? evaluate(.bind("x", .number(3), body: .call("*", [.name("x"), .name("x")])))) == 9)
// (let x 1 (+ (let x 10 x) x)): the inner x does not change the outer one
let shadow = Expr.bind("x", .number(1), body: .call("+", [.bind("x", .number(10), body: .name("x")), .name("x")]))
assert((try? evaluate(shadow)) == 11)
assert((try? evaluate(.name("y"))) == nil)var inner = env copies the dictionary, so the binding exists only while
evaluating the body. This is a value-semantics environment: simple and
correct for let, but not enough for define inside functions, which is
why Scheme needs the shared Frame objects above.
Q5 (optional): Infix arithmetic
Write calculate(_:), which evaluates ordinary arithmetic like
2 + 3 * (4 - 1), with * and / binding tighter than + and -, all
operators associating to the left, and parentheses. Numbers are whole and
non-negative, and spaces may appear anywhere. Use recursive descent with
one function per level of the grammar:
expression = term { ("+" | "-") term }
term = factor { ("*" | "/") factor }
factor = number | "(" expression ")"
Show solution
func calculate(_ text: String) -> Int? {
let characters = Array(text.filter { $0 != " " })
var position = 0
func peek() -> Character? {
position < characters.count ? characters[position] : nil
}
func expression() -> Int? {
guard var value = term() else { return nil }
while let op = peek(), op == "+" || op == "-" {
position += 1
guard let right = term() else { return nil }
value = op == "+" ? value + right : value - right
}
return value
}
func term() -> Int? {
guard var value = factor() else { return nil }
while let op = peek(), op == "*" || op == "/" {
position += 1
guard let right = factor(), op == "*" || right != 0 else { return nil }
value = op == "*" ? value * right : value / right
}
return value
}
func factor() -> Int? {
if peek() == "(" {
position += 1
guard let value = expression(), peek() == ")" else { return nil }
position += 1
return value
}
var digits = ""
while let c = peek(), c.isNumber {
digits.append(c)
position += 1
}
return Int(digits)
}
guard let result = expression(), position == characters.count else { return nil }
return result
}
assert(calculate("2 + 3 * (4 - 1)") == 11)
assert(calculate("10 - 4 - 3") == 3) // left to right: (10 - 4) - 3
assert(calculate("2 * (3 + 4) * 5") == 70)
assert(calculate("(1 + 2") == nil)
assert(calculate("8 / (4 - 4)") == nil)Precedence comes from the structure: expression only ever sees whole
terms, so every * and / has been applied before any + or -. The
while loops, instead of recursion on the right, are what make
10 - 4 - 3 associate to the left. Int("") is nil, so a missing number
is reported without any extra check.
What’s next
The calculator reports its mistakes by throwing errors, and so far we have
used them without looking closely. Next lesson: errors, Result, and what a
function should do when it cannot do its job.