← back to programming

Register Machine Simulator

Abelson & Sussman · 1996 · SICP §5.2

A software simulator for register machines. The assembler translates symbolic instructions into executable procedures. Testing machines before building hardware.

symbolic instructions assemble executable procedures execute machine state the assembler translates symbols into runnable procedures

The machine model

A register machine has named registers, a program counter, and a stack. The model stores register contents in an association list. Each register is a pair: a name and a mutable value. The machine dispatches on message type — get, set, start.

Scheme

The assembler — extract-labels

The assembler walks the instruction sequence and separates labels (symbols marking positions) from instructions (lists to execute). extract-labels builds two parallel structures: a list of label/position pairs and a list of instruction procedures.

Scheme

Generating execution procedures

Each instruction type — assign, test, branch, goto, perform — gets a corresponding execution procedure. The procedure closes over the machine's registers and stack, so executing it is just a function call. No interpretation at runtime.

Scheme

A complete mini-simulator

Putting it together: a machine that computes factorial using registers, a stack, and a controller sequence. The simulator steps through instructions one at a time, dispatching on instruction type.

Scheme

Monitoring machine performance

Instrumenting the machine: count how many instructions execute, how deep the stack grows. These metrics reveal the complexity of the computation — iterative processes use constant stack depth, recursive ones grow linearly.

Scheme

Notation reference

Scheme / Register Machine Python Meaning
(assign reg (op f) ...)reg = f(...)Assign result of operation to register
(test (op =) (reg n) (const 0))flag = (n == 0)Set condition flag
(branch (label done))if flag: goto doneConditional jump
(goto (label start))goto startUnconditional jump
(save reg) / (restore reg)stack.push(reg) / reg = stack.pop()Stack operations
(perform (op display) ...)print(...)Side effect (no assignment)

Translation notes

The register machine language is assembly-level: each instruction names an operation, its source registers, and its destination. The assembler closes over the machine state so that each instruction becomes a zero-argument procedure. This is the same trick interpreters use — compile once, execute many times. Python's equivalent is compile() turning source into bytecode objects.

Neighbors

Other reading pages

  • SICP Ch.18 — Register Machines (the design language this chapter simulates)

Foundations (Wikipedia)

Ready for the real thing? Read SICP §5.2.