fromscratch-pycpu 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fromscratch_pycpu-0.1.0.dist-info/METADATA +232 -0
- fromscratch_pycpu-0.1.0.dist-info/RECORD +47 -0
- fromscratch_pycpu-0.1.0.dist-info/WHEEL +4 -0
- fromscratch_pycpu-0.1.0.dist-info/entry_points.txt +2 -0
- fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE +21 -0
- pycpu/__init__.py +11 -0
- pycpu/__main__.py +68 -0
- pycpu/_version.py +24 -0
- pycpu/arithmetic.py +176 -0
- pycpu/assembler.py +580 -0
- pycpu/circuit.py +359 -0
- pycpu/cockpit/__init__.py +8 -0
- pycpu/cockpit/app.py +545 -0
- pycpu/cockpit/code.py +161 -0
- pycpu/cockpit/examples/countdown.pebble +7 -0
- pycpu/cockpit/examples/divide-by-zero.pebble +7 -0
- pycpu/cockpit/examples/factorial.pebble +9 -0
- pycpu/cockpit/examples/greeting.pebble +4 -0
- pycpu/cockpit/examples/times-table.pebble +6 -0
- pycpu/cockpit/examples/tour.pebble +31 -0
- pycpu/cockpit/explain.py +660 -0
- pycpu/cockpit/page.html +1261 -0
- pycpu/cockpit/picture.py +470 -0
- pycpu/cockpit/session.py +778 -0
- pycpu/cockpit/walks/a-call-and-the-stack.toml +47 -0
- pycpu/cockpit/walks/many-instructions.toml +39 -0
- pycpu/cockpit/walks/subtracting-with-gates.toml +39 -0
- pycpu/cockpit/walks/where-n-lives.toml +39 -0
- pycpu/cockpit/walks/why-the-clock-ticks.toml +50 -0
- pycpu/cockpit/walks.py +518 -0
- pycpu/computer.py +175 -0
- pycpu/cpu.py +648 -0
- pycpu/cpu_parts.py +140 -0
- pycpu/fast.py +320 -0
- pycpu/isa.py +243 -0
- pycpu/logic.py +222 -0
- pycpu/memory.py +268 -0
- pycpu/proof.py +263 -0
- pycpu/py.typed +0 -0
- pycpu/simulator.py +361 -0
- pycpu/state.py +146 -0
- pycpu/translator/__init__.py +29 -0
- pycpu/translator/codegen.py +493 -0
- pycpu/translator/program.py +211 -0
- pycpu/translator/runtime.py +166 -0
- pycpu/translator/subset.py +688 -0
- pycpu/view.py +55 -0
pycpu/cockpit/explain.py
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
"""What just happened: one plain sentence about the last move, written from the real change.
|
|
2
|
+
|
|
3
|
+
Think of a radio commentator at a football match. You cannot see the pitch, so after
|
|
4
|
+
every play they tell you what happened, with the real names and the real score, and
|
|
5
|
+
never what might have happened. This module is the Cockpit's commentator. It is given
|
|
6
|
+
two snapshots of the machine, `start` (the state at the start of the instruction, before
|
|
7
|
+
the move) and `after`, and fills a set phrase with the numbers it reads from them: the
|
|
8
|
+
numbers going into an instruction come from `start`'s registers, and the answer comes
|
|
9
|
+
from `after`. Instructions are taken apart by `isa.decode`, never by hand.
|
|
10
|
+
|
|
11
|
+
It also holds `Depth`, how closely the glass looks, because every sentence is shaped by
|
|
12
|
+
the depth of the move it describes.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from enum import StrEnum
|
|
17
|
+
|
|
18
|
+
from pycpu.arithmetic import AluOp
|
|
19
|
+
from pycpu.assembler import disassemble
|
|
20
|
+
from pycpu.cpu import MicroStep
|
|
21
|
+
from pycpu.isa import OUTPUT_PORT, Condition, Fault, Instruction, Opcode, decode
|
|
22
|
+
from pycpu.memory import WORD_BITS
|
|
23
|
+
from pycpu.state import BYTE_MASK, WORD_MASK, MachineState
|
|
24
|
+
from pycpu.translator import FRAME_POINTER, TranslatedProgram
|
|
25
|
+
|
|
26
|
+
FINISHED_NOTE = "The program has finished, so there is no next line."
|
|
27
|
+
MAIN_CLOCK = "clk" # the CPU's main clock wire, named plainly in notes
|
|
28
|
+
NO_GATE_ENDING = "so there is no gate to show." # the page looks for these words
|
|
29
|
+
END_NOTE = f"That step finished the instruction, not a gate, {NO_GATE_ENDING}"
|
|
30
|
+
|
|
31
|
+
NEW_LINE = 10 # the character code that starts a new line on the screen
|
|
32
|
+
FIRST_PRINTABLE = 32 # a space: the first character code the screen shows as a letter
|
|
33
|
+
LAST_PRINTABLE = 126 # "~": the last one
|
|
34
|
+
_SIGN_BIT = 1 << (WORD_BITS - 1)
|
|
35
|
+
|
|
36
|
+
# One sentence for each ALU function: `a` and `b` are the numbers going in, from `start`.
|
|
37
|
+
ALU_TEMPLATES: dict[AluOp, str] = {
|
|
38
|
+
AluOp.ADD: "The ALU added {a} and {b}.",
|
|
39
|
+
AluOp.SUB: "The ALU took {b} away from {a}.",
|
|
40
|
+
AluOp.AND: "The ALU kept only the bits that are 1 in both {a} and {b}.",
|
|
41
|
+
AluOp.OR: "The ALU kept the bits that are 1 in {a} or in {b}.",
|
|
42
|
+
AluOp.XOR: "The ALU kept the bits that are 1 in {a} or in {b}, but not in both.",
|
|
43
|
+
AluOp.SHL: "The ALU slid every bit of {a} one place to the left.",
|
|
44
|
+
AluOp.SHR: "The ALU slid every bit of {a} one place to the right.",
|
|
45
|
+
AluOp.PASS_B: "The ALU let {b} straight through.",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
# One sentence for each opcode. Numbers going in come from `start`; `answer`, `pc`, `sp`
|
|
49
|
+
# and `top` (the word on top of the stack) are read from `after`.
|
|
50
|
+
OPCODE_TEMPLATES: dict[Opcode, str] = {
|
|
51
|
+
Opcode.ALU: "{alu} The answer, {answer}, went into r{rd}.",
|
|
52
|
+
Opcode.CMP: (
|
|
53
|
+
"The ALU compared {a} with {b} by taking {b} away from {a}. It kept no answer, "
|
|
54
|
+
"only the flag lamps: zero lamp {zero}, negative lamp {negative}, carry lamp "
|
|
55
|
+
"{carry} ({borrow}), overflow lamp {overflow}."
|
|
56
|
+
),
|
|
57
|
+
Opcode.LI: "The CPU put the number {answer} into r{rd}.",
|
|
58
|
+
Opcode.LHI: "The CPU put {imm} into the top half of r{rd}, so r{rd} is now {answer}.",
|
|
59
|
+
Opcode.LOAD: "The CPU copied {answer} from memory address {address} into r{rd}.",
|
|
60
|
+
Opcode.STORE: "The CPU copied {stored} from r{rd} into memory address {address}.",
|
|
61
|
+
Opcode.JMP: "The CPU jumped to address {pc}.",
|
|
62
|
+
Opcode.CALL: (
|
|
63
|
+
"The CPU pushed the return address, {top}, onto the stack and jumped to address {pc}."
|
|
64
|
+
),
|
|
65
|
+
Opcode.BR: 'The branch asked "{question}?" {outcome}',
|
|
66
|
+
Opcode.RET: "The CPU popped the return address, {pc}, off the stack and went back there.",
|
|
67
|
+
Opcode.PUSH: "The CPU pushed {top} from r{rd} onto the stack, at address {sp}.",
|
|
68
|
+
Opcode.POP: "The CPU popped {answer} off the stack into r{rd}.",
|
|
69
|
+
Opcode.GETSP: "The CPU copied the stack pointer, {answer}, into r{rd}.",
|
|
70
|
+
Opcode.SETSP: "The CPU set the stack pointer to {sp}, the number in r{rd}.",
|
|
71
|
+
Opcode.ADDI: "The ALU added {imm} to {value}. The answer, {answer}, went into r{rd}.",
|
|
72
|
+
Opcode.HALT: "The program finished, so the CPU stopped.",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
# The few instructions whose sentence depends on what really happened.
|
|
76
|
+
ADDI_DOWN_TEMPLATE = "The ALU took {down} away from {value}. The answer, {answer}, went into r{rd}."
|
|
77
|
+
SCREEN_TEMPLATE = "The CPU sent {stored} from r{rd} to the screen{shown}."
|
|
78
|
+
TAKEN_TEMPLATE = "The answer was yes, so the CPU jumped to address {pc}."
|
|
79
|
+
NOT_TAKEN_TEMPLATE = "The answer was no, so the CPU went on to address {pc}."
|
|
80
|
+
# A branch whose target is the very next word goes there whatever the answer, so the
|
|
81
|
+
# sentence cannot say which answer it was without working the condition out again.
|
|
82
|
+
NEXT_ANYWAY_TEMPLATE = (
|
|
83
|
+
"Either answer leads to the next address, so the CPU went on to address {pc}."
|
|
84
|
+
)
|
|
85
|
+
LAMP_WORDS = ("off", "on")
|
|
86
|
+
BORROW_WORDS = ("it had to borrow", "nothing had to be borrowed") # carry after a subtract
|
|
87
|
+
HALT_CODE_TEMPLATE = "The CPU stopped with code {code}, which means {meaning}."
|
|
88
|
+
OWN_CODE_TEMPLATE = "The program stopped itself with code {code}."
|
|
89
|
+
FAULT_TEMPLATE = "The CPU stopped: {text} tried to use an address outside memory."
|
|
90
|
+
FETCH_FAULT_TEMPLATE = (
|
|
91
|
+
"The CPU stopped: it tried to fetch an instruction from address {pc}, which is outside memory."
|
|
92
|
+
)
|
|
93
|
+
FETCH_TEMPLATE = "Fetch: the CPU read the word at address {pc}, which says {text}."
|
|
94
|
+
GATE_TEMPLATE = "Gate {gate}, a NAND inside {place}, worked out a {value}."
|
|
95
|
+
BARE_GATE_TEMPLATE = "Gate {gate} worked out a {value}."
|
|
96
|
+
LINE_TEMPLATE = "Line {line} {ran}."
|
|
97
|
+
ROUTINE_TEMPLATE = (
|
|
98
|
+
"{ran}, starting inside a built-in routine (such as the one print uses), "
|
|
99
|
+
"which has no Pebble line."
|
|
100
|
+
)
|
|
101
|
+
# How a count of instructions is said. A move begun part-way through an instruction
|
|
102
|
+
# first finishes it in the gates; that one is said apart, so every number is real.
|
|
103
|
+
RAN_PHRASE = "ran {count}"
|
|
104
|
+
FINISHED_PHRASE = "finished the instruction you were in"
|
|
105
|
+
FINISHED_THEN_PHRASE = "finished the instruction you were in, then ran {more:,} more"
|
|
106
|
+
CHANGED_TEMPLATE = " {name} changed from {old} to {new}."
|
|
107
|
+
# A line step that ends in another frame (a call or a return) says where it went,
|
|
108
|
+
# never "changed from": the old number would belong to some other frame's box.
|
|
109
|
+
INTO_TEMPLATE = " and went into {function}{where}."
|
|
110
|
+
SET_UP_TEMPLATE = " and finished setting up {function}{where}."
|
|
111
|
+
INTO_AGAIN_TEMPLATE = " and went into a new copy of {function}{where}."
|
|
112
|
+
BACK_TEMPLATE = " and came back to {function}{where}."
|
|
113
|
+
BACK_AGAIN_TEMPLATE = " and came back to the copy of {function} that called it{where}."
|
|
114
|
+
MAIN_WORDS = "the main program"
|
|
115
|
+
WHERE_TEMPLATE = ", where {names}"
|
|
116
|
+
STOPPED_ENDING = ", and then the program stopped."
|
|
117
|
+
SCREEN_SHOWED_TEMPLATE = ' The screen showed "{text}".'
|
|
118
|
+
GATE_STEPS_TEMPLATE = "Took {count:,} gate steps. {last}"
|
|
119
|
+
RUN_TEMPLATE = "{ran}."
|
|
120
|
+
RUN_TO_LINE_TEMPLATE = "{ran} to reach line {line}."
|
|
121
|
+
NOTHING_RAN = "Nothing ran, because the program has already finished."
|
|
122
|
+
REWOUND = "Went back to the start of this instruction."
|
|
123
|
+
ALREADY_AT_START = "You were already at the start of this instruction, so nothing changed."
|
|
124
|
+
|
|
125
|
+
# The question each branch asks the flag lamps. `eq` and `ne` only look at the zero lamp,
|
|
126
|
+
# so they are asked that way: they often follow an `addi`, not a compare. The others
|
|
127
|
+
# follow a compare in Pebble's code, so they ask about its two numbers.
|
|
128
|
+
BRANCH_QUESTIONS: dict[Condition, str] = {
|
|
129
|
+
Condition.EQ: "is the zero lamp on",
|
|
130
|
+
Condition.NE: "is the zero lamp off",
|
|
131
|
+
Condition.LT: "was the first number in the last compare less than the second",
|
|
132
|
+
Condition.GE: "was the first number in the last compare at least the second",
|
|
133
|
+
Condition.LE: "was the first number in the last compare at most the second",
|
|
134
|
+
Condition.GT: "was the first number in the last compare more than the second",
|
|
135
|
+
Condition.LTU: (
|
|
136
|
+
"was the first number in the last compare less than the second, counting without signs"
|
|
137
|
+
),
|
|
138
|
+
Condition.GEU: (
|
|
139
|
+
"was the first number in the last compare at least the second, counting without signs"
|
|
140
|
+
),
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
# What each fault code means, for a `halt` that uses one.
|
|
144
|
+
FAULT_MEANINGS: dict[Fault, str] = {
|
|
145
|
+
Fault.BAD_ADDRESS: "an address outside memory",
|
|
146
|
+
Fault.STACK_OVERFLOW: "the stack ran out of room",
|
|
147
|
+
Fault.DIVIDE_BY_ZERO: "a division by zero",
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
# Plain words for the last name in a gate's scope path. Numbered names are handled apart.
|
|
151
|
+
GATE_PART_WORDS: dict[str, str] = {
|
|
152
|
+
"cpu": "CPU",
|
|
153
|
+
"and": "AND",
|
|
154
|
+
"or": "OR",
|
|
155
|
+
"xor": "XOR",
|
|
156
|
+
"not_bus": "row of NOT gates",
|
|
157
|
+
"mux_bus": "chooser",
|
|
158
|
+
"choose": "chooser",
|
|
159
|
+
"master": "master latch",
|
|
160
|
+
"slave": "slave latch",
|
|
161
|
+
"condition": "branch checker",
|
|
162
|
+
"control": "control unit",
|
|
163
|
+
"fault": "fault checker",
|
|
164
|
+
"flags": "flag register",
|
|
165
|
+
"halt_code": "halt-code register",
|
|
166
|
+
"halted": "halted register",
|
|
167
|
+
"ir": "instruction register",
|
|
168
|
+
"is_zero": "zero checker",
|
|
169
|
+
"next_pc": "next-instruction part",
|
|
170
|
+
"next_sp": "stack pointer part",
|
|
171
|
+
"overflow": "overflow checker",
|
|
172
|
+
"pc": "program counter",
|
|
173
|
+
"phase": "phase register",
|
|
174
|
+
"ram_data": "memory data chooser",
|
|
175
|
+
"ram_wires": "memory wires",
|
|
176
|
+
"sp": "stack pointer",
|
|
177
|
+
"write_back": "write-back part",
|
|
178
|
+
}
|
|
179
|
+
# Plain words for the top-level part of the CPU a gate sits in: the name after `cpu.`.
|
|
180
|
+
CPU_PART_WORDS: dict[str, str] = {
|
|
181
|
+
"address_check": "address checker",
|
|
182
|
+
"address_mux": "memory address chooser",
|
|
183
|
+
"alu": "ALU",
|
|
184
|
+
"branch_target": "branch-target adder",
|
|
185
|
+
"condition": "branch checker",
|
|
186
|
+
"control": "control unit",
|
|
187
|
+
"decode": "instruction decoder",
|
|
188
|
+
"fault": "fault checker",
|
|
189
|
+
"flags": "flag register",
|
|
190
|
+
"halt": "halt part",
|
|
191
|
+
"ir": "instruction register",
|
|
192
|
+
"next_pc": "next-instruction part",
|
|
193
|
+
"next_sp": "stack pointer part",
|
|
194
|
+
"operand": "operand chooser",
|
|
195
|
+
"pc": "program counter",
|
|
196
|
+
"pc_plus_1": "pc + 1 adder",
|
|
197
|
+
"phase": "phase register",
|
|
198
|
+
"port": "screen port",
|
|
199
|
+
"ram_data": "memory data chooser",
|
|
200
|
+
"ram_wires": "memory wires",
|
|
201
|
+
"registers": "registers",
|
|
202
|
+
"sp": "stack pointer",
|
|
203
|
+
"sp_minus_1": "sp - 1 adder",
|
|
204
|
+
"sp_plus_1": "sp + 1 adder",
|
|
205
|
+
"write_back": "write-back part",
|
|
206
|
+
}
|
|
207
|
+
_REGISTER = re.compile(r"^r\d$")
|
|
208
|
+
_COPY_NUMBER = re.compile(r"#\d+$") # `half_adder#1` is the second half adder in its part
|
|
209
|
+
_NUMBERED = re.compile(r"^(bit|word|r)(\d+)$")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class Depth(StrEnum):
|
|
213
|
+
"""How closely the glass looks, and so how big one press of Step is.
|
|
214
|
+
|
|
215
|
+
Attributes:
|
|
216
|
+
LINE: One line of Pebble.
|
|
217
|
+
INSTRUCTION: One machine instruction.
|
|
218
|
+
PART: One clock beat of the CPU part that does the instruction's work.
|
|
219
|
+
GATE: One NAND gate.
|
|
220
|
+
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
LINE = "line"
|
|
224
|
+
INSTRUCTION = "instruction"
|
|
225
|
+
PART = "part"
|
|
226
|
+
GATE = "gate"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def count_instructions(count: int) -> str:
|
|
230
|
+
"""Say `count` instructions in words, with "instruction" singular for 1."""
|
|
231
|
+
return "1 instruction" if count == 1 else f"{count:,} instructions"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def no_gate_note(micro: MicroStep) -> str:
|
|
235
|
+
"""Say why a gate step whose last movement was not a gate has no gate to show."""
|
|
236
|
+
if micro.kind == "edge":
|
|
237
|
+
# The main clock is simply "the clock"; "the clk clock wire" would say it twice.
|
|
238
|
+
wire = "the clock wire" if micro.wire == MAIN_CLOCK else f"the {micro.wire} clock wire"
|
|
239
|
+
return f"That step moved {wire}, not a gate, {NO_GATE_ENDING}"
|
|
240
|
+
return END_NOTE
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def gate_words(path: str) -> str:
|
|
244
|
+
"""Turn a gate's scope path into plain words for the part it lives in.
|
|
245
|
+
|
|
246
|
+
Only the last name counts, without its copy number: the gate in
|
|
247
|
+
`cpu.alu.adder.bit0.full_adder.half_adder#1.xor` lives in an "XOR". A register
|
|
248
|
+
or memory word keeps its number, and a memory bit says which word it belongs to.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
path: A dotted scope path from `Circuit.scope_of`; `""` for the top level.
|
|
252
|
+
|
|
253
|
+
"""
|
|
254
|
+
parent, _, last = path.rpartition(".")
|
|
255
|
+
last = _COPY_NUMBER.sub("", last)
|
|
256
|
+
if not last:
|
|
257
|
+
return "circuit"
|
|
258
|
+
numbered = _NUMBERED.match(last)
|
|
259
|
+
if numbered is not None:
|
|
260
|
+
kind, number = numbered.groups()
|
|
261
|
+
if kind == "r":
|
|
262
|
+
return f"register r{number}"
|
|
263
|
+
if kind == "word":
|
|
264
|
+
return f"memory word {number}"
|
|
265
|
+
return f"bit {number} of {gate_words(parent)}"
|
|
266
|
+
return GATE_PART_WORDS.get(last, last.replace("_", " "))
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _top_part(path: str) -> tuple[str, str]:
|
|
270
|
+
"""Return the scope path and plain words of the top-level part `path` sits in.
|
|
271
|
+
|
|
272
|
+
That is the memory for `ram...`, a register for `cpu.registers.r1...`, and otherwise
|
|
273
|
+
the part named just after `cpu.`, such as the ALU.
|
|
274
|
+
"""
|
|
275
|
+
if not path:
|
|
276
|
+
return path, "the circuit"
|
|
277
|
+
first, _, rest = path.partition(".")
|
|
278
|
+
if first == "ram":
|
|
279
|
+
return "ram", "the memory"
|
|
280
|
+
if first != "cpu" or not rest:
|
|
281
|
+
return path, f"the {gate_words(path)}"
|
|
282
|
+
name, _, inner = rest.partition(".")
|
|
283
|
+
register = inner.partition(".")[0]
|
|
284
|
+
if name == "registers" and _REGISTER.match(register):
|
|
285
|
+
return f"cpu.registers.{register}", f"register {register}"
|
|
286
|
+
return f"cpu.{name}", f"the {CPU_PART_WORDS.get(name, name.replace('_', ' '))}"
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def gate_place(path: str) -> str:
|
|
290
|
+
"""Say where a gate sits: the small part it belongs to, inside the big part.
|
|
291
|
+
|
|
292
|
+
`cpu.alu.adder.bit0.full_adder.half_adder#1.xor` gives "an XOR in the ALU". A gate
|
|
293
|
+
straight inside a big part names only that part ("the program counter"), and a
|
|
294
|
+
numbered register or memory word already says where it is ("memory word 12").
|
|
295
|
+
"""
|
|
296
|
+
top_path, top = _top_part(path)
|
|
297
|
+
small = gate_words(path)
|
|
298
|
+
# A gate straight inside the big part, or a small part named like it (a chooser in
|
|
299
|
+
# the operand chooser), names only the big part.
|
|
300
|
+
if _COPY_NUMBER.sub("", path) == top_path or top == f"the {small}" or top.endswith(f" {small}"):
|
|
301
|
+
return top
|
|
302
|
+
if _NUMBERED.match(_COPY_NUMBER.sub("", path.rpartition(".")[2])):
|
|
303
|
+
return small
|
|
304
|
+
article = "an" if small[0] in "AEIOUaeiou" or small.startswith("XOR") else "a"
|
|
305
|
+
return f"{article} {small} in {top}"
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _ran_words(ran: int, finishing: int) -> str:
|
|
309
|
+
"""Say how many instructions a move ran, saying a gate-finished one apart."""
|
|
310
|
+
if not finishing:
|
|
311
|
+
return RAN_PHRASE.format(count=count_instructions(ran))
|
|
312
|
+
return FINISHED_THEN_PHRASE.format(more=ran) if ran else FINISHED_PHRASE
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _signed(word: int) -> int:
|
|
316
|
+
"""Read a 16-bit word as a signed number, the way Pebble's code means it (65535 is -1)."""
|
|
317
|
+
return word - (_SIGN_BIT << 1) if word & _SIGN_BIT else word
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _screen_words(word: int) -> str:
|
|
321
|
+
"""Say what the screen did with a word sent to it, or nothing for a code it cannot show."""
|
|
322
|
+
code = word & BYTE_MASK
|
|
323
|
+
if code == NEW_LINE:
|
|
324
|
+
return ", which started a new line"
|
|
325
|
+
if FIRST_PRINTABLE <= code <= LAST_PRINTABLE:
|
|
326
|
+
return f', which showed "{chr(code)}"'
|
|
327
|
+
return ""
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _halt_sentence(code: int) -> str:
|
|
331
|
+
"""Say why a `halt` stopped the machine, from its code."""
|
|
332
|
+
if code == 0:
|
|
333
|
+
return OPCODE_TEMPLATES[Opcode.HALT]
|
|
334
|
+
if code in Fault:
|
|
335
|
+
return HALT_CODE_TEMPLATE.format(code=code, meaning=FAULT_MEANINGS[Fault(code)])
|
|
336
|
+
return OWN_CODE_TEMPLATE.format(code=code)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def describe_instruction(start: MachineState, after: MachineState) -> str:
|
|
340
|
+
"""Say what the instruction that started in `start` did, ending in `after`.
|
|
341
|
+
|
|
342
|
+
The word is read from `start`'s memory at `start.pc` and taken apart by `decode`.
|
|
343
|
+
The numbers going in are `start`'s registers; the answer and every other result
|
|
344
|
+
are read from `after`, so the sentence says what really happened.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
start: The state at the start of the instruction.
|
|
348
|
+
after: The state once the instruction has finished.
|
|
349
|
+
|
|
350
|
+
"""
|
|
351
|
+
if start.pc >= len(start.memory):
|
|
352
|
+
return FETCH_FAULT_TEMPLATE.format(pc=start.pc)
|
|
353
|
+
word = start.memory[start.pc]
|
|
354
|
+
i: Instruction = decode(word)
|
|
355
|
+
if i.opcode == Opcode.HALT:
|
|
356
|
+
return _halt_sentence(after.halt_code)
|
|
357
|
+
if after.halted:
|
|
358
|
+
return FAULT_TEMPLATE.format(text=disassemble(word, start.pc))
|
|
359
|
+
return _fill(i, start, after)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _fill(i: Instruction, start: MachineState, after: MachineState) -> str:
|
|
363
|
+
"""Fill the opcode's template for an instruction that finished normally."""
|
|
364
|
+
a, b, value = start.registers[i.ra], start.registers[i.rb], start.registers[i.rd]
|
|
365
|
+
answer = after.registers[i.rd]
|
|
366
|
+
# The one number not read from a state: no `MachineState` keeps the address a load
|
|
367
|
+
# or store used. Working it out here is safe because it is only shown, never used to
|
|
368
|
+
# decide what happened, and only for a load or store that finished without a fault,
|
|
369
|
+
# where the machine used exactly this sum (`ra` plus the offset, wrapped to 16 bits,
|
|
370
|
+
# as `isa.py` defines it). A store's value is then read from `after` at this address.
|
|
371
|
+
address = (start.registers[i.ra] + i.imm) & WORD_MASK
|
|
372
|
+
top = after.memory[after.sp] if after.sp < len(after.memory) else 0
|
|
373
|
+
fields: dict[str, object] = {
|
|
374
|
+
"a": a,
|
|
375
|
+
"b": b,
|
|
376
|
+
"rd": i.rd,
|
|
377
|
+
"imm": i.imm,
|
|
378
|
+
"value": value,
|
|
379
|
+
"answer": answer,
|
|
380
|
+
"address": address,
|
|
381
|
+
"pc": after.pc,
|
|
382
|
+
"sp": after.sp,
|
|
383
|
+
"top": top,
|
|
384
|
+
**{name: LAMP_WORDS[lamp] for name, lamp in after.flags._asdict().items()},
|
|
385
|
+
"borrow": BORROW_WORDS[after.flags.carry],
|
|
386
|
+
}
|
|
387
|
+
match i.opcode:
|
|
388
|
+
case Opcode.ALU:
|
|
389
|
+
fields["alu"] = ALU_TEMPLATES[AluOp(i.fn)].format(a=a, b=b)
|
|
390
|
+
case Opcode.STORE if address == OUTPUT_PORT:
|
|
391
|
+
sent = after.output[-1] # the word the screen really took
|
|
392
|
+
return SCREEN_TEMPLATE.format(stored=sent, rd=i.rd, shown=_screen_words(sent))
|
|
393
|
+
case Opcode.STORE:
|
|
394
|
+
fields["stored"] = after.memory[address]
|
|
395
|
+
case Opcode.BR:
|
|
396
|
+
fields["question"] = BRANCH_QUESTIONS[Condition(i.rd)]
|
|
397
|
+
following = (start.pc + 1) & WORD_MASK
|
|
398
|
+
if (following + i.imm) & WORD_MASK == following:
|
|
399
|
+
outcome = NEXT_ANYWAY_TEMPLATE
|
|
400
|
+
else:
|
|
401
|
+
outcome = TAKEN_TEMPLATE if after.pc != following else NOT_TAKEN_TEMPLATE
|
|
402
|
+
fields["outcome"] = outcome.format(pc=after.pc)
|
|
403
|
+
case Opcode.ADDI if i.imm < 0:
|
|
404
|
+
return ADDI_DOWN_TEMPLATE.format(down=-i.imm, value=value, answer=answer, rd=i.rd)
|
|
405
|
+
case _:
|
|
406
|
+
pass
|
|
407
|
+
return OPCODE_TEMPLATES[i.opcode].format(**fields)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _frame_names(
|
|
411
|
+
translated: TranslatedProgram, state: MachineState
|
|
412
|
+
) -> list[tuple[str, int]] | None:
|
|
413
|
+
"""List the visible Pebble names of `state`'s frame with their addresses, or None.
|
|
414
|
+
|
|
415
|
+
None means `state`'s word has no ready frame (a prologue, a return or a routine).
|
|
416
|
+
Hidden names the translator made up, such as `$for_limit_0`, are left out.
|
|
417
|
+
"""
|
|
418
|
+
if not 0 <= state.pc < len(translated.frames):
|
|
419
|
+
return None
|
|
420
|
+
layout = translated.frames[state.pc]
|
|
421
|
+
if layout is None:
|
|
422
|
+
return None
|
|
423
|
+
pointer = state.registers[FRAME_POINTER]
|
|
424
|
+
return [
|
|
425
|
+
(slot.name, pointer + slot.offset)
|
|
426
|
+
for slot in layout.slots
|
|
427
|
+
if not slot.hidden and 0 <= pointer + slot.offset < len(state.memory)
|
|
428
|
+
]
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _frame(translated: TranslatedProgram, state: MachineState) -> tuple[str | None, int] | None:
|
|
432
|
+
"""Return the function and frame pointer of `state`'s ready frame, or None if it has none."""
|
|
433
|
+
if not 0 <= state.pc < len(translated.frames):
|
|
434
|
+
return None
|
|
435
|
+
layout = translated.frames[state.pc]
|
|
436
|
+
return None if layout is None else (layout.function, state.registers[FRAME_POINTER])
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _function_of_line(translated: TranslatedProgram, pc: int) -> tuple[str | None] | None:
|
|
440
|
+
"""Return (the function) whose Pebble line holds the word at `pc`, or None if unknown.
|
|
441
|
+
|
|
442
|
+
This is for a word with no ready frame, such as a prologue that is still making its
|
|
443
|
+
frame: its line belongs to one function, and a ready word on that line says which.
|
|
444
|
+
A runtime routine's word has no line, so its function is unknown.
|
|
445
|
+
"""
|
|
446
|
+
line = translated.line_at(pc)
|
|
447
|
+
if line is None:
|
|
448
|
+
return None
|
|
449
|
+
for address, layout in enumerate(translated.frames):
|
|
450
|
+
if layout is not None and translated.line_at(address) == line:
|
|
451
|
+
return (layout.function,)
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _and_list(items: list[str]) -> str:
|
|
456
|
+
"""Join words the way a person lists them: "a", "a and b", "a, b and c"."""
|
|
457
|
+
return items[0] if len(items) == 1 else f"{', '.join(items[:-1])} and {items[-1]}"
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _went(
|
|
461
|
+
translated: TranslatedProgram,
|
|
462
|
+
before: tuple[str | None, int],
|
|
463
|
+
now: tuple[str | None, int],
|
|
464
|
+
start: MachineState,
|
|
465
|
+
after: MachineState,
|
|
466
|
+
) -> str:
|
|
467
|
+
"""Say where a line step that changed frames went, and the names it finds there.
|
|
468
|
+
|
|
469
|
+
The stack grows down, so a frame below the stack as it was at `start` is a new
|
|
470
|
+
one (a call: into), and a frame above it belongs to a caller (a return: back).
|
|
471
|
+
Each name is read from `after` alone, in the new frame.
|
|
472
|
+
"""
|
|
473
|
+
names = _frame_names(translated, after) or []
|
|
474
|
+
listed = [f"{name} is {_signed(after.memory[address])}" for name, address in names]
|
|
475
|
+
where = WHERE_TEMPLATE.format(names=_and_list(listed)) if listed else ""
|
|
476
|
+
function = MAIN_WORDS if now[0] is None else now[0]
|
|
477
|
+
same = now[0] == before[0]
|
|
478
|
+
if now[1] >= start.sp:
|
|
479
|
+
template = BACK_AGAIN_TEMPLATE if same and now[0] is not None else BACK_TEMPLATE
|
|
480
|
+
else:
|
|
481
|
+
template = INTO_AGAIN_TEMPLATE if same and now[0] is not None else INTO_TEMPLATE
|
|
482
|
+
return template.format(function=function, where=where)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def describe_line(
|
|
486
|
+
translated: TranslatedProgram,
|
|
487
|
+
start: MachineState,
|
|
488
|
+
after: MachineState,
|
|
489
|
+
ran: int,
|
|
490
|
+
finishing: int = 0,
|
|
491
|
+
) -> str:
|
|
492
|
+
"""Say what one Pebble line step did: the line, how many instructions, what changed.
|
|
493
|
+
|
|
494
|
+
Each visible variable is compared between `start`'s memory and `after`'s. The
|
|
495
|
+
frame is `after`'s when it has one (so a line that makes a variable, such as the
|
|
496
|
+
first, still sees it), else `start`'s. When both have a ready frame and they are
|
|
497
|
+
different frames (a call or a return happened), nothing is compared: the sentence
|
|
498
|
+
says where the step went instead, such as "Line 9 ran 12 instructions and went
|
|
499
|
+
into fact, where n is 7.".
|
|
500
|
+
|
|
501
|
+
A slot below `start.sp` was not on the stack when the step began, so in a function
|
|
502
|
+
(not main, whose memory is zeroed at load) it is new, never "changed": a step that
|
|
503
|
+
began while the function was still making its frame says "and finished setting up
|
|
504
|
+
sq, where t is 16." rather than comparing t with a dead call's leftover word.
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
translated: The Pebble program, with its source map and frames.
|
|
508
|
+
start: The state at the start of the instruction the step began in.
|
|
509
|
+
after: The state where the step stopped.
|
|
510
|
+
ran: How many instructions the step ran on the fast engine.
|
|
511
|
+
finishing: 1 if the step first finished, in the gates, an instruction that was
|
|
512
|
+
part-way through; else 0.
|
|
513
|
+
|
|
514
|
+
"""
|
|
515
|
+
line = translated.line_at(start.pc)
|
|
516
|
+
words = _ran_words(ran, finishing)
|
|
517
|
+
if line is None:
|
|
518
|
+
sentence = ROUTINE_TEMPLATE.format(ran=words[0].upper() + words[1:])
|
|
519
|
+
else:
|
|
520
|
+
sentence = LINE_TEMPLATE.format(line=line, ran=words)
|
|
521
|
+
before, now = _frame(translated, start), _frame(translated, after)
|
|
522
|
+
if before is None and now is not None:
|
|
523
|
+
# The start was still making its frame: only a different function is a new frame.
|
|
524
|
+
known = _function_of_line(translated, start.pc)
|
|
525
|
+
if known is not None and known[0] != now[0]:
|
|
526
|
+
before = (known[0], start.sp)
|
|
527
|
+
if after.halted:
|
|
528
|
+
sentence = sentence.removesuffix(".") + STOPPED_ENDING
|
|
529
|
+
elif before is not None and now is not None and before != now:
|
|
530
|
+
sentence = sentence.removesuffix(".") + _went(translated, before, now, start, after)
|
|
531
|
+
return sentence + _screen_showed(start, after)
|
|
532
|
+
function = None if now is None else now[0]
|
|
533
|
+
made: list[str] = []
|
|
534
|
+
changed = ""
|
|
535
|
+
for name, address in _frame_names(translated, after) or _frame_names(translated, start) or []:
|
|
536
|
+
old, new = _signed(start.memory[address]), _signed(after.memory[address])
|
|
537
|
+
if function is not None and address < start.sp:
|
|
538
|
+
made.append(f"{name} is {new}") # its box was not on the stack yet at the start
|
|
539
|
+
elif old != new:
|
|
540
|
+
changed += CHANGED_TEMPLATE.format(name=name, old=old, new=new)
|
|
541
|
+
if made:
|
|
542
|
+
where = WHERE_TEMPLATE.format(names=_and_list(made))
|
|
543
|
+
sentence = sentence.removesuffix(".") + SET_UP_TEMPLATE.format(
|
|
544
|
+
function=function, where=where
|
|
545
|
+
)
|
|
546
|
+
return sentence + changed + _screen_showed(start, after)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _screen_showed(start: MachineState, after: MachineState) -> str:
|
|
550
|
+
"""Say what the screen showed during the step, or nothing if it showed nothing new."""
|
|
551
|
+
shown = "".join(chr(w & BYTE_MASK) for w in after.output[len(start.output) :]).strip()
|
|
552
|
+
return SCREEN_SHOWED_TEMPLATE.format(text=" ".join(shown.split())) if shown else ""
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def describe_move(
|
|
556
|
+
depth: Depth,
|
|
557
|
+
start: MachineState,
|
|
558
|
+
after: MachineState,
|
|
559
|
+
micro: MicroStep | None,
|
|
560
|
+
translated: TranslatedProgram | None,
|
|
561
|
+
ran: int,
|
|
562
|
+
*,
|
|
563
|
+
gate_path: str | None = None,
|
|
564
|
+
finishing: int = 0,
|
|
565
|
+
) -> str:
|
|
566
|
+
"""Say in one plain sentence what a step at `depth` really did.
|
|
567
|
+
|
|
568
|
+
- **LINE**: "Line 5 ran 10 instructions. n changed from 2 to 1."
|
|
569
|
+
- **INSTRUCTION**: the opcode's template filled with real numbers, such as
|
|
570
|
+
"The ALU took 1 away from 2. The answer, 1, went into r1."
|
|
571
|
+
- **PART**: a fetch beat ("Fetch: the CPU read the word at address 2, which says
|
|
572
|
+
sub r1, r1, r2.") or, when the beat finished the instruction, its sentence.
|
|
573
|
+
- **GATE**: "Gate 41226, a NAND inside an XOR in the ALU, worked out a 1.", or the
|
|
574
|
+
no-gate note for a clock wire or an instruction's end.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
depth: How big the step was.
|
|
578
|
+
start: The state at the start of the current instruction before the step
|
|
579
|
+
(`instruction_start`), so a step begun part-way through an instruction
|
|
580
|
+
describes all of it.
|
|
581
|
+
after: The state after the step.
|
|
582
|
+
micro: The last gate step's micro step, for GATE; else None.
|
|
583
|
+
translated: The Pebble program, needed for LINE; None for assembly.
|
|
584
|
+
ran: How many whole instructions the step ran: a line's count on the fast
|
|
585
|
+
engine, 1 for an instruction, and 0 or 1 for a beat (0 means a fetch).
|
|
586
|
+
gate_path: The scope path of the gate in `micro`, for its part's words.
|
|
587
|
+
finishing: For LINE, 1 if the step first finished a part-done instruction in
|
|
588
|
+
the gates, which is said apart from `ran`.
|
|
589
|
+
|
|
590
|
+
"""
|
|
591
|
+
if start.halted:
|
|
592
|
+
return FINISHED_NOTE
|
|
593
|
+
match depth:
|
|
594
|
+
case Depth.LINE if translated is not None:
|
|
595
|
+
return describe_line(translated, start, after, ran, finishing)
|
|
596
|
+
case Depth.PART if ran == 0 and start.pc < len(start.memory):
|
|
597
|
+
word = start.memory[start.pc]
|
|
598
|
+
return FETCH_TEMPLATE.format(pc=start.pc, text=disassemble(word, start.pc))
|
|
599
|
+
case Depth.GATE if micro is not None:
|
|
600
|
+
return _describe_gate(micro, gate_path)
|
|
601
|
+
case _:
|
|
602
|
+
return describe_instruction(start, after)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _describe_gate(micro: MicroStep, path: str | None) -> str:
|
|
606
|
+
"""Say which gate one gate step worked out, or why it had no gate to show."""
|
|
607
|
+
if micro.kind != "gate":
|
|
608
|
+
return no_gate_note(micro)
|
|
609
|
+
if path is None:
|
|
610
|
+
return BARE_GATE_TEMPLATE.format(gate=micro.gate, value=micro.value)
|
|
611
|
+
return GATE_TEMPLATE.format(gate=micro.gate, place=gate_place(path), value=micro.value)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def describe_gate_steps(count: int, last: str) -> str:
|
|
615
|
+
"""Say how many gate steps one request took, then what the last one did."""
|
|
616
|
+
return GATE_STEPS_TEMPLATE.format(count=count, last=last)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def describe_run(ran: int, after: MachineState, finishing: int = 0) -> str:
|
|
620
|
+
"""Say how many instructions a press of Run ran, and whether the program stopped.
|
|
621
|
+
|
|
622
|
+
Args:
|
|
623
|
+
ran: How many instructions ran on the fast engine.
|
|
624
|
+
after: The state once the run paused again.
|
|
625
|
+
finishing: 1 if Run first finished, in the gates, an instruction that was
|
|
626
|
+
part-way through; else 0. It is said apart from `ran`.
|
|
627
|
+
|
|
628
|
+
"""
|
|
629
|
+
if ran == 0 and not finishing:
|
|
630
|
+
return NOTHING_RAN
|
|
631
|
+
words = _ran_words(ran, finishing)
|
|
632
|
+
sentence = RUN_TEMPLATE.format(ran=words[0].upper() + words[1:])
|
|
633
|
+
return sentence.removesuffix(".") + STOPPED_ENDING if after.halted else sentence
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def describe_run_to_line(ran: int, line: int, finishing: int = 0) -> str:
|
|
637
|
+
"""Say how many instructions a walk's run to a line ran to reach that line.
|
|
638
|
+
|
|
639
|
+
A run that stopped short (the program halted, or it gave up) is said by
|
|
640
|
+
`describe_run` instead, because it never reached the line.
|
|
641
|
+
|
|
642
|
+
Args:
|
|
643
|
+
ran: How many instructions ran on the fast engine.
|
|
644
|
+
line: The Pebble line it reached.
|
|
645
|
+
finishing: 1 if it first finished, in the gates, an instruction that was
|
|
646
|
+
part-way through; else 0. It is said apart from `ran`.
|
|
647
|
+
|
|
648
|
+
"""
|
|
649
|
+
words = _ran_words(ran, finishing)
|
|
650
|
+
return RUN_TO_LINE_TEMPLATE.format(ran=words[0].upper() + words[1:], line=line)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def describe_rewind(*, moved: bool) -> str:
|
|
654
|
+
"""Say what Rewind did: went back, or found nothing to undo.
|
|
655
|
+
|
|
656
|
+
Args:
|
|
657
|
+
moved: True when the instruction was part-way through, so rewinding changed it.
|
|
658
|
+
|
|
659
|
+
"""
|
|
660
|
+
return REWOUND if moved else ALREADY_AT_START
|