Designing an Expression Evaluator
Difficulty: Advanced Patterns: Interpreter, Visitor, Composite Asked at: Google, Amazon, Databricks, Confluent
Take a string a user typed – 2 + 3 * 4, max(2, 3) + sqrt(16), rate * principal ^ years – and return a number. It sounds like a parsing exercise, and the parser is the part most candidates spend the hour on. The parser is not where the design is decided. What separates a good answer here is three things, and only the first of them is about parsing at all.
The first is that precedence and associativity are structure, not a lookup table. Everybody knows 2 + 3 * 4 is 14 and not 20. Far fewer can say where that fact should live in the code, and the common answer – a Map from operator to priority, consulted by one big loop – is the answer that goes stale, because the map and the loop that reads it can disagree and nothing fails loudly when they do. There is a design where the precedence cannot drift, because it is not written down anywhere: it is the order in which the parsing methods call each other. Associativity is the part that actually catches people out. 1 - 2 - 3 is -4 and 2 ^ 3 ^ 2 is 512, and if you get either direction backwards you get 2 and 64 instead, from code that looks completely reasonable.
The second is that the tree has to outlive the evaluation. It is tempting to collect the answer as you parse – see a number, push it, see an operator, pop two and combine – and that works, exactly once, for exactly one question. The moment anyone asks a second question about the same expression you are stuck, because you threw away the only thing that could answer it. Print this formula back with the redundant brackets removed. Tell me which variables it reads so I know when to recompute it. Simplify it. Differentiate it. Type-check it before it runs. Compile it. Those are all operations over structure, and a design that reduced the structure to a double while parsing cannot do any of them. So you keep the tree, and then the interesting question becomes how to add the fifth operation without editing the node classes a fourth time.
The third is that the input is hostile and the string is tiny. ((((((...)))))) is a few hundred characters that will exhaust the parser’s own call stack. 9^9^9 is five characters that asks for a number with three hundred and seventy million digits. 1/0 and an unbound x are not crashes but something worse: on IEEE doubles they quietly become Infinity and NaN, and a NaN propagates through every later arithmetic step without complaint until somebody reads a blank cell and trusts it. None of those are exotic attacks. They are what a formula bar receives on an ordinary Tuesday.
💡 Tokenizer, also called a lexer = the stage that turns characters into labelled chunks, so the parser sees NUMBER, PLUS, NUMBER instead of '2', '+', '3'. It exists so that two separate concerns – “is 12.5 one number or three characters” and “does multiplication bind tighter than addition” – never appear in the same method.
💡 AST, short for abstract syntax tree = the expression as a tree of small node objects, with the syntax thrown away. 2 + 3 * 4 becomes a plus node holding a 2 and a multiply node. The brackets, the spaces and the original text are gone; only the structure survives. Learn more →
💡 Recursive descent = one parsing method per grammar rule, each calling the methods for the rules beneath it. The precedence of the operators is then the shape of the call graph rather than data anywhere.
💡 Associativity = which way a chain of equal-precedence operators groups. Left-associative means 1 - 2 - 3 is (1 - 2) - 3; right-associative means 2 ^ 3 ^ 2 is 2 ^ (3 ^ 2). It is a property of each operator and the two directions give different numbers.
💡 Visitor = an operation over a fixed set of node types, written as one class instead of one method smeared across every node. It is what you reach for when the node set has settled and the operations are what keep arriving. Learn more →
Functional Requirements
- Tokenize – turn the source text into numbers with optional decimals, identifiers, the five operators, parentheses and commas, skipping whitespace and recording the index of every token.
- Parse – build an AST honouring standard precedence and the associativity of each operator, and reject malformed input with a message that names the position and what was expected.
- Evaluate – walk the tree against a map of variable bindings and return a number, or a typed error that says which rule failed and where.
- Pretty-print – render the tree back to text with only the brackets the structure actually needs, so
(1 + 2) * 3keeps them and1 + (2 * 3)loses them. - Functions – resolve
max(a, b)andsqrt(x)through a registry keyed by name and argument count, so a new function is a map entry rather than a parser change. - Re-bind and re-evaluate – evaluate one parsed tree many times against different variable bindings without re-parsing the text.
- Collect dependencies – report the set of variable names an expression reads, which is what a caller needs to know when to recompute it.
Non-Functional Requirements
- Linear in the input – tokenizing is one pass over the characters and parsing is one pass over the tokens with no backtracking, so both are O(n). Evaluation is O(nodes) and visits each node once.
- Bounded recursion – parsing depth is capped by an explicit counter checked on the way down, so deeply nested input returns a typed parse error rather than a
StackOverflowErrorthat unwinds through half-built state. - Bounded magnitude – an operation whose result cannot be represented, or whose cost is driven by a value rather than by the input length, is refused before it is attempted. No evaluation returns
NaNorInfinityto a caller. - Immutable, reusable trees – a parsed tree holds no evaluation state, so one tree can be evaluated concurrently against different environments with no locking.
Discussion
Newest first