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.
Files changed (47) hide show
  1. fromscratch_pycpu-0.1.0.dist-info/METADATA +232 -0
  2. fromscratch_pycpu-0.1.0.dist-info/RECORD +47 -0
  3. fromscratch_pycpu-0.1.0.dist-info/WHEEL +4 -0
  4. fromscratch_pycpu-0.1.0.dist-info/entry_points.txt +2 -0
  5. fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. pycpu/__init__.py +11 -0
  7. pycpu/__main__.py +68 -0
  8. pycpu/_version.py +24 -0
  9. pycpu/arithmetic.py +176 -0
  10. pycpu/assembler.py +580 -0
  11. pycpu/circuit.py +359 -0
  12. pycpu/cockpit/__init__.py +8 -0
  13. pycpu/cockpit/app.py +545 -0
  14. pycpu/cockpit/code.py +161 -0
  15. pycpu/cockpit/examples/countdown.pebble +7 -0
  16. pycpu/cockpit/examples/divide-by-zero.pebble +7 -0
  17. pycpu/cockpit/examples/factorial.pebble +9 -0
  18. pycpu/cockpit/examples/greeting.pebble +4 -0
  19. pycpu/cockpit/examples/times-table.pebble +6 -0
  20. pycpu/cockpit/examples/tour.pebble +31 -0
  21. pycpu/cockpit/explain.py +660 -0
  22. pycpu/cockpit/page.html +1261 -0
  23. pycpu/cockpit/picture.py +470 -0
  24. pycpu/cockpit/session.py +778 -0
  25. pycpu/cockpit/walks/a-call-and-the-stack.toml +47 -0
  26. pycpu/cockpit/walks/many-instructions.toml +39 -0
  27. pycpu/cockpit/walks/subtracting-with-gates.toml +39 -0
  28. pycpu/cockpit/walks/where-n-lives.toml +39 -0
  29. pycpu/cockpit/walks/why-the-clock-ticks.toml +50 -0
  30. pycpu/cockpit/walks.py +518 -0
  31. pycpu/computer.py +175 -0
  32. pycpu/cpu.py +648 -0
  33. pycpu/cpu_parts.py +140 -0
  34. pycpu/fast.py +320 -0
  35. pycpu/isa.py +243 -0
  36. pycpu/logic.py +222 -0
  37. pycpu/memory.py +268 -0
  38. pycpu/proof.py +263 -0
  39. pycpu/py.typed +0 -0
  40. pycpu/simulator.py +361 -0
  41. pycpu/state.py +146 -0
  42. pycpu/translator/__init__.py +29 -0
  43. pycpu/translator/codegen.py +493 -0
  44. pycpu/translator/program.py +211 -0
  45. pycpu/translator/runtime.py +166 -0
  46. pycpu/translator/subset.py +688 -0
  47. pycpu/view.py +55 -0
