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/session.py
ADDED
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
"""The Cockpit's session: the one running computer and every rule about moving it.
|
|
2
|
+
|
|
3
|
+
Think of the pilot's seat: the pilot is the only one who moves the controls, and the
|
|
4
|
+
seat refuses anything that would break the aeroplane. A `Cockpit` owns the single
|
|
5
|
+
real `Computer`, the program on it (with its Pebble source map when there is one),
|
|
6
|
+
and the state just before the last move. Every move goes through its methods (play
|
|
7
|
+
too, one slice at a time through `play_tick`), which refuse bad requests with a
|
|
8
|
+
`CockpitRefusal` that names the reason; the web app only reads requests and answers,
|
|
9
|
+
and the picture module only reads.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
from pycpu.assembler import AssemblyError, assemble
|
|
15
|
+
from pycpu.cockpit.explain import (
|
|
16
|
+
END_NOTE,
|
|
17
|
+
FINISHED_NOTE,
|
|
18
|
+
MAIN_CLOCK,
|
|
19
|
+
NO_GATE_ENDING,
|
|
20
|
+
Depth,
|
|
21
|
+
count_instructions,
|
|
22
|
+
describe_gate_steps,
|
|
23
|
+
describe_move,
|
|
24
|
+
describe_rewind,
|
|
25
|
+
describe_run,
|
|
26
|
+
describe_run_to_line,
|
|
27
|
+
no_gate_note,
|
|
28
|
+
)
|
|
29
|
+
from pycpu.cockpit.walks import (
|
|
30
|
+
Action,
|
|
31
|
+
RunInstructions,
|
|
32
|
+
RunToLine,
|
|
33
|
+
Start,
|
|
34
|
+
StepAt,
|
|
35
|
+
StepGateUntil,
|
|
36
|
+
StepLineInto,
|
|
37
|
+
Walk,
|
|
38
|
+
WalkError,
|
|
39
|
+
passes,
|
|
40
|
+
walk_named,
|
|
41
|
+
)
|
|
42
|
+
from pycpu.computer import Computer, StepSize
|
|
43
|
+
from pycpu.cpu import MicroStep
|
|
44
|
+
from pycpu.memory import RAM_ADDRESS_BITS
|
|
45
|
+
from pycpu.state import MachineState
|
|
46
|
+
from pycpu.translator import FRAME_POINTER, TranslatedProgram, translate
|
|
47
|
+
|
|
48
|
+
# Depth and the notes live in explain.py, which writes every sentence; they are listed
|
|
49
|
+
# here too so the moves' old imports (`from pycpu.cockpit.session import Depth`) still work.
|
|
50
|
+
__all__ = [
|
|
51
|
+
"BUSY_MESSAGE",
|
|
52
|
+
"DEMO_PROGRAM",
|
|
53
|
+
"END_NOTE",
|
|
54
|
+
"FINISHED_NOTE",
|
|
55
|
+
"LIMIT_REASON",
|
|
56
|
+
"MAIN_CLOCK",
|
|
57
|
+
"MAX_GATE_STEPS",
|
|
58
|
+
"MAX_LINE_INSTRUCTIONS",
|
|
59
|
+
"MAX_PEBBLE_CHARACTERS",
|
|
60
|
+
"MAX_RUN",
|
|
61
|
+
"MAX_SPEED",
|
|
62
|
+
"NOT_PEBBLE_MESSAGE",
|
|
63
|
+
"NOT_PLAYING_MESSAGE",
|
|
64
|
+
"NO_GATE_ENDING",
|
|
65
|
+
"NO_LINES_NOTE",
|
|
66
|
+
"TICK_SECONDS",
|
|
67
|
+
"Cockpit",
|
|
68
|
+
"CockpitBusy",
|
|
69
|
+
"CockpitRefusal",
|
|
70
|
+
"Depth",
|
|
71
|
+
"LineStep",
|
|
72
|
+
"NoSuchWalk",
|
|
73
|
+
"WalkProgress",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
MAX_RUN = 10_000 # the most instructions one press of Run may ask for
|
|
77
|
+
MAX_GATE_STEPS = 100_000 # the most gate steps one request may ask for
|
|
78
|
+
MAX_PEBBLE_CHARACTERS = 65_536 # far more Pebble than fits in 4K words once translated
|
|
79
|
+
MAX_LINE_INSTRUCTIONS = 10_000 # the most instructions one line step may run before giving up
|
|
80
|
+
MAX_SPEED = 100_000 # the fastest play, in instructions a second
|
|
81
|
+
TICK_SECONDS = 0.1 # how long play waits between two slices (and two live events)
|
|
82
|
+
|
|
83
|
+
DEMO_PROGRAM = """\
|
|
84
|
+
set r1, 0xFFFF ; the output port's address
|
|
85
|
+
li r2, 3 ; count down from 3
|
|
86
|
+
loop:
|
|
87
|
+
call show ; print the digit for r2
|
|
88
|
+
addi r2, -1
|
|
89
|
+
br ne, loop ; again, until r2 reaches 0
|
|
90
|
+
halt
|
|
91
|
+
show:
|
|
92
|
+
li r3, 48 ; 48 is the character '0'
|
|
93
|
+
add r3, r3, r2 ; '0' + r2 is the digit for r2
|
|
94
|
+
store r3, [r1] ; send it to the screen
|
|
95
|
+
ret
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
BUSY_MESSAGE = "the computer is running: press pause first"
|
|
99
|
+
NOT_PEBBLE_MESSAGE = "line steps need a Pebble program: this one is assembly"
|
|
100
|
+
NOT_PLAYING_MESSAGE = "the computer is not playing: press play first"
|
|
101
|
+
LIMIT_REASON = "the line may be stuck in a loop, or a call it makes is very long"
|
|
102
|
+
NO_LINES_NOTE = (
|
|
103
|
+
"This program is machine code, so it has no Pebble lines to step. "
|
|
104
|
+
"Look closer to step an instruction."
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class CockpitRefusal(Exception): # noqa: N818
|
|
109
|
+
"""Say that the Cockpit will not do what was asked, and why, in one sentence."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class CockpitBusy(CockpitRefusal):
|
|
113
|
+
"""Say that the computer is playing, so only pause or a load is allowed."""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class NoSuchWalk(CockpitRefusal):
|
|
117
|
+
"""Say that there is no walk with the name asked for (the web app answers 404)."""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class WalkProgress:
|
|
122
|
+
"""Where the learner is in the walk they are on.
|
|
123
|
+
|
|
124
|
+
Attributes:
|
|
125
|
+
name: The walk's name, such as `"many-instructions"`.
|
|
126
|
+
step: The step the machine was replayed to; the walk's step count means
|
|
127
|
+
the "Now you try" stage.
|
|
128
|
+
off_script: True once the learner made a move of their own during the
|
|
129
|
+
walk's steps, or loaded a program, so the page offers "Back to the walk".
|
|
130
|
+
done: True once the "Now you try" check has passed. It is latched: it stays
|
|
131
|
+
true however far the learner steps on afterwards.
|
|
132
|
+
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
name: str
|
|
136
|
+
step: int
|
|
137
|
+
off_script: bool = False
|
|
138
|
+
done: bool = False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass(frozen=True)
|
|
142
|
+
class LineStep:
|
|
143
|
+
"""What one Pebble line step did: how far it ran and why it stopped.
|
|
144
|
+
|
|
145
|
+
Attributes:
|
|
146
|
+
instructions: How many instructions ran on the fast engine.
|
|
147
|
+
stopped: `"line"` if it reached the next line, `"halted"` if the program
|
|
148
|
+
stopped (or had already stopped), `"limit"` if it gave up after
|
|
149
|
+
`MAX_LINE_INSTRUCTIONS` instructions.
|
|
150
|
+
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
instructions: int
|
|
154
|
+
stopped: str
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _check_whole(name: str, value: int, largest: int) -> None:
|
|
158
|
+
"""Refuse `value` unless it is a whole number from 1 to `largest`."""
|
|
159
|
+
if not 1 <= value <= largest:
|
|
160
|
+
msg = f"{name} must be a whole number from 1 to {largest}"
|
|
161
|
+
raise CockpitRefusal(msg)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class Cockpit:
|
|
165
|
+
"""One running computer, paused, with the rules for moving and loading it.
|
|
166
|
+
|
|
167
|
+
Attributes:
|
|
168
|
+
computer: The real computer, paused at an instruction boundary unless playing.
|
|
169
|
+
translated: The Pebble program on it, or None for an assembly program.
|
|
170
|
+
assembly: The assembly text shown in the listing.
|
|
171
|
+
program: The assembled program on the machine, for the listing.
|
|
172
|
+
before: The state just before the last move, for marking what changed.
|
|
173
|
+
last_gate: The micro step of the last gate step, else None.
|
|
174
|
+
note: One sentence about the last move, else None.
|
|
175
|
+
happened: The "What just happened" sentence for the last move, written from
|
|
176
|
+
the real change by `explain.py`. None before any move, after a load, while
|
|
177
|
+
playing, and after a step that could not move (`note` says why).
|
|
178
|
+
playing: Whether the computer is running on its own.
|
|
179
|
+
loads: How many programs have been loaded, 0 for the demo it starts with. Every
|
|
180
|
+
load adds one, so the page can tell which program a listing belongs to.
|
|
181
|
+
walk: The guided walk the learner is on, or None.
|
|
182
|
+
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def __init__(self, address_bits: int = RAM_ADDRESS_BITS) -> None:
|
|
186
|
+
"""Build the computer with `DEMO_PROGRAM` loaded and paused at its start."""
|
|
187
|
+
self.program = assemble(DEMO_PROGRAM, words=1 << address_bits)
|
|
188
|
+
self.computer = Computer(self.program, address_bits)
|
|
189
|
+
self.computer.pause()
|
|
190
|
+
self.translated: TranslatedProgram | None = None
|
|
191
|
+
self.assembly = DEMO_PROGRAM
|
|
192
|
+
self.before: MachineState = self.computer.state()
|
|
193
|
+
self.last_gate: MicroStep | None = None
|
|
194
|
+
self.note: str | None = None
|
|
195
|
+
self.happened: str | None = None
|
|
196
|
+
self.playing = False
|
|
197
|
+
self.loads = 0
|
|
198
|
+
self.walk: WalkProgress | None = None
|
|
199
|
+
self._replaying = False # True while `go_to_walk` makes the walk's own moves
|
|
200
|
+
|
|
201
|
+
def _begin(self) -> None:
|
|
202
|
+
"""Start a move: refuse it while playing, then set `before` and clear the notes."""
|
|
203
|
+
if self.playing:
|
|
204
|
+
raise CockpitBusy(BUSY_MESSAGE)
|
|
205
|
+
self._off_script(load=False)
|
|
206
|
+
self._mark()
|
|
207
|
+
|
|
208
|
+
def _off_script(self, *, load: bool) -> None:
|
|
209
|
+
"""Mark the walk off script when the learner moves by themselves during its steps.
|
|
210
|
+
|
|
211
|
+
At the "Now you try" stage the learner's own moves are the task, so only a load
|
|
212
|
+
takes them off script there. The walk's own replayed moves never do.
|
|
213
|
+
"""
|
|
214
|
+
walk = self.walk
|
|
215
|
+
if walk is None or self._replaying:
|
|
216
|
+
return
|
|
217
|
+
current = walk_named(walk.name)
|
|
218
|
+
if load or current is None or walk.step < len(current.steps):
|
|
219
|
+
walk.off_script = True
|
|
220
|
+
|
|
221
|
+
def _judge(self) -> None:
|
|
222
|
+
"""After a move at the "Now you try" stage, test the walk's check; once true, keep it.
|
|
223
|
+
|
|
224
|
+
Nothing is judged while the walk replays itself, or once the learner is off
|
|
225
|
+
script (their own program could pass a check by chance).
|
|
226
|
+
"""
|
|
227
|
+
walk = self.walk
|
|
228
|
+
if walk is None or self._replaying or walk.off_script or walk.done:
|
|
229
|
+
return
|
|
230
|
+
current = walk_named(walk.name)
|
|
231
|
+
if current is None or walk.step < len(current.steps):
|
|
232
|
+
return
|
|
233
|
+
now = self.computer.state()
|
|
234
|
+
# While playing the fast engine is live and the gate engine's instruction start is
|
|
235
|
+
# stale; play is always between two instructions, so the live state is the start.
|
|
236
|
+
start = self.computer.instruction_start if self.computer.paused else now
|
|
237
|
+
walk.done = passes(current.trial.check, now, start, self.translated)
|
|
238
|
+
|
|
239
|
+
def _mark(self) -> None:
|
|
240
|
+
"""Remember the state before a move, and clear the last move's sentences and gate step."""
|
|
241
|
+
self.before = self.computer.state()
|
|
242
|
+
self.note = None
|
|
243
|
+
self.happened = None
|
|
244
|
+
self.last_gate = None
|
|
245
|
+
|
|
246
|
+
def start_with_pebble(self, source: str) -> None:
|
|
247
|
+
"""Load a Pebble program as the Cockpit's starting program.
|
|
248
|
+
|
|
249
|
+
Kept for older callers: it does what `load_pebble` does, and a load marks
|
|
250
|
+
nothing changed.
|
|
251
|
+
|
|
252
|
+
This is for a Cockpit that has just been built: the program is loaded as
|
|
253
|
+
`load_pebble` does, and a load marks nothing changed, because a visitor never
|
|
254
|
+
saw the demo program it replaced.
|
|
255
|
+
|
|
256
|
+
Raises:
|
|
257
|
+
CockpitRefusal: If the program does not fit this Cockpit's memory.
|
|
258
|
+
PebbleError: If Pebble itself finds a mistake in the program.
|
|
259
|
+
UnsupportedFeature: If the program uses something PyCPU cannot do yet.
|
|
260
|
+
|
|
261
|
+
"""
|
|
262
|
+
self.load_pebble(source)
|
|
263
|
+
|
|
264
|
+
def start_playing(self) -> None:
|
|
265
|
+
"""Let the computer run on its own: resume it onto the fast engine and mark it playing.
|
|
266
|
+
|
|
267
|
+
`resume` first finishes a part-done instruction in the gates. After this the
|
|
268
|
+
computer only moves through `play_tick`, until `stop_playing` (or a load)
|
|
269
|
+
pauses it again. Starting is a move, so `before` is set and the notes cleared.
|
|
270
|
+
|
|
271
|
+
Raises:
|
|
272
|
+
CockpitBusy: If it is already playing.
|
|
273
|
+
|
|
274
|
+
"""
|
|
275
|
+
self._begin()
|
|
276
|
+
self.computer.resume()
|
|
277
|
+
self.playing = True
|
|
278
|
+
|
|
279
|
+
def play_tick(self, instructions: int) -> bool:
|
|
280
|
+
"""Run one slice of play: up to `instructions` instructions on the fast engine.
|
|
281
|
+
|
|
282
|
+
A tick is a move, so `before` becomes the state at the start of the slice,
|
|
283
|
+
and the changed marks show what this slice changed. A tick of 0 instructions
|
|
284
|
+
is allowed: at slow speeds most ticks run nothing.
|
|
285
|
+
|
|
286
|
+
Returns:
|
|
287
|
+
True while the program is still going, False once it has halted.
|
|
288
|
+
|
|
289
|
+
Raises:
|
|
290
|
+
CockpitRefusal: If the computer is not playing.
|
|
291
|
+
|
|
292
|
+
"""
|
|
293
|
+
if not self.playing:
|
|
294
|
+
raise CockpitRefusal(NOT_PLAYING_MESSAGE)
|
|
295
|
+
self._mark()
|
|
296
|
+
self.computer.run(instructions)
|
|
297
|
+
self._judge()
|
|
298
|
+
return not self.computer.state().halted
|
|
299
|
+
|
|
300
|
+
def stop_playing(self) -> None:
|
|
301
|
+
"""Stop play and pause just before the next instruction, in the gate engine.
|
|
302
|
+
|
|
303
|
+
Stopping when not playing does nothing, so pause and load can both call it.
|
|
304
|
+
"""
|
|
305
|
+
self.playing = False
|
|
306
|
+
if not self.computer.paused:
|
|
307
|
+
self.computer.pause()
|
|
308
|
+
|
|
309
|
+
def load_assembly(self, source: str) -> None:
|
|
310
|
+
"""Assemble `source`, load it and pause at its start.
|
|
311
|
+
|
|
312
|
+
If the computer is playing, play stops first; a refused text leaves it playing.
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
CockpitRefusal: Naming the line the assembler refused; the machine is left as it was.
|
|
316
|
+
|
|
317
|
+
"""
|
|
318
|
+
try:
|
|
319
|
+
assembled = assemble(source, words=self.computer.gate.words)
|
|
320
|
+
except AssemblyError as error:
|
|
321
|
+
raise CockpitRefusal(str(error)) from None
|
|
322
|
+
self.stop_playing()
|
|
323
|
+
self._off_script(load=True)
|
|
324
|
+
self.computer.load_program(assembled)
|
|
325
|
+
self.computer.pause()
|
|
326
|
+
self._mark() # a load marks nothing changed: `before` is the loaded state
|
|
327
|
+
self.translated = None
|
|
328
|
+
self.assembly = source
|
|
329
|
+
self.program = assembled
|
|
330
|
+
self.loads += 1
|
|
331
|
+
|
|
332
|
+
def load_pebble(self, source: str) -> None:
|
|
333
|
+
"""Translate a Pebble program, load it and pause at its start.
|
|
334
|
+
|
|
335
|
+
If the computer is playing, play stops first; a refused program leaves it playing.
|
|
336
|
+
|
|
337
|
+
Raises:
|
|
338
|
+
CockpitRefusal: If the text is longer than `MAX_PEBBLE_CHARACTERS` or the
|
|
339
|
+
program (with room for its stack) needs more words than this memory has.
|
|
340
|
+
PebbleError: If Pebble itself finds a mistake in the program.
|
|
341
|
+
UnsupportedFeature: If the program uses something PyCPU cannot do yet.
|
|
342
|
+
|
|
343
|
+
"""
|
|
344
|
+
# Refuse a huge text before Pebble's compiler spends time on it: anything this long
|
|
345
|
+
# could never fit in memory once translated.
|
|
346
|
+
if len(source) > MAX_PEBBLE_CHARACTERS:
|
|
347
|
+
msg = f"a Pebble program may be at most {MAX_PEBBLE_CHARACTERS:,} characters long"
|
|
348
|
+
raise CockpitRefusal(msg)
|
|
349
|
+
translated = translate(source)
|
|
350
|
+
needed, words = len(translated.program.words), self.computer.gate.words
|
|
351
|
+
if needed > words:
|
|
352
|
+
msg = f"this program needs {needed} words, but this Cockpit's memory has only {words}"
|
|
353
|
+
raise CockpitRefusal(msg)
|
|
354
|
+
# Main's first frame sits just past the program; without room it would stop at once.
|
|
355
|
+
if translated.memory_needed > words:
|
|
356
|
+
msg = (
|
|
357
|
+
f"this program needs room for its stack too ({translated.memory_needed} words "
|
|
358
|
+
f"in all), but this Cockpit's memory has only {words}"
|
|
359
|
+
)
|
|
360
|
+
raise CockpitRefusal(msg)
|
|
361
|
+
self.stop_playing()
|
|
362
|
+
self._off_script(load=True)
|
|
363
|
+
self.computer.load_program(translated.program)
|
|
364
|
+
self.computer.pause()
|
|
365
|
+
self._mark() # a load marks nothing changed: `before` is the loaded state
|
|
366
|
+
self.translated = translated
|
|
367
|
+
self.assembly = translated.assembly
|
|
368
|
+
self.program = translated.program
|
|
369
|
+
self.loads += 1
|
|
370
|
+
|
|
371
|
+
def step(self, size: StepSize, count: int = 1) -> None:
|
|
372
|
+
"""Step the paused computer by `size`, `count` times.
|
|
373
|
+
|
|
374
|
+
A gate step may carry a `count` from 1 to `MAX_GATE_STEPS`, because one
|
|
375
|
+
instruction is thousands of gate steps; the steps stop early if the machine
|
|
376
|
+
halts. A cycle or instruction step may only say `count` 1.
|
|
377
|
+
|
|
378
|
+
Raises:
|
|
379
|
+
CockpitRefusal: For a count out of range or a count with a bigger step.
|
|
380
|
+
CockpitBusy: While playing.
|
|
381
|
+
|
|
382
|
+
"""
|
|
383
|
+
_check_whole("count", count, MAX_GATE_STEPS)
|
|
384
|
+
if size != StepSize.GATE and count != 1:
|
|
385
|
+
msg = "count is only for gate steps"
|
|
386
|
+
raise CockpitRefusal(msg)
|
|
387
|
+
self._begin()
|
|
388
|
+
self._steps(size, count, None)
|
|
389
|
+
|
|
390
|
+
def step_gate_until(self, prefix: str) -> bool:
|
|
391
|
+
"""Take gate steps until a gate inside the part `prefix` works, like a walk does.
|
|
392
|
+
|
|
393
|
+
A gate counts when its scope path is `prefix` or starts with `prefix` and a
|
|
394
|
+
dot, so `"cpu.alu"` means any gate in the ALU. The steps stop early if the
|
|
395
|
+
machine halts, and give up after `MAX_GATE_STEPS`.
|
|
396
|
+
|
|
397
|
+
Returns:
|
|
398
|
+
True if a gate inside `prefix` worked, False if the steps stopped first.
|
|
399
|
+
|
|
400
|
+
Raises:
|
|
401
|
+
CockpitBusy: While playing.
|
|
402
|
+
|
|
403
|
+
"""
|
|
404
|
+
self._begin()
|
|
405
|
+
if self.before.halted:
|
|
406
|
+
self.note = FINISHED_NOTE
|
|
407
|
+
return False
|
|
408
|
+
return self._steps(StepSize.GATE, MAX_GATE_STEPS, prefix)
|
|
409
|
+
|
|
410
|
+
def _steps(self, size: StepSize, count: int, until: str | None) -> bool:
|
|
411
|
+
"""Take up to `count` steps of `size`, stopping at a halt or at a gate inside `until`.
|
|
412
|
+
|
|
413
|
+
Returns:
|
|
414
|
+
True if a gate step stopped at a gate inside `until`.
|
|
415
|
+
|
|
416
|
+
"""
|
|
417
|
+
start = self.computer.instruction_start
|
|
418
|
+
circuit = self.computer.gate.simulator.circuit
|
|
419
|
+
taken = finished = 0
|
|
420
|
+
found = False
|
|
421
|
+
for _ in range(count):
|
|
422
|
+
micro = self.computer.step(size)
|
|
423
|
+
self.last_gate = micro
|
|
424
|
+
taken += 1
|
|
425
|
+
# Only an instruction's end can leave the machine halted, so look only there.
|
|
426
|
+
if micro is not None and micro.kind == "end":
|
|
427
|
+
finished += 1
|
|
428
|
+
if self.computer.state().halted:
|
|
429
|
+
break
|
|
430
|
+
elif until is not None and micro is not None and micro.kind == "gate":
|
|
431
|
+
path = circuit.scope_of(micro.gate)
|
|
432
|
+
if path == until or path.startswith(f"{until}."):
|
|
433
|
+
found = True
|
|
434
|
+
break
|
|
435
|
+
# A clock beat is made of clock-wire moves as well as gates, so a gate step can end
|
|
436
|
+
# on one; say so, rather than leave the page with nothing to show and no reason.
|
|
437
|
+
last = self.last_gate
|
|
438
|
+
if size == StepSize.GATE and last is not None and last.kind != "gate":
|
|
439
|
+
self.note = no_gate_note(last)
|
|
440
|
+
if not self.before.halted:
|
|
441
|
+
self._describe_step(size, start, finished, taken)
|
|
442
|
+
self._judge()
|
|
443
|
+
return found
|
|
444
|
+
|
|
445
|
+
def _describe_step(
|
|
446
|
+
self, size: StepSize, start: MachineState, finished: int, taken: int
|
|
447
|
+
) -> None:
|
|
448
|
+
"""Write `happened` for a gate, beat or instruction step that has just moved.
|
|
449
|
+
|
|
450
|
+
Args:
|
|
451
|
+
size: The step size that was taken.
|
|
452
|
+
start: `instruction_start` before the step, so the sentence covers the
|
|
453
|
+
whole instruction even when the step began part-way through it.
|
|
454
|
+
finished: How many instructions the gate steps finished.
|
|
455
|
+
taken: How many gate steps were taken.
|
|
456
|
+
|
|
457
|
+
"""
|
|
458
|
+
after = self.computer.state()
|
|
459
|
+
match size:
|
|
460
|
+
case StepSize.GATE:
|
|
461
|
+
last = self.last_gate
|
|
462
|
+
path = None
|
|
463
|
+
if last is not None and last.kind == "gate":
|
|
464
|
+
path = self.computer.gate.simulator.circuit.scope_of(last.gate)
|
|
465
|
+
sentence = describe_move(
|
|
466
|
+
Depth.GATE, start, after, last, self.translated, finished, gate_path=path
|
|
467
|
+
)
|
|
468
|
+
self.happened = sentence if taken == 1 else describe_gate_steps(taken, sentence)
|
|
469
|
+
case StepSize.CYCLE:
|
|
470
|
+
ran = int(self.computer.gate.at_boundary) # a beat that ends an instruction
|
|
471
|
+
self.happened = describe_move(Depth.PART, start, after, None, self.translated, ran)
|
|
472
|
+
case StepSize.INSTRUCTION:
|
|
473
|
+
self.happened = describe_move(
|
|
474
|
+
Depth.INSTRUCTION, start, after, None, self.translated, 1
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
def step_at(self, depth: Depth) -> None:
|
|
478
|
+
"""Press Step at `depth`: one line, one instruction, one beat or one gate.
|
|
479
|
+
|
|
480
|
+
Each depth is one of the older moves: `step_line(into=False)` for a line,
|
|
481
|
+
`step` with `StepSize.INSTRUCTION`, `CYCLE` or `GATE` for the others. A depth
|
|
482
|
+
that cannot move does not raise: the machine stays as it is and `note` says
|
|
483
|
+
why, in plain words. That is a halted machine at any depth
|
|
484
|
+
(`FINISHED_NOTE`), or a line step on assembly (`NO_LINES_NOTE`). A step
|
|
485
|
+
started part-way through a smaller one finishes that one first.
|
|
486
|
+
|
|
487
|
+
Raises:
|
|
488
|
+
CockpitBusy: While playing.
|
|
489
|
+
|
|
490
|
+
"""
|
|
491
|
+
self._begin()
|
|
492
|
+
if self.computer.state().halted:
|
|
493
|
+
self.note = FINISHED_NOTE
|
|
494
|
+
return
|
|
495
|
+
match depth:
|
|
496
|
+
case Depth.LINE if self.translated is None:
|
|
497
|
+
self.note = NO_LINES_NOTE
|
|
498
|
+
case Depth.LINE:
|
|
499
|
+
self.step_line(into=False)
|
|
500
|
+
case Depth.INSTRUCTION:
|
|
501
|
+
self.step(StepSize.INSTRUCTION)
|
|
502
|
+
case Depth.PART:
|
|
503
|
+
self.step(StepSize.CYCLE)
|
|
504
|
+
case Depth.GATE:
|
|
505
|
+
self.step(StepSize.GATE)
|
|
506
|
+
|
|
507
|
+
def go_to_walk(self, name: str, step: int) -> None:
|
|
508
|
+
"""Open the walk called `name` at `step`, by replaying it on the real machine.
|
|
509
|
+
|
|
510
|
+
Play stops first. The walk's program is loaded (its first step is always
|
|
511
|
+
`start`), and then every step's move up to and including `steps[step]` is
|
|
512
|
+
made again, for real, from that start. Replaying from the start each time
|
|
513
|
+
makes it exact: Next, Back and "Back to the walk" all land on the same
|
|
514
|
+
moment, whatever the learner did in between. `step == len(steps)` opens the
|
|
515
|
+
"Now you try" stage, with the check judged straight away (a fresh try never
|
|
516
|
+
starts done).
|
|
517
|
+
|
|
518
|
+
Raises:
|
|
519
|
+
NoSuchWalk: If there is no walk called `name`.
|
|
520
|
+
CockpitRefusal: If `step` is not from 0 to the walk's number of steps.
|
|
521
|
+
WalkError: If a move of the walk does not reach where it should (a test
|
|
522
|
+
failure for the walk file, never something a learner can cause).
|
|
523
|
+
|
|
524
|
+
"""
|
|
525
|
+
walk = self.check_walk(name, step)
|
|
526
|
+
self.stop_playing()
|
|
527
|
+
self.walk = WalkProgress(name, step)
|
|
528
|
+
self._replaying = True
|
|
529
|
+
try:
|
|
530
|
+
for walk_step in walk.steps[: step + 1]:
|
|
531
|
+
self._act(walk, walk_step.action)
|
|
532
|
+
except BaseException:
|
|
533
|
+
self.walk = None
|
|
534
|
+
raise
|
|
535
|
+
finally:
|
|
536
|
+
self._replaying = False
|
|
537
|
+
self._judge()
|
|
538
|
+
|
|
539
|
+
def check_walk(self, name: str, step: int) -> Walk:
|
|
540
|
+
"""Return the walk called `name` if `step` is one of its steps, changing nothing.
|
|
541
|
+
|
|
542
|
+
`go_to_walk` checks this before it stops play, so a refused request leaves a
|
|
543
|
+
playing computer playing; the web app asks first for the same reason.
|
|
544
|
+
|
|
545
|
+
Raises:
|
|
546
|
+
NoSuchWalk: If there is no walk called `name`.
|
|
547
|
+
CockpitRefusal: If `step` is not from 0 to the walk's number of steps.
|
|
548
|
+
|
|
549
|
+
"""
|
|
550
|
+
walk = walk_named(name)
|
|
551
|
+
if walk is None:
|
|
552
|
+
msg = f"There is no walk called {name}."
|
|
553
|
+
raise NoSuchWalk(msg)
|
|
554
|
+
count = len(walk.steps)
|
|
555
|
+
if not 0 <= step <= count:
|
|
556
|
+
msg = f"step must be a whole number from 0 to {count}"
|
|
557
|
+
raise CockpitRefusal(msg)
|
|
558
|
+
return walk
|
|
559
|
+
|
|
560
|
+
def act(self, action: Action) -> None:
|
|
561
|
+
"""Make one walk action as a move of the learner's own, on the walk they are on.
|
|
562
|
+
|
|
563
|
+
This is how a test plays a walk's "Now you try" solution: each action is the
|
|
564
|
+
same move a button makes, so the check is judged after it as usual.
|
|
565
|
+
|
|
566
|
+
Raises:
|
|
567
|
+
CockpitRefusal: If no walk is open.
|
|
568
|
+
WalkError: If a fast-forward does not reach where it should.
|
|
569
|
+
|
|
570
|
+
"""
|
|
571
|
+
walk = None if self.walk is None else walk_named(self.walk.name)
|
|
572
|
+
if walk is None:
|
|
573
|
+
msg = "there is no walk open to make a walk move on"
|
|
574
|
+
raise CockpitRefusal(msg)
|
|
575
|
+
self._act(walk, action)
|
|
576
|
+
|
|
577
|
+
def leave_walk(self) -> None:
|
|
578
|
+
"""Leave the walk: the machine stays where it is, with no walk on top of it."""
|
|
579
|
+
self.walk = None
|
|
580
|
+
|
|
581
|
+
def _act(self, walk: Walk, action: Action) -> None:
|
|
582
|
+
"""Make one action of `walk` on the real machine; a fast-forward must arrive."""
|
|
583
|
+
match action:
|
|
584
|
+
case Start():
|
|
585
|
+
self.load_pebble(walk.source)
|
|
586
|
+
case StepAt(depth):
|
|
587
|
+
self.step_at(depth)
|
|
588
|
+
case StepLineInto():
|
|
589
|
+
self.step_line(into=True)
|
|
590
|
+
case RunInstructions(count):
|
|
591
|
+
self.run(count)
|
|
592
|
+
case RunToLine(line):
|
|
593
|
+
if self.run_to_line(line).stopped != "line":
|
|
594
|
+
msg = f"{walk.name}: run to line {line} never reached line {line}"
|
|
595
|
+
raise WalkError(msg)
|
|
596
|
+
case StepGateUntil(prefix):
|
|
597
|
+
if not self.step_gate_until(prefix):
|
|
598
|
+
msg = f"{walk.name}: step gate until {prefix} never reached a gate in it"
|
|
599
|
+
raise WalkError(msg)
|
|
600
|
+
|
|
601
|
+
def rewind(self) -> None:
|
|
602
|
+
"""Go back to the start of the current instruction."""
|
|
603
|
+
self._begin()
|
|
604
|
+
moved = not self.computer.gate.at_boundary
|
|
605
|
+
self.computer.rewind()
|
|
606
|
+
self.happened = describe_rewind(moved=moved)
|
|
607
|
+
self._judge()
|
|
608
|
+
|
|
609
|
+
def run(self, instructions: int) -> int:
|
|
610
|
+
"""Resume, run up to `instructions` instructions on the fast engine, and pause again.
|
|
611
|
+
|
|
612
|
+
Returns:
|
|
613
|
+
How many instructions ran.
|
|
614
|
+
|
|
615
|
+
Raises:
|
|
616
|
+
CockpitRefusal: For a count outside 1 to `MAX_RUN`.
|
|
617
|
+
CockpitBusy: While playing.
|
|
618
|
+
|
|
619
|
+
"""
|
|
620
|
+
_check_whole("instructions", instructions, MAX_RUN)
|
|
621
|
+
self._begin()
|
|
622
|
+
# `resume` finishes a part-done instruction in the gates; it ran too, so say so.
|
|
623
|
+
finishing = int(not self.computer.gate.at_boundary)
|
|
624
|
+
self.computer.resume()
|
|
625
|
+
try:
|
|
626
|
+
ran = self.computer.run(instructions)
|
|
627
|
+
finally:
|
|
628
|
+
self.computer.pause()
|
|
629
|
+
self.happened = describe_run(ran, self.computer.state(), finishing)
|
|
630
|
+
self._judge()
|
|
631
|
+
return ran
|
|
632
|
+
|
|
633
|
+
def step_line(self, *, into: bool) -> LineStep:
|
|
634
|
+
"""Run to the next Pebble line on the fast engine, then pause there in the gates.
|
|
635
|
+
|
|
636
|
+
The step starts from the current instruction's line and frame pointer (`r7`).
|
|
637
|
+
It finishes a part-done instruction in the gates (`resume`), then runs one
|
|
638
|
+
instruction at a time on the fast engine. Before each one it stops if the
|
|
639
|
+
word has a ready frame and a Pebble line, and that line or the frame pointer
|
|
640
|
+
differs from the start. A step over (`into=False`) also needs the frame
|
|
641
|
+
pointer at or above the start's, so it runs a whole call; a step into stops
|
|
642
|
+
on the called function's first line. Runtime routine words have no line, so
|
|
643
|
+
they never stop a step. It also stops when the program halts, or after
|
|
644
|
+
`MAX_LINE_INSTRUCTIONS` instructions, and it always pauses at the end.
|
|
645
|
+
`note` says why it stopped, and `instructions` counts only the fast engine's
|
|
646
|
+
instructions, not one the gates finish first.
|
|
647
|
+
|
|
648
|
+
A step that starts where no frame is ready (a prologue word, a return's `ret`
|
|
649
|
+
or a routine) has no frame of its own to compare against. Its `start_fp` is
|
|
650
|
+
taken from the first ready word it reaches instead, so it stops at the next
|
|
651
|
+
*different* line: pressing it just after a load reaches the program's second
|
|
652
|
+
line, and a step over from a function's prologue runs on past its first line.
|
|
653
|
+
|
|
654
|
+
Args:
|
|
655
|
+
into: True to step into a call; False to step over it.
|
|
656
|
+
|
|
657
|
+
Returns:
|
|
658
|
+
How many instructions ran and why the step stopped.
|
|
659
|
+
|
|
660
|
+
Raises:
|
|
661
|
+
CockpitRefusal: If the program is assembly, which has no lines to step.
|
|
662
|
+
CockpitBusy: While playing.
|
|
663
|
+
|
|
664
|
+
"""
|
|
665
|
+
translated = self._pebble_begin()
|
|
666
|
+
if self.before.halted:
|
|
667
|
+
self.note = FINISHED_NOTE
|
|
668
|
+
return LineStep(0, "halted")
|
|
669
|
+
start = self.computer.instruction_start
|
|
670
|
+
finishing = int(not self.computer.gate.at_boundary) # `resume` finishes it in the gates
|
|
671
|
+
ran, stopped, line = self._run_lines(translated, into=into, target=None)
|
|
672
|
+
self.note = _line_note(ran, stopped, line)
|
|
673
|
+
self.happened = describe_move(
|
|
674
|
+
Depth.LINE, start, self.computer.state(), None, translated, ran, finishing=finishing
|
|
675
|
+
)
|
|
676
|
+
self._judge()
|
|
677
|
+
return LineStep(ran, stopped)
|
|
678
|
+
|
|
679
|
+
def run_to_line(self, line: int) -> LineStep:
|
|
680
|
+
"""Run on the fast engine until Pebble line `line` is about to start, then pause.
|
|
681
|
+
|
|
682
|
+
This is a line step (into calls) that keeps going until the line it reaches
|
|
683
|
+
is `line`, so a walk can fast-forward to a moment with a real run. It stops
|
|
684
|
+
where a line step would, the first time that line is `line`; and, like a line
|
|
685
|
+
step, it stops if the program halts or after `MAX_LINE_INSTRUCTIONS`.
|
|
686
|
+
|
|
687
|
+
Returns:
|
|
688
|
+
How many instructions ran, and why it stopped (`"line"` once it is there).
|
|
689
|
+
|
|
690
|
+
Raises:
|
|
691
|
+
CockpitRefusal: If the program is assembly, which has no lines.
|
|
692
|
+
CockpitBusy: While playing.
|
|
693
|
+
|
|
694
|
+
"""
|
|
695
|
+
translated = self._pebble_begin()
|
|
696
|
+
if self.before.halted:
|
|
697
|
+
self.note = FINISHED_NOTE
|
|
698
|
+
return LineStep(0, "halted")
|
|
699
|
+
finishing = int(not self.computer.gate.at_boundary)
|
|
700
|
+
ran, stopped, reached = self._run_lines(translated, into=True, target=line)
|
|
701
|
+
self.note = _line_note(ran, stopped, reached)
|
|
702
|
+
if stopped == "line":
|
|
703
|
+
self.happened = describe_run_to_line(ran, line, finishing)
|
|
704
|
+
else:
|
|
705
|
+
self.happened = describe_run(ran, self.computer.state(), finishing)
|
|
706
|
+
self._judge()
|
|
707
|
+
return LineStep(ran, stopped)
|
|
708
|
+
|
|
709
|
+
def _pebble_begin(self) -> TranslatedProgram:
|
|
710
|
+
"""Start a line move: refuse it for assembly, or while playing, then mark the start."""
|
|
711
|
+
translated = self.translated
|
|
712
|
+
if translated is None:
|
|
713
|
+
raise CockpitRefusal(NOT_PEBBLE_MESSAGE)
|
|
714
|
+
self._begin()
|
|
715
|
+
return translated
|
|
716
|
+
|
|
717
|
+
def _run_lines(
|
|
718
|
+
self, translated: TranslatedProgram, *, into: bool, target: int | None
|
|
719
|
+
) -> tuple[int, str, int | None]:
|
|
720
|
+
"""Run on the fast engine to the next line (or to the line `target`), then pause.
|
|
721
|
+
|
|
722
|
+
See `step_line` for where a line step stops; with a `target` it also needs the
|
|
723
|
+
line it has reached to be `target`.
|
|
724
|
+
|
|
725
|
+
Returns:
|
|
726
|
+
How many instructions ran, why it stopped, and the line it stopped at.
|
|
727
|
+
|
|
728
|
+
"""
|
|
729
|
+
start = self.computer.instruction_start
|
|
730
|
+
frames = translated.frames
|
|
731
|
+
start_line, start_fp = translated.line_at(start.pc), start.registers[FRAME_POINTER]
|
|
732
|
+
settled = start.pc < len(frames) and frames[start.pc] is not None
|
|
733
|
+
self.computer.resume()
|
|
734
|
+
fast = self.computer.fast
|
|
735
|
+
ran, stopped, line, left = 0, "limit", None, False
|
|
736
|
+
try:
|
|
737
|
+
while True:
|
|
738
|
+
if fast.halted:
|
|
739
|
+
stopped = "halted"
|
|
740
|
+
break
|
|
741
|
+
pc, fp = fast.pc, fast.register(FRAME_POINTER)
|
|
742
|
+
line = translated.line_at(pc)
|
|
743
|
+
ready = pc < len(frames) and frames[pc] is not None
|
|
744
|
+
if ready and not settled:
|
|
745
|
+
start_fp, settled = fp, True # the start's own frame, now made
|
|
746
|
+
moved = line != start_line or fp != start_fp
|
|
747
|
+
# A run to a line counts as moved once it has been anywhere else, so a run
|
|
748
|
+
# to the line it starts on goes once round the loop instead of nowhere.
|
|
749
|
+
left = left or (ready and moved and target is not None)
|
|
750
|
+
wanted = target is None or line == target
|
|
751
|
+
if (
|
|
752
|
+
ready
|
|
753
|
+
and line is not None
|
|
754
|
+
and (moved or left)
|
|
755
|
+
and wanted
|
|
756
|
+
and (into or fp >= start_fp)
|
|
757
|
+
):
|
|
758
|
+
stopped = "line"
|
|
759
|
+
break
|
|
760
|
+
if ran == MAX_LINE_INSTRUCTIONS:
|
|
761
|
+
break
|
|
762
|
+
fast.step()
|
|
763
|
+
ran += 1
|
|
764
|
+
finally:
|
|
765
|
+
self.computer.pause()
|
|
766
|
+
return ran, stopped, line
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def _line_note(ran: int, stopped: str, line: int | None) -> str:
|
|
770
|
+
"""Say in one sentence why a line step that moved stopped where it did."""
|
|
771
|
+
if stopped == "line":
|
|
772
|
+
return f"Ran {count_instructions(ran)} to reach line {line}."
|
|
773
|
+
if stopped == "halted":
|
|
774
|
+
return f"Ran {count_instructions(ran)}, and then the program stopped."
|
|
775
|
+
return (
|
|
776
|
+
f"Ran {count_instructions(ran)} without reaching another line, so the step gave up "
|
|
777
|
+
f"there; {LIMIT_REASON}."
|
|
778
|
+
)
|