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
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fromscratch-pycpu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An educational computer simulated from NAND gates in Python
|
|
5
|
+
Project-URL: Homepage, https://github.com/robcox2910/pycpu
|
|
6
|
+
Project-URL: Repository, https://github.com/robcox2910/pycpu
|
|
7
|
+
Project-URL: Issues, https://github.com/robcox2910/pycpu/issues
|
|
8
|
+
Project-URL: Documentation, https://robcox2910.github.io/pycpu/
|
|
9
|
+
Author: Rob Cox
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: cpu,education,learning,logic-gates,nand
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Education
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Education
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.14
|
|
21
|
+
Requires-Dist: fromscratch-pebble>=0.4.1
|
|
22
|
+
Requires-Dist: fromscratch-pynet>=0.2.0
|
|
23
|
+
Requires-Dist: fromscratch-pyweb>=0.4.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: commitizen>=4.4.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: hypothesis>=6.100; extra == 'dev'
|
|
27
|
+
Requires-Dist: pip-audit>=2.10.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pre-commit>=4.0.1; extra == 'dev'
|
|
29
|
+
Requires-Dist: pyright>=1.1.400; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest-cov>=6.0.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-timeout>=2.3.1; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=8.3.4; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff>=0.9.3; extra == 'dev'
|
|
34
|
+
Provides-Extra: docs
|
|
35
|
+
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# PyCPU
|
|
39
|
+
|
|
40
|
+
An educational computer, built from nothing but NAND gates, in Python.
|
|
41
|
+
|
|
42
|
+
Have you ever wondered what a computer *actually is*, underneath the apps and the
|
|
43
|
+
screen? PyCPU is a project that answers that question by building one, from the
|
|
44
|
+
very bottom. Everything starts with a single tiny part, the **NAND gate**: a switch
|
|
45
|
+
that only turns on when its two inputs are *not both on*. It sounds far too simple to
|
|
46
|
+
matter. But if you wire enough NAND gates together you can make every other gate (a gate is
|
|
47
|
+
a small part that turns switches into a decision), then adders that do sums, then memory
|
|
48
|
+
that remembers, and eventually a whole processor (the part of a computer that follows
|
|
49
|
+
instructions).
|
|
50
|
+
|
|
51
|
+
You build it yourself, in code. [Build It Yourself](docs/build-it-yourself.md) is the
|
|
52
|
+
instruction sheet: the order to write the parts, from one NAND gate up to a computer that
|
|
53
|
+
runs a Pebble program, with a picture to check each step. Then you open the **Cockpit** to
|
|
54
|
+
check and watch what you built.
|
|
55
|
+
|
|
56
|
+
Part of the "from scratch in Python" series. Each layer is made only from the one
|
|
57
|
+
below it, so nothing is hidden, and nothing is faked: when a page shows you a circuit,
|
|
58
|
+
that is the real circuit, doing the real work.
|
|
59
|
+
|
|
60
|
+
## The ladder
|
|
61
|
+
|
|
62
|
+
Each rung is built only from the rung beneath it. An ALU is the part that does the
|
|
63
|
+
sums, RAM is the computer's big notebook, the CPU is the processor that follows instructions,
|
|
64
|
+
and the Assembler turns readable instructions into the numbers the CPU understands. The docs explain every word.
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
Pebble programs <- built for part of Pebble
|
|
68
|
+
Assembler <- built
|
|
69
|
+
The CPU <- built
|
|
70
|
+
Memory (RAM) <- built
|
|
71
|
+
Arithmetic (adders, ALU) <- built
|
|
72
|
+
Gates (AND, OR, ...) <- built
|
|
73
|
+
NAND <- built, where it all starts
|
|
74
|
+
|
|
75
|
+
The Cockpit sits beside the ladder: use it to watch any rung.
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The Cockpit comes second, as the place to check and watch what you built. It is a
|
|
79
|
+
screen where you can watch a program written in Pebble (a small programming language
|
|
80
|
+
from the same series) run on this computer, pause at any moment, and zoom all the way
|
|
81
|
+
down to individual gates.
|
|
82
|
+
The Cockpit is built: a local page (`uv run pycpu`) that opens on **guided
|
|
83
|
+
walks**, short tours of the real machine that end with a small task for you. It shows the
|
|
84
|
+
Pebble program on the left and a magnifying glass on the right. One Step button moves by a
|
|
85
|
+
whole Pebble line, an instruction, a part of the CPU or a single gate, a sentence says
|
|
86
|
+
what just happened, and you can rewind, run, or play the program while the page updates
|
|
87
|
+
live, then pause and look from the CPU down to a single gate. The Expert drawer keeps
|
|
88
|
+
every exact control. Pebble programs run on PyCPU: whole numbers, variables, `if`,
|
|
89
|
+
`while`, `for` over a range, functions and `print`, translated into machine code, with
|
|
90
|
+
multiplying, dividing and printing done by small assembly routines. The rest of Pebble
|
|
91
|
+
(decimals, lists, text in variables, ...) is refused with a friendly message. What is
|
|
92
|
+
left comes next: PyCPU in PyStack (the series' project that joins the others together).
|
|
93
|
+
|
|
94
|
+
## Features
|
|
95
|
+
|
|
96
|
+
- **A gate simulator** -- NAND is the only building block, and every wire's value is real
|
|
97
|
+
- **Logic gates** -- NOT, AND, OR, XOR and friends, each built from NANDs
|
|
98
|
+
- **Choosing and decoding** -- pick one of two values, or light one of many lines
|
|
99
|
+
- **Arithmetic** -- half and full adders, a 16-bit adder, negative numbers
|
|
100
|
+
- **The ALU** -- add, subtract, AND, OR, XOR and shifts, with zero, negative, carry and overflow flags
|
|
101
|
+
- **Memory** -- latches, flip-flops, a two-beat clock, registers, and 4,096 words of RAM
|
|
102
|
+
- **Zoom** -- every part is named, so you can open any circuit and see the gates inside
|
|
103
|
+
- **An instruction set** -- 16 opcodes, every instruction one 16-bit word, with flags, a stack and fault halts
|
|
104
|
+
- **The CPU** -- built from NAND gates and wired to the RAM, fetching and executing one clock beat at a time
|
|
105
|
+
- **An assembler** -- readable assembly in, machine code out, with labels and friendly line-numbered errors
|
|
106
|
+
- **Two engines** -- a fast engine in plain Python, checked in lockstep against the gates
|
|
107
|
+
- **Pause and rewind** -- run fast, pause into the gates, step by a gate, a beat or an instruction, rewind, resume
|
|
108
|
+
- **Pebble on the CPU** -- a translator from Pebble's compiled programs to PyCPU assembly, with frames, jumps, calls, fault lines and a source map
|
|
109
|
+
- **The Cockpit** -- a local web page (served by [PyWeb](https://github.com/robcox2910/pyweb)) opening on guided walks, with the Pebble program on the left and a magnifying glass on the right, one Step button at four depths (line, instruction, part, gate), a "what just happened" sentence, live play and pause
|
|
110
|
+
|
|
111
|
+
## Example
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from pycpu.arithmetic import ripple_adder
|
|
115
|
+
from pycpu.circuit import Circuit
|
|
116
|
+
from pycpu.simulator import Simulator
|
|
117
|
+
|
|
118
|
+
c = Circuit()
|
|
119
|
+
a = c.bus_input("a", 16)
|
|
120
|
+
b = c.bus_input("b", 16)
|
|
121
|
+
total, carry_out = ripple_adder(c, a, b, c.low)
|
|
122
|
+
|
|
123
|
+
sim = Simulator(c)
|
|
124
|
+
sim.set_bus(a, 1234)
|
|
125
|
+
sim.set_bus(b, 4321)
|
|
126
|
+
sim.settle()
|
|
127
|
+
print(sim.get_bus(total)) # 5555, worked out by 240 NAND gates
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Quick start
|
|
131
|
+
|
|
132
|
+
You need Python 3.14 and [uv](https://docs.astral.sh/uv/).
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
uv sync --all-extras
|
|
136
|
+
uv run pytest
|
|
137
|
+
uv run python examples/run_assembly.py # assemble and run a program that prints Hi
|
|
138
|
+
uv run python examples/run_pebble.py # translate a Pebble program and run it: prints 6, 4, 2
|
|
139
|
+
uv run python examples/cockpit_tour.py # follow one Pebble line down to a single gate
|
|
140
|
+
uv run python examples/alu_tour.py # more programs live in examples/
|
|
141
|
+
uv run mkdocs serve # build and read the docs on your own computer
|
|
142
|
+
uv run pycpu # open the Cockpit at http://127.0.0.1:8765
|
|
143
|
+
uvx --from fromscratch-pycpu pycpu # the same, without a clone
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Concepts
|
|
147
|
+
|
|
148
|
+
Every idea gets its own page, with an everyday analogy:
|
|
149
|
+
|
|
150
|
+
| Concept | Doc | Analogy |
|
|
151
|
+
|---------|-----|---------|
|
|
152
|
+
| Bits and binary | [bits-and-binary.md](docs/concepts/bits-and-binary.md) | A light switch |
|
|
153
|
+
| Switches and NAND | [switches-and-nand.md](docs/concepts/switches-and-nand.md) | A lamp with two switches |
|
|
154
|
+
| Simulating a circuit | [simulating-a-circuit.md](docs/concepts/simulating-a-circuit.md) | Dominoes |
|
|
155
|
+
| Logic gates from NAND | [gates.md](docs/concepts/gates.md) | One lamp, many questions |
|
|
156
|
+
| Choosing and decoding | [choosing-and-decoding.md](docs/concepts/choosing-and-decoding.md) | Railway points and a hotel panel |
|
|
157
|
+
| Looking inside a circuit | [looking-inside.md](docs/concepts/looking-inside.md) | A map you can zoom |
|
|
158
|
+
| Adding | [adding.md](docs/concepts/adding.md) | Column addition and carrying the one |
|
|
159
|
+
| Negative numbers | [negative-numbers.md](docs/concepts/negative-numbers.md) | A mileage counter that rolls backwards |
|
|
160
|
+
| The ALU | [the-alu.md](docs/concepts/the-alu.md) | A kitchen multi-tool with a dial |
|
|
161
|
+
| Remembering | [remembering.md](docs/concepts/remembering.md) | Two friends who keep repeating |
|
|
162
|
+
| The clock | [the-clock.md](docs/concepts/the-clock.md) | The drummer in a rowing boat |
|
|
163
|
+
| Registers | [registers.md](docs/concepts/registers.md) | A row of sticky notes |
|
|
164
|
+
| RAM | [ram.md](docs/concepts/ram.md) | A wall of lockers |
|
|
165
|
+
| How big is our memory? | [how-big-is-our-memory.md](docs/concepts/how-big-is-our-memory.md) | Lockers and a stopwatch |
|
|
166
|
+
| Instruction set (reference) | [instruction-set.md](docs/reference/instruction-set.md) | A lookup table, not a lesson |
|
|
167
|
+
| What is a CPU? | [what-is-a-cpu.md](docs/concepts/what-is-a-cpu.md) | A cook and a stack of recipe cards |
|
|
168
|
+
| Machine code | [machine-code.md](docs/concepts/machine-code.md) | A secret code card |
|
|
169
|
+
| Assembly language | [assembly-language.md](docs/concepts/assembly-language.md) | A recipe, and a helper who translates it |
|
|
170
|
+
| The control unit | [the-control-unit.md](docs/concepts/the-control-unit.md) | A railway signal box |
|
|
171
|
+
| Fetch, decode, execute | [fetch-decode-execute.md](docs/concepts/fetch-decode-execute.md) | A cook and a drum |
|
|
172
|
+
| The stack | [the-stack.md](docs/concepts/the-stack.md) | A pile of plates |
|
|
173
|
+
| Calling and returning | [calling-and-returning.md](docs/concepts/calling-and-returning.md) | A bookmark on the pile |
|
|
174
|
+
| Two engines | [two-engines.md](docs/concepts/two-engines.md) | A flip-book and a slow-motion camera |
|
|
175
|
+
| Pausing and rewinding | [pausing-and-rewinding.md](docs/concepts/pausing-and-rewinding.md) | Pause, replay, back to live |
|
|
176
|
+
| From Pebble to machine code | [from-pebble-to-machine-code.md](docs/concepts/from-pebble-to-machine-code.md) | Translating a recipe, card by card |
|
|
177
|
+
| Variables in memory | [variables-in-memory.md](docs/concepts/variables-in-memory.md) | Pigeonholes behind the counter |
|
|
178
|
+
| Why 16-bit numbers wrap | [why-16-bit-numbers-wrap.md](docs/concepts/why-16-bit-numbers-wrap.md) | The mileage counter again |
|
|
179
|
+
| If and while as jumps | [if-and-while-as-jumps.md](docs/concepts/if-and-while-as-jumps.md) | A choose-your-own-adventure book |
|
|
180
|
+
| How a function call really works | [how-a-function-call-really-works.md](docs/concepts/how-a-function-call-really-works.md) | Leaving your desk to help a friend |
|
|
181
|
+
| Multiply and divide | [multiply-and-divide.md](docs/concepts/multiply-and-divide.md) | Long multiplication on paper |
|
|
182
|
+
| Printing a number | [printing-a-number.md](docs/concepts/printing-a-number.md) | A cash register with one slot per letter |
|
|
183
|
+
| What happens when things go wrong | [what-happens-when-things-go-wrong.md](docs/concepts/what-happens-when-things-go-wrong.md) | The referee's whistle |
|
|
184
|
+
| The Cockpit | [the-cockpit.md](docs/concepts/the-cockpit.md) | An aeroplane cockpit: every dial in view, and a pilot who can freeze the flight |
|
|
185
|
+
| Stepping a Pebble line | [stepping-a-pebble-line.md](docs/concepts/stepping-a-pebble-line.md) | Reading aloud with a bookmark |
|
|
186
|
+
| Watching it run | [watching-it-run.md](docs/concepts/watching-it-run.md) | Live radio commentary of a match |
|
|
187
|
+
| A tour of the Cockpit | [a-tour-of-the-cockpit.md](docs/concepts/a-tour-of-the-cockpit.md) | Following one letter through the post |
|
|
188
|
+
| The magnifying glass | [the-magnifying-glass.md](docs/concepts/the-magnifying-glass.md) | A magnifying glass over a map |
|
|
189
|
+
| What just happened | [what-just-happened.md](docs/concepts/what-just-happened.md) | A commentator who only says what really happened |
|
|
190
|
+
| Build It Yourself | [build-it-yourself.md](docs/build-it-yourself.md) | A model kit with a picture on every bag |
|
|
191
|
+
| The code behind a part | [the-code-behind-a-part.md](docs/concepts/the-code-behind-a-part.md) | A toy's instruction booklet, open at the right page |
|
|
192
|
+
| Guided walks | [guided-walks.md](docs/concepts/guided-walks.md) | A museum audio guide |
|
|
193
|
+
|
|
194
|
+
## Read the docs
|
|
195
|
+
|
|
196
|
+
Start with [`docs/index.md`](docs/index.md) ("What Is a Computer, Really?"), then
|
|
197
|
+
[`docs/from-scratch.md`](docs/from-scratch.md) ("Why Build a Computer From Nothing?").
|
|
198
|
+
The docs are the heart of the project; the code exists to back them up.
|
|
199
|
+
|
|
200
|
+
## Developing alongside a sibling
|
|
201
|
+
|
|
202
|
+
PyCPU uses PyWeb, Pebble and PyNet from PyPI (`fromscratch-pyweb`,
|
|
203
|
+
`fromscratch-pebble` and `fromscratch-pynet`). To work on a sibling
|
|
204
|
+
checkout at the same time, install it editable and tell `uv` not to
|
|
205
|
+
re-sync over it:
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
uv pip install -e ../pyweb
|
|
209
|
+
uv run --no-sync pytest
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
## Releasing
|
|
213
|
+
|
|
214
|
+
PyCPU's first release is `v0.1.0`: the whole climb, from gates to Pebble
|
|
215
|
+
programs running in the Cockpit. Other projects in the series use a released
|
|
216
|
+
version of it from PyPI (`fromscratch-pycpu`), not whatever is on `main`. To
|
|
217
|
+
publish a change for them:
|
|
218
|
+
|
|
219
|
+
1. Merge the change to `main`.
|
|
220
|
+
2. Release it: `gh release create vX.Y.Z --target main --generate-notes`
|
|
221
|
+
(or push a `vX.Y.Z` tag); the release workflow publishes it to PyPI.
|
|
222
|
+
A change to the public API bumps the minor version (`v0.1.0` → `v0.2.0`);
|
|
223
|
+
anything else bumps the patch (`v0.1.0` → `v0.1.1`).
|
|
224
|
+
3. In each project that uses it, raise the `fromscratch-pycpu>=X.Y.Z` floor in
|
|
225
|
+
`pyproject.toml`, run `uv lock --upgrade-package fromscratch-pycpu`, and open
|
|
226
|
+
a pull request so CI checks the pair together.
|
|
227
|
+
|
|
228
|
+
Docs-only and tooling-only changes do not get a release.
|
|
229
|
+
|
|
230
|
+
## License
|
|
231
|
+
|
|
232
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
pycpu/__init__.py,sha256=wPlLu0uaol4HZHSSODg8cXEbGk6l411spgWAr3TFuaU,590
|
|
2
|
+
pycpu/__main__.py,sha256=TMpVA7wFV0sbBF59k8SuHFJP-w1DC9Wp8RYg4fhDBIQ,2256
|
|
3
|
+
pycpu/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
|
|
4
|
+
pycpu/arithmetic.py,sha256=84iipKBTHWRjJ4J4k0ZNaQ2GIBW7cEbTCRmuer_ksyA,6094
|
|
5
|
+
pycpu/assembler.py,sha256=XYLulhNKl2jzcjr1ZBAwIUdIywSSF6yapJUgIK8VI3c,21582
|
|
6
|
+
pycpu/circuit.py,sha256=exaWJXxvYw12xIQfmvwap4Vf7337SHRuT80-emRoB48,14087
|
|
7
|
+
pycpu/computer.py,sha256=8ie5yNqxaxW1Dgcugdf1qlZJy7LsSrOUMD5MVzz34Pw,6878
|
|
8
|
+
pycpu/cpu.py,sha256=YK4znx7t1h9EWSj1l_WiJL7btl3h_pYVlGIq03VZLVc,27667
|
|
9
|
+
pycpu/cpu_parts.py,sha256=vliBxoai0ZTFH78-mjuC4oji0w51BgkYHSbKnXLdfk0,5741
|
|
10
|
+
pycpu/fast.py,sha256=9Ykrva3YTLLD6-02B3OsETHcpE7DQem4u4-_7L6379Y,11771
|
|
11
|
+
pycpu/isa.py,sha256=I0CIz8oCFEwf2DdL6An17d08_hVU1NqqXWXx_NVtybY,7202
|
|
12
|
+
pycpu/logic.py,sha256=3_tQqc0fPoMwlrkhOR7e6VWXAEuapoki7pQEpmmHfcw,7200
|
|
13
|
+
pycpu/memory.py,sha256=S1JTFD0Jb_nrLRgZhQzWiah6JFRDzTkm4912oQCi5Rw,11254
|
|
14
|
+
pycpu/proof.py,sha256=6LPJ-sTZT5FufCsTjkPqr4OLZIzajRfLkzThn3RVXvU,10523
|
|
15
|
+
pycpu/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
pycpu/simulator.py,sha256=58Ay_EG6Ct2DsF0VZ9cZAw1P5VbPjddv-05pz1ahJYU,14012
|
|
17
|
+
pycpu/state.py,sha256=aHZcCezc_WhkEktLS_6iAk6oEkHvFPKvPBeL7cVSq-Q,5171
|
|
18
|
+
pycpu/view.py,sha256=DJ7Jbfmhqs0Aqd5IW_m-cV5ijXVe2wn98Wx6z4jKflY,2230
|
|
19
|
+
pycpu/cockpit/__init__.py,sha256=oWTk12xwT2TXtlE_BYdubbZCoN2Lb9fvfPlCV0HFlsw,496
|
|
20
|
+
pycpu/cockpit/app.py,sha256=A6rIMKwaQ5PWsMHiL5R7HtlukawPFoycl8xTKH84Xuw,22849
|
|
21
|
+
pycpu/cockpit/code.py,sha256=mRqxG0s6Wiws5N_EzB37q4G7JB3WGyQnaaj0QvNvANk,6296
|
|
22
|
+
pycpu/cockpit/explain.py,sha256=cbjM4FegY2R4C40gUQt9gvQLO9M6G8ZdmXspyj1nmFU,29355
|
|
23
|
+
pycpu/cockpit/picture.py,sha256=QrmxPS1vteRRJB1A1rZKzOBuqPDtFXZYb9zGEhjHaOk,19847
|
|
24
|
+
pycpu/cockpit/session.py,sha256=oqeZcRThRuvLRxL9w7qSmKx2aPE3K2BoySAtYzhUhTA,31755
|
|
25
|
+
pycpu/cockpit/walks.py,sha256=9o3UrgSCLTuAj_RZkB8Y_waEYfmq95_qfCfpxJuzNxw,17549
|
|
26
|
+
pycpu/cockpit/examples/countdown.pebble,sha256=RamoEQ7bdYAZPYXXAHYfRkSc-o8ip2YHO7pO3TYWBzg,97
|
|
27
|
+
pycpu/cockpit/examples/divide-by-zero.pebble,sha256=2YJgYjP34AFQICWtxT3bygpD6A5vtXiQJpkO41CPZCA,168
|
|
28
|
+
pycpu/cockpit/examples/factorial.pebble,sha256=eU_0439wSHwFCI_5f9WDH8C45PjJSiTrODvjPd_mDug,153
|
|
29
|
+
pycpu/cockpit/examples/greeting.pebble,sha256=BJOrrULzbA9gzGW_7qVLKI9oBsE4O--rq5oxBJlr90A,152
|
|
30
|
+
pycpu/cockpit/examples/times-table.pebble,sha256=oXu7x0kJOz6WBi1V6Pyjh49e-u5RhjCWuAM_YfwULFY,138
|
|
31
|
+
pycpu/cockpit/examples/tour.pebble,sha256=_lc7zaEpC9eLQ9vr6vrkjYAlCVLptVrTCmz4_D70HXw,515
|
|
32
|
+
pycpu/cockpit/walks/a-call-and-the-stack.toml,sha256=zjM6VoBJ6TC9xQ_WlZXfvrGzvbSC2CEPYAdA679r1hc,1628
|
|
33
|
+
pycpu/cockpit/walks/many-instructions.toml,sha256=ASJataWGxTLSdEviIewyH8pN_Q9MyeVtSlO2t6Eny3M,1204
|
|
34
|
+
pycpu/cockpit/walks/subtracting-with-gates.toml,sha256=XUP3vnD99LdnCi0vddeB_UTOn-EprzUw8E2v0CApINk,1161
|
|
35
|
+
pycpu/cockpit/walks/where-n-lives.toml,sha256=MiH7Z-XsnZLD0JG10AGlgHlDHNWoLPHUY-TmqmUDCv0,1013
|
|
36
|
+
pycpu/cockpit/walks/why-the-clock-ticks.toml,sha256=ullVOtz1fzq5fvDGTndeiDFDTHggN59q9r8uqtf8CmQ,1610
|
|
37
|
+
pycpu/translator/__init__.py,sha256=B-YiweT_4dTk5G2Yy4rS_p2ZynhL7osbv0yk40_cRQk,1187
|
|
38
|
+
pycpu/translator/codegen.py,sha256=gHmqXa70j5GHGjDLt_v8HpKh4BXv2Jk0o0j5z6ZZHVw,23794
|
|
39
|
+
pycpu/translator/program.py,sha256=TV8W6SP4IERu82y6wqHpdjI6pUu0tYRV-kdMmCKeToM,8952
|
|
40
|
+
pycpu/translator/runtime.py,sha256=NgxDnOzIEZtXUqF1DHYGyEZFD25SEfupUXz-0WmShwY,9712
|
|
41
|
+
pycpu/translator/subset.py,sha256=IP1c1tMj8o4yrpsLmx8fxNyMSbvfzRJ0W26d0jv__i0,28153
|
|
42
|
+
pycpu/cockpit/page.html,sha256=OP6_Q6t0cMjt9heLmws6XUgmLuFm8y1z2izJttDA1ec,60392
|
|
43
|
+
fromscratch_pycpu-0.1.0.dist-info/METADATA,sha256=Orw9KYC7iCPd3USOZ7loM-hwQRXB8dAubrqY1xte5io,13576
|
|
44
|
+
fromscratch_pycpu-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
45
|
+
fromscratch_pycpu-0.1.0.dist-info/entry_points.txt,sha256=Eqmdk_tJt2vUREkVbvWvza_7bkTaBRU0TqrNqqvC7Gk,46
|
|
46
|
+
fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE,sha256=NtHM2ak--oE71VCcY50kcCoC1cKS0LRUsxq_xA89RNc,1064
|
|
47
|
+
fromscratch_pycpu-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rob Cox
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pycpu/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""PyCPU: a computer built from nothing but NAND gates.
|
|
2
|
+
|
|
3
|
+
Imagine a giant machine made of Lego. Every clever thing it does, from adding
|
|
4
|
+
numbers to running a program, is made by snapping together tiny identical bricks.
|
|
5
|
+
In PyCPU the one brick is the NAND gate, a switch that is on unless both of its
|
|
6
|
+
inputs are on. Gates become adders, adders become an ALU, and memory and a
|
|
7
|
+
processor come after that, each layer built only from the one below it.
|
|
8
|
+
|
|
9
|
+
This package is the start of that climb. Nothing here is faked: when a later layer
|
|
10
|
+
claims to add two numbers, it will do it with real gates.
|
|
11
|
+
"""
|
pycpu/__main__.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Start the Cockpit with `pycpu`.
|
|
2
|
+
|
|
3
|
+
Like switching on the lights in the workshop: this builds the Cockpit app, with a
|
|
4
|
+
whole computer made of NAND gates on it, and serves it on this computer only
|
|
5
|
+
(127.0.0.1) with the tour, the example Pebble program that uses everything PyCPU can
|
|
6
|
+
run, already loaded. Then it prints the address to visit. Building the full-size
|
|
7
|
+
computer takes a few seconds, so it says so first.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from pynet.loop import run
|
|
13
|
+
from pyweb.aserver import AsyncServer
|
|
14
|
+
|
|
15
|
+
from pycpu.cockpit.app import create_cockpit
|
|
16
|
+
from pycpu.memory import RAM_ADDRESS_BITS
|
|
17
|
+
|
|
18
|
+
HOST = "127.0.0.1"
|
|
19
|
+
PORT = 8765
|
|
20
|
+
ADDRESS_BITS = RAM_ADDRESS_BITS # the full 4K words of memory
|
|
21
|
+
START_EXAMPLE = "tour" # the example program loaded when the Cockpit opens
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def open_cockpit(
|
|
25
|
+
port: int = PORT, address_bits: int = ADDRESS_BITS, start_example: str | None = START_EXAMPLE
|
|
26
|
+
) -> AsyncServer:
|
|
27
|
+
"""Switch the Cockpit on at 127.0.0.1 and return the running server.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
port: The port to listen on. Use 0 to let the computer pick a free one.
|
|
31
|
+
address_bits: How many address wires the Cockpit computer's RAM has.
|
|
32
|
+
start_example: The example program to load at the start (the tour unless told
|
|
33
|
+
otherwise), or None for the little assembly demo.
|
|
34
|
+
|
|
35
|
+
"""
|
|
36
|
+
server = AsyncServer(create_cockpit(address_bits, start_example))
|
|
37
|
+
await server.start(HOST, port)
|
|
38
|
+
return server
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def banner(server: AsyncServer) -> str:
|
|
42
|
+
"""Return the two lines that tell the user where the Cockpit is."""
|
|
43
|
+
return f"The Cockpit is open at http://{HOST}:{server.port}\nPress Ctrl+C to close it.\n"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def serve() -> None:
|
|
47
|
+
"""Serve the Cockpit until the user presses Ctrl+C."""
|
|
48
|
+
sys.stdout.write("Building the computer from NAND gates...\n")
|
|
49
|
+
sys.stdout.flush()
|
|
50
|
+
server = await open_cockpit(PORT, ADDRESS_BITS, START_EXAMPLE)
|
|
51
|
+
sys.stdout.write(banner(server))
|
|
52
|
+
sys.stdout.flush()
|
|
53
|
+
try:
|
|
54
|
+
await server.serve_forever()
|
|
55
|
+
finally:
|
|
56
|
+
await server.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def main() -> None:
|
|
60
|
+
"""Run the Cockpit server, quietly stopping on Ctrl+C."""
|
|
61
|
+
try:
|
|
62
|
+
run(serve())
|
|
63
|
+
except KeyboardInterrupt:
|
|
64
|
+
sys.stdout.write("\nThe Cockpit is closed.\n")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
main()
|
pycpu/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
pycpu/arithmetic.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Adders and the ALU, built from the logic gates and nothing else.
|
|
2
|
+
|
|
3
|
+
Think of adding on paper: you work one column at a time from the right, write
|
|
4
|
+
down a digit and carry a one to the next column. A ripple adder is that same
|
|
5
|
+
row of columns made of gates, each column handing its carry to its neighbour.
|
|
6
|
+
The ALU is a kitchen multi-tool wrapped around one such adder: two numbers go
|
|
7
|
+
in, a dial picks the job, and one result comes out with four little lamps
|
|
8
|
+
(flags) that describe it.
|
|
9
|
+
|
|
10
|
+
Like `logic.py`, every function here takes a `Circuit`, adds gates and returns
|
|
11
|
+
wires. None of them works out a value; the `Simulator` does that.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from enum import IntEnum
|
|
16
|
+
|
|
17
|
+
from pycpu.circuit import Bus, Circuit, Wire
|
|
18
|
+
from pycpu.logic import (
|
|
19
|
+
and_,
|
|
20
|
+
and_bus,
|
|
21
|
+
in_own_scope,
|
|
22
|
+
is_zero,
|
|
23
|
+
mux_bus,
|
|
24
|
+
not_,
|
|
25
|
+
or_,
|
|
26
|
+
or_bus,
|
|
27
|
+
xor,
|
|
28
|
+
xor_bus,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
OP_WIDTH = 3
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@in_own_scope
|
|
35
|
+
def half_adder(c: Circuit, a: Wire, b: Wire) -> tuple[Wire, Wire]:
|
|
36
|
+
"""Add two bits and return `(sum, carry)`.
|
|
37
|
+
|
|
38
|
+
The sum digit is 1 when the bits differ (an XOR) and the carry is 1 when
|
|
39
|
+
both are 1 (an AND). Six NAND gates.
|
|
40
|
+
"""
|
|
41
|
+
return xor(c, a, b), and_(c, a, b)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@in_own_scope
|
|
45
|
+
def full_adder(c: Circuit, a: Wire, b: Wire, carry_in: Wire) -> tuple[Wire, Wire]:
|
|
46
|
+
"""Add two bits and a carry that came in, and return `(sum, carry)`.
|
|
47
|
+
|
|
48
|
+
Two half adders in a row, then an OR to join their carries (they can never
|
|
49
|
+
both be 1). Fifteen NAND gates.
|
|
50
|
+
"""
|
|
51
|
+
first_sum, first_carry = half_adder(c, a, b)
|
|
52
|
+
total, second_carry = half_adder(c, first_sum, carry_in)
|
|
53
|
+
return total, or_(c, first_carry, second_carry)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def ripple_adder(c: Circuit, a: Bus, b: Bus, carry_in: Wire) -> tuple[Bus, Wire]:
|
|
57
|
+
"""Add two numbers one column at a time and return `(sum, carry_out)`.
|
|
58
|
+
|
|
59
|
+
Column `i` is a full adder filed in a scope named `bit{i}` in whatever part
|
|
60
|
+
is being built, so a caller can zoom into any column. The carry out of each
|
|
61
|
+
column feeds the next, which is the ripple. Sixteen columns cost 240 gates.
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
ValueError: If the buses differ in width.
|
|
65
|
+
|
|
66
|
+
"""
|
|
67
|
+
if len(a) != len(b):
|
|
68
|
+
msg = f"bus width mismatch: {len(a)} wires against {len(b)}"
|
|
69
|
+
raise ValueError(msg)
|
|
70
|
+
carry = carry_in
|
|
71
|
+
total: list[Wire] = []
|
|
72
|
+
for i, (x, y) in enumerate(zip(a, b, strict=True)):
|
|
73
|
+
with c.scope(f"bit{i}"):
|
|
74
|
+
digit, carry = full_adder(c, x, y, carry)
|
|
75
|
+
total.append(digit)
|
|
76
|
+
return tuple(total), carry
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class AluOp(IntEnum):
|
|
80
|
+
"""The settings on the ALU's dial, as the number the `op` wires spell."""
|
|
81
|
+
|
|
82
|
+
ADD = 0
|
|
83
|
+
SUB = 1
|
|
84
|
+
AND = 2
|
|
85
|
+
OR = 3
|
|
86
|
+
XOR = 4
|
|
87
|
+
SHL = 5
|
|
88
|
+
SHR = 6
|
|
89
|
+
PASS_B = 7
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class AluOutput:
|
|
94
|
+
"""What comes out of the ALU: the answer and four lamps describing it.
|
|
95
|
+
|
|
96
|
+
Attributes:
|
|
97
|
+
result: The answer, 16 wires.
|
|
98
|
+
zero: 1 when every bit of the result is 0.
|
|
99
|
+
negative: 1 when the top bit of the result is 1.
|
|
100
|
+
carry: 1 when a bit fell off the end (see `alu`).
|
|
101
|
+
overflow: 1 when a signed ADD or SUB gave an answer that does not fit.
|
|
102
|
+
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
result: Bus
|
|
106
|
+
zero: Wire
|
|
107
|
+
negative: Wire
|
|
108
|
+
carry: Wire
|
|
109
|
+
overflow: Wire
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def alu(c: Circuit, a: Bus, b: Bus, op: Bus) -> AluOutput:
|
|
113
|
+
"""Add an ALU that does the job `op` names to `a` and `b`.
|
|
114
|
+
|
|
115
|
+
Every answer is worked out all the time and a tree of choosers steered by
|
|
116
|
+
the three `op` wires picks one. Only one adder exists: for `SUB` the bits
|
|
117
|
+
of `b` are flipped and the carry in is 1, because `a - b` is
|
|
118
|
+
`a + NOT b + 1`. The carry flag is the carry out for `ADD` (and for `SUB`,
|
|
119
|
+
where 1 means no borrow), the bit shifted out for `SHL` and `SHR`, and 0
|
|
120
|
+
for the logic operations. The overflow flag is only ever 1 for `ADD` and
|
|
121
|
+
`SUB`. `SHR` is logical: it shifts in a 0.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
ValueError: If `a` and `b` differ in width, or `op` is not 3 wires wide.
|
|
125
|
+
|
|
126
|
+
"""
|
|
127
|
+
if len(a) != len(b):
|
|
128
|
+
msg = f"bus width mismatch: {len(a)} wires against {len(b)}"
|
|
129
|
+
raise ValueError(msg)
|
|
130
|
+
if len(op) != OP_WIDTH:
|
|
131
|
+
msg = f"the op bus must be {OP_WIDTH} wires wide, not {len(op)}"
|
|
132
|
+
raise ValueError(msg)
|
|
133
|
+
top = len(a) - 1
|
|
134
|
+
with c.scope("alu"):
|
|
135
|
+
with c.scope("control"):
|
|
136
|
+
not_o1, not_o2 = not_(c, op[1]), not_(c, op[2])
|
|
137
|
+
subtract = and_(c, and_(c, op[0], not_o1), not_o2) # op == SUB
|
|
138
|
+
with c.scope("operand"):
|
|
139
|
+
b_in = xor_bus(c, b, (subtract,) * len(b))
|
|
140
|
+
with c.scope("adder"):
|
|
141
|
+
total, carry_out = ripple_adder(c, a, b_in, subtract)
|
|
142
|
+
with c.scope("overflow"):
|
|
143
|
+
same_sign = not_(c, xor(c, a[top], b_in[top]))
|
|
144
|
+
changed_sign = xor(c, a[top], total[top])
|
|
145
|
+
overflow = and_(c, same_sign, changed_sign)
|
|
146
|
+
low = c.low
|
|
147
|
+
# Only ADD and SUB carry the real overflow wire; every other candidate
|
|
148
|
+
# holds `low` in that slot, so the flag is 0 for them without extra gates.
|
|
149
|
+
# Each candidate is the 16 result wires, then carry, then overflow.
|
|
150
|
+
candidates = [
|
|
151
|
+
(*total, carry_out, overflow), # ADD
|
|
152
|
+
(*total, carry_out, overflow), # SUB
|
|
153
|
+
(*and_bus(c, a, b), low, low), # AND
|
|
154
|
+
(*or_bus(c, a, b), low, low), # OR
|
|
155
|
+
(*xor_bus(c, a, b), low, low), # XOR
|
|
156
|
+
(low, *a[:top], a[top], low), # SHL: result = 0, a0..a14; carry = a15; overflow = 0
|
|
157
|
+
(*a[1:], low, a[0], low), # SHR: result = a1..a15, 0; carry = a0; overflow = 0
|
|
158
|
+
(*b, low, low), # PASS_B
|
|
159
|
+
]
|
|
160
|
+
with c.scope("select"):
|
|
161
|
+
level = candidates
|
|
162
|
+
for select in op:
|
|
163
|
+
level = [
|
|
164
|
+
mux_bus(c, select, level[i], level[i + 1]) for i in range(0, len(level), 2)
|
|
165
|
+
]
|
|
166
|
+
chosen = level[0]
|
|
167
|
+
result = chosen[: len(a)]
|
|
168
|
+
with c.scope("flags"):
|
|
169
|
+
zero = is_zero(c, result)
|
|
170
|
+
return AluOutput(
|
|
171
|
+
result=result,
|
|
172
|
+
zero=zero,
|
|
173
|
+
negative=result[top],
|
|
174
|
+
carry=chosen[len(a)],
|
|
175
|
+
overflow=chosen[len(a) + 1],
|
|
176
|
+
)
|