Interpreters and errors
A tokenizer that reports where it failed, a stack calculator with typed errors, a parser for boolean formulas, a configuration reader that collects every problem, and a tiny Forth.
- Lessons
- Writing an interpreter · Error handling
This homework uses Lessons 20 and 21. Put everything in hw09.swift with the
assert lines, and run it. Every function that can fail here throws a
specific error type; the tests check the error as well as the value, since a
wrong error message is a bug too.
Q1: Where did it go wrong?
Write tokenize(_:) for arithmetic like 12 + (3*4). Tokens are whole
numbers, the operators + - * /, and parentheses; spaces separate tokens but
are not tokens. Any other character throws .unexpected(character, at: index), where index counts characters from 0.
enum Token: Equatable {
case number(Int)
case op(Character)
case open, close
}
enum LexError: Error, Equatable {
case unexpected(Character, at: Int)
}
Show solution
enum Token: Equatable {
case number(Int)
case op(Character)
case open, close
}
enum LexError: Error, Equatable {
case unexpected(Character, at: Int)
}
func tokenize(_ text: String) throws(LexError) -> [Token] {
var tokens: [Token] = []
var digits = ""
for (index, character) in text.enumerated() {
if character.isNumber {
digits.append(character)
continue
}
if let n = Int(digits) {
tokens.append(.number(n))
digits = ""
}
switch character {
case "+", "-", "*", "/": tokens.append(.op(character))
case "(": tokens.append(.open)
case ")": tokens.append(.close)
case " ": break
default: throw .unexpected(character, at: index)
}
}
if let n = Int(digits) {
tokens.append(.number(n))
}
return tokens
}
assert(try! tokenize("12 + (3*4)") == [.number(12), .op("+"), .open, .number(3), .op("*"), .number(4), .close])
assert(try! tokenize("") == [])
do {
_ = try tokenize("2 + x")
assert(false, "should have thrown")
} catch {
assert(error == .unexpected("x", at: 4))
}enumerated() pairs each character with its position, so the error can say
exactly where the problem is. A message like “unexpected x at 4” is the
difference between a user fixing their input in seconds and guessing.
Q2: A stack calculator
In reverse Polish notation, operators come after their operands:
3 4 + 2 * means (3 + 4) × 2. It needs no parentheses, and it is evaluated
with a stack: push each number; for an operator, pop two numbers, apply it,
and push the result. At the end exactly one number must remain.
Write evaluateRPN(_:) with typed throws, for words separated by spaces.
enum RPNError: Error, Equatable {
case notEnoughOperands(String) // the operator that found too few
case unknownWord(String)
case divisionByZero
case leftover(Int) // how many numbers remained, if not 1
}
Show solution
enum RPNError: Error, Equatable {
case notEnoughOperands(String)
case unknownWord(String)
case divisionByZero
case leftover(Int)
}
func evaluateRPN(_ text: String) throws(RPNError) -> Int {
var stack: [Int] = []
for word in text.split(separator: " ").map(String.init) {
if let n = Int(word) {
stack.append(n)
continue
}
guard ["+", "-", "*", "/"].contains(word) else {
throw .unknownWord(word)
}
guard stack.count >= 2 else {
throw .notEnoughOperands(word)
}
let b = stack.removeLast()
let a = stack.removeLast()
switch word {
case "+": stack.append(a + b)
case "-": stack.append(a - b)
case "*": stack.append(a * b)
default:
guard b != 0 else {
throw .divisionByZero
}
stack.append(a / b)
}
}
guard stack.count == 1 else {
throw .leftover(stack.count)
}
return stack[0]
}
func result(_ text: String) -> Result<Int, RPNError> {
Result { () throws(RPNError) -> Int in try evaluateRPN(text) }
}
assert(result("3 4 + 2 *") == .success(14))
assert(result("5 1 2 + 4 * + 3 -") == .success(14))
assert(result("10 3 -") == .success(7))
assert(result("1 +") == .failure(.notEnoughOperands("+")))
assert(result("2 x") == .failure(.unknownWord("x")))
assert(result("1 0 /") == .failure(.divisionByZero))
assert(result("1 2") == .failure(.leftover(2)))
assert(result("") == .failure(.leftover(0)))Note which operand is which: the first number popped is the right
operand, so 10 3 - is 10 − 3. Wrapping each evaluation in a Result
makes the tests one line each: Result is Equatable when its value and
error types are.
Q3: Boolean formulas
Write evaluateFormula(_:), which evaluates formulas made of T, F, !
(not), & (and), | (or), and parentheses, with ! binding tightest and
& tighter than |. Spaces may appear anywhere. Use recursive descent, as
in Lesson 20’s last lab problem, and throw FormulaError.invalid(at:) with
the position of the first character that cannot be understood, or the length
of the formula if it ends too early.
formula = conjunction { "|" conjunction }
conjunction = negation { "&" negation }
negation = "!" negation | "T" | "F" | "(" formula ")"
Show solution
enum FormulaError: Error, Equatable {
case invalid(at: Int)
}
func evaluateFormula(_ text: String) throws(FormulaError) -> Bool {
let characters = Array(text.filter { $0 != " " })
var position = 0
func peek() -> Character? {
position < characters.count ? characters[position] : nil
}
func formula() throws(FormulaError) -> Bool {
var value = try conjunction()
while peek() == "|" {
position += 1
let right = try conjunction()
value = value || right
}
return value
}
func conjunction() throws(FormulaError) -> Bool {
var value = try negation()
while peek() == "&" {
position += 1
let right = try negation()
value = value && right
}
return value
}
func negation() throws(FormulaError) -> Bool {
guard let c = peek() else {
throw .invalid(at: position)
}
position += 1
switch c {
case "!":
return try !negation()
case "T":
return true
case "F":
return false
case "(":
let value = try formula()
guard peek() == ")" else {
throw .invalid(at: position)
}
position += 1
return value
default:
throw .invalid(at: position - 1)
}
}
let value = try formula()
guard position == characters.count else {
throw .invalid(at: position)
}
return value
}
assert(try! evaluateFormula("T & (F | !T)") == false)
assert(try! evaluateFormula("F | T & T") == true) // & before |
assert(try! evaluateFormula("!!T") == true)
assert(try! evaluateFormula("!(F | F) & T") == true)
assert((try? evaluateFormula("T & ")) == nil)
do {
_ = try evaluateFormula("T & X")
} catch {
assert(error == .invalid(at: 2)) // positions ignore spaces: "T&X"
}Each function evaluates while it parses, so there is no tree: for a
language this small, the parser is the interpreter. Note that
value || right is computed after right has been parsed, not with ||’s
short circuit applied to the parse itself; otherwise T | X would skip over
the X without noticing it is invalid.
Q4: Every problem in a file
A configuration file has one key = value setting per line; blank lines and
lines starting with # are ignored. Write readConfig(_:), which returns
the settings found and a list of problems, each with its line number
(counting from 1): a line without =, an empty key, or a key set twice. Use a
function that returns a Result for each line.
enum ConfigProblem: Error, Equatable {
case missingEquals(line: Int)
case emptyKey(line: Int)
case duplicate(String, line: Int)
}
Show solution
enum ConfigProblem: Error, Equatable {
case missingEquals(line: Int)
case emptyKey(line: Int)
case duplicate(String, line: Int)
}
func trimmed(_ s: Substring) -> String {
String(s.drop { $0 == " " }.reversed().drop { $0 == " " }.reversed())
}
func parseLine(_ line: String, number: Int) -> Result<(String, String), ConfigProblem>? {
let text = trimmed(line[...])
if text.isEmpty || text.hasPrefix("#") {
return nil
}
guard let equals = text.firstIndex(of: "=") else {
return .failure(.missingEquals(line: number))
}
let key = trimmed(text[..<equals])
let value = trimmed(text[text.index(after: equals)...])
guard !key.isEmpty else {
return .failure(.emptyKey(line: number))
}
return .success((key, value))
}
func readConfig(_ text: String) -> (settings: [String: String], problems: [ConfigProblem]) {
var settings: [String: String] = [:]
var problems: [ConfigProblem] = []
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
for (index, line) in lines.enumerated() {
switch parseLine(String(line), number: index + 1) {
case nil:
continue
case .failure(let problem):
problems.append(problem)
case .success(let (key, value)):
if settings[key] != nil {
problems.append(.duplicate(key, line: index + 1))
} else {
settings[key] = value
}
}
}
return (settings, problems)
}
let file = """
# display
theme = dark
font size = 14
width
= 80
theme = light
"""
let config = readConfig(file)
assert(config.settings == ["theme": "dark", "font size": "14"])
assert(config.problems == [.missingEquals(line: 5), .emptyKey(line: 6), .duplicate("theme", line: 7)])parseLine returns an optional Result: nil for lines with nothing in
them, and otherwise success or failure. The switch in readConfig matches
all three with patterns, as Lesson 19 showed for optionals. The duplicate
check needs all the lines before it, so it belongs in readConfig, not in
parseLine, which sees one line at a time.
Q5 (optional): A tiny Forth
Forth is a stack language, like Q2’s calculator, in which programs can define
new words. Write runForth(_:), which returns the stack at the end. Support
numbers; +, -, *; dup (copy the top), drop (remove the top),
swap (exchange the top two); and definitions: : name body… ; defines
name so that using it runs the body. A word used before it is defined, or
an operation on too small a stack, throws.
Show solution
enum ForthError: Error, Equatable {
case unknownWord(String)
case stackUnderflow(String)
case unfinishedDefinition
}
func runForth(_ program: String) throws(ForthError) -> [Int] {
var stack: [Int] = []
var definitions: [String: [String]] = [:]
func pop(_ word: String, _ count: Int) throws(ForthError) -> [Int] {
guard stack.count >= count else {
throw .stackUnderflow(word)
}
let top = Array(stack.suffix(count))
stack.removeLast(count)
return top
}
func execute(_ words: [String]) throws(ForthError) {
var index = 0
while index < words.count {
let word = words[index]
index += 1
if let n = Int(word) {
stack.append(n)
} else if word == ":" {
guard let end = words[index...].firstIndex(of: ";"), end > index else {
throw .unfinishedDefinition
}
definitions[words[index]] = Array(words[(index + 1)..<end])
index = end + 1
} else if let body = definitions[word] {
try execute(body)
} else {
switch word {
case "+": let v = try pop(word, 2); stack.append(v[0] + v[1])
case "-": let v = try pop(word, 2); stack.append(v[0] - v[1])
case "*": let v = try pop(word, 2); stack.append(v[0] * v[1])
case "dup": let v = try pop(word, 1); stack += [v[0], v[0]]
case "drop": _ = try pop(word, 1)
case "swap": let v = try pop(word, 2); stack += [v[1], v[0]]
default: throw .unknownWord(word)
}
}
}
}
try execute(program.split(separator: " ").map(String.init))
return stack
}
assert(try! runForth("1 2 3 + *") == [5])
assert(try! runForth(": square dup * ; 7 square") == [49])
assert(try! runForth(": square dup * ; : fourth square square ; 3 fourth") == [81])
assert(try! runForth("1 2 swap drop") == [2])
assert((try? runForth("1 +")) == nil)
assert((try? runForth("foo")) == nil)
assert((try? runForth(": broken 1 2")) == nil)Definitions are stored as lists of words, and running a defined word runs
its body with the same execute function, recursively. The dictionary is an
environment with a single frame, and a definition may use words defined
before it, as fourth uses square. Checking definitions[word] before the
built-in words means a program could even redefine dup.