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/cockpit/app.py ADDED
@@ -0,0 +1,545 @@
1
+ """The Cockpit's web app: routes only, over one `Cockpit` session.
2
+
3
+ Think of the cockpit's radio to the ground crew: each message is read, passed to the
4
+ pilot, and the answer read back. Visitors can freeze the flight, nudge it forward
5
+ (`/api/step`: one gate, a beat, an instruction or a whole Pebble line), wind it back
6
+ (`/api/rewind`), run it a set distance (`/api/run`), let it fly on its own and stop
7
+ it (`/api/play`, `/api/pause`), load a new program (`/api/program`, or `/api/pebble`
8
+ for one that comes with its lyric sheet), pick from the flight plans kept on board
9
+ (`/api/examples`), read its dials (`/api/machine`) and ask what any part is carrying
10
+ (`/api/view`), or meter a CPU part's real inputs and outputs (`/api/part`). The
11
+ guided tours are here too: `/api/walks` lists them, `/api/walk` opens one at a step,
12
+ and `/api/walk/leave` puts the guide away.
13
+ `/api/events` is the radio left switched on: after
14
+ every move, and every slice of play, the new picture goes out to every open page. These
15
+ routes only parse the request, call the session and answer; every rule lives in
16
+ `session.py` and every dial in `picture.py`.
17
+ """
18
+
19
+ from collections.abc import Generator, Mapping
20
+ from contextlib import contextmanager
21
+ from fractions import Fraction
22
+ from importlib import resources
23
+ from typing import Literal
24
+
25
+ from pebble import PebbleError
26
+ from pynet.loop import Task, current_task, sleep, spawn
27
+ from pyweb.app import App
28
+ from pyweb.messages import HTTPError, HttpRequest, HttpResponse, JsonValue, html, json
29
+ from pyweb.sse import EventHub, EventStream, ServerEvent
30
+
31
+ from pycpu.cockpit.picture import listing, machine_picture, part_picture
32
+ from pycpu.cockpit.session import (
33
+ MAX_GATE_STEPS,
34
+ MAX_RUN,
35
+ MAX_SPEED,
36
+ TICK_SECONDS,
37
+ Cockpit,
38
+ CockpitBusy,
39
+ CockpitRefusal,
40
+ Depth,
41
+ NoSuchWalk,
42
+ )
43
+ from pycpu.cockpit.walks import example_source, load_walks
44
+ from pycpu.computer import StepSize
45
+ from pycpu.memory import RAM_ADDRESS_BITS
46
+ from pycpu.translator import UnsupportedFeature
47
+ from pycpu.view import circuit_view
48
+
49
+ BAD_REQUEST = 400
50
+ NOT_FOUND = 404
51
+ CONFLICT = 409
52
+
53
+ # The example programs in `examples/`, in the order the page lists them: the tour first,
54
+ # then from the simplest to the one that goes wrong on purpose.
55
+ EXAMPLE_NAMES = ("tour", "countdown", "times-table", "factorial", "greeting", "divide-by-zero")
56
+
57
+
58
+ # The route checks type and range too so the 400 bodies stay byte-identical; the session
59
+ # re-checks so direct callers are safe.
60
+ def _whole_number(body: Mapping[str, object], name: str, largest: int, default: int | None) -> int:
61
+ """Return `body[name]` as a whole number from 1 to `largest`, or raise a 400.
62
+
63
+ A missing value takes `default` when there is one. Booleans are refused even
64
+ though Python counts them as numbers, because `true` is not what anyone means
65
+ by "run 1 instruction".
66
+ """
67
+ value = body.get(name, default)
68
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= largest:
69
+ msg = f"{name} must be a whole number from 1 to {largest}"
70
+ raise HTTPError(BAD_REQUEST, msg)
71
+ return value
72
+
73
+
74
+ def _object(request: HttpRequest, what: str) -> Mapping[str, object]:
75
+ """Return the request's JSON body as an object, or raise a 400 saying what to send."""
76
+ body = request.json()
77
+ if not isinstance(body, dict):
78
+ raise HTTPError(BAD_REQUEST, f"send a JSON object with {what}")
79
+ return body
80
+
81
+
82
+ def refusal(error: PebbleError | UnsupportedFeature) -> HttpResponse:
83
+ """Answer 400 with the error's message and the line and column it points at.
84
+
85
+ The body has the same `error` and `message` as every other 400 from the Cockpit,
86
+ plus `line` and `column` (1-based, or null when nobody knows) so the page could
87
+ point at the place.
88
+ """
89
+ body: dict[str, JsonValue] = {
90
+ "error": "Bad Request",
91
+ "message": str(error),
92
+ "line": error.line,
93
+ "column": error.column,
94
+ }
95
+ return json(body, BAD_REQUEST)
96
+
97
+
98
+ class _ConflictError(HTTPError):
99
+ """A 409 whose body says "Conflict": PyWeb has no reason phrase of its own for 409."""
100
+
101
+ def __init__(self, message: str) -> None:
102
+ """Store the 409 and the session's message."""
103
+ super().__init__(CONFLICT, message)
104
+
105
+ def to_response(self, request: HttpRequest) -> HttpResponse: # noqa: ARG002
106
+ """Answer with the usual `error` and `message` body, naming the status "Conflict"."""
107
+ return json({"error": "Conflict", "message": self.message}, CONFLICT)
108
+
109
+
110
+ @contextmanager
111
+ def _as_http() -> Generator[None]:
112
+ """Turn a session refusal into the HTTP error a route answers: 409 if busy, else 400."""
113
+ try:
114
+ yield
115
+ except CockpitRefusal as error:
116
+ if isinstance(error, CockpitBusy):
117
+ raise _ConflictError(str(error)) from None
118
+ raise HTTPError(BAD_REQUEST, str(error)) from None
119
+
120
+
121
+ # A line step's size, mapped to whether it steps into calls (True) or over them (False).
122
+ type LineSize = Literal["line", "line_into"]
123
+ LINE_SIZES: dict[LineSize, bool] = {"line": False, "line_into": True}
124
+
125
+
126
+ def _size(value: object) -> StepSize | LineSize | None:
127
+ """Return `value` as a step size or a line size, or None if it is neither."""
128
+ match value:
129
+ case "line":
130
+ return "line"
131
+ case "line_into":
132
+ return "line_into"
133
+ case str() if value in tuple(StepSize):
134
+ return StepSize(value)
135
+ case _:
136
+ return None
137
+
138
+
139
+ def _step_request(request: HttpRequest) -> tuple[StepSize | LineSize | Depth, int]:
140
+ """Read a `POST /api/step` body as a depth, or a step size (or line size) and a count.
141
+
142
+ A body has `depth` or `size`, never both; a `depth` takes no count.
143
+ """
144
+ body = _object(request, "a size")
145
+ if "depth" in body:
146
+ if "size" in body:
147
+ raise HTTPError(BAD_REQUEST, "give a depth or a size, not both")
148
+ depths = ", ".join(f'"{d}"' for d in Depth)
149
+ if body["depth"] not in tuple(Depth):
150
+ raise HTTPError(BAD_REQUEST, f"depth must be one of {depths}")
151
+ count = body.get("count", 1)
152
+ # Only the whole number 1 (or no count): `True` and `1.0` compare equal to 1 but are not it.
153
+ if isinstance(count, bool) or not isinstance(count, int) or count != 1:
154
+ raise HTTPError(BAD_REQUEST, "a depth step takes no count")
155
+ return Depth(body["depth"]), 1
156
+ size = _size(body.get("size"))
157
+ if size is None:
158
+ sizes = ", ".join(f'"{s}"' for s in (*StepSize, *LINE_SIZES))
159
+ raise HTTPError(BAD_REQUEST, f"size must be one of {sizes}")
160
+ count = _whole_number(body, "count", MAX_GATE_STEPS, 1)
161
+ if not isinstance(size, StepSize) and count != 1:
162
+ raise HTTPError(BAD_REQUEST, "count is only for gate steps")
163
+ return size, count
164
+
165
+
166
+ def _step(cockpit: Cockpit, size: StepSize | LineSize | Depth, count: int) -> None:
167
+ """Make one step request's move: a depth's step, a gate, beat or instruction, or a line."""
168
+ if isinstance(size, Depth):
169
+ cockpit.step_at(size)
170
+ elif isinstance(size, StepSize):
171
+ cockpit.step(size, count)
172
+ else:
173
+ cockpit.step_line(into=LINE_SIZES[size])
174
+
175
+
176
+ def _text(request: HttpRequest, what: str, complaint: str) -> str:
177
+ """Return the `source` text of a request body, or raise a 400 with `complaint`."""
178
+ source = _object(request, what).get("source")
179
+ if not isinstance(source, str):
180
+ raise HTTPError(BAD_REQUEST, complaint)
181
+ return source
182
+
183
+
184
+ class _Slicer:
185
+ """Cut play into whole-instruction slices, carrying the leftover fraction to the next.
186
+
187
+ At `speed` instructions a second and a tick of `tick_seconds`, each tick owes
188
+ `speed x tick_seconds` instructions, which is often not a whole number (3 a
189
+ second at 0.1 seconds is 0.3 a tick). Each slice runs the whole part of what is
190
+ owed and keeps the rest, so nothing is lost to rounding. The sums use exact
191
+ fractions, because floating-point 0.1 is not quite a tenth.
192
+ """
193
+
194
+ def __init__(self, speed: int, tick_seconds: float) -> None:
195
+ """Work out the exact share of instructions each tick owes."""
196
+ self.per_tick = speed * Fraction(repr(tick_seconds))
197
+ self.owed = Fraction(0)
198
+
199
+ def next(self) -> int:
200
+ """Return how many whole instructions this tick runs, keeping the fraction."""
201
+ self.owed += self.per_tick
202
+ whole = int(self.owed)
203
+ self.owed -= whole
204
+ return whole
205
+
206
+
207
+ class _Live:
208
+ """The Cockpit's commentator: the session, the event hub and the one play loop.
209
+
210
+ Every route that moves the machine answers through `moved`, which also publishes
211
+ the same picture to every listener. Play is a task on the routes' own event loop,
212
+ so the computer is only ever touched from one thread, and a route never runs
213
+ half-way through a slice.
214
+ """
215
+
216
+ def __init__(self, cockpit: Cockpit, tick_seconds: float) -> None:
217
+ """Start with nobody listening and nothing playing."""
218
+ self.cockpit = cockpit
219
+ self.tick_seconds = tick_seconds
220
+ self.hub = EventHub()
221
+ # The play loop that may be running. A new play or a pause cancels it, so a
222
+ # pause and a quick play again can never leave two loops moving the machine.
223
+ self.player: Task[None] | None = None
224
+
225
+ def answer(self) -> HttpResponse:
226
+ """Answer with the machine picture, without telling anyone else (nothing moved)."""
227
+ return json(machine_picture(self.cockpit)) # pyright: ignore[reportArgumentType]
228
+
229
+ def moved(self) -> HttpResponse:
230
+ """Answer with the machine picture, and publish the same JSON to every listener."""
231
+ response = self.answer()
232
+ self.hub.publish(ServerEvent(response.body.decode(), event="machine"))
233
+ return response
234
+
235
+ def _cancel_player(self) -> None:
236
+ """Cancel the play loop if one is still waiting for its next tick."""
237
+ if self.player is not None:
238
+ self.player.cancel()
239
+ self.player = None
240
+
241
+ def play(self, speed: int) -> HttpResponse:
242
+ """Start playing at `speed` instructions a second, and answer the running picture.
243
+
244
+ Raises:
245
+ CockpitBusy: If it is already playing.
246
+
247
+ """
248
+ self.cockpit.start_playing()
249
+ self._cancel_player()
250
+ self.player = spawn(self._loop(_Slicer(speed, self.tick_seconds)), name="cockpit play")
251
+ return self.moved()
252
+
253
+ def walk(self, name: str, step: int) -> HttpResponse:
254
+ """Open a walk at `step` (stopping any play loop first), and publish the picture.
255
+
256
+ The name and step are checked before the play loop is touched, so a refused
257
+ request leaves play running.
258
+ """
259
+ self.cockpit.check_walk(name, step)
260
+ self._cancel_player()
261
+ self.cockpit.go_to_walk(name, step)
262
+ return self.moved()
263
+
264
+ def pause(self) -> HttpResponse:
265
+ """Stop play at the next instruction boundary; if not playing, change nothing."""
266
+ if not self.cockpit.playing:
267
+ return self.answer()
268
+ self._cancel_player()
269
+ self.cockpit.stop_playing()
270
+ return self.moved()
271
+
272
+ async def _loop(self, slicer: _Slicer) -> None:
273
+ """Run one slice a tick and publish it, until paused, loaded over, or halted."""
274
+ cockpit = self.cockpit
275
+ try:
276
+ while cockpit.playing:
277
+ going = cockpit.play_tick(slicer.next())
278
+ if not going:
279
+ cockpit.stop_playing() # loads the gate engine, at the halt
280
+ self.moved() # the one event for this tick; after a halt, the last
281
+ if not going:
282
+ return
283
+ await sleep(self.tick_seconds)
284
+ finally:
285
+ # Forget this loop once it ends, unless a newer play has already replaced it.
286
+ if self.player is current_task():
287
+ self.player = None
288
+
289
+
290
+ def _example_source(name: str) -> str:
291
+ """Read just the one example file called `name`, which must be one of `EXAMPLE_NAMES`."""
292
+ source = example_source(name)
293
+ if source is None: # pragma: no cover - every name in EXAMPLE_NAMES has a file
294
+ msg = f"no example file called {name}"
295
+ raise ValueError(msg)
296
+ return source
297
+
298
+
299
+ def example_programs() -> list[dict[str, str]]:
300
+ """Read the example Pebble programs, in the order the page lists them.
301
+
302
+ Each file in `src/pycpu/cockpit/examples/` starts with a `#` comment line, which is
303
+ its title.
304
+
305
+ Returns:
306
+ One `{"name", "title", "source"}` for each example: the file's name without
307
+ `.pebble`, the words of its first-line comment, and the whole program.
308
+
309
+ """
310
+ examples: list[dict[str, str]] = []
311
+ for name in EXAMPLE_NAMES:
312
+ source = _example_source(name)
313
+ title = source.splitlines()[0].removeprefix("#").strip()
314
+ examples.append({"name": name, "title": title, "source": source})
315
+ return examples
316
+
317
+
318
+ def create_cockpit(
319
+ address_bits: int = RAM_ADDRESS_BITS,
320
+ start_example: str | None = None,
321
+ *,
322
+ tick_seconds: float = TICK_SECONDS,
323
+ ) -> App:
324
+ """Build the Cockpit app around one `Cockpit` session, paused at the demo program's start.
325
+
326
+ Args:
327
+ address_bits: How many address wires the RAM has. The real Cockpit uses the
328
+ full 12 (4,096 words), which takes a few seconds to build; tests and the
329
+ docs use 6 (64 words).
330
+ start_example: The name of an example (one of `EXAMPLE_NAMES`, such as
331
+ `"tour"`) to load at the start, paused on its first line; None keeps
332
+ `DEMO_PROGRAM`, the little assembly countdown.
333
+ tick_seconds: How long play waits between two slices; tests and the docs
334
+ make it shorter to stay quick.
335
+
336
+ Returns:
337
+ A PyWeb `App` with the routes `GET /` (the page), `GET /api/machine`,
338
+ `GET /api/listing`, `GET /api/examples`, `GET /api/view`, `GET /api/part`,
339
+ `GET /api/events`,
340
+ `POST /api/step`,
341
+ `POST /api/rewind`, `POST /api/run`, `POST /api/play`, `POST /api/pause`,
342
+ `POST /api/program`, `POST /api/pebble`, `GET /api/walks`, `POST /api/walk`
343
+ and `POST /api/walk/leave`. See the Cockpit pages in the
344
+ docs for each one.
345
+
346
+ Raises:
347
+ ValueError: If `start_example` is not the name of an example, or that example
348
+ does not fit in `address_bits` of memory.
349
+
350
+ """
351
+ cockpit = Cockpit(address_bits)
352
+ if start_example is not None:
353
+ _start_with(cockpit, start_example)
354
+ live = _Live(cockpit, tick_seconds)
355
+ app = App()
356
+ _reading_routes(app, live)
357
+ _moving_routes(app, live)
358
+ _play_routes(app, live)
359
+ _walk_routes(app, live)
360
+ return app
361
+
362
+
363
+ def _start_with(cockpit: Cockpit, name: str) -> None:
364
+ """Load the example called `name` on a new Cockpit, as if it had been there all along.
365
+
366
+ Raises:
367
+ ValueError: If there is no example called `name`, or it does not fit this
368
+ Cockpit's memory.
369
+
370
+ """
371
+ if name not in EXAMPLE_NAMES:
372
+ msg = f"no example called {name}; the examples are {', '.join(EXAMPLE_NAMES)}"
373
+ raise ValueError(msg)
374
+ source = _example_source(name)
375
+ try:
376
+ cockpit.start_with_pebble(source)
377
+ except CockpitRefusal as error:
378
+ msg = f"the example {name} cannot start this Cockpit: {error}"
379
+ raise ValueError(msg) from None
380
+
381
+
382
+ def _reading_routes(app: App, live: _Live) -> None:
383
+ """Add the routes that only look: the page, the picture, the listing, the view, events."""
384
+ cockpit = live.cockpit
385
+ page = resources.files("pycpu.cockpit").joinpath("page.html").read_text(encoding="utf-8")
386
+
387
+ @app.get("/")
388
+ def front_page(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
389
+ """Serve the Cockpit page."""
390
+ return html(page)
391
+
392
+ @app.get("/api/machine")
393
+ def machine(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
394
+ """Describe the computer as it is now."""
395
+ return live.answer()
396
+
397
+ @app.get("/api/listing")
398
+ def program_listing( # pyright: ignore[reportUnusedFunction]
399
+ _request: HttpRequest,
400
+ ) -> HttpResponse:
401
+ """List every word of the loaded program, with its source line and labels."""
402
+ return json(listing(cockpit)) # pyright: ignore[reportArgumentType]
403
+
404
+ @app.get("/api/examples")
405
+ def examples(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
406
+ """List the example programs the page offers to load, the tour first."""
407
+ return json(example_programs()) # pyright: ignore[reportArgumentType]
408
+
409
+ @app.get("/api/view")
410
+ def view(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
411
+ """Describe the part named by `?path=`, or the whole circuit with no path.
412
+
413
+ While playing this is the gate engine as it was last paused: the gates are
414
+ not running then, and the fast engine has no wires to show.
415
+ """
416
+ path = request.query.get("path", "") or ""
417
+ try:
418
+ described = circuit_view(cockpit.computer.gate.simulator, path)
419
+ except KeyError:
420
+ raise HTTPError(NOT_FOUND, f"No part called {path}") from None
421
+ return json(described) # pyright: ignore[reportArgumentType]
422
+
423
+ @app.get("/api/part")
424
+ def part(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
425
+ """Read the inputs and outputs of the CPU part named by `?path=`, off its real wires.
426
+
427
+ Unlike `/api/view`, this refuses with 409 while playing: a reading must be the
428
+ wires' value now, and the gates stand still while the fast engine plays.
429
+ """
430
+ path = request.query.get("path", "") or ""
431
+ try:
432
+ with _as_http():
433
+ described = part_picture(cockpit, path)
434
+ except KeyError:
435
+ raise HTTPError(NOT_FOUND, f"No part view for {path or 'an empty path'}") from None
436
+ return json(described) # pyright: ignore[reportArgumentType]
437
+
438
+ @app.get("/api/events")
439
+ def events(_request: HttpRequest) -> EventStream: # pyright: ignore[reportUnusedFunction]
440
+ """Tune in to the live pictures: one `machine` event after every move and tick."""
441
+ return EventStream(live.hub.subscribe())
442
+
443
+
444
+ def _moving_routes(app: App, live: _Live) -> None:
445
+ """Add the routes that move the machine or load it; each publishes its answer."""
446
+ cockpit = live.cockpit
447
+
448
+ @app.post("/api/step")
449
+ def step(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
450
+ """Step by a gate (`count` of them), a clock beat, an instruction or a Pebble line."""
451
+ size, count = _step_request(request)
452
+ with _as_http():
453
+ _step(cockpit, size, count)
454
+ return live.moved()
455
+
456
+ @app.post("/api/rewind")
457
+ def rewind(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
458
+ """Go back to the start of the current instruction."""
459
+ with _as_http():
460
+ cockpit.rewind()
461
+ return live.moved()
462
+
463
+ @app.post("/api/run")
464
+ def run(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
465
+ """Resume, run some instructions on the fast engine, and pause again."""
466
+ body = _object(request, "a number of instructions")
467
+ instructions = _whole_number(body, "instructions", MAX_RUN, None)
468
+ with _as_http():
469
+ cockpit.run(instructions)
470
+ return live.moved()
471
+
472
+ @app.post("/api/program")
473
+ def program(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
474
+ """Assemble new source and load it (stopping play first), or answer 400."""
475
+ source = _text(request, "the assembly text as source", "source must be the assembly text")
476
+ with _as_http():
477
+ cockpit.load_assembly(source)
478
+ return live.moved()
479
+
480
+ @app.post("/api/pebble")
481
+ def pebble(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
482
+ """Translate a Pebble program and load it (stopping play first), or answer 400."""
483
+ complaint = "source must be the Pebble program's text"
484
+ source = _text(request, "the Pebble program as source", complaint)
485
+ try:
486
+ with _as_http():
487
+ cockpit.load_pebble(source)
488
+ except (PebbleError, UnsupportedFeature) as error:
489
+ return refusal(error)
490
+ return live.moved()
491
+
492
+
493
+ def _play_routes(app: App, live: _Live) -> None:
494
+ """Add play and pause."""
495
+
496
+ @app.post("/api/play")
497
+ def play(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
498
+ """Let the computer run on its own at `speed` instructions a second."""
499
+ speed = _whole_number(_object(request, "a speed"), "speed", MAX_SPEED, None)
500
+ with _as_http():
501
+ return live.play(speed)
502
+
503
+ @app.post("/api/pause")
504
+ def pause(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
505
+ """Stop play just before the next instruction; if not playing, change nothing."""
506
+ return live.pause()
507
+
508
+
509
+ def _walk_request(request: HttpRequest) -> tuple[str, int]:
510
+ """Read a `POST /api/walk` body: the walk's `name` and the `step` to open it at."""
511
+ body = _object(request, "a walk name and a step")
512
+ name, step = body.get("name"), body.get("step")
513
+ if not isinstance(name, str):
514
+ raise HTTPError(BAD_REQUEST, "name must be the name of a walk")
515
+ if isinstance(step, bool) or not isinstance(step, int):
516
+ raise HTTPError(BAD_REQUEST, "step must be a whole number")
517
+ return name, step
518
+
519
+
520
+ def _walk_routes(app: App, live: _Live) -> None:
521
+ """Add the guided walks: list them, open one at a step, and leave."""
522
+
523
+ @app.get("/api/walks")
524
+ def walks(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
525
+ """List the walks in the order the page offers them."""
526
+ listed: list[JsonValue] = [
527
+ {"name": w.name, "title": w.title, "see_also": w.see_also} for w in load_walks()
528
+ ]
529
+ return json(listed)
530
+
531
+ @app.post("/api/walk")
532
+ def walk(request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
533
+ """Open a walk at a step by replaying it from its start; play stops first."""
534
+ name, step = _walk_request(request)
535
+ with _as_http():
536
+ try:
537
+ return live.walk(name, step)
538
+ except NoSuchWalk as error: # a refusal too, but one that answers 404
539
+ raise HTTPError(NOT_FOUND, str(error)) from None
540
+
541
+ @app.post("/api/walk/leave")
542
+ def leave(_request: HttpRequest) -> HttpResponse: # pyright: ignore[reportUnusedFunction]
543
+ """Leave the walk; the machine stays where it is."""
544
+ live.cockpit.leave_walk()
545
+ return live.moved()