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
@@ -0,0 +1,470 @@
1
+ """The Cockpit's picture: the dials the pilot reads, as plain JSON-ready data.
2
+
3
+ Think of the instrument panel in a cockpit: it does not fly the plane, it only shows
4
+ what the plane is doing right now. This module reads the paused computer in a
5
+ `Cockpit` session and lays its registers, memory, current instruction and Pebble
6
+ line out as a dictionary the page can draw. Everything is read, nothing is changed.
7
+ """
8
+
9
+ from typing import cast
10
+
11
+ from pycpu.assembler import disassemble
12
+ from pycpu.cockpit.code import built_by, page_link
13
+ from pycpu.cockpit.session import BUSY_MESSAGE, Cockpit, CockpitBusy
14
+ from pycpu.cockpit.walks import walk_named
15
+ from pycpu.computer import Computer
16
+ from pycpu.cpu import GateMachine
17
+ from pycpu.isa import Fault, Opcode, decode
18
+ from pycpu.state import WORD_BITS, MachineState
19
+ from pycpu.translator import FRAME_POINTER, PebbleRun, TranslatedProgram
20
+
21
+ WINDOW_WORDS = 16 # how many words of memory the page shows
22
+ WINDOW_BEHIND = 4 # how many of them sit before pc
23
+ STACK_CELLS = 16 # how many words of the stack the page shows, from sp upwards
24
+ _SIGN_BIT = 1 << (WORD_BITS - 1)
25
+
26
+ # Which part of the circuit does the main work of each kind of instruction.
27
+ _PART_FOR_OPCODE = {
28
+ Opcode.ALU: "cpu.alu",
29
+ Opcode.CMP: "cpu.alu",
30
+ Opcode.ADDI: "cpu.alu",
31
+ Opcode.LI: "cpu.write_back",
32
+ Opcode.LHI: "cpu.write_back",
33
+ Opcode.LOAD: "cpu.address_mux",
34
+ Opcode.STORE: "cpu.address_mux",
35
+ Opcode.JMP: "cpu.next_pc",
36
+ Opcode.BR: "cpu.next_pc",
37
+ Opcode.CALL: "cpu.next_pc",
38
+ Opcode.RET: "cpu.next_pc",
39
+ Opcode.PUSH: "cpu.next_sp",
40
+ Opcode.POP: "cpu.next_sp",
41
+ Opcode.GETSP: "cpu.next_sp",
42
+ Opcode.SETSP: "cpu.next_sp",
43
+ Opcode.HALT: "cpu.halt",
44
+ }
45
+
46
+ # What the page calls each part in its Step button, for every part above and the whole CPU.
47
+ PART_NAMES = {
48
+ "cpu.alu": "ALU",
49
+ "cpu.write_back": "write-back",
50
+ "cpu.address_mux": "memory address",
51
+ "cpu.next_pc": "next-instruction",
52
+ "cpu.next_sp": "stack pointer",
53
+ "cpu.halt": "halt",
54
+ "cpu.registers": "registers",
55
+ "ram": "RAM",
56
+ "cpu": "CPU",
57
+ }
58
+
59
+
60
+ def gate_path(gate: GateMachine, part: str) -> str:
61
+ """Name the part of the circuit whose gates make `part`'s outputs, for the gate zoom.
62
+
63
+ Like the label on a fuse box saying which room each switch lights: a part's name
64
+ and the room its gates sit in are nearly always the same. The halt part is the odd
65
+ one: its wires are made in the `fault` block, next to it (`cpu.fault`), while
66
+ `cpu.halt` holds only the two registers that remember the answer. So when a part's
67
+ builder recorded a block name, the gates are that block, beside the part.
68
+
69
+ Args:
70
+ gate: The gate machine whose builders were recorded as it was wired up.
71
+ part: A part's scope path, such as `"cpu.halt"`, or any other path.
72
+
73
+ Returns:
74
+ The scope path to zoom to: `"cpu.fault"` for `"cpu.halt"`, else `part` itself.
75
+
76
+ """
77
+ _builder, scope = gate.builders.get(part, (None, None))
78
+ if not scope:
79
+ return part
80
+ parent = part.rpartition(".")[0]
81
+ return f"{parent}.{scope}" if parent else scope
82
+
83
+
84
+ def part_picture(cockpit: Cockpit, path: str) -> dict[str, object]:
85
+ """Describe one part of the CPU by what goes into it and what comes out, right now.
86
+
87
+ Like a meter clipped onto the cables of a machine: each value is a row of the
88
+ part's real wires (its tap in `GateMachine.taps`), read one wire at a time with
89
+ `simulator.get` and added up, lowest bit first. Nothing is worked out here.
90
+
91
+ Args:
92
+ cockpit: The paused session to read.
93
+ path: The part's scope path, such as `"cpu.alu"`.
94
+
95
+ Returns:
96
+ `path`, `name` (from `PART_NAMES`), and `inputs` and `outputs`, each a list
97
+ of `{"name", "value"}` in the order the CPU's builder recorded them,
98
+ `gates`: the scope that holds the gates making its outputs (see `gate_path`),
99
+ and `built_by`: the live source of the code that built the part (see
100
+ `code.built_by`).
101
+
102
+ Raises:
103
+ KeyError: If the part has no taps (an unknown path, or the whole `cpu`).
104
+ CockpitBusy: If the session is playing: the gates stand still then, so
105
+ there are no live wires to read.
106
+
107
+ """
108
+ gate = cockpit.computer.gate
109
+ if path not in gate.taps:
110
+ raise KeyError(path)
111
+ if cockpit.playing:
112
+ raise CockpitBusy(BUSY_MESSAGE)
113
+ sim = gate.simulator
114
+ outputs = gate.tap_outputs[path]
115
+ inputs_seen: list[dict[str, object]] = []
116
+ outputs_seen: list[dict[str, object]] = []
117
+ for name, bus in gate.taps[path].items():
118
+ value = sum(sim.get(wire) << bit for bit, wire in enumerate(bus))
119
+ (outputs_seen if name in outputs else inputs_seen).append({"name": name, "value": value})
120
+ return {
121
+ "path": path,
122
+ "name": PART_NAMES[path],
123
+ "inputs": inputs_seen,
124
+ "outputs": outputs_seen,
125
+ "gates": gate_path(gate, path),
126
+ "built_by": built_by(gate, path),
127
+ }
128
+
129
+
130
+ def _cell(state: MachineState, address: int) -> dict[str, object]:
131
+ """Describe one word of memory as its address, its number and its assembly text."""
132
+ word = state.memory[address]
133
+ return {
134
+ "address": address,
135
+ "word": word,
136
+ "text": disassemble(word, address),
137
+ "part": f"ram.word{address}",
138
+ }
139
+
140
+
141
+ def part_for_instruction(word: int) -> str:
142
+ """Name the part of the circuit that does the main work of the instruction `word`.
143
+
144
+ Args:
145
+ word: A 16-bit machine word. Every word decodes to some instruction.
146
+
147
+ Returns:
148
+ A scope path such as `"cpu.alu"` for an add, or `"cpu.next_pc"` for a jump.
149
+
150
+ """
151
+ return _PART_FOR_OPCODE[decode(word).opcode]
152
+
153
+
154
+ def _changed(before: MachineState, now: MachineState) -> dict[str, object]:
155
+ """List what differs between two states: registers, pc, sp, flags and memory words.
156
+
157
+ Memory is compared with a plain scan over both tuples. That is fine at 4K words
158
+ (measured at about 0.3 ms; a slow test pins it under 0.05 s at full size), so there is
159
+ no need for anything cleverer such as remembering which words were written.
160
+ """
161
+ registers = [
162
+ i for i, (a, b) in enumerate(zip(before.registers, now.registers, strict=True)) if a != b
163
+ ]
164
+ flags = [
165
+ name
166
+ for name, a, b in zip(now.flags._fields, before.flags, now.flags, strict=True)
167
+ if a != b
168
+ ]
169
+ memory = [i for i, (a, b) in enumerate(zip(before.memory, now.memory, strict=True)) if a != b]
170
+ return {
171
+ "registers": registers,
172
+ "pc": before.pc != now.pc,
173
+ "sp": before.sp != now.sp,
174
+ "flags": flags,
175
+ "memory": memory,
176
+ }
177
+
178
+
179
+ def _stack(state: MachineState) -> list[dict[str, object]]:
180
+ """Describe up to 16 words of the stack, from sp upwards (the top first)."""
181
+ return [
182
+ _cell(state, a) for a in range(state.sp, min(state.sp + STACK_CELLS, len(state.memory)))
183
+ ]
184
+
185
+
186
+ def _signed(word: int) -> int:
187
+ """Read a 16-bit word as a signed number, the way Pebble's code means it (65535 is -1)."""
188
+ return word - (_SIGN_BIT << 1) if word & _SIGN_BIT else word
189
+
190
+
191
+ def variables_picture(
192
+ translated: TranslatedProgram | None,
193
+ start: MachineState,
194
+ now: MachineState | None = None,
195
+ ) -> dict[str, object] | None:
196
+ """Describe the Pebble names of the running code: each one's address and value.
197
+
198
+ The frame is the one of the instruction that started in `start` (its `pc`), found
199
+ in `translated.frames`, and `r7` says where that frame sits. Each name lives at `r7`
200
+ plus its slot's offset; a name whose address falls outside memory is left out.
201
+ The frame and `r7` come from `start`, because part-way through an epilogue's
202
+ `pop r7` the register has already moved on to the caller's frame. Each value is
203
+ read from `now`, so that part-way through a store the variable agrees with the
204
+ memory pane and its changed mark.
205
+
206
+ Args:
207
+ translated: The Pebble program, or None for assembly.
208
+ start: The state at the start of the current instruction.
209
+ now: The state to read each name's word from; `start` when None.
210
+
211
+ Returns:
212
+ `function` (None for the top level), `frame_pointer` and `names`, or None for
213
+ assembly, or when the current word has no ready frame (a prologue, a return's
214
+ `ret`, or a runtime routine).
215
+
216
+ """
217
+ if translated is None or not 0 <= start.pc < len(translated.frames):
218
+ return None
219
+ layout = translated.frames[start.pc]
220
+ if layout is None:
221
+ return None
222
+ pointer = start.registers[FRAME_POINTER]
223
+ memory = start.memory if now is None else now.memory
224
+ names: list[dict[str, object]] = []
225
+ for slot in layout.slots:
226
+ address = pointer + slot.offset
227
+ if not 0 <= address < len(memory):
228
+ continue
229
+ word = memory[address]
230
+ names.append(
231
+ {
232
+ "name": slot.name,
233
+ "kind": slot.kind,
234
+ "hidden": slot.hidden,
235
+ "address": address,
236
+ "word": word,
237
+ "value": _signed(word),
238
+ "part": f"ram.word{address}",
239
+ }
240
+ )
241
+ return {"function": layout.function, "frame_pointer": pointer, "names": names}
242
+
243
+
244
+ def _last_gate(cockpit: Cockpit) -> dict[str, object] | None:
245
+ """Describe the last gate step: which gate, the part it lives in, and its new output.
246
+
247
+ A clock edge or an instruction's end is not a gate thinking, so those give None.
248
+ """
249
+ micro = cockpit.last_gate
250
+ if micro is None or micro.kind != "gate":
251
+ return None
252
+ circuit = cockpit.computer.gate.simulator.circuit
253
+ return {"id": micro.gate, "path": circuit.scope_of(micro.gate), "value": micro.value}
254
+
255
+
256
+ def walk_picture(cockpit: Cockpit) -> dict[str, object] | None:
257
+ """Describe the walk the learner is on, for the page to drive the glass and say its words.
258
+
259
+ Returns:
260
+ None with no walk, else `name`, `title`, `step`, `count` (how many steps it
261
+ has), and for that step `say`, `look` and `show`. At the "Now you try" stage
262
+ (`step == count`) `trying` is true, `say` is None, and `look` and `show` are
263
+ the try's, and `step_kind` is the try's `step` (`"into"` when the page should
264
+ offer Step into; None otherwise, and always None before the try). `task` is
265
+ always the try's task, and `done` and `off_script` come from the session's
266
+ `WalkProgress`. `see_also` is the `title` and `url` of the concept page that
267
+ explains the walk's idea, on the docs server on your own computer.
268
+
269
+ """
270
+ progress = cockpit.walk
271
+ walk = None if progress is None else walk_named(progress.name)
272
+ if progress is None or walk is None:
273
+ return None
274
+ count = len(walk.steps)
275
+ trying = progress.step >= count
276
+ if trying:
277
+ say, look, show, kind = None, walk.trial.look, walk.trial.show, walk.trial.step
278
+ else:
279
+ here = walk.steps[progress.step]
280
+ say, look, show, kind = here.say, here.look, here.show, None
281
+ return {
282
+ "name": walk.name,
283
+ "title": walk.title,
284
+ "step": progress.step,
285
+ "count": count,
286
+ "say": say,
287
+ "look": str(look),
288
+ "show": show,
289
+ "step_kind": kind,
290
+ "trying": trying,
291
+ "task": walk.trial.task,
292
+ "done": progress.done,
293
+ "off_script": progress.off_script,
294
+ "see_also": page_link(walk.see_also),
295
+ }
296
+
297
+
298
+ def listing(cockpit: Cockpit) -> dict[str, object]:
299
+ """Describe the whole loaded program, one row for each word of machine code.
300
+
301
+ Each row has its `address`, `word`, `text`, `first` (true for the first word that
302
+ came from its source line, since a line such as `set` makes two), the `labels` that
303
+ mark this address, and `pebble_line` (the Pebble line that made the word, or None
304
+ for assembly and runtime words).
305
+ The `text` is the source line the word came from, as the program was written
306
+ (a word made by `set` shows the `set` line, not the `li` it became).
307
+
308
+ Args:
309
+ cockpit: The session whose program to list.
310
+
311
+ Returns:
312
+ `rows`; `pebble`, the Pebble source as a list of lines, or None for assembly;
313
+ and `program`, the session's load count, which the picture carries too.
314
+
315
+ """
316
+ program, translated = cockpit.program, cockpit.translated
317
+ source = cockpit.assembly.splitlines()
318
+ names: dict[int, list[str]] = {}
319
+ for name, address in program.labels.items():
320
+ names.setdefault(address, []).append(name)
321
+ rows: list[dict[str, object]] = []
322
+ for address, (word, line) in enumerate(zip(program.words, program.lines, strict=True)):
323
+ text = source[line - 1].strip() if 0 < line <= len(source) else ""
324
+ rows.append(
325
+ {
326
+ "address": address,
327
+ "word": word,
328
+ "text": text,
329
+ "first": address == 0 or program.lines[address - 1] != line,
330
+ "labels": names.get(address, []),
331
+ "pebble_line": None if translated is None else translated.line_at(address),
332
+ }
333
+ )
334
+ pebble = None if translated is None else translated.source.splitlines()
335
+ return {"rows": rows, "pebble": pebble, "program": cockpit.loads}
336
+
337
+
338
+ def pebble_picture(
339
+ computer: Computer,
340
+ translated: TranslatedProgram,
341
+ *,
342
+ state: MachineState | None = None,
343
+ start_pc: int | None = None,
344
+ ) -> dict[str, object]:
345
+ """Describe the Pebble program on the Cockpit: its lines and the one running now.
346
+
347
+ The running line is the Pebble line of the current instruction, the one that
348
+ started at `instruction_start.pc` (half way through an instruction `pc` has moved
349
+ on). It is None inside the ready-made runtime routines, which belong to no line.
350
+ Once the machine has halted nothing runs next, so the line is the one a fault is
351
+ blamed on (None after a normal finish), and `message` says how the run ended in
352
+ one sentence, such as "Division by zero at line 2". Before that `message` is None.
353
+
354
+ Args:
355
+ computer: The paused computer running the program.
356
+ translated: The program it is running, with its source map.
357
+ state: The state to describe; the computer's own when None.
358
+ start_pc: The address the current instruction started at; the computer's
359
+ `instruction_start.pc` when None.
360
+
361
+ Returns:
362
+ `source` (a list of the Pebble lines), `line` and `message`.
363
+
364
+ """
365
+ state = computer.state() if state is None else state
366
+ if start_pc is None:
367
+ start_pc = computer.instruction_start.pc
368
+ if state.halted:
369
+ # steps=0 is not a count: the Cockpit does not count instructions, and a halted
370
+ # run's sentence never mentions one.
371
+ ended = PebbleRun.from_state(translated, state, steps=0)
372
+ line, message = ended.line, ended.describe()
373
+ else:
374
+ line, message = translated.line_at(start_pc), None
375
+ return {"source": translated.source.splitlines(), "line": line, "message": message}
376
+
377
+
378
+ def machine_picture(cockpit: Cockpit) -> dict[str, object]:
379
+ """Describe the paused computer the way the Cockpit page draws it.
380
+
381
+ Everything is read from the gate engine while paused (and from the fast engine
382
+ while the session is playing, when `phase` is always `"fetch"` and `last_gate`
383
+ is None). `changed` marks what differs from the state before the last move,
384
+ `stack` lists up to 16 words from `sp` up, `last_gate` names the last gate step,
385
+ and `parts` gives the circuit path to zoom to for each value. The current instruction
386
+ is the one that started at `instruction_start.pc`, read from memory as it was
387
+ then, because half way through an instruction `pc` has already moved on. When
388
+ that address is outside memory (a fetch fault) its word is None and its text
389
+ is empty. The memory window holds 16 words, starting 4 before `pc` (or at 0), and
390
+ slides back so it never runs past the last word: a `pc` far outside memory still
391
+ shows the final 16 words. `fault` is the name of the `Fault` (such as
392
+ `"BAD_ADDRESS"`) when the machine has halted with one of those codes, else None;
393
+ a program's own `halt 1` to `halt 3` shares those codes. `pebble` is the
394
+ `pebble_picture` when the program came from Pebble, and None for assembly.
395
+ `variables` is the `variables_picture` of the current instruction (None while
396
+ playing). `steps` is the label of each Step depth, with the part's name taken from
397
+ `PART_NAMES`. `happened` is the "What just happened" sentence for the last move
398
+ (None before any move and after a load). `walk` is the `walk_picture` of the walk the
399
+ learner is on, or None. `program` is the session's load count, so
400
+ the page can tell whether its listing is of the program on the machine.
401
+ `parts["gates"]` maps every part with a part view to the scope its gate zoom shows
402
+ (see `gate_path`).
403
+
404
+ Args:
405
+ cockpit: The session to describe.
406
+
407
+ Returns:
408
+ A dictionary ready to send as JSON; the Cockpit's routes all answer with it.
409
+
410
+ """
411
+ computer = cockpit.computer
412
+ state = computer.state()
413
+ playing = cockpit.playing
414
+ # While playing only the fast engine is live: the gate engine's phase and boundary
415
+ # are stale, and the machine is always between two instructions, about to fetch.
416
+ start = state if playing else computer.instruction_start
417
+ start_pc = state.pc if playing else start.pc
418
+ if start_pc < len(start.memory):
419
+ # The instruction's zoom target is `parts["instruction"]`, so its cell has no `part`.
420
+ instruction = {k: v for k, v in _cell(start, start_pc).items() if k != "part"}
421
+ else:
422
+ instruction = {"address": start_pc, "word": None, "text": ""}
423
+ first = max(0, min(state.pc - WINDOW_BEHIND, len(state.memory) - WINDOW_WORDS))
424
+ last = min(first + WINDOW_WORDS, len(state.memory))
425
+ fault = Fault(state.halt_code).name if state.halted and state.halt_code in Fault else None
426
+ translated = cockpit.translated
427
+ word: int | None = cast("int | None", instruction["word"])
428
+ pebble = None
429
+ if translated is not None:
430
+ pebble = pebble_picture(computer, translated, state=state, start_pc=start_pc)
431
+ instruction_part = "cpu" if word is None else part_for_instruction(word)
432
+ return {
433
+ "paused": computer.paused,
434
+ "running": playing,
435
+ "phase": "fetch" if playing else computer.gate.phase.name.lower(),
436
+ "at_boundary": True if playing else computer.gate.at_boundary,
437
+ "registers": list(state.registers),
438
+ "pc": state.pc,
439
+ "sp": state.sp,
440
+ "flags": state.flags._asdict(),
441
+ "halted": state.halted,
442
+ "halt_code": state.halt_code,
443
+ "fault": fault,
444
+ "output": state.output_text,
445
+ "instruction": instruction,
446
+ "memory": [_cell(state, address) for address in range(first, last)],
447
+ "pebble": pebble,
448
+ "changed": _changed(cockpit.before, state),
449
+ "stack": _stack(state),
450
+ "variables": None if playing else variables_picture(translated, start, state),
451
+ "last_gate": None if playing else _last_gate(cockpit),
452
+ "note": cockpit.note,
453
+ "happened": cockpit.happened,
454
+ "program": cockpit.loads,
455
+ "walk": walk_picture(cockpit),
456
+ "parts": {
457
+ "registers": [f"cpu.registers.r{i}" for i in range(len(state.registers))],
458
+ "pc": "cpu.pc",
459
+ "sp": "cpu.sp",
460
+ "flags": "cpu.flags",
461
+ "instruction": instruction_part,
462
+ "gates": {part: gate_path(computer.gate, part) for part in computer.gate.taps},
463
+ },
464
+ "steps": {
465
+ "line": "Step one line \u25b8",
466
+ "instruction": "Step one instruction \u25b8",
467
+ "part": f"Step one {PART_NAMES[instruction_part]} beat \u25b8",
468
+ "gate": "Step one gate \u25b8",
469
+ },
470
+ }