pycpu/cpu.py ADDED
@@ -0,0 +1,648 @@
1
+ """The CPU built from gates: a cook who picks up a card on one drum beat and obeys it on the next.
2
+
3
+ A drummer beats a slow drum in the kitchen. On the first beat the cook picks up
4
+ the recipe card the finger points at and slides the finger to the next card
5
+ (fetch). On the second beat the cook reads the card and does what it says
6
+ (decode and execute). Pick up, do; pick up, do. That two-beat habit, wired from
7
+ the registers, the ALU, the control unit's parts and the real RAM, is a whole
8
+ computer.
9
+
10
+ Everything that thinks here is NAND gates: the choosers, the adders, the
11
+ decoder and every register. The Python in `GateMachine` only drives the clock,
12
+ reads and writes the storage cells (`peek` and `poke`), and plays the part of
13
+ the screen plugged into the output port, which listens to the CPU's real
14
+ `port_write` wire and never decides anything for it.
15
+ """
16
+
17
+ from collections.abc import Callable, Sequence
18
+ from dataclasses import dataclass
19
+ from enum import IntEnum
20
+
21
+ from pycpu.arithmetic import AluOutput, alu, ripple_adder
22
+ from pycpu.circuit import Bus, Circuit, Wire
23
+ from pycpu.cpu_parts import RegisterFile, condition_met, opcode_lines, outside_ram, sign_extend
24
+ from pycpu.isa import (
25
+ ADDR12_BITS,
26
+ IMM8_BITS,
27
+ OFF6_BITS,
28
+ OFF9_BITS,
29
+ OPCODE_SHIFT,
30
+ RA_SHIFT,
31
+ RB_SHIFT,
32
+ RD_SHIFT,
33
+ WORD_MASK,
34
+ Fault,
35
+ Opcode,
36
+ )
37
+ from pycpu.logic import and_, buffer_into, is_zero, mux_bus, not_, not_bus, or_, or_many
38
+ from pycpu.memory import RAM_ADDRESS_BITS, WORD_BITS, Ram, Register, make_clock
39
+ from pycpu.simulator import NOTHING_WAITING, Simulator
40
+ from pycpu.state import HALT_CODE_MAX, Flags, MachineState, power_on, program_state, validate_state
41
+
42
+ HALT_CODE_BITS = HALT_CODE_MAX.bit_length()
43
+ FIELD_BITS = 3
44
+ FLAG_COUNT = len(Flags._fields)
45
+ LAST_STAGE = 8 # the gates that ripple after `clk` falls: the end of a clock cycle
46
+ WRITE_RISE = 1 # the stage at which the `write` wire goes up
47
+
48
+
49
+ class Phase(IntEnum):
50
+ """Which beat comes next: picking up a card (fetch) or obeying it (execute)."""
51
+
52
+ FETCH = 0
53
+ EXECUTE = 1
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class MicroStep:
58
+ """One tiny movement of the machine: one gate thinking, or one clock wire moving.
59
+
60
+ Attributes:
61
+ kind: `"gate"` for one gate evaluation, `"edge"` for a clock wire going up
62
+ or down, `"end"` when an instruction has just finished.
63
+ gate: The id of the gate that was evaluated, or -1 when it was not a gate.
64
+ wire: The clock wire that moved (`"write"` or `"clk"`) for an edge, else `""`.
65
+ value: The gate's new output, or the clock wire's new value; 0 for `"end"`.
66
+ phase: The beat the movement belongs to.
67
+
68
+ """
69
+
70
+ kind: str
71
+ gate: int
72
+ wire: str
73
+ value: int
74
+ phase: Phase
75
+
76
+
77
+ # The four clock edges of one cycle, in the order `Simulator.tick` makes them.
78
+ _EDGES = (("write", 1), ("write", 0), ("clk", 1), ("clk", 0))
79
+
80
+
81
+ def _placeholders(c: Circuit, width: int) -> Bus:
82
+ """Make `width` wires now that a gate will drive later (see `_drive`).
83
+
84
+ A register's data and `load` wires are needed when the register is built,
85
+ but the values that feed them are worked out from registers built later.
86
+ """
87
+ return tuple(c.wire_placeholder() for _ in range(width))
88
+
89
+
90
+ def _drive(c: Circuit, source: Bus, target: Bus) -> None:
91
+ """Make every placeholder in `target` a copy of the matching wire in `source`."""
92
+ for wire, placeholder in zip(source, target, strict=True):
93
+ buffer_into(c, wire, placeholder)
94
+
95
+
96
+ def _constant(c: Circuit, value: int, width: int) -> Bus:
97
+ """Spell a fixed number with the circuit's always-1 and always-0 wires."""
98
+ return tuple(c.high if (value >> bit) & 1 else c.low for bit in range(width))
99
+
100
+
101
+ def _field(word: Bus, shift: int, width: int) -> Bus:
102
+ """Take the `width` wires of a field starting at bit `shift`: a field is just wires."""
103
+ return word[shift : shift + width]
104
+
105
+
106
+ @dataclass
107
+ class _Wires:
108
+ """The named wires one build step hands to the next while the CPU is wired up.
109
+
110
+ Fields after `address` are filled in by the later steps.
111
+ """
112
+
113
+ line: Bus
114
+ imm8: Bus
115
+ fetch: Wire
116
+ execute: Wire
117
+ running: Wire
118
+ memory_op: Wire
119
+ bank: RegisterFile
120
+ write_back: Bus
121
+ register_write: Wire
122
+ out: AluOutput
123
+ met: Wire
124
+ sp_down: Bus
125
+ sp_up: Bus
126
+ pushes: Wire
127
+ pops: Wire
128
+ address: Bus
129
+ outside: Wire = -1
130
+ go: Wire = -1
131
+ act: Wire = -1
132
+ ram_write: Wire = -1
133
+ ram_data: Bus = ()
134
+
135
+
136
+ class GateMachine:
137
+ """A whole computer made of NAND gates: the CPU wired to the real RAM.
138
+
139
+ One clock cycle is one beat. On a fetch beat the instruction register `ir`
140
+ takes the word at `pc`, and `pc` takes `pc + 1`. On an execute beat the
141
+ instruction in `ir` is decoded and obeyed, and its results load at the
142
+ clock's rise. `step` runs one whole instruction, `step_cycle` one beat, and
143
+ `micro_step` one gate or one clock edge. The state goes in and out as the
144
+ same `MachineState` the fast engine uses, so the two can be compared.
145
+
146
+ Attributes:
147
+ words: How many words of RAM the machine has.
148
+ circuit: The circuit: the CPU in part `cpu`, the RAM in part `ram`.
149
+ simulator: The simulator running the circuit.
150
+ port_write: The wire that is 1 when this beat stores to the output port.
151
+ port_data: The 16 wires carrying the word a `STORE` would write.
152
+ taps: For each part of the CPU (such as `"cpu.alu"`), its inputs and then
153
+ its outputs, each a name for a row of wires the CPU already has. They are
154
+ recorded while the CPU is wired up and only read after that; a tap never
155
+ adds a gate or a wire.
156
+ tap_outputs: For each part in `taps`, which of its names are outputs.
157
+ builders: For each part in `taps`, the function or method whose code built it,
158
+ and the name of the `with c.scope(...)` block to show (None means the part's
159
+ own last path segment, and "" means the whole function). The Cockpit reads
160
+ that live source for its code panel.
161
+
162
+ """
163
+
164
+ def __init__(self, address_bits: int = RAM_ADDRESS_BITS) -> None:
165
+ """Build the CPU and its RAM from gates, then switch the machine on.
166
+
167
+ Args:
168
+ address_bits: How many address wires the RAM has; it holds
169
+ `2 ** address_bits` words.
170
+
171
+ Raises:
172
+ ValueError: If `address_bits` is below 1, or so big that the RAM would
173
+ reach the output port's address.
174
+
175
+ """
176
+ if not 1 <= address_bits < WORD_BITS:
177
+ msg = f"address_bits must be from 1 to {WORD_BITS - 1}, not {address_bits}"
178
+ raise ValueError(msg)
179
+ self.words = 1 << address_bits
180
+ # Registers whose input placeholders still wait for a driver (see `_feed`).
181
+ self._pending: dict[str, tuple[Bus, Wire]] = {}
182
+ self.taps: dict[str, dict[str, Bus]] = {}
183
+ self.tap_outputs: dict[str, tuple[str, ...]] = {}
184
+ self.builders: dict[str, tuple[Callable[..., object], str | None]] = {}
185
+ c = Circuit()
186
+ self.circuit = c
187
+ self._clock = make_clock(c)
188
+ ram_address = _placeholders(c, address_bits)
189
+ ram_data = _placeholders(c, WORD_BITS)
190
+ (ram_write,) = _placeholders(c, 1)
191
+ self._ram = Ram(c, ram_address, ram_data, ram_write, self._clock)
192
+ self._tap(
193
+ "ram",
194
+ {"address": ram_address, "data": ram_data, "write": (ram_write,)},
195
+ {"out": self._ram.out},
196
+ Ram.__init__,
197
+ )
198
+ with c.scope("cpu"):
199
+ address, data, write = self._build_cpu(c, address_bits)
200
+ with c.scope("ram_wires"):
201
+ _drive(c, address[:address_bits], ram_address)
202
+ _drive(c, data, ram_data)
203
+ _drive(c, (write,), (ram_write,))
204
+ self.simulator = Simulator(c)
205
+ self._gate_outputs = c.gate_wires[2]
206
+ self._output: list[int] = []
207
+ self._stage = 0
208
+ self._cycle_phase = Phase.FETCH
209
+ self.load_state(power_on(self.words))
210
+
211
+ def _build_cpu(self, c: Circuit, address_bits: int) -> tuple[Bus, Bus, Wire]:
212
+ """Add the CPU's gates; return the RAM's address, data and write wires.
213
+
214
+ The registers come first, with placeholders on their inputs, because
215
+ the logic that feeds them reads their own outputs. Every placeholder is
216
+ driven before this returns; a register still waiting in `_pending` is a
217
+ wiring mistake, caught here by name (the `Simulator` would only count
218
+ the undriven wires).
219
+ """
220
+ self._phase = self._register(c, "phase", 1)
221
+ self._ir = self._register(c, "ir", WORD_BITS, data=self._ram.out)
222
+ self._pc = self._register(c, "pc", WORD_BITS)
223
+ self._sp = self._register(c, "sp", WORD_BITS)
224
+ self._flags = self._register(c, "flags", FLAG_COUNT)
225
+ with c.scope("halt"):
226
+ self._halted = self._register(c, "halted", 1, data=(c.high,))
227
+ self._halt_code = self._register(c, "halt_code", HALT_CODE_BITS)
228
+ line = opcode_lines(c, self._ir.q[OPCODE_SHIFT:])
229
+ w = self._build_datapath(c, line)
230
+ self._build_checks(c, w, address_bits)
231
+ self._build_next_pc(c, w)
232
+ self._build_write_back(c, w)
233
+ if self._pending:
234
+ msg = f"registers left with undriven inputs: {sorted(self._pending)}"
235
+ raise RuntimeError(msg)
236
+ return w.address, w.ram_data, w.ram_write
237
+
238
+ def _register(self, c: Circuit, name: str, width: int, data: Bus | None = None) -> Register:
239
+ """Build a register whose `load` (and, unless given, data) wires are filled in later."""
240
+ load = c.wire_placeholder()
241
+ data_in = _placeholders(c, width) if data is None else data
242
+ if data is None:
243
+ self._pending[name] = (data_in, load)
244
+ else:
245
+ self._pending[name] = ((), load)
246
+ return Register(c, width, data_in, load, self._clock, name)
247
+
248
+ def _tap(
249
+ self,
250
+ part: str,
251
+ inputs: dict[str, Bus],
252
+ outputs: dict[str, Bus],
253
+ builder: Callable[..., object],
254
+ scope: str | None = None,
255
+ ) -> None:
256
+ """Name a part's input and output wires, and the code that built it.
257
+
258
+ This only writes names down, like labels tied onto cables already laid:
259
+ it makes no gate and no wire. `builder` is the function or method that holds
260
+ the part's `with c.scope(...)` block, so the Cockpit can show its source; `scope`
261
+ names that block when it is not called after the part's last path segment; an empty
262
+ `scope` means every line of the builder makes the part, so all of it is shown.
263
+ """
264
+ self.builders[part] = (builder, scope)
265
+ self.taps[part] = {**inputs, **outputs}
266
+ self.tap_outputs[part] = tuple(outputs)
267
+
268
+ def _feed(self, c: Circuit, name: str, load: Wire, data: Bus = ()) -> None:
269
+ """Drive the waiting `load` (and data) placeholders of the register `name`."""
270
+ data_in, load_in = self._pending.pop(name)
271
+ _drive(c, (load,), (load_in,))
272
+ _drive(c, data, data_in)
273
+
274
+ def _build_datapath(self, c: Circuit, line: Bus) -> _Wires:
275
+ """Add the register file, the ALU and the choosers in front of them.
276
+
277
+ The register file's windows read `ra` and `rb`, or `rd` where an
278
+ instruction needs it. The ALU's second input and its job dial are
279
+ chosen by the opcode lines. Two adders keep `sp - 1` and `sp + 1`
280
+ ready for the stack, and the address chooser picks `pc`, the ALU's
281
+ answer, `sp - 1` (a push) or `sp` (a pop).
282
+ """
283
+ ir = self._ir.q
284
+ rd = _field(ir, RD_SHIFT, FIELD_BITS)
285
+ imm8 = _field(ir, 0, IMM8_BITS)
286
+ with c.scope("control"):
287
+ execute = self._phase.q[0]
288
+ fetch = not_(c, execute)
289
+ running = not_(c, self._halted.q[0])
290
+ # Window a reads rd for the two opcodes that change rd in place.
291
+ read_a = mux_bus(
292
+ c, or_(c, line[Opcode.ADDI], line[Opcode.LHI]), _field(ir, RA_SHIFT, FIELD_BITS), rd
293
+ )
294
+ # Window b reads rd for the opcodes that send rd somewhere.
295
+ sends_rd = or_many(c, [line[Opcode.STORE], line[Opcode.PUSH], line[Opcode.SETSP]])
296
+ read_b = mux_bus(c, sends_rd, _field(ir, RB_SHIFT, FIELD_BITS), rd)
297
+ write_back, register_write = _placeholders(c, WORD_BITS), c.wire_placeholder()
298
+ bank = RegisterFile(c, write_back, register_write, rd, read_a, read_b, self._clock)
299
+ self._registers = bank.registers
300
+ self._tap(
301
+ "cpu.registers",
302
+ {
303
+ "write": (register_write,),
304
+ "write_select": rd,
305
+ "data": write_back,
306
+ "read_a": read_a,
307
+ "read_b": read_b,
308
+ },
309
+ {"a": bank.a, "b": bank.b},
310
+ RegisterFile.__init__,
311
+ )
312
+ with c.scope("operand"):
313
+ memory_op = or_(c, line[Opcode.LOAD], line[Opcode.STORE])
314
+ b = mux_bus(c, memory_op, bank.b, sign_extend(c, _field(ir, 0, OFF6_BITS)))
315
+ b = mux_bus(c, line[Opcode.ADDI], b, sign_extend(c, imm8))
316
+ # CMP always subtracts; ADDI, LOAD and STORE always add; others use fn.
317
+ forced = or_many(
318
+ c, [line[Opcode.CMP], line[Opcode.ADDI], line[Opcode.LOAD], line[Opcode.STORE]]
319
+ )
320
+ op = mux_bus(c, forced, _field(ir, 0, FIELD_BITS), (line[Opcode.CMP], c.low, c.low))
321
+ out = alu(c, bank.a, b, op)
322
+ self._tap(
323
+ "cpu.alu",
324
+ {"a": bank.a, "b": b},
325
+ {"result": out.result, "flags": (out.zero, out.negative, out.carry, out.overflow)},
326
+ alu,
327
+ scope="", # the whole function: its flags are made after the block closes
328
+ )
329
+ flags = self._flags.q
330
+ met = condition_met(c, rd, flags[0], flags[1], flags[2], flags[3])
331
+ sp = self._sp.q
332
+ with c.scope("sp_minus_1"):
333
+ # Adding 0xFFFF is adding -1 in two's complement: the finger moves down.
334
+ sp_down, _ = ripple_adder(c, sp, _constant(c, WORD_MASK, WORD_BITS), c.low)
335
+ with c.scope("sp_plus_1"):
336
+ sp_up, _ = ripple_adder(c, sp, _constant(c, 0, WORD_BITS), c.high)
337
+ with c.scope("address_mux"):
338
+ pushes = or_(c, line[Opcode.PUSH], line[Opcode.CALL])
339
+ pops = or_(c, line[Opcode.POP], line[Opcode.RET])
340
+ stack_spot = mux_bus(c, pops, sp_down, sp)
341
+ execute_address = mux_bus(c, or_(c, pushes, pops), out.result, stack_spot)
342
+ address = mux_bus(c, execute, self._pc.q, execute_address)
343
+ self._tap(
344
+ "cpu.address_mux",
345
+ {"pc": self._pc.q, "alu": out.result, "sp": sp, "sp_minus_1": sp_down},
346
+ {"address": address},
347
+ self._build_datapath,
348
+ )
349
+ return _Wires(
350
+ line=line,
351
+ imm8=imm8,
352
+ fetch=fetch,
353
+ execute=execute,
354
+ running=running,
355
+ memory_op=memory_op,
356
+ bank=bank,
357
+ write_back=write_back,
358
+ register_write=register_write,
359
+ out=out,
360
+ met=met,
361
+ sp_down=sp_down,
362
+ sp_up=sp_up,
363
+ pushes=pushes,
364
+ pops=pops,
365
+ address=address,
366
+ )
367
+
368
+ def _build_checks(self, c: Circuit, w: _Wires, address_bits: int) -> None:
369
+ """Add the output port's wire and the fault and halt logic.
370
+
371
+ A bad address (outside RAM, except a STORE to the port) or a HALT
372
+ instruction stops the machine and blocks every other load that beat.
373
+ The stack opcodes need RAM too, so for them even `0xFFFF` is bad.
374
+ """
375
+ w.outside = outside_ram(c, w.address, address_bits)
376
+ with c.scope("port"):
377
+ port_store = and_(c, w.line[Opcode.STORE], is_zero(c, not_bus(c, w.address)))
378
+ self.port_write: Wire = and_(c, and_(c, w.execute, port_store), w.running)
379
+ self.port_data: Bus = w.bank.b
380
+ with c.scope("fault"):
381
+ uses_memory = or_many(c, [and_(c, w.memory_op, not_(c, port_store)), w.pushes, w.pops])
382
+ needs_ram = or_(c, w.fetch, uses_memory)
383
+ bad = and_(c, w.outside, needs_ram)
384
+ halt_instruction = and_(c, w.execute, w.line[Opcode.HALT])
385
+ stop = or_(c, bad, halt_instruction)
386
+ w.go = and_(c, w.running, not_(c, stop)) # nothing else may load after a stop
387
+ w.act = and_(c, w.go, w.execute)
388
+ halt_load = and_(c, w.running, stop)
389
+ self._feed(c, "halted", halt_load)
390
+ fault_code = _constant(c, Fault.BAD_ADDRESS, HALT_CODE_BITS)
391
+ code = mux_bus(c, bad, w.imm8, fault_code)
392
+ self._feed(c, "halt_code", halt_load, code)
393
+ # The outputs are what the halt logic sends this beat, not what the `halted` and
394
+ # `halt_code` registers hold: those only take it in when the clock rises.
395
+ self._tap(
396
+ "cpu.halt",
397
+ {"bad_address": (bad,), "halt_instruction": (halt_instruction,), "imm8": w.imm8},
398
+ {"halt_now": (halt_load,), "code": code},
399
+ self._build_checks,
400
+ scope="fault",
401
+ )
402
+
403
+ def _build_next_pc(self, c: Circuit, w: _Wires) -> None:
404
+ """Add the two adders and the choosers that decide `pc`, `ir` and `phase`.
405
+
406
+ `JMP` and `CALL` take the 12-bit address from `ir`; `RET` takes the
407
+ return address from `ram.out`, which is safe because `pc` is a
408
+ register and nothing writes the RAM on a `RET` beat.
409
+ """
410
+ ir, pc = self._ir.q, self._pc.q
411
+ with c.scope("pc_plus_1"):
412
+ plus_one, _ = ripple_adder(c, pc, _constant(c, 0, WORD_BITS), c.high)
413
+ with c.scope("branch_target"):
414
+ target, _ = ripple_adder(c, pc, sign_extend(c, _field(ir, 0, OFF9_BITS)), c.low)
415
+ with c.scope("next_pc"):
416
+ jump_to = (*_field(ir, 0, ADDR12_BITS), *_constant(c, 0, WORD_BITS - ADDR12_BITS))
417
+ line = w.line
418
+ jumps = or_(c, line[Opcode.JMP], line[Opcode.CALL])
419
+ elsewhere = mux_bus(c, jumps, target, jump_to)
420
+ elsewhere = mux_bus(c, line[Opcode.RET], elsewhere, self._ram.out)
421
+ moves = or_many(c, [jumps, line[Opcode.RET], and_(c, line[Opcode.BR], w.met)])
422
+ pc_load = and_(c, w.go, or_(c, w.fetch, moves))
423
+ next_pc = mux_bus(c, w.execute, plus_one, elsewhere)
424
+ self._feed(c, "pc", pc_load, next_pc)
425
+ self._feed(c, "ir", and_(c, w.go, w.fetch))
426
+ self._feed(c, "phase", w.go, (w.fetch,))
427
+ self._tap(
428
+ "cpu.next_pc",
429
+ {
430
+ "pc": pc,
431
+ "pc_plus_1": plus_one,
432
+ "branch_target": target,
433
+ "jump_to": jump_to,
434
+ "memory": self._ram.out,
435
+ },
436
+ {"next_pc": next_pc, "load": (pc_load,)},
437
+ self._build_next_pc,
438
+ )
439
+
440
+ def _build_write_back(self, c: Circuit, w: _Wires) -> None:
441
+ """Add the choosers for what goes into `rd`, `sp` and the RAM, and their load wires."""
442
+ line = w.line
443
+ with c.scope("write_back"):
444
+ from_ram = or_(c, line[Opcode.LOAD], line[Opcode.POP])
445
+ value = mux_bus(c, from_ram, w.out.result, self._ram.out)
446
+ value = mux_bus(c, line[Opcode.LI], value, (*w.imm8, *_constant(c, 0, IMM8_BITS)))
447
+ value = mux_bus(c, line[Opcode.LHI], value, (*w.bank.a[:IMM8_BITS], *w.imm8))
448
+ value = mux_bus(c, line[Opcode.GETSP], value, self._sp.q)
449
+ _drive(c, value, w.write_back)
450
+ writers = [
451
+ Opcode.ALU,
452
+ Opcode.LI,
453
+ Opcode.LHI,
454
+ Opcode.LOAD,
455
+ Opcode.POP,
456
+ Opcode.GETSP,
457
+ Opcode.ADDI,
458
+ ]
459
+ loads_rd = or_many(c, [line[o] for o in writers])
460
+ write = and_(c, w.act, loads_rd)
461
+ _drive(c, (write,), (w.register_write,))
462
+ sets_flags = or_many(c, [line[Opcode.ALU], line[Opcode.CMP], line[Opcode.ADDI]])
463
+ out = w.out
464
+ flags = (out.zero, out.negative, out.carry, out.overflow)
465
+ self._feed(c, "flags", and_(c, w.act, sets_flags), flags)
466
+ with c.scope("next_sp"):
467
+ moved = mux_bus(c, w.pops, w.sp_down, w.sp_up)
468
+ sp_value = mux_bus(c, line[Opcode.SETSP], moved, w.bank.b)
469
+ sp_load = or_many(c, [w.pushes, w.pops, line[Opcode.SETSP]])
470
+ sp_write = and_(c, w.act, sp_load)
471
+ self._feed(c, "sp", sp_write, sp_value)
472
+ rd = _field(self._ir.q, RD_SHIFT, FIELD_BITS)
473
+ self._tap(
474
+ "cpu.write_back",
475
+ {
476
+ "alu": w.out.result,
477
+ "memory": self._ram.out,
478
+ "imm8": w.imm8,
479
+ "register_a": w.bank.a,
480
+ "sp": self._sp.q,
481
+ "destination": rd,
482
+ },
483
+ {"value": value, "write": (write,)},
484
+ self._build_write_back,
485
+ )
486
+ self._tap(
487
+ "cpu.next_sp",
488
+ {
489
+ "sp": self._sp.q,
490
+ "sp_minus_1": w.sp_down,
491
+ "sp_plus_1": w.sp_up,
492
+ "register": w.bank.b,
493
+ },
494
+ {"next_sp": sp_value, "load": (sp_write,)},
495
+ self._build_write_back,
496
+ )
497
+ with c.scope("ram_data"):
498
+ # CALL writes the return address (pc); STORE and PUSH write window b.
499
+ w.ram_data = mux_bus(c, line[Opcode.CALL], w.bank.b, self._pc.q)
500
+ writes = or_(c, line[Opcode.STORE], w.pushes)
501
+ w.ram_write = and_(c, w.act, and_(c, writes, not_(c, w.outside)))
502
+
503
+ @property
504
+ def phase(self) -> Phase:
505
+ """Return which beat comes next: `Phase.FETCH` or `Phase.EXECUTE`."""
506
+ return Phase(self._phase.peek(self.simulator))
507
+
508
+ def _is_halted(self) -> bool:
509
+ """Return True when the `halted` register holds 1."""
510
+ return self._halted.peek(self.simulator) == 1
511
+
512
+ @property
513
+ def at_boundary(self) -> bool:
514
+ """Return True when no instruction is part-way through (always, once halted)."""
515
+ return self._stage == 0 and (self._is_halted() or self.phase == Phase.FETCH)
516
+
517
+ def load_state(self, state: MachineState) -> None:
518
+ """Replace the whole machine with `state`, writing straight into its storage.
519
+
520
+ The clock wires drop to 0 first, so no beat is half way through. `ir`
521
+ and `phase` are set to 0, so the next beat is a fetch.
522
+
523
+ Raises:
524
+ ValueError: If the state does not fit this machine, by the same rules
525
+ as the fast engine (`validate_state`). The machine is left unchanged.
526
+
527
+ """
528
+ validate_state(state, self.words)
529
+ sim = self.simulator
530
+ sim.set(self._clock.clk, 0)
531
+ sim.set(self._clock.write, 0)
532
+ sim.settle()
533
+ self._phase.poke(sim, Phase.FETCH)
534
+ self._ir.poke(sim, 0)
535
+ self._pc.poke(sim, state.pc)
536
+ self._sp.poke(sim, state.sp)
537
+ self._flags.poke(sim, sum(flag << bit for bit, flag in enumerate(state.flags)))
538
+ self._halted.poke(sim, int(state.halted))
539
+ self._halt_code.poke(sim, state.halt_code)
540
+ for register, value in zip(self._registers, state.registers, strict=True):
541
+ register.poke(sim, value)
542
+ self._ram.load(sim, state.memory)
543
+ self._output = list(state.output)
544
+ self._stage = 0
545
+ self._cycle_phase = Phase.FETCH
546
+
547
+ def state(self) -> MachineState:
548
+ """Read the whole machine into a frozen `MachineState`, using `peek`."""
549
+ sim = self.simulator
550
+ flags = self._flags.peek(sim)
551
+ return MachineState(
552
+ pc=self._pc.peek(sim),
553
+ sp=self._sp.peek(sim),
554
+ registers=tuple(register.peek(sim) for register in self._registers),
555
+ flags=Flags(*((flags >> bit) & 1 for bit in range(FLAG_COUNT))),
556
+ memory=tuple(self._ram.peek(sim, address) for address in range(self.words)),
557
+ halted=self._is_halted(),
558
+ halt_code=self._halt_code.peek(sim),
559
+ output=tuple(self._output),
560
+ )
561
+
562
+ def load_program(self, words: Sequence[int]) -> None:
563
+ """Power on, then put `words` into memory starting at address 0.
564
+
565
+ Raises:
566
+ ValueError: If the program is bigger than memory or holds a non-word.
567
+
568
+ """
569
+ self.load_state(program_state(words, self.words))
570
+
571
+ def _edge(self) -> MicroStep:
572
+ """Move the clock wire this stage names, and listen to the port on `write`'s rise.
573
+
574
+ The screen is outside the CPU: at the moment the `write` pulse starts it
575
+ looks at the real `port_write` wire and, if it is 1, takes the word on
576
+ the store data wires, the way a terminal reads a cable.
577
+ """
578
+ name, value = _EDGES[(self._stage - 1) // 2]
579
+ sim = self.simulator
580
+ if self._stage == WRITE_RISE and sim.get(self.port_write):
581
+ self._output.append(sim.get_bus(self.port_data))
582
+ wire = self._clock.write if name == "write" else self._clock.clk
583
+ sim.set(wire, value)
584
+ self._stage += 1
585
+ return MicroStep("edge", NOTHING_WAITING, name, value, self._cycle_phase)
586
+
587
+ def step_cycle(self) -> None:
588
+ """Finish the current clock cycle (one beat), or play a whole one from its start.
589
+
590
+ This follows `Simulator.tick`: settle, `write` up and down, `clk` up and
591
+ down, settling after each. A halted machine at a boundary does nothing.
592
+ """
593
+ if self._stage == 0:
594
+ if self._is_halted():
595
+ return
596
+ self._cycle_phase = self.phase
597
+ while True:
598
+ if self._stage % 2:
599
+ self._edge()
600
+ continue
601
+ self.simulator.settle()
602
+ if self._stage == LAST_STAGE:
603
+ self._stage = 0
604
+ return
605
+ self._stage += 1
606
+
607
+ def step(self) -> bool:
608
+ """Run one whole instruction (two beats); return False if already halted."""
609
+ if self.at_boundary and self._is_halted():
610
+ return False
611
+ self.step_cycle()
612
+ while not self.at_boundary:
613
+ self.step_cycle()
614
+ return True
615
+
616
+ def micro_step(self) -> MicroStep:
617
+ """Do one tiny thing: evaluate one gate, or move one clock wire.
618
+
619
+ The order is exactly `Simulator.tick`'s, for the fetch beat and then the
620
+ execute beat. When an instruction has just finished, the step is of
621
+ kind `"end"`; a halted machine only ever returns `"end"`.
622
+ """
623
+ if self._stage == 0:
624
+ if self._is_halted():
625
+ return MicroStep("end", NOTHING_WAITING, "", 0, self.phase)
626
+ self._cycle_phase = self.phase
627
+ sim = self.simulator
628
+ while True:
629
+ if self._stage % 2:
630
+ return self._edge()
631
+ gate = sim.step()
632
+ if gate != NOTHING_WAITING:
633
+ output = sim.get(self._gate_outputs[gate])
634
+ return MicroStep("gate", gate, "", output, self._cycle_phase)
635
+ if self._stage < LAST_STAGE:
636
+ self._stage += 1
637
+ continue
638
+ self._stage = 0
639
+ if self.at_boundary:
640
+ return MicroStep("end", NOTHING_WAITING, "", 0, self._cycle_phase)
641
+ self._cycle_phase = self.phase
642
+
643
+ def run(self, max_steps: int) -> int:
644
+ """Step until the machine halts or `max_steps` steps are taken; return the count."""
645
+ steps = 0
646
+ while steps < max_steps and self.step():
647
+ steps += 1
648
+ return steps