KatInterview

Build a Tiny Expression Language Interpreter in Three Stages

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesparsinginterpreterrecursive-descent

Last 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 -x or -(a - b).
  • A print(expr) statement that emits the integer value of expr.

Required structure

Build the solution as a pipeline of separate stages:

  1. Lexer: turn the source text into tokens.
  2. Parser: turn the tokens into an abstract syntax tree (AST).
  3. Evaluator: walk the AST and collect the printed values in order.

Rules

  • Division of integers truncates toward zero (so -7 / 2 is -3 and 7 / -2 is -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.