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/walks.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
"""Guided walks: short tours of the real machine, one sentence at a time.
|
|
2
|
+
|
|
3
|
+
Think of a museum audio guide. It tells you where to stand and what to look at, one
|
|
4
|
+
sentence at a time, and when the tour is over it lets you wander on your own. A walk
|
|
5
|
+
is the Cockpit's audio guide. Each one is a small TOML file in `walks/`: a program,
|
|
6
|
+
a list of steps (a move to make, a sentence to say, a depth for the glass to look at)
|
|
7
|
+
and a last "Now you try" task with a check the server can test on the real machine.
|
|
8
|
+
|
|
9
|
+
This module only reads and checks those files. It turns each action and each check
|
|
10
|
+
into a small value with an explicit grammar (`str.split` and `match`, never `eval`),
|
|
11
|
+
so a typo in a file is a `WalkError` naming the file and the problem. The moves
|
|
12
|
+
themselves are made by the session (`Cockpit.go_to_walk` and `Cockpit.act`), which
|
|
13
|
+
replays a walk from its `start` on the real machine, and never sets any state by hand.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import tomllib
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from functools import cache
|
|
19
|
+
from importlib import resources
|
|
20
|
+
|
|
21
|
+
from pycpu.cockpit.explain import Depth
|
|
22
|
+
from pycpu.state import WORD_BITS, MachineState
|
|
23
|
+
from pycpu.translator import FRAME_POINTER, TranslatedProgram
|
|
24
|
+
|
|
25
|
+
# The five walks, in the order the page lists them, matching the ideas in the spec.
|
|
26
|
+
WALK_ORDER = (
|
|
27
|
+
"many-instructions",
|
|
28
|
+
"where-n-lives",
|
|
29
|
+
"subtracting-with-gates",
|
|
30
|
+
"a-call-and-the-stack",
|
|
31
|
+
"why-the-clock-ticks",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# What a step may highlight on the page: a key (or a key inside a key) of the picture.
|
|
35
|
+
SHOW_TARGETS = (
|
|
36
|
+
"pebble.line",
|
|
37
|
+
"variables",
|
|
38
|
+
"registers",
|
|
39
|
+
"memory",
|
|
40
|
+
"stack",
|
|
41
|
+
"output",
|
|
42
|
+
"instruction",
|
|
43
|
+
"flags",
|
|
44
|
+
"last_gate",
|
|
45
|
+
"happened",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
_SIGN_BIT = 1 << (WORD_BITS - 1)
|
|
49
|
+
_WALK_KEYS = frozenset({"title", "example", "source", "see_also", "steps", "try"})
|
|
50
|
+
_STEP_KEYS = frozenset({"say", "do", "look", "show"})
|
|
51
|
+
_TRY_KEYS = frozenset({"task", "look", "check", "solution", "show", "step"})
|
|
52
|
+
TRY_STEP_KINDS = ("into",) # the kinds of Step a try may ask the page to offer
|
|
53
|
+
_DEPTHS = ", ".join(d.value for d in Depth)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class WalkError(ValueError):
|
|
57
|
+
"""Say that a walk file, or one action or check in it, is not right, and why."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class Start:
|
|
62
|
+
"""Load the walk's program and pause at its start."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class StepAt:
|
|
67
|
+
"""Press Step once at `depth`, exactly as the learner's Step button does."""
|
|
68
|
+
|
|
69
|
+
depth: Depth
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class StepLineInto:
|
|
74
|
+
"""Press Step into once at line depth: a line step that follows a call into a function."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class RunToLine:
|
|
79
|
+
"""Run on the fast engine until Pebble line `line` is about to start, then pause."""
|
|
80
|
+
|
|
81
|
+
line: int
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class RunInstructions:
|
|
86
|
+
"""Press Run for `count` instructions: the fast engine runs them, then pauses."""
|
|
87
|
+
|
|
88
|
+
count: int
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class StepGateUntil:
|
|
93
|
+
"""Take gate steps until a gate inside the part `prefix` (a scope path) works."""
|
|
94
|
+
|
|
95
|
+
prefix: str
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
type Action = Start | StepAt | StepLineInto | RunToLine | RunInstructions | StepGateUntil
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class VariableIs:
|
|
103
|
+
"""Pass when the Pebble variable `name` of the running code holds `value`."""
|
|
104
|
+
|
|
105
|
+
name: str
|
|
106
|
+
value: int
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class LineIs:
|
|
111
|
+
"""Pass when Pebble line `line` is the one running."""
|
|
112
|
+
|
|
113
|
+
line: int
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class RegisterIs:
|
|
118
|
+
"""Pass when register `r<index>` holds `value`."""
|
|
119
|
+
|
|
120
|
+
index: int
|
|
121
|
+
value: int
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class OutputContains:
|
|
126
|
+
"""Pass when the screen shows `text` somewhere."""
|
|
127
|
+
|
|
128
|
+
text: str
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True)
|
|
132
|
+
class Halted:
|
|
133
|
+
"""Pass once the program has stopped."""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
type Check = VariableIs | LineIs | RegisterIs | OutputContains | Halted
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class WalkStep:
|
|
141
|
+
"""One step of a walk: the move to make, the sentence to say, and where to look.
|
|
142
|
+
|
|
143
|
+
Attributes:
|
|
144
|
+
say: The one sentence the page shows for this step.
|
|
145
|
+
action: The move that takes the machine to this step, from the step before.
|
|
146
|
+
look: The depth the glass shows.
|
|
147
|
+
show: What the page highlights (one of `SHOW_TARGETS`), or None.
|
|
148
|
+
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
say: str
|
|
152
|
+
action: Action
|
|
153
|
+
look: Depth
|
|
154
|
+
show: str | None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(frozen=True)
|
|
158
|
+
class WalkTry:
|
|
159
|
+
"""A walk's "Now you try": a task, the check that says it is done, and a solution.
|
|
160
|
+
|
|
161
|
+
Attributes:
|
|
162
|
+
task: The one sentence that tells the learner what to do.
|
|
163
|
+
look: The depth the glass shows while trying.
|
|
164
|
+
check: The test, on the real machine, that the task is done.
|
|
165
|
+
solution: Moves that do the task, so a test can prove it can be done.
|
|
166
|
+
show: What the page highlights while trying, or None.
|
|
167
|
+
step: `"into"` when the page should offer Step into (a line step that
|
|
168
|
+
follows calls) for this task, else None for the plain Step.
|
|
169
|
+
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
task: str
|
|
173
|
+
look: Depth
|
|
174
|
+
check: Check
|
|
175
|
+
solution: tuple[Action, ...]
|
|
176
|
+
show: str | None
|
|
177
|
+
step: str | None = None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass(frozen=True)
|
|
181
|
+
class Walk:
|
|
182
|
+
"""One guided walk, read from its file.
|
|
183
|
+
|
|
184
|
+
Attributes:
|
|
185
|
+
name: The file's name without `.toml`, such as `"many-instructions"`.
|
|
186
|
+
title: The walk's title, the idea it teaches.
|
|
187
|
+
source: The Pebble program it runs (an example's text, or its own).
|
|
188
|
+
see_also: The concept page (without `.md`) that explains the same idea.
|
|
189
|
+
steps: Its steps; the first is always `start`.
|
|
190
|
+
trial: Its "Now you try".
|
|
191
|
+
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
name: str
|
|
195
|
+
title: str
|
|
196
|
+
source: str
|
|
197
|
+
see_also: str
|
|
198
|
+
steps: tuple[WalkStep, ...]
|
|
199
|
+
trial: WalkTry
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _whole(text: str, what: str) -> int:
|
|
203
|
+
"""Read `text` as a whole number (it may start with a minus), or raise a `WalkError`."""
|
|
204
|
+
digits = text.removeprefix("-")
|
|
205
|
+
if not digits.isdigit():
|
|
206
|
+
msg = f"{what} must be a whole number, not {text!r}"
|
|
207
|
+
raise WalkError(msg)
|
|
208
|
+
return int(text)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _depth(text: object, where: str) -> Depth:
|
|
212
|
+
"""Read `text` as a depth, or raise a `WalkError` listing the depths."""
|
|
213
|
+
if text not in tuple(Depth):
|
|
214
|
+
msg = f"{where} must be one of {_DEPTHS}, not {text!r}"
|
|
215
|
+
raise WalkError(msg)
|
|
216
|
+
return Depth(str(text))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def parse_action(text: str) -> Action:
|
|
220
|
+
"""Read one action, such as `"step line"` or `"run to line 5"`.
|
|
221
|
+
|
|
222
|
+
The actions are `start`, `step <depth>`, `step line into`, `run to line <n>`,
|
|
223
|
+
`run <n> instructions` and `step gate until <scope prefix>`.
|
|
224
|
+
|
|
225
|
+
Raises:
|
|
226
|
+
WalkError: If the text is none of those.
|
|
227
|
+
|
|
228
|
+
"""
|
|
229
|
+
match text.split():
|
|
230
|
+
case ["start"]:
|
|
231
|
+
return Start()
|
|
232
|
+
case ["step", "line", "into"]:
|
|
233
|
+
return StepLineInto()
|
|
234
|
+
case ["step", "gate", "until", prefix]:
|
|
235
|
+
return StepGateUntil(prefix)
|
|
236
|
+
case ["step", depth]:
|
|
237
|
+
return StepAt(_depth(depth, "the depth in a step"))
|
|
238
|
+
case ["run", "to", "line", line]:
|
|
239
|
+
number = _whole(line, "the line in run to line")
|
|
240
|
+
if number < 1:
|
|
241
|
+
msg = f"run to line needs a line from 1 up, not {number}"
|
|
242
|
+
raise WalkError(msg)
|
|
243
|
+
return RunToLine(number)
|
|
244
|
+
case ["run", count, "instructions" | "instruction"]:
|
|
245
|
+
number = _whole(count, "the count in run")
|
|
246
|
+
if number < 1:
|
|
247
|
+
msg = f"run needs at least 1 instruction, not {number}"
|
|
248
|
+
raise WalkError(msg)
|
|
249
|
+
return RunInstructions(number)
|
|
250
|
+
case _:
|
|
251
|
+
msg = f"unknown action {text!r}"
|
|
252
|
+
raise WalkError(msg)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def parse_check(text: str) -> Check:
|
|
256
|
+
"""Read one check, such as `"variable n == 0"` or `'output contains "120"'`.
|
|
257
|
+
|
|
258
|
+
The checks are `variable <name> == <int>`, `line == <int>`,
|
|
259
|
+
`register r<i> == <int>`, `output contains "<text>"` and `halted`.
|
|
260
|
+
|
|
261
|
+
Raises:
|
|
262
|
+
WalkError: If the text is none of those.
|
|
263
|
+
|
|
264
|
+
"""
|
|
265
|
+
match text.split(maxsplit=2):
|
|
266
|
+
case ["halted"]:
|
|
267
|
+
return Halted()
|
|
268
|
+
case ["output", "contains", quoted] if (
|
|
269
|
+
len(quoted) >= 2 # noqa: PLR2004
|
|
270
|
+
and quoted[0] == quoted[-1] == '"'
|
|
271
|
+
):
|
|
272
|
+
return OutputContains(quoted[1:-1])
|
|
273
|
+
case _:
|
|
274
|
+
pass
|
|
275
|
+
match text.split():
|
|
276
|
+
case ["variable", name, "==", value] if name.isidentifier():
|
|
277
|
+
return VariableIs(name, _whole(value, "the value in a variable check"))
|
|
278
|
+
case ["line", "==", value]:
|
|
279
|
+
return LineIs(_whole(value, "the line in a line check"))
|
|
280
|
+
case ["register", register, "==", value] if (
|
|
281
|
+
register.startswith("r") and register[1:].isdigit()
|
|
282
|
+
):
|
|
283
|
+
return RegisterIs(int(register[1:]), _whole(value, "the value in a register check"))
|
|
284
|
+
case _:
|
|
285
|
+
msg = f"unknown check {text!r}"
|
|
286
|
+
raise WalkError(msg)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _signed(word: int) -> int:
|
|
290
|
+
"""Read a 16-bit word as a signed number, the way Pebble's code means it (65535 is -1)."""
|
|
291
|
+
return word - (_SIGN_BIT << 1) if word & _SIGN_BIT else word
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _variable(
|
|
295
|
+
name: str, translated: TranslatedProgram, start: MachineState, now: MachineState
|
|
296
|
+
) -> int | None:
|
|
297
|
+
"""Read the variable `name` of the running code, as the variables pane shows it.
|
|
298
|
+
|
|
299
|
+
The frame is the one of the instruction that started in `start`, and `r7` in
|
|
300
|
+
`start` says where it sits, exactly as `picture.variables_picture` finds it.
|
|
301
|
+
"""
|
|
302
|
+
if not 0 <= start.pc < len(translated.frames):
|
|
303
|
+
return None
|
|
304
|
+
layout = translated.frames[start.pc]
|
|
305
|
+
if layout is None:
|
|
306
|
+
return None
|
|
307
|
+
for slot in layout.slots:
|
|
308
|
+
address = start.registers[FRAME_POINTER] + slot.offset
|
|
309
|
+
if slot.name == name and not slot.hidden and 0 <= address < len(now.memory):
|
|
310
|
+
return _signed(now.memory[address])
|
|
311
|
+
return None
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def passes(
|
|
315
|
+
check: Check, now: MachineState, start: MachineState, translated: TranslatedProgram | None
|
|
316
|
+
) -> bool:
|
|
317
|
+
"""Say whether `check` holds for the machine right now.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
check: The check to test.
|
|
321
|
+
now: The machine's state now.
|
|
322
|
+
start: The state at the start of the current instruction, which says which
|
|
323
|
+
line is running and which frame the variables are in.
|
|
324
|
+
translated: The Pebble program, or None for assembly (no lines, no variables).
|
|
325
|
+
|
|
326
|
+
"""
|
|
327
|
+
match check:
|
|
328
|
+
case Halted():
|
|
329
|
+
return now.halted
|
|
330
|
+
case OutputContains(text):
|
|
331
|
+
return text in now.output_text
|
|
332
|
+
case RegisterIs(index, value):
|
|
333
|
+
return 0 <= index < len(now.registers) and now.registers[index] == value
|
|
334
|
+
case LineIs(line):
|
|
335
|
+
return (
|
|
336
|
+
translated is not None and not now.halted and translated.line_at(start.pc) == line
|
|
337
|
+
)
|
|
338
|
+
case VariableIs(name, value):
|
|
339
|
+
if translated is None or now.halted:
|
|
340
|
+
return False
|
|
341
|
+
return _variable(name, translated, start, now) == value
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def example_source(name: str) -> str | None:
|
|
345
|
+
"""Read the example program called `name` from `examples/`, or None if there is none."""
|
|
346
|
+
path = resources.files("pycpu.cockpit").joinpath("examples").joinpath(f"{name}.pebble")
|
|
347
|
+
return path.read_text(encoding="utf-8") if path.is_file() else None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _text(table: dict[str, object], key: str, where: str) -> str:
|
|
351
|
+
"""Return `table[key]` as non-empty text, or raise a `WalkError` saying it is missing."""
|
|
352
|
+
value = table.get(key)
|
|
353
|
+
if not isinstance(value, str) or not value.strip():
|
|
354
|
+
msg = f"{where} needs {key} as some text"
|
|
355
|
+
raise WalkError(msg)
|
|
356
|
+
return value.strip()
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _show(table: dict[str, object], where: str) -> str | None:
|
|
360
|
+
"""Return the optional `show` of a step or try, checking it is a known target."""
|
|
361
|
+
show = table.get("show")
|
|
362
|
+
if show is None:
|
|
363
|
+
return None
|
|
364
|
+
if show not in SHOW_TARGETS:
|
|
365
|
+
msg = f"{where} has show {show!r}, which is not one of {', '.join(SHOW_TARGETS)}"
|
|
366
|
+
raise WalkError(msg)
|
|
367
|
+
return str(show)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _unknown_keys(table: dict[str, object], allowed: frozenset[str], where: str) -> None:
|
|
371
|
+
"""Refuse keys a walk file has no use for, so a misspelt key is not silently ignored."""
|
|
372
|
+
extra = sorted(set(table) - allowed)
|
|
373
|
+
if extra:
|
|
374
|
+
msg = f"{where} has unknown keys: {', '.join(extra)}"
|
|
375
|
+
raise WalkError(msg)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _source(data: dict[str, object]) -> str:
|
|
379
|
+
"""Return the walk's program: the named example's text, or its own `source`."""
|
|
380
|
+
example, source = data.get("example"), data.get("source")
|
|
381
|
+
if (example is None) == (source is None):
|
|
382
|
+
msg = "the walk needs an example or a source, and not both"
|
|
383
|
+
raise WalkError(msg)
|
|
384
|
+
if source is not None:
|
|
385
|
+
if not isinstance(source, str) or not source.strip():
|
|
386
|
+
msg = "source must be the Pebble program's text"
|
|
387
|
+
raise WalkError(msg)
|
|
388
|
+
return source
|
|
389
|
+
text = example_source(example) if isinstance(example, str) else None
|
|
390
|
+
if text is None:
|
|
391
|
+
msg = f"there is no example called {example!r}"
|
|
392
|
+
raise WalkError(msg)
|
|
393
|
+
return text
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _steps(data: dict[str, object]) -> tuple[WalkStep, ...]:
|
|
397
|
+
"""Read the `[[steps]]` tables; the first must be `start`."""
|
|
398
|
+
raw = data.get("steps")
|
|
399
|
+
if not isinstance(raw, list) or not raw:
|
|
400
|
+
msg = "the walk needs at least one [[steps]]"
|
|
401
|
+
raise WalkError(msg)
|
|
402
|
+
steps: list[WalkStep] = []
|
|
403
|
+
for number, table in enumerate(raw, start=1): # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType]
|
|
404
|
+
where = f"step {number}"
|
|
405
|
+
if not isinstance(table, dict):
|
|
406
|
+
msg = f"{where} must be a table"
|
|
407
|
+
raise WalkError(msg)
|
|
408
|
+
step: dict[str, object] = table # pyright: ignore[reportUnknownVariableType]
|
|
409
|
+
_unknown_keys(step, _STEP_KEYS, where)
|
|
410
|
+
action = parse_action(_text(step, "do", where))
|
|
411
|
+
steps.append(
|
|
412
|
+
WalkStep(
|
|
413
|
+
say=_text(step, "say", where),
|
|
414
|
+
action=action,
|
|
415
|
+
look=_depth(step.get("look"), f"{where}'s look"),
|
|
416
|
+
show=_show(step, where),
|
|
417
|
+
)
|
|
418
|
+
)
|
|
419
|
+
if steps[0].action != Start():
|
|
420
|
+
msg = "the first step must do start, so every replay begins with a clean load"
|
|
421
|
+
raise WalkError(msg)
|
|
422
|
+
return tuple(steps)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _trial(data: dict[str, object]) -> WalkTry:
|
|
426
|
+
"""Read the `[try]` table: the task, its look, its check and its solution."""
|
|
427
|
+
table = data.get("try")
|
|
428
|
+
if not isinstance(table, dict):
|
|
429
|
+
msg = "the walk needs a [try] table"
|
|
430
|
+
raise WalkError(msg)
|
|
431
|
+
trial: dict[str, object] = table # pyright: ignore[reportUnknownVariableType]
|
|
432
|
+
_unknown_keys(trial, _TRY_KEYS, "[try]")
|
|
433
|
+
solution = trial.get("solution")
|
|
434
|
+
if not isinstance(solution, list) or not solution:
|
|
435
|
+
msg = "[try] needs a solution: a list of actions that do the task"
|
|
436
|
+
raise WalkError(msg)
|
|
437
|
+
actions: list[Action] = []
|
|
438
|
+
for item in solution: # pyright: ignore[reportUnknownVariableType]
|
|
439
|
+
if not isinstance(item, str):
|
|
440
|
+
msg = "[try]'s solution must be a list of actions, as text"
|
|
441
|
+
raise WalkError(msg)
|
|
442
|
+
actions.append(parse_action(item))
|
|
443
|
+
return WalkTry(
|
|
444
|
+
task=_text(trial, "task", "[try]"),
|
|
445
|
+
look=_depth(trial.get("look"), "[try]'s look"),
|
|
446
|
+
check=parse_check(_text(trial, "check", "[try]")),
|
|
447
|
+
solution=tuple(actions),
|
|
448
|
+
show=_show(trial, "[try]"),
|
|
449
|
+
step=_step_kind(trial),
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _step_kind(trial: dict[str, object]) -> str | None:
|
|
454
|
+
"""Return the try's optional `step` kind, which only `"into"` (at line depth) may be."""
|
|
455
|
+
kind = trial.get("step")
|
|
456
|
+
if kind is None:
|
|
457
|
+
return None
|
|
458
|
+
if kind not in TRY_STEP_KINDS or trial.get("look") != Depth.LINE.value:
|
|
459
|
+
msg = f'[try]\'s step may only be "into", with look = "line", not {kind!r}'
|
|
460
|
+
raise WalkError(msg)
|
|
461
|
+
return str(kind)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def parse_walk(name: str, text: str) -> Walk:
|
|
465
|
+
"""Read one walk file's text.
|
|
466
|
+
|
|
467
|
+
Args:
|
|
468
|
+
name: The walk's name, used in every error so the file is easy to find.
|
|
469
|
+
text: The TOML text of `walks/<name>.toml`.
|
|
470
|
+
|
|
471
|
+
Raises:
|
|
472
|
+
WalkError: Naming the file and the first problem found in it.
|
|
473
|
+
|
|
474
|
+
"""
|
|
475
|
+
try:
|
|
476
|
+
data: dict[str, object] = tomllib.loads(text)
|
|
477
|
+
_unknown_keys(data, _WALK_KEYS, "the walk")
|
|
478
|
+
return Walk(
|
|
479
|
+
name=name,
|
|
480
|
+
title=_text(data, "title", "the walk"),
|
|
481
|
+
source=_source(data),
|
|
482
|
+
see_also=_text(data, "see_also", "the walk"),
|
|
483
|
+
steps=_steps(data),
|
|
484
|
+
trial=_trial(data),
|
|
485
|
+
)
|
|
486
|
+
except (WalkError, tomllib.TOMLDecodeError) as error:
|
|
487
|
+
msg = f"{name}.toml: {error}"
|
|
488
|
+
raise WalkError(msg) from None
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def load_walk(name: str) -> Walk:
|
|
492
|
+
"""Read the walk called `name` from `walks/<name>.toml`.
|
|
493
|
+
|
|
494
|
+
Raises:
|
|
495
|
+
WalkError: If there is no such file, or the file is not right.
|
|
496
|
+
|
|
497
|
+
"""
|
|
498
|
+
path = resources.files("pycpu.cockpit").joinpath("walks").joinpath(f"{name}.toml")
|
|
499
|
+
if not path.is_file():
|
|
500
|
+
msg = f"{name}.toml: there is no walk file called that"
|
|
501
|
+
raise WalkError(msg)
|
|
502
|
+
return parse_walk(name, path.read_text(encoding="utf-8"))
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
@cache
|
|
506
|
+
def load_walks() -> tuple[Walk, ...]:
|
|
507
|
+
"""Read every walk in `WALK_ORDER`; the files never change while the Cockpit runs.
|
|
508
|
+
|
|
509
|
+
Raises:
|
|
510
|
+
WalkError: If any walk file is missing or not right.
|
|
511
|
+
|
|
512
|
+
"""
|
|
513
|
+
return tuple(load_walk(name) for name in WALK_ORDER)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def walk_named(name: str) -> Walk | None:
|
|
517
|
+
"""Return the walk called `name`, or None if there is no walk called that."""
|
|
518
|
+
return next((walk for walk in load_walks() if walk.name == name), None)
|
pycpu/computer.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""The computer: a football match you can pause, replay in slow motion, rewind and rejoin live.
|
|
2
|
+
|
|
3
|
+
The match races along live on the fast engine. Press pause and the picture freezes
|
|
4
|
+
just before the next move, and the whole machine is carried over to the slow-motion
|
|
5
|
+
camera, the gate engine, where every gate can be watched thinking. Nudge the replay
|
|
6
|
+
forward a gate, a clock beat or an instruction at a time; rewind it to the start of
|
|
7
|
+
the move; press play, and the replay finishes the move before the match carries on
|
|
8
|
+
live from exactly that moment.
|
|
9
|
+
|
|
10
|
+
`Computer` is the remote control. It works nothing out itself: it only decides which
|
|
11
|
+
engine is live and copies a `MachineState` from one to the other, always at an
|
|
12
|
+
instruction boundary, the only moment both engines understand.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from enum import StrEnum
|
|
17
|
+
|
|
18
|
+
from pycpu.assembler import Program
|
|
19
|
+
from pycpu.cpu import GateMachine, MicroStep
|
|
20
|
+
from pycpu.fast import FastMachine
|
|
21
|
+
from pycpu.memory import RAM_ADDRESS_BITS
|
|
22
|
+
from pycpu.state import MachineState
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class StepSize(StrEnum):
|
|
26
|
+
"""How far one paused step moves the gate engine.
|
|
27
|
+
|
|
28
|
+
Attributes:
|
|
29
|
+
GATE: One gate works out its output, or one clock wire moves.
|
|
30
|
+
CYCLE: Finish the current clock beat, or play a whole one from its start.
|
|
31
|
+
INSTRUCTION: Finish the current instruction, or play a whole one from its start.
|
|
32
|
+
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
GATE = "gate"
|
|
36
|
+
CYCLE = "cycle"
|
|
37
|
+
INSTRUCTION = "instruction"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Computer:
|
|
41
|
+
"""A whole computer with two engines: run it fast, pause it into the gates, step and rewind.
|
|
42
|
+
|
|
43
|
+
While running, the fast engine is live. `pause` copies its state into the gate
|
|
44
|
+
engine and remembers it as `instruction_start`, the frame `rewind` goes back to.
|
|
45
|
+
`step` moves the gates forward; whenever an instruction ends, `instruction_start`
|
|
46
|
+
moves to the new boundary. `resume` finishes the current instruction in the gates
|
|
47
|
+
and copies the state back to the fast engine.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
fast: The fast engine, live while running.
|
|
51
|
+
gate: The gate engine, live while paused. It is built once, here, because
|
|
52
|
+
building a full-size one takes a few seconds.
|
|
53
|
+
paused: True while the gate engine holds the machine.
|
|
54
|
+
instruction_start: The state at the start of the current instruction, set by
|
|
55
|
+
`pause` and moved on whenever a step finishes an instruction.
|
|
56
|
+
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self, program: Program | Sequence[int], address_bits: int = RAM_ADDRESS_BITS
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Build both engines and load `program` into them, running and unpaused.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
program: An assembled `Program`, or the plain words of one.
|
|
66
|
+
address_bits: How many address wires the RAM has; both engines get
|
|
67
|
+
`2 ** address_bits` words.
|
|
68
|
+
|
|
69
|
+
"""
|
|
70
|
+
self.gate = GateMachine(address_bits)
|
|
71
|
+
self.fast = FastMachine(self.gate.words)
|
|
72
|
+
self.paused = False
|
|
73
|
+
self.instruction_start = self.fast.state()
|
|
74
|
+
self.load_program(program)
|
|
75
|
+
|
|
76
|
+
def load_program(self, program: Program | Sequence[int]) -> None:
|
|
77
|
+
"""Power both engines on with `program` in memory, and go back to running."""
|
|
78
|
+
words = program.words if isinstance(program, Program) else program
|
|
79
|
+
self.fast.load_program(words)
|
|
80
|
+
self.gate.load_program(words)
|
|
81
|
+
self.paused = False
|
|
82
|
+
self.instruction_start = self.fast.state()
|
|
83
|
+
|
|
84
|
+
def _require(self, *, paused: bool) -> None:
|
|
85
|
+
"""Refuse a call that only makes sense for the other engine being live."""
|
|
86
|
+
if self.paused != paused:
|
|
87
|
+
msg = "the computer is paused" if self.paused else "the computer is not paused"
|
|
88
|
+
raise RuntimeError(msg)
|
|
89
|
+
|
|
90
|
+
def run(self, max_steps: int) -> int:
|
|
91
|
+
"""Run up to `max_steps` instructions on the fast engine; return how many ran.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
RuntimeError: If the computer is paused; `resume` first.
|
|
95
|
+
|
|
96
|
+
"""
|
|
97
|
+
self._require(paused=False)
|
|
98
|
+
return self.fast.run(max_steps)
|
|
99
|
+
|
|
100
|
+
def pause(self) -> None:
|
|
101
|
+
"""Freeze between two instructions and carry the machine into the gate engine.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
RuntimeError: If the computer is already paused, because pausing again
|
|
105
|
+
would throw away the steps taken in the gates.
|
|
106
|
+
|
|
107
|
+
"""
|
|
108
|
+
if self.paused:
|
|
109
|
+
msg = "the computer is already paused"
|
|
110
|
+
raise RuntimeError(msg)
|
|
111
|
+
self.instruction_start = self.fast.state()
|
|
112
|
+
self.gate.load_state(self.instruction_start)
|
|
113
|
+
self.paused = True
|
|
114
|
+
|
|
115
|
+
def step(self, size: StepSize) -> MicroStep | None:
|
|
116
|
+
"""Move the paused gate engine forward by one gate, one beat or one instruction.
|
|
117
|
+
|
|
118
|
+
`GATE` returns the `MicroStep` that happened; when it is of kind `"end"`, the
|
|
119
|
+
instruction has finished. `CYCLE` finishes the current clock beat (or plays a
|
|
120
|
+
whole one). `INSTRUCTION` finishes the current instruction if one is part-way
|
|
121
|
+
through, and otherwise plays one whole instruction. Whenever a step leaves the
|
|
122
|
+
machine at an instruction boundary having moved, `instruction_start` becomes
|
|
123
|
+
that new state. A halted machine does not move.
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
The micro step for `GATE`; None for `CYCLE` and `INSTRUCTION`.
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
RuntimeError: If the computer is not paused.
|
|
130
|
+
|
|
131
|
+
"""
|
|
132
|
+
self._require(paused=True)
|
|
133
|
+
micro = None
|
|
134
|
+
match size:
|
|
135
|
+
case StepSize.GATE:
|
|
136
|
+
micro = self.gate.micro_step()
|
|
137
|
+
finished = micro.kind == "end"
|
|
138
|
+
case StepSize.CYCLE:
|
|
139
|
+
self.gate.step_cycle()
|
|
140
|
+
finished = self.gate.at_boundary
|
|
141
|
+
case StepSize.INSTRUCTION:
|
|
142
|
+
self.gate.step()
|
|
143
|
+
finished = True
|
|
144
|
+
if finished:
|
|
145
|
+
self.instruction_start = self.gate.state()
|
|
146
|
+
return micro
|
|
147
|
+
|
|
148
|
+
def rewind(self) -> None:
|
|
149
|
+
"""Go back to the start of the current instruction by reloading `instruction_start`.
|
|
150
|
+
|
|
151
|
+
Raises:
|
|
152
|
+
RuntimeError: If the computer is not paused.
|
|
153
|
+
|
|
154
|
+
"""
|
|
155
|
+
self._require(paused=True)
|
|
156
|
+
self.gate.load_state(self.instruction_start)
|
|
157
|
+
|
|
158
|
+
def resume(self) -> None:
|
|
159
|
+
"""Finish the current instruction in the gates, copy the state to the fast engine, run on.
|
|
160
|
+
|
|
161
|
+
At a boundary there is nothing to finish, so the state is copied as it is.
|
|
162
|
+
|
|
163
|
+
Raises:
|
|
164
|
+
RuntimeError: If the computer is not paused.
|
|
165
|
+
|
|
166
|
+
"""
|
|
167
|
+
self._require(paused=True)
|
|
168
|
+
if not self.gate.at_boundary:
|
|
169
|
+
self.gate.step()
|
|
170
|
+
self.fast.load_state(self.gate.state())
|
|
171
|
+
self.paused = False
|
|
172
|
+
|
|
173
|
+
def state(self) -> MachineState:
|
|
174
|
+
"""Return the live engine's state: the gates' while paused, the fast engine's otherwise."""
|
|
175
|
+
return self.gate.state() if self.paused else self.fast.state()
|