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.
Files changed (88) hide show
  1. digsim/circuit/__init__.py +7 -0
  2. digsim/circuit/_circuit.py +764 -0
  3. digsim/circuit/_native.py +1029 -0
  4. digsim/circuit/_waves_writer.py +131 -0
  5. digsim/circuit/components/__init__.py +52 -0
  6. digsim/circuit/components/_arithmetic.py +266 -0
  7. digsim/circuit/components/_bus_bits.py +103 -0
  8. digsim/circuit/components/_button.py +61 -0
  9. digsim/circuit/components/_buzzer.py +64 -0
  10. digsim/circuit/components/_circuit_port.py +293 -0
  11. digsim/circuit/components/_clock.py +105 -0
  12. digsim/circuit/components/_counter.py +147 -0
  13. digsim/circuit/components/_decoder.py +140 -0
  14. digsim/circuit/components/_dip_switch.py +91 -0
  15. digsim/circuit/components/_flip_flops.py +162 -0
  16. digsim/circuit/components/_gates.py +408 -0
  17. digsim/circuit/components/_hd44780.py +451 -0
  18. digsim/circuit/components/_hd44780_rom.py +118 -0
  19. digsim/circuit/components/_hexdigit.py +107 -0
  20. digsim/circuit/components/_ic.py +96 -0
  21. digsim/circuit/components/_label_wire.py +204 -0
  22. digsim/circuit/components/_led.py +66 -0
  23. digsim/circuit/components/_led_bar.py +67 -0
  24. digsim/circuit/components/_logic_analyzer.py +111 -0
  25. digsim/circuit/components/_memory.py +517 -0
  26. digsim/circuit/components/_memstdout.py +60 -0
  27. digsim/circuit/components/_note.py +40 -0
  28. digsim/circuit/components/_on_off_switch.py +64 -0
  29. digsim/circuit/components/_probe.py +90 -0
  30. digsim/circuit/components/_seven_segment.py +47 -0
  31. digsim/circuit/components/_splitter.py +214 -0
  32. digsim/circuit/components/_static_level.py +54 -0
  33. digsim/circuit/components/_static_value.py +97 -0
  34. digsim/circuit/components/_subcircuit.py +439 -0
  35. digsim/circuit/components/_tristate_buffer.py +81 -0
  36. digsim/circuit/components/_verilog_component.py +26 -0
  37. digsim/circuit/components/_yosys_atoms.py +1373 -0
  38. digsim/circuit/components/_yosys_component.py +1126 -0
  39. digsim/circuit/components/_yosys_functional.py +1714 -0
  40. digsim/circuit/components/atoms/__init__.py +28 -0
  41. digsim/circuit/components/atoms/_component.py +329 -0
  42. digsim/circuit/components/atoms/_digsim_exception.py +8 -0
  43. digsim/circuit/components/atoms/_port.py +708 -0
  44. digsim/circuit/components/ic/4017.json +1062 -0
  45. digsim/circuit/components/ic/4021.json +286 -0
  46. digsim/circuit/components/ic/4029.json +1447 -0
  47. digsim/circuit/components/ic/4094.json +584 -0
  48. digsim/circuit/components/ic/4511.json +1071 -0
  49. digsim/circuit/components/ic/74138.json +763 -0
  50. digsim/circuit/components/ic/74139.json +610 -0
  51. digsim/circuit/components/ic/74148.json +1368 -0
  52. digsim/circuit/components/ic/74151.json +303 -0
  53. digsim/circuit/components/ic/74157.json +248 -0
  54. digsim/circuit/components/ic/74161.json +674 -0
  55. digsim/circuit/components/ic/74162.json +631 -0
  56. digsim/circuit/components/ic/74163.json +673 -0
  57. digsim/circuit/components/ic/74164.json +267 -0
  58. digsim/circuit/components/ic/74165.json +319 -0
  59. digsim/circuit/components/ic/74173.json +403 -0
  60. digsim/circuit/components/ic/74181.json +2002 -0
  61. digsim/circuit/components/ic/74182.json +893 -0
  62. digsim/circuit/components/ic/74193.json +1386 -0
  63. digsim/circuit/components/ic/74194.json +919 -0
  64. digsim/circuit/components/ic/74245.json +466 -0
  65. digsim/circuit/components/ic/74283.json +732 -0
  66. digsim/circuit/components/ic/74374.json +395 -0
  67. digsim/circuit/components/ic/7448.json +834 -0
  68. digsim/circuit/components/ic/74574.json +395 -0
  69. digsim/circuit/components/ic/74595.json +603 -0
  70. digsim/circuit/components/ic/7485.json +1042 -0
  71. digsim/storage_model/__init__.py +19 -0
  72. digsim/storage_model/_app.py +159 -0
  73. digsim/storage_model/_circuit.py +266 -0
  74. digsim/synth/__init__.py +12 -0
  75. digsim/synth/__main__.py +111 -0
  76. digsim/synth/_synthesis.py +529 -0
  77. digsim/utils/__init__.py +25 -0
  78. digsim/utils/_netlist_graph.py +199 -0
  79. digsim/utils/_yosys_netlist.py +251 -0
  80. digsim/verilog/__init__.py +19 -0
  81. digsim/verilog/__main__.py +78 -0
  82. digsim/verilog/_formatter.py +225 -0
  83. digsim/verilog/_lexer.py +218 -0
  84. digsim_engine-1.13.0.dist-info/METADATA +59 -0
  85. digsim_engine-1.13.0.dist-info/RECORD +88 -0
  86. digsim_engine-1.13.0.dist-info/WHEEL +5 -0
  87. digsim_engine-1.13.0.dist-info/licenses/LICENSE.md +32 -0
  88. digsim_engine-1.13.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,225 @@
