Skip to content
Tutorials Center
My learning

Topics

Lesson 133 of 146 ยท Projects

Project: Expression Calculator

Build a calculator in Swift from scratch: a tokenizer, a recursive descent parser, an indirect enum syntax tree, an evaluator and typed errors. Complete program, runs in your browser.

Your first big Swift program should do something real, and few programs teach as much as a calculator that understands text. You type 2 + 3 * (4 - 1) and it answers 11. Behind that simple behavior sit the three ideas that every compiler, query language and configuration reader uses: tokenizing (cutting text into pieces), parsing (finding the structure in the pieces) and evaluating (computing a result from the structure).

In this project you build the whole thing in one file with nothing but the standard library and a little Foundation. You will use indirect enums for the syntax tree, typed throws for errors, pattern matching to walk the tree, and structs with mutating methods for the parser. Each step runs on its own, and the last step is the complete program, reading expressions from the Input box.

What we are building

The calculator will support:

  • numbers such as 42 and 3.14, and the operators + - * / ^
  • the usual precedence (* before +) and parentheses
  • unary minus (-4, 2 * -3) and right-associative powers (2 ^ 3 ^ 2 means 2 ^ (3 ^ 2))
  • the constants pi and e, your own variables (rate = 0.08), and the functions sqrt, abs, min, max, round
  • friendly errors with a clear message instead of a crash

The data flows through three stages. Keeping them separate is the central design decision, because each stage can be tested and changed alone:

TEXT
"2 + 3 * 4"  --tokenize-->  [2, +, 3, *, 4]  --parse-->  add(2, multiply(3, 4))  --evaluate-->  14

Step 1: the tokenizer

A token is the smallest meaningful piece of the input: a number, a name, an operator, a parenthesis. The tokenizer walks the characters once and groups them. Spaces separate tokens and are thrown away. An enum models the token kinds, and a second enum models what can go wrong, so that errors are values the compiler can check:

Swift Step 1: turning text into tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the function with the data in mind. It keeps an index i and looks at one character at a time. A digit or a dot starts a number: an inner loop runs to the end of the digits, and Double(literal) decides whether the text is a real number. That is how 1.2.3 is rejected, since Double("1.2.3") returns nil. A letter starts an identifier, which may continue with letters, digits and underscores. Everything else is a single-character symbol, and an unknown character throws with its position.

Two details are worth noting. First, the function is declared throws(CalcError), so the catch block receives a CalcError and not just any Error, and throw .invalidNumber(literal) can leave out the type name. Second, isDigit compares against the range "0"..."9" on purpose. Character.isNumber is true for characters like ยฒ and ูฃ as well, and Double("ยฒ") would then fail with a confusing result.

The line while j < chars.count, isDigit(chars[j]) || chars[j] == "." puts the bounds check first. In a while condition list, the comma stops at the first false item, so chars[j] is never evaluated out of range. A missing bounds check is the classic trap in hand-written tokenizers.

Step 2: the syntax tree and the evaluator

Tokens are still a flat list. The meaning of 2 + 3 * 4 lives in its tree: the multiplication happens first, so it sits deeper. An indirect enum models the tree: each case is one kind of expression and the recursive cases hold smaller expressions. This is the structure from the indirect enums lesson, grown up:

Swift Step 2: a syntax tree you can evaluate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The Operator enum has Character raw values, so a symbol and its case are one definition. The evaluator is a recursive switch: numbers return themselves, negate flips the sign of its inner value, and binary evaluates both sides first and then combines them. Division is the one operation that can fail, so it checks the divisor and throws the typed error. Because the error type is CalcError, the final catch needs no cast.

The compiler also protects the tree as it grows. Suppose you add function calls to Expr but forget to teach the evaluator about them:

