Skip to content

Commit 412eb98

Browse files
committed
resolve linter errors
Signed-off-by: Wojciech Sipak <[email protected]>
1 parent aadd59e commit 412eb98

15 files changed

+440
-398
lines changed

xls/modules/zstd/cocotb/channel.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
"""Cocotb interfaces for XLS channels using data, valid, and ready signals."""
16+
1517
from typing import Any, Sequence, Type, Union
1618

1719
import cocotb
@@ -30,6 +32,7 @@
3032

3133

3234
class XLSChannel(Bus):
35+
"""Represents an XLS- channel with ready/valid handshake."""
3336
_signals = XLS_CHANNEL_SIGNALS
3437
_optional_signals = XLS_CHANNEL_OPTIONAL_SIGNALS
3538

@@ -41,7 +44,7 @@ def __init__(self, entity, name, clk, *, start_now=False, **kwargs: Any):
4144

4245
@cocotb.coroutine
4346
async def recv_channel(self):
44-
"""Cocotb coroutine that acts as a proc receiving data from a channel"""
47+
"""Cocotb coroutine that acts as a proc receiving data from a channel."""
4548
self.rdy.setimmediatevalue(1)
4649
while True:
4750
await RisingEdge(self.clk)
@@ -51,6 +54,7 @@ def start_recv_loop(self):
5154

5255

5356
class XLSChannelDriver(BusDriver):
57+
"""Drives transactions on an XLS channel."""
5458
_signals = XLS_CHANNEL_SIGNALS
5559
_optional_signals = XLS_CHANNEL_OPTIONAL_SIGNALS
5660

