cocotb 1.9.2__cp311-cp311-win32.whl → 2.0.0b1__cp311-cp311-win32.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.

Potentially problematic release.


This version of cocotb might be problematic. Click here for more details.

Files changed (155) hide show
  1. cocotb/{ANSI.py → _ANSI.py} +5 -25
  2. cocotb/__init__.py +76 -332
  3. cocotb/_base_triggers.py +513 -0
  4. cocotb/_bridge.py +187 -0
  5. cocotb/_decorators.py +515 -0
  6. cocotb/_deprecation.py +3 -3
  7. cocotb/_exceptions.py +7 -0
  8. cocotb/_extended_awaitables.py +419 -0
  9. cocotb/_gpi_triggers.py +382 -0
  10. cocotb/_init.py +295 -0
  11. cocotb/_outcomes.py +54 -0
  12. cocotb/_profiling.py +46 -0
  13. cocotb/_py_compat.py +100 -29
  14. cocotb/_scheduler.py +454 -0
  15. cocotb/_test.py +245 -0
  16. cocotb/_test_factory.py +309 -0
  17. cocotb/_test_functions.py +42 -0
  18. cocotb/_typing.py +7 -0
  19. cocotb/_utils.py +296 -0
  20. cocotb/_version.py +3 -7
  21. cocotb/_xunit_reporter.py +66 -0
  22. cocotb/clock.py +271 -108
  23. cocotb/handle.py +1342 -795
  24. cocotb/libs/cocotb.dll +0 -0
  25. cocotb/libs/cocotb.exp +0 -0
  26. cocotb/libs/cocotb.lib +0 -0
  27. cocotb/libs/cocotbfli_modelsim.dll +0 -0
  28. cocotb/libs/cocotbfli_modelsim.exp +0 -0
  29. cocotb/libs/cocotbfli_modelsim.lib +0 -0
  30. cocotb/libs/cocotbutils.dll +0 -0
  31. cocotb/libs/cocotbutils.exp +0 -0
  32. cocotb/libs/cocotbutils.lib +0 -0
  33. cocotb/libs/cocotbvhpi_aldec.dll +0 -0
  34. cocotb/libs/cocotbvhpi_aldec.exp +0 -0
  35. cocotb/libs/cocotbvhpi_aldec.lib +0 -0
  36. cocotb/libs/cocotbvhpi_modelsim.dll +0 -0
  37. cocotb/libs/cocotbvhpi_modelsim.exp +0 -0
  38. cocotb/libs/cocotbvhpi_modelsim.lib +0 -0
  39. cocotb/libs/cocotbvpi_aldec.dll +0 -0
  40. cocotb/libs/cocotbvpi_aldec.exp +0 -0
  41. cocotb/libs/cocotbvpi_aldec.lib +0 -0
  42. cocotb/libs/cocotbvpi_ghdl.dll +0 -0
  43. cocotb/libs/cocotbvpi_ghdl.exp +0 -0
  44. cocotb/libs/cocotbvpi_ghdl.lib +0 -0
  45. cocotb/libs/cocotbvpi_icarus.exp +0 -0
  46. cocotb/libs/cocotbvpi_icarus.lib +0 -0
  47. cocotb/libs/cocotbvpi_icarus.vpl +0 -0
  48. cocotb/libs/cocotbvpi_modelsim.dll +0 -0
  49. cocotb/libs/cocotbvpi_modelsim.exp +0 -0
  50. cocotb/libs/cocotbvpi_modelsim.lib +0 -0
  51. cocotb/libs/embed.dll +0 -0
  52. cocotb/libs/embed.exp +0 -0
  53. cocotb/libs/embed.lib +0 -0
  54. cocotb/libs/gpi.dll +0 -0
  55. cocotb/libs/gpi.exp +0 -0
  56. cocotb/libs/gpi.lib +0 -0
  57. cocotb/libs/gpilog.dll +0 -0
  58. cocotb/libs/gpilog.exp +0 -0
  59. cocotb/libs/gpilog.lib +0 -0
  60. cocotb/libs/pygpilog.dll +0 -0
  61. cocotb/libs/pygpilog.exp +0 -0
  62. cocotb/libs/pygpilog.lib +0 -0
  63. cocotb/{log.py → logging.py} +105 -110
  64. cocotb/queue.py +103 -57
  65. cocotb/regression.py +667 -712
  66. cocotb/result.py +17 -188
  67. cocotb/share/def/aldec.exp +0 -0
  68. cocotb/share/def/aldec.lib +0 -0
  69. cocotb/share/def/ghdl.exp +0 -0
  70. cocotb/share/def/ghdl.lib +0 -0
  71. cocotb/share/def/icarus.exp +0 -0
  72. cocotb/share/def/icarus.lib +0 -0
  73. cocotb/share/def/modelsim.def +1 -0
  74. cocotb/share/def/modelsim.exp +0 -0
  75. cocotb/share/def/modelsim.lib +0 -0
  76. cocotb/share/include/cocotb_utils.h +6 -29
  77. cocotb/share/include/embed.h +5 -28
  78. cocotb/share/include/gpi.h +137 -92
  79. cocotb/share/include/gpi_logging.h +221 -142
  80. cocotb/share/include/py_gpi_logging.h +7 -4
  81. cocotb/share/include/vpi_user_ext.h +4 -26
  82. cocotb/share/lib/verilator/verilator.cpp +59 -54
  83. cocotb/simulator.cp311-win32.exp +0 -0
  84. cocotb/simulator.cp311-win32.lib +0 -0
  85. cocotb/simulator.cp311-win32.pyd +0 -0
  86. cocotb/simulator.pyi +107 -0
  87. cocotb/task.py +434 -212
  88. cocotb/triggers.py +55 -1092
  89. cocotb/types/__init__.py +25 -47
  90. cocotb/types/_abstract_array.py +151 -0
  91. cocotb/types/_array.py +264 -0
  92. cocotb/types/_logic.py +296 -0
  93. cocotb/types/_logic_array.py +834 -0
  94. cocotb/types/{range.py → _range.py} +36 -44
  95. cocotb/types/_resolve.py +76 -0
  96. cocotb/utils.py +119 -587
  97. cocotb-2.0.0b1.dist-info/METADATA +60 -0
  98. cocotb-2.0.0b1.dist-info/RECORD +143 -0
  99. {cocotb-1.9.2.dist-info → cocotb-2.0.0b1.dist-info}/WHEEL +1 -1
  100. cocotb-2.0.0b1.dist-info/entry_points.txt +2 -0
  101. {cocotb-1.9.2.dist-info → cocotb-2.0.0b1.dist-info}/top_level.txt +1 -0
  102. cocotb_tools/__init__.py +0 -0
  103. cocotb_tools/_coverage.py +33 -0
  104. cocotb_tools/_vendor/__init__.py +3 -0
  105. cocotb_tools/check_results.py +65 -0
  106. cocotb_tools/combine_results.py +152 -0
  107. cocotb_tools/config.py +241 -0
  108. {cocotb → cocotb_tools}/ipython_support.py +29 -22
  109. cocotb_tools/makefiles/Makefile.deprecations +27 -0
  110. {cocotb/share → cocotb_tools}/makefiles/Makefile.inc +82 -54
  111. {cocotb/share → cocotb_tools}/makefiles/Makefile.sim +8 -33
  112. {cocotb/share → cocotb_tools}/makefiles/simulators/Makefile.activehdl +9 -16
  113. cocotb_tools/makefiles/simulators/Makefile.cvc +61 -0
  114. cocotb_tools/makefiles/simulators/Makefile.dsim +39 -0
  115. {cocotb/share → cocotb_tools}/makefiles/simulators/Makefile.ghdl +13 -42
  116. cocotb_tools/makefiles/simulators/Makefile.icarus +80 -0
  117. cocotb_tools/makefiles/simulators/Makefile.ius +93 -0
  118. cocotb_tools/makefiles/simulators/Makefile.modelsim +9 -0
  119. cocotb_tools/makefiles/simulators/Makefile.nvc +60 -0
  120. cocotb_tools/makefiles/simulators/Makefile.questa +29 -0
  121. cocotb/share/makefiles/simulators/Makefile.questa → cocotb_tools/makefiles/simulators/Makefile.questa-compat +26 -54
  122. cocotb_tools/makefiles/simulators/Makefile.questa-qisqrun +149 -0
  123. {cocotb/share → cocotb_tools}/makefiles/simulators/Makefile.riviera +17 -56
  124. cocotb_tools/makefiles/simulators/Makefile.vcs +65 -0
  125. {cocotb/share → cocotb_tools}/makefiles/simulators/Makefile.verilator +15 -22
  126. {cocotb/share → cocotb_tools}/makefiles/simulators/Makefile.xcelium +20 -52
  127. cocotb_tools/py.typed +0 -0
  128. {cocotb → cocotb_tools}/runner.py +794 -361
  129. cocotb/_sim_versions.py → cocotb_tools/sim_versions.py +16 -21
  130. pygpi/entry.py +34 -17
  131. pygpi/py.typed +0 -0
  132. cocotb/binary.py +0 -858
  133. cocotb/config.py +0 -289
  134. cocotb/decorators.py +0 -332
  135. cocotb/memdebug.py +0 -35
  136. cocotb/outcomes.py +0 -56
  137. cocotb/scheduler.py +0 -1099
  138. cocotb/share/makefiles/Makefile.deprecations +0 -12
  139. cocotb/share/makefiles/simulators/Makefile.cvc +0 -94
  140. cocotb/share/makefiles/simulators/Makefile.icarus +0 -111
  141. cocotb/share/makefiles/simulators/Makefile.ius +0 -125
  142. cocotb/share/makefiles/simulators/Makefile.modelsim +0 -32
  143. cocotb/share/makefiles/simulators/Makefile.nvc +0 -64
  144. cocotb/share/makefiles/simulators/Makefile.vcs +0 -98
  145. cocotb/types/array.py +0 -309
  146. cocotb/types/logic.py +0 -292
  147. cocotb/types/logic_array.py +0 -298
  148. cocotb/wavedrom.py +0 -199
  149. cocotb/xunit_reporter.py +0 -80
  150. cocotb-1.9.2.dist-info/METADATA +0 -168
  151. cocotb-1.9.2.dist-info/RECORD +0 -121
  152. cocotb-1.9.2.dist-info/entry_points.txt +0 -2
  153. /cocotb/{_vendor/__init__.py → py.typed} +0 -0
  154. {cocotb-1.9.2.dist-info → cocotb-2.0.0b1.dist-info/licenses}/LICENSE +0 -0
  155. {cocotb → cocotb_tools}/_vendor/distutils_version.py +0 -0
