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/logic.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Every everyday logic gate, built from NAND and nothing else.
|
|
2
|
+
|
|
3
|
+
Think of a box of identical building blocks. With enough of the one kind of
|
|
4
|
+
block you can make doors, windows, stairs and roofs, if you are clever about
|
|
5
|
+
how they fit together. NAND is the one block here, and this file is the
|
|
6
|
+
instructions for the doors and windows: NOT, AND, OR, XOR, a chooser (mux) and
|
|
7
|
+
a decoder.
|
|
8
|
+
|
|
9
|
+
Each function takes a `Circuit`, adds NAND gates to it, and returns the wire
|
|
10
|
+
(or bus) where the answer will appear. None of them works out a value; the
|
|
11
|
+
`Simulator` does that. The only logic primitive used anywhere in this file is
|
|
12
|
+
`Circuit.nand`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
|
+
from functools import wraps
|
|
17
|
+
from typing import Concatenate
|
|
18
|
+
|
|
19
|
+
from pycpu.circuit import Bus, Circuit, Wire
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def in_own_scope[**P, R](
|
|
23
|
+
build: Callable[Concatenate[Circuit, P], R],
|
|
24
|
+
) -> Callable[Concatenate[Circuit, P], R]:
|
|
25
|
+
"""Make `build` file its gates in a scope named after itself.
|
|
26
|
+
|
|
27
|
+
The scope is a child of whatever part is being built when `build` is
|
|
28
|
+
called, so `xor` called inside `with c.scope("alu")` lands in `alu.xor`.
|
|
29
|
+
Underscores at the end of a name are dropped (`and_` becomes `and`). A
|
|
30
|
+
single NAND (`not_`) is too small to be worth a part and is not wrapped.
|
|
31
|
+
"""
|
|
32
|
+
name = build.__name__.strip("_")
|
|
33
|
+
|
|
34
|
+
@wraps(build)
|
|
35
|
+
def wrapper(c: Circuit, *args: P.args, **kwargs: P.kwargs) -> R:
|
|
36
|
+
"""Open the scope, then build the gates inside it."""
|
|
37
|
+
with c.scope(name):
|
|
38
|
+
return build(c, *args, **kwargs)
|
|
39
|
+
|
|
40
|
+
return wrapper
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def not_(c: Circuit, a: Wire) -> Wire:
|
|
44
|
+
"""Add a NOT gate: the output is 1 when `a` is 0, and 0 when `a` is 1.
|
|
45
|
+
|
|
46
|
+
A NAND with both inputs joined to the same wire. One NAND gate.
|
|
47
|
+
"""
|
|
48
|
+
return c.nand(a, a)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def buffer_into(c: Circuit, source: Wire, target: Wire) -> None:
|
|
52
|
+
"""Make `target` a copy of `source`, using two NOT gates in a row.
|
|
53
|
+
|
|
54
|
+
Flip a wire, then flip it back, and you hold the same value you started
|
|
55
|
+
with. Use this to close a loop when `target` is a placeholder made earlier
|
|
56
|
+
(see `Circuit.wire_placeholder`): a placeholder can only be driven by a gate,
|
|
57
|
+
and a gate that copies is two NANDs. The first NOT lives in the calling part.
|
|
58
|
+
"""
|
|
59
|
+
flipped = not_(c, source)
|
|
60
|
+
c.nand_into(flipped, flipped, target)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@in_own_scope
|
|
64
|
+
def and_(c: Circuit, a: Wire, b: Wire) -> Wire:
|
|
65
|
+
"""Add an AND gate: the output is 1 only when both `a` and `b` are 1.
|
|
66
|
+
|
|
67
|
+
A NAND followed by a NOT. Two NAND gates.
|
|
68
|
+
"""
|
|
69
|
+
return not_(c, c.nand(a, b))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@in_own_scope
|
|
73
|
+
def or_(c: Circuit, a: Wire, b: Wire) -> Wire:
|
|
74
|
+
"""Add an OR gate: the output is 1 when `a`, `b` or both are 1.
|
|
75
|
+
|
|
76
|
+
Flip both inputs, then NAND them. Three NAND gates.
|
|
77
|
+
"""
|
|
78
|
+
return c.nand(not_(c, a), not_(c, b))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@in_own_scope
|
|
82
|
+
def xor(c: Circuit, a: Wire, b: Wire) -> Wire:
|
|
83
|
+
"""Add an XOR gate: the output is 1 when `a` and `b` differ.
|
|
84
|
+
|
|
85
|
+
The classic recipe: `n = NAND(a, b)`, then NAND `a` with `n`, NAND `b` with
|
|
86
|
+
`n`, and NAND those two answers. Four NAND gates.
|
|
87
|
+
"""
|
|
88
|
+
n = c.nand(a, b)
|
|
89
|
+
return c.nand(c.nand(a, n), c.nand(b, n))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@in_own_scope
|
|
93
|
+
def _choose(c: Circuit, not_select: Wire, select: Wire, when_0: Wire, when_1: Wire) -> Wire:
|
|
94
|
+
"""Pick between two wires when the lever and its opposite are already made.
|
|
95
|
+
|
|
96
|
+
Sharing one NOT of the lever across a whole bus saves a gate per bit.
|
|
97
|
+
"""
|
|
98
|
+
return c.nand(c.nand(when_0, not_select), c.nand(when_1, select))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@in_own_scope
|
|
102
|
+
def mux(c: Circuit, select: Wire, when_0: Wire, when_1: Wire) -> Wire:
|
|
103
|
+
"""Add a chooser: pass `when_0` if `select` is 0, or `when_1` if it is 1.
|
|
104
|
+
|
|
105
|
+
Four NAND gates (one of them the NOT of `select`).
|
|
106
|
+
"""
|
|
107
|
+
return _choose(c, not_(c, select), select, when_0, when_1)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _check_widths(a: Bus, b: Bus) -> None:
|
|
111
|
+
"""Raise unless the two buses have the same number of wires."""
|
|
112
|
+
if len(a) != len(b):
|
|
113
|
+
msg = f"bus width mismatch: {len(a)} wires against {len(b)}"
|
|
114
|
+
raise ValueError(msg)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@in_own_scope
|
|
118
|
+
def not_bus(c: Circuit, a: Bus) -> Bus:
|
|
119
|
+
"""Add a NOT gate to every wire of `a` and return the flipped bus."""
|
|
120
|
+
return tuple(not_(c, bit) for bit in a)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@in_own_scope
|
|
124
|
+
def and_bus(c: Circuit, a: Bus, b: Bus) -> Bus:
|
|
125
|
+
"""Add an AND gate for each pair of matching wires in `a` and `b`.
|
|
126
|
+
|
|
127
|
+
Raises:
|
|
128
|
+
ValueError: If the buses differ in width.
|
|
129
|
+
|
|
130
|
+
"""
|
|
131
|
+
_check_widths(a, b)
|
|
132
|
+
return tuple(and_(c, x, y) for x, y in zip(a, b, strict=True))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@in_own_scope
|
|
136
|
+
def or_bus(c: Circuit, a: Bus, b: Bus) -> Bus:
|
|
137
|
+
"""Add an OR gate for each pair of matching wires in `a` and `b`.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
ValueError: If the buses differ in width.
|
|
141
|
+
|
|
142
|
+
"""
|
|
143
|
+
_check_widths(a, b)
|
|
144
|
+
return tuple(or_(c, x, y) for x, y in zip(a, b, strict=True))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@in_own_scope
|
|
148
|
+
def xor_bus(c: Circuit, a: Bus, b: Bus) -> Bus:
|
|
149
|
+
"""Add an XOR gate for each pair of matching wires in `a` and `b`.
|
|
150
|
+
|
|
151
|
+
Raises:
|
|
152
|
+
ValueError: If the buses differ in width.
|
|
153
|
+
|
|
154
|
+
"""
|
|
155
|
+
_check_widths(a, b)
|
|
156
|
+
return tuple(xor(c, x, y) for x, y in zip(a, b, strict=True))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@in_own_scope
|
|
160
|
+
def mux_bus(c: Circuit, select: Wire, when_0: Bus, when_1: Bus) -> Bus:
|
|
161
|
+
"""Pass the whole bus `when_0` if `select` is 0, or `when_1` if it is 1.
|
|
162
|
+
|
|
163
|
+
The NOT of `select` is made once and shared by every bit.
|
|
164
|
+
|
|
165
|
+
Raises:
|
|
166
|
+
ValueError: If the buses differ in width.
|
|
167
|
+
|
|
168
|
+
"""
|
|
169
|
+
_check_widths(when_0, when_1)
|
|
170
|
+
not_select = not_(c, select)
|
|
171
|
+
return tuple(_choose(c, not_select, select, x, y) for x, y in zip(when_0, when_1, strict=True))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@in_own_scope
|
|
175
|
+
def or_many(c: Circuit, wires: Sequence[Wire]) -> Wire:
|
|
176
|
+
"""Return a wire that is 1 when any of `wires` is 1.
|
|
177
|
+
|
|
178
|
+
The ORs are arranged as a balanced tree, so a change on one input passes
|
|
179
|
+
through only about log2(n) gates. With no wires the answer is `c.low`.
|
|
180
|
+
"""
|
|
181
|
+
level = list(wires)
|
|
182
|
+
if not level:
|
|
183
|
+
return c.low
|
|
184
|
+
while len(level) > 1:
|
|
185
|
+
paired = [or_(c, level[i], level[i + 1]) for i in range(0, len(level) - 1, 2)]
|
|
186
|
+
if len(level) % 2:
|
|
187
|
+
paired.append(level[-1])
|
|
188
|
+
level = paired
|
|
189
|
+
return level[0]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@in_own_scope
|
|
193
|
+
def _and_many(c: Circuit, wires: Sequence[Wire]) -> Wire:
|
|
194
|
+
"""Return a wire that is 1 when all of `wires` are 1 (they must not be empty)."""
|
|
195
|
+
level = list(wires)
|
|
196
|
+
while len(level) > 1:
|
|
197
|
+
paired = [and_(c, level[i], level[i + 1]) for i in range(0, len(level) - 1, 2)]
|
|
198
|
+
if len(level) % 2:
|
|
199
|
+
paired.append(level[-1])
|
|
200
|
+
level = paired
|
|
201
|
+
return level[0]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@in_own_scope
|
|
205
|
+
def is_zero(c: Circuit, a: Bus) -> Wire:
|
|
206
|
+
"""Return a wire that is 1 when every bit of `a` is 0."""
|
|
207
|
+
return not_(c, or_many(c, a))
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@in_own_scope
|
|
211
|
+
def decoder(c: Circuit, select: Bus) -> Bus:
|
|
212
|
+
"""Turn a number into one lit line out of many.
|
|
213
|
+
|
|
214
|
+
Output line `i` is 1 exactly when `select` holds the number `i`, so the
|
|
215
|
+
result has `2 ** len(select)` wires and exactly one of them is high.
|
|
216
|
+
"""
|
|
217
|
+
flipped = not_bus(c, select)
|
|
218
|
+
lines: list[Wire] = []
|
|
219
|
+
for value in range(2 ** len(select)):
|
|
220
|
+
bits = [select[i] if (value >> i) & 1 else flipped[i] for i in range(len(select))]
|
|
221
|
+
lines.append(_and_many(c, bits) if bits else c.high)
|
|
222
|
+
return tuple(lines)
|
pycpu/memory.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Memory made of gates: a latch, a flip-flop and a register.
|
|
2
|
+
|
|
3
|
+
Think of a classroom whiteboard. Chalk on the board stays until someone wipes it,
|
|
4
|
+
so the board remembers. A gate on its own is like a puff of smoke: it shows its
|
|
5
|
+
answer and then it is gone. This file shows how to build a whiteboard out of
|
|
6
|
+
smoke, by sending a gate's answer back round to listen to itself.
|
|
7
|
+
|
|
8
|
+
A latch holds one bit. A flip-flop holds one bit and changes only on the beat of
|
|
9
|
+
the clock. A register is a row of flip-flops holding one whole number. RAM is a
|
|
10
|
+
wall of numbered lockers, each a row of latches, with an address to pick one.
|
|
11
|
+
Every piece is made of NAND gates and nothing else; the one thing outside the
|
|
12
|
+
gates is `poke`, which writes a starting value straight into the storage wires.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
|
|
17
|
+
from pycpu.circuit import Bus, Circuit, Clock, Wire
|
|
18
|
+
from pycpu.logic import and_, decoder, in_own_scope, mux_bus, not_, or_many
|
|
19
|
+
from pycpu.simulator import Simulator
|
|
20
|
+
|
|
21
|
+
RAM_ADDRESS_BITS = 12
|
|
22
|
+
RAM_WORDS = 1 << RAM_ADDRESS_BITS
|
|
23
|
+
WORD_BITS = 16
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def make_clock(c: Circuit) -> Clock:
|
|
27
|
+
"""Add the two clock wires, `clk` and `write`, as inputs and return them.
|
|
28
|
+
|
|
29
|
+
Drive them with `Simulator.tick`, which pulses `write` and then `clk`.
|
|
30
|
+
"""
|
|
31
|
+
return Clock(clk=c.input("clk"), write=c.input("write"))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _latch_into(c: Circuit, data: Wire, enable: Wire, q: Wire, qn: Wire) -> None:
|
|
35
|
+
"""Build a D latch whose output wires `q` and `qn` already exist as placeholders.
|
|
36
|
+
|
|
37
|
+
Two NANDs gate `data` with `enable`; two more are the cross-coupled loop.
|
|
38
|
+
The loop gate for `qn` is added first, so with quiet inputs the cell powers
|
|
39
|
+
on holding 0. That guarantee holds only if `enable` is low at power-on; with
|
|
40
|
+
`enable` high the latch follows `data` instead.
|
|
41
|
+
"""
|
|
42
|
+
set_n = c.nand(data, enable)
|
|
43
|
+
reset_n = c.nand(set_n, enable)
|
|
44
|
+
# q_n's gate goes first so that, at power-on, a latch settles to 0, not 1.
|
|
45
|
+
c.nand_into(reset_n, q, qn)
|
|
46
|
+
c.nand_into(set_n, qn, q)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@in_own_scope
|
|
50
|
+
def d_latch(c: Circuit, data: Wire, enable: Wire) -> tuple[Wire, Wire]:
|
|
51
|
+
"""Add a latch that copies `data` while `enable` is 1 and holds it while 0.
|
|
52
|
+
|
|
53
|
+
Four NAND gates. Returns `(q, q_n)`: the held bit and its opposite.
|
|
54
|
+
"""
|
|
55
|
+
q, qn = c.wire_placeholder(), c.wire_placeholder()
|
|
56
|
+
_latch_into(c, data, enable, q, qn)
|
|
57
|
+
return q, qn
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _flip_flop_into(
|
|
61
|
+
c: Circuit, data: Wire, clk: Wire, not_clk: Wire, q: Wire
|
|
62
|
+
) -> tuple[tuple[Wire, Wire], tuple[Wire, Wire]]:
|
|
63
|
+
"""Build a master-slave flip-flop that drives the existing wire `q`.
|
|
64
|
+
|
|
65
|
+
The master is open while `clk` is low; the slave is open while it is high.
|
|
66
|
+
Both cells are registered as state pairs so they can be poked, and returned
|
|
67
|
+
as `(master, slave)`, each a `(q, q_n)` pair.
|
|
68
|
+
"""
|
|
69
|
+
m_q, m_qn = c.wire_placeholder(), c.wire_placeholder()
|
|
70
|
+
s_qn = c.wire_placeholder()
|
|
71
|
+
with c.scope("master"):
|
|
72
|
+
_latch_into(c, data, not_clk, m_q, m_qn)
|
|
73
|
+
with c.scope("slave"):
|
|
74
|
+
_latch_into(c, m_q, clk, q, s_qn)
|
|
75
|
+
c.state_pair("master", m_q, m_qn)
|
|
76
|
+
c.state_pair("slave", q, s_qn)
|
|
77
|
+
return (m_q, m_qn), (q, s_qn)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@in_own_scope
|
|
81
|
+
def d_flip_flop(c: Circuit, data: Wire, clk: Wire) -> Wire:
|
|
82
|
+
"""Add a bit that copies `data` only as `clk` rises, and holds it otherwise.
|
|
83
|
+
|
|
84
|
+
Two latches (master and slave) and one NOT: nine NAND gates. `clk` must be
|
|
85
|
+
a primary clock wire (an input), because the flip-flop relies on its NOT being
|
|
86
|
+
exactly one gate away from it.
|
|
87
|
+
"""
|
|
88
|
+
q = c.wire_placeholder()
|
|
89
|
+
_flip_flop_into(c, data, clk, not_(c, clk), q)
|
|
90
|
+
return q
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Register:
|
|
94
|
+
"""A row of flip-flops holding one number, with a `load` switch.
|
|
95
|
+
|
|
96
|
+
On each `clk` beat the register takes `data` if `load` is 1, and keeps its
|
|
97
|
+
old number if `load` is 0. Each bit lives in its own part, `bit0` upwards,
|
|
98
|
+
inside a part named after the register.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self, c: Circuit, width: int, data: Bus, load: Wire, clock: Clock, name: str
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Add the register's gates to the circuit.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
c: The circuit to build in.
|
|
108
|
+
width: How many bits the register holds.
|
|
109
|
+
data: The wires to copy when loading; they may be placeholders.
|
|
110
|
+
load: A wire that is 1 when the register should take `data`.
|
|
111
|
+
clock: The clock whose `clk` wire steps the register.
|
|
112
|
+
name: The name of the part that holds the register (no dots).
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
ValueError: If `data` is not `width` wires wide.
|
|
116
|
+
|
|
117
|
+
"""
|
|
118
|
+
if len(data) != width:
|
|
119
|
+
msg = f"bus width mismatch: register of {width} bits given {len(data)} wires"
|
|
120
|
+
raise ValueError(msg)
|
|
121
|
+
self.q: Bus = tuple(c.wire_placeholder() for _ in range(width))
|
|
122
|
+
self._cells: list[tuple[tuple[Wire, Wire], tuple[Wire, Wire]]] = []
|
|
123
|
+
with c.scope(name):
|
|
124
|
+
chosen = mux_bus(c, load, self.q, data) # load 0 keeps q, load 1 takes data
|
|
125
|
+
not_clk = not_(c, clock.clk)
|
|
126
|
+
for i in range(width):
|
|
127
|
+
with c.scope(f"bit{i}"):
|
|
128
|
+
self._cells.append(_flip_flop_into(c, chosen[i], clock.clk, not_clk, self.q[i]))
|
|
129
|
+
|
|
130
|
+
def peek(self, sim: Simulator) -> int:
|
|
131
|
+
"""Read the number the register holds, from its output wires."""
|
|
132
|
+
return sim.get_bus(self.q)
|
|
133
|
+
|
|
134
|
+
def poke(self, sim: Simulator, value: int) -> None:
|
|
135
|
+
"""Write a number straight into the register, with no clock beat.
|
|
136
|
+
|
|
137
|
+
Both the master and the slave of every bit are written, or the master
|
|
138
|
+
would still hold the old bit. The circuit is settled afterwards.
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
ValueError: If `value` is negative or too big for the register.
|
|
142
|
+
|
|
143
|
+
"""
|
|
144
|
+
width = len(self._cells)
|
|
145
|
+
if not 0 <= value < 1 << width:
|
|
146
|
+
msg = f"{value} does not fit in {width} bits"
|
|
147
|
+
raise ValueError(msg)
|
|
148
|
+
for i, (master, slave) in enumerate(self._cells):
|
|
149
|
+
sim.poke_pairs([master, slave], (value >> i) & 1)
|
|
150
|
+
sim.settle()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class Ram:
|
|
154
|
+
"""A wall of numbered lockers, each holding one 16-bit word.
|
|
155
|
+
|
|
156
|
+
Give it an address and `out` shows that word. Raise `write_enable` and tick
|
|
157
|
+
the clock and the word at the address becomes `data`. Every bit is a D latch
|
|
158
|
+
(four NAND gates); the address is split in half and each half is decoded,
|
|
159
|
+
and a word's line is one row line AND one column line, so changing the
|
|
160
|
+
address stirs only a few gates. Word `N` lives in part `word<N>`, its bits in
|
|
161
|
+
`bit<M>` inside it, all inside a part named after the RAM.
|
|
162
|
+
|
|
163
|
+
Each cell is a level-sensitive latch: it follows `data` for as long as its
|
|
164
|
+
word's write line is up. So `data` and `address` must not depend on
|
|
165
|
+
`ram.out` while a write happens (for example `data = ram.out + 1` never
|
|
166
|
+
settles, and an address taken straight from `ram.out` can send the write to
|
|
167
|
+
the wrong words). Pass such a value through a `Register` first.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def __init__(
|
|
171
|
+
self,
|
|
172
|
+
c: Circuit,
|
|
173
|
+
address: Bus,
|
|
174
|
+
data: Bus,
|
|
175
|
+
write_enable: Wire,
|
|
176
|
+
clock: Clock,
|
|
177
|
+
name: str = "ram",
|
|
178
|
+
) -> None:
|
|
179
|
+
"""Add the RAM's gates to the circuit.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
c: The circuit to build in.
|
|
183
|
+
address: The wires choosing a word; there are `2 ** len(address)` words.
|
|
184
|
+
data: Sixteen wires to copy into the chosen word when writing.
|
|
185
|
+
write_enable: A wire that is 1 when the beat should write `data`.
|
|
186
|
+
clock: The clock whose `write` pulse times the write.
|
|
187
|
+
name: The name of the part that holds the RAM (no dots).
|
|
188
|
+
|
|
189
|
+
Raises:
|
|
190
|
+
ValueError: If `data` is not 16 wires wide, or `address` is empty.
|
|
191
|
+
|
|
192
|
+
"""
|
|
193
|
+
if len(data) != WORD_BITS:
|
|
194
|
+
msg = f"bus width mismatch: RAM words are {WORD_BITS} bits, given {len(data)} wires"
|
|
195
|
+
raise ValueError(msg)
|
|
196
|
+
if not address:
|
|
197
|
+
msg = "RAM needs at least one address wire"
|
|
198
|
+
raise ValueError(msg)
|
|
199
|
+
low_bits = len(address) // 2
|
|
200
|
+
self._words = 1 << len(address)
|
|
201
|
+
self._cells: list[list[tuple[Wire, Wire]]] = []
|
|
202
|
+
with c.scope(name):
|
|
203
|
+
write_pulse = and_(c, write_enable, clock.write)
|
|
204
|
+
with c.scope("decoder"):
|
|
205
|
+
columns = decoder(c, address[:low_bits])
|
|
206
|
+
rows = decoder(c, address[low_bits:])
|
|
207
|
+
picked: list[list[Wire]] = [[] for _ in range(WORD_BITS)]
|
|
208
|
+
for word in range(self._words):
|
|
209
|
+
row, column = divmod(word, len(columns))
|
|
210
|
+
with c.scope(f"word{word}"):
|
|
211
|
+
# Gates are added directly (not via and_) to keep scopes few.
|
|
212
|
+
word_line = not_(c, c.nand(rows[row], columns[column]))
|
|
213
|
+
write_line = not_(c, c.nand(word_line, write_pulse))
|
|
214
|
+
cells: list[tuple[Wire, Wire]] = []
|
|
215
|
+
for bit in range(WORD_BITS):
|
|
216
|
+
with c.scope(f"bit{bit}"):
|
|
217
|
+
q, qn = c.wire_placeholder(), c.wire_placeholder()
|
|
218
|
+
_latch_into(c, data[bit], write_line, q, qn)
|
|
219
|
+
c.state_pair("cell", q, qn)
|
|
220
|
+
picked[bit].append(not_(c, c.nand(word_line, q)))
|
|
221
|
+
cells.append((q, qn))
|
|
222
|
+
self._cells.append(cells)
|
|
223
|
+
outputs: list[Wire] = []
|
|
224
|
+
for bit in range(WORD_BITS):
|
|
225
|
+
with c.scope(f"read{bit}"):
|
|
226
|
+
outputs.append(or_many(c, picked[bit]))
|
|
227
|
+
self.out: Bus = tuple(outputs)
|
|
228
|
+
|
|
229
|
+
def peek(self, sim: Simulator, address: int) -> int:
|
|
230
|
+
"""Read the word stored at `address` straight from its latches."""
|
|
231
|
+
self._check_address(address)
|
|
232
|
+
return sum(sim.get(q) << bit for bit, (q, _) in enumerate(self._cells[address]))
|
|
233
|
+
|
|
234
|
+
def poke(self, sim: Simulator, address: int, value: int) -> None:
|
|
235
|
+
"""Write a word straight into its latches, with no clock beat and no settling.
|
|
236
|
+
|
|
237
|
+
Settle the simulator afterwards (or use `load`) to see it on `out`.
|
|
238
|
+
|
|
239
|
+
Raises:
|
|
240
|
+
ValueError: If `address` is out of range or `value` does not fit in 16 bits.
|
|
241
|
+
|
|
242
|
+
"""
|
|
243
|
+
self._check_address(address)
|
|
244
|
+
if not 0 <= value < 1 << WORD_BITS:
|
|
245
|
+
msg = f"{value} does not fit in {WORD_BITS} bits"
|
|
246
|
+
raise ValueError(msg)
|
|
247
|
+
for bit, pair in enumerate(self._cells[address]):
|
|
248
|
+
sim.poke_pairs([pair], (value >> bit) & 1)
|
|
249
|
+
|
|
250
|
+
def load(self, sim: Simulator, words: Sequence[int]) -> None:
|
|
251
|
+
"""Poke a whole list of words, starting at address 0, then settle once.
|
|
252
|
+
|
|
253
|
+
Raises:
|
|
254
|
+
ValueError: If there are more words than the RAM holds.
|
|
255
|
+
|
|
256
|
+
"""
|
|
257
|
+
if len(words) > self._words:
|
|
258
|
+
msg = f"{len(words)} words do not fit in a RAM of {self._words} words"
|
|
259
|
+
raise ValueError(msg)
|
|
260
|
+
for address, value in enumerate(words):
|
|
261
|
+
self.poke(sim, address, value)
|
|
262
|
+
sim.settle()
|
|
263
|
+
|
|
264
|
+
def _check_address(self, address: int) -> None:
|
|
265
|
+
"""Raise `ValueError` unless `address` names a word."""
|
|
266
|
+
if not 0 <= address < self._words:
|
|
267
|
+
msg = f"address {address} is outside the RAM's {self._words} words"
|
|
268
|
+
raise ValueError(msg)
|