@@ -79,6 +83,7 @@ async def _driver_send(self, transaction: Transaction, sync: bool = True, **kwar
7983

8084

8185
class XLSChannelMonitor(BusMonitor):
86+
"""Monitors and decodes transactions on an XLS channel."""
8287
_signals = XLS_CHANNEL_SIGNALS
8388
_optional_signals = XLS_CHANNEL_OPTIONAL_SIGNALS
8489

xls/modules/zstd/cocotb/data_generator.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,16 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from pathlib import Path
16-
from enum import Enum
15+
"""Module for generating and decompressing test frames."""
16+
17+
import pathlib
18+
import enum
1719

1820
from xls.common import runfiles
1921
import subprocess
2022
import zstandard
2123

22-
class BlockType(Enum):
24+
class BlockType(enum.Enum):
2325
RAW = 0
2426
RLE = 1
2527
COMPRESSED = 2
@@ -33,10 +35,10 @@ def from_string(s):
3335
try:
3436
return BlockType[s]
3537
except KeyError as e:
36-
raise ValueError(str(e))
38+
raise ValueError(str(e)) from e
3739

3840
def CallDecodecorpus(args):
39-
decodecorpus = Path(runfiles.get_path("decodecorpus", repository = "zstd"))
41+
decodecorpus = pathlib.Path(runfiles.get_path("decodecorpus", repository = "zstd"))
4042
cmd = args
4143
cmd.insert(0, str(decodecorpus))
4244
cmd_concat = " ".join(cmd)

xls/modules/zstd/cocotb/memory.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,37 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
"""
16+
Extensions of the cocotb AXI RAM models that initialize
17+
memory contents from a binary file.
18+
"""
19+
1520
import os
1621

1722
from cocotbext.axi.axi_ram import AxiRam, AxiRamRead, AxiRamWrite
1823
from cocotbext.axi.sparse_memory import SparseMemory
1924

2025

21-
def init_axi_mem(path: os.PathLike, kwargs):
26+
def init_axi_mem(path: os.PathLike[str], kwargs):
2227
with open(path, "rb") as f:
2328
sparse_mem = SparseMemory(size=kwargs["size"])
2429
sparse_mem.write(0x0, f.read())
2530
kwargs["mem"] = sparse_mem
2631

2732

2833
class AxiRamReadFromFile(AxiRamRead):
29-
def __init__(self, *args, path: os.PathLike, **kwargs):
34+
def __init__(self, *args, path: os.PathLike[str], **kwargs):
3035
init_axi_mem(path, kwargs)
3136
super().__init__(*args, **kwargs)
3237

3338

3439
class AxiRamFromFile(AxiRam):
35-
def __init__(self, *args, path: os.PathLike, **kwargs):
40+
def __init__(self, *args, path: os.PathLike[str], **kwargs):
3641
init_axi_mem(path, kwargs)
3742
super().__init__(*args, **kwargs)
3843

3944

4045
class AxiRamWriteFromFile(AxiRamWrite):
41-
def __init__(self, *args, path: os.PathLike, **kwargs):
46+
def __init__(self, *args, path: os.PathLike[str], **kwargs):
4247
init_axi_mem(path, kwargs)
4348
super().__init__(*args, **kwargs)

xls/modules/zstd/cocotb/scoreboard.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,14 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from dataclasses import dataclass
16-
from queue import Queue
15+
"""Scoreboard creator for measuring request-response latency.
16+
17+
Tracks transactions from channel monitors, computes cycle-based latency,
18+
and logs results.
19+
"""
20+
21+
import dataclasses
22+
import queue
1723

1824
from cocotb.clock import Clock
1925
from cocotb.log import SimLog
@@ -23,20 +29,26 @@
2329
from xls.modules.zstd.cocotb.xlsstruct import XLSStruct
2430

2531

26-
@dataclass
32+
@dataclasses.dataclass
2733
class LatencyQueueItem:
34+
"""
35+
Data container for items in a latency queue.
36+
"""
37+
2838
transaction: XLSStruct
2939
timestamp: int
3040

3141

3242
class LatencyScoreboard:
43+
"""Tracks and reports latency between request and response transactions."""
44+
3345
def __init__(self, dut, clock: Clock, req_monitor: XLSChannelMonitor, resp_monitor: XLSChannelMonitor):
3446
self.dut = dut
3547
self.log = SimLog(f"zstd.cocotb.scoreboard.{self.dut._name}")
3648
self.clock = clock
3749
self.req_monitor = req_monitor
3850
self.resp_monitor = resp_monitor
39-
self.pending_req = Queue()
51+
self.pending_req = queue.Queue()
4052
self.results = []
4153

4254
self.req_monitor.add_callback(self._req_callback)
@@ -48,19 +60,20 @@ def _current_cycle(self):
4860
def _req_callback(self, transaction: XLSStruct):
4961
self.pending_req.put(LatencyQueueItem(transaction, self._current_cycle()))
5062

51-
def _resp_callback(self, transaction: XLSStruct):
63+
def _resp_callback(self, _transaction: XLSStruct):
5264
latency_item = self.pending_req.get()
5365
self.results.append(self._current_cycle() - latency_item.timestamp)
5466

5567
def average_latency(self):
5668
return sum(self.results)/len(self.results)
5769

5870
def report_result(self):
71+
"""Logs a summary of latency measurements and any unfulfilled requests."""
5972
if not self.pending_req.empty():
6073
self.log.warning(f"There are unfulfilled requests from channel {self.req_monitor.name}")
6174
while not self.pending_req.empty():
6275
self.log.warning(f"Unfulfilled request: {self.pending_req.get()}")
63-
if len(self.results) > 0:
76+
if self.results:
6477
self.log.info(f"Latency report - 1st latency: {self.results[0]}")
6578
if len(self.results) > 1:
6679
self.log.info(f"Latency report - 2nd latency: {self.results[1]}")

xls/modules/zstd/cocotb/utils.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,29 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
"""Helpers for setting up and running simulations using Icarus Verilog with Cocotb."""
16+
1517
import os
16-
from pathlib import Path
18+
import pathlib
1719

1820
import cocotb
19-
from cocotb.runner import check_results_file, get_runner
21+
from cocotb.runner import check_results_file
22+
from cocotb.runner import get_runner
2023
from cocotb.triggers import ClockCycles
2124

2225
from xls.common import runfiles
2326

2427

2528
def setup_com_iverilog():
26-
iverilog_path = Path(runfiles.get_path("iverilog", repository = "com_icarus_iverilog"))
27-
vvp_path = Path(runfiles.get_path("vvp", repository = "com_icarus_iverilog"))
29+
iverilog_path = pathlib.Path(runfiles.get_path("iverilog", repository = "com_icarus_iverilog"))
30+
vvp_path = pathlib.Path(runfiles.get_path("vvp", repository = "com_icarus_iverilog"))
2831
os.environ["PATH"] += os.pathsep + str(iverilog_path.parent)
2932
os.environ["PATH"] += os.pathsep + str(vvp_path.parent)
30-
build_dir = Path(os.environ['BUILD_WORKING_DIRECTORY'], "sim_build")
33+
build_dir = pathlib.Path(os.environ['BUILD_WORKING_DIRECTORY'], "sim_build")
3134
return build_dir
3235

3336
def run_test(toplevel, test_module, verilog_sources):
37+
"""Builds and runs a Cocotb testbench using Icarus Verilog."""
3438
build_dir = setup_com_iverilog()
3539
runner = get_runner("icarus")
3640
runner.build(
@@ -51,7 +55,7 @@ def run_test(toplevel, test_module, verilog_sources):
5155

5256
@cocotb.coroutine
5357
async def reset(clk, rst, cycles=1):
54-
"""Cocotb coroutine that performs the reset"""
58+
"""Cocotb coroutine that performs the reset."""
5559
rst.value = 1
5660
await ClockCycles(clk, cycles)
5761
rst.value = 0

xls/modules/zstd/cocotb/xlsstruct.py

Lines changed: 31 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,15 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
"""
16+
Provides utilities for defining Python representations of XLS structs.
17+
"""
18+
1519
import random
16-
from dataclasses import asdict, astuple, dataclass, fields
20+
from dataclasses import asdict
21+
from dataclasses import astuple
22+
from dataclasses import dataclass
23+
from dataclasses import fields
1724

1825
from cocotb.binary import BinaryValue
1926

@@ -22,13 +29,18 @@ class TruncationError(Exception):
2229
pass
2330

2431
def xls_dataclass(cls):
25-
"""
26-
Class decorator for XLS structs.
32+
"""Class decorator for XLS structs.
33+
2734
Usage:
2835
29-
@xls_dataclass
30-
class MyStruct(XLSStruct):
31-
...
36+
@xls_dataclass
37+
class MyStruct(XLSStruct):
38+
...
39+
Args:
40+
cls (type): The class to decorate.
41+
42+
Returns:
43+
type: The dataclass-decorated class with repr disabled.
3244
"""
3345
return dataclass(cls, repr=False)
3446

@@ -70,8 +82,7 @@ class MyStruct(XLSStruct):
7082

7183
@classmethod
7284
def _masks(cls):
73-
"""
74-
Returns a list of field-sized bitmasks.
85+
"""Returns a list of field-sized bitmasks.
7586
7687
For example for fields of widths 2, 3, 4
7788
returns [2'b11, 3'b111, 4'b1111].
@@ -84,9 +95,7 @@ def _masks(cls):
8495

8596
@classmethod
8697
def _positions(cls):
87-
"""
88-
Returns a list of start positions in a bit vector for
89-
struct's fields.
98+
"""Returns a list of start positions in a bit vector for struct's fields.
9099
91100
For example for fields of widths 1, 2, 3, 4, 5, 6
92101
returns [20, 18, 15, 11, 6, 0]
@@ -103,16 +112,12 @@ def _positions(cls):
103112
@classmethod
104113
@property
105114
def total_width(cls):
106-
"""
107-
Returns total bit width of the struct
108-
"""
115+
"""Returns total bit width of the struct."""
109116
return sum(field.type for field in fields(cls))
110117

111118
@property
112119
def value(self):
113-
"""
114-
Returns struct's value as a Python integer
115-
"""
120+
"""Returns struct's value as a Python integer."""
116121
value = 0
117122
masks = self._masks()
118123
positions = self._positions()
@@ -124,31 +129,25 @@ def value(self):
124129

125130
@property
126131
def binaryvalue(self):
127-
"""
128-
Returns struct's value as a cocotb.binary.BinaryValue
129-
"""
132+
"""Returns struct's value as a cocotb.binary.BinaryValue."""
130133
return BinaryValue(self.binstr)
131134

132135
@property
133136
def binstr(self):
134-
"""
135-
Returns struct's value as a string with its binary representation
136-
"""
137+
"""Returns struct's value as a string with its binary representation."""
137138
return f"{self.value:>0{self.total_width}b}"
138139

139140
@property
140141
def hexstr(self):
141-
"""
142-
Returns struct's value as a string with its hex representation
143-
(without leading "0x")
142+
"""Returns struct's value as a string with its hex representation.
143+
144+
The result does NOT have leading "0x".
144145
"""
145146
return f"{self.value:>0{self.total_width // 4}x}"
146147

147148
@classmethod
148149
def from_int(cls, value):
149-
"""
150-
Returns an instance of the struct from Python integer
151-
"""
150+
"""Returns an instance of the struct from Python integer."""
152151
instance = {}
153152
masks = cls._masks()
154153
positions = cls._positions()
@@ -158,9 +157,7 @@ def from_int(cls, value):
158157

159158
@classmethod
160159
def randomize(cls):
161-
"""
162-
Returns an instance of the struct with all fields' values randomized
163-
"""
160+
"""Returns an instance of the struct with all fields' values randomized."""
164161
instance = {}
165162
for field in fields(cls):
166163
instance[field.name] = random.randrange(0, 2**field.type)
@@ -171,5 +168,5 @@ def __str__(self):
171168

172169
def __repr__(self):
173170
classname = self.__class__.__name__
174-
fields = [f"{name}={hex(value)}" for name, value in asdict(self).items()]
175-
return f"{classname}({', '.join(fields)})"
171+
class_fields = [f"{name}={hex(value)}" for name, value in asdict(self).items()]
172+
return f"{classname}({', '.join(class_fields)})"

0 commit comments

Comments
 (0)