---
title: "Project: An Assembler and Simulator for the Toy Machine"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 21
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/21-project-an-assembler-and-simulator-for-the-toy-machine
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 21 — Project: An Assembler and Simulator for the Toy Machine

Every program of the toy machine in this book has so far been assembled and run by a tool that came with the series. This project rebuilds both halves of that tool in Python: the [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly), which turns the text of a program into bytes, and the [simulator](#def-g11-project-toy-machine-simulator), which runs the bytes one instruction at a time. When the project is finished, the two tools must agree with the series’ own, byte for byte and step for step, on every program of chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine).

**You already know.**

The toy machine: $256$ cells of one byte, four registers, `PC` and `SP`, the flags Z, N and C, $28$ instructions of two bytes each (chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine)). Numbers modulo $256$ and [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement) (chapter [3](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#ch-g10-machine-integers)). Modules and their interfaces, and tests that check an [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) against another (chapter [20](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#ch-g11-modules-and-interfaces)).

## 21.1 The specification

Write, in Python, a [two-pass assembler](#def-g11-project-toy-machine-two-pass) for the toy machine’s [assembly language](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly), with labels, comments, the four ways of writing a number and `DATA`; and a [simulator](#def-g11-project-toy-machine-simulator) of its fetch–execute cycle with the $28$ instructions, the flags, the stack, `IN` and `OUT`, a limit on the number of steps and a trace. Check both against the series’ package `toymachine` on every program of chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine): same bytes, same outputs, same final state, same trace.

The shared package is used only to compare: the chapter’s code adds its folder to `sys.path` and imports it, never changes it. The work goes in five milestones, each one runnable before the next starts.

![The two passes. The first only counts bytes, to learn the address of every label; the second encodes each line, replacing labels by their addresses. The simulator receives the bytes, not the text.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-project-toy-machine/fig-e90d17d433b4.svg)

*The two passes. The first only counts bytes, to learn the address of every label; the second encodes each line, replacing labels by their addresses. The [simulator](#def-g11-project-toy-machine-simulator) receives the bytes, not the text.*

## 21.2 Milestone 1: reading the lines

A line of assembly has up to three parts: a label ending in a colon, a mnemonic, and operands separated by commas; a semicolon starts a comment, unless it stands between quotes as a character. The first module turns each line into a tuple `(line number, label, mnemonic, operands)`. Its function `parse_number(tok, line)`, not shown, turns a number written in decimal, hexadecimal, binary or as a character into a byte, and refuses anything that does not fit; writing it is exercise [21.5](#exo-g11-project-toy-machine-5).

```python
def is_name(tok):
    """True for a name made of letters, digits and _, not starting with a digit."""
    return tok != "" and not tok[0].isdigit() and tok.replace("_", "a").isalnum()


def strip_comment(raw):
    """The line without its comment; a ';' between quotes is a character."""
    kept, quoted = "", False
    for ch in raw:
        if ch == "'":
            quoted = not quoted
        elif ch == ";" and not quoted:
            break
        kept += ch
    return kept


def read_line(raw, line):
    """(label or None, mnemonic or None, operands) for one line of source."""
    code = strip_comment(raw).strip()
    label = None
    head, colon, rest = code.partition(":")
    if colon and is_name(head.strip()):
        label, code = head.strip(), rest.strip()
    if not code:
        return label, None, []
    parts = code.split(None, 1)
    operands = [op.strip() for op in parts[1].split(",")] if len(parts) > 1 else []
    return label, parts[0].upper(), operands


def read_program(text):
    """[(line number, label, mnemonic, operands)] for every line of text."""
    return [(n, *read_line(raw, n)) for n, raw in enumerate(text.splitlines(), start=1)]
```

***Listing 21.1.** Milestone 1: names, comments, and one line cut into its parts. code/grade-11/10-project-toy-machine/listings/tokens.py*

```
$ python run_m1.py
(1, None, None, [])
(2, 'start', 'LOADI', ['R0', '0x2A'])
(3, None, 'LOADI', ['R1', "';'"])
(4, None, 'ADDI', ['R0', '-3'])
(5, 'end', 'HALT', [])
(6, 'table', 'DATA', ['0b101', "'A'", '7'])
       42 -> 42
     0x2A -> 42
 0b101010 -> 42
      '*' -> 42
       -3 -> 253
      300 -> ValueError: line 1: 300 does not fit in one byte
       4x -> ValueError: line 1: '4x' is not a number
```

***Output 21.1.** The rows of a small program, then seven numbers; each error names its line.*

## 21.3 Milestone 2: two passes

**Definition 21.1 (Two-pass assembler, symbol table).**

A *two-pass assembler* reads the program twice. The first pass computes the address of every line and records each label with its address in the *symbol table*; the second pass encodes every line, looking up in the table the labels used as operands.

Two passes are needed because a label may be used before the line that defines it: `JZ done` comes before `done:`. The first pass needs only sizes: two bytes per instruction, one per number of a `DATA` line.

```python
"""Milestone 2: a two-pass assembler for the toy machine."""
from tokens import is_name, parse_number, read_program

OPS = [("HALT", ""), ("LOADI", "rn"), ("LOAD", "r[a]"), ("STORE", "r[a]"),
       ("ADD", "rs"), ("SUB", "rs"), ("ADDI", "rn"), ("AND", "rs"), ("OR", "rs"),
       ("XOR", "rs"), ("NOT", "r"), ("SHL", "r"), ("SHR", "r"), ("CMP", "rs"),
       ("JMP", "a"), ("JZ", "a"), ("JNZ", "a"), ("JN", "a"), ("JC", "a"),
       ("IN", "r"), ("OUT", "r"), ("LOADR", "rs"), ("STORER", "rs"), ("PUSH", "r"),
       ("POP", "r"), ("CALL", "a"), ("RET", ""), ("NOP", "")]
OPCODE = {name: i for i, (name, _) in enumerate(OPS)}
KIND = dict(OPS)
OPERANDS = {"": 0, "r": 1, "a": 1, "rn": 2, "rs": 2, "r[a]": 2}
REGISTERS = ["R0", "R1", "R2", "R3"]


def size(mnemonic, operands, line):
    """How many bytes a line places in memory."""
    if mnemonic == "DATA":
        if not operands:
            raise ValueError(f"line {line}: DATA needs at least one number")
        return len(operands)
    if mnemonic not in OPCODE:
        raise ValueError(f"line {line}: unknown instruction {mnemonic!r}")
    return 2


def first_pass(rows):
    """The symbol table: each label, and the address of what follows it."""
    symbols, address = {}, 0
    for line, label, mnemonic, operands in rows:
        if label:
            if label in symbols:
                raise ValueError(f"line {line}: label {label!r} is defined twice")
            symbols[label] = address
        if mnemonic:
            address += size(mnemonic, operands, line)
    if address > 256:
        raise ValueError(f"the program needs {address} bytes; the memory has 256")
    return symbols

```

***Listing 21.2.** Milestone 2: the table of operations, and the first pass. code/grade-11/10-project-toy-machine/listings/assembler_m2.py*

```python
def register(tok, line):
    if tok.upper() not in REGISTERS:
        raise ValueError(f"line {line}: {tok!r} is not a register (R0 to R3)")
    return int(tok[1])


def value(tok, symbols, line):
    """A number, or a label replaced by its address from the symbol table."""
    if is_name(tok) and tok.upper() not in REGISTERS:
        if tok not in symbols:
            raise ValueError(f"line {line}: label {tok!r} is used but not defined")
        return symbols[tok]
    return parse_number(tok, line)


def encode(mnemonic, operands, symbols, line):
    """The bytes of one line: [4 * opcode + r, operand], or the bytes of DATA."""
    if mnemonic == "DATA":
        return [value(op, symbols, line) for op in operands]
    kind = KIND[mnemonic]
    if len(operands) != OPERANDS[kind]:
        raise ValueError(f"line {line}: {mnemonic} takes {OPERANDS[kind]} operand(s),"
                         f" got {len(operands)}")
    r = register(operands[0], line) if kind.startswith("r") else 0
    operand = 0
    if kind == "rn":
        operand = value(operands[1], symbols, line)
    elif kind == "rs":
        operand = register(operands[1], line)
    elif kind == "r[a]":
        inside = operands[1]
        if not (inside.startswith("[") and inside.endswith("]")):
            raise ValueError(f"line {line}: {mnemonic} wants an address in brackets")
        operand = value(inside[1:-1].strip(), symbols, line)
    elif kind == "a":
        operand = value(operands[0], symbols, line)
    return [4 * OPCODE[mnemonic] + r, operand]

```

***Listing 21.3.** Milestone 2: encoding one line as $4 \times \text{opcode} + r$, then the operand. code/grade-11/10-project-toy-machine/listings/assembler_m2.py*

```python
def second_pass(rows, symbols):
    """[(address, bytes, line number)] for every line that places bytes."""
    placed, address = [], 0
    for line, _label, mnemonic, operands in rows:
        if mnemonic:
            data = encode(mnemonic, operands, symbols, line)
            placed.append((address, data, line))
            address += len(data)
    return placed


def assemble(text):
    """The 256 bytes of memory holding the program, from address 0."""
    rows = read_program(text)
    memory = [0] * 256
    for address, data, _line in second_pass(rows, first_pass(rows)):
        memory[address:address + len(data)] = data
    return memory
```

***Listing 21.4.** Milestone 2: the second pass, and the whole [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly). code/grade-11/10-project-toy-machine/listings/assembler_m2.py*

```
$ python run_m2.py
symbol table: {'loop': 6, 'length': 20, 'array': 21}
  0:   4   0      from line 2
  2:   5  21      from line 3
  4:  10  20      from line 4
  6:  87   1      from line 5
  8:  16   3      from line 6
 10:  25   1      from line 7
 12:  26 255      from line 8
 14:  64   6      from line 9
 16:  80   0      from line 10
 18:   0   0      from line 11
 20:   6          from line 12
 21:  12   7  30  from line 13
 24:   1  25   9  from line 14
```

***Output 21.2.** `sum_array.toy`: the [symbol table](#def-g11-project-toy-machine-two-pass), then the bytes of every line.*

![The memory after assembling sum_array.toy: ten instructions of two bytes, then seven bytes of DATA. Each label of the symbol table points at an address; the rest of memory, from 27 to 255, is free, and the stack grows down from the top.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-project-toy-machine/fig-5608a1913094.svg)

*The memory after assembling `sum_array.toy`: ten instructions of two bytes, then seven bytes of `DATA`. Each label of the [symbol table](#def-g11-project-toy-machine-two-pass) points at an address; the rest of memory, from $27$ to $255$, is free, and the stack grows down from the top.*

The output is compared with the shared [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) in milestone 5: for every program, the $256$ bytes are the same.

## 21.4 Milestone 3: the core of the simulator

**Definition 21.2 (Simulator).**

A *simulator* is a program that imitates a machine: it keeps the machine’s state in its own variables and changes it, step by step, as the machine would.

The state is a dictionary: memory, registers, `PC`, `SP`, flags, inputs and outputs. Each instruction is a small function of the machine, the register field and the operand byte; a dictionary maps each operation code to its function. This milestone gives the cycle and seven instructions only, enough for a first program.

![Decoding the instruction at address 6 of sum_array.toy. The top six bits of the first byte are the operation code, the bottom two the register: LOADR R3, R1.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-project-toy-machine/fig-056a569f06c4.svg)

*Decoding the instruction at address $6$ of `sum_array.toy`. The top six bits of the first byte are the operation code, the bottom two the register: `LOADR R3, R1`.*

```python
"""Milestone 3: the core of the simulator: fetch, decode, execute."""


def new_machine(memory, inputs=()):
    """A machine in its starting state, with the program in memory."""
    return {"mem": list(memory), "reg": [0, 0, 0, 0], "pc": 0, "sp": 0,
            "flags": {"Z": 0, "N": 0, "C": 0}, "inputs": list(inputs),
            "outputs": [], "halted": False, "steps": 0}


def halt(m, r, b):
    m["halted"] = True
    m["pc"] -= 2                     # PC stays on the HALT


def loadi(m, r, b):
    m["reg"][r] = b


def load(m, r, b):
    m["reg"][r] = m["mem"][b]


def store(m, r, b):
    m["mem"][b] = m["reg"][r]


def jmp(m, r, b):
    m["pc"] = b


def out(m, r, b):
    m["outputs"].append(m["reg"][r])


def nop(m, r, b):
    pass


EXECUTE = {0: halt, 1: loadi, 2: load, 3: store, 14: jmp, 20: out, 27: nop}
```

***Listing 21.5.** Milestone 3: the state, and seven instructions. code/grade-11/10-project-toy-machine/listings/simulator_m3.py*

```python
def step(m, execute=EXECUTE):
    """Run one instruction: fetch two bytes, decode them, execute."""
    if m["pc"] > 254:
        raise RuntimeError(f"PC = {m['pc']}: past the end of memory")
    b0, b1 = m["mem"][m["pc"]], m["mem"][m["pc"] + 1]          # fetch
    m["pc"] += 2
    m["steps"] += 1
    opcode, r = b0 // 4, b0 % 4                                 # decode
    if opcode not in execute:
        raise RuntimeError(f"no instruction has operation code {opcode}"
                           f" (address {m['pc'] - 2})")
    execute[opcode](m, r, b1)                                   # execute


def run(m, max_steps=10_000, execute=EXECUTE, trace=None):
    """Step until HALT; stop with an error after max_steps steps."""
    while not m["halted"]:
        if m["steps"] >= max_steps:
            raise RuntimeError(f"no HALT after {max_steps} steps")
        if trace:
            trace(m)
        step(m, execute)
    return m["outputs"]
```

***Listing 21.6.** Milestone 3: one step of the cycle, and running with a limit. code/grade-11/10-project-toy-machine/listings/simulator_m3.py*

```
$ python run_m3.py
outputs: [77] | steps: 5 | PC: 8
memory 10 and 11: [77, 77]
RuntimeError: no HALT after 500 steps
```

***Output 21.3.** A copy through memory, then a loop with no `HALT`, stopped by the limit.*

![The simulator’s loop. Each step fetches two bytes, adds 2 to PC, decodes and executes; it stops at HALT, or with an error that names the cause.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-project-toy-machine/fig-486de2da3dfc.svg)

*The [simulator](#def-g11-project-toy-machine-simulator)’s loop. Each step fetches two bytes, adds $2$ to `PC`, decodes and executes; it stops at `HALT`, or with an error that names the cause.*

## 21.5 Milestone 4: flags, jumps and the stack

The fourth module imports the third and extends its table: the twenty-one other instructions. Arithmetic sets the flags in one place, `set_flags`; the jumps read them.

```python
"""Milestone 4: flags, jumps, input, the stack and subroutines: all 28 instructions."""
import simulator_m3

new_machine = simulator_m3.new_machine          # offered again by this module
step = simulator_m3.step


def set_flags(m, result, carry=0):
    """Keep the result modulo 256 and set Z, N and C from it."""
    v = result % 256
    m["flags"] = {"Z": int(v == 0), "N": int(v >= 128), "C": int(carry)}
    return v


def add(m, r, s):
    total = m["reg"][r] + m["reg"][s % 4]
    m["reg"][r] = set_flags(m, total, total > 255)


def addi(m, r, n):
    total = m["reg"][r] + n
    m["reg"][r] = set_flags(m, total, total > 255)


def sub(m, r, s):
    a, b = m["reg"][r], m["reg"][s % 4]
    m["reg"][r] = set_flags(m, a - b, a < b)        # C: a borrow was needed


def cmp(m, r, s):
    a, b = m["reg"][r], m["reg"][s % 4]
    set_flags(m, a - b, a < b)                       # the flags only
```

***Listing 21.7.** Milestone 4: flags, and the arithmetic that sets them. code/grade-11/10-project-toy-machine/listings/simulator_m4.py*

```python
def jump_if(m, flag, wanted, a):
    if m["flags"][flag] == wanted:
        m["pc"] = a


def jz(m, r, a):
    jump_if(m, "Z", 1, a)


def jnz(m, r, a):
    jump_if(m, "Z", 0, a)


def jn(m, r, a):
    jump_if(m, "N", 1, a)


def jc(m, r, a):
    jump_if(m, "C", 1, a)


def read(m, r, b):
    if not m["inputs"]:
        raise RuntimeError("IN: no input left")
    v = m["inputs"].pop(0)
    if not -128 <= v <= 255:
        raise RuntimeError(f"IN: {v} does not fit in one byte")
    m["reg"][r] = v % 256

```

***Listing 21.8.** Milestone 4: [conditional jumps](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-jump), and `IN`. code/grade-11/10-project-toy-machine/listings/simulator_m4.py*

```python
def loadr(m, r, s):
    m["reg"][r] = m["mem"][m["reg"][s % 4]]


def storer(m, r, s):
    m["mem"][m["reg"][s % 4]] = m["reg"][r]


def push_value(m, v):
    m["sp"] = (m["sp"] - 1) % 256                    # the stack grows downward
    m["mem"][m["sp"]] = v


def pop_value(m):
    v = m["mem"][m["sp"]]
    m["sp"] = (m["sp"] + 1) % 256
    return v


def push(m, r, b):
    push_value(m, m["reg"][r])


def pop(m, r, b):
    m["reg"][r] = pop_value(m)


def call(m, r, a):
    push_value(m, m["pc"])                     # PC already holds the next address
    m["pc"] = a


def ret(m, r, b):
    m["pc"] = pop_value(m)

```

***Listing 21.9.** Milestone 4: memory through a register, the stack, [subroutines](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-subroutine). code/grade-11/10-project-toy-machine/listings/simulator_m4.py*

`AND`, `OR` and `XOR` are made by one function `logic`, and the shifts follow the flags’ specification; those lines are not shown (`NOT` and `SHR` are exercise [21.7](#exo-g11-project-toy-machine-7)). The module ends with the full table and a `run` that uses it.

```python
EXECUTE = simulator_m3.EXECUTE | {
    4: add, 5: sub, 6: addi, 7: logic(lambda a, b: a & b),
    8: logic(lambda a, b: a | b), 9: logic(lambda a, b: a ^ b), 10: not_, 11: shl,
    12: shr, 13: cmp, 15: jz, 16: jnz, 17: jn, 18: jc, 19: read, 21: loadr,
    22: storer, 23: push, 24: pop, 25: call, 26: ret}


def run(m, max_steps=10_000, trace=None):
    """Step until HALT with all 28 instructions."""
    return simulator_m3.run(m, max_steps, EXECUTE, trace)
```

***Listing 21.10.** Milestone 4: the table of the $28$ instructions. code/grade-11/10-project-toy-machine/listings/simulator_m4.py*

```
$ python run_m4.py
count_down   inputs []         outputs [3, 2, 1]  steps  12  SP 0
max2         inputs [57, 201]  outputs [201]      steps   6  SP 0
multiply     inputs [6, 7]     outputs [42]       steps  29  SP 0
abs_value    inputs [-25]      outputs [25]       steps   7  SP 0
call_square  inputs []         outputs [9]        steps  19  SP 0
sum_array    inputs []         outputs [84]       steps  35  SP 0
```

***Output 21.4.** Six programs of chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine); after the [subroutine](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-subroutine) of `call_square`, `SP` is back at $0$.*

## 21.6 Milestone 5: tests and a trace

The trace prints, before each step, the instruction about to run and the state, in the shared tool’s format; a disassembler turns two bytes back into text.

```python
"""Milestone 5: disassembling one instruction, and a trace like the shared tool."""
from assembler_m2 import OPS


def disassemble(b0, b1):
    """The assembly text of the two bytes b0, b1."""
    opcode, r = b0 // 4, b0 % 4
    if opcode >= len(OPS):
        return f"?? ({b0} {b1})"
    name, kind = OPS[opcode]
    shapes = {"": name, "r": f"{name} R{r}", "a": f"{name} {b1}",
              "rn": f"{name} R{r}, {b1}", "r[a]": f"{name} R{r}, [{b1}]",
              "rs": f"{name} R{r}, R{b1 % 4}"}
    return shapes[kind]


HEADER = (f"{'step':>4} {'PC':>3}  {'instruction':<16} {'R0':>3} {'R1':>3} {'R2':>3}"
          f" {'R3':>3}  Z N C")


def trace_row(m):
    """One row, printed before each step: what is about to run, and the state."""
    pc, f = m["pc"], m["flags"]
    text = disassemble(m["mem"][pc], m["mem"][(pc + 1) % 256])
    registers = " ".join(f"{v:3d}" for v in m["reg"])
    flags = f"{f['Z']} {f['N']} {f['C']}"
    return f"{m['steps'] + 1:4d} {pc:3d}  {text:<16} {registers}  {flags}"

```

***Listing 21.11.** Milestone 5: two bytes back to text, and one row of the trace. code/grade-11/10-project-toy-machine/listings/trace_m5.py*

```python
def run_traced(m, run, max_steps=10_000):
    """Run with a trace; an output is printed as soon as OUT runs, as the tool does."""
    print(HEADER)
    printed = 0

    def trace(m):
        nonlocal printed
        for v in m["outputs"][printed:]:
            print(v)
        printed = len(m["outputs"])
        print(trace_row(m))

    run(m, max_steps, trace)
    for v in m["outputs"][printed:]:
        print(v)
    print(f"halted after {m['steps']} steps")
```

***Listing 21.12.** Milestone 5: a run with a trace, which prints each output as soon as `OUT` runs, as the shared tool does. code/grade-11/10-project-toy-machine/listings/trace_m5.py*

```python
import io
import sys
from contextlib import redirect_stdout
from pathlib import Path

from assembler_m2 import assemble
from simulator_m4 import new_machine, run
from trace_m5 import run_traced

CODE = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(CODE / "shared" / "toymachine"))
from toymachine.__main__ import main as shared_tool

program = CODE / "grade-11" / "02-von-neumann-machine" / "listings" / "max2.toy"
ours, theirs = io.StringIO(), io.StringIO()
with redirect_stdout(ours):
    run_traced(new_machine(assemble(program.read_text()), [57, 201]), run)
sys.stdin = io.StringIO("57\n201\n")
with redirect_stdout(theirs):
    shared_tool(["run", "--trace", str(program)])
print(ours.getvalue(), end="")
print("same text as the shared tool:", ours.getvalue() == theirs.getvalue())
```

***Listing 21.13.** Our trace of `max2.toy`, compared with the shared tool’s, character for character. code/grade-11/10-project-toy-machine/listings/run_m5.py*

```
$ python run_m5.py
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  IN R0              0   0   0   0  0 0 0
   2   2  IN R1             57   0   0   0  0 0 0
   3   4  CMP R0, R1        57 201   0   0  0 0 0
   4   6  JC 12             57 201   0   0  0 0 1
   5  12  OUT R1            57 201   0   0  0 0 1
201
   6  14  HALT              57 201   0   0  0 0 1
halted after 6 steps
same text as the shared tool: True
```

***Output 21.5.** The two traces are the same text.*

Then every program of chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine), with its inputs, goes through both [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface).

```python
"""Ours against the shared package, on every program of the toy machine's chapter."""
import sys
from pathlib import Path

from assembler_m2 import assemble
from simulator_m4 import new_machine, run

CODE = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(CODE / "shared" / "toymachine"))
import toymachine

PROGRAMS = CODE / "grade-11" / "02-von-neumann-machine" / "listings"
for path in sorted(PROGRAMS.glob("*.toy")):
    text = path.read_text()
    stdin = path.with_suffix(".stdin")
    inputs = [int(v, 0) for v in stdin.read_text().split()] if stdin.exists() else []
    ours = new_machine(assemble(text), inputs)
    theirs = toymachine.Machine(toymachine.assemble(text), inputs)
    run(ours)
    theirs.run()
    same = (ours["outputs"] == theirs.outputs
            and ours["mem"] == theirs.mem and ours["reg"] == theirs.reg
            and ours["flags"] == theirs.flags and ours["steps"] == theirs.steps
            and ours["sp"] == theirs.sp and ours["pc"] == theirs.pc)
    print(f"{path.name:<20} bytes {assemble(text) == toymachine.assemble(text)!s:<5}"
          f" outputs {str(ours['outputs']):<14} same outputs and state: {same}")
```

***Listing 21.14.** Ours against the shared package, on every program. code/grade-11/10-project-toy-machine/listings/compare_shared.py*

```
$ python compare_shared.py
abs_value.toy        bytes True  outputs [42]           same outputs and state: True
call_square.toy      bytes True  outputs [9]            same outputs and state: True
count_down.toy       bytes True  outputs [3, 2, 1]      same outputs and state: True
max2.toy             bytes True  outputs [201]          same outputs and state: True
multiply.toy         bytes True  outputs [143]          same outputs and state: True
self_modify.toy      bytes True  outputs [80]           same outputs and state: True
shift_multiply.toy   bytes True  outputs [143]          same outputs and state: True
sum_array.toy        bytes True  outputs [84]           same outputs and state: True
```

***Output 21.6.** Eight programs: same bytes, same outputs, same memory, registers, flags and counts at the end.*

Finally, a test file keeps the checks for every later change, including the errors: each faulty program must be refused by both [assemblers](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly), and every addition of two bytes must set the same flags in both [simulators](#def-g11-project-toy-machine-simulator).

```python
"""Tests of our assembler and simulator, against the shared package."""
import sys
import unittest
from pathlib import Path

from assembler_m2 import assemble
from simulator_m4 import new_machine, run

CODE = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(CODE / "shared" / "toymachine"))
import toymachine

FOLDER = CODE / "grade-11" / "02-von-neumann-machine" / "listings"
PROGRAMS = sorted(FOLDER.glob("*.toy"))
BAD = {"unknown instruction": "LOADX R0, 1", "undefined label": "JMP nowhere",
       "too large": "LOADI R0, 300", "bad register": "ADD R0, R7",
       "twice": "a: NOP\na: NOP", "operands": "ADD R0"}
```

***Listing 21.15.** The tests, first part: the shared package, the programs, and six faulty ones. code/grade-11/10-project-toy-machine/listings/ours_tests.py*

```python
class OursTests(unittest.TestCase):
    def test_same_bytes(self):
        for path in PROGRAMS:
            with self.subTest(path.name):
                text = path.read_text()
                self.assertEqual(assemble(text), toymachine.assemble(text))

    def test_errors_where_shared_errs(self):
        for name, text in BAD.items():
            with self.subTest(name):
                with self.assertRaises(ValueError):
                    assemble(text)
                with self.assertRaises(toymachine.ToyError):
                    toymachine.assemble(text)

    def test_flags_of_every_addition(self):
        for a in range(0, 256, 5):
            for b in range(0, 256, 7):
                text = f"LOADI R0, {a}\nLOADI R1, {b}\nADD R0, R1\nHALT"
                m = new_machine(assemble(text))
                run(m)
                shared = toymachine.Machine(toymachine.assemble(text))
                shared.run()
                self.assertEqual((m["reg"], m["flags"]), (shared.reg, shared.flags))

    def test_step_limit(self):
        with self.assertRaises(RuntimeError):
            run(new_machine(assemble("again: JMP again")), max_steps=100)


if __name__ == "__main__":
    unittest.main(verbosity=2)
```

***Listing 21.16.** The tests, second part: bytes, errors, flags and the step limit. code/grade-11/10-project-toy-machine/listings/ours_tests.py*

```
$ bash run_ours_tests.sh
test_errors_where_shared_errs (__main__.OursTests.test_errors_where_shared_errs) ... ok
test_flags_of_every_addition (__main__.OursTests.test_flags_of_every_addition) ... ok
test_same_bytes (__main__.OursTests.test_same_bytes) ... ok
test_step_limit (__main__.OursTests.test_step_limit) ... ok

----------------------------------------------------------------------

OK
```

***Output 21.7.** All four pass.*

**Remark 21.3.**

The tests of the chapter’s own folder go further: the trace of every program, and $300$ random memories run for $40$ steps by both [simulators](#def-g11-project-toy-machine-simulator), compared after every step.

## 21.7 Exercises

**Exercise 21.1 ★.**

Give the [symbol table](#def-g11-project-toy-machine-two-pass) of `multiply.toy` (chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine)): six instructions come before `loop:`, and three more before `done:`.

**Solution of Exercise 21.1.**

Six instructions of two bytes: `loop` is at $12$; three more: `done` at $18$. The table is `{'loop': 12, 'done': 18}`.

**Exercise 21.2 ★.**

How many bytes does the line `DATA 1, 2, 3` place in memory, and which?

**Solution of Exercise 21.2.**

Three bytes, $1$, $2$ and $3$, one per number: `DATA` has no operation code.

**Exercise 21.3 ★.**

What does the [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) of milestone 2 report for the one-line program `JMP finish`?

**Solution of Exercise 21.3.**

A `ValueError` with the message `line 1: label 'finish' is used but not defined`, raised by the second pass when it looks the label up.

**Exercise 21.4 ★.**

The first byte of an instruction is `0x51`. Which operation, and which register?

**Solution of Exercise 21.4.**

`0x51` $= 81 = 4 \times 20 + 1$: operation code $20$, `OUT`, register R1. The instruction is `OUT R1`.

**Exercise 21.5 ★.**

Write `parse_number(tok)` for the four notations, `42`, `0x2A`, `0b101010` and `'*'`, with negative numbers from $-128$ stored in [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement), and an error for anything outside $-128$ to $255$.

**Solution of Exercise 21.5.**

    `def parse_number(tok):`

        `tok = tok.strip()`

        `if len(tok) == 3 and tok[0] == tok[2] == "'":`

            `value = ord(tok[1])`

        `elif tok.lower().startswith(("0x", "-0x")):`

            `value = int(tok, 16)`

        `elif tok.lower().startswith(("0b", "-0b")):`

            `value = int(tok, 2)`

        `else:`

            `value = int(tok)`

        `if not -128 <= value <= 255:`

            `raise ValueError(f"{value} does not fit in one byte")`

        `return value % 256`

`int` accepts the prefixes `0x` and `0b` with base $16$ or $2$; `value % 256` turns $-3$ into $253$, its [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement) on eight bits. The module of milestone 1 writes the same with `int(tok, 0)`, which reads the prefix itself.

**Exercise 21.6 ★★.**

A student writes a one-pass [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly), which encodes each line as soon as it reads it. It works on `count_down.toy` and fails on `multiply.toy`. Why? Name two ways to repair it.

**Solution of Exercise 21.6.**

In `count_down.toy` the only label, `loop`, is defined before the jump that uses it. In `multiply.toy`, `JZ done` comes before `done:`: when the one-pass [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) encodes it, the address of `done` is not known yet. Two repairs: two passes, as in milestone 2; or one pass that leaves a hole, notes the address of the hole and the label, and fills every hole at the end, when all labels are known.

**Exercise 21.7 ★★.**

Write `not_(m, r, b)` and `shr(m, r, b)` for the [simulator](#def-g11-project-toy-machine-simulator), with the flags of the specification, using neither `~` nor `>>`.

**Solution of Exercise 21.7.**

    `def not_(m, r, b):`

        `m["reg"][r] = set_flags(m, 255 - m["reg"][r])`

    `def shr(m, r, b):`

        `v = m["reg"][r]`

        `m["reg"][r] = set_flags(m, v // 2, v % 2)`

Flipping every bit of $v$ gives $255 - v$, since $v$ plus its flipped bits is $11111111$. Halving drops bit $0$, which is $v \bmod 2$ and goes to C. The tests compare both with the shared [simulator](#def-g11-project-toy-machine-simulator) on all $256$ values.

**Exercise 21.8 ★★.**

A student sets the carry of `SUB` and `CMP` with `a >= b` instead of `a < b`. Which programs of `compare_shared.py` now print a wrong result, and what do they print?

**Solution of Exercise 21.8.**

Three lines print `False`. `max2.toy` prints the wrong output, $57$ instead of $201$: `CMP R0, R1` with $57 < 201$ must set C, and `JC` jumps to print R1; with the inverted carry C is $0$, so it prints R0. `count_down.toy` and `multiply.toy` still print the right outputs, but their last subtraction leaves the opposite C flag, and the comparison of the final state catches it. The other five programs never subtract. Only `max2.toy` reads C, so a test of outputs alone would find only it: a [test suite](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-test-suite) must compare the flags too, or include a program that reads each flag.

**Exercise 21.9 ★★.**

How many cells of memory are left for the stack while `sum_array.toy` runs? Could a deep chain of calls overwrite the program?

**Solution of Exercise 21.9.**

The program and its data take addresses $0$ to $26$; the stack starts at $255$ and grows down: $256 - 27 = 229$ cells. `sum_array.toy` pushes nothing. A chain of more than $229$ pushes or calls would write over the data, then the instructions: nothing in the machine prevents it, which is why the [simulator](#def-g11-project-toy-machine-simulator) stops after a number of steps, and a careful program keeps its stack small.

**Exercise 21.10 ★★.**

Write `dump(m)`, which returns the text printed by the shared tool’s `run --dump`: one line with the registers, `PC`, `SP` and the flags, then the non-zero cells, eight per line, as `M[a]=v`.

**Solution of Exercise 21.10.**

    `def dump(m):`

        `f = m["flags"]`

        `lines = ["R0={} R1={} R2={} R3={} PC={} SP={} Z={} N={} C={}".format(`

            `*m["reg"], m["pc"], m["sp"], f["Z"], f["N"], f["C"])]`

        `cells = [(a, v) for a, v in enumerate(m["mem"]) if v]`

        `for i in range(0, len(cells), 8):`

            `lines.append(" " + " ".join(f"M[{a}]={v}" for a, v in cells[i:i + 8]))`

        `return "\n".join(lines)`

After `sum_array.toy`, the first line is `R0=84 R1=27 R2=0 R3=9 PC=18 SP=0 Z=1 N=0 C=1`; the tests compare the whole text with the shared tool’s.

**Exercise 21.11 ★★.**

Write the trace rows of this program: `LOADI R0, 250`, `ADDI R0, 10`, `JC big`, `HALT`, `big: OUT R0`, `HALT`.

**Solution of Exercise 21.11.**

| step | PC | instruction | R0 | R1 | R2 | R3 | Z | N | C |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| $1$ | $0$ | `LOADI R0, 250` | $0$ | $0$ | $0$ | $0$ | $0$ | $0$ | $0$ |
| $2$ | $2$ | `ADDI R0, 10` | $250$ | $0$ | $0$ | $0$ | $0$ | $0$ | $0$ |
| $3$ | $4$ | `JC 8` | $4$ | $0$ | $0$ | $0$ | $0$ | $0$ | $1$ |
| $4$ | $8$ | `OUT R0` | $4$ | $0$ | $0$ | $0$ | $0$ | $0$ | $1$ |
| $5$ | $10$ | `HALT` | $4$ | $0$ | $0$ | $0$ | $0$ | $0$ | $1$ |

$250 + 10 = 260 = 256 + 4$: R0 is $4$ with a carry, so `JC` jumps to `big`, at address $8$; the program prints $4$ and halts after $5$ steps.

**Exercise 21.12 ★★★.**

Add to the [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) a pseudo-instruction `INC r`, which the [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) expands into `ADDI r, 1`. Where in the two passes does the expansion go, and why does the [symbol table](#def-g11-project-toy-machine-two-pass) stay right?

**Solution of Exercise 21.12.**

The expansion goes on the rows, before the first pass: each row `INC r` becomes `ADDI r, 1`. Both passes then see only real instructions. The [symbol table](#def-g11-project-toy-machine-two-pass) stays right because `INC` takes two bytes, as `ADDI` does: every address counted by the first pass is the address where the second pass places the bytes. (A pseudo-instruction that expanded into two instructions would have to be counted as four bytes in the first pass.)

    `def expand(rows):`

        `out = []`

        `for line, label, mnemonic, operands in rows:`

            `if mnemonic == "INC":`

                `mnemonic, operands = "ADDI", operands + ["1"]`

            `out.append((line, label, mnemonic, operands))`

        `return out`

**Exercise 21.13 ★★★.**

Prove that every pair of bytes whose first byte is below $112$ disassembles into exactly one instruction, and that assembling that text gives back the same two bytes when the unused fields are $0$.

**Solution of Exercise 21.13.**

Let $b_0 < 112$ and $b_1$ be two bytes. The division of $b_0$ by $4$ gives one quotient $q$ and one remainder $r$, $b_0 = 4q + r$ with $0 \le r < 4$; since $b_0 < 112 = 4 \times 28$, $q \le 27$ is the operation code of exactly one line of the table, with one mnemonic and one kind of operands. The text is then fixed: the mnemonic, followed, according to the kind, by R$r$, by $b_1$, by `[`$b_1$`]` or by R$(b_1 \bmod 4)$. Two different instructions never come from one pair of bytes.

Assembling that text gives the operation code $q$ back from the mnemonic. The first byte is $4q + r$ when the kind has a register, $4q$ otherwise; the second is $b_1$ for a number or an address, $b_1 \bmod 4$ for a second register, $0$ when there is no operand. So it gives back $b_0$ and $b_1$ exactly when the fields the kind does not use are $0$: $r = 0$ for an instruction without register, $b_1 < 4$ for a second register, $b_1 = 0$ without operand.

**Exercise 21.14 ★★★.**

Write `disassemble_program(memory, end)`, which disassembles the instructions before address `end` and shows the non-zero bytes after it as one `DATA` line. Try it on `sum_array.toy` with `end = 20`.

**Solution of Exercise 21.14.**

    `def disassemble_program(memory, end):`

        `lines = [f"{a:3d}: {disassemble(memory[a], memory[a + 1])}"`

                `for a in range(0, end, 2)]`

        `last = max((a for a, v in enumerate(memory) if v), default=end - 1)`

        `if last >= end:`

            `rest = ", ".join(str(v) for v in memory[end:last + 1])`

            `lines.append(f"{end:3d}: DATA {rest}")`

        `return lines`

On `sum_array.toy`: ten instructions from `0: LOADI R0, 0` to `18: HALT`, with `2: LOADI R1, 21` and `12: ADDI R2, 255` where the source said `array` and `-1`: the labels and the notations are lost; then `20: DATA 6, 12, 7, 30, 1, 25, 9`. Where the instructions end cannot be read from the bytes; that is why `end` is a parameter.

**Exercise 21.15 ★★★.**

How many different instructions does the encoding allow, counting each choice of register, number or address, with the unused fields at $0$?

**Solution of Exercise 21.15.**

By kind of operands: no operand (`HALT`, `RET`, `NOP`): $3 \times 1$; one register (`NOT`, `SHL`, `SHR`, `IN`, `OUT`, `PUSH`, `POP`): $7 \times 4 = 28$; one address (`JMP`, the four [conditional jumps](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-jump), `CALL`): $6 \times 256 = 1536$; a register and a number or an address (`LOADI`, `ADDI`, `LOAD`, `STORE`): $4 \times 4 \times 256 = 4096$; two registers (`ADD`, `SUB`, `AND`, `OR`, `XOR`, `CMP`, `LOADR`, `STORER`): $8 \times 16 = 128$. In all $3 + 28 + 1536 + 4096 + 128 = 5791$, out of $65\,536$ pairs of bytes.
