Build a Tiny Expression Language Interpreter in Three Stages
Stacks & QueuesModel answerLast updated
Implement a lexer, recursive-descent parser and evaluator for a small integer language with variables, unary minus, precedence, truncating division and print.
Task
Design and implement an interpreter for a tiny scripting language. The input is a program given as one string, possibly spanning several lines. Your interpreter must return the values printed by the program, in order.
Language features
- Integer literals such as
42. - Variables, created or updated with assignment, such as
x = 3 + 4. - The binary operators
+,-,*,/with the usual precedence, plus parentheses for grouping. - Unary minus, such as
-xor-(a - b). - A
print(expr)statement that emits the integer value ofexpr.
Required structure
Build the solution as a pipeline of separate stages:
- Lexer: turn the source text into tokens.
- Parser: turn the tokens into an abstract syntax tree (AST).
- Evaluator: walk the AST and collect the printed values in order.
Rules
- Division of integers truncates toward zero (so
-7 / 2is-3and7 / -2is-3). - All variables live in a single global scope.
- Malformed programs must produce a clear error (ideally with a line and column), not a crash or a silently wrong result.
- Reading an undefined variable and dividing by zero are runtime errors.
Example
Program:
x = 10
print(x + 2 * 3)
print(-(x - 7))
Output:
16
-3
What to discuss
Explain your grammar, how it enforces precedence and associativity, how you implement truncating division, which inputs you treat as errors, and how you would handle very deeply nested input.
Hints
Hint 1
Write the grammar first, with one rule per precedence level: expression (+, -), term (*, /), unary (-), primary (number, variable, parenthesized expression). Each rule becomes one parsing function.
Hint 2
Use a loop, not right recursion, for + - and * /. Folding the loop to the left gives left associativity, so 10 - 3 - 2 evaluates to 5.
Hint 3
Python's // floors, and int(a / b) goes through floats. Divide the absolute values with integer division and negate the result if the operand signs differ.
Hint 4
Make unary minus recursive and place it below * and / in the grammar. Require a newline or end of input after each statement so that `x = 1 2` is rejected.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the work into three stages with narrow interfaces. This keeps each part simple to test and lets you replace the evaluator later (for example with a bytecode compiler) without touching the lexer or parser.
1. Lexer
Scan the string once and emit tokens: numbers, identifiers, the keyword print, the symbols + - * / ( ) =, NEWLINE and EOF. Skip spaces, tabs and \r. Track line and column on every token so later stages can report positions. Any other character (such as @) raises a lexing error immediately.
2. Parser (recursive descent)
Grammar:
program := (statement? NEWLINE)* EOF
statement := 'print' '(' expr ')' | IDENT '=' expr
expr := term (('+' | '-') term)*
term := unary (('*' | '/') unary)*
unary := '-' unary | primary
primary := NUM | IDENT | '(' expr ')'
Why this works:
- Precedence comes from nesting:
exprcallsterm, which callsunary, which callsprimary. Multiplicative operators therefore bind tighter than additive ones. A parenthesis insideprimarycallsexpragain, which resets precedence inside the group. - Left associativity comes from the
whileloops inexprandterm. Each new operand is attached to the tree built so far, so10 - 3 - 2becomes(10 - 3) - 2 = 5. The common bug is a right-recursive rule likeexpr := term '-' expr, which yields10 - (3 - 2) = 9. - Unary minus is recursive, so
--xworks, and it sits below*and/, so-2 * 3parses as(-2) * 3. - One statement per line: after each statement the parser demands
NEWLINEorEOF. That makesx = 1 2a syntax error. printis a keyword, soprint = 3fails because the statement rule seesprintand expects(.
3. Evaluator
Walk the AST recursively with a global dictionary as the environment and an output list.
Numreturns its value,Varlooks up the name (undefined gives a runtime error),Negnegates its operand.BinOpevaluates both sides, then applies the operator.Assignevaluates the right side first and then stores it, sox = x + 1uses the old value ofx.Printappends the evaluated value to the output list.
Truncating division
Python's // floors, so -7 // 2 == -4, which is wrong here. int(a / b) goes through floating point and loses precision for large integers. Use:
def trunc_div(a, b):
q = abs(a) // abs(b)
return -q if (a < 0) != (b < 0) else q
Check trunc_div(-7, 2) == -3 and trunc_div(7, -2) == -3. Raise a runtime error if b == 0.
Code (Python)
class LangError(Exception): pass
def tokenize(src):
toks, i, line, col, n = [], 0, 1, 1, len(src)
while i < n:
c = src[i]
if c == '\n':
toks.append(('NL', None, line, col)); i += 1; line += 1; col = 1
elif c in ' \t\r':
i += 1; col += 1
elif c.isdigit():
j = i
while j < n and src[j].isdigit(): j += 1
toks.append(('NUM', int(src[i:j]), line, col)); col += j - i; i = j
elif c.isalpha() or c == '_':
j = i
while j < n and (src[j].isalnum() or src[j] == '_'): j += 1
w = src[i:j]
toks.append(('PRINT' if w == 'print' else 'ID', w, line, col)); col += j - i; i = j
elif c in '+-*/()=':
toks.append((c, c, line, col)); i += 1; col += 1
else:
raise LangError(f"bad character {c!r} at {line}:{col}")
toks.append(('EOF', None, line, col))
return toks
class Parser:
def __init__(self, toks): self.t, self.p = toks, 0
def kind(self, k=0): return self.t[min(self.p + k, len(self.t) - 1)][0]
def eat(self, kind=None):
tok = self.t[min(self.p, len(self.t) - 1)]
if kind and tok[0] != kind:
raise LangError(f"expected {kind} at {tok[2]}:{tok[3]}, got {tok[0]}")
self.p += 1
return tok
def program(self):
out = []
while self.kind() != 'EOF':
if self.kind() == 'NL': self.eat(); continue
out.append(self.stmt())
if self.kind() != 'EOF': self.eat('NL')
return out
def stmt(self):
if self.kind() == 'PRINT':
self.eat(); self.eat('('); e = self.expr(); self.eat(')')
return ('print', e)
if self.kind() == 'ID' and self.kind(1) == '=':
name = self.eat()[1]; self.eat()
return ('assign', name, self.expr())
tok = self.t[self.p]
raise LangError(f"bad statement at {tok[2]}:{tok[3]}")
def expr(self):
node = self.term()
while self.kind() in ('+', '-'):
op = self.eat()[0]; node = ('bin', op, node, self.term())
return node
def term(self):
node = self.unary()
while self.kind() in ('*', '/'):
op = self.eat()[0]; node = ('bin', op, node, self.unary())
return node
def unary(self):
if self.kind() == '-':
self.eat(); return ('neg', self.unary())
return self.primary()
def primary(self):
k = self.kind()
if k == 'NUM': return ('num', self.eat()[1])
if k == 'ID': return ('var', self.eat()[1])
if k == '(':
self.eat(); e = self.expr(); self.eat(')'); return e
tok = self.t[self.p]
raise LangError(f"unexpected {k} at {tok[2]}:{tok[3]}")
def evaluate(node, env):
k = node[0]
if k == 'num': return node[1]
if k == 'var':
if node[1] not in env: raise LangError(f"undefined variable {node[1]}")
return env[node[1]]
if k == 'neg': return -evaluate(node[1], env)
a, b = evaluate(node[2], env), evaluate(node[3], env)
op = node[1]
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if b == 0: raise LangError("division by zero")
q = abs(a) // abs(b)
return -q if (a < 0) != (b < 0) else q
def run(src):
env, out = {}, []
for s in Parser(tokenize(src)).program():
if s[0] == 'assign': env[s[1]] = evaluate(s[2], env)
else: out.append(evaluate(s[1], env))
return out
Complexity
- Time: O(n) for lexing and parsing, since each token is consumed once. Evaluation is O(AST size) = O(n), ignoring big-integer arithmetic cost.
- Space: O(n) for tokens and AST. Recursion depth is proportional to nesting depth.
Edge cases and common mistakes
- Blank lines, extra whitespace, and a missing final newline must all be accepted.
- Associativity:
10 - 3 - 2must give5. - Truncation:
-7 / 2and7 / -2both give-3. - Division by zero, undefined variables, and reassignment (
x = x + 1). - Each of these must raise a clear error:
x =,print(1 + ),3 = x,print 5,x = 1 2,(1 + 2,@. - Using
//orint(a / b)for division is the most common arithmetic mistake.
Trade-offs and extensions
- Deep nesting can hit the host recursion limit. Options are an explicit stack, a Pratt parser or shunting-yard, or raising the limit with a documented depth cap.
- Error recovery: this version stops at the first error. Collecting several errors requires synchronizing at newlines.
- Performance: a tree-walking evaluator is fine here. For heavy workloads, compile the AST to bytecode and run it on a stack machine, reusing the same lexer and parser.
- Testing: unit test each stage separately (token streams, AST shapes, evaluation results), then add end-to-end programs including the error cases above.