digsim-engine 1.13.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.
- digsim/circuit/__init__.py +7 -0
- digsim/circuit/_circuit.py +764 -0
- digsim/circuit/_native.py +1029 -0
- digsim/circuit/_waves_writer.py +131 -0
- digsim/circuit/components/__init__.py +52 -0
- digsim/circuit/components/_arithmetic.py +266 -0
- digsim/circuit/components/_bus_bits.py +103 -0
- digsim/circuit/components/_button.py +61 -0
- digsim/circuit/components/_buzzer.py +64 -0
- digsim/circuit/components/_circuit_port.py +293 -0
- digsim/circuit/components/_clock.py +105 -0
- digsim/circuit/components/_counter.py +147 -0
- digsim/circuit/components/_decoder.py +140 -0
- digsim/circuit/components/_dip_switch.py +91 -0
- digsim/circuit/components/_flip_flops.py +162 -0
- digsim/circuit/components/_gates.py +408 -0
- digsim/circuit/components/_hd44780.py +451 -0
- digsim/circuit/components/_hd44780_rom.py +118 -0
- digsim/circuit/components/_hexdigit.py +107 -0
- digsim/circuit/components/_ic.py +96 -0
- digsim/circuit/components/_label_wire.py +204 -0
- digsim/circuit/components/_led.py +66 -0
- digsim/circuit/components/_led_bar.py +67 -0
- digsim/circuit/components/_logic_analyzer.py +111 -0
- digsim/circuit/components/_memory.py +517 -0
- digsim/circuit/components/_memstdout.py +60 -0
- digsim/circuit/components/_note.py +40 -0
- digsim/circuit/components/_on_off_switch.py +64 -0
- digsim/circuit/components/_probe.py +90 -0
- digsim/circuit/components/_seven_segment.py +47 -0
- digsim/circuit/components/_splitter.py +214 -0
- digsim/circuit/components/_static_level.py +54 -0
- digsim/circuit/components/_static_value.py +97 -0
- digsim/circuit/components/_subcircuit.py +439 -0
- digsim/circuit/components/_tristate_buffer.py +81 -0
- digsim/circuit/components/_verilog_component.py +26 -0
- digsim/circuit/components/_yosys_atoms.py +1373 -0
- digsim/circuit/components/_yosys_component.py +1126 -0
- digsim/circuit/components/_yosys_functional.py +1714 -0
- digsim/circuit/components/atoms/__init__.py +28 -0
- digsim/circuit/components/atoms/_component.py +329 -0
- digsim/circuit/components/atoms/_digsim_exception.py +8 -0
- digsim/circuit/components/atoms/_port.py +708 -0
- digsim/circuit/components/ic/4017.json +1062 -0
- digsim/circuit/components/ic/4021.json +286 -0
- digsim/circuit/components/ic/4029.json +1447 -0
- digsim/circuit/components/ic/4094.json +584 -0
- digsim/circuit/components/ic/4511.json +1071 -0
- digsim/circuit/components/ic/74138.json +763 -0
- digsim/circuit/components/ic/74139.json +610 -0
- digsim/circuit/components/ic/74148.json +1368 -0
- digsim/circuit/components/ic/74151.json +303 -0
- digsim/circuit/components/ic/74157.json +248 -0
- digsim/circuit/components/ic/74161.json +674 -0
- digsim/circuit/components/ic/74162.json +631 -0
- digsim/circuit/components/ic/74163.json +673 -0
- digsim/circuit/components/ic/74164.json +267 -0
- digsim/circuit/components/ic/74165.json +319 -0
- digsim/circuit/components/ic/74173.json +403 -0
- digsim/circuit/components/ic/74181.json +2002 -0
- digsim/circuit/components/ic/74182.json +893 -0
- digsim/circuit/components/ic/74193.json +1386 -0
- digsim/circuit/components/ic/74194.json +919 -0
- digsim/circuit/components/ic/74245.json +466 -0
- digsim/circuit/components/ic/74283.json +732 -0
- digsim/circuit/components/ic/74374.json +395 -0
- digsim/circuit/components/ic/7448.json +834 -0
- digsim/circuit/components/ic/74574.json +395 -0
- digsim/circuit/components/ic/74595.json +603 -0
- digsim/circuit/components/ic/7485.json +1042 -0
- digsim/storage_model/__init__.py +19 -0
- digsim/storage_model/_app.py +159 -0
- digsim/storage_model/_circuit.py +266 -0
- digsim/synth/__init__.py +12 -0
- digsim/synth/__main__.py +111 -0
- digsim/synth/_synthesis.py +529 -0
- digsim/utils/__init__.py +25 -0
- digsim/utils/_netlist_graph.py +199 -0
- digsim/utils/_yosys_netlist.py +251 -0
- digsim/verilog/__init__.py +19 -0
- digsim/verilog/__main__.py +78 -0
- digsim/verilog/_formatter.py +225 -0
- digsim/verilog/_lexer.py +218 -0
- digsim_engine-1.13.0.dist-info/METADATA +59 -0
- digsim_engine-1.13.0.dist-info/RECORD +88 -0
- digsim_engine-1.13.0.dist-info/WHEEL +5 -0
- digsim_engine-1.13.0.dist-info/licenses/LICENSE.md +32 -0
- digsim_engine-1.13.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1029 @@
|
|
|
1
|
+
# Copyright (c) Fredrik Andersson, 2023-2026
|
|
2
|
+
# All rights reserved
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
The optional native simulation engine (a trial): the digsim_native package, in Rust,
|
|
6
|
+
from https://github.com/freand76/digsim-native. Without it, or with
|
|
7
|
+
DIGSIM_ENGINE=python, the circuit simulates in Python as before.
|
|
8
|
+
|
|
9
|
+
DIGSIM_ENGINE selects the engine:
|
|
10
|
+
- "native" (the default): the native engine runs the event loop, and simulates the
|
|
11
|
+
Yosys gate cells and the bus ports it knows, the other components are called back in
|
|
12
|
+
Python
|
|
13
|
+
- "python": no native code
|
|
14
|
+
|
|
15
|
+
The native engine simulates a Yosys component as one compiled block (see _block_plan()),
|
|
16
|
+
and the combinational cells it simulates without delays between them. DIGSIM_BLOCKS=0
|
|
17
|
+
turns both off: then every cell has its delay and events, exactly like in the Python
|
|
18
|
+
engine (the same VCD file).
|
|
19
|
+
|
|
20
|
+
The ports that the native engine simulates get a subclass of their class while it runs:
|
|
21
|
+
their value is read from the engine, and setting them sets them in the engine.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import functools
|
|
27
|
+
import os
|
|
28
|
+
from collections.abc import Callable
|
|
29
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
30
|
+
|
|
31
|
+
from .components import _yosys_atoms as atoms
|
|
32
|
+
from .components import _yosys_functional as functional
|
|
33
|
+
from .components._clock import Clock
|
|
34
|
+
from .components._static_level import GND, VDD
|
|
35
|
+
from .components._yosys_component import SignalPort, StatePort, YosysComponent
|
|
36
|
+
from .components.atoms import (
|
|
37
|
+
VALUE_TYPE,
|
|
38
|
+
Component,
|
|
39
|
+
DigsimException,
|
|
40
|
+
Port,
|
|
41
|
+
PortIn,
|
|
42
|
+
PortMultiBitWire,
|
|
43
|
+
PortOutDelta,
|
|
44
|
+
PortWire,
|
|
45
|
+
PortWireBit,
|
|
46
|
+
)
|
|
47
|
+
from .components.atoms._port import connection_generation
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if TYPE_CHECKING:
|
|
51
|
+
from ._circuit import Circuit
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
import digsim_native # type: ignore[import-untyped, import-not-found, unused-ignore]
|
|
55
|
+
except ImportError:
|
|
56
|
+
digsim_native = None
|
|
57
|
+
# An older digsim-native (without blocks, clocks or the initial values of the registers)
|
|
58
|
+
# lacks what this engine calls
|
|
59
|
+
if digsim_native is not None and getattr(digsim_native, "INTERFACE", 0) < 4:
|
|
60
|
+
digsim_native = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def mode() -> str:
|
|
64
|
+
"""The engine to use: "native" or "python" """
|
|
65
|
+
if digsim_native is None:
|
|
66
|
+
return "python"
|
|
67
|
+
return "python" if os.environ.get("DIGSIM_ENGINE") == "python" else "native"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def vcd_writer() -> Any:
|
|
71
|
+
"""
|
|
72
|
+
The VcdWriter class of digsim-native (with both engines), None without one: then
|
|
73
|
+
pyvcd writes the VCD file
|
|
74
|
+
"""
|
|
75
|
+
if digsim_native is None or getattr(digsim_native, "INTERFACE", 0) < 5:
|
|
76
|
+
return None
|
|
77
|
+
return digsim_native.VcdWriter
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# The native cells, by the class they are made from: the kind (the order of Kind in
|
|
81
|
+
# src/lib.rs of digsim-native) and the input ports in the order of the kind
|
|
82
|
+
_GATES: dict[type[Component], tuple[int, str]] = {
|
|
83
|
+
atoms._BUF_: (0, "A"),
|
|
84
|
+
atoms._NOT_: (1, "A"),
|
|
85
|
+
atoms._AND_: (2, "AB"),
|
|
86
|
+
atoms._NAND_: (3, "AB"),
|
|
87
|
+
atoms._OR_: (4, "AB"),
|
|
88
|
+
atoms._NOR_: (5, "AB"),
|
|
89
|
+
atoms._XOR_: (6, "AB"),
|
|
90
|
+
atoms._XNOR_: (7, "AB"),
|
|
91
|
+
atoms._ANDNOT_: (8, "AB"),
|
|
92
|
+
atoms._ORNOT_: (9, "AB"),
|
|
93
|
+
atoms._MUX_: (10, "ABS"),
|
|
94
|
+
atoms._NMUX_: (11, "ABS"),
|
|
95
|
+
atoms._MUX4_: (12, "ABCDST"),
|
|
96
|
+
atoms._MUX8_: (13, "ABCDEFGHSTU"),
|
|
97
|
+
atoms._MUX16_: (14, "ABCDEFGHIJKLMNOPSTUV"),
|
|
98
|
+
atoms._AOI3_: (15, "ABC"),
|
|
99
|
+
atoms._OAI3_: (16, "ABC"),
|
|
100
|
+
atoms._AOI4_: (17, "ABCD"),
|
|
101
|
+
atoms._OAI4_: (18, "ABCD"),
|
|
102
|
+
atoms._TBUF_: (26, "AE"),
|
|
103
|
+
}
|
|
104
|
+
# Flip-flops, latches and GND/VDD, by their base class
|
|
105
|
+
_STATEFUL: dict[type[Component], int] = {
|
|
106
|
+
atoms._DFF_: 19,
|
|
107
|
+
atoms._DFFE2_: 20,
|
|
108
|
+
atoms._DFF3_: 21,
|
|
109
|
+
atoms._DFFE4_: 22,
|
|
110
|
+
atoms._SDFF_: 23,
|
|
111
|
+
atoms._SDFFE_: 24,
|
|
112
|
+
atoms._SDFFCE_: 25,
|
|
113
|
+
GND: 27,
|
|
114
|
+
VDD: 27,
|
|
115
|
+
atoms._SR_: 28,
|
|
116
|
+
atoms._DLATCH_: 29,
|
|
117
|
+
atoms._DLATCH3_: 30,
|
|
118
|
+
atoms._DLATCHSR_: 31,
|
|
119
|
+
atoms._ALDFF_: 32,
|
|
120
|
+
atoms._ALDFFE_: 33,
|
|
121
|
+
atoms._DFFSR_: 34,
|
|
122
|
+
atoms._DFFSRE_: 35,
|
|
123
|
+
}
|
|
124
|
+
# The inputs of the stateful cells (those it has), and their levels
|
|
125
|
+
_STATEFUL_INPUTS = ("C", "D", "E", "R", "S", "L", "AD")
|
|
126
|
+
_LEVELS = (
|
|
127
|
+
"_clock_edge",
|
|
128
|
+
"_reset_level",
|
|
129
|
+
"_reset_value",
|
|
130
|
+
"_enable_level",
|
|
131
|
+
"_set_level",
|
|
132
|
+
"_load_level",
|
|
133
|
+
)
|
|
134
|
+
# The native functional cells, by their class: the kind (the order of KINDS in
|
|
135
|
+
# src/word.rs of digsim-native). Their inputs are in the order they are added.
|
|
136
|
+
_FUNCTIONAL_CLASSES: list[list[type[functional.FunctionalCell]]] = [
|
|
137
|
+
[functional.Not],
|
|
138
|
+
[functional.Pos, functional.Buf],
|
|
139
|
+
[functional.Neg],
|
|
140
|
+
[functional.And],
|
|
141
|
+
[functional.Or],
|
|
142
|
+
[functional.Xor],
|
|
143
|
+
[functional.Xnor],
|
|
144
|
+
[functional.ReduceAnd],
|
|
145
|
+
[functional.ReduceOr, functional.ReduceBool],
|
|
146
|
+
[functional.ReduceXor],
|
|
147
|
+
[functional.ReduceXnor],
|
|
148
|
+
[functional.LogicNot],
|
|
149
|
+
[functional.LogicAnd],
|
|
150
|
+
[functional.LogicOr],
|
|
151
|
+
[functional.Shl, functional.Sshl],
|
|
152
|
+
[functional.Shr],
|
|
153
|
+
[functional.Sshr],
|
|
154
|
+
[functional.Shift],
|
|
155
|
+
[functional.Shiftx],
|
|
156
|
+
[functional.Lt],
|
|
157
|
+
[functional.Le],
|
|
158
|
+
[functional.Gt],
|
|
159
|
+
[functional.Ge],
|
|
160
|
+
[functional.Eq],
|
|
161
|
+
[functional.Ne],
|
|
162
|
+
[functional.Eqx],
|
|
163
|
+
[functional.Nex],
|
|
164
|
+
[functional.Add],
|
|
165
|
+
[functional.Sub],
|
|
166
|
+
[functional.Mul],
|
|
167
|
+
[functional.Div],
|
|
168
|
+
[functional.Mod],
|
|
169
|
+
[functional.DivFloor],
|
|
170
|
+
[functional.ModFloor],
|
|
171
|
+
[functional.Pow],
|
|
172
|
+
[functional.Mux],
|
|
173
|
+
[functional.Pmux],
|
|
174
|
+
[functional.Bmux],
|
|
175
|
+
[functional.Demux],
|
|
176
|
+
[functional.Bwmux],
|
|
177
|
+
[functional.Dff],
|
|
178
|
+
[functional.Dffe],
|
|
179
|
+
[functional.Adff],
|
|
180
|
+
[functional.Adffe],
|
|
181
|
+
[functional.Aldff],
|
|
182
|
+
[functional.Aldffe],
|
|
183
|
+
[functional.Sdff],
|
|
184
|
+
[functional.Sdffe],
|
|
185
|
+
[functional.Sdffce],
|
|
186
|
+
[functional.Dffsr],
|
|
187
|
+
[functional.Dffsre],
|
|
188
|
+
[functional.Dlatch],
|
|
189
|
+
[functional.Adlatch],
|
|
190
|
+
[functional.Dlatchsr],
|
|
191
|
+
[functional.Sr],
|
|
192
|
+
[functional.Decoder],
|
|
193
|
+
[functional.Alu],
|
|
194
|
+
[functional.Lcu],
|
|
195
|
+
[functional.Fa],
|
|
196
|
+
[functional.MaccV2],
|
|
197
|
+
[functional.Lut],
|
|
198
|
+
[functional.Sop],
|
|
199
|
+
[functional.Bweqx],
|
|
200
|
+
[functional.Concat],
|
|
201
|
+
[functional.Slice],
|
|
202
|
+
[functional.Tribuf],
|
|
203
|
+
]
|
|
204
|
+
_FUNCTIONAL: dict[type[functional.FunctionalCell], int] = {
|
|
205
|
+
cls: kind for kind, classes in enumerate(_FUNCTIONAL_CLASSES) for cls in classes
|
|
206
|
+
}
|
|
207
|
+
# Port kinds, as in src/lib.rs of digsim-native
|
|
208
|
+
_PY, _IN, _WIRE, _OUT, _BIT, _BUS, _CELL_INPUT, _WORD, _BLOCK_PIN, _BLOCK_INNER, _CLOCK = range(11)
|
|
209
|
+
# Bus ports that work the same natively, they don't change how the value is handled
|
|
210
|
+
_BUS_CLASSES = (PortMultiBitWire, SignalPort, StatePort)
|
|
211
|
+
_NONE = 2**32 - 1
|
|
212
|
+
_CODES: dict[Any, int] = {0: 0, 1: 1, "X": 2, "Z": 3}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _cell(component: Component) -> tuple[int, list[Port | None], list[int]] | None:
|
|
216
|
+
"""The native kind, input ports and levels of a component, None if it isn't one"""
|
|
217
|
+
gate = _GATES.get(type(component))
|
|
218
|
+
if gate is not None:
|
|
219
|
+
kind, names = gate
|
|
220
|
+
return kind, [component.port(name) for name in names], [0] * len(_LEVELS)
|
|
221
|
+
for base in type(component).__mro__:
|
|
222
|
+
stateful = _STATEFUL.get(base)
|
|
223
|
+
if stateful is None:
|
|
224
|
+
continue
|
|
225
|
+
port_names = {port.name() for port in component.ports}
|
|
226
|
+
inputs = [
|
|
227
|
+
component.port(name) if name in port_names else None for name in _STATEFUL_INPUTS
|
|
228
|
+
]
|
|
229
|
+
levels = [getattr(component, attribute, 0) for attribute in _LEVELS]
|
|
230
|
+
return stateful, inputs, levels
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _plain(port: Port) -> bool:
|
|
235
|
+
"""A port without several drivers or its own set_value()"""
|
|
236
|
+
return port._drivers is None and "set_value" not in port.__dict__
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _resolved(port: Port) -> bool:
|
|
240
|
+
"""A port of one bit with several drivers, the engine resolves its value"""
|
|
241
|
+
drivers = port._drivers
|
|
242
|
+
return (
|
|
243
|
+
drivers is not None
|
|
244
|
+
and port.width == 1
|
|
245
|
+
and port.__dict__.get("set_value") == drivers.set_value
|
|
246
|
+
and all(driver.width == 1 for driver in drivers.drivers)
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _driven_natively(port: Port) -> bool:
|
|
251
|
+
"""A port that the engine can set: one driver, or one bit and several"""
|
|
252
|
+
return _plain(port) or _resolved(port)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _can_be_native(component: Component) -> bool:
|
|
256
|
+
"""A cell whose ports work the same natively: one bit each"""
|
|
257
|
+
for port in component.ports:
|
|
258
|
+
if port.width != 1 or not _driven_natively(port):
|
|
259
|
+
return False
|
|
260
|
+
if port.is_output():
|
|
261
|
+
if type(port) is not PortOutDelta or port._update_parent:
|
|
262
|
+
return False
|
|
263
|
+
elif type(port) not in (PortIn, PortWire):
|
|
264
|
+
return False
|
|
265
|
+
return True
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _word_cell_can_be_native(component: Component) -> bool:
|
|
269
|
+
"""A functional cell whose ports work the same natively"""
|
|
270
|
+
if type(component) not in _FUNCTIONAL:
|
|
271
|
+
return False
|
|
272
|
+
assert isinstance(component, functional.FunctionalCell)
|
|
273
|
+
for port in component.ports:
|
|
274
|
+
if not _driven_natively(port):
|
|
275
|
+
return False
|
|
276
|
+
if port.is_output():
|
|
277
|
+
if type(port) is not PortOutDelta or port._update_parent:
|
|
278
|
+
return False
|
|
279
|
+
elif type(port) is not functional._CellInput:
|
|
280
|
+
return False
|
|
281
|
+
return all(type(port) is functional._WordOut for port in component._word_outputs.values())
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _native_word_cells(components: list[Component]) -> list[functional.FunctionalCell]:
|
|
285
|
+
"""
|
|
286
|
+
The functional cells to simulate natively. Cells linked as words are both native or
|
|
287
|
+
both Python, so a cell that can't be native keeps the cells it is linked to in Python.
|
|
288
|
+
"""
|
|
289
|
+
cells = [c for c in components if isinstance(c, functional.FunctionalCell)]
|
|
290
|
+
native = {cell for cell in cells if _word_cell_can_be_native(cell)}
|
|
291
|
+
changed = True
|
|
292
|
+
while changed:
|
|
293
|
+
changed = False
|
|
294
|
+
for cell in cells:
|
|
295
|
+
for word_output in cell._word_outputs.values():
|
|
296
|
+
for target in word_output._links:
|
|
297
|
+
if (cell in native) != (target in native):
|
|
298
|
+
native.discard(cell)
|
|
299
|
+
native.discard(target)
|
|
300
|
+
changed = True
|
|
301
|
+
return [cell for cell in cells if cell in native]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _bus_can_be_native(port: Port) -> bool:
|
|
305
|
+
"""A bus port, of at most 64 bits, that works the same natively"""
|
|
306
|
+
if type(port) not in _BUS_CLASSES or port.width > 64 or not _plain(port):
|
|
307
|
+
return False
|
|
308
|
+
bits = port._bits # type: ignore[attr-defined]
|
|
309
|
+
return all(type(bit) is PortWireBit and _driven_natively(bit) for bit in bits)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _BlockCell(NamedTuple):
|
|
313
|
+
"""A cell of a block: its component, and its arguments for the engine but the word cell"""
|
|
314
|
+
|
|
315
|
+
component: Component
|
|
316
|
+
op: int # 0 functional, 1 gate, 2 constant
|
|
317
|
+
kind: int
|
|
318
|
+
inputs: list[tuple[list[tuple[int, int]], bool]]
|
|
319
|
+
outputs: list[int]
|
|
320
|
+
stateful: bool
|
|
321
|
+
levels: list[int]
|
|
322
|
+
clock: int
|
|
323
|
+
value: int # A constant: its value, a gate flip-flop or latch: its initial value
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class _BlockPlan(NamedTuple):
|
|
327
|
+
"""A Yosys component compiled to one block of the engine (see src/block.rs)"""
|
|
328
|
+
|
|
329
|
+
component: YosysComponent
|
|
330
|
+
members: set[Component]
|
|
331
|
+
widths: list[int]
|
|
332
|
+
cells: list[_BlockCell]
|
|
333
|
+
ranks: list[int]
|
|
334
|
+
# The (slot, bit) of each port of the members, by id()
|
|
335
|
+
bits: dict[int, tuple[int, int]]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _compiled() -> bool:
|
|
339
|
+
"""Blocks and levels of cells (DIGSIM_BLOCKS=0 for the events of every cell)"""
|
|
340
|
+
return os.environ.get("DIGSIM_BLOCKS") != "0"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _block_plan(component: YosysComponent) -> _BlockPlan | None:
|
|
344
|
+
"""
|
|
345
|
+
The block of a Yosys component, None if it can't be one: the native engine simulates
|
|
346
|
+
it as one block, the combinational cells in the order of their ranks without events
|
|
347
|
+
in between (like a compiled simulator), instead of with a delay for each cell. A
|
|
348
|
+
netlist with a combinational loop, tristate buffers or inout ports, or cells it
|
|
349
|
+
doesn't have, keeps the cells.
|
|
350
|
+
"""
|
|
351
|
+
if not _compiled():
|
|
352
|
+
return None
|
|
353
|
+
try:
|
|
354
|
+
parts = component.netlist_parts()
|
|
355
|
+
except DigsimException:
|
|
356
|
+
return None
|
|
357
|
+
if any(port.is_inout for port in parts.ports.values()):
|
|
358
|
+
return None
|
|
359
|
+
members = set(parts.components.values())
|
|
360
|
+
widths = [1, 1] # GND and VDD
|
|
361
|
+
net_bits: dict[Any, tuple[int, int]] = {"0": (0, 0), "1": (1, 0)}
|
|
362
|
+
for module_port in parts.ports.values():
|
|
363
|
+
if module_port.is_output:
|
|
364
|
+
continue
|
|
365
|
+
slot = len(widths)
|
|
366
|
+
widths.append(len(module_port.bits))
|
|
367
|
+
for bit, net in enumerate(module_port.bits):
|
|
368
|
+
net_bits.setdefault(net, (slot, bit))
|
|
369
|
+
# The cells and their output slots, then their inputs (they need all outputs)
|
|
370
|
+
found: list[tuple[Component, Any, list[int]]] = []
|
|
371
|
+
for cellname, yosys_cell in parts.cells.items():
|
|
372
|
+
cell_component = parts.components.get(cellname)
|
|
373
|
+
if cell_component is None:
|
|
374
|
+
continue
|
|
375
|
+
outputs: list[int] = []
|
|
376
|
+
if isinstance(cell_component, functional.FunctionalCell):
|
|
377
|
+
if (
|
|
378
|
+
not _word_cell_can_be_native(cell_component)
|
|
379
|
+
or isinstance(cell_component, functional.Tribuf)
|
|
380
|
+
or cell_component._word_outputs.keys() - cell_component._outputs.keys()
|
|
381
|
+
):
|
|
382
|
+
return None
|
|
383
|
+
for name in cell_component._outputs:
|
|
384
|
+
slot = len(widths)
|
|
385
|
+
widths.append(len(cell_component._bits[name]))
|
|
386
|
+
outputs.append(slot)
|
|
387
|
+
for bit, net in enumerate(yosys_cell.connections[name]):
|
|
388
|
+
net_bits[net] = (slot, bit)
|
|
389
|
+
else:
|
|
390
|
+
gate = _cell(cell_component)
|
|
391
|
+
if gate is None or gate[0] in (26, 27) or not _can_be_native(cell_component):
|
|
392
|
+
return None
|
|
393
|
+
output = cell_component.outports()[0]
|
|
394
|
+
slot = len(widths)
|
|
395
|
+
widths.append(1)
|
|
396
|
+
outputs.append(slot)
|
|
397
|
+
net_bits[yosys_cell.connections[output.name()][0]] = (slot, 0)
|
|
398
|
+
found.append((cell_component, yosys_cell, outputs))
|
|
399
|
+
|
|
400
|
+
def net_bit(net: Any) -> tuple[int, int]:
|
|
401
|
+
return net_bits.get(net, (_NONE, 0))
|
|
402
|
+
|
|
403
|
+
bits: dict[int, tuple[int, int]] = {}
|
|
404
|
+
cells: list[_BlockCell] = []
|
|
405
|
+
for cell_component, yosys_cell, outputs in found:
|
|
406
|
+
inputs: list[tuple[list[tuple[int, int]], bool]] = []
|
|
407
|
+
if isinstance(cell_component, functional.FunctionalCell):
|
|
408
|
+
stateful = isinstance(cell_component, functional._Register)
|
|
409
|
+
for name in cell_component._inputs:
|
|
410
|
+
nets = yosys_cell.connections[name]
|
|
411
|
+
update = name in cell_component._updating_inputs
|
|
412
|
+
if not stateful and not update:
|
|
413
|
+
return None
|
|
414
|
+
inputs.append(([net_bit(net) for net in nets], update))
|
|
415
|
+
for bit_port, net in zip(cell_component._bits[name], nets, strict=True):
|
|
416
|
+
bits[id(bit_port)] = net_bit(net)
|
|
417
|
+
for name, slot in zip(cell_component._outputs, outputs, strict=True):
|
|
418
|
+
for bit, bit_port in enumerate(cell_component._bits[name]):
|
|
419
|
+
bits[id(bit_port)] = (slot, bit)
|
|
420
|
+
cells.append(
|
|
421
|
+
_BlockCell(cell_component, 0, 0, inputs, outputs, stateful, [0] * 6, 2, 0)
|
|
422
|
+
)
|
|
423
|
+
continue
|
|
424
|
+
kind, ports, levels = _cell(cell_component) # type: ignore[misc]
|
|
425
|
+
stateful = kind >= 19
|
|
426
|
+
names = _GATES[type(cell_component)][1] if not stateful else _STATEFUL_INPUTS
|
|
427
|
+
names_list = list(names) if not stateful else list(_STATEFUL_INPUTS)
|
|
428
|
+
for name, gate_port in zip(names_list, ports, strict=True):
|
|
429
|
+
if gate_port is None:
|
|
430
|
+
inputs.append(([(_NONE, 0)], False))
|
|
431
|
+
continue
|
|
432
|
+
update = type(gate_port) is PortIn
|
|
433
|
+
if not stateful and not update:
|
|
434
|
+
return None
|
|
435
|
+
net = yosys_cell.connections[name][0]
|
|
436
|
+
inputs.append(([net_bit(net)], update))
|
|
437
|
+
bits[id(gate_port)] = net_bit(net)
|
|
438
|
+
bits[id(cell_component.outports()[0])] = (outputs[0], 0)
|
|
439
|
+
clock = _CODES.get(getattr(cell_component, "_old_C_level", "X"), 2)
|
|
440
|
+
initial = _CODES[getattr(cell_component, "initial_value", 0)] if stateful else 0
|
|
441
|
+
cells.append(
|
|
442
|
+
_BlockCell(cell_component, 1, kind, inputs, outputs, stateful, levels, clock, initial)
|
|
443
|
+
)
|
|
444
|
+
for value, name in ((0, "GND"), (1, "VDD")):
|
|
445
|
+
constant = parts.components[name]
|
|
446
|
+
bits[id(constant.port("O"))] = (value, 0)
|
|
447
|
+
cells.append(_BlockCell(constant, 2, 27, [], [value], True, [0] * 6, 2, value))
|
|
448
|
+
# The ranks of the combinational cells: above the cells that drive them
|
|
449
|
+
producer = {slot: number for number, c in enumerate(cells) for slot in c.outputs}
|
|
450
|
+
drivers: list[set[int]] = []
|
|
451
|
+
for block_cell in cells:
|
|
452
|
+
sources = set()
|
|
453
|
+
if not block_cell.stateful:
|
|
454
|
+
for input_bits, _update in block_cell.inputs:
|
|
455
|
+
for slot, _bit in input_bits:
|
|
456
|
+
producer_cell = producer.get(slot)
|
|
457
|
+
if producer_cell is not None and not cells[producer_cell].stateful:
|
|
458
|
+
sources.add(producer_cell)
|
|
459
|
+
drivers.append(sources)
|
|
460
|
+
driven: list[list[int]] = [[] for _ in cells]
|
|
461
|
+
for number, sources in enumerate(drivers):
|
|
462
|
+
for source in sources:
|
|
463
|
+
driven[source].append(number)
|
|
464
|
+
ranks = [-1] * len(cells)
|
|
465
|
+
waiting = [len(sources) for sources in drivers]
|
|
466
|
+
ready = [n for n, c in enumerate(cells) if not c.stateful and not waiting[n]]
|
|
467
|
+
for number in ready:
|
|
468
|
+
ranks[number] = 0
|
|
469
|
+
while ready:
|
|
470
|
+
number = ready.pop()
|
|
471
|
+
for target in driven[number]:
|
|
472
|
+
ranks[target] = max(ranks[target], ranks[number] + 1)
|
|
473
|
+
waiting[target] -= 1
|
|
474
|
+
if not waiting[target]:
|
|
475
|
+
ready.append(target)
|
|
476
|
+
if any(rank < 0 for rank, c in zip(ranks, cells, strict=True) if not c.stateful):
|
|
477
|
+
return None # A combinational loop
|
|
478
|
+
ranks = [_NONE if c.stateful else rank for rank, c in zip(ranks, cells, strict=True)]
|
|
479
|
+
for member in members:
|
|
480
|
+
for member_port in member.ports:
|
|
481
|
+
if not member_port.is_input():
|
|
482
|
+
continue
|
|
483
|
+
if member_port.wired_ports or member_port._drivers is not None:
|
|
484
|
+
return None
|
|
485
|
+
member_driver = member_port.get_driver()
|
|
486
|
+
# Driven from outside: the bit must be one of an input of the module
|
|
487
|
+
outside = member_driver is not None and member_driver.parent() not in members
|
|
488
|
+
if outside and bits.get(id(member_port), (_NONE, 0))[0] == _NONE:
|
|
489
|
+
return None
|
|
490
|
+
return _BlockPlan(component, members, widths, cells, ranks, bits)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
class NativeEngine:
|
|
494
|
+
"""The native engine of a circuit, and the Python ports it took over"""
|
|
495
|
+
|
|
496
|
+
def __init__(self, circuit: Circuit, time_ns: int) -> None:
|
|
497
|
+
components = list(circuit._components.values())
|
|
498
|
+
# The Yosys components compiled to blocks, and the block of each of their cells
|
|
499
|
+
self.blocks: list[_BlockPlan] = []
|
|
500
|
+
self._member_block: dict[Component, int] = {}
|
|
501
|
+
for component in components:
|
|
502
|
+
if isinstance(component, YosysComponent):
|
|
503
|
+
plan = _block_plan(component)
|
|
504
|
+
if plan is not None:
|
|
505
|
+
for member in plan.members:
|
|
506
|
+
self._member_block[member] = len(self.blocks)
|
|
507
|
+
self.blocks.append(plan)
|
|
508
|
+
self._blocks_defaulted: set[int] = set()
|
|
509
|
+
members = self._member_block
|
|
510
|
+
# The clocks that the engine runs: without a callback (the GUI's), the timer and
|
|
511
|
+
# the output have no other drivers (not with DIGSIM_BLOCKS=0: the events in the
|
|
512
|
+
# order of the Python engine)
|
|
513
|
+
self.clocks = [
|
|
514
|
+
component
|
|
515
|
+
for component in components
|
|
516
|
+
if _compiled()
|
|
517
|
+
and type(component) is Clock
|
|
518
|
+
and component._callback is None
|
|
519
|
+
and not component._feedback.wired_ports
|
|
520
|
+
and component.O._drivers is None
|
|
521
|
+
]
|
|
522
|
+
clock_timers = {id(clock._feedback): number for number, clock in enumerate(self.clocks)}
|
|
523
|
+
clock_outputs = {id(clock.O) for clock in self.clocks}
|
|
524
|
+
cells: dict[Component, tuple[int, list[Port | None], list[int]]] = {}
|
|
525
|
+
for component in components:
|
|
526
|
+
if component in members:
|
|
527
|
+
continue
|
|
528
|
+
found = _cell(component)
|
|
529
|
+
if found is not None and _can_be_native(component):
|
|
530
|
+
cells[component] = found
|
|
531
|
+
self.cells = list(cells)
|
|
532
|
+
cell_index = {component: index for index, component in enumerate(self.cells)}
|
|
533
|
+
self.word_cells = _native_word_cells([c for c in components if c not in members])
|
|
534
|
+
self._word_index = {cell: number for number, cell in enumerate(self.word_cells)}
|
|
535
|
+
|
|
536
|
+
# Every port that can have an event or be driven: the components' ports (also the
|
|
537
|
+
# ones a component keeps for itself, like the feedback of a clock), the bits of
|
|
538
|
+
# bus ports, and the ports they drive
|
|
539
|
+
self.ports: list[Port] = []
|
|
540
|
+
index: dict[int, int] = {}
|
|
541
|
+
|
|
542
|
+
def add(port: Port) -> None:
|
|
543
|
+
if id(port) not in index:
|
|
544
|
+
index[id(port)] = len(self.ports)
|
|
545
|
+
self.ports.append(port)
|
|
546
|
+
|
|
547
|
+
for component in components:
|
|
548
|
+
for port in [*component.ports, *vars(component).values()]:
|
|
549
|
+
if isinstance(port, Port):
|
|
550
|
+
add(port)
|
|
551
|
+
if isinstance(component, functional.FunctionalCell):
|
|
552
|
+
for port in component._word_outputs.values():
|
|
553
|
+
add(port)
|
|
554
|
+
position = 0
|
|
555
|
+
while position < len(self.ports):
|
|
556
|
+
port = self.ports[position]
|
|
557
|
+
for target in port.wired_ports:
|
|
558
|
+
add(target)
|
|
559
|
+
if port._drivers is not None:
|
|
560
|
+
for driver in port._drivers.drivers:
|
|
561
|
+
add(driver)
|
|
562
|
+
if isinstance(port, PortMultiBitWire):
|
|
563
|
+
for bit in port._bits:
|
|
564
|
+
add(bit)
|
|
565
|
+
elif isinstance(port, PortWireBit):
|
|
566
|
+
add(port.get_parent_port())
|
|
567
|
+
position += 1
|
|
568
|
+
|
|
569
|
+
buses = [port for port in self.ports if _bus_can_be_native(port)]
|
|
570
|
+
bus_index = {id(port): number for number, port in enumerate(buses)}
|
|
571
|
+
kinds = []
|
|
572
|
+
owners = []
|
|
573
|
+
aux = []
|
|
574
|
+
# The input and bit of each input bit of a functional cell, the output of a word port
|
|
575
|
+
word_ports: dict[int, int] = {}
|
|
576
|
+
for word_cell_component in self.word_cells:
|
|
577
|
+
bits = word_cell_component._bits
|
|
578
|
+
for input_number, name in enumerate(word_cell_component._inputs):
|
|
579
|
+
for bit_number, bit_port in enumerate(bits[name]):
|
|
580
|
+
word_ports[id(bit_port)] = input_number << 20 | bit_number
|
|
581
|
+
for output_number, name in enumerate(word_cell_component._outputs):
|
|
582
|
+
word_output = word_cell_component._word_outputs.get(name)
|
|
583
|
+
if word_output is not None:
|
|
584
|
+
word_ports[id(word_output)] = output_number
|
|
585
|
+
# The ports of the blocks: (slot, bit) of each, and the pins
|
|
586
|
+
block_bits: list[tuple[int, int]] = []
|
|
587
|
+
block_pins: list[list[tuple[int, int, int]]] = [[] for _ in self.blocks]
|
|
588
|
+
block_vcd: list[list[tuple[int, int, int]]] = [[] for _ in self.blocks]
|
|
589
|
+
# The ports of the blocks that drive ports outside, and those they drive
|
|
590
|
+
self._outside: dict[int, list[Port]] = {}
|
|
591
|
+
for nid, port in enumerate(self.ports):
|
|
592
|
+
number = members.get(port.parent())
|
|
593
|
+
if number is None:
|
|
594
|
+
continue
|
|
595
|
+
plan = self.blocks[number]
|
|
596
|
+
slot, bit_index = plan.bits.get(id(port), (_NONE, 0))
|
|
597
|
+
if port.is_output():
|
|
598
|
+
outside = [t for t in port.wired_ports if t.parent() not in plan.members]
|
|
599
|
+
if outside and slot != _NONE:
|
|
600
|
+
self._outside[nid] = outside
|
|
601
|
+
block_pins[number].append((slot, bit_index, nid))
|
|
602
|
+
if slot != _NONE and not isinstance(port, functional._WordOut):
|
|
603
|
+
block_vcd[number].append((slot, bit_index, nid))
|
|
604
|
+
outside_ids = {id(self.ports[nid]) for nid in self._outside}
|
|
605
|
+
# One input of a block for each bit it gets from outside: the ports of the other
|
|
606
|
+
# cells on the bit read it from the block
|
|
607
|
+
self._pins: set[int] = set()
|
|
608
|
+
seen: set[tuple[int, int, int]] = set()
|
|
609
|
+
for port in self.ports:
|
|
610
|
+
number = members.get(port.parent())
|
|
611
|
+
if number is None or port.is_output():
|
|
612
|
+
continue
|
|
613
|
+
plan = self.blocks[number]
|
|
614
|
+
source = port.get_driver()
|
|
615
|
+
if source is None or source.parent() in plan.members:
|
|
616
|
+
continue
|
|
617
|
+
key = (number, *plan.bits[id(port)])
|
|
618
|
+
if key not in seen:
|
|
619
|
+
seen.add(key)
|
|
620
|
+
self._pins.add(id(port))
|
|
621
|
+
for port in self.ports:
|
|
622
|
+
number = members.get(port.parent())
|
|
623
|
+
if number is not None:
|
|
624
|
+
plan = self.blocks[number]
|
|
625
|
+
owners.append(number)
|
|
626
|
+
aux.append(len(block_bits))
|
|
627
|
+
block_bits.append(plan.bits.get(id(port), (_NONE, 0)))
|
|
628
|
+
if id(port) in self._pins:
|
|
629
|
+
kinds.append(_BLOCK_PIN)
|
|
630
|
+
elif id(port) in outside_ids:
|
|
631
|
+
kinds.append(_OUT)
|
|
632
|
+
else:
|
|
633
|
+
kinds.append(_BLOCK_INNER)
|
|
634
|
+
continue
|
|
635
|
+
cell = cell_index.get(port.parent())
|
|
636
|
+
aux.append(word_ports.get(id(port), 0))
|
|
637
|
+
word_cell = self._word_index.get(port.parent()) # type: ignore[call-overload]
|
|
638
|
+
if word_cell is not None:
|
|
639
|
+
if isinstance(port, functional._CellInput):
|
|
640
|
+
kinds.append(_CELL_INPUT)
|
|
641
|
+
elif isinstance(port, functional._WordOut):
|
|
642
|
+
kinds.append(_WORD)
|
|
643
|
+
else:
|
|
644
|
+
kinds.append(_OUT)
|
|
645
|
+
owners.append(word_cell)
|
|
646
|
+
elif id(port) in bus_index:
|
|
647
|
+
kinds.append(_BUS)
|
|
648
|
+
owners.append(bus_index[id(port)])
|
|
649
|
+
elif isinstance(port, PortWireBit) and id(port.get_parent_port()) in bus_index:
|
|
650
|
+
kinds.append(_BIT)
|
|
651
|
+
owners.append(index[id(port.get_parent_port())])
|
|
652
|
+
elif id(port) in clock_timers:
|
|
653
|
+
kinds.append(_CLOCK)
|
|
654
|
+
owners.append(clock_timers[id(port)])
|
|
655
|
+
elif id(port) in clock_outputs:
|
|
656
|
+
kinds.append(_OUT)
|
|
657
|
+
owners.append(_NONE)
|
|
658
|
+
elif cell is None or isinstance(port, PortMultiBitWire):
|
|
659
|
+
kinds.append(_PY)
|
|
660
|
+
owners.append(_NONE)
|
|
661
|
+
elif port.is_output():
|
|
662
|
+
kinds.append(_OUT)
|
|
663
|
+
owners.append(cell)
|
|
664
|
+
else:
|
|
665
|
+
kinds.append(_IN if type(port) is PortIn else _WIRE)
|
|
666
|
+
owners.append(cell)
|
|
667
|
+
native_cells = []
|
|
668
|
+
for component, (kind, inputs, levels) in cells.items():
|
|
669
|
+
native_cells.append(
|
|
670
|
+
(
|
|
671
|
+
kind,
|
|
672
|
+
[_NONE if port is None else index[id(port)] for port in inputs],
|
|
673
|
+
index[id(component.outports()[0])],
|
|
674
|
+
levels,
|
|
675
|
+
_CODES.get(getattr(component, "_old_C_level", "X"), 2),
|
|
676
|
+
)
|
|
677
|
+
)
|
|
678
|
+
self.engine = digsim_native.Engine(
|
|
679
|
+
self.ports,
|
|
680
|
+
kinds,
|
|
681
|
+
owners,
|
|
682
|
+
[_CODES.get(port._value, 2) if port.width == 1 else 2 for port in self.ports],
|
|
683
|
+
[
|
|
684
|
+
[index[id(target)] for target in self._wired(nid, port)]
|
|
685
|
+
for nid, port in enumerate(self.ports)
|
|
686
|
+
],
|
|
687
|
+
[
|
|
688
|
+
[index[id(driver)] for driver in port._drivers.drivers] # type: ignore[union-attr]
|
|
689
|
+
if kind != _PY and _resolved(port)
|
|
690
|
+
else []
|
|
691
|
+
for port, kind in zip(self.ports, kinds, strict=True)
|
|
692
|
+
],
|
|
693
|
+
[getattr(port, "_delay_ns", 0) for port in self.ports],
|
|
694
|
+
[port.parent().is_toplevel() for port in self.ports],
|
|
695
|
+
native_cells,
|
|
696
|
+
[([index[id(bit)] for bit in bus._bits], bus._value) for bus in buses], # type: ignore[attr-defined]
|
|
697
|
+
aux,
|
|
698
|
+
[self._word_cell(cell, index) for cell in self.word_cells],
|
|
699
|
+
time_ns,
|
|
700
|
+
[
|
|
701
|
+
self._block_args(plan, block_pins[number], block_vcd[number])
|
|
702
|
+
for number, plan in enumerate(self.blocks)
|
|
703
|
+
],
|
|
704
|
+
block_bits,
|
|
705
|
+
_compiled(),
|
|
706
|
+
)
|
|
707
|
+
self.generation = connection_generation.value
|
|
708
|
+
for nid, port in enumerate(self.ports):
|
|
709
|
+
port._nid = nid # type: ignore[attr-defined]
|
|
710
|
+
# The ports that the engine simulates read and set their values in it
|
|
711
|
+
self._native_ports = [
|
|
712
|
+
port for port, kind in zip(self.ports, kinds, strict=True) if kind != _PY
|
|
713
|
+
]
|
|
714
|
+
classes: dict[tuple[type[Port], bool], type[Port]] = {}
|
|
715
|
+
for port, kind in zip(self.ports, kinds, strict=True):
|
|
716
|
+
if kind == _PY:
|
|
717
|
+
continue
|
|
718
|
+
# An output can't be driven, also one of a cell in a block or a clock
|
|
719
|
+
driven = kind not in (_OUT, _CLOCK) and not (kind == _BLOCK_INNER and port.is_output())
|
|
720
|
+
class_key = (type(port), driven)
|
|
721
|
+
if class_key not in classes:
|
|
722
|
+
classes[class_key] = self._native_class(type(port), driven=driven)
|
|
723
|
+
port.__class__ = classes[class_key]
|
|
724
|
+
# A port with several drivers has the set_value() of its _Drivers, which resolves
|
|
725
|
+
# in Python: the engine does it for the ports it sets
|
|
726
|
+
self._resolved_ports = [
|
|
727
|
+
port
|
|
728
|
+
for port, kind in zip(self.ports, kinds, strict=True)
|
|
729
|
+
if kind != _PY and _resolved(port)
|
|
730
|
+
]
|
|
731
|
+
for port in self._resolved_ports:
|
|
732
|
+
port.set_value = self._resolved_set_value(port) # type: ignore[method-assign]
|
|
733
|
+
# The Python ports that the engine sets itself, without calling their set_value()
|
|
734
|
+
fast: list[tuple[int, int, Callable[[], None] | None]] = []
|
|
735
|
+
for nid, (port, kind) in enumerate(zip(self.ports, kinds, strict=True)):
|
|
736
|
+
if kind != _PY or port._drivers is not None:
|
|
737
|
+
continue
|
|
738
|
+
if (
|
|
739
|
+
type(port) is PortOutDelta
|
|
740
|
+
and not port._update_parent
|
|
741
|
+
and "delta_cycle" not in port.__dict__
|
|
742
|
+
):
|
|
743
|
+
# Its events set the ports it drives in the engine
|
|
744
|
+
fast.append((nid, 3, None))
|
|
745
|
+
continue
|
|
746
|
+
if port.wired_ports or "set_value" in port.__dict__:
|
|
747
|
+
continue
|
|
748
|
+
if type(port) is PortIn:
|
|
749
|
+
fast.append((nid, 1, port.parent().update))
|
|
750
|
+
elif type(port) is PortWire:
|
|
751
|
+
fast.append((nid, 2, None))
|
|
752
|
+
self.engine.set_fast_ports(fast)
|
|
753
|
+
self.engine.set_clocks([index[id(clock.O)] for clock in self.clocks])
|
|
754
|
+
|
|
755
|
+
def _wired(self, nid: int, port: Port) -> list[Port]:
|
|
756
|
+
"""The ports a port drives in the engine: a block drives its cells itself"""
|
|
757
|
+
members = self._member_block
|
|
758
|
+
if port.parent() in members:
|
|
759
|
+
return self._outside.get(nid, [])
|
|
760
|
+
return [t for t in port.wired_ports if t.parent() not in members or id(t) in self._pins]
|
|
761
|
+
|
|
762
|
+
def _block_args(
|
|
763
|
+
self,
|
|
764
|
+
plan: _BlockPlan,
|
|
765
|
+
pins: list[tuple[int, int, int]],
|
|
766
|
+
vcd: list[tuple[int, int, int]],
|
|
767
|
+
) -> tuple[Any, ...]:
|
|
768
|
+
"""A block for the engine"""
|
|
769
|
+
cells = []
|
|
770
|
+
for cell, rank in zip(plan.cells, plan.ranks, strict=True):
|
|
771
|
+
word = None
|
|
772
|
+
if cell.op == 0:
|
|
773
|
+
component = cell.component
|
|
774
|
+
assert isinstance(component, functional.FunctionalCell)
|
|
775
|
+
inputs = [
|
|
776
|
+
(len(component._bits[name]), name in component._updating_inputs, w[0], w[1])
|
|
777
|
+
for name, w in component._inputs.items()
|
|
778
|
+
]
|
|
779
|
+
outputs: list[tuple[Any, ...]] = [
|
|
780
|
+
(len(component._bits[name]), [], 0, None, [], last)
|
|
781
|
+
for name, last in component._outputs.items()
|
|
782
|
+
]
|
|
783
|
+
parameters = {name: component.param(name) for name in component._cell.parameters}
|
|
784
|
+
q = getattr(component, "_q", (0, 0))
|
|
785
|
+
initial = getattr(component, "initial_value", (0, 0))
|
|
786
|
+
clock = _CODES.get(getattr(component, "_old_clock", "X"), 2)
|
|
787
|
+
kind = _FUNCTIONAL[type(component)]
|
|
788
|
+
word = (kind, inputs, outputs, parameters, q, clock, True, initial)
|
|
789
|
+
old_clock = clock
|
|
790
|
+
else:
|
|
791
|
+
old_clock = cell.clock
|
|
792
|
+
cells.append(
|
|
793
|
+
(
|
|
794
|
+
cell.op,
|
|
795
|
+
cell.kind,
|
|
796
|
+
cell.inputs,
|
|
797
|
+
cell.outputs,
|
|
798
|
+
rank,
|
|
799
|
+
word,
|
|
800
|
+
cell.levels,
|
|
801
|
+
old_clock,
|
|
802
|
+
cell.value,
|
|
803
|
+
)
|
|
804
|
+
)
|
|
805
|
+
return (plan.widths, cells, pins, vcd)
|
|
806
|
+
|
|
807
|
+
def _word_cell(
|
|
808
|
+
self, cell: functional.FunctionalCell, index: dict[int, int]
|
|
809
|
+
) -> tuple[Any, ...]:
|
|
810
|
+
"""A functional cell for the engine"""
|
|
811
|
+
inputs = [
|
|
812
|
+
(len(cell._bits[name]), name in cell._updating_inputs, word[0], word[1])
|
|
813
|
+
for name, word in cell._inputs.items()
|
|
814
|
+
]
|
|
815
|
+
outputs = []
|
|
816
|
+
for name, last in cell._outputs.items():
|
|
817
|
+
ports = cell._bits[name]
|
|
818
|
+
mask = (1 << len(ports)) - 1
|
|
819
|
+
word_output = cell._word_outputs.get(name)
|
|
820
|
+
links = []
|
|
821
|
+
if word_output is not None:
|
|
822
|
+
for target, target_links in word_output._links.items():
|
|
823
|
+
names = list(target._inputs)
|
|
824
|
+
links.append(
|
|
825
|
+
(
|
|
826
|
+
self._word_index[target],
|
|
827
|
+
[
|
|
828
|
+
(names.index(port), offset, start, width)
|
|
829
|
+
for port, offset, start, width in target_links
|
|
830
|
+
],
|
|
831
|
+
)
|
|
832
|
+
)
|
|
833
|
+
outputs.append(
|
|
834
|
+
(
|
|
835
|
+
len(ports),
|
|
836
|
+
[index[id(port)] for port in ports],
|
|
837
|
+
cell._bit_outputs.get(name, mask),
|
|
838
|
+
None if word_output is None else index[id(word_output)],
|
|
839
|
+
links,
|
|
840
|
+
last,
|
|
841
|
+
)
|
|
842
|
+
)
|
|
843
|
+
parameters = {name: cell.param(name) for name in cell._cell.parameters}
|
|
844
|
+
q = getattr(cell, "_q", (0, 0))
|
|
845
|
+
initial = getattr(cell, "initial_value", (0, 0))
|
|
846
|
+
clock = _CODES.get(getattr(cell, "_old_clock", "X"), 2)
|
|
847
|
+
driving = getattr(cell, "_driving", True)
|
|
848
|
+
return (_FUNCTIONAL[type(cell)], inputs, outputs, parameters, q, clock, driving, initial)
|
|
849
|
+
|
|
850
|
+
def default_state(self, component: Component) -> bool:
|
|
851
|
+
"""Set the default state of a component the engine simulates, False if it doesn't"""
|
|
852
|
+
block = self._member_block.get(component)
|
|
853
|
+
if block is not None:
|
|
854
|
+
if block not in self._blocks_defaulted:
|
|
855
|
+
self._blocks_defaulted.add(block)
|
|
856
|
+
self.engine.block_default_state(block)
|
|
857
|
+
return True
|
|
858
|
+
number = self._word_index.get(component) # type: ignore[call-overload]
|
|
859
|
+
if number is None:
|
|
860
|
+
return False
|
|
861
|
+
self.engine.word_default_state(number)
|
|
862
|
+
return True
|
|
863
|
+
|
|
864
|
+
def _resolved_set_value(self, port: Port) -> Any:
|
|
865
|
+
"""The set_value() of a port that the engine resolves, the value is ignored"""
|
|
866
|
+
engine = self.engine
|
|
867
|
+
|
|
868
|
+
def set_value(value: Any) -> None:
|
|
869
|
+
engine.set_input(port._nid, value) # type: ignore[attr-defined]
|
|
870
|
+
|
|
871
|
+
return set_value
|
|
872
|
+
|
|
873
|
+
def _native_class(self, cls: type[Port], driven: bool) -> type[Port]:
|
|
874
|
+
"""A subclass of a port class for ports that the engine simulates"""
|
|
875
|
+
engine = self.engine
|
|
876
|
+
|
|
877
|
+
def get_value(port: Port) -> Any:
|
|
878
|
+
return engine.value(port._nid) # type: ignore[attr-defined]
|
|
879
|
+
|
|
880
|
+
def set_raw(port: Port, value: Any) -> None:
|
|
881
|
+
engine.set_raw(port._nid, value) # type: ignore[attr-defined]
|
|
882
|
+
|
|
883
|
+
# Read in the engine without a Python call (engine.get() reads the _nid of the port)
|
|
884
|
+
def set_value_of(port: Port, value: Any) -> None:
|
|
885
|
+
port.set_value(value)
|
|
886
|
+
|
|
887
|
+
namespace: dict[str, Any] = {
|
|
888
|
+
"_value": property(engine.get, set_raw),
|
|
889
|
+
"value": property(engine.get, set_value_of),
|
|
890
|
+
}
|
|
891
|
+
if driven:
|
|
892
|
+
# Port.value = x calls set_value(), the engine's for a port it drives
|
|
893
|
+
namespace["value"] = property(engine.get, engine.put)
|
|
894
|
+
base_set_value = cls.set_value
|
|
895
|
+
|
|
896
|
+
def set_value(port: Port, value: Any) -> None:
|
|
897
|
+
if type(port) is native_class:
|
|
898
|
+
engine.set_input(port._nid, value) # type: ignore[attr-defined]
|
|
899
|
+
else:
|
|
900
|
+
# The port is back in Python, but a port with several drivers keeps
|
|
901
|
+
# the set_value() it had when it got its second driver (see _Drivers)
|
|
902
|
+
base_set_value(port, value)
|
|
903
|
+
|
|
904
|
+
namespace["set_value"] = set_value
|
|
905
|
+
native_class = type(cls.__name__, (cls,), namespace)
|
|
906
|
+
return native_class
|
|
907
|
+
|
|
908
|
+
def next_event_ns(self, port: Port) -> int | None:
|
|
909
|
+
"""The time of the latest event of a port, None if it has none"""
|
|
910
|
+
nid = getattr(port, "_nid", None)
|
|
911
|
+
return None if nid is None else self.engine.next_event_time(nid)
|
|
912
|
+
|
|
913
|
+
def delay_changed(self, port: PortOutDelta) -> None:
|
|
914
|
+
"""A port has a new delay (a Clock with a new frequency)"""
|
|
915
|
+
nid = getattr(port, "_nid", None)
|
|
916
|
+
if nid is not None:
|
|
917
|
+
self.engine.set_delay(nid, port._delay_ns)
|
|
918
|
+
|
|
919
|
+
def nid(self, port: Port) -> int:
|
|
920
|
+
"""The index of a port in the engine, a Python port it doesn't have is added"""
|
|
921
|
+
nid = getattr(port, "_nid", None)
|
|
922
|
+
if nid is None:
|
|
923
|
+
# Its targets first, the ports it drives
|
|
924
|
+
wired = [self.nid(target) for target in port.wired_ports]
|
|
925
|
+
nid = self.engine.add_port(port, wired, port.parent().is_toplevel())
|
|
926
|
+
port._nid = nid # type: ignore[attr-defined]
|
|
927
|
+
self.ports.append(port)
|
|
928
|
+
return int(nid)
|
|
929
|
+
|
|
930
|
+
def close(
|
|
931
|
+
self,
|
|
932
|
+
) -> tuple[list[tuple[int, int, Port, Any]], dict[int, int], int, list[Callable[[], None]]]:
|
|
933
|
+
"""
|
|
934
|
+
Give the ports back to Python. Returns the events in the order of the heap as
|
|
935
|
+
(time, seq, port, value), the seq of the latest event of each port (by id()),
|
|
936
|
+
the time, and what to call when the Python engine has the events: the cells of a
|
|
937
|
+
block that wait for a settle make their events.
|
|
938
|
+
"""
|
|
939
|
+
events, latest, clocks = self.engine.export()
|
|
940
|
+
block_states = [self.engine.export_block(number) for number in range(len(self.blocks))]
|
|
941
|
+
for port in self._resolved_ports:
|
|
942
|
+
# Unless a removed driver left it with one, it resolves in Python again
|
|
943
|
+
if port._drivers is not None:
|
|
944
|
+
port.set_value = port._drivers.set_value # type: ignore[method-assign]
|
|
945
|
+
for port in self._native_ports:
|
|
946
|
+
value = port._value
|
|
947
|
+
port.__class__ = type(port).__mro__[1]
|
|
948
|
+
port._value = value
|
|
949
|
+
for port in self.ports:
|
|
950
|
+
del port._nid # type: ignore[attr-defined]
|
|
951
|
+
for component, clock in zip(self.cells, clocks, strict=True):
|
|
952
|
+
if hasattr(component, "_old_C_level"):
|
|
953
|
+
setattr(component, "_old_C_level", clock) # noqa: B010
|
|
954
|
+
for cell, (inputs, outputs, q, clock, driving) in zip(
|
|
955
|
+
self.word_cells, self.engine.export_words(), strict=True
|
|
956
|
+
):
|
|
957
|
+
# In place: the input bits keep the list of their word
|
|
958
|
+
for word, (bits, undefined) in zip(cell._inputs.values(), inputs, strict=True):
|
|
959
|
+
word[0], word[1] = bits, undefined
|
|
960
|
+
for name, last in zip(list(cell._outputs), outputs, strict=True):
|
|
961
|
+
cell._outputs[name] = last
|
|
962
|
+
if isinstance(cell, functional._Register):
|
|
963
|
+
cell._q = q
|
|
964
|
+
cell._old_clock = clock
|
|
965
|
+
if isinstance(cell, functional.Tribuf):
|
|
966
|
+
cell._driving = driving
|
|
967
|
+
after: list[Callable[[], None]] = []
|
|
968
|
+
for plan, states in zip(self.blocks, block_states, strict=True):
|
|
969
|
+
after.extend(_restore_block(plan, states))
|
|
970
|
+
ports = self.ports
|
|
971
|
+
return (
|
|
972
|
+
[(time, seq, ports[nid], value) for time, seq, nid, value in events],
|
|
973
|
+
{id(ports[nid]): seq for nid, seq in enumerate(latest) if seq is not None},
|
|
974
|
+
self.engine.time,
|
|
975
|
+
after,
|
|
976
|
+
)
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
def _word_of(ports: list[Port]) -> tuple[int, int]:
|
|
980
|
+
"""The bits and the undefined bits of the values of ports"""
|
|
981
|
+
bits = undefined = 0
|
|
982
|
+
for number, port in enumerate(ports):
|
|
983
|
+
value = port._value
|
|
984
|
+
if value == 1:
|
|
985
|
+
bits |= 1 << number
|
|
986
|
+
elif value != 0:
|
|
987
|
+
undefined |= 1 << number
|
|
988
|
+
return bits, undefined
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _restore_block(
|
|
992
|
+
plan: _BlockPlan, states: list[tuple[tuple[int, int] | None, Any, bool]]
|
|
993
|
+
) -> list[Callable[[], None]]:
|
|
994
|
+
"""
|
|
995
|
+
The state of the cells of a block in Python, from the values of their ports (back in
|
|
996
|
+
Python) and the state of the engine. Returns what the cells that wait for a settle do
|
|
997
|
+
then: a flip-flop sets its new output, a combinational cell updates.
|
|
998
|
+
"""
|
|
999
|
+
after: list[Callable[[], None]] = []
|
|
1000
|
+
for cell, (q, clock, waiting) in zip(plan.cells, states, strict=True):
|
|
1001
|
+
component = cell.component
|
|
1002
|
+
if isinstance(component, functional.FunctionalCell):
|
|
1003
|
+
for name, word in component._inputs.items():
|
|
1004
|
+
word[0], word[1] = _word_of(component._bits[name])
|
|
1005
|
+
for name in component._outputs:
|
|
1006
|
+
component._outputs[name] = _word_of(component._bits[name])
|
|
1007
|
+
for name, word_output in component._word_outputs.items():
|
|
1008
|
+
bits, undefined = component._outputs[name] # type: ignore[misc]
|
|
1009
|
+
word_output._value = bits | (undefined << len(component._bits[name]))
|
|
1010
|
+
if isinstance(component, functional._Register):
|
|
1011
|
+
component._old_clock = clock
|
|
1012
|
+
if q is not None:
|
|
1013
|
+
component._q = q
|
|
1014
|
+
if waiting:
|
|
1015
|
+
after.append(functools.partial(component.write, "Q", q))
|
|
1016
|
+
elif waiting:
|
|
1017
|
+
after.append(component.update)
|
|
1018
|
+
elif cell.op == 1:
|
|
1019
|
+
if hasattr(component, "_old_C_level"):
|
|
1020
|
+
component._old_C_level = clock # type: ignore[attr-defined]
|
|
1021
|
+
if waiting and cell.stateful and q is not None:
|
|
1022
|
+
code: VALUE_TYPE = "X" if q[1] & 1 else q[0] & 1
|
|
1023
|
+
output = component.outports()[0]
|
|
1024
|
+
after.append(functools.partial(output.set_value, code))
|
|
1025
|
+
elif waiting:
|
|
1026
|
+
after.append(component.update)
|
|
1027
|
+
elif waiting:
|
|
1028
|
+
after.append(component.default_state)
|
|
1029
|
+
return after
|