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 = 20This 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.