Interpreter for a Simple Language with Integer Arithmetic and Variable Assignment
Company: Jane Street
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design an interpreter for a simple expression language that supports integer arithmetic and variable assignment.
The interpreter evaluates statements one at a time. A statement is either an assignment of the form `name = expr` (which stores the evaluated value of `expr` and returns `None`), or a bare expression (which is evaluated and the integer result is returned).
Expressions support the binary operators `+`, `-`, `*`, `/` (integer division truncated toward zero), parentheses for grouping, non-negative integer literals, and previously assigned variable names. Variable names consist of letters, digits, and underscores, and must start with a letter or underscore. Operator precedence follows standard math rules: `*` and `/` bind tighter than `+` and `-`, and operators of equal precedence are left-associative.
Implement a class `SimpleInterpreter` with this method:
- `execute(statement: str) -> Optional[int]`: execute a single statement. If it is an assignment of the form `name = expr`, store the value and return `None`. Otherwise evaluate the expression and return its integer value.
Example 1:
```text
Input:
["SimpleInterpreter", "execute", "execute", "execute", "execute"]
[[], ["x = 5"], ["y = x + 3"], ["x * y"], ["(x + y) * 2"]]
Output: [null, null, null, 40, 26]
Explanation:
interp = SimpleInterpreter() # fresh environment
interp.execute("x = 5") # None (x = 5)
interp.execute("y = x + 3") # None (y = 8)
interp.execute("x * y") # 40
interp.execute("(x + y) * 2") # 26
```
Example 2:
```text
Input:
["SimpleInterpreter", "execute", "execute", "execute", "execute"]
[[], ["a = 10"], ["b = 3"], ["a / b"], ["a - b * 2 + 1"]]
Output: [null, null, null, 3, 5]
Explanation:
interp = SimpleInterpreter() # fresh environment
interp.execute("a = 10") # None (a = 10)
interp.execute("b = 3") # None (b = 3)
interp.execute("a / b") # 3 (integer division)
interp.execute("a - b * 2 + 1") # 5 (10 - 6 + 1)
```
```hint Structure the parser
Write one grammar rule for each precedence level and give each rule its own function. Think about which rule should call which, and how a loop inside a rule affects associativity.
```
```hint Division pitfall
Check what Python returns for `-7 // 2` before you use `//` for `/`. Literals are non-negative, but intermediate values are not.
```
### Constraints & Assumptions
- `1 <= len(statement) <= 200`
- All integer literals fit in a 32-bit signed integer.
- Variable names match the pattern `[A-Za-z_][A-Za-z0-9_]*`.
- At most 10,000 calls to `execute`.
- Division by zero will not occur in valid test cases.
### Clarifying Questions to Ask
- What should happen when an expression uses a variable that has not been assigned yet?
- Is unary minus allowed, as in `-x` or `3 * -2`, or are all operands non-negative as written?
- If a statement fails to parse, must the stored variables stay exactly as they were?
- Can intermediate results exceed 32 bits, and if so should they stay exact or overflow?
### What a Strong Answer Covers
- A tokenizer that splits a statement into numbers, names, operators, parentheses and `=`, with whitespace optional.
- A parsing approach that gets precedence and left-associativity right, with parentheses overriding both.
- Correct results for `/` when an intermediate value is negative.
- How an assignment is told apart from an expression, and how variable state persists between calls.
- Behavior on bad input (undefined names, unmatched parentheses, leftover tokens) and the time and space cost per call.
### Follow-up Questions
- How would you add unary minus and a right-associative exponent operator `^` that binds tighter than `*`?
- Would you build an abstract syntax tree instead of evaluating while parsing? What does each approach make easier?
- How would you report the position of a syntax error, and how do you guarantee that a failed statement leaves the variables unchanged?
- How would you extend the environment to support nested scopes, such as blocks or function calls?
Overview: Design a small interpreter that evaluates integer arithmetic with +, -, *, / and parentheses, and stores variables through assignment statements across calls. It tests tokenizing, recursive descent parsing with correct precedence and left-associativity, and integer division that truncates toward zero.