Swift A new case the evaluator forgot (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: switch must be exhaustive and offers add missing case: '.call(_, _)'. This is the main reason to model syntax with enums: the moment the language grows, the compiler lists every function that needs attention, and nothing silently falls through.

Step 3: the parser

The parser turns the token list into the tree. The technique is called recursive descent, and it is easy to write by hand because the code mirrors a grammar. Write down the rules in plain words, loosest binding first:

TEXT
expression = term   { ("+" | "-") term }
term       = unary  { ("*" | "/") unary }
unary      = "-" unary | power
power      = primary [ "^" unary ]
primary    = number | name | name "(" [ expression { "," expression } ] ")" | "(" expression ")"

Each rule becomes one method. Operators that bind loosely (+) are handled in the methods that sit higher in the call chain, and operators that bind tightly (*, then ^) in methods that sit lower, so a deeper node is computed first. { ... } means "repeat", which becomes a while loop, and that loop is what makes 10 - 4 - 3 left-associative: (10 - 4) - 3. The power rule calls unary for its exponent, which makes it right-associative and also lets 2 ^ -1 work.

The parser is a struct that owns the tokens and a position, and its methods are mutating because they advance that position:

Swift Step 3: a recursive descent parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The description of each tree prints it fully parenthesized, which makes the structure visible. That is the best debugging view of a parser: 10 - 4 - 3 becomes ((10.0 - 4.0) - 3.0), proving left associativity; 2 ^ 3 ^ 2 becomes (2.0 ^ (3.0 ^ 2.0)); and -2 ^ 2 becomes (-(2.0 ^ 2.0)), which is the convention in mathematics (the answer is -4, not 4).

Three helper methods carry the machinery. peek looks at the next token without consuming it, advance consumes and returns it, and accept consumes it only if it matches. Using defer in advance lets the function return the current token and then move the position, in one tidy line. The last two lists show errors: an unclosed parenthesis reports the end of input, and 1 2 leaves a token over, which parse() catches by checking that nothing remains after the expression.

Parsing 1 2 would silently return 1 if parse() did not check for leftover tokens. That one if let extra = peek line is easy to forget and is a very common parser bug: the parser must consume the whole input, not just a valid prefix.

Step 4: the complete calculator

Now we join the stages and add what makes it feel like a calculator: variables, functions, one error type for the whole pipeline, number formatting and a read loop. The program below is complete. The Input box holds the lines it reads, and readLine() returns them one by one until the input ends. A line like x = 5 stores a variable, a line starting with ast shows the tree instead of evaluating it, and any other line is calculated.

Swift Step 4: the complete expression calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Study how the pieces connect. Parser.parse(_:) is the only entry point and does tokenizing and parsing in one call, with one error type so callers handle a single catch. The Calculator struct owns the variables, so the evaluator is a method on state. run(_:) is the seam between input and output: it takes a string and returns a string and never prints. That one decision makes the calculator trivial to test, and the main loop is only four lines.

Three small design choices deserve a closer look:

  • Number formatting uses String(format: "%.10g", value), which prints 11 for 11.0 and 0.3 for 0.1 + 0.2. Plain print(0.1 + 0.2) shows 0.30000000000000004, which is correct but unfriendly in a calculator. The format also keeps the display honest: ten significant digits, no more.
  • Typed throws means each function lists exactly the failure it can produce, so apply cannot accidentally throw a ParseError. If you later add a second error type, the compiler tells you where the two must meet.
  • ast is a debugging command: the tree for ast -(4 - x) ^ 2 shows (-((4 - x) ^ 2)), confirming that the power binds tighter than the minus sign in front of it.

Extending the calculator

The structure makes new features small. Here are the likely edits, each touching one stage:

  • A new function such as floor or log is one more case in apply. Nothing else changes.
  • Remainder % needs a new Token case and Operator case, a branch in the tokenizer, term() and evaluate. The compiler lists every switch that must change.
  • Comparisons and if mean a new tree case and a new precedence level above expression.
  • Better error positions mean storing an offset in each token, then putting it in the errors. The tokenizer already tracks i.
  • Tests: because run(_:) is a pure function of its input, a test is Calculator().run("2+3") == "5". See testing in Swift for how to run such checks.

Recursive descent recurses once per nested parenthesis or unary minus. A hostile input such as ten thousand opening parentheses can overflow the call stack. A real calculator exposed to untrusted text should reject inputs beyond a maximum nesting depth, which is a counter passed down through expression().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the tokenizer produce?

    Tokenizing only groups characters into tokens. Structure comes from the parser, and the value from the evaluator.
  2. 2. Why is 10 - 4 - 3 calculated as (10 - 4) - 3 by the parser?

    A while loop that replaces left with a new binary node each time builds a left-leaning tree, which gives left associativity.
  3. 3. Why does power() call unary() for the exponent instead of primary()?

    Recursing into the same level on the right-hand side makes ^ right-associative, and routing through unary() accepts a leading minus on the exponent.
  4. 4. What is the benefit of declaring throws(CalcError)?

    Typed throws names the exact error type, so catch blocks know the type without casting and the compiler rejects throwing anything else.
  5. 5. What happens if parse() forgets to check for leftover tokens?

    Without the final check a parser accepts any valid prefix of the input and ignores the rest, hiding mistakes.

Summary

  • A calculator is a pipeline: tokenize the text, parse the tokens into a tree, evaluate the tree. Each stage has its own function and its own tests.
  • An indirect enum models the syntax tree, and exhaustive switch statements make the compiler list every function you must update when the language grows.
  • Recursive descent maps each grammar rule to one method. Loops give left associativity, recursion on the right gives right associativity, and the call depth gives precedence.
  • Typed throws, throws(CalcError), keeps each stage honest about the failures it can produce.
  • Keep the core free of printing: run(_:) returns a string, so the logic can be tested without capturing output.
  • Always check that the parser consumed the entire input, and consider a nesting limit for untrusted text.

Next: Project: Command-Line To-Do Manager