本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
21Project: 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, which turns the text of a program into bytes, and the 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.
You already know
The toy machine: cells of one byte, four registers, PC and SP, the flags Z, N and C, instructions of two bytes each (chapter 13). Numbers modulo and two’s complement (chapter 3). Modules and their interfaces, and tests that check an implementation against another (chapter 20).
21.1 The specification
Write, in Python, a two-pass assembler for the toy machine’s assembly language, with labels, comments, the four ways of writing a number and DATA; and a simulator of its fetch–execute cycle with the 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: 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.
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.
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)]
$ 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
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.
"""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
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]
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
$ 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
sum_array.toy: the symbol table, then the bytes of every line.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 to , is free, and the stack grows down from the top.The output is compared with the shared assembler in milestone 5: for every program, the 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.
sum_array.toy. The top six bits of the first byte are the operation code, the bottom two the register: LOADR R3, R1."""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}
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"]
$ python run_m3.py
outputs: [77] | steps: 5 | PC: 8
memory 10 and 11: [77, 77]
RuntimeError: no HALT after 500 steps
HALT, stopped by the limit.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.
"""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
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
IN. code/grade-11/10-project-toy-machine/listings/simulator_m4.pydef 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)
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). The module ends with the full table and a run that uses it.
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)
$ 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
call_square, SP is back at .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.
"""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}"
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")
OUT runs, as the shared tool does. code/grade-11/10-project-toy-machine/listings/trace_m5.pyimport 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())
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
Then every program of chapter 13, with its inputs, goes through both implementations.
"""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}")
$ 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
Finally, a test file keeps the checks for every later change, including the errors: each faulty program must be refused by both assemblers, and every addition of two bytes must set the same flags in both simulators.
"""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"}
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)
$ 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
Remark 21.3
The tests of the chapter’s own folder go further: the trace of every program, and random memories run for steps by both simulators, compared after every step.
21.7 Exercises
Exercise 21.1 ★
Give the symbol table of multiply.toy (chapter 13): six instructions come before loop:, and three more before done:.
Solution
Solution of Exercise 21.1.
Six instructions of two bytes: loop is at ; three more: done at . 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
Solution of Exercise 21.2.
Three bytes, , and , one per number: DATA has no operation code.
Exercise 21.3 ★
What does the assembler of milestone 2 report for the one-line program JMP finish?
Solution
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
Solution of Exercise 21.4.
0x51 : operation code , 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 stored in two’s complement, and an error for anything outside to .
Solution
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 or ; value % 256 turns into , its two’s 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, 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
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 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, with the flags of the specification, using neither ~ nor >>.
Solution
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 gives , since plus its flipped bits is . Halving drops bit , which is and goes to C. The tests compare both with the shared simulator on all 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
Solution of Exercise 21.8.
Three lines print False. max2.toy prints the wrong output, instead of : CMP R0, R1 with must set C, and JC jumps to print R1; with the inverted carry C is , 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 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
Solution of Exercise 21.9.
The program and its data take addresses to ; the stack starts at and grows down: cells. sum_array.toy pushes nothing. A chain of more than pushes or calls would write over the data, then the instructions: nothing in the machine prevents it, which is why the 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
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
Solution of Exercise 21.11.
| step | PC | instruction | R0 | R1 | R2 | R3 | Z | N | C |
|---|---|---|---|---|---|---|---|---|---|
LOADI R0, 250 | |||||||||
ADDI R0, 10 | |||||||||
JC 8 | |||||||||
OUT R0 | |||||||||
HALT |
: R0 is with a carry, so JC jumps to big, at address ; the program prints and halts after steps.
Exercise 21.12 ★★★
Add to the assembler a pseudo-instruction INC r, which the assembler expands into ADDI r, 1. Where in the two passes does the expansion go, and why does the symbol table stay right?
Solution
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 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 disassembles into exactly one instruction, and that assembling that text gives back the same two bytes when the unused fields are .
Solution
Solution of Exercise 21.13.
Let and be two bytes. The division of by gives one quotient and one remainder , with ; since , 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, by , by [] or by R. Two different instructions never come from one pair of bytes.
Assembling that text gives the operation code back from the mnemonic. The first byte is when the kind has a register, otherwise; the second is for a number or an address, for a second register, when there is no operand. So it gives back and exactly when the fields the kind does not use are : for an instruction without register, for a second register, 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
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 ?
Solution
Solution of Exercise 21.15.
By kind of operands: no operand (HALT, RET, NOP): ; one register (NOT, SHL, SHR, IN, OUT, PUSH, POP): ; one address (JMP, the four conditional jumps, CALL): ; a register and a number or an address (LOADI, ADDI, LOAD, STORE): ; two registers (ADD, SUB, AND, OR, XOR, CMP, LOADR, STORER): . In all , out of pairs of bytes.