Build a Stack-Based Mini Language Interpreter in Python
Stacks & QueuesModel answerLast updated
Write an interpreter that parses a line-based program of LOAD, STORE and integer arithmetic instructions, runs it on an operand stack, and returns the final variable memory.
You are asked to build an interpreter for a tiny instruction language. The language has instructions to move values on and off a stack and to do integer arithmetic. Your task is to read a program as text and execute it.
The exact specification may vary, so use the minimal one below as your working assumption and structure the code so a different spec (for example, a register-based machine) would be easy to swap in.
The machine
- A program is a string with one instruction per line. Tokens are separated by whitespace. Blank lines are ignored.
- The machine has a stack of integers and a memory that maps variable names to integers.
- A variable name starts with a letter or underscore and continues with letters, digits or underscores.
Instructions
LOAD vpushes a value. The operandvis either an integer literal (such as7or-3) or the name of a variable that was stored earlier.STORE xremoves the top of the stack and saves it in variablex.ADD,SUB,MUL,DIVremove the top value as the right operand, then the next value as the left operand, and pushleft + right,left - right,left * rightorleft / right.
Task
Implement run(source: str) -> dict[str, int] that executes the program and returns the final memory.
LOAD 10
LOAD 4
SUB
STORE a
LOAD a
LOAD 3
MUL
STORE b
run(program) -> {"a": 6, "b": 18}
What to settle and handle
- No control flow (labels, jumps, loops) is part of this version.
- Decide and state your policy on: integer width and overflow, rounding of
DIVfor negative results, division by zero, unknown instructions, missing or extra operands, popping from an empty stack, loading a variable that was never stored, values left on the stack at the end, and case sensitivity of opcodes. - Error messages should identify the line number and the cause.
Practice extensions
- Add a new instruction (for example
MODorNEG) and show how little code changes. - Rework the design for a register-based language.
- Describe the tests you would write.
Hints
Hint 1
Separate the work into two phases: turn the text into a list of validated instruction records (with line numbers), then run that list. Syntax errors can then be reported before anything executes.
Hint 2
For binary operators, pop the right operand first and the left operand second. Getting this backwards silently breaks SUB and DIV while ADD and MUL still pass.
Hint 3
Use a table that maps each opcode to its operand count and a handler function, so a new instruction is one table entry instead of another branch in a long if-chain. Pick a DIV rule (truncate toward zero is common) and write it down.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
Before coding I would confirm these points, and state the defaults I pick if the interviewer has no preference:
- Integers: unbounded (Python
int). With fixed width I would wrap or raise on overflow, depending on the spec. - DIV: truncate toward zero (C-style), so
-7 / 2 = -3. Python's//floors, which gives-4, so it needs care. Division by zero is a runtime error. - Errors: unknown opcode, wrong operand count, bad variable name, stack underflow, undefined variable and division by zero all raise an exception carrying the line number.
- Leftover stack values at the end: allowed, not an error (I would mention it is a one-line change to make it strict).
- Opcodes: case-sensitive, uppercase.
- Output: return the final memory dictionary.
Design
Split the work into two phases.
- Parse. Walk the lines, skip blanks, split on whitespace, look the opcode up in a table and check its operand count. Validate that a
STOREtarget is a legal name and that aLOADoperand is either an integer literal or a legal name. The result is a list of(line_no, opcode, operand)records. - Execute. Keep a
stacklist and amemorydict. Run each record through its handler.
Parsing first means a malformed program fails before any side effects, and the executor never deals with raw text. Adding an instruction means adding one handler and one table row. The same split also makes a register-based variant easy: only the instruction table and the executor's state change.
Code
import re
NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
INT = re.compile(r"^[+-]?\d+$")
class InterpreterError(Exception):
def __init__(self, line_no, message):
super().__init__(f"line {line_no}: {message}")
self.line_no = line_no
def _div(left, right):
q = abs(left) // abs(right) # truncate toward zero
return q if (left < 0) == (right < 0) else -q
BINARY = {
"ADD": lambda a, b: a + b,
"SUB": lambda a, b: a - b,
"MUL": lambda a, b: a * b,
"DIV": _div,
}
OPERANDS = {"LOAD": 1, "STORE": 1, "ADD": 0, "SUB": 0, "MUL": 0, "DIV": 0}
def parse(source):
program = []
for line_no, raw in enumerate(source.splitlines(), start=1):
parts = raw.split()
if not parts:
continue
op, args = parts[0], parts[1:]
if op not in OPERANDS:
raise InterpreterError(line_no, f"unknown instruction '{op}'")
if len(args) != OPERANDS[op]:
raise InterpreterError(
line_no, f"{op} expects {OPERANDS[op]} operand(s), got {len(args)}")
arg = args[0] if args else None
if op == "STORE" and not NAME.match(arg):
raise InterpreterError(line_no, f"invalid variable name '{arg}'")
if op == "LOAD" and not (INT.match(arg) or NAME.match(arg)):
raise InterpreterError(line_no, f"invalid operand '{arg}'")
program.append((line_no, op, arg))
return program
def run(source):
stack, memory = [], {}
def pop(line_no):
if not stack:
raise InterpreterError(line_no, "stack underflow")
return stack.pop()
for line_no, op, arg in parse(source):
if op == "LOAD":
if INT.match(arg):
stack.append(int(arg))
elif arg in memory:
stack.append(memory[arg])
else:
raise InterpreterError(line_no, f"undefined variable '{arg}'")
elif op == "STORE":
memory[arg] = pop(line_no)
else:
right = pop(line_no)
left = pop(line_no)
if op == "DIV" and right == 0:
raise InterpreterError(line_no, "division by zero")
stack.append(BINARY[op](left, right))
return memory
Tracing the example: LOAD 10, LOAD 4 gives [10, 4]. SUB pops right=4 and left=10 and pushes 6. STORE a saves 6. LOAD a, LOAD 3, MUL pushes 18, and STORE b saves it. The result is {"a": 6, "b": 18}.
Complexity
Parsing and execution are both O(n) in the number of lines, since every instruction does O(1) work (ignoring big-integer arithmetic cost). Space is O(n) for the instruction list plus the stack and memory.
Trade-offs
- Parse-then-run vs. interpret line by line: line-by-line is shorter, but a syntax error late in the file would arrive after earlier lines already changed memory. Two phases give cleaner failure behavior and make future features such as jumps (which need the whole program) possible.
- Table of handlers vs. if-chain: the table keeps additions local and makes arity checking uniform.
- Exceptions with line numbers vs. error codes: exceptions keep the happy path clean, and the line number makes failures debuggable.
- Register-based variant: instructions would name their operands (
ADD r1 r2 r3), the stack disappears, and operand-order questions become explicit in the syntax.
Common mistakes
- Popping in the wrong order, which breaks
SUBandDIVonly. - Using
//orint(a / b)forDIVwithout thinking about negative numbers or float precision on large values. - Forgetting the empty-stack check on the second pop of a binary operator.
- Treating
LOAD xas an integer parse that crashes on names, or allowing a name like3x. - Silently defaulting undefined variables to 0, which hides bugs.
- Mutating memory before the whole program has been validated.
Tests to write
- Each instruction on its own, with the example program above.
SUBandDIVoperand order (10 4 SUBis 6,7 2 DIVis 3).- Negative division:
-7 2 DIVis -3 and7 -2 DIVis -3. - Blank lines and extra whitespace.
- Each error: unknown opcode, missing or extra operand, invalid name, underflow on
STOREand on binary operators (with only one value on the stack), undefined variable, and division by zero, each asserting the reported line number. - Reassigning a variable, and a leftover value on the stack.