@@ -0,0 +1,309 @@
1
+ # Copyright cocotb contributors
2
+ # Licensed under the Revised BSD License, see LICENSE for details.
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+
5
+ import functools
6
+ import inspect
7
+ import logging
8
+ import warnings
9
+ from itertools import product
10
+ from types import FrameType, FunctionType
11
+ from typing import (
12
+ Callable,
13
+ Coroutine,
14
+ Dict,
15
+ Optional,
16
+ Sequence,
17
+ Tuple,
18
+ Type,
19
+ Union,
20
+ cast,
21
+ overload,
22
+ )
23
+
24
+ from cocotb._base_triggers import Trigger
25
+ from cocotb._decorators import Test
26
+ from cocotb._typing import TimeUnit
27
+
28
+
29
+ class TestFactory:
30
+ """Factory to automatically generate tests.
31
+
32
+ Args:
33
+ test_function: A Callable that returns the test Coroutine.
34
+ Must take *dut* as the first argument.
35
+ *args: Remaining arguments are passed directly to the test function.
36
+ Note that these arguments are not varied. An argument that
37
+ varies with each test must be a keyword argument to the
38
+ test function.
39
+ **kwargs: Remaining keyword arguments are passed directly to the test function.
40
+ Note that these arguments are not varied. An argument that
41
+ varies with each test must be a keyword argument to the
42
+ test function.
43
+
44
+ Assuming we have a common test function that will run a test. This test
45
+ function will take keyword arguments (for example generators for each of
46
+ the input interfaces) and generate tests that call the supplied function.
47
+
48
+ This Factory allows us to generate sets of tests based on the different
49
+ permutations of the possible arguments to the test function.
50
+
51
+ For example, if we have a module that takes backpressure, has two configurable
52
+ features where enabling ``feature_b`` requires ``feature_a`` to be active, and
53
+ need to test against data generation routines ``gen_a`` and ``gen_b``:
54
+
55
+ >>> tf = TestFactory(test_function=run_test)
56
+ >>> tf.add_option(name="data_in", optionlist=[gen_a, gen_b])
57
+ >>> tf.add_option("backpressure", [None, random_backpressure])
58
+ >>> tf.add_option(
59
+ ... ("feature_a", "feature_b"), [(False, False), (True, False), (True, True)]
60
+ ... )
61
+ >>> tf.generate_tests()
62
+
63
+ We would get the following tests:
64
+
65
+ * ``gen_a`` with no backpressure and both features disabled
66
+ * ``gen_a`` with no backpressure and only ``feature_a`` enabled
67
+ * ``gen_a`` with no backpressure and both features enabled
68
+ * ``gen_a`` with ``random_backpressure`` and both features disabled
69
+ * ``gen_a`` with ``random_backpressure`` and only ``feature_a`` enabled
70
+ * ``gen_a`` with ``random_backpressure`` and both features enabled
71
+ * ``gen_b`` with no backpressure and both features disabled
72
+ * ``gen_b`` with no backpressure and only ``feature_a`` enabled
73
+ * ``gen_b`` with no backpressure and both features enabled
74
+ * ``gen_b`` with ``random_backpressure`` and both features disabled
75
+ * ``gen_b`` with ``random_backpressure`` and only ``feature_a`` enabled
76
+ * ``gen_b`` with ``random_backpressure`` and both features enabled
77
+
78
+ The tests are appended to the calling module for auto-discovery.
79
+
80
+ Tests are simply named ``test_function_N``. The docstring for the test (hence
81
+ the test description) includes the name and description of each generator.
82
+
83
+ .. versionchanged:: 1.5
84
+ Groups of options are now supported
85
+
86
+ .. versionchanged:: 2.0
87
+ You can now pass :func:`cocotb.test` decorator arguments when generating tests.
88
+
89
+ .. deprecated:: 2.0
90
+ Use :func:`cocotb.parametrize` instead.
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ test_function: Callable[..., Coroutine[Trigger, None, None]],
96
+ *args: object,
97
+ **kwargs: object,
98
+ ) -> None:
99
+ warnings.warn(
100
+ "TestFactory is deprecated, use `@cocotb.parametrize` instead",
101
+ DeprecationWarning,
102
+ stacklevel=2,
103
+ )
104
+ self.test_function = test_function
105
+ self.args = args
106
+ self.kwargs_constant = kwargs
107
+ self.kwargs: Dict[
108
+ Union[str, Sequence[str]],
109
+ Union[Sequence[object], Sequence[Sequence[object]]],
110
+ ] = {}
111
+ self._log = logging.getLogger(f"TestFactory({self.test_function.__name__})")
112
+
113
+ @overload
114
+ def add_option(self, name: str, optionlist: Sequence[object]) -> None: ...
115
+
116
+ @overload
117
+ def add_option(
118
+ self, name: Sequence[str], optionlist: Sequence[Sequence[object]]
119
+ ) -> None: ...
120
+
121
+ def add_option(
122
+ self,
123
+ name: Union[str, Sequence[str]],
124
+ optionlist: Union[Sequence[object], Sequence[Sequence[object]]],
125
+ ) -> None:
126
+ """Add a named option to the test.
127
+
128
+ Args:
129
+ name:
130
+ An option name, or an iterable of several option names. Passed to test as keyword arguments.
131
+
132
+ optionlist:
133
+ A list of possible options for this test knob.
134
+ If N names were specified, this must be a list of N-tuples or
135
+ lists, where each element specifies a value for its respective
136
+ option.
137
+
138
+ .. versionchanged:: 1.5
139
+ Groups of options are now supported
140
+ """
141
+ if not isinstance(name, str):
142
+ optionlist = cast("Sequence[Sequence[object]]", optionlist)
143
+ for opt in optionlist:
144
+ if len(name) != len(opt):
145
+ raise ValueError(
146
+ "Mismatch between number of options and number of option values in group"
147
+ )
148
+ self.kwargs[name] = optionlist
149
+
150
+ def generate_tests(
151
+ self,
152
+ *,
153
+ prefix: Optional[str] = None,
154
+ postfix: Optional[str] = None,
155
+ stacklevel: int = 0,
156
+ name: Optional[str] = None,
157
+ timeout_time: Optional[float] = None,
158
+ timeout_unit: TimeUnit = "step",
159
+ expect_fail: bool = False,
160
+ expect_error: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = (),
161
+ skip: bool = False,
162
+ stage: int = 0,
163
+ ) -> None:
164
+ """
165
+ Generate an exhaustive set of tests using the cartesian product of the
166
+ possible keyword arguments.
167
+
168
+ The generated tests are appended to the namespace of the calling
169
+ module.
170
+
171
+ Args:
172
+ prefix:
173
+ Text string to append to start of ``test_function`` name when naming generated test cases.
174
+ This allows reuse of a single ``test_function`` with multiple :class:`TestFactories <.TestFactory>` without name clashes.
175
+
176
+ .. deprecated:: 2.0
177
+ Use the more flexible ``name`` field instead.
178
+
179
+ postfix:
180
+ Text string to append to end of ``test_function`` name when naming generated test cases.
181
+ This allows reuse of a single ``test_function`` with multiple :class:`TestFactories <.TestFactory>` without name clashes.
182
+
183
+ .. deprecated:: 2.0
184
+ Use the more flexible ``name`` field instead.
185
+ stacklevel:
186
+ Which stack level to add the generated tests to. This can be used to make a custom TestFactory wrapper.
187
+
188
+ name:
189
+ Passed as ``name`` argument to :func:`cocotb.test`.
190
+
191
+ .. versionadded:: 2.0
192
+
193
+ timeout_time:
194
+ Passed as ``timeout_time`` argument to :func:`cocotb.test`.
195
+
196
+ .. versionadded:: 2.0
197
+
198
+ timeout_unit:
199
+ Passed as ``timeout_unit`` argument to :func:`cocotb.test`.
200
+
201
+ .. versionadded:: 2.0
202
+
203
+ expect_fail:
204
+ Passed as ``expect_fail`` argument to :func:`cocotb.test`.
205
+
206
+ .. versionadded:: 2.0
207
+
208
+ expect_error:
209
+ Passed as ``expect_error`` argument to :func:`cocotb.test`.
210
+
211
+ .. versionadded:: 2.0
212
+
213
+ skip:
214
+ Passed as ``skip`` argument to :func:`cocotb.test`.
215
+
216
+ .. versionadded:: 2.0
217
+
218
+ stage:
219
+ Passed as ``stage`` argument to :func:`cocotb.test`.
220
+
221
+ .. versionadded:: 2.0
222
+ """
223
+
224
+ if prefix is not None:
225
+ warnings.warn(
226
+ "``prefix`` argument is deprecated. Use the more flexible ``name`` field instead.",
227
+ DeprecationWarning,
228
+ stacklevel=2,
229
+ )
230
+ else:
231
+ prefix = ""
232
+
233
+ if postfix is not None:
234
+ warnings.warn(
235
+ "``postfix`` argument is deprecated. Use the more flexible ``name`` field instead.",
236
+ DeprecationWarning,
237
+ stacklevel=2,
238
+ )
239
+ else:
240
+ postfix = ""
241
+
242
+ # trust the user puts a reasonable stacklevel in
243
+ glbs = cast("FrameType", inspect.stack()[stacklevel][0].f_back).f_globals
244
+
245
+ test_func_name = self.test_function.__qualname__ if name is None else name
246
+
247
+ for index, testoptions in enumerate(
248
+ dict(zip(self.kwargs, v)) for v in product(*self.kwargs.values())
249
+ ):
250
+ name = f"{prefix}{test_func_name}{postfix}_{(index + 1):03d}"
251
+ doc: str = "Automatically generated test\n\n"
252
+
253
+ # preprocess testoptions to split tuples
254
+ testoptions_split: Dict[str, Sequence[object]] = {}
255
+ for optname, optvalue in testoptions.items():
256
+ if isinstance(optname, str):
257
+ optvalue = cast("Sequence[object]", optvalue)
258
+ testoptions_split[optname] = optvalue
259
+ else:
260
+ # previously checked in add_option; ensure nothing has changed
261
+ optvalue = cast("Sequence[Sequence[object]]", optvalue)
262
+ assert len(optname) == len(optvalue)
263
+ for n, v in zip(optname, optvalue):
264
+ testoptions_split[n] = v
265
+
266
+ for optname, optvalue in testoptions_split.items():
267
+ if callable(optvalue):
268
+ optvalue = cast("FunctionType", optvalue)
269
+ if optvalue.__doc__ is None:
270
+ desc = "No docstring supplied"
271
+ else:
272
+ desc = optvalue.__doc__.split("\n")[0]
273
+ doc += f"\t{optname}: {optvalue.__qualname__} ({desc})\n"
274
+ else:
275
+ doc += f"\t{optname}: {optvalue!r}\n"
276
+
277
+ kwargs = self.kwargs_constant.copy()
278
+ kwargs.update(testoptions_split)
279
+
280
+ @functools.wraps(self.test_function)
281
+ async def _my_test(dut: object, kwargs: Dict[str, object] = kwargs) -> None:
282
+ await self.test_function(dut, *self.args, **kwargs)
283
+
284
+ _my_test.__doc__ = doc
285
+ _my_test.__name__ = name
286
+ _my_test.__qualname__ = name
287
+
288
+ if name in glbs:
289
+ self._log.error(
290
+ "Overwriting %s in module %s. "
291
+ "This causes a previously defined testcase not to be run. "
292
+ "Consider using the `name`, `prefix`, or `postfix` arguments to augment the name.",
293
+ name,
294
+ glbs["__name__"],
295
+ )
296
+
297
+ test = Test(
298
+ func=_my_test,
299
+ name=name,
300
+ module=glbs["__name__"],
301
+ timeout_time=timeout_time,
302
+ timeout_unit=timeout_unit,
303
+ expect_fail=expect_fail,
304
+ expect_error=expect_error,
305
+ skip=skip,
306
+ stage=stage,
307
+ )
308
+
309
+ glbs[test.name] = test
@@ -0,0 +1,42 @@
1
+ # Copyright cocotb contributors
2
+ # Licensed under the Revised BSD License, see LICENSE for details.
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ """Collection of functions to control a running test and related exceptions."""
5
+
6
+ from typing import NoReturn, Type, Union
7
+
8
+ Failed: Type[BaseException]
9
+ try:
10
+ import pytest
11
+ except ModuleNotFoundError:
12
+ Failed = AssertionError
13
+ else:
14
+ try:
15
+ with pytest.raises(Exception):
16
+ pass
17
+ except BaseException as _raises_e:
18
+ Failed = type(_raises_e)
19
+ else:
20
+ assert False, "pytest.raises doesn't raise an exception when it fails"
21
+
22
+
23
+ class TestSuccess(BaseException):
24
+ """Implementation of :func:`pass_test`.
25
+
26
+ Users are *not* intended to catch this exception type.
27
+ """
28
+
29
+ def __init__(self, msg: Union[str, None]) -> None:
30
+ super().__init__(msg)
31
+ self.msg = msg
32
+
33
+
34
+ def pass_test(msg: Union[str, None] = None) -> NoReturn:
35
+ """Force a test to pass.
36
+
37
+ The test will end and enter termination phase when this is called.
38
+
39
+ Args:
40
+ msg: The message to display when the test passes.
41
+ """
42
+ raise TestSuccess(msg)
cocotb/_typing.py ADDED
@@ -0,0 +1,7 @@
1
+ # Copyright cocotb contributors
2
+ # Licensed under the Revised BSD License, see LICENSE for details.
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ from cocotb._py_compat import Literal, TypeAlias
5
+
6
+ RoundMode: TypeAlias = Literal["error", "round", "ceil", "floor"]
7
+ TimeUnit: TypeAlias = Literal["step", "fs", "ps", "ns", "us", "ms", "sec"]
cocotb/_utils.py ADDED
@@ -0,0 +1,296 @@
1
+ # Copyright cocotb contributors
2
+ # Copyright (c) 2013 Potential Ventures Ltd
3
+ # Copyright (c) 2013 SolarFlare Communications Inc
4
+ # Licensed under the Revised BSD License, see LICENSE for details.
5
+ # SPDX-License-Identifier: BSD-3-Clause
6
+
7
+ """Utilities for implementors."""
8
+
9
+ import os
10
+ import sys
11
+ import traceback
12
+ import types
13
+ from enum import Enum, IntEnum
14
+ from functools import lru_cache, update_wrapper, wraps
15
+ from types import TracebackType
16
+ from typing import (
17
+ TYPE_CHECKING,
18
+ Any,
19
+ Iterable,
20
+ List,
21
+ Optional,
22
+ Tuple,
23
+ Type,
24
+ TypeVar,
25
+ Union,
26
+ cast,
27
+ overload,
28
+ )
29
+
30
+
31
+ @lru_cache(maxsize=None)
32
+ def want_color_output() -> bool:
33
+ """Return ``True`` if colored output is possible/requested and not running in GUI.
34
+
35
+ Colored output can be explicitly requested in a cocotb-specific way
36
+ by setting :envvar:`COCOTB_ANSI_OUTPUT` to ``1``.
37
+
38
+ Returns: Whether color output is wanted and supported.
39
+ """
40
+ want_color = sys.stdout.isatty() # default to color for TTYs
41
+ if os.getenv("NO_COLOR") is not None:
42
+ want_color = False
43
+ if os.getenv("COCOTB_ANSI_OUTPUT", default="0") == "1":
44
+ want_color = True
45
+ if os.getenv("GUI", default="0") == "1":
46
+ want_color = False
47
+ return want_color
48
+
49
+
50
+ ExceptionTuple = Tuple[
51
+ Type[BaseException], BaseException, TracebackType
52
+ ] # TypeAlias in Python 3.10
53
+
54
+
55
+ @overload
56
+ def remove_traceback_frames(
57
+ tb_or_exc: ExceptionTuple, frame_names: List[str]
58
+ ) -> ExceptionTuple: ...
59
+
60
+
61
+ @overload
62
+ def remove_traceback_frames(
63
+ tb_or_exc: BaseException, frame_names: List[str]
64
+ ) -> BaseException: ...
65
+
66
+
67
+ @overload
68
+ def remove_traceback_frames(
69
+ tb_or_exc: TracebackType, frame_names: List[str]
70
+ ) -> TracebackType: ...
71
+
72
+
73
+ def remove_traceback_frames(
74
+ tb_or_exc: Union[ExceptionTuple, BaseException, TracebackType],
75
+ frame_names: List[str],
76
+ ) -> Union[ExceptionTuple, BaseException, TracebackType]:
77
+ """
78
+ Strip leading frames from a traceback
79
+
80
+ Args:
81
+ tb_or_exc:
82
+ Object to strip frames from. If an exception is passed, creates
83
+ a copy of the exception with a new shorter traceback. If a tuple
84
+ from `sys.exc_info` is passed, returns the same tuple with the
85
+ traceback shortened
86
+ frame_names:
87
+ Names of the frames to strip, which must be present at the top of the Traceback or Exception.
88
+
89
+ Returns:
90
+ Traceback or Exception passed to the function with the *frame_names* stripped out.
91
+ """
92
+ # self-invoking overloads
93
+ if isinstance(tb_or_exc, BaseException):
94
+ exc: BaseException = tb_or_exc
95
+ return exc.with_traceback(
96
+ remove_traceback_frames(
97
+ cast("TracebackType", exc.__traceback__), frame_names
98
+ )
99
+ )
100
+ elif isinstance(tb_or_exc, tuple):
101
+ exc_type, exc_value, exc_tb = tb_or_exc
102
+ exc_tb = remove_traceback_frames(exc_tb, frame_names)
103
+ return exc_type, exc_value, exc_tb
104
+ # base case
105
+ else:
106
+ tb: TracebackType = tb_or_exc
107
+ for frame_name in frame_names:
108
+ # the assert and cast are there assuming the frame_names being removed are correct
109
+ assert tb.tb_frame.f_code.co_name == frame_name
110
+ tb = cast("TracebackType", tb.tb_next)
111
+ return tb
112
+
113
+
114
+ def walk_coro_stack(
115
+ coro: "types.CoroutineType[Any, Any, Any]",
116
+ ) -> Iterable[Tuple[types.FrameType, int]]:
117
+ """Walk down the coroutine stack, starting at *coro*.
118
+
119
+ Args:
120
+ coro: The :class:`coroutine` object to traverse.
121
+
122
+ Yields:
123
+ Frame and line number of each frame in the coroutine.
124
+ """
125
+ c: Optional[types.CoroutineType[Any, Any, Any]] = coro
126
+ while c is not None:
127
+ try:
128
+ f = c.cr_frame
129
+ except AttributeError:
130
+ break
131
+ else:
132
+ c = c.cr_await
133
+ if f is not None:
134
+ yield (f, f.f_lineno)
135
+
136
+
137
+ def extract_coro_stack(
138
+ coro: "types.CoroutineType[Any, Any, Any]", limit: Optional[int] = None
139
+ ) -> traceback.StackSummary:
140
+ r"""Create a list of pre-processed entries from the coroutine stack.
141
+
142
+ This is based on :func:`traceback.extract_tb`.
143
+
144
+ If *limit* is omitted or ``None``, all entries are extracted.
145
+ The list is a :class:`traceback.StackSummary` object, and
146
+ each entry in the list is a :class:`traceback.FrameSummary` object
147
+ containing attributes ``filename``, ``lineno``, ``name``, and ``line``
148
+ representing the information that is usually printed for a stack
149
+ trace. The line is a string with leading and trailing
150
+ whitespace stripped; if the source is not available it is ``None``.
151
+
152
+ Args:
153
+ coro: The :class:`coroutine` object from which to extract a stack.
154
+ level: The maximum number of frames from *coro*\ s stack to extract.
155
+
156
+ Returns:
157
+ The stack of *coro*.
158
+ """
159
+ return traceback.StackSummary.extract(walk_coro_stack(coro), limit=limit)
160
+
161
+
162
+ EnumT = TypeVar("EnumT", bound=Enum)
163
+
164
+
165
+ class DocEnum(Enum):
166
+ """Like :class:`enum.Enum`, but allows documenting enum values.
167
+
168
+ Documentation for enum members can be optionally added by setting enum values to a tuple of the intended value and the docstring.
169
+ This adds the provided docstring to the ``__doc__`` field of the enum value.
170
+
171
+ .. code-block:: python
172
+
173
+ class MyEnum(DocEnum):
174
+ \"\"\"Class documentation\"\"\"
175
+
176
+ VALUE1 = 1, "Value documentation"
177
+ VALUE2 = 2 # no documentation
178
+
179
+ Taken from :ref:`this StackOverflow answer <https://stackoverflow.com/questions/50473951/how-can-i-attach-documentation-to-members-of-a-python-enum/50473952#50473952>`
180
+ by :ref:`Eric Wieser <https://stackoverflow.com/users/102441/eric>`,
181
+ as recommended by the ``enum_tools`` documentation.
182
+ """
183
+
184
+ def __new__(cls: Type[EnumT], value: object, doc: Optional[str] = None) -> EnumT:
185
+ # super().__new__() assumes the value is already an enum value
186
+ # so we side step that and create a raw object and fill in _value_
187
+ self = object.__new__(cls)
188
+ self._value_ = value
189
+ if doc is not None:
190
+ self.__doc__ = doc
191
+ return self
192
+
193
+
194
+ IntEnumT = TypeVar("IntEnumT", bound=IntEnum)
195
+
196
+
197
+ class DocIntEnum(IntEnum):
198
+ """Like DocEnum but for :class:`IntEnum` enum types."""
199
+
200
+ def __new__(cls: Type[IntEnumT], value: int, doc: Optional[str] = None) -> IntEnumT:
201
+ self = int.__new__(cls, value)
202
+ self._value_ = value
203
+ if doc is not None:
204
+ self.__doc__ = doc
205
+ return self
206
+
207
+
208
+ if TYPE_CHECKING:
209
+ F = TypeVar("F")
210
+
211
+ def cached_method(f: F) -> F: ...
212
+
213
+ else:
214
+
215
+ class cached_method:
216
+ def __init__(self, method):
217
+ self._method = method
218
+ update_wrapper(self, method)
219
+
220
+ def __get__(self, instance, objtype=None):
221
+ if instance is None:
222
+ return self
223
+
224
+ cache = {}
225
+
226
+ @wraps(self._method)
227
+ def lookup(*args, **kwargs):
228
+ key = (args, tuple(kwargs.items()))
229
+ try:
230
+ return cache[key]
231
+ except KeyError:
232
+ res = self._method(instance, *args, **kwargs)
233
+ cache[key] = res
234
+ return res
235
+
236
+ lookup.cache = cache
237
+
238
+ setattr(instance, self._method.__name__, lookup)
239
+ return lookup
240
+
241
+ def __call__(self, instance, *args, **kwargs):
242
+ func = getattr(instance, self._method.__name__)
243
+ return func(*args, **kwargs)
244
+
245
+
246
+ T = TypeVar("T")
247
+
248
+
249
+ if TYPE_CHECKING:
250
+
251
+ def singleton(orig_cls: T) -> T: ...
252
+
253
+ else:
254
+
255
+ def singleton(orig_cls):
256
+ """Class decorator which turns a type into a Singleton type."""
257
+ orig_new = orig_cls.__new__
258
+ orig_init = orig_cls.__init__
259
+ instance = None
260
+
261
+ @wraps(orig_cls.__new__)
262
+ def __new__(cls, *args, **kwargs):
263
+ nonlocal instance
264
+ if instance is None:
265
+ instance = orig_new(cls, *args, **kwargs)
266
+ orig_init(instance, *args, **kwargs)
267
+ return instance
268
+
269
+ @wraps(orig_cls.__init__)
270
+ def __init__(self, *args, **kwargs):
271
+ pass
272
+
273
+ orig_cls.__new__ = __new__
274
+ orig_cls.__init__ = __init__
275
+ return orig_cls
276
+
277
+
278
+ def pointer_str(obj: object) -> str:
279
+ """Get the memory address of *obj* as used in :meth:`object.__repr__`.
280
+
281
+ This is equivalent to ``sprintf("%p", id(obj))``, but Python does not
282
+ support ``%p``.
283
+ """
284
+ full_repr = object.__repr__(obj) # gives "<{type} object at {address}>"
285
+ return full_repr.rsplit(" ", 1)[1][:-1]
286
+
287
+
288
+ def safe_divide(a: float, b: float) -> float:
289
+ """Used when computing time ratios to ensure no exception is raised if either time is 0."""
290
+ try:
291
+ return a / b
292
+ except ZeroDivisionError:
293
+ if a == 0:
294
+ return float("nan")
295
+ else:
296
+ return float("inf")
cocotb/_version.py CHANGED
@@ -1,8 +1,4 @@
1
- # Package versioning solution originally found here:
2
- # http://stackoverflow.com/q/458550
1
+ # Package version
2
+ # Generated by setup.py -- do not modify directly
3
3
 
4
- # Store the version here so:
5
- # 1) we don't load dependencies by storing it in __init__.py
6
- # 2) we can import it in setup.py for the same reason
7
- # 3) we can import it into your module
8
- __version__ = "1.9.2"
4
+ __version__ = "2.0.0b1"