Python theorytheory 0/50 · 0%
Capstone · hard

49. Building a mini virtual machine / interpreter

Executing a tiny stack-based instruction set in Python.

Implementing a toy stack machine reinforces how real VMs (including the EVM) execute a sequence of simple opcodes against a stack and program counter.

python
def run(program: list[tuple]) -> int:
    stack = []
    for instr in program:
        op = instr[0]
        if op == "PUSH":
            stack.append(instr[1])
        elif op == "ADD":
            b, a = stack.pop(), stack.pop()
            stack.append(a + b)
        elif op == "MUL":
            b, a = stack.pop(), stack.pop()
            stack.append(a * b)
        else:
            raise ValueError(f"unknown op {op}")
    return stack[-1]

run([("PUSH", 2), ("PUSH", 3), ("ADD",), ("PUSH", 4), ("MUL",)])  # (2+3)*4 = 20

This mirrors the EVM's stack-based execution model at a tiny scale: opcodes pop operands, compute, and push results, with the final stack top as the result.

Check your understanding

  1. 1. In the ADD case, why is `b` popped before `a`?

  2. 2. What does the toy VM's stack represent conceptually?

  3. 3. What does `run([("PUSH",2),("PUSH",3),("ADD",)])` return?