1
+ # Copyright (c) Fredrik Andersson, 2023-2026
2
+ # All rights reserved
3
+
4
+ """A Verilog formatter that only changes the indentation and the whitespace around lines"""
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from ._lexer import DIRECTIVES, LexState, Token, TokenKind, split_lines, tokenize, tokenize_line
11
+
12
+
13
+ class VerilogFormatError(ValueError):
14
+ """The formatted text would not have the same tokens, so it is not formatted"""
15
+
16
+
17
+ # The keywords that open a block, and the keywords that close it
18
+ _BLOCKS = {
19
+ "begin": ("end",),
20
+ "fork": ("join", "join_any", "join_none"),
21
+ "case": ("endcase",),
22
+ "casex": ("endcase",),
23
+ "casez": ("endcase",),
24
+ "randcase": ("endcase",),
25
+ "module": ("endmodule",),
26
+ "macromodule": ("endmodule",),
27
+ "interface": ("endinterface",),
28
+ "package": ("endpackage",),
29
+ "program": ("endprogram",),
30
+ "class": ("endclass",),
31
+ "function": ("endfunction",),
32
+ "task": ("endtask",),
33
+ "generate": ("endgenerate",),
34
+ "specify": ("endspecify",),
35
+ "primitive": ("endprimitive",),
36
+ "table": ("endtable",),
37
+ "config": ("endconfig",),
38
+ "covergroup": ("endgroup",),
39
+ "property": ("endproperty",),
40
+ "sequence": ("endsequence",),
41
+ "clocking": ("endclocking",),
42
+ "checker": ("endchecker",),
43
+ }
44
+ _CLOSERS = {closer for closers in _BLOCKS.values() for closer in closers}
45
+ # A block keyword after one of these on its line doesn't open a block: "extern function f();",
46
+ # "wait fork;", "assert property (...)", "typedef class c;" and "virtual interface i"
47
+ _NOT_A_BLOCK_AFTER = {
48
+ "function": {"extern", "pure", "import", "export"},
49
+ "task": {"extern", "pure", "import", "export"},
50
+ "fork": {"wait", "disable"},
51
+ "property": {"assert", "assume", "cover", "restrict", "expect"},
52
+ "sequence": {"assert", "assume", "cover", "restrict", "expect"},
53
+ "class": {"typedef"},
54
+ "interface": {"virtual"},
55
+ }
56
+ _BRACKETS = {"(": ")", "[": "]", "{": "}"}
57
+
58
+
59
+ @dataclass
60
+ class _Open:
61
+ """A block or a bracket that is open, and the indentation of the line it opened on"""
62
+
63
+ closers: tuple[str, ...]
64
+ indent: int
65
+
66
+
67
+ def _code(tokens: list[Token]) -> list[Token]:
68
+ return [
69
+ token for token in tokens if token.kind not in (TokenKind.WHITESPACE, TokenKind.COMMENT)
70
+ ]
71
+
72
+
73
+ def _is_directive_line(code: list[Token]) -> bool:
74
+ """A line with a compiler directive like `ifdef or `define, not a macro"""
75
+ return len(code) > 0 and code[0].kind == TokenKind.DIRECTIVE and code[0].text[1:] in DIRECTIVES
76
+
77
+
78
+ def _same_tokens(text: str) -> list[tuple[TokenKind, str]]:
79
+ """The tokens to compare before and after formatting: no whitespace, comment lines stripped"""
80
+ return [
81
+ (token.kind, token.text.strip())
82
+ for token in tokenize(text)
83
+ if token.kind != TokenKind.WHITESPACE
84
+ ]
85
+
86
+
87
+ class VerilogFormatter:
88
+ """
89
+ Formats Verilog and SystemVerilog. Only the whitespace changes: the indentation of
90
+ each line, whitespace at the end of lines, and blank lines.
91
+
92
+ - A block (`module`, `begin`, `case`, `function` and so on, to its `end` keyword) and
93
+ a bracket that is open at the end of a line indent the lines in it one step.
94
+ - A line that doesn't end a statement (like `if (a)` or `assign y = a &`) indents
95
+ the next line one step.
96
+ - Tabs at the start of a line become spaces, there is at most `blank_lines` empty
97
+ lines in a row, and the text ends with one newline.
98
+
99
+ Comments and strings are not changed, and lines that a `define continues are kept as
100
+ they are. The lines of a block comment move with its first line.
101
+
102
+ Args:
103
+ indent: The number of spaces for one step of indentation.
104
+ blank_lines: The most empty lines in a row.
105
+ """
106
+
107
+ def __init__(self, indent: int = 4, blank_lines: int = 1) -> None:
108
+ self._indent = indent
109
+ self._blank_lines = blank_lines
110
+
111
+ def format(self, text: str) -> str:
112
+ """
113
+ The formatted text. The newlines are the ones of the text (\\n or \\r\\n).
114
+
115
+ Raises:
116
+ VerilogFormatError: If formatting would change the tokens of the text. That
117
+ is a bug in the formatter, and the text is not formatted.
118
+ """
119
+ newline = "\r\n" if "\r\n" in text else "\n"
120
+ lines = self._format_lines(split_lines(text))
121
+ formatted = newline.join(lines) + newline if lines else ""
122
+ if _same_tokens(formatted) != _same_tokens(text):
123
+ raise VerilogFormatError("Formatting would change the code, the text is not formatted")
124
+ return formatted
125
+
126
+ def _format_lines(self, lines: list[str]) -> list[str]:
127
+ stack: list[_Open] = []
128
+ # The line before doesn't end its statement, the next line is indented a step more
129
+ continued = False
130
+ # How far the lines of a block comment move (in characters)
131
+ comment_shift = 0
132
+ state = LexState.CODE
133
+ result: list[str] = []
134
+ for number, line in enumerate(lines):
135
+ start_state = state
136
+ tokens, state = tokenize_line(line, state, number)
137
+ code = _code(tokens)
138
+ if start_state in (LexState.DEFINE, LexState.STRING):
139
+ # Continued with a backslash: kept as it is
140
+ result.append(line)
141
+ continue
142
+ if start_state == LexState.BLOCK_COMMENT:
143
+ result.append(self._shift(line, comment_shift).rstrip())
144
+ level = self._line_level(stack, code, continued)
145
+ elif line.strip() == "":
146
+ result.append("")
147
+ continue
148
+ else:
149
+ level = self._line_level(stack, code, continued)
150
+ indent = level * self._indent
151
+ result.append(" " * indent + line.strip())
152
+ comment_shift = indent - (len(line) - len(line.lstrip()))
153
+ if code and not _is_directive_line(code):
154
+ continued = self._update(stack, code, level)
155
+ return self._blank(result)
156
+
157
+ @staticmethod
158
+ def _shift(line: str, shift: int) -> str:
159
+ """Move a line of a block comment, but not into its text"""
160
+ if shift >= 0:
161
+ return " " * shift + line
162
+ leading = len(line) - len(line.lstrip(" "))
163
+ return line[min(-shift, leading) :]
164
+
165
+ @staticmethod
166
+ def _line_level(stack: list[_Open], code: list[Token], continued: bool) -> int:
167
+ """The indentation of a line: a line that starts with a closer is at its opener"""
168
+ if code and not _is_directive_line(code):
169
+ first = code[0].text
170
+ for open_index in range(len(stack) - 1, -1, -1):
171
+ if first in stack[open_index].closers:
172
+ return stack[open_index].indent
173
+ level = stack[-1].indent + 1 if stack else 0
174
+ return level + 1 if continued else level
175
+
176
+ @staticmethod
177
+ def _update(stack: list[_Open], code: list[Token], level: int) -> bool:
178
+ """
179
+ Open and close the blocks and brackets of a line. Returns True if the line doesn't
180
+ end a statement, so that the next line continues it.
181
+ """
182
+ depth = len(stack)
183
+ for index, token in enumerate(code):
184
+ text = token.text
185
+ closes = token.kind == TokenKind.OPERATOR and text in _BRACKETS.values()
186
+ closes = closes or (token.kind == TokenKind.KEYWORD and text in _CLOSERS)
187
+ if closes:
188
+ for open_index in range(len(stack) - 1, -1, -1):
189
+ if text in stack[open_index].closers:
190
+ del stack[open_index:]
191
+ break
192
+ depth = min(depth, len(stack))
193
+ elif token.kind == TokenKind.OPERATOR and text in _BRACKETS:
194
+ stack.append(_Open((_BRACKETS[text],), level))
195
+ elif token.kind == TokenKind.KEYWORD and text in _BLOCKS:
196
+ before = {token.text for token in code[:index]}
197
+ if not before & _NOT_A_BLOCK_AFTER.get(text, set()):
198
+ stack.append(_Open(_BLOCKS[text], level))
199
+ if len(stack) > depth:
200
+ # A block or bracket is still open from this line
201
+ return False
202
+ if stack and stack[-1].closers[0] in _BRACKETS.values():
203
+ # In a bracket, the lines are indented by the bracket
204
+ return False
205
+ last = code[-1]
206
+ if last.text == ";":
207
+ return False
208
+ if last.kind == TokenKind.KEYWORD and (last.text in _CLOSERS or last.text in _BLOCKS):
209
+ return False
210
+ # A block with a name: "end : name"
211
+ return not (len(code) >= 3 and code[-2].text == ":" and code[-3].text in _CLOSERS)
212
+
213
+ def _blank(self, lines: list[str]) -> list[str]:
214
+ """At most blank_lines empty lines in a row, and none at the start and end"""
215
+ result: list[str] = []
216
+ empty = 0
217
+ for line in lines:
218
+ if line == "":
219
+ empty += 1
220
+ continue
221
+ if result:
222
+ result.extend([""] * min(empty, self._blank_lines))
223
+ empty = 0
224
+ result.append(line)
225
+ return result
@@ -0,0 +1,218 @@
1
+ # Copyright (c) Fredrik Andersson, 2023-2026
2
+ # All rights reserved
3
+
4
+ """
5
+ A lexer for Verilog and SystemVerilog, for formatting and syntax highlighting.
6
+ It works one line at a time, so that a highlighter can lex a changed line again.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass
13
+ from enum import Enum, StrEnum
14
+
15
+
16
+ class TokenKind(StrEnum):
17
+ """The kind of a token"""
18
+
19
+ KEYWORD = "keyword"
20
+ IDENTIFIER = "identifier"
21
+ NUMBER = "number"
22
+ STRING = "string"
23
+ COMMENT = "comment"
24
+ DIRECTIVE = "directive"
25
+ SYSTEM = "system"
26
+ OPERATOR = "operator"
27
+ WHITESPACE = "whitespace"
28
+
29
+
30
+ class LexState(Enum):
31
+ """What the next line starts in"""
32
+
33
+ CODE = 0
34
+ BLOCK_COMMENT = 1
35
+ # A `define, or a string, continued with a backslash at the end of the line
36
+ DEFINE = 2
37
+ STRING = 3
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Token:
42
+ """
43
+ A token of a line.
44
+
45
+ Args:
46
+ kind: The kind of token.
47
+ text: The text of the token.
48
+ line: The line number, from 0.
49
+ column: The column in the line, from 0.
50
+ """
51
+
52
+ kind: TokenKind
53
+ text: str
54
+ line: int
55
+ column: int
56
+
57
+
58
+ def _words(text: str) -> list[str]:
59
+ return text.split()
60
+
61
+
62
+ KEYWORDS = frozenset(
63
+ _words(
64
+ """
65
+ accept_on alias always always_comb always_ff always_latch and assert assign assume
66
+ automatic before begin bind bins binsof bit break buf bufif0 bufif1 byte case casex casez
67
+ cell chandle checker class clocking cmos config const constraint context continue cover
68
+ covergroup coverpoint cross deassign default defparam design disable dist do edge else end
69
+ endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup
70
+ endinterface endmodule endpackage endprimitive endprogram endproperty endspecify
71
+ endsequence endtable endtask enum event eventually expect export extends extern final
72
+ first_match for force foreach forever fork forkjoin function generate genvar global
73
+ highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import incdir
74
+ include initial inout input inside instance int integer interconnect interface intersect
75
+ join join_any join_none large let liblist library local localparam logic longint
76
+ macromodule matches medium modport module nand negedge nettype new nexttime nmos nor
77
+ noshowcancelled not notif0 notif1 null or output package packed parameter pmos posedge
78
+ primitive priority program property protected pull0 pull1 pulldown pullup
79
+ pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real
80
+ realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran rtranif0
81
+ rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared sequence shortint
82
+ shortreal showcancelled signed small soft solve specify specparam static string strong
83
+ strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on table tagged
84
+ task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand
85
+ trior trireg type typedef union unique unique0 unsigned until until_with untyped use uwire
86
+ var vectored virtual void wait wait_order wand weak weak0 weak1 while wildcard wire with
87
+ within wor xnor xor
88
+ """
89
+ )
90
+ )
91
+
92
+ # The compiler directives that are not macros. A `define takes the rest of the line, and
93
+ # the lines after it that a backslash continues.
94
+ DIRECTIVES = frozenset(
95
+ _words(
96
+ """
97
+ begin_keywords celldefine default_nettype define else elsif end_keywords endcelldefine
98
+ endif ifdef ifndef include line nounconnected_drive pragma resetall timescale
99
+ unconnected_drive undef undefineall
100
+ """
101
+ )
102
+ )
103
+
104
+ _SIZE = r"(?:\d[\d_]*[ \t]*)?"
105
+ _BASED = _SIZE + r"'[sS]?(?:[bB][01xXzZ?_]+|[oO][0-7xXzZ?_]+|[dD][\d_]+|[dD][xXzZ?]_*"
106
+ _BASED += r"|[hH][0-9a-fA-FxXzZ?_]+)"
107
+ _BASED_SPACED = _SIZE + r"'[sS]?[bBoOdDhH][ \t]+[0-9a-fA-FxXzZ?][0-9a-fA-FxXzZ?_]*"
108
+ _REAL = r"\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d[\d_]*)?(?:(?:[fpnum]?s|step)(?![\w$]))?"
109
+ _OPERATORS = sorted(
110
+ _words(
111
+ """
112
+ <<<= >>>= <<< >>> === !== ==? !=? <-> ->> |-> |=> <<= >>= ** == != <= >= && || << >> ~& ~|
113
+ ~^ ^~ -> +: -: :: ++ -- += -= *= /= %= &= |= ^= :/ := #- #= ##
114
+ """
115
+ ),
116
+ key=len,
117
+ reverse=True,
118
+ )
119
+ _TOKEN = re.compile(
120
+ "|".join(
121
+ [
122
+ # Any whitespace, also Unicode like a non-breaking space (a line has no newline)
123
+ r"(?P<whitespace>\s+)",
124
+ r"(?P<line_comment>//.*)",
125
+ r"(?P<block_comment>/\*)",
126
+ r'(?P<string>")',
127
+ r"(?P<directive>`[a-zA-Z_][\w$]*)",
128
+ r"(?P<system>\$[a-zA-Z_][\w$]*)",
129
+ f"(?P<number>{_BASED_SPACED}|{_BASED}|'[01xXzZ](?![\\w$])|{_REAL})",
130
+ r"(?P<identifier>[a-zA-Z_][\w$]*|\\\S+)",
131
+ # Any other character is a token of its own, so that every line is tokenized
132
+ "(?P<operator>" + "|".join(re.escape(op) for op in _OPERATORS) + r"|.)",
133
+ ]
134
+ )
135
+ )
136
+ _STRING_END = re.compile(r'(?:[^"\\]|\\.)*"')
137
+
138
+
139
+ def tokenize_line(
140
+ text: str, state: LexState = LexState.CODE, line: int = 0
141
+ ) -> tuple[list[Token], LexState]:
142
+ """
143
+ The tokens of one line (without its newline), and the state the next line starts in.
144
+
145
+ Args:
146
+ text: The line.
147
+ state: The state the line starts in, from the line before it.
148
+ line: The line number for the tokens.
149
+ """
150
+ tokens: list[Token] = []
151
+ pos = 0
152
+
153
+ def add(kind: TokenKind, end: int) -> None:
154
+ nonlocal pos
155
+ tokens.append(Token(kind, text[pos:end], line, pos))
156
+ pos = end
157
+
158
+ if state == LexState.BLOCK_COMMENT:
159
+ end = text.find("*/")
160
+ if end < 0:
161
+ add(TokenKind.COMMENT, len(text))
162
+ return tokens, LexState.BLOCK_COMMENT
163
+ add(TokenKind.COMMENT, end + 2)
164
+ elif state == LexState.DEFINE:
165
+ add(TokenKind.DIRECTIVE, len(text))
166
+ return tokens, LexState.DEFINE if text.endswith("\\") else LexState.CODE
167
+ elif state == LexState.STRING:
168
+ match = _STRING_END.match(text)
169
+ if match is None:
170
+ add(TokenKind.STRING, len(text))
171
+ return tokens, LexState.STRING if text.endswith("\\") else LexState.CODE
172
+ add(TokenKind.STRING, match.end())
173
+
174
+ while pos < len(text):
175
+ match = _TOKEN.match(text, pos)
176
+ assert match is not None and match.lastgroup is not None
177
+ group = match.lastgroup
178
+ if group == "block_comment":
179
+ end = text.find("*/", pos + 2)
180
+ if end < 0:
181
+ add(TokenKind.COMMENT, len(text))
182
+ return tokens, LexState.BLOCK_COMMENT
183
+ add(TokenKind.COMMENT, end + 2)
184
+ elif group == "line_comment":
185
+ add(TokenKind.COMMENT, len(text))
186
+ elif group == "string":
187
+ string_end = _STRING_END.match(text, pos + 1)
188
+ if string_end is None:
189
+ # Not closed on this line: continued with a backslash, or a syntax error
190
+ add(TokenKind.STRING, len(text))
191
+ return tokens, LexState.STRING if text.endswith("\\") else LexState.CODE
192
+ add(TokenKind.STRING, string_end.end())
193
+ elif group == "directive" and match.group() == "`define":
194
+ add(TokenKind.DIRECTIVE, len(text))
195
+ return tokens, LexState.DEFINE if text.endswith("\\") else LexState.CODE
196
+ elif group == "identifier" and match.group() in KEYWORDS:
197
+ add(TokenKind.KEYWORD, match.end())
198
+ else:
199
+ add(TokenKind(group), match.end())
200
+ return tokens, LexState.CODE
201
+
202
+
203
+ def split_lines(text: str) -> list[str]:
204
+ """The lines of a text, without their newlines (\\n, \\r\\n or \\r)"""
205
+ return text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
206
+
207
+
208
+ def tokenize(text: str) -> list[Token]:
209
+ """
210
+ The tokens of a Verilog text, line by line. A block comment over several lines is a
211
+ comment token on each line. The newlines are not tokens.
212
+ """
213
+ tokens: list[Token] = []
214
+ state = LexState.CODE
215
+ for number, line in enumerate(split_lines(text)):
216
+ line_tokens, state = tokenize_line(line, state, number)
217
+ tokens.extend(line_tokens)
218
+ return tokens
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: digsim-engine
3
+ Version: 1.13.0
4
+ Summary: The simulator of DigSim: digital logic circuits in Python, and Verilog with Yosys
5
+ Author-email: Fredrik Andersson <freand@gmail.com>
6
+ Maintainer-email: Fredrik Andersson <freand@gmail.com>
7
+ Project-URL: homepage, https://github.com/freand76/digsim
8
+ Project-URL: documentation, https://freand76.github.io/digsim/
9
+ Keywords: educational,simulation,digital,verilog
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE.md
21
+ Requires-Dist: pyvcd==0.5.0
22
+ Requires-Dist: platformdirs==4.9.4
23
+ Requires-Dist: pydantic==2.14.1
24
+ Requires-Dist: yowasp-yosys==0.70.0.0.post1259
25
+ Requires-Dist: yowasp-runtime==1.96
26
+ Requires-Dist: wasmtime==47.0.1
27
+ Requires-Dist: digsim-native==0.5.0; (sys_platform == "linux" and platform_machine in "x86_64 aarch64") or (sys_platform == "win32" and platform_machine in "AMD64 ARM64") or sys_platform == "darwin"
28
+ Dynamic: license-file
29
+
30
+ # digsim-engine
31
+
32
+ The simulator of [DigSim](https://github.com/freand76/digsim), without its GUI: digital
33
+ logic circuits in Python, Verilog synthesized by Yosys (which runs in-process, nothing
34
+ else to install), VCD files for GTKWave, and the circuit files of the GUI.
35
+
36
+ ```sh
37
+ pip install digsim-engine
38
+ ```
39
+
40
+ ```python
41
+ from digsim.circuit import Circuit
42
+ from digsim.circuit.components import AND, PushButton
43
+
44
+ circuit = Circuit(vcd="and.vcd")
45
+ a = PushButton(circuit, "a")
46
+ b = PushButton(circuit, "b")
47
+ gate = AND(circuit, "gate")
48
+ a.O.wire = gate.A
49
+ b.O.wire = gate.B
50
+ circuit.init()
51
+ a.push()
52
+ b.push()
53
+ circuit.run(ns=10)
54
+ print(gate.Y.value) # 1
55
+ ```
56
+
57
+ The GUI application, `pip install digsim-logic-simulator`, uses this package. See the
58
+ [documentation](https://freand76.github.io/digsim/) for the Python API, Verilog components
59
+ and testbenches with pytest.
@@ -0,0 +1,88 @@
1
+ digsim/circuit/__init__.py,sha256=Iu4jCaFYUAzKAhubcYbn3EnFhUJDvFa6S6eH8OUoKno,204
2
+ digsim/circuit/_circuit.py,sha256=Rv0fXmpaqCX_ToCGOljRdfRRXGzh78rbf1hKOu8wsuw,29537
3
+ digsim/circuit/_native.py,sha256=kcUdKtQqeDKdNc48B4pfN0RKr4c_30AVUoBMA9X15IE,43150
4
+ digsim/circuit/_waves_writer.py,sha256=R8xGIKVAVs9o8KphKmwQ3c0V_luLqmFd_8MGD7i1EtI,5217
5
+ digsim/circuit/components/__init__.py,sha256=MBDhCO9oqHWl4TPaeAC6m1TE5t55rZjrhiGcfAIx8kI,1745
6
+ digsim/circuit/components/_arithmetic.py,sha256=lQqZpp9INMkU1T7KOLu4BlL32I9ysWKAPOK5wjoTep4,8731
7
+ digsim/circuit/components/_bus_bits.py,sha256=vzN8O0mFLDO6sh4_H8dnSlrkqVpZFU-4B1pQJtUdKdE,2936
8
+ digsim/circuit/components/_button.py,sha256=rAc80tU-pyeb7rluNA4zEwKfa9PW3f2DntZAAdfj4bw,1347
9
+ digsim/circuit/components/_buzzer.py,sha256=JXEEV1TrpIroVk-Vo72ub1AWTW3KBvAiFRVVgdwVuds,1617
10
+ digsim/circuit/components/_circuit_port.py,sha256=MEa50axs0I8EU5xZbCng-UFr3gq38ILX7_l7SoJY2hY,9184
11
+ digsim/circuit/components/_clock.py,sha256=O01Y4oANsBMYLh2_WkqkgnTUGXdMwoWiRlHIzHVxkJw,3093
12
+ digsim/circuit/components/_counter.py,sha256=dVmCL6czq7IyaKTnSYVzvt1bj6ac5eSgRgnl60w0sQg,4717
13
+ digsim/circuit/components/_decoder.py,sha256=GKR7BNO8UE9YAvT6lL-Xw7XfZIpU-1JcLv2WM4zMgRA,4470
14
+ digsim/circuit/components/_dip_switch.py,sha256=SafKh_W4J1piXOyoF01qOCwXkwRahVuuIFRK9r-vcAk,2405
15
+ digsim/circuit/components/_flip_flops.py,sha256=LF-HY47RgUuleFdHz6GMCfDTy9Jps_FMhFRVaHiybrw,4713
16
+ digsim/circuit/components/_gates.py,sha256=n97fl77xF8xJnpqa9-faGOpSK5SMzW5jtOV0OPTyZUQ,12100
17
+ digsim/circuit/components/_hd44780.py,sha256=CwuDow5bIGEHpyQeLx-JlAlg-rpE1OYG3pC96v6_cVU,16856
18
+ digsim/circuit/components/_hd44780_rom.py,sha256=zQ3NunmgYt6aOQ_wfMQlT2qyOawwGp3iQdu9IGjokcA,6768
19
+ digsim/circuit/components/_hexdigit.py,sha256=nB__Y-WW--_mblbzFQSmg5H1sF5i6CJHk2KBT2lFtq8,3054
20
+ digsim/circuit/components/_ic.py,sha256=jo9zuppX1G8pyQTbjdLTxvhTtfKsOJkxOm0YYwV5VUY,3511
21
+ digsim/circuit/components/_label_wire.py,sha256=cZ6KARHa_JWGbagfE83HRv0zmxnXwmyR4M4KOc4txS4,6830
22
+ digsim/circuit/components/_led.py,sha256=Rz1TX5GfxzmQGKn5DZYV4LtSJqlbhUJQxLRoVEEr7yE,1708
23
+ digsim/circuit/components/_led_bar.py,sha256=P8diurpv7KrEuQ-pa2XTUErlStkzHQkdBWhG9cYXso8,1902
24
+ digsim/circuit/components/_logic_analyzer.py,sha256=3Og9vLqEjlRB4QXvO9jtGJbnB-Fkvq-Mp4i1UzuqLg4,4198
25
+ digsim/circuit/components/_memory.py,sha256=k87EcrovtpmVVflnzf0JmCMEANZZgyOPXWPnSVxfXuM,18762
26
+ digsim/circuit/components/_memstdout.py,sha256=a4dqsVGPwOh5hbnPSkLglr4uuJXyQljMTNDyQzOpafM,1844
27
+ digsim/circuit/components/_note.py,sha256=9co3rQpONrUCd9BY75UgpIMVR4ppeKBsUk7bLMFpBK4,999
28
+ digsim/circuit/components/_on_off_switch.py,sha256=tNPPxRdkwVNmLz1KcMh3OJyHgq8YDrwSvpQeiTXAsC4,1466
29
+ digsim/circuit/components/_probe.py,sha256=6ZM2oZpIJCa4R9jgNtUC0y0V-1InvC7UomATrlJhwes,2823
30
+ digsim/circuit/components/_seven_segment.py,sha256=hN5934MX_1SUS2vY4GNOuQuVaoZQGZEGVjcAZq509QU,1267
31
+ digsim/circuit/components/_splitter.py,sha256=ONzU8WWMNJpn6qnae8ZwBP3VRNQCW1jsS3KWAlxmomw,7366
32
+ digsim/circuit/components/_static_level.py,sha256=xjiQNGzDvdDKAECsM0H1m9C8AaZ3xDinCPkOBwb5LjY,1209
33
+ digsim/circuit/components/_static_value.py,sha256=q4Qkj-TljXE5m7qdcMn7JkxS7oKniQkvagE3OWi7zcc,2891
34
+ digsim/circuit/components/_subcircuit.py,sha256=5vHppfEap1GXuoiqjOgwOh9VQWVDnV6enfcrnkCRbLA,17669
35
+ digsim/circuit/components/_tristate_buffer.py,sha256=nA9PSujpdXpkc2wThZh0YXXRMCNMmmYkEE1b2HNsGks,2489
36
+ digsim/circuit/components/_verilog_component.py,sha256=tUT6EA3wcdNcndUPqxdMbNRjxnrxrry7-93XpjwGFww,774
37
+ digsim/circuit/components/_yosys_atoms.py,sha256=83vSR0d0Qrd5DoFZkuWSvoVZoZ8jNqzieOtOniIOeBg,38661
38
+ digsim/circuit/components/_yosys_component.py,sha256=v60A9Xp5rVLBVztFqUAZcWvygveIdder-elBVPMFaIM,47436
39
+ digsim/circuit/components/_yosys_functional.py,sha256=_3-MOviNUP8_c2hGapVG5E6ypq4R491M0dVqTCH9S7g,57548
40
+ digsim/circuit/components/atoms/__init__.py,sha256=k-4_iRqG7CQEFMk5kI4lRLhowCM0JCCeFNk-O2xtT9M,554
41
+ digsim/circuit/components/atoms/_component.py,sha256=3sG6roW3a32U7XkozlUqVqycXYcdaGZMkIdNpbsqb9U,11233
42
+ digsim/circuit/components/atoms/_digsim_exception.py,sha256=vSBuRWVl5HXQBEqwKjnPm55LWGUdYar5NQCJAVyQ1xg,178
43
+ digsim/circuit/components/atoms/_port.py,sha256=mrQUnZFkC31LugUsvxT2_Dzqm9aHjT_xRutYhh-Slp4,25933
44
+ digsim/circuit/components/ic/4017.json,sha256=mzHJODbD9-4YNzgC5oaWHq-vpXBw5FET-bJ3Y7r99vg,30895
45
+ digsim/circuit/components/ic/4021.json,sha256=Sn-tb8laLHgQJIxkXIwM1d0ZxE0DqvQgls0eaWKvSpI,7067
46
+ digsim/circuit/components/ic/4029.json,sha256=XbRr3cmsx0z88Za5k-BOidqsG56QRKv8xPa-XvZfrgM,40370
47
+ digsim/circuit/components/ic/4094.json,sha256=zKtkZkXj7EMXf8fNqbsTNZHPbT_ZKHEFKjCfX_VxpfI,14570
48
+ digsim/circuit/components/ic/4511.json,sha256=g-hYX2AkpZTxvKA67ZsUFhup9XFly2G8peCUrDOcxxg,26653
49
+ digsim/circuit/components/ic/74138.json,sha256=cgduIBSWuG3Qb85aLu1SFqBeGoaZAsdpVB5ONP8XeNw,21086
50
+ digsim/circuit/components/ic/74139.json,sha256=qz3xH2Nb3dwgNaUVA0GQ6E3odKRgzjmaCch4jaCK9rE,16836
51
+ digsim/circuit/components/ic/74148.json,sha256=I2okeQcSg4tHo7BVFhNiqYc5RWRxv0k2eaHN_lu68Tk,36306
52
+ digsim/circuit/components/ic/74151.json,sha256=olzXCIzmcE33I-yfBtVeTSyRfn0vl1FKoM_rLgOHJUc,8371
53
+ digsim/circuit/components/ic/74157.json,sha256=H1dM-_vN4qupyyPOxYapQ0Mt6lhSc1Kk1pERlPBp9pw,6267
54
+ digsim/circuit/components/ic/74161.json,sha256=D46ewijmBP07TtUltiJdSSVslap4SBg-bFYbWPdfy_4,17727
55
+ digsim/circuit/components/ic/74162.json,sha256=WmHOLA2N96eF_g5JPcbYcAMLjDrMNe92HtJYbx5fvZU,16079
56
+ digsim/circuit/components/ic/74163.json,sha256=DH0J_mOR2mlaHiSfS_MUkGjUp74tC5mESboQKGZ6amI,17681
57
+ digsim/circuit/components/ic/74164.json,sha256=NXa9_kQ3LsijGj4iGZz8Mm94C6oZbJseDqY4ZSLiJFA,6619
58
+ digsim/circuit/components/ic/74165.json,sha256=ASZXFv7aN0waO1_AE5dQFeuhVB3XgjltnxUfLZZ9vkE,7955
59
+ digsim/circuit/components/ic/74173.json,sha256=ZbsCGriA1Lc9VvDTMKdfjQHqphzDCttc3TwfQlp2r_Q,10146
60
+ digsim/circuit/components/ic/74181.json,sha256=9IUCc5ZQuxl8PQe2WSM90HcpLPX1vQ0LspnzeM7jf-Y,53942
61
+ digsim/circuit/components/ic/74182.json,sha256=EKXu95BW0MVqbw_qstglIBNKW3vBzJReRR3W-ASG3es,23199
62
+ digsim/circuit/components/ic/74193.json,sha256=jkknRixEECdde4SPXGqQRJJKNMpvRIDbY2vdc1kS1Y4,36517
63
+ digsim/circuit/components/ic/74194.json,sha256=MDJXl9II-Zkk6PeJ0X0WcTF9MIPQ8OF3ZCiW9x5ef0o,24089
64
+ digsim/circuit/components/ic/74245.json,sha256=HXylNOOV2z7rD-nr3OS_VIAUwJU6_RjDScwOIYK92sA,12032
65
+ digsim/circuit/components/ic/74283.json,sha256=p3_pGz4sm_XUccqnRA42PgDIioQCLMhw9d0IpFm_d7M,22282
66
+ digsim/circuit/components/ic/74374.json,sha256=V3Z3ppGJqlzCotFwr4vJdXM14a97JdQwyS1DWAR9NcY,9957
67
+ digsim/circuit/components/ic/7448.json,sha256=4lmKGRP06g3NjkkK2On7htIQyuOlE7g7ZUr10OEiLcY,20651
68
+ digsim/circuit/components/ic/74574.json,sha256=LWPuR0x1I2DzSsn_0hhuYMbT4YaKsC9I4TgsoVJxVDk,9957
69
+ digsim/circuit/components/ic/74595.json,sha256=Rs2YZH1ZY9kPjV4dIH6b5orRp2jCqP0rcAv_yw6HhtE,15090
70
+ digsim/circuit/components/ic/7485.json,sha256=4Gt0Lri7_A68OBtRr5Dv65PBsp9VOGN05_ZRZXP4o30,29090
71
+ digsim/storage_model/__init__.py,sha256=z6eOe4e20YwagWcTGGBeKQlbTb8c36u6HyFmUmoO0v4,397
72
+ digsim/storage_model/_app.py,sha256=R73tfH52SnrDCFCqg5vY3tvD3uTkD9kp-WmwOXxZplQ,5441
73
+ digsim/storage_model/_circuit.py,sha256=EHk-6BsB2S3BHyhq4L0b2fPA8n1w_D5xEhOzsQmGTRE,10159
74
+ digsim/synth/__init__.py,sha256=8iI3UeV-ljtibOGHSWYYtPhL4oUcdlrN8vwChUke8w8,246
75
+ digsim/synth/__main__.py,sha256=WCdDZ_YF8LY1I0iR3zZf-CXObXT-sZK-t7ds3hFpK-8,3753
76
+ digsim/synth/_synthesis.py,sha256=-fw1aSnw4Fo-0N2HOwV37EOOAb_rf0ztTr_GBTCuVVY,20789
77
+ digsim/utils/__init__.py,sha256=2UUG0VvxZeFm7QfB5ItEWMGtLv7P6gdgXqtxWajidiA,438
78
+ digsim/utils/_netlist_graph.py,sha256=1MpSQvDtAdPwCzMyknptYHjmkwFHv6Q15fkitxEr-MA,7346
79
+ digsim/utils/_yosys_netlist.py,sha256=SAoeSq-Gz5NdETIN53LeBDywqS34voOxiiuCl_Pe--s,9210
80
+ digsim/verilog/__init__.py,sha256=CHKSiDMu9x4PmBENZNpn8hk_qLnn4WtWHdkNlg8qVbk,436
81
+ digsim/verilog/__main__.py,sha256=ohIG1ShVn04JNxwEHoQYDghaMdk10KtsvT1rEMBhVMA,2842
82
+ digsim/verilog/_formatter.py,sha256=mKR1wzo42HgVcTjvcv_MQNLbqISJbsDDBEkFRfXAhFI,9102
83
+ digsim/verilog/_lexer.py,sha256=Ilc2Vgid_M8zdUkpektHvpnk_GOsrumZMt_pJmSRJQ8,8198
84
+ digsim_engine-1.13.0.dist-info/licenses/LICENSE.md,sha256=FrvohZfyfpH4xrvKdXiQ5hD7dUB7w4DcsRA3p-pOmLw,1693
85
+ digsim_engine-1.13.0.dist-info/METADATA,sha256=UP6v35ZQMPjkv9XstfmDDyQUO8jjsIPp0sUjm6G785E,2209
86
+ digsim_engine-1.13.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
87
+ digsim_engine-1.13.0.dist-info/top_level.txt,sha256=qpCMzQKADZHVqZIoQgFrv3qJ3u7PPU73gTCXQglqLa8,7
88
+ digsim_engine-1.13.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,32 @@
1
+ The Clear BSD License
2
+
3
+ Copyright (c) 2023-2024, Fredrik Andersson
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
21
+ LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
25
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
27
+ GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30
+ OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ -------------------------------------------------------------------------------
@@ -0,0 +1 @@
1
+ digsim