KatInterview

Build a Stack-Based Mini Language Interpreter in Python

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesinterpreterstackparsing

Last 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 v pushes a value. The operand v is either an integer literal (such as 7 or -3) or the name of a variable that was stored earlier.
  • STORE x removes the top of the stack and saves it in variable x.
  • ADD, SUB, MUL, DIV remove the top value as the right operand, then the next value as the left operand, and push left + right, left - right, left * right or left / 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 DIV for 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 MOD or NEG) 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.