Show contents
Chapter 6 of 7 · 25 min
Project: your own machine
By the end of this chapter, you'll be able to
- Parse a text program into instructions and labels
- Execute instructions that read and write a memory
- Program a loop with conditional jumps
- Report a program's errors clearly
The machine's language
Our machine understands these instructions. The operand x can be a number or the name of a variable in memory:
| Instruction | Effect |
|---|---|
LOAD x | acc ← x |
STORE v | variable v receives acc |
ADD x, SUB x, MUL x | acc ← acc + x, acc − x, acc × x |
JUMP l | continue at label l |
JUMP_IF_ZERO l | jump to l if acc is 0 |
PRINT | print acc |
STOP | stop the machine |
A line ending with : is a label: it names the position of the next instruction.
PRINT outputs the result.
Text description of the animation
- The program is plain text, readable by a human.
- The assembler notes the position of each label and skips empty lines.
- Each instruction becomes a pair (operation, operand).
- The machine runs the cycle; a jump replaces the counter with the label's position.
- PRINT outputs the result.
The assembler and the machine
def assemble(text):
instructions, labels = [], {}
for line in text.strip().splitlines():
line = line.split("#")[0].strip()
if not line:
continue
if line.endswith(":"):
labels[line[:-1]] = len(instructions)
else:
words = line.split()
instructions.append((words[0], words[1] if len(words) > 1 else None))
for operation, operand in instructions:
if operation.startswith("JUMP") and operand not in labels:
raise ValueError(f"unknown label: {operand}")
return instructions, labels
def run(text, max_cycles=10_000):
instructions, labels = assemble(text)
acc, counter, memory, cycles = 0, 0, {}, 0
value = lambda x: memory.get(x, 0) if x.isidentifier() else int(x)
while cycles < max_cycles:
operation, x = instructions[counter]
counter += 1
cycles += 1
if operation == "LOAD": acc = value(x)
elif operation == "STORE": memory[x] = acc
elif operation == "ADD": acc += value(x)
elif operation == "SUB": acc -= value(x)
elif operation == "MUL": acc *= value(x)
elif operation == "JUMP": counter = labels[x]
elif operation == "JUMP_IF_ZERO":
if acc == 0: counter = labels[x]
elif operation == "PRINT": print(acc)
elif operation == "STOP": return cycles
else: raise ValueError(f"unknown instruction: {operation}")
raise RuntimeError(f"stopped after {max_cycles} cycles: infinite loop?")
sum_1_to_10 = """
LOAD 10
STORE n # n: the number to add
LOAD 0
STORE total
loop:
LOAD n
JUMP_IF_ZERO end
LOAD total
ADD n
STORE total
LOAD n
SUB 1
STORE n
JUMP loop
end:
LOAD total
PRINT
STOP
"""
print("cycles:", run(sum_1_to_10))
55
cycles: 99
A few design choices:
split("#")[0]removes comments,strip()the spaces: the program can be freely indented and commented;- the assembler checks before running that every jump targets an existing label, like a compiler;
value(x)reads a variable if the operand is a name (isidentifier), otherwise converts it to a number;max_cyclesprotects against infinite loops: the machine stops with a clear message.
The loop runs 10 times, from 10 down to 1, and adds each value: 55, in 99 cycles. A real processor would do this work in a few dozen nanoseconds.
Mini-lab: program the machine yourselfPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the factorial
Write a program for the machine that computes and prints the factorial of 5: 5! = 5 × 4 × 3 × 2 × 1. Use two variables: n, which goes down from 5 to 1, and result, which accumulates the product.
Hint 1
result to 1 (not 0: we multiply).Hint 2
n is 0, go to the end; otherwise result ← result × n, then n ← n − 1.Show the solution and common mistakes
def run(text):
lines = [l.split("#")[0].strip() for l in text.strip().splitlines()]
lines = [l for l in lines if l]
labels, instructions = {}, []
for l in lines:
if l.endswith(":"):
labels[l[:-1]] = len(instructions)
else:
w = l.split()
instructions.append((w[0], w[1] if len(w) > 1 else None))
acc, pc, mem = 0, 0, {}
val = lambda x: mem.get(x, 0) if x.isidentifier() else int(x)
for _ in range(10_000):
op, x = instructions[pc]
pc += 1
if op == "LOAD": acc = val(x)
elif op == "STORE": mem[x] = acc
elif op == "ADD": acc += val(x)
elif op == "SUB": acc -= val(x)
elif op == "MUL": acc *= val(x)
elif op == "JUMP": pc = labels[x]
elif op == "JUMP_IF_ZERO" and acc == 0: pc = labels[x]
elif op == "PRINT": print(acc)
elif op == "STOP": return
run("""
LOAD 5
STORE n
LOAD 1
STORE result
loop:
LOAD n
JUMP_IF_ZERO end
LOAD result
MUL n
STORE result
LOAD n
SUB 1
STORE n
JUMP loop
end:
LOAD result
PRINT
STOP
""")
120
The program has exactly the same shape as the sum: only the initialisation (1 instead of 0) and the operation (MUL instead of ADD) change. You have just written, in assembly, what a for does in one line.
Common mistakes:
- Initialising
resultto 0: any product with 0 stays 0, and the machine prints 0. - Testing
nafter decrementing it, without reloading it:JUMP_IF_ZEROlooks at the accumulator, which then holds something other thann. Always reload the value to test just before the conditional jump.
Summary
- 1An assembler turns a text program into instructions and a label table.
- 2The machine runs the cycle with an accumulator, a memory of variables and a program counter.
- 3A loop is written with a conditional jump to exit and an unconditional jump to start again.
- 4Checking labels before running catches errors as early as possible.
- 5A cycle limit turns an infinite loop into a clear error.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.