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/circuit.py ADDED
@@ -0,0 +1,359 @@
1
+ """The netlist: a plain list of wires and the NAND gates that join them.
2
+
3
+ Think of a model railway layout drawn on paper before any track is laid. The
4
+ drawing says which stations exist and which lines join them, but no train runs
5
+ on it. A `Circuit` is that drawing for electronics: it records wires and gates
6
+ and never works out a single value. The `Simulator` is the one who runs trains.
7
+
8
+ NAND is the only kind of gate there is. Each gate is stored as three whole
9
+ numbers (first input wire, second input wire, output wire) in compact arrays, so
10
+ a circuit of half a million gates fits comfortably in memory.
11
+
12
+ Gates can also be filed into named parts, like rooms inside a house inside a
13
+ street. A part is a *scope*, written as a dotted path such as `alu.adder.bit1`,
14
+ and the empty path `""` is the whole circuit. Each gate remembers its scope with
15
+ one more whole number (4 bytes). The parts themselves cost about 200 bytes each:
16
+ a measured 500,010-gate circuit with 197,229 parts used about 59 MB in all, under
17
+ 40 MB of it for part bookkeeping. Each part keeps its running gate total, so
18
+ asking how big a part is takes no searching.
19
+ """
20
+
21
+ from array import array
22
+ from collections.abc import Generator
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass
25
+
26
+ type Wire = int
27
+ type Bus = tuple[Wire, ...]
28
+
29
+ LOW: Wire = 0
30
+ HIGH: Wire = 1
31
+ _FIRST_FREE_WIRE = 2
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Clock:
36
+ """The two beat wires of the machine: `write` first, then `clk`.
37
+
38
+ Registers step when `clk` rises. Memory copies a value in while `write` is
39
+ high. `Simulator.tick` pulses `write` and then `clk`, so memory always
40
+ writes while every register still holds this beat's address and data.
41
+ """
42
+
43
+ clk: Wire
44
+ write: Wire
45
+
46
+
47
+ class Circuit:
48
+ """A drawing of wires and NAND gates, with nothing yet switched on.
49
+
50
+ Every circuit starts with two built-in wires: `low`, which is always 0, and
51
+ `high`, which is always 1. Build the rest with `input`, `bus_input` and
52
+ `nand`, then hand the circuit to a `Simulator` to bring it to life.
53
+ """
54
+
55
+ def __init__(self) -> None:
56
+ """Make an empty circuit holding only the `low` and `high` wires."""
57
+ self.low: Wire = LOW
58
+ self.high: Wire = HIGH
59
+ self._wire_count = _FIRST_FREE_WIRE
60
+ self._first = array("i")
61
+ self._second = array("i")
62
+ self._out = array("i")
63
+ self._driven = bytearray(b"\x01\x01") # 1 when something already sets this wire
64
+ self._is_input = bytearray(_FIRST_FREE_WIRE) # 1 for wires made by `input`
65
+ self._input_names: dict[str, Wire] = {}
66
+ self._state_pairs: list[tuple[str, Wire, Wire]] = []
67
+ # Scope tables: arrays indexed by scope id, with id 0 the root. A path
68
+ # is only stored once, as a key of `_scope_ids`.
69
+ self._scope_of = array("i") # the scope id of each gate
70
+ self._scope_names = [""] # scope id -> its own name, such as "xor#1"
71
+ self._scope_parent = array("i", [-1])
72
+ self._scope_repeats = array("i", [1]) # times this name has been used under its parent
73
+ self._scope_direct = array("i", [0]) # gates sitting directly in the scope
74
+ self._scope_total = array("i", [0]) # gates in the scope and everything nested in it
75
+ self._scope_first_child = array("i", [-1])
76
+ self._scope_last_child = array("i", [-1])
77
+ self._scope_next_sibling = array("i", [-1])
78
+ self._scope_ids: dict[str, int] = {"": 0}
79
+ self._current_scope = 0
80
+ self._by_scope = array("i") # gate ids grouped by scope, built when first needed
81
+ self._by_scope_start = array("i")
82
+ self._index_valid = False
83
+
84
+ @property
85
+ def gate_count(self) -> int:
86
+ """Return how many NAND gates the circuit holds."""
87
+ return len(self._out)
88
+
89
+ @property
90
+ def wire_count(self) -> int:
91
+ """Return how many wires the circuit holds, counting `low` and `high`."""
92
+ return self._wire_count
93
+
94
+ @property
95
+ def gate_wires(self) -> tuple[array[int], array[int], array[int]]:
96
+ """Return the gate table: first inputs, second inputs and outputs.
97
+
98
+ Gate `i` reads `first[i]` and `second[i]` and drives `out[i]`. The arrays
99
+ are the circuit's own, shared for speed, so treat them as read-only.
100
+ """
101
+ return self._first, self._second, self._out
102
+
103
+ @property
104
+ def undriven_count(self) -> int:
105
+ """Return how many wires have no input, constant or gate driving them.
106
+
107
+ These are `wire_placeholder` wires still waiting for their `nand_into`.
108
+ """
109
+ return len(self._driven) - sum(self._driven)
110
+
111
+ @property
112
+ def first_undriven(self) -> Wire:
113
+ """Return the lowest-numbered undriven wire, or -1 if every wire is driven."""
114
+ return self._driven.find(0)
115
+
116
+ @property
117
+ def state_pairs(self) -> tuple[tuple[str, Wire, Wire], ...]:
118
+ """Return every registered storage cell as `(name, q, q_n)`, in the order made."""
119
+ return tuple(self._state_pairs)
120
+
121
+ def state_pair(self, name: str, q: Wire, qn: Wire) -> None:
122
+ """Register a storage cell: two wires that hold a bit and its opposite.
123
+
124
+ `Simulator.poke_pairs` can then write the cell directly, which is how a
125
+ saved state is loaded without ticking the clock. The cell is filed under
126
+ the path of the part being built, such as `r.bit0.master`.
127
+
128
+ Args:
129
+ name: A label for the cell, unique within the current part.
130
+ q: The wire that holds the bit.
131
+ qn: The wire that holds the opposite of the bit.
132
+
133
+ """
134
+ for wire in (q, qn):
135
+ self._check(wire)
136
+ path = self.scope_path(self._current_scope)
137
+ self._state_pairs.append((f"{path}.{name}" if path else name, q, qn))
138
+
139
+ def _new_wire(self, *, driven: bool, is_input: bool = False) -> Wire:
140
+ """Add one wire; `driven` says whether an input or constant already owns it."""
141
+ wire = self._wire_count
142
+ self._wire_count += 1
143
+ self._driven.append(1 if driven else 0)
144
+ self._is_input.append(1 if is_input else 0)
145
+ return wire
146
+
147
+ def _check(self, wire: Wire) -> None:
148
+ """Raise unless `wire` names a wire in this circuit."""
149
+ if not 0 <= wire < self._wire_count:
150
+ msg = f"no such wire: {wire}"
151
+ raise ValueError(msg)
152
+
153
+ def input(self, name: str) -> Wire:
154
+ """Add a wire that a person (or a test) can switch on and off.
155
+
156
+ Args:
157
+ name: A label for the wire. Each label may be used once.
158
+
159
+ Returns:
160
+ The new wire.
161
+
162
+ """
163
+ if name in self._input_names:
164
+ msg = f"input name already used: {name}"
165
+ raise ValueError(msg)
166
+ wire = self._new_wire(driven=True, is_input=True)
167
+ self._input_names[name] = wire
168
+ return wire
169
+
170
+ def bus_input(self, name: str, width: int) -> Bus:
171
+ """Add a row of input wires that together hold one number.
172
+
173
+ Args:
174
+ name: A label for the row; wire `i` is labelled `name[i]`.
175
+ width: How many wires (bits) the row has.
176
+
177
+ Returns:
178
+ The wires, least significant bit first.
179
+
180
+ """
181
+ return tuple(self.input(f"{name}[{i}]") for i in range(width))
182
+
183
+ def nand(self, a: Wire, b: Wire) -> Wire:
184
+ """Add a NAND gate reading wires `a` and `b`, and return its output wire.
185
+
186
+ The output is 0 only when both inputs are 1; otherwise it is 1.
187
+ """
188
+ out = self.wire_placeholder()
189
+ self.nand_into(a, b, out)
190
+ return out
191
+
192
+ def wire_placeholder(self) -> Wire:
193
+ """Add a wire with no gate driving it yet, so a loop can be closed later.
194
+
195
+ A gate cannot read a wire that does not exist, so a circuit that feeds
196
+ its own output back to its input first makes the wire, then connects the
197
+ gate that drives it with `nand_into`.
198
+ """
199
+ return self._new_wire(driven=False)
200
+
201
+ def nand_into(self, a: Wire, b: Wire, out: Wire) -> None:
202
+ """Add a NAND gate reading `a` and `b` that drives the existing wire `out`.
203
+
204
+ Raises:
205
+ ValueError: If a wire does not exist, or `out` is already driven by
206
+ an input, a constant or another gate.
207
+
208
+ """
209
+ for wire in (a, b, out):
210
+ self._check(wire)
211
+ if self._driven[out]:
212
+ msg = f"wire {out} is already driven"
213
+ raise ValueError(msg)
214
+ self._driven[out] = 1
215
+ self._first.append(a)
216
+ self._second.append(b)
217
+ self._out.append(out)
218
+ self._scope_of.append(self._current_scope)
219
+ scope_id = self._current_scope
220
+ self._scope_direct[scope_id] += 1
221
+ while scope_id >= 0: # every part up to the root counts this gate too
222
+ self._scope_total[scope_id] += 1
223
+ scope_id = self._scope_parent[scope_id]
224
+ self._index_valid = False
225
+
226
+ def is_input(self, wire: Wire) -> bool:
227
+ """Return True if `wire` is one made by `input` or `bus_input`."""
228
+ return 0 <= wire < self._wire_count and bool(self._is_input[wire])
229
+
230
+ @contextmanager
231
+ def scope(self, name: str) -> Generator[None]:
232
+ """Label every gate made inside the `with` block as a named part.
233
+
234
+ Scopes nest, so the parts of a part get dotted paths like `alu.adder`.
235
+ Repeated names under one parent get numbered: the first use of `xor`
236
+ stays `xor`, the second becomes `xor#1`, the third `xor#2`, so every
237
+ path names exactly one part.
238
+
239
+ Args:
240
+ name: The part's name. It must not be empty or contain a dot.
241
+
242
+ Raises:
243
+ ValueError: If the name is empty or contains a dot.
244
+
245
+ """
246
+ if not name or "." in name:
247
+ msg = f"a scope name must be non-empty and have no dots: {name!r}"
248
+ raise ValueError(msg)
249
+ parent = self._current_scope
250
+ parent_path = self.scope_path(parent)
251
+ base = f"{parent_path}.{name}" if parent_path else name
252
+ first = self._scope_ids.get(base)
253
+ if first is None:
254
+ unique, path = name, base
255
+ else:
256
+ uses = self._scope_repeats[first]
257
+ self._scope_repeats[first] = uses + 1
258
+ unique = f"{name}#{uses}"
259
+ path = f"{parent_path}.{unique}" if parent_path else unique
260
+ scope_id = len(self._scope_names)
261
+ self._scope_names.append(unique)
262
+ self._scope_parent.append(parent)
263
+ self._scope_repeats.append(1)
264
+ self._scope_direct.append(0)
265
+ self._scope_total.append(0)
266
+ self._scope_first_child.append(-1)
267
+ self._scope_last_child.append(-1)
268
+ self._scope_next_sibling.append(-1)
269
+ self._scope_ids[path] = scope_id
270
+ self._index_valid = False
271
+ last = self._scope_last_child[parent]
272
+ if last < 0:
273
+ self._scope_first_child[parent] = scope_id
274
+ else:
275
+ self._scope_next_sibling[last] = scope_id
276
+ self._scope_last_child[parent] = scope_id
277
+ self._current_scope = scope_id
278
+ try:
279
+ yield
280
+ finally:
281
+ self._current_scope = parent
282
+
283
+ def has_scope(self, path: str) -> bool:
284
+ """Return True if `path` names a part of the circuit (`""` is the whole)."""
285
+ return path in self._scope_ids
286
+
287
+ def _scope_id(self, path: str) -> int:
288
+ """Return the id of a scope, or raise `KeyError` naming the missing path."""
289
+ try:
290
+ return self._scope_ids[path]
291
+ except KeyError:
292
+ msg = f"no such scope: {path!r}"
293
+ raise KeyError(msg) from None
294
+
295
+ def scope_path(self, scope_id: int) -> str:
296
+ """Return the dotted path of scope number `scope_id` (the root is `""`)."""
297
+ names: list[str] = []
298
+ while scope_id > 0:
299
+ names.append(self._scope_names[scope_id])
300
+ scope_id = self._scope_parent[scope_id]
301
+ return ".".join(reversed(names))
302
+
303
+ def children(self, path: str) -> list[str]:
304
+ """Return the names of the parts directly inside `path`, in the order made.
305
+
306
+ Raises:
307
+ KeyError: If `path` is not a scope.
308
+
309
+ """
310
+ names: list[str] = []
311
+ child = self._scope_first_child[self._scope_id(path)]
312
+ while child >= 0:
313
+ names.append(self._scope_names[child])
314
+ child = self._scope_next_sibling[child]
315
+ return names
316
+
317
+ def _build_index(self) -> None:
318
+ """Group the gate ids by scope (a counting sort), so a part finds its gates fast.
319
+
320
+ Built once, the first time a part's gates are asked for after the
321
+ circuit last changed. It costs one pass over the gates and 4 bytes a gate.
322
+ """
323
+ starts = array("i", [0]) * (len(self._scope_names) + 1)
324
+ for scope_id, count in enumerate(self._scope_direct):
325
+ starts[scope_id + 1] = starts[scope_id] + count
326
+ cursor = array("i", starts)
327
+ ordered = array("i", [0]) * len(self._scope_of)
328
+ for gate, scope_id in enumerate(self._scope_of):
329
+ ordered[cursor[scope_id]] = gate
330
+ cursor[scope_id] += 1
331
+ self._by_scope, self._by_scope_start = ordered, starts
332
+ self._index_valid = True
333
+
334
+ def gates_in(self, path: str) -> list[int]:
335
+ """Return the gates that sit directly in `path`, not those in its sub-parts.
336
+
337
+ Raises:
338
+ KeyError: If `path` is not a scope.
339
+
340
+ """
341
+ scope_id = self._scope_id(path)
342
+ if not self._index_valid:
343
+ self._build_index()
344
+ return list(
345
+ self._by_scope[self._by_scope_start[scope_id] : self._by_scope_start[scope_id + 1]]
346
+ )
347
+
348
+ def gate_count_in(self, path: str) -> int:
349
+ """Return how many gates are in `path`, counting every part nested inside it.
350
+
351
+ Raises:
352
+ KeyError: If `path` is not a scope.
353
+
354
+ """
355
+ return self._scope_total[self._scope_id(path)]
356
+
357
+ def scope_of(self, gate: int) -> str:
358
+ """Return the dotted path of the part that gate number `gate` belongs to."""
359
+ return self.scope_path(self._scope_of[gate])
@@ -0,0 +1,8 @@
1
+ """The Cockpit: every dial in view, and a pilot who can freeze the flight.
2
+
3
+ Picture an aeroplane cockpit where every dial shows at once and the pilot can
4
+ freeze the flight, look at any dial, and nudge time forward a little. This package
5
+ is that cockpit for PyCPU: a small local web page that shows the real gates of the
6
+ real computer, with the real 0s and 1s on their wires. It grew out of the Bench.
7
+ It has a session (`session.py`), a picture of it (`picture.py`) and the routes (`app.py`).
8
+ """