Skip to content

Commit 34aeda7

Browse files
committed
Enable ruff-specific checks and apply fixes. This removes many unnecessary str and list conversions.
1 parent 79a69bd commit 34aeda7

23 files changed

Lines changed: 255 additions & 228 deletions

pyproject.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ select = [
8787
"PLE", "PLW", "PLC",
8888
# refurb
8989
"FURB",
90+
# ruff-specific checks
91+
"RUF"
9092
]
9193
ignore = [
9294
# Use ternary operator:
@@ -105,4 +107,8 @@ ignore = [
105107
# `import` should be at the top-level of a file:
106108
# PyRTL uses many function-level imports to avoid circular dependencies.
107109
"PLC0415",
110+
# String/docstring/comment contains ambiguous <unicode>
111+
"RUF001", "RUF002", "RUF003",
112+
# `__all__` is not sorted
113+
"RUF022",
108114
]

pyrtl/analysis.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,9 @@ def _memory_read_estimate(mem):
228228
tech_in_um = 0.130
229229
return 270 * tech_in_um**1.38 * bits**0.25 * ports**1.30 + 1.05
230230

231-
def max_freq(self, tech_in_nm: float = 130, ffoverhead: float = None) -> float:
231+
def max_freq(
232+
self, tech_in_nm: float = 130, ffoverhead: float | None = None
233+
) -> float:
232234
"""Estimates the max frequency of a block in MHz.
233235
234236
:param tech_in_nm: the size of the circuit technology to be estimated
@@ -338,7 +340,10 @@ def print_critical_paths(critical_paths):
338340

339341

340342
def yosys_area_delay(
341-
library: str, abc_cmd: str = None, leave_in_dir: str = None, block: Block = None
343+
library: str,
344+
abc_cmd: str | None = None,
345+
leave_in_dir: str | None = None,
346+
block: Block = None,
342347
) -> tuple[float, float]:
343348
"""Synthesize with `Yosys <https://yosyshq.net/yosys/>`_ and return estimate of area
344349
and delay.
@@ -441,15 +446,15 @@ def path_sort_key(path):
441446
for i, paths in enumerate(sorted(all_paths, key=path_sort_key)):
442447
print(f" Path {i}", file=file)
443448
for path in paths:
444-
print(f" {str(path)}", file=file)
449+
print(f" {path}", file=file)
445450
else:
446451
print(" (No paths)", file=file)
447452

448453

449454
def paths(
450455
src: WireVector | Iterable[WireVector] = None,
451456
dst: WireVector | Iterable[WireVector] = None,
452-
dst_nets: dict[WireVector, LogicNet] = None,
457+
dst_nets: dict[WireVector, LogicNet] | None = None,
453458
block: Block = None,
454459
) -> PathsResult:
455460
"""Get the list of all paths from ``src`` to ``dst``.
@@ -530,9 +535,9 @@ def dfs(w, curr_path):
530535
if dst_net not in curr_path:
531536
if dst_net.op == "@": # dests will be the read ports
532537
for read_net in dst_net.op_param[1].readport_nets:
533-
dfs(read_net.dests[0], curr_path + [dst_net, read_net])
538+
dfs(read_net.dests[0], [*curr_path, dst_net, read_net])
534539
else:
535-
dfs(dst_net.dests[0], curr_path + [dst_net])
540+
dfs(dst_net.dests[0], [*curr_path, dst_net])
536541

537542
dfs(src, [])
538543
return paths

pyrtl/compilesim.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,8 @@ class CompiledSimulation:
105105
def __init__(
106106
self,
107107
tracer: SimulationTrace = True,
108-
register_value_map: dict[Register, int] = None,
109-
memory_value_map: dict[MemBlock, dict[int, int]] = None,
108+
register_value_map: dict[Register, int] | None = None,
109+
memory_value_map: dict[MemBlock, dict[int, int]] | None = None,
110110
default_value: int = 0,
111111
block: Block = None,
112112
):
@@ -161,7 +161,7 @@ def inspect(self, w: str) -> int:
161161
msg = "CompiledSimulation does not support inspecting internal WireVectors"
162162
raise PyrtlError(msg)
163163

164-
def step(self, provided_inputs: dict[str, int] = None, inputs=None):
164+
def step(self, provided_inputs: dict[str, int] | None = None, inputs=None):
165165
if provided_inputs is None:
166166
provided_inputs = {}
167167
if inputs is not None:
@@ -175,9 +175,9 @@ def step(self, provided_inputs: dict[str, int] = None, inputs=None):
175175

176176
def step_multiple(
177177
self,
178-
provided_inputs: dict[str, list[int]] = None,
179-
expected_outputs: dict[str, int] = None,
180-
nsteps: int = None,
178+
provided_inputs: dict[str, list[int]] | None = None,
179+
expected_outputs: dict[str, int] | None = None,
180+
nsteps: int | None = None,
181181
file=sys.stdout,
182182
stop_after_first_error: bool = False,
183183
):

pyrtl/core.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def __str__(self):
186186
f"{name}[{addr}] & \\leftarrow @ \\, - & "
187187
f"{data} we={we} ({extrainfo}) \\\\"
188188
)
189-
msg = f'error, unknown op "{str(self.op)}"'
189+
msg = f'error, unknown op "{self.op}"'
190190
raise PyrtlInternalError(msg)
191191

192192
# not in ipython
@@ -200,7 +200,7 @@ def __str__(self):
200200
return f"{lhs} <-- m -- {memblock.name}[{rhs}]({extrainfo})"
201201
addr, data, we = (str(x) for x in self.args)
202202
return f"{memblock.name}[{addr}] <-- @ -- {data} we={we} ({extrainfo})"
203-
msg = f'error, unknown op "{str(self.op)}"'
203+
msg = f'error, unknown op "{self.op}"'
204204
raise PyrtlInternalError(msg)
205205

206206
def __hash__(self):
@@ -461,7 +461,7 @@ def get_memblock_by_name(self, name: str, strict: bool = False) -> MemBlock:
461461
return None
462462

463463
def wirevector_subset(
464-
self, cls: tuple[type] = None, exclude: tuple[type] = ()
464+
self, cls: tuple[type] | None = None, exclude: tuple[type] = ()
465465
) -> set[WireVector]:
466466
"""Return a subset of the ``Block's`` :class:`WireVectors<WireVector>`.
467467
@@ -512,7 +512,7 @@ def wirevector_subset(
512512
return set(initial_set)
513513
return {x for x in initial_set if not isinstance(x, exclude)}
514514

515-
def logic_subset(self, op: tuple[str] = None) -> set[LogicNet]:
515+
def logic_subset(self, op: tuple[str] | None = None) -> set[LogicNet]:
516516
"""Return a subset of the ``Block's`` :class:`LogicNets<LogicNet>`.
517517
518518
Filters :class:`LogicNets<LogicNet>` by their :attr:`~LogicNet.op`.
@@ -715,9 +715,8 @@ def sanity_check(self):
715715
wirevector_names_list.remove(w)
716716
msg = (
717717
"Duplicate wire names found for the following different signals: "
718-
f"{repr(wirevector_names_list)} (make sure you are not using "
719-
'"tmp" or "const_" as a signal name because those are reserved for '
720-
"internal use)"
718+
f'{wirevector_names_list} (make sure you are not using "tmp" or '
719+
'"const_" as a signal name because those are reserved for internal use)'
721720
)
722721
raise PyrtlError(msg)
723722

@@ -835,8 +834,7 @@ def sanity_check_memory_sync(self, wire_src_dict=None):
835834
msg = (
836835
f'memory "{net.op_param[1].name}" is not specified as '
837836
f'asynchronous but has an index "{net.args[0].name}" that is '
838-
"not ready at the start of the cycle due to net "
839-
f'"{str(src_net)}"'
837+
f'not ready at the start of the cycle due to net "{src_net}"'
840838
)
841839
raise PyrtlError(msg)
842840

pyrtl/corecircuits.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -750,7 +750,7 @@ def match_bitwidth(*args: WireVector, signed: bool = False) -> tuple[WireVector]
750750

751751
def as_wires(
752752
val: WireVectorLike,
753-
bitwidth: int = None,
753+
bitwidth: int | None = None,
754754
truncating: bool = True,
755755
block: Block = None,
756756
) -> WireVector:
@@ -817,7 +817,7 @@ def as_wires(
817817
if not isinstance(val, WireVector):
818818
msg = (
819819
"error, expecting a wirevector, int, or Verilog-style const string got "
820-
f"{repr(val)} instead"
820+
f"{val} instead"
821821
)
822822
raise PyrtlError(msg)
823823
if bitwidth == "0":
@@ -1020,7 +1020,7 @@ class Command(IntEnum):
10201020
if len(keytypeset) != 1:
10211021
msg = f"table mixes multiple types {keytypeset} as keys"
10221022
raise PyrtlError(msg)
1023-
keytype = list(keytypeset)[0]
1023+
keytype = next(iter(keytypeset))
10241024
# check that dictionary is complete for the enum
10251025
try:
10261026
enumkeys = list(keytype.__members__.values())

pyrtl/helperfuncs.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
probeIndexer = _NameIndexer("Probe-")
4141

4242

43-
def probe(w: WireVector, name: str = None) -> WireVector:
43+
def probe(w: WireVector, name: str | None = None) -> WireVector:
4444
"""Print useful information about a :class:`WireVector` in debug mode.
4545
4646
``probe`` can be inserted into a existing design easily because it returns the
@@ -272,7 +272,7 @@ def __exit__(self, *execinfo):
272272

273273

274274
def match_bitpattern(
275-
w: WireVector, bitpattern: str, field_map: dict[str, str] = None
275+
w: WireVector, bitpattern: str, field_map: dict[str, str] | None = None
276276
) -> MatchedFields:
277277
"""Returns a single-bit :class:`WireVector` that is ``1`` if and only if ``w``
278278
matches the ``bitpattern``, and a tuple containing the matched fields, if any.
@@ -587,7 +587,9 @@ def chop(w: WireVector, *segment_widths: int) -> list[WireVector]:
587587
return [w[s:e] for s, e in zip(starts, ends)]
588588

589589

590-
def input_list(names: str | list[str], bitwidth: int | list[int] = None) -> list[Input]:
590+
def input_list(
591+
names: str | list[str], bitwidth: int | list[int] | None = None
592+
) -> list[Input]:
591593
"""Allocate and return a list of :class:`Inputs<Input>`.
592594
593595
See :func:`wirevector_list`. Equivalent to::
@@ -608,7 +610,7 @@ def input_list(names: str | list[str], bitwidth: int | list[int] = None) -> list
608610

609611

610612
def output_list(
611-
names: str | list[str], bitwidth: int | list[int] = None
613+
names: str | list[str], bitwidth: int | list[int] | None = None
612614
) -> list[Output]:
613615
"""Allocate and return a list of :class:`Outputs<Output>`.
614616
@@ -630,7 +632,7 @@ def output_list(
630632

631633

632634
def register_list(
633-
names: str | list[str], bitwidth: int | list[int] = None
635+
names: str | list[str], bitwidth: int | list[int] | None = None
634636
) -> list[Register]:
635637
"""Allocate and return a list of :class:`Registers<Register>`.
636638
@@ -653,7 +655,7 @@ def register_list(
653655

654656
def wirevector_list(
655657
names: str | list[str],
656-
bitwidth: int | list[int] = None,
658+
bitwidth: int | list[int] | None = None,
657659
wvtype: type[WireVector] = WireVector,
658660
) -> list[WireVector]:
659661
"""Allocate and return a list of :class:`WireVectors<WireVector>`.
@@ -908,7 +910,7 @@ class ValueBitwidthTuple(NamedTuple):
908910

909911

910912
def infer_val_and_bitwidth(
911-
rawinput: int | bool | str, bitwidth: int = None, signed: bool = False
913+
rawinput: int | bool | str, bitwidth: int | None = None, signed: bool = False
912914
) -> ValueBitwidthTuple:
913915
"""Return a ``(value, bitwidth)`` :class:`tuple` inferred from the specified input.
914916
@@ -967,7 +969,7 @@ def infer_val_and_bitwidth(
967969

968970

969971
def _convert_bool(
970-
bool_val: bool, bitwidth: int = None, signed: bool = False
972+
bool_val: bool, bitwidth: int | None = None, signed: bool = False
971973
) -> ValueBitwidthTuple:
972974
if signed:
973975
msg = "error, booleans cannot be signed (convert to int first)"
@@ -982,7 +984,7 @@ def _convert_bool(
982984

983985

984986
def _convert_int(
985-
val: numbers.Integral, bitwidth: int = None, signed: bool = False
987+
val: numbers.Integral, bitwidth: int | None = None, signed: bool = False
986988
) -> ValueBitwidthTuple:
987989
# Convert val from numbers.Integral to int. This avoids issues with
988990
# limited-precision types like numpy.int32.
@@ -1026,7 +1028,7 @@ def _convert_int(
10261028

10271029

10281030
def _convert_verilog_str(
1029-
val: str, bitwidth: int = None, signed: bool = False
1031+
val: str, bitwidth: int | None = None, signed: bool = False
10301032
) -> ValueBitwidthTuple:
10311033
if signed:
10321034
msg = 'error, "signed" option with Verilog-style string constants not supported'
@@ -1981,7 +1983,7 @@ def __init__(
19811983
block: Block = None,
19821984
concatenated_type=WireVector,
19831985
component_type=WireVector,
1984-
values: list = None,
1986+
values: list | None = None,
19851987
):
19861988
# The concatenated WireVector contains all the _WireMatrix's wires.
19871989
# WrappedWireVector (base class) will forward all attribute and
@@ -2144,7 +2146,7 @@ def one_hot_to_binary(w: WireVectorLike) -> WireVector:
21442146

21452147

21462148
def binary_to_one_hot(
2147-
bit_position: WireVectorLike, max_bitwidth: int = None
2149+
bit_position: WireVectorLike, max_bitwidth: int | None = None
21482150
) -> WireVector:
21492151
"""Given a ``bit_position``, return a :class:`WireVector` with only that bit set to
21502152
``1``.

pyrtl/importexport.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def input_from_blif(
112112
block: Block = None,
113113
merge_io_vectors: bool = True,
114114
clock_name: str = "clk",
115-
top_model: str = None,
115+
top_model: str | None = None,
116116
):
117117
"""Read an open BLIF file or string as input, updating the block appropriately.
118118
@@ -528,10 +528,10 @@ def flop_next(data, enable, set, reset, prev):
528528
"$_DFFSR_PPP": lambda: select(reset, 0, select(set, 1, data)),
529529
"$_DFFSRE_PPPN_": lambda: select(
530530
reset, 0, select(set, 1, select(~enable, data, prev))
531-
), # noqa
531+
),
532532
"$_DFFSRE_PPPP_": lambda: select(
533533
reset, 0, select(set, 1, select(enable, data, prev))
534-
), # noqa
534+
),
535535
"$_SDFF_PN0_": lambda: select(~reset, 0, data),
536536
"$_SDFF_PN1_": lambda: select(~reset, 1, data),
537537
"$_SDFF_PP0_": lambda: select(reset, 0, data),
@@ -637,8 +637,8 @@ def instantiate(subckt):
637637
def input_from_verilog(
638638
verilog,
639639
clock_name: str = "clk",
640-
toplevel: str = None,
641-
leave_in_dir: bool = None,
640+
toplevel: str | None = None,
641+
leave_in_dir: bool | None = None,
642642
block: Block = None,
643643
):
644644
"""Read an open Verilog file or string as input via `Yosys
@@ -860,7 +860,7 @@ def name_list(wires):
860860
inputs, outputs, registers, wires, memories = _verilog_block_parts(block)
861861

862862
# module name
863-
io_list = ["clk"] + name_list(name_sorted(inputs)) + name_list(name_sorted(outputs))
863+
io_list = ["clk", *name_list(name_sorted(inputs)), *name_list(name_sorted(outputs))]
864864
if add_reset:
865865
io_list.insert(1, "rst")
866866
if any(w.startswith("tmp") for w in io_list):
@@ -971,7 +971,7 @@ def name_sorted(wires):
971971
# someone please check if we need this special handling for scalars
972972
catlist = ", ".join(
973973
[
974-
varname(net.args[0]) + f"[{str(i)}]"
974+
varname(net.args[0]) + f"[{i}]"
975975
if len(net.args[0]) > 1
976976
else varname(net.args[0])
977977
for i in reversed(net.op_param)
@@ -1070,9 +1070,9 @@ def _to_verilog_footer(file):
10701070
def output_verilog_testbench(
10711071
dest_file,
10721072
simulation_trace: SimulationTrace = None,
1073-
toplevel_include: str = None,
1073+
toplevel_include: str | None = None,
10741074
vcd: str = "waveform.vcd",
1075-
cmd: str = None,
1075+
cmd: str | None = None,
10761076
add_reset: bool | str = True,
10771077
block: Block = None,
10781078
):
@@ -1217,7 +1217,7 @@ def default_value():
12171217
print(" integer tb_iter;", file=dest_file)
12181218

12191219
# Instantiate logic block
1220-
io_list = ["clk"] + name_list(name_sorted(inputs)) + name_list(name_sorted(outputs))
1220+
io_list = ["clk", *name_list(name_sorted(inputs)), *name_list(name_sorted(outputs))]
12211221
if add_reset:
12221222
io_list.insert(1, "rst")
12231223
io_list_str = [f".{w:s}({w:s})" for w in io_list]
@@ -1286,7 +1286,9 @@ def default_value():
12861286
#
12871287

12881288

1289-
def output_to_firrtl(open_file, rom_blocks: list[RomBlock] = None, block: Block = None):
1289+
def output_to_firrtl(
1290+
open_file, rom_blocks: list[RomBlock] | None = None, block: Block = None
1291+
):
12901292
"""Output the block as FIRRTL code to the output file.
12911293
12921294
If ROM is initialized in PyRTL code, you can pass in the :class:`RomBlocks` as a

0 commit comments

Comments
 (0)