| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
"""Build HDL and run cocotb tests.""" |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
import logging |
| 13 |
import multiprocessing |
| 14 |
import os |
| 15 |
import re |
| 16 |
import shlex |
| 17 |
import shutil |
| 18 |
import subprocess |
| 19 |
import sys |
| 20 |
import tempfile |
| 21 |
import warnings |
| 22 |
from abc import ABC, abstractmethod |
| 23 |
from contextlib import suppress |
| 24 |
from itertools import chain |
| 25 |
from pathlib import Path |
| 26 |
from typing import ( |
| 27 |
Dict, |
| 28 |
Generic, |
| 29 |
Iterable, |
| 30 |
List, |
| 31 |
Mapping, |
| 32 |
Optional, |
| 33 |
Sequence, |
| 34 |
TextIO, |
| 35 |
Tuple, |
| 36 |
Type, |
| 37 |
TypeVar, |
| 38 |
Union, |
| 39 |
) |
| 40 |
|
| 41 |
import find_libpython |
| 42 |
|
| 43 |
import cocotb_tools.config |
| 44 |
from cocotb_tools.check_results import get_results |
| 45 |
from cocotb_tools.sim_versions import NvcVersion |
| 46 |
|
| 47 |
if sys.version_info >= (3, 10): |
| 48 |
from typing import TypeAlias |
| 49 |
|
| 50 |
PathLike: "TypeAlias" = Union["os.PathLike[str]", str] |
| 51 |
"A path that can be passed to :class:`pathlib.Path` or :func:`open`" |
| 52 |
|
| 53 |
_Command: "TypeAlias" = List[str] |
| 54 |
|
| 55 |
_magic_re = re.compile(r"([\\{}])") |
| 56 |
_space_re = re.compile(r"([\s])", re.ASCII) |
| 57 |
|
| 58 |
|
| 59 |
MAX_PARALLEL_BUILD_JOBS: int = 4 |
| 60 |
"""The maximum number of parallel build threads in calls to :meth:`.Runner.build`. |
| 61 |
|
| 62 |
If the number of CPU cores is less than this value, it uses the CPU core count. |
| 63 |
Set this variable to globally change the number of parallel build jobs. |
| 64 |
""" |
| 65 |
|
| 66 |
|
| 67 |
def _get_max_parallel_build_jobs() -> int: |
| 68 |
return min(MAX_PARALLEL_BUILD_JOBS, multiprocessing.cpu_count()) |
| 69 |
|
| 70 |
|
| 71 |
def _as_tcl_value(value: str) -> str: |
| 72 |
|
| 73 |
value = _magic_re.sub(r"\\\1", value) |
| 74 |
value = value.replace("\n", r"\n") |
| 75 |
value = _space_re.sub(r"\\\1", value) |
| 76 |
if value[:1] == '"': |
| 77 |
value = "\\" + value |
| 78 |
|
| 79 |
return value |
| 80 |
|
| 81 |
|
| 82 |
_sv_escapes = { |
| 83 |
"\n": "\\n", |
| 84 |
"\t": "\\t", |
| 85 |
"\\": "\\\\", |
| 86 |
'"': '\\"', |
| 87 |
"\v": "\\v", |
| 88 |
"\f": "\\f", |
| 89 |
"\xff": "\\xFF", |
| 90 |
} |
| 91 |
for i in range(32): |
| 92 |
if chr(i) not in _sv_escapes: |
| 93 |
_sv_escapes[chr(i)] = f"\\x{i:02x}" |
| 94 |
|
| 95 |
_sv_escape_translate_table = str.maketrans(_sv_escapes) |
| 96 |
|
| 97 |
|
| 98 |
def _as_sv_literal(value: object) -> str: |
| 99 |
if isinstance(value, (int, float)): |
| 100 |
return str(value) |
| 101 |
elif isinstance(value, str): |
| 102 |
return '"' + value.translate(_sv_escape_translate_table) + '"' |
| 103 |
else: |
| 104 |
raise TypeError("Can't serialize this type as an SV literal") |
| 105 |
|
| 106 |
|
| 107 |
def _shlex_join(split_command: Iterable[str]) -> str: |
| 108 |
""" |
| 109 |
Return a shell-escaped string from *split_command* |
| 110 |
This is here more for compatibility purposes |
| 111 |
""" |
| 112 |
return " ".join(shlex.quote(arg) for arg in split_command) |
| 113 |
|
| 114 |
|
| 115 |
_T = TypeVar("_T") |
| 116 |
|
| 117 |
|
| 118 |
class _Tag(Generic[_T]): |
| 119 |
def __init__(self, value: _T) -> None: |
| 120 |
self.value = value |
| 121 |
|
| 122 |
def __repr__(self) -> str: |
| 123 |
return f"{type(self).__qualname__}({self.value!r})" |
| 124 |
|
| 125 |
|
| 126 |
class _ValueAndTag(Generic[_T]): |
| 127 |
def __init__(self, value: _T, tag: Type[_Tag]) -> None: |
| 128 |
self.value = value |
| 129 |
self.tag = tag |
| 130 |
|
| 131 |
|
| 132 |
class _ValueAndOptionalTag(Generic[_T]): |
| 133 |
def __init__(self, value: _T, tag: Union[Type[_Tag], None]) -> None: |
| 134 |
self.value = value |
| 135 |
self.tag = tag |
| 136 |
|
| 137 |
|
| 138 |
class VHDL(_Tag): |
| 139 |
"""Tags source files and build arguments to :meth:`Runner.build() <cocotb_tools.runner.Runner.build>` as VHDL-specific.""" |
| 140 |
|
| 141 |
|
| 142 |
class Verilog(_Tag): |
| 143 |
"""Tags source files and build arguments to :meth:`Runner.build() <cocotb_tools.runner.Runner.build>` as Verilog-specific.""" |
| 144 |
|
| 145 |
|
| 146 |
class VerilatorControlFile(_Tag): |
| 147 |
"""Tags source files to :meth:`Runner.build() <cocotb_tools.runner.Runner.build>` as Verilator control files.""" |
| 148 |
|
| 149 |
|
| 150 |
_verilog_extensions = (".v", ".sv", ".vh", ".svh") |
| 151 |
_vhdl_extensions = (".vhd", ".vhdl") |
| 152 |
|
| 153 |
|
| 154 |
def _determine_file_type( |
| 155 |
filename: PathLike, |
| 156 |
) -> Union[Type[Verilog], Type[VHDL], Type[VerilatorControlFile]]: |
| 157 |
ext = Path(filename).suffix |
| 158 |
if ext in _verilog_extensions: |
| 159 |
return Verilog |
| 160 |
elif ext in _vhdl_extensions: |
| 161 |
return VHDL |
| 162 |
elif ext == "vlt": |
| 163 |
return VerilatorControlFile |
| 164 |
else: |
| 165 |
raise ValueError( |
| 166 |
f"Can't determine source file type of {filename}. Use the `VHDL`, `Verilog`, or `VerilatorControlFile` tags." |
| 167 |
) |
| 168 |
|
| 169 |
|
| 170 |
class Runner(ABC): |
| 171 |
supported_gpi_interfaces: Dict[str, List[str]] = {} |
| 172 |
|
| 173 |
def __init__(self) -> None: |
| 174 |
self._simulator_in_path() |
| 175 |
|
| 176 |
self.env: Dict[str, str] = {} |
| 177 |
|
| 178 |
|
| 179 |
self.build_dir: Path = get_abs_path("sim_build") |
| 180 |
self.parameters: Mapping[str, object] = {} |
| 181 |
|
| 182 |
self.log = logging.getLogger(type(self).__qualname__) |
| 183 |
self.log.setLevel(logging.INFO) |
| 184 |
|
| 185 |
@abstractmethod |
| 186 |
def _simulator_in_path(self) -> None: |
| 187 |
"""Raise exception if the simulator executable does not exist in :envvar:`PATH`. |
| 188 |
|
| 189 |
Raises: |
| 190 |
SystemExit: Simulator executable does not exist in :envvar:`PATH`. |
| 191 |
""" |
| 192 |
|
| 193 |
def _check_hdl_toplevel_lang(self, hdl_toplevel_lang: Optional[str]) -> str: |
| 194 |
"""Return *hdl_toplevel_lang* if supported by simulator, raise exception otherwise. |
| 195 |
|
| 196 |
Returns: |
| 197 |
*hdl_toplevel_lang* if supported by the simulator. |
| 198 |
|
| 199 |
Raises: |
| 200 |
ValueError: *hdl_toplevel_lang* is not supported by the simulator. |
| 201 |
""" |
| 202 |
if hdl_toplevel_lang is None: |
| 203 |
if self._vhdl_sources and not self._verilog_sources and not self._sources: |
| 204 |
lang = "vhdl" |
| 205 |
elif self._verilog_sources and not self._vhdl_sources and not self._sources: |
| 206 |
lang = "verilog" |
| 207 |
elif self._sources and not self._vhdl_sources and not self._verilog_sources: |
| 208 |
top_source = self._sources[-1] |
| 209 |
if top_source.tag is VHDL: |
| 210 |
lang = "vhdl" |
| 211 |
elif top_source.tag is Verilog: |
| 212 |
lang = "verilog" |
| 213 |
else: |
| 214 |
raise ValueError( |
| 215 |
"First argument to *sources* must be a VHDL or Verilog file. " |
| 216 |
f"Got a {top_source.tag.__qualname__} file: {top_source.value}" |
| 217 |
) |
| 218 |
else: |
| 219 |
raise ValueError( |
| 220 |
f"{type(self).__qualname__}: Must specify a hdl_toplevel_lang in a mixed-language design" |
| 221 |
) |
| 222 |
else: |
| 223 |
lang = hdl_toplevel_lang |
| 224 |
|
| 225 |
if lang in self.supported_gpi_interfaces: |
| 226 |
return lang |
| 227 |
else: |
| 228 |
raise ValueError( |
| 229 |
f"{type(self).__qualname__}: hdl_toplevel_lang {hdl_toplevel_lang!r} is not " |
| 230 |
f"in supported list: {', '.join(self.supported_gpi_interfaces)}" |
| 231 |
) |
| 232 |
|
| 233 |
def _set_env(self) -> None: |
| 234 |
"""Set environment variables for sub-processes.""" |
| 235 |
|
| 236 |
for e in os.environ: |
| 237 |
self.env[e] = os.environ[e] |
| 238 |
|
| 239 |
if "LIBPYTHON_LOC" not in self.env: |
| 240 |
libpython_path = find_libpython.find_libpython() |
| 241 |
if not libpython_path: |
| 242 |
raise ValueError( |
| 243 |
"Unable to find libpython, please make sure the appropriate libpython is installed" |
| 244 |
) |
| 245 |
self.env["LIBPYTHON_LOC"] = libpython_path |
| 246 |
|
| 247 |
self.env["PATH"] += os.pathsep + str(cocotb_tools.config.libs_dir) |
| 248 |
self.env["PYTHONPATH"] = os.pathsep.join(sys.path) |
| 249 |
self.env["PYGPI_PYTHON_BIN"] = sys.executable |
| 250 |
self.env["COCOTB_TOPLEVEL"] = self.sim_hdl_toplevel |
| 251 |
self.env["COCOTB_TEST_MODULES"] = self.test_module |
| 252 |
self.env["TOPLEVEL_LANG"] = self.hdl_toplevel_lang |
| 253 |
|
| 254 |
@abstractmethod |
| 255 |
def _build_command(self) -> Sequence[_Command]: |
| 256 |
"""Return command to build the HDL sources.""" |
| 257 |
|
| 258 |
@abstractmethod |
| 259 |
def _test_command(self) -> Sequence[_Command]: |
| 260 |
"""Return command to run a test.""" |
| 261 |
|
| 262 |
def _use_external_viewer(self) -> bool: |
| 263 |
"""Return if an external viewer should be called after simulation when ``gui=True``.""" |
| 264 |
return False |
| 265 |
|
| 266 |
def _waves_file(self) -> Optional[str]: |
| 267 |
"""Return file name of the generated waveform file for use with external viewer.""" |
| 268 |
return None |
| 269 |
|
| 270 |
def build( |
| 271 |
self, |
| 272 |
hdl_library: str = "top", |
| 273 |
verilog_sources: Sequence[Union[PathLike, Verilog]] = [], |
| 274 |
vhdl_sources: Sequence[Union[PathLike, VHDL]] = [], |
| 275 |
sources: Sequence[Union[PathLike, VHDL, Verilog, VerilatorControlFile]] = [], |
| 276 |
includes: Sequence[PathLike] = [], |
| 277 |
defines: Mapping[str, object] = {}, |
| 278 |
parameters: Mapping[str, object] = {}, |
| 279 |
build_args: Sequence[Union[str, VHDL, Verilog]] = [], |
| 280 |
hdl_toplevel: Optional[str] = None, |
| 281 |
always: bool = False, |
| 282 |
build_dir: PathLike = "sim_build", |
| 283 |
clean: bool = False, |
| 284 |
verbose: bool = False, |
| 285 |
timescale: Optional[Tuple[str, str]] = None, |
| 286 |
waves: bool = False, |
| 287 |
log_file: Optional[PathLike] = None, |
| 288 |
) -> None: |
| 289 |
"""Build the HDL sources. |
| 290 |
|
| 291 |
With mixed language simulators, *sources* will be built, |
| 292 |
followed by *vhdl_sources*, then *verilog_sources*. |
| 293 |
With simulators that only support either VHDL or Verilog, *sources* will be built, |
| 294 |
followed by *vhdl_sources* and *verilog_sources*, respectively. |
| 295 |
|
| 296 |
If your source files use an atypical file extension, |
| 297 |
use :class:`VHDL`, :class:`Verilog`, or :class:`VerilatorControlFile` |
| 298 |
to tag the path as a VHDL, Verilog, or Verilator control file source file, respectively. |
| 299 |
If the filepaths aren't tagged, the extension is used to determine if they are VHDL or Verilog files. |
| 300 |
|
| 301 |
+----------+------------------------------------+ |
| 302 |
| Language | File Extensions | |
| 303 |
+==========+====================================+ |
| 304 |
| VHDL | ``.vhd``, ``.vhdl`` | |
| 305 |
+----------+------------------------------------+ |
| 306 |
| Verilog | ``.v``, ``.sv``, ``.vh``, ``.svh`` | |
| 307 |
+----------+------------------------------------+ |
| 308 |
|
| 309 |
|
| 310 |
.. code-block:: python |
| 311 |
|
| 312 |
runner.build( |
| 313 |
sources=[ |
| 314 |
VHDL("/my/file.is_actually_vhdl"), |
| 315 |
Verilog("/other/file.verilog"), |
| 316 |
], |
| 317 |
) |
| 318 |
|
| 319 |
The same tagging works for *build_args*. |
| 320 |
Tagged *build_args* only supply that option to the compiler when building the source file for the tagged language. |
| 321 |
Non-tagged *build_args* are supplied when compiling any language. |
| 322 |
|
| 323 |
Args: |
| 324 |
hdl_library: The library name to compile into. |
| 325 |
verilog_sources: Verilog source files to build. |
| 326 |
vhdl_sources: VHDL source files to build. |
| 327 |
sources: Language-agnostic list of source files to build. |
| 328 |
includes: Verilog include directories. |
| 329 |
defines: Defines to set. |
| 330 |
parameters: Verilog parameters or VHDL generics. |
| 331 |
build_args: Extra build arguments for the simulator. |
| 332 |
hdl_toplevel: The name of the HDL toplevel module. |
| 333 |
always: Always run the build step. |
| 334 |
build_dir: Directory to run the build step in. |
| 335 |
clean: Delete *build_dir* before building. |
| 336 |
verbose: Enable verbose messages. |
| 337 |
timescale: Tuple containing time unit and time precision for simulation. |
| 338 |
waves: Record signal traces. Overridden by the :envvar:`WAVES` environment variable. |
| 339 |
log_file: File to write the build log to. |
| 340 |
|
| 341 |
.. deprecated:: 2.0 |
| 342 |
|
| 343 |
Uses of the *verilog_sources* and *vhdl_sources* parameters should be replaced with the language-agnostic *sources* argument. |
| 344 |
""" |
| 345 |
|
| 346 |
self.clean: bool = clean |
| 347 |
self.build_dir = get_abs_path(build_dir) |
| 348 |
if self.clean: |
| 349 |
self.rm_build_folder(self.build_dir) |
| 350 |
self.build_dir.mkdir(parents=True, exist_ok=True) |
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
self.hdl_library: str = hdl_library |
| 357 |
if verilog_sources: |
| 358 |
warnings.warn( |
| 359 |
"Simulator.build *verilog_sources* parameter is deprecated. Use the language-agnostic *sources* parameter instead.", |
| 360 |
DeprecationWarning, |
| 361 |
stacklevel=2, |
| 362 |
) |
| 363 |
self._set_verilog_sources(verilog_sources) |
| 364 |
if vhdl_sources: |
| 365 |
warnings.warn( |
| 366 |
"Simulator.build *vhdl_sources* parameter is deprecated. Use the language-agnostic *sources* parameter instead.", |
| 367 |
DeprecationWarning, |
| 368 |
stacklevel=2, |
| 369 |
) |
| 370 |
self._set_vhdl_sources(vhdl_sources) |
| 371 |
self._set_sources(sources) |
| 372 |
self.includes: List[Path] = [ |
| 373 |
get_abs_path(include_dir) for include_dir in includes |
| 374 |
] |
| 375 |
self.defines = dict(defines) |
| 376 |
self.parameters = dict(parameters) |
| 377 |
self._set_build_args(build_args) |
| 378 |
self.always: bool = always |
| 379 |
self.hdl_toplevel: Optional[str] = hdl_toplevel |
| 380 |
self.verbose: bool = verbose |
| 381 |
self.timescale: Optional[Tuple[str, str]] = timescale |
| 382 |
self.log_file: Optional[PathLike] = log_file |
| 383 |
|
| 384 |
self.waves = bool(os.getenv("WAVES", waves)) |
| 385 |
|
| 386 |
self.env.update(os.environ) |
| 387 |
|
| 388 |
cmds: Sequence[_Command] = self._build_command() |
| 389 |
self._execute(cmds, cwd=self.build_dir) |
| 390 |
|
| 391 |
def test( |
| 392 |
self, |
| 393 |
test_module: Union[str, Sequence[str]], |
| 394 |
hdl_toplevel: str, |
| 395 |
hdl_toplevel_library: str = "top", |
| 396 |
hdl_toplevel_lang: Optional[str] = None, |
| 397 |
gpi_interfaces: Optional[List[str]] = None, |
| 398 |
testcase: Optional[Union[str, Sequence[str]]] = None, |
| 399 |
seed: Optional[Union[str, int]] = None, |
| 400 |
elab_args: Sequence[str] = [], |
| 401 |
test_args: Sequence[str] = [], |
| 402 |
plusargs: Sequence[str] = [], |
| 403 |
extra_env: Mapping[str, str] = {}, |
| 404 |
waves: bool = False, |
| 405 |
gui: bool = False, |
| 406 |
parameters: Optional[Mapping[str, object]] = None, |
| 407 |
build_dir: Optional[PathLike] = None, |
| 408 |
test_dir: Optional[PathLike] = None, |
| 409 |
results_xml: Optional[str] = None, |
| 410 |
pre_cmd: Optional[List[str]] = None, |
| 411 |
verbose: bool = False, |
| 412 |
timescale: Optional[Tuple[str, str]] = None, |
| 413 |
log_file: Optional[PathLike] = None, |
| 414 |
test_filter: Optional[str] = None, |
| 415 |
) -> Path: |
| 416 |
"""Run the tests. |
| 417 |
|
| 418 |
Args: |
| 419 |
test_module: Name(s) of the Python module(s) containing the tests to run. |
| 420 |
Can be a comma-separated list. |
| 421 |
hdl_toplevel: Name of the HDL toplevel module. |
| 422 |
hdl_toplevel_library: The library name for HDL toplevel module. |
| 423 |
hdl_toplevel_lang: Language of the HDL toplevel module. |
| 424 |
gpi_interfaces: List of GPI interfaces to use, with the first one being the entry point. |
| 425 |
testcase: Name(s) of a specific testcase(s) to run. |
| 426 |
If not set, run all testcases found in *test_module*. |
| 427 |
Can be a comma-separated list. |
| 428 |
seed: A specific random seed to use. |
| 429 |
elab_args: A list of elaboration arguments for the simulator. |
| 430 |
test_args: A list of extra arguments for the simulator. |
| 431 |
plusargs: 'plusargs' to set for the simulator. |
| 432 |
extra_env: Extra environment variables to set. |
| 433 |
waves: Record signal traces. Overridden by the :envvar:`WAVES` environment variable. |
| 434 |
gui: Run with simulator GUI. Overridden by the :envvar:`GUI` environment variable. |
| 435 |
parameters: Verilog parameters or VHDL generics. |
| 436 |
build_dir: Directory the build step has been run in. |
| 437 |
test_dir: Directory to run the tests in. |
| 438 |
results_xml: Name of xUnit XML file to store test results in. |
| 439 |
If an absolute path is provided it will be used as-is, |
| 440 |
:file:`{build_dir}/results.xml` otherwise. |
| 441 |
This argument should not be set when run with ``pytest``. |
| 442 |
verbose: Enable verbose messages. |
| 443 |
pre_cmd: Commands to run before simulation begins. |
| 444 |
Typically Tcl commands for simulators that support them. |
| 445 |
timescale: Tuple containing time unit and time precision for simulation. |
| 446 |
log_file: File to write the test log to. |
| 447 |
test_filter: Regular expression which matches test names. |
| 448 |
Only matched tests are run if this argument if given. |
| 449 |
|
| 450 |
Returns: |
| 451 |
The absolute location of the results XML file which can be |
| 452 |
defined by the *results_xml* argument. |
| 453 |
""" |
| 454 |
|
| 455 |
__tracebackhide__ = True |
| 456 |
|
| 457 |
if build_dir is not None: |
| 458 |
self.build_dir = get_abs_path(build_dir) |
| 459 |
|
| 460 |
if parameters is not None: |
| 461 |
self.parameters = dict(parameters) |
| 462 |
|
| 463 |
if test_dir is None: |
| 464 |
self.test_dir = self.build_dir |
| 465 |
else: |
| 466 |
self.test_dir = get_abs_path(test_dir) |
| 467 |
self.test_dir.mkdir(parents=True, exist_ok=True) |
| 468 |
|
| 469 |
if isinstance(test_module, str): |
| 470 |
self.test_module = test_module |
| 471 |
else: |
| 472 |
self.test_module = ",".join(test_module) |
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
self.sim_hdl_toplevel = hdl_toplevel |
| 479 |
self.hdl_toplevel_library: str = hdl_toplevel_library |
| 480 |
self.hdl_toplevel_lang = self._check_hdl_toplevel_lang(hdl_toplevel_lang) |
| 481 |
if gpi_interfaces: |
| 482 |
self.gpi_interfaces = gpi_interfaces |
| 483 |
else: |
| 484 |
self.gpi_interfaces = [] |
| 485 |
for gpi_if in self.supported_gpi_interfaces.values(): |
| 486 |
self.gpi_interfaces.append(gpi_if[0]) |
| 487 |
|
| 488 |
self.pre_cmd = pre_cmd |
| 489 |
|
| 490 |
self.elab_args = list(elab_args) |
| 491 |
self.test_args = list(test_args) |
| 492 |
self.plusargs = list(plusargs) |
| 493 |
self.env = dict(extra_env) |
| 494 |
|
| 495 |
if testcase is not None: |
| 496 |
if isinstance(testcase, str): |
| 497 |
self.env["COCOTB_TESTCASE"] = testcase |
| 498 |
else: |
| 499 |
self.env["COCOTB_TESTCASE"] = ",".join(testcase) |
| 500 |
|
| 501 |
if test_filter is not None: |
| 502 |
self.env["COCOTB_TEST_FILTER"] = test_filter |
| 503 |
|
| 504 |
if seed is not None: |
| 505 |
self.env["COCOTB_RANDOM_SEED"] = str(seed) |
| 506 |
|
| 507 |
self.log_file = log_file |
| 508 |
self.waves = bool(int(os.getenv("WAVES", waves))) |
| 509 |
self.gui = bool(int(os.getenv("GUI", gui))) |
| 510 |
self.timescale = timescale |
| 511 |
|
| 512 |
if verbose is not None: |
| 513 |
self.verbose = verbose |
| 514 |
|
| 515 |
|
| 516 |
pytest_current_test = os.getenv("PYTEST_CURRENT_TEST", None) |
| 517 |
|
| 518 |
if pytest_current_test is not None: |
| 519 |
self.current_test_name = pytest_current_test.split(":")[-1].split(" ")[0] |
| 520 |
else: |
| 521 |
self.current_test_name = "test" |
| 522 |
|
| 523 |
results_xml_path: Union[None, Path] = ( |
| 524 |
Path(results_xml) if results_xml is not None else None |
| 525 |
) |
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
if results_xml_path is not None and results_xml_path.is_absolute(): |
| 533 |
results_xml_file = results_xml_path |
| 534 |
elif pytest_current_test is not None: |
| 535 |
if results_xml_path is not None: |
| 536 |
raise NotImplementedError( |
| 537 |
"Relative result_xml paths aren't supported when using pytest" |
| 538 |
) |
| 539 |
results_xml_file = self.test_dir / f"{self.current_test_name}.result.xml" |
| 540 |
elif results_xml_path is not None: |
| 541 |
results_xml_file = self.test_dir / results_xml_path |
| 542 |
else: |
| 543 |
results_xml_file = self.test_dir / "results.xml" |
| 544 |
|
| 545 |
with suppress(OSError): |
| 546 |
results_xml_file.unlink() |
| 547 |
|
| 548 |
|
| 549 |
self._set_env() |
| 550 |
self.env["COCOTB_RESULTS_FILE"] = str(results_xml_file) |
| 551 |
|
| 552 |
cmds: Sequence[_Command] = self._test_command() |
| 553 |
simulator_exit_code: int = 0 |
| 554 |
try: |
| 555 |
self._execute(cmds, cwd=self.test_dir) |
| 556 |
except subprocess.CalledProcessError as e: |
| 557 |
|
| 558 |
self.log.error("Simulation failed: %d", e.returncode) |
| 559 |
simulator_exit_code = e.returncode |
| 560 |
|
| 561 |
|
| 562 |
|
| 563 |
|
| 564 |
if pytest_current_test: |
| 565 |
try: |
| 566 |
(num_tests, num_failed) = get_results(results_xml_file) |
| 567 |
except RuntimeError as e: |
| 568 |
self.log.error("%s", e.args[0]) |
| 569 |
sys.exit(simulator_exit_code) |
| 570 |
else: |
| 571 |
if num_failed: |
| 572 |
self.log.error( |
| 573 |
"ERROR: Failed %d of %d tests.", num_failed, num_tests |
| 574 |
) |
| 575 |
sys.exit(1 if simulator_exit_code == 0 else simulator_exit_code) |
| 576 |
|
| 577 |
if simulator_exit_code != 0: |
| 578 |
sys.exit(simulator_exit_code) |
| 579 |
|
| 580 |
if pytest_current_test and self._use_external_viewer() and self.gui: |
| 581 |
viewer = os.getenv("COCOTB_WAVEFORM_VIEWER") |
| 582 |
if viewer is not None: |
| 583 |
viewer_path = shutil.which(viewer) |
| 584 |
if viewer_path is None: |
| 585 |
raise ValueError(f"Cannot find {viewer} in the system path") |
| 586 |
else: |
| 587 |
viewer_path = shutil.which("surfer") |
| 588 |
if viewer_path is None: |
| 589 |
viewer_path = shutil.which("gtkwave") |
| 590 |
if viewer_path is None: |
| 591 |
raise SystemError( |
| 592 |
"Cannot find any viewer (surfer or gtkwave) in the system path" |
| 593 |
) |
| 594 |
|
| 595 |
subprocess.run( |
| 596 |
[f"{viewer_path} {self._waves_file()}"], |
| 597 |
cwd=self.test_dir, |
| 598 |
check=True, |
| 599 |
shell=True, |
| 600 |
) |
| 601 |
|
| 602 |
self.log.info("Results file: %s", results_xml_file) |
| 603 |
return results_xml_file |
| 604 |
|
| 605 |
@abstractmethod |
| 606 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 607 |
"""Return simulator-specific formatted option strings with *includes* directories.""" |
| 608 |
|
| 609 |
@abstractmethod |
| 610 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 611 |
"""Return simulator-specific formatted option strings with *defines* macros.""" |
| 612 |
|
| 613 |
@abstractmethod |
| 614 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 615 |
"""Return simulator-specific formatted option strings with *parameters*/generics.""" |
| 616 |
|
| 617 |
def _execute(self, cmds: Sequence[_Command], cwd: PathLike) -> None: |
| 618 |
__tracebackhide__ = True |
| 619 |
|
| 620 |
if self.log_file is None: |
| 621 |
self._execute_cmds(cmds, cwd) |
| 622 |
else: |
| 623 |
with open(self.log_file, "w") as f: |
| 624 |
self._execute_cmds(cmds, cwd, f) |
| 625 |
|
| 626 |
def _execute_cmds( |
| 627 |
self, cmds: Sequence[_Command], cwd: PathLike, stdout: Optional[TextIO] = None |
| 628 |
) -> None: |
| 629 |
__tracebackhide__ = True |
| 630 |
|
| 631 |
for cmd in cmds: |
| 632 |
self.log.info("Running command %s in directory %s", _shlex_join(cmd), cwd) |
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
stderr = None if stdout is None else subprocess.STDOUT |
| 638 |
subprocess.run( |
| 639 |
cmd, cwd=cwd, env=self.env, check=True, stdout=stdout, stderr=stderr |
| 640 |
) |
| 641 |
|
| 642 |
def rm_build_folder(self, build_dir: Path) -> None: |
| 643 |
if build_dir.is_dir(): |
| 644 |
self.log.info("Removing: %s", build_dir) |
| 645 |
shutil.rmtree(build_dir, ignore_errors=True) |
| 646 |
|
| 647 |
@property |
| 648 |
def verilog_sources(self) -> List[Path]: |
| 649 |
return [source.value for source in self._verilog_sources] |
| 650 |
|
| 651 |
@verilog_sources.setter |
| 652 |
def verilog_sources(self, value: List[Path]) -> None: |
| 653 |
self._set_verilog_sources(value) |
| 654 |
|
| 655 |
def _set_verilog_sources( |
| 656 |
self, sources: Sequence[Union[PathLike, Verilog, VerilatorControlFile]] |
| 657 |
) -> None: |
| 658 |
verilog_sources: List[_ValueAndTag] = [] |
| 659 |
for source in sources: |
| 660 |
if isinstance(source, _Tag): |
| 661 |
if isinstance(source, (Verilog, VerilatorControlFile)): |
| 662 |
abs_path = get_abs_path(source.value) |
| 663 |
verilog_sources.append(_ValueAndTag(abs_path, type(source))) |
| 664 |
else: |
| 665 |
raise ValueError(f"Unsupported file type: {source}") |
| 666 |
else: |
| 667 |
tag = _determine_file_type(source) |
| 668 |
abs_path = get_abs_path(source) |
| 669 |
verilog_sources.append(_ValueAndTag(abs_path, tag)) |
| 670 |
self._verilog_sources = verilog_sources |
| 671 |
|
| 672 |
@property |
| 673 |
def vhdl_sources(self) -> List[Path]: |
| 674 |
return [source.value for source in self._vhdl_sources] |
| 675 |
|
| 676 |
@vhdl_sources.setter |
| 677 |
def vhdl_sources(self, value: List[Path]) -> None: |
| 678 |
self._set_vhdl_sources(value) |
| 679 |
|
| 680 |
def _set_vhdl_sources(self, sources: Sequence[Union[PathLike, VHDL]]) -> None: |
| 681 |
vhdl_sources: List[_ValueAndTag] = [] |
| 682 |
for source in sources: |
| 683 |
if isinstance(source, _Tag): |
| 684 |
if isinstance(source, VHDL): |
| 685 |
abs_path = get_abs_path(source.value) |
| 686 |
vhdl_sources.append(_ValueAndTag(abs_path, type(source))) |
| 687 |
else: |
| 688 |
raise ValueError(f"Unsupported file type: {source}") |
| 689 |
else: |
| 690 |
tag = _determine_file_type(source) |
| 691 |
abs_path = get_abs_path(source) |
| 692 |
vhdl_sources.append(_ValueAndTag(abs_path, tag)) |
| 693 |
self._vhdl_sources = vhdl_sources |
| 694 |
|
| 695 |
@property |
| 696 |
def sources(self) -> List[Path]: |
| 697 |
return [source.value for source in self._sources] |
| 698 |
|
| 699 |
@sources.setter |
| 700 |
def sources(self, value: List[Path]) -> None: |
| 701 |
self._set_sources(value) |
| 702 |
|
| 703 |
def _set_sources( |
| 704 |
self, sources: Sequence[Union[PathLike, Verilog, VHDL, VerilatorControlFile]] |
| 705 |
) -> None: |
| 706 |
sources_: List[_ValueAndTag] = [] |
| 707 |
for source in sources: |
| 708 |
if isinstance(source, _Tag): |
| 709 |
if isinstance(source, (Verilog, VHDL, VerilatorControlFile)): |
| 710 |
abs_path = get_abs_path(source.value) |
| 711 |
sources_.append(_ValueAndTag(abs_path, type(source))) |
| 712 |
else: |
| 713 |
raise ValueError(f"Unsupported file type: {source}") |
| 714 |
else: |
| 715 |
tag = _determine_file_type(source) |
| 716 |
abs_path = get_abs_path(source) |
| 717 |
sources_.append(_ValueAndTag(abs_path, tag)) |
| 718 |
self._sources = sources_ |
| 719 |
|
| 720 |
@property |
| 721 |
def build_args(self) -> List[str]: |
| 722 |
return [arg.value for arg in self._build_args] |
| 723 |
|
| 724 |
@build_args.setter |
| 725 |
def build_args(self, value: List[str]) -> None: |
| 726 |
self._set_build_args(value) |
| 727 |
|
| 728 |
def _set_build_args(self, build_args: Sequence[Union[str, Verilog, VHDL]]) -> None: |
| 729 |
build_args_: List[_ValueAndOptionalTag] = [] |
| 730 |
for build_arg in build_args: |
| 731 |
if isinstance(build_arg, _Tag): |
| 732 |
if isinstance(build_arg, (Verilog, VHDL)): |
| 733 |
build_args_.append( |
| 734 |
_ValueAndOptionalTag(build_arg.value, type(build_arg)) |
| 735 |
) |
| 736 |
else: |
| 737 |
raise ValueError(f"Unsupported tag type: {build_arg}") |
| 738 |
else: |
| 739 |
build_args_.append(_ValueAndOptionalTag(build_arg, None)) |
| 740 |
self._build_args = build_args_ |
| 741 |
|
| 742 |
|
| 743 |
def outdated(output: Path, dependencies: Iterable[Path]) -> bool: |
| 744 |
"""Return ``True`` if any source files in *dependencies* are newer than the *output* directory. |
| 745 |
|
| 746 |
Returns: |
| 747 |
``True`` if any source files are newer, ``False`` otherwise. |
| 748 |
""" |
| 749 |
|
| 750 |
if not output.is_file(): |
| 751 |
return True |
| 752 |
|
| 753 |
output_mtime = output.stat().st_mtime |
| 754 |
|
| 755 |
dep_mtime = 0.0 |
| 756 |
for dependency in dependencies: |
| 757 |
mtime = dependency.stat().st_mtime |
| 758 |
dep_mtime = max(mtime, dep_mtime) |
| 759 |
|
| 760 |
return dep_mtime > output_mtime |
| 761 |
|
| 762 |
|
| 763 |
def get_abs_path(path: PathLike) -> Path: |
| 764 |
"""Return *path* in absolute form.""" |
| 765 |
|
| 766 |
path = Path(path) |
| 767 |
if path.is_absolute(): |
| 768 |
return path.resolve() |
| 769 |
else: |
| 770 |
return Path(Path.cwd() / path).resolve() |
| 771 |
|
| 772 |
|
| 773 |
class Icarus(Runner): |
| 774 |
"""Implementation of :class:`Runner` for Icarus Verilog. |
| 775 |
|
| 776 |
.. admonition:: Simulator-specific Usage |
| 777 |
|
| 778 |
* ``hdl_toplevel`` argument to :meth:`.build` is *required*. |
| 779 |
* ``waves=True`` *must* be given to :meth:`.build` if either ``waves`` or ``gui`` are to be used during :meth:`.test`. |
| 780 |
* ``timescale`` argument to :meth:`.build` must be given to support dumping the command file. |
| 781 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 782 |
""" |
| 783 |
|
| 784 |
supported_gpi_interfaces = {"verilog": ["vpi"]} |
| 785 |
|
| 786 |
def _simulator_in_path(self) -> None: |
| 787 |
if shutil.which("iverilog") is None: |
| 788 |
raise SystemExit("ERROR: iverilog executable not found!") |
| 789 |
|
| 790 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 791 |
return [f"-I{include}" for include in includes] |
| 792 |
|
| 793 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 794 |
return [f"-D{name}={_as_sv_literal(value)}" for name, value in defines.items()] |
| 795 |
|
| 796 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 797 |
return [ |
| 798 |
f"-P{self.hdl_toplevel}.{name}={value}" |
| 799 |
for name, value in parameters.items() |
| 800 |
] |
| 801 |
|
| 802 |
def _use_external_viewer(self) -> bool: |
| 803 |
return True |
| 804 |
|
| 805 |
def _waves_file(self) -> Optional[str]: |
| 806 |
return f"{self.hdl_toplevel}.fst" |
| 807 |
|
| 808 |
def _create_cmd_file(self) -> None: |
| 809 |
assert self.timescale is not None |
| 810 |
with open(self.cmds_file, "w") as f: |
| 811 |
f.write("+timescale+{}/{}\n".format(*self.timescale)) |
| 812 |
|
| 813 |
def _create_iverilog_dump_file(self) -> None: |
| 814 |
dumpfile_path = _as_sv_literal(str(self.build_dir / f"{self.hdl_toplevel}.fst")) |
| 815 |
with open(self.iverilog_dump_file, "w") as f: |
| 816 |
f.write("module cocotb_iverilog_dump();\n") |
| 817 |
f.write("initial begin\n") |
| 818 |
f.write(" string dumpfile_path;") |
| 819 |
f.write( |
| 820 |
' if ($value$plusargs("dumpfile_path=%s", dumpfile_path)) begin\n' |
| 821 |
) |
| 822 |
f.write(" $dumpfile(dumpfile_path);\n") |
| 823 |
f.write(" end else begin\n") |
| 824 |
f.write(f" $dumpfile({dumpfile_path});\n") |
| 825 |
f.write(" end\n") |
| 826 |
f.write(f" $dumpvars(0, {self.hdl_toplevel});\n") |
| 827 |
f.write("end\n") |
| 828 |
f.write("endmodule\n") |
| 829 |
|
| 830 |
@property |
| 831 |
def sim_file(self) -> Path: |
| 832 |
return self.build_dir / "sim.vvp" |
| 833 |
|
| 834 |
@property |
| 835 |
def iverilog_dump_file(self) -> Path: |
| 836 |
return self.build_dir / "cocotb_iverilog_dump.v" |
| 837 |
|
| 838 |
@property |
| 839 |
def cmds_file(self) -> Path: |
| 840 |
return self.build_dir / "cmds.f" |
| 841 |
|
| 842 |
def _build_command(self) -> List[_Command]: |
| 843 |
if self.hdl_toplevel is None: |
| 844 |
raise ValueError("hdl_toplevel argument is required for all Icarus builds") |
| 845 |
|
| 846 |
sources = self._sources + self._verilog_sources |
| 847 |
|
| 848 |
for source in sources: |
| 849 |
if source.tag is not Verilog: |
| 850 |
raise ValueError( |
| 851 |
f"{type(self).__qualname__} only supports Verilog. {str(source.value)!r} cannot be compiled." |
| 852 |
) |
| 853 |
|
| 854 |
for arg in self._build_args: |
| 855 |
if arg.tag not in (Verilog, None): |
| 856 |
raise ValueError( |
| 857 |
f"{type(self).__qualname__} only supports Verilog. build_args {arg.value!r} cannot be applied." |
| 858 |
) |
| 859 |
|
| 860 |
build_args = [arg.value for arg in self._build_args] |
| 861 |
if self.waves: |
| 862 |
self._create_iverilog_dump_file() |
| 863 |
build_args += ["-s", "cocotb_iverilog_dump"] |
| 864 |
|
| 865 |
if self.timescale is not None: |
| 866 |
self._create_cmd_file() |
| 867 |
build_args += ["-f", str(self.cmds_file)] |
| 868 |
|
| 869 |
cmds: list[_Command] = [] |
| 870 |
if outdated(self.sim_file, (source.value for source in sources)) or self.always: |
| 871 |
cmds = [ |
| 872 |
[ |
| 873 |
"iverilog", |
| 874 |
"-o", |
| 875 |
str(self.sim_file), |
| 876 |
"-s", |
| 877 |
self.hdl_toplevel, |
| 878 |
"-g2012", |
| 879 |
] |
| 880 |
+ self._get_define_options(self.defines) |
| 881 |
+ self._get_include_options(self.includes) |
| 882 |
+ self._get_parameter_options(self.parameters) |
| 883 |
+ [arg for arg in build_args if type(arg) in (str, Verilog)] |
| 884 |
+ [str(source_file.value) for source_file in sources] |
| 885 |
+ [ |
| 886 |
str(source_file) |
| 887 |
for source_file in [self.iverilog_dump_file] |
| 888 |
if self.waves |
| 889 |
] |
| 890 |
] |
| 891 |
|
| 892 |
else: |
| 893 |
self.log.warning("Skipping compilation of %s", self.sim_file) |
| 894 |
|
| 895 |
return cmds |
| 896 |
|
| 897 |
def _test_command(self) -> List[_Command]: |
| 898 |
if self.pre_cmd is not None: |
| 899 |
raise RuntimeError("pre_cmd is not implemented for Icarus Verilog.") |
| 900 |
|
| 901 |
plusargs = self.plusargs |
| 902 |
if self.waves or self.gui: |
| 903 |
plusargs += ["-fst"] |
| 904 |
else: |
| 905 |
|
| 906 |
plusargs += ["-none"] |
| 907 |
|
| 908 |
return [ |
| 909 |
[ |
| 910 |
"vvp", |
| 911 |
"-M", |
| 912 |
str(cocotb_tools.config.libs_dir), |
| 913 |
"-m", |
| 914 |
cocotb_tools.config.lib_name("vpi", "icarus"), |
| 915 |
*self.test_args, |
| 916 |
str(self.sim_file), |
| 917 |
*plusargs, |
| 918 |
] |
| 919 |
] |
| 920 |
|
| 921 |
|
| 922 |
class Questa(Runner): |
| 923 |
"""Implementation of :class:`Runner` for Siemens Questa. |
| 924 |
|
| 925 |
.. admonition:: Simulator-specific Usage |
| 926 |
|
| 927 |
* Does not support the ``timescale`` argument to :meth:`.build` or :meth:`.test`. |
| 928 |
""" |
| 929 |
|
| 930 |
supported_gpi_interfaces = {"verilog": ["vpi"], "vhdl": ["fli", "vhpi"]} |
| 931 |
|
| 932 |
def _simulator_in_path(self) -> None: |
| 933 |
if shutil.which("vsim") is None: |
| 934 |
raise SystemExit("ERROR: vsim executable not found!") |
| 935 |
|
| 936 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 937 |
return [f"+incdir+{_as_tcl_value(str(include))}" for include in includes] |
| 938 |
|
| 939 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 940 |
return [ |
| 941 |
f"+define+{name}={_as_sv_literal(value)}" for name, value in defines.items() |
| 942 |
] |
| 943 |
|
| 944 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 945 |
return [f"-g{name}={value}" for name, value in parameters.items()] |
| 946 |
|
| 947 |
def _build_command(self) -> List[_Command]: |
| 948 |
cmds = [] |
| 949 |
|
| 950 |
cmds.append(["vlib", _as_tcl_value(self.hdl_library)]) |
| 951 |
|
| 952 |
vhdl_args = [ |
| 953 |
_as_tcl_value(arg.value) |
| 954 |
for arg in self._build_args |
| 955 |
if arg.tag in (VHDL, None) |
| 956 |
] |
| 957 |
verilog_args = [ |
| 958 |
_as_tcl_value(arg.value) |
| 959 |
for arg in self._build_args |
| 960 |
if arg.tag in (Verilog, None) |
| 961 |
] |
| 962 |
hdl_library = _as_tcl_value(self.hdl_library) |
| 963 |
defines = self._get_define_options(self.defines) |
| 964 |
includes = self._get_include_options(self.includes) |
| 965 |
|
| 966 |
for source in chain(self._sources, self._vhdl_sources, self._verilog_sources): |
| 967 |
if source.tag is VHDL: |
| 968 |
cmds.append( |
| 969 |
[ |
| 970 |
"vcom", |
| 971 |
"-work", |
| 972 |
hdl_library, |
| 973 |
*vhdl_args, |
| 974 |
_as_tcl_value(str(source.value)), |
| 975 |
] |
| 976 |
) |
| 977 |
elif source.tag is Verilog: |
| 978 |
cmds.append( |
| 979 |
[ |
| 980 |
"vlog", |
| 981 |
*([] if self.always else ["-incr"]), |
| 982 |
"-work", |
| 983 |
hdl_library, |
| 984 |
"-sv", |
| 985 |
*defines, |
| 986 |
*includes, |
| 987 |
*verilog_args, |
| 988 |
_as_tcl_value(str(source.value)), |
| 989 |
] |
| 990 |
) |
| 991 |
else: |
| 992 |
raise ValueError(f"Unsupported file type: {source.value}") |
| 993 |
|
| 994 |
return cmds |
| 995 |
|
| 996 |
def _test_command(self) -> List[_Command]: |
| 997 |
cmds = [] |
| 998 |
|
| 999 |
if self.pre_cmd is not None: |
| 1000 |
pre_cmd = ["-do", *self.pre_cmd] |
| 1001 |
else: |
| 1002 |
pre_cmd = [] |
| 1003 |
|
| 1004 |
do_script = "" |
| 1005 |
if self.waves: |
| 1006 |
do_script += "log -recursive /*;" |
| 1007 |
|
| 1008 |
if not self.gui: |
| 1009 |
do_script += "run -all; quit" |
| 1010 |
|
| 1011 |
gpi_if_entry = self.gpi_interfaces[0] |
| 1012 |
if gpi_if_entry == "fli": |
| 1013 |
lib_opts = [ |
| 1014 |
"-foreign", |
| 1015 |
"cocotb_init " |
| 1016 |
+ _as_tcl_value( |
| 1017 |
cocotb_tools.config.lib_name_path("fli", "questa").as_posix() |
| 1018 |
), |
| 1019 |
] |
| 1020 |
elif gpi_if_entry == "vhpi": |
| 1021 |
lib_opts = ["-voptargs=-access=rw+/."] |
| 1022 |
lib_opts += [ |
| 1023 |
"-foreign", |
| 1024 |
"vhpi_startup_routines_bootstrap " |
| 1025 |
+ _as_tcl_value( |
| 1026 |
cocotb_tools.config.lib_name_path("vhpi", "questa").as_posix() |
| 1027 |
), |
| 1028 |
] |
| 1029 |
else: |
| 1030 |
lib_opts = [ |
| 1031 |
"-pli", |
| 1032 |
_as_tcl_value( |
| 1033 |
cocotb_tools.config.lib_name_path("vpi", "questa").as_posix() |
| 1034 |
), |
| 1035 |
] |
| 1036 |
|
| 1037 |
cmds.append( |
| 1038 |
["vsim"] |
| 1039 |
+ ["-gui" if self.gui else "-c"] |
| 1040 |
+ ["-onfinish", "stop" if self.gui else "exit"] |
| 1041 |
+ lib_opts |
| 1042 |
+ [_as_tcl_value(v) for v in self.test_args] |
| 1043 |
+ [_as_tcl_value(v) for v in self._get_parameter_options(self.parameters)] |
| 1044 |
+ [_as_tcl_value(f"{self.hdl_toplevel_library}.{self.sim_hdl_toplevel}")] |
| 1045 |
+ [_as_tcl_value(v) for v in self.plusargs] |
| 1046 |
+ pre_cmd |
| 1047 |
+ ["-do", do_script] |
| 1048 |
) |
| 1049 |
|
| 1050 |
gpi_extra_list = [] |
| 1051 |
for gpi_if in self.gpi_interfaces[1:]: |
| 1052 |
gpi_if_lib_path = cocotb_tools.config.lib_name_path(gpi_if, "questa") |
| 1053 |
if gpi_if_lib_path.is_file(): |
| 1054 |
gpi_extra_list.append( |
| 1055 |
gpi_if_lib_path.as_posix() + f":cocotb{gpi_if}_entry_point" |
| 1056 |
) |
| 1057 |
else: |
| 1058 |
raise RuntimeError(f"{gpi_if_lib_path} library not found.") |
| 1059 |
self.env["GPI_EXTRA"] = ",".join(gpi_extra_list) |
| 1060 |
|
| 1061 |
return cmds |
| 1062 |
|
| 1063 |
|
| 1064 |
class Ghdl(Runner): |
| 1065 |
"""Implementation of :class:`Runner` for GHDL. |
| 1066 |
|
| 1067 |
.. admonition:: Simulator-specific Usage |
| 1068 |
|
| 1069 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1070 |
""" |
| 1071 |
|
| 1072 |
supported_gpi_interfaces = {"vhdl": ["vpi"]} |
| 1073 |
|
| 1074 |
def _set_env(self) -> None: |
| 1075 |
super()._set_env() |
| 1076 |
if "COCOTB_TRUST_INERTIAL_WRITES" not in self.env: |
| 1077 |
self.env["COCOTB_TRUST_INERTIAL_WRITES"] = "1" |
| 1078 |
|
| 1079 |
def _simulator_in_path(self) -> None: |
| 1080 |
if shutil.which("ghdl") is None: |
| 1081 |
raise SystemExit("ERROR: ghdl executable not found!") |
| 1082 |
|
| 1083 |
def _is_mcode_backend(self) -> bool: |
| 1084 |
"""Is GHDL using the mcode backend?""" |
| 1085 |
result = subprocess.run( |
| 1086 |
["ghdl", "--version"], |
| 1087 |
check=True, |
| 1088 |
universal_newlines=True, |
| 1089 |
stdout=subprocess.PIPE, |
| 1090 |
stderr=subprocess.STDOUT, |
| 1091 |
) |
| 1092 |
return "mcode" in result.stdout |
| 1093 |
|
| 1094 |
def _use_external_viewer(self) -> bool: |
| 1095 |
return True |
| 1096 |
|
| 1097 |
def _waves_file(self) -> Optional[str]: |
| 1098 |
return f"{self.hdl_toplevel}.ghw" |
| 1099 |
|
| 1100 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1101 |
raise RuntimeError |
| 1102 |
|
| 1103 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1104 |
raise RuntimeError |
| 1105 |
|
| 1106 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1107 |
return [f"-g{name}={value}" for name, value in parameters.items()] |
| 1108 |
|
| 1109 |
def _build_command(self) -> List[_Command]: |
| 1110 |
sources = self._sources + self._vhdl_sources |
| 1111 |
|
| 1112 |
for source in sources: |
| 1113 |
if source.tag is not VHDL: |
| 1114 |
raise ValueError( |
| 1115 |
f"{type(self).__qualname__} only supports VHDL. {str(source.value)!r} cannot be compiled." |
| 1116 |
) |
| 1117 |
|
| 1118 |
for arg in self._build_args: |
| 1119 |
if arg.tag not in (VHDL, None): |
| 1120 |
raise ValueError( |
| 1121 |
f"{type(self).__qualname__} only supports VHDL. build_args {arg.value!r} will not be applied." |
| 1122 |
) |
| 1123 |
|
| 1124 |
cmds = [ |
| 1125 |
["ghdl", "-i"] |
| 1126 |
+ [f"--work={self.hdl_library}"] |
| 1127 |
+ [arg.value for arg in self._build_args] |
| 1128 |
+ [str(source.value) for source in sources] |
| 1129 |
] |
| 1130 |
|
| 1131 |
if self.hdl_toplevel is not None: |
| 1132 |
cmds += [ |
| 1133 |
[ |
| 1134 |
"ghdl", |
| 1135 |
"-m", |
| 1136 |
f"--work={self.hdl_library}", |
| 1137 |
*(arg.value for arg in self._build_args), |
| 1138 |
self.hdl_toplevel, |
| 1139 |
] |
| 1140 |
] |
| 1141 |
|
| 1142 |
return cmds |
| 1143 |
|
| 1144 |
def _test_command(self) -> List[_Command]: |
| 1145 |
if self.pre_cmd is not None: |
| 1146 |
raise RuntimeError("pre_cmd is not implemented for GHDL.") |
| 1147 |
|
| 1148 |
ghdl_run_args = self.test_args |
| 1149 |
|
| 1150 |
if self._is_mcode_backend() and self.timescale: |
| 1151 |
_, precision = self.timescale |
| 1152 |
|
| 1153 |
|
| 1154 |
|
| 1155 |
|
| 1156 |
|
| 1157 |
|
| 1158 |
if precision == "1fs": |
| 1159 |
ghdl_time_resolution = "fs" |
| 1160 |
elif precision == "1ps": |
| 1161 |
ghdl_time_resolution = "ps" |
| 1162 |
elif precision == "1ns": |
| 1163 |
ghdl_time_resolution = "ns" |
| 1164 |
elif precision == "1us": |
| 1165 |
ghdl_time_resolution = "us" |
| 1166 |
elif precision == "1ms": |
| 1167 |
ghdl_time_resolution = "ms" |
| 1168 |
elif precision == "1s": |
| 1169 |
ghdl_time_resolution = "sec" |
| 1170 |
else: |
| 1171 |
raise ValueError( |
| 1172 |
"GHDL only supports the following precisions in timescale: 1fs, 1ps, 1us, 1ms, 1s" |
| 1173 |
) |
| 1174 |
|
| 1175 |
ghdl_run_args.append(f"--time-resolution={ghdl_time_resolution}") |
| 1176 |
|
| 1177 |
cmds = [ |
| 1178 |
["ghdl", "-r"] |
| 1179 |
+ [f"--work={self.hdl_toplevel_library}"] |
| 1180 |
+ ghdl_run_args |
| 1181 |
+ [self.sim_hdl_toplevel] |
| 1182 |
+ ["--vpi=" + cocotb_tools.config.lib_name_path("vpi", "ghdl").as_posix()] |
| 1183 |
+ self.plusargs |
| 1184 |
+ self._get_parameter_options(self.parameters) |
| 1185 |
+ ([f"--wave={self._waves_file()}"] if self.waves or self.gui else []) |
| 1186 |
] |
| 1187 |
|
| 1188 |
return cmds |
| 1189 |
|
| 1190 |
|
| 1191 |
class Nvc(Runner): |
| 1192 |
"""Implementation of :class:`Runner` for NVC. |
| 1193 |
|
| 1194 |
.. admonition:: Simulator-specific Usage |
| 1195 |
|
| 1196 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1197 |
* Does not support the ``timescale`` argument to :meth:`.build` or :meth:`.test`. |
| 1198 |
""" |
| 1199 |
|
| 1200 |
supported_gpi_interfaces = {"vhdl": ["vhpi"]} |
| 1201 |
|
| 1202 |
def __init__(self) -> None: |
| 1203 |
super().__init__() |
| 1204 |
|
| 1205 |
version_str = subprocess.run( |
| 1206 |
["nvc", "--version"], |
| 1207 |
check=True, |
| 1208 |
universal_newlines=True, |
| 1209 |
stdout=subprocess.PIPE, |
| 1210 |
).stdout |
| 1211 |
version = NvcVersion.from_commandline(version_str) |
| 1212 |
if version > NvcVersion("1.16"): |
| 1213 |
self._preserve_case = ["--preserve-case"] |
| 1214 |
else: |
| 1215 |
self._preserve_case = [] |
| 1216 |
|
| 1217 |
def _set_env(self) -> None: |
| 1218 |
super()._set_env() |
| 1219 |
if "COCOTB_TRUST_INERTIAL_WRITES" not in self.env: |
| 1220 |
self.env["COCOTB_TRUST_INERTIAL_WRITES"] = "1" |
| 1221 |
|
| 1222 |
def _simulator_in_path(self) -> None: |
| 1223 |
if shutil.which("nvc") is None: |
| 1224 |
raise SystemExit("ERROR: nvc executable not found!") |
| 1225 |
|
| 1226 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1227 |
raise RuntimeError |
| 1228 |
|
| 1229 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1230 |
raise RuntimeError |
| 1231 |
|
| 1232 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1233 |
return [f"-g{name}={value}" for name, value in parameters.items()] |
| 1234 |
|
| 1235 |
def _use_external_viewer(self) -> bool: |
| 1236 |
return True |
| 1237 |
|
| 1238 |
def _waves_file(self) -> Optional[str]: |
| 1239 |
return f"{self.hdl_toplevel}.fst" |
| 1240 |
|
| 1241 |
def _build_command(self) -> List[_Command]: |
| 1242 |
sources = self._sources + self._vhdl_sources |
| 1243 |
|
| 1244 |
for source in sources: |
| 1245 |
if source.tag is not VHDL: |
| 1246 |
raise ValueError( |
| 1247 |
f"{type(self).__qualname__} only supports VHDL. {str(source.value)!r} cannot be compiled." |
| 1248 |
) |
| 1249 |
|
| 1250 |
for arg in self._build_args: |
| 1251 |
if arg.tag not in (VHDL, None): |
| 1252 |
raise ValueError( |
| 1253 |
f"{type(self).__qualname__} only supports VHDL. build_args {arg.value!r} will not be applied." |
| 1254 |
) |
| 1255 |
|
| 1256 |
cmds = [ |
| 1257 |
[ |
| 1258 |
"nvc", |
| 1259 |
f"--work={self.hdl_library}", |
| 1260 |
"-L", |
| 1261 |
str(get_abs_path(self.build_dir)), |
| 1262 |
] |
| 1263 |
+ [arg.value for arg in self._build_args] |
| 1264 |
+ ["-a"] |
| 1265 |
+ [str(source.value) for source in sources] |
| 1266 |
+ self._preserve_case |
| 1267 |
] |
| 1268 |
|
| 1269 |
return cmds |
| 1270 |
|
| 1271 |
def _test_command(self) -> List[_Command]: |
| 1272 |
work_library = str(get_abs_path(self.build_dir / self.hdl_toplevel_library)) |
| 1273 |
cmds = [ |
| 1274 |
[ |
| 1275 |
"nvc", |
| 1276 |
f"--work={self.hdl_toplevel_library}:{work_library}", |
| 1277 |
"-L", |
| 1278 |
str(get_abs_path(self.build_dir)), |
| 1279 |
] |
| 1280 |
+ [arg.value for arg in self._build_args] |
| 1281 |
+ ["-e", self.sim_hdl_toplevel, "--no-save", "--jit"] |
| 1282 |
+ self.elab_args |
| 1283 |
+ self._get_parameter_options(self.parameters) |
| 1284 |
+ ["-r"] |
| 1285 |
+ self.test_args |
| 1286 |
+ ["--load=" + cocotb_tools.config.lib_name_path("vhpi", "nvc").as_posix()] |
| 1287 |
+ self.plusargs |
| 1288 |
+ ([f"--wave={self._waves_file()}"] if self.waves or self.gui else []) |
| 1289 |
] |
| 1290 |
|
| 1291 |
return cmds |
| 1292 |
|
| 1293 |
|
| 1294 |
class Riviera(Runner): |
| 1295 |
"""Implementation of :class:`Runner` for Aldec Riviera-PRO. |
| 1296 |
|
| 1297 |
.. admonition:: Simulator-specific Usage |
| 1298 |
|
| 1299 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1300 |
* Does not support the ``gui`` argument to :meth:`.test`. |
| 1301 |
* Does not support the ``timescale`` argument to :meth:`.build` or :meth:`.test`. |
| 1302 |
""" |
| 1303 |
|
| 1304 |
supported_gpi_interfaces = {"verilog": ["vpi"], "vhdl": ["vhpi"]} |
| 1305 |
|
| 1306 |
def _simulator_in_path(self) -> None: |
| 1307 |
if shutil.which("vsimsa") is None: |
| 1308 |
raise SystemExit("ERROR: vsimsa executable not found!") |
| 1309 |
|
| 1310 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1311 |
return [f"+incdir+{_as_tcl_value(str(include))}" for include in includes] |
| 1312 |
|
| 1313 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1314 |
return [ |
| 1315 |
f"+define+{name}={self._as_define_value(value)}" |
| 1316 |
for name, value in defines.items() |
| 1317 |
] |
| 1318 |
|
| 1319 |
def _as_define_value(self, value: object) -> str: |
| 1320 |
if isinstance(value, int): |
| 1321 |
return str(value) |
| 1322 |
elif isinstance(value, str): |
| 1323 |
for char in value: |
| 1324 |
if ord(char) < 32 or ord(char) >= 255 or char in '\\"': |
| 1325 |
|
| 1326 |
|
| 1327 |
raise ValueError( |
| 1328 |
f"Character {char!r} not supported in define value" |
| 1329 |
) |
| 1330 |
return '\\"\\\\"' + value + '\\\\"\\"' |
| 1331 |
else: |
| 1332 |
raise TypeError("Can't serialize this type as an SV literal") |
| 1333 |
|
| 1334 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1335 |
return [f"-g{name}={value}" for name, value in parameters.items()] |
| 1336 |
|
| 1337 |
def _build_command(self) -> List[_Command]: |
| 1338 |
do_script: List[str] = ["onerror {\n quit -code 1 \n}"] |
| 1339 |
|
| 1340 |
out_file = self.build_dir / self.hdl_library / f"{self.hdl_library}.lib" |
| 1341 |
|
| 1342 |
sources = self._sources + self._vhdl_sources + self._verilog_sources |
| 1343 |
|
| 1344 |
if outdated(out_file, (source.value for source in sources)) or self.always: |
| 1345 |
vhdl_args = [ |
| 1346 |
arg.value for arg in self._build_args if arg.tag in (VHDL, None) |
| 1347 |
] |
| 1348 |
verilog_args = [ |
| 1349 |
arg.value for arg in self._build_args if arg.tag in (Verilog, None) |
| 1350 |
] |
| 1351 |
defines = " ".join(self._get_define_options(self.defines)) |
| 1352 |
includes = " ".join(self._get_include_options(self.includes)) |
| 1353 |
verilog_args_str = " ".join(_as_tcl_value(v) for v in verilog_args) |
| 1354 |
vhdl_args_str = " ".join(_as_tcl_value(v) for v in vhdl_args) |
| 1355 |
hdl_library = _as_tcl_value(self.hdl_library) |
| 1356 |
ext_name = _as_tcl_value( |
| 1357 |
cocotb_tools.config.lib_name_path("vpi", "riviera").as_posix() |
| 1358 |
) |
| 1359 |
|
| 1360 |
do_script.append(f"alib {hdl_library}") |
| 1361 |
|
| 1362 |
for source in sources: |
| 1363 |
if source.tag is Verilog: |
| 1364 |
do_script.append( |
| 1365 |
f"alog -work {hdl_library} -pli {ext_name} -sv {defines} {includes} {verilog_args_str} {_as_tcl_value(str(source.value))}" |
| 1366 |
) |
| 1367 |
elif source.tag is VHDL: |
| 1368 |
do_script.append( |
| 1369 |
f"acom -work {hdl_library} {vhdl_args_str} {_as_tcl_value(str(source.value))}" |
| 1370 |
) |
| 1371 |
else: |
| 1372 |
raise ValueError(f"Unsupported file type: {source.value}") |
| 1373 |
|
| 1374 |
|
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
|
| 1379 |
do_script.append("exit") |
| 1380 |
|
| 1381 |
with tempfile.NamedTemporaryFile(delete=False) as do_file: |
| 1382 |
do_file.write("\n".join(do_script).encode()) |
| 1383 |
|
| 1384 |
return [["vsimsa", "-do", "do", do_file.name]] |
| 1385 |
|
| 1386 |
def _test_command(self) -> List[_Command]: |
| 1387 |
if self.pre_cmd is not None: |
| 1388 |
raise RuntimeError("pre_cmd is not implemented for Riviera.") |
| 1389 |
|
| 1390 |
do_script: str = "\nonerror {\n quit -code 1 \n} \n" |
| 1391 |
|
| 1392 |
if self.hdl_toplevel_lang == "vhdl": |
| 1393 |
do_script += "asim +access +w_nets -interceptcoutput -loadvhpi {EXT_NAME} {EXTRA_ARGS} {TOPLEVEL} {PLUSARGS}\n".format( |
| 1394 |
TOPLEVEL=_as_tcl_value( |
| 1395 |
f"{self.hdl_toplevel_library}.{self.sim_hdl_toplevel}" |
| 1396 |
), |
| 1397 |
EXT_NAME=_as_tcl_value( |
| 1398 |
cocotb_tools.config.lib_name_path("vhpi", "riviera").as_posix() |
| 1399 |
+ ":vhpi_startup_routines_bootstrap" |
| 1400 |
), |
| 1401 |
EXTRA_ARGS=" ".join( |
| 1402 |
_as_tcl_value(v) |
| 1403 |
for v in ( |
| 1404 |
self.test_args + self._get_parameter_options(self.parameters) |
| 1405 |
) |
| 1406 |
), |
| 1407 |
PLUSARGS=" ".join(_as_tcl_value(v) for v in self.plusargs), |
| 1408 |
) |
| 1409 |
|
| 1410 |
self.env["GPI_EXTRA"] = ( |
| 1411 |
cocotb_tools.config.lib_name_path("vpi", "riviera").as_posix() |
| 1412 |
+ ":cocotbvpi_entry_point" |
| 1413 |
) |
| 1414 |
else: |
| 1415 |
do_script += "asim +access +w_nets -interceptcoutput -pli {EXT_NAME} {EXTRA_ARGS} {TOPLEVEL} {PLUSARGS} \n".format( |
| 1416 |
TOPLEVEL=_as_tcl_value( |
| 1417 |
f"{self.hdl_toplevel_library}.{self.sim_hdl_toplevel}" |
| 1418 |
), |
| 1419 |
EXT_NAME=_as_tcl_value( |
| 1420 |
cocotb_tools.config.lib_name_path("vpi", "riviera").as_posix() |
| 1421 |
), |
| 1422 |
EXTRA_ARGS=" ".join( |
| 1423 |
_as_tcl_value(v) |
| 1424 |
for v in ( |
| 1425 |
self.test_args + self._get_parameter_options(self.parameters) |
| 1426 |
) |
| 1427 |
), |
| 1428 |
PLUSARGS=" ".join(_as_tcl_value(v) for v in self.plusargs), |
| 1429 |
) |
| 1430 |
|
| 1431 |
self.env["GPI_EXTRA"] = ( |
| 1432 |
cocotb_tools.config.lib_name_path("vhpi", "riviera").as_posix() |
| 1433 |
+ ":cocotbvhpi_entry_point" |
| 1434 |
) |
| 1435 |
|
| 1436 |
if self.waves: |
| 1437 |
do_script += "log -recursive /*;" |
| 1438 |
|
| 1439 |
do_script += "run -all \nexit" |
| 1440 |
|
| 1441 |
with tempfile.NamedTemporaryFile(delete=False) as do_file: |
| 1442 |
do_file.write(do_script.encode()) |
| 1443 |
|
| 1444 |
return [["vsimsa", "-do", "do", do_file.name]] |
| 1445 |
|
| 1446 |
|
| 1447 |
class Verilator(Runner): |
| 1448 |
"""Implementation of :class:`Runner` for Verilator. |
| 1449 |
|
| 1450 |
.. admonition:: Simulator-specific Usage |
| 1451 |
|
| 1452 |
* ``waves=True`` *must* be given to :meth:`.build` if either ``waves`` or ``gui`` are to be used during :meth:`.test`. |
| 1453 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1454 |
""" |
| 1455 |
|
| 1456 |
supported_gpi_interfaces = {"verilog": ["vpi"]} |
| 1457 |
|
| 1458 |
def _set_env(self) -> None: |
| 1459 |
super()._set_env() |
| 1460 |
if "COCOTB_TRUST_INERTIAL_WRITES" not in self.env: |
| 1461 |
self.env["COCOTB_TRUST_INERTIAL_WRITES"] = "1" |
| 1462 |
|
| 1463 |
def _simulator_in_path(self) -> None: |
| 1464 |
|
| 1465 |
return |
| 1466 |
|
| 1467 |
def _use_external_viewer(self) -> bool: |
| 1468 |
return True |
| 1469 |
|
| 1470 |
def _waves_file(self) -> Optional[str]: |
| 1471 |
return "dump.vcd" |
| 1472 |
|
| 1473 |
def _simulator_in_path_build_only(self) -> None: |
| 1474 |
executable = shutil.which("verilator") |
| 1475 |
if executable is None: |
| 1476 |
raise SystemExit("ERROR: verilator executable not found!") |
| 1477 |
self.executable: str = executable |
| 1478 |
|
| 1479 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1480 |
return [f"-I{include}" for include in includes] |
| 1481 |
|
| 1482 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1483 |
return [f"-D{name}={_as_sv_literal(value)}" for name, value in defines.items()] |
| 1484 |
|
| 1485 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1486 |
return [f"-G{name}={value}" for name, value in parameters.items()] |
| 1487 |
|
| 1488 |
def _build_command(self) -> List[_Command]: |
| 1489 |
self._simulator_in_path_build_only() |
| 1490 |
|
| 1491 |
sources = self._sources + self._verilog_sources |
| 1492 |
|
| 1493 |
for source in sources: |
| 1494 |
if source.tag not in (Verilog, VerilatorControlFile): |
| 1495 |
raise ValueError( |
| 1496 |
f"{type(self).__qualname__} only supports Verilog and Verilator Control Files. {str(source.value)!r} cannot be compiled." |
| 1497 |
) |
| 1498 |
|
| 1499 |
for arg in self._build_args: |
| 1500 |
if arg.tag not in (Verilog, None): |
| 1501 |
raise ValueError( |
| 1502 |
f"{type(self).__qualname__} only supports Verilog. build_args {arg.value!r} will not be applied." |
| 1503 |
) |
| 1504 |
|
| 1505 |
if self.hdl_toplevel is None: |
| 1506 |
raise ValueError( |
| 1507 |
f"{type(self).__qualname__} requires the hdl_toplevel parameter to be specified." |
| 1508 |
) |
| 1509 |
|
| 1510 |
|
| 1511 |
|
| 1512 |
|
| 1513 |
verilator_cpp = str( |
| 1514 |
cocotb_tools.config.share_dir / "lib" / "verilator" / "verilator.cpp" |
| 1515 |
) |
| 1516 |
|
| 1517 |
cmds = [] |
| 1518 |
cmds.append( |
| 1519 |
[ |
| 1520 |
"perl", |
| 1521 |
self.executable, |
| 1522 |
"-cc", |
| 1523 |
"--exe", |
| 1524 |
"-Mdir", |
| 1525 |
str(self.build_dir), |
| 1526 |
"--top-module", |
| 1527 |
self.hdl_toplevel, |
| 1528 |
"--vpi", |
| 1529 |
"--public-flat-rw", |
| 1530 |
"--prefix", |
| 1531 |
"Vtop", |
| 1532 |
"-o", |
| 1533 |
self.hdl_toplevel, |
| 1534 |
"-LDFLAGS", |
| 1535 |
f"-Wl,-rpath,{cocotb_tools.config.libs_dir} -L{cocotb_tools.config.libs_dir} -lcocotbvpi_verilator", |
| 1536 |
] |
| 1537 |
+ (["--trace"] if self.waves else []) |
| 1538 |
+ [arg.value for arg in self._build_args] |
| 1539 |
+ ( |
| 1540 |
["--timescale", "{}/{}".format(*self.timescale)] |
| 1541 |
if self.timescale is not None |
| 1542 |
else [] |
| 1543 |
) |
| 1544 |
+ self._get_define_options(self.defines) |
| 1545 |
+ self._get_include_options(self.includes) |
| 1546 |
+ self._get_parameter_options(self.parameters) |
| 1547 |
+ [verilator_cpp] |
| 1548 |
+ [str(source.value) for source in sources] |
| 1549 |
) |
| 1550 |
|
| 1551 |
cmds.append( |
| 1552 |
[ |
| 1553 |
"make", |
| 1554 |
"-j", |
| 1555 |
f"{_get_max_parallel_build_jobs()}", |
| 1556 |
"-C", |
| 1557 |
str(self.build_dir), |
| 1558 |
"-f", |
| 1559 |
"Vtop.mk", |
| 1560 |
f"VM_TRACE={int(self.waves)}", |
| 1561 |
] |
| 1562 |
) |
| 1563 |
|
| 1564 |
return cmds |
| 1565 |
|
| 1566 |
def _test_command(self) -> List[_Command]: |
| 1567 |
if self.pre_cmd is not None: |
| 1568 |
raise RuntimeError("pre_cmd is not implemented for Verilator.") |
| 1569 |
|
| 1570 |
out_file = self.build_dir / self.sim_hdl_toplevel |
| 1571 |
return [ |
| 1572 |
[str(out_file)] |
| 1573 |
+ (["--trace"] if self.waves or self.gui else []) |
| 1574 |
+ self.test_args |
| 1575 |
+ self.plusargs |
| 1576 |
] |
| 1577 |
|
| 1578 |
|
| 1579 |
class Xcelium(Runner): |
| 1580 |
"""Implementation of :class:`Runner` for Cadence Xcelium. |
| 1581 |
|
| 1582 |
.. admonition:: Simulator-specific Usage |
| 1583 |
|
| 1584 |
* Does not support the ``waves`` argument to :meth:`.build` (must be set in :meth:`.test` instead). |
| 1585 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1586 |
* Does not support the ``timescale`` argument to :meth:`.test`. |
| 1587 |
""" |
| 1588 |
|
| 1589 |
supported_gpi_interfaces = {"verilog": ["vpi"], "vhdl": ["vhpi"]} |
| 1590 |
|
| 1591 |
def _simulator_in_path(self) -> None: |
| 1592 |
if shutil.which("xrun") is None: |
| 1593 |
raise SystemExit("ERROR: xrun executable not found!") |
| 1594 |
|
| 1595 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1596 |
return [f"-incdir {include}" for include in includes] |
| 1597 |
|
| 1598 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1599 |
return [ |
| 1600 |
f"-define {name}={self._as_define_value(value)}" |
| 1601 |
for name, value in defines.items() |
| 1602 |
] |
| 1603 |
|
| 1604 |
def _as_define_value(self, value: object) -> str: |
| 1605 |
if isinstance(value, int): |
| 1606 |
return str(value) |
| 1607 |
elif isinstance(value, str): |
| 1608 |
for char in value: |
| 1609 |
if ord(char) < 32 or ord(char) >= 255 or char == '"': |
| 1610 |
|
| 1611 |
|
| 1612 |
raise ValueError( |
| 1613 |
f"Character {char!r} not supported in define value" |
| 1614 |
) |
| 1615 |
return '"\\"' + value.replace("\\", "\\\\") + '\\""' |
| 1616 |
else: |
| 1617 |
raise TypeError("Can't serialize this type as an SV literal") |
| 1618 |
|
| 1619 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1620 |
return [f'-gpg "{name} => {value}"' for name, value in parameters.items()] |
| 1621 |
|
| 1622 |
def _build_command(self) -> List[_Command]: |
| 1623 |
self.env["CDS_AUTO_64BIT"] = "all" |
| 1624 |
|
| 1625 |
if self.waves: |
| 1626 |
raise RuntimeError( |
| 1627 |
"waves is not supported in the build step. Please set it in the test step." |
| 1628 |
) |
| 1629 |
|
| 1630 |
if self.hdl_toplevel is None: |
| 1631 |
raise ValueError("A HDL toplevel is required in all Xcelium compiles.") |
| 1632 |
|
| 1633 |
verbosity_opts = [] |
| 1634 |
if self.verbose: |
| 1635 |
verbosity_opts += ["-messages"] |
| 1636 |
verbosity_opts += ["-status"] |
| 1637 |
verbosity_opts += ["-gverbose"] |
| 1638 |
verbosity_opts += ["-pliverbose"] |
| 1639 |
verbosity_opts += ["-plidebug"] |
| 1640 |
verbosity_opts += [ |
| 1641 |
"-plierr_verbose" |
| 1642 |
] |
| 1643 |
|
| 1644 |
else: |
| 1645 |
verbosity_opts += ["-quiet"] |
| 1646 |
verbosity_opts += ["-plinowarn"] |
| 1647 |
|
| 1648 |
sources = self._sources + self._vhdl_sources + self._verilog_sources |
| 1649 |
|
| 1650 |
for source in sources: |
| 1651 |
if source.tag not in (VHDL, Verilog): |
| 1652 |
raise ValueError(f"Unsupported file type: {source.value}") |
| 1653 |
|
| 1654 |
vhpi_opts = [] |
| 1655 |
if any(source.tag is VHDL for source in sources): |
| 1656 |
|
| 1657 |
|
| 1658 |
vhpi_opts.append("-NEW_VHPI_PROPAGATE_DELAY") |
| 1659 |
|
| 1660 |
cmds = [ |
| 1661 |
["xrun"] |
| 1662 |
+ ["-logfile"] |
| 1663 |
+ ["xrun_build.log"] |
| 1664 |
+ ["-elaborate"] |
| 1665 |
+ ["-xmlibdirname"] |
| 1666 |
+ [f"{self.build_dir}/xrun_snapshot"] |
| 1667 |
+ ["-licqueue"] |
| 1668 |
+ (["-clean"] if self.always else []) |
| 1669 |
+ verbosity_opts |
| 1670 |
|
| 1671 |
+ ["-access +rwc"] |
| 1672 |
+ ["-loadvpi"] |
| 1673 |
|
| 1674 |
+ [ |
| 1675 |
cocotb_tools.config.lib_name_path("vpi", "xcelium").as_posix() |
| 1676 |
+ ":vlog_startup_routines_bootstrap" |
| 1677 |
] |
| 1678 |
+ vhpi_opts |
| 1679 |
+ [f"-work {self.hdl_library}"] |
| 1680 |
+ ( |
| 1681 |
["-timescale", "{}/{}".format(*self.timescale)] |
| 1682 |
if self.timescale is not None |
| 1683 |
else [] |
| 1684 |
) |
| 1685 |
+ [arg.value for arg in self._build_args] |
| 1686 |
+ self._get_include_options(self.includes) |
| 1687 |
+ self._get_define_options(self.defines) |
| 1688 |
+ self._get_parameter_options(self.parameters) |
| 1689 |
+ [f"-top {self.hdl_toplevel}"] |
| 1690 |
+ [str(source_file.value) for source_file in sources] |
| 1691 |
] |
| 1692 |
|
| 1693 |
return cmds |
| 1694 |
|
| 1695 |
def _test_command(self) -> List[_Command]: |
| 1696 |
if self.pre_cmd is not None: |
| 1697 |
raise RuntimeError("pre_cmd is not implemented for Xcelium.") |
| 1698 |
|
| 1699 |
if self.timescale is not None: |
| 1700 |
raise RuntimeError( |
| 1701 |
"timescale is not supported in the test step. Please set it in the build step." |
| 1702 |
) |
| 1703 |
|
| 1704 |
self.env["CDS_AUTO_64BIT"] = "all" |
| 1705 |
|
| 1706 |
verbosity_opts = [] |
| 1707 |
if self.verbose: |
| 1708 |
verbosity_opts += ["-messages"] |
| 1709 |
verbosity_opts += ["-status"] |
| 1710 |
verbosity_opts += ["-gverbose"] |
| 1711 |
verbosity_opts += ["-pliverbose"] |
| 1712 |
verbosity_opts += ["-plidebug"] |
| 1713 |
verbosity_opts += [ |
| 1714 |
"-plierr_verbose" |
| 1715 |
] |
| 1716 |
|
| 1717 |
else: |
| 1718 |
verbosity_opts += ["-quiet"] |
| 1719 |
verbosity_opts += ["-plinowarn"] |
| 1720 |
|
| 1721 |
tmpdir = f"implicit_tmpdir_{self.current_test_name}" |
| 1722 |
|
| 1723 |
if self.hdl_toplevel_lang == "vhdl": |
| 1724 |
xrun_top = ":" |
| 1725 |
else: |
| 1726 |
xrun_top = self.sim_hdl_toplevel |
| 1727 |
|
| 1728 |
if self.waves: |
| 1729 |
input_tcl = [ |
| 1730 |
f'-input "@database -open cocotb_waves -default" ' |
| 1731 |
f'-input "@probe -database cocotb_waves -create {xrun_top} -all -depth all" ' |
| 1732 |
f'-input "@run" ' |
| 1733 |
f'-input "@exit" ' |
| 1734 |
] |
| 1735 |
else: |
| 1736 |
input_tcl = ["-input", "@run; exit;"] |
| 1737 |
|
| 1738 |
sources = self._sources + self._vhdl_sources + self._verilog_sources |
| 1739 |
|
| 1740 |
vhpi_opts = [] |
| 1741 |
if any(source.tag is VHDL for source in sources): |
| 1742 |
|
| 1743 |
|
| 1744 |
vhpi_opts.append("-NEW_VHPI_PROPAGATE_DELAY") |
| 1745 |
|
| 1746 |
cmds = [["mkdir", "-p", tmpdir]] |
| 1747 |
cmds += [ |
| 1748 |
[ |
| 1749 |
"xrun", |
| 1750 |
"-logfile", |
| 1751 |
f"xrun_{self.current_test_name}.log", |
| 1752 |
"-xmlibdirname", |
| 1753 |
f"{self.build_dir}/xrun_snapshot", |
| 1754 |
"-cds_implicit_tmpdir", |
| 1755 |
tmpdir, |
| 1756 |
"-licqueue", |
| 1757 |
*vhpi_opts, |
| 1758 |
*verbosity_opts, |
| 1759 |
"-R", |
| 1760 |
*self.test_args, |
| 1761 |
*self.plusargs, |
| 1762 |
"-gui" if self.gui else "", |
| 1763 |
*input_tcl, |
| 1764 |
] |
| 1765 |
] |
| 1766 |
self.env["GPI_EXTRA"] = ( |
| 1767 |
cocotb_tools.config.lib_name_path("vhpi", "xcelium").as_posix() |
| 1768 |
+ ":cocotbvhpi_entry_point" |
| 1769 |
) |
| 1770 |
|
| 1771 |
return cmds |
| 1772 |
|
| 1773 |
|
| 1774 |
class Vcs(Runner): |
| 1775 |
"""Implementation of :class:`Runner` for Synopsys VCS. |
| 1776 |
|
| 1777 |
.. admonition:: Simulator-specific Usage |
| 1778 |
|
| 1779 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1780 |
* Does not support VHDL. |
| 1781 |
* Does not support the ``timescale`` argument to :meth:`.build` or :meth:`.test`. |
| 1782 |
""" |
| 1783 |
|
| 1784 |
supported_gpi_interfaces = {"verilog": ["vpi"]} |
| 1785 |
|
| 1786 |
def _simulator_in_path(self) -> None: |
| 1787 |
if shutil.which("vcs") is None: |
| 1788 |
raise SystemExit("ERROR: vcs executable not found!") |
| 1789 |
|
| 1790 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1791 |
return [f"+incdir+{include}" for include in includes] |
| 1792 |
|
| 1793 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1794 |
return [ |
| 1795 |
f"+define+{name}={_as_sv_literal(value)}" for name, value in defines.items() |
| 1796 |
] |
| 1797 |
|
| 1798 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1799 |
if self.hdl_toplevel is None: |
| 1800 |
raise ValueError("A HDL toplevel is required in all VCS compiles.") |
| 1801 |
return [ |
| 1802 |
f"-pvalue+{self.hdl_toplevel}.{name}={value}" |
| 1803 |
for name, value in parameters.items() |
| 1804 |
] |
| 1805 |
|
| 1806 |
@property |
| 1807 |
def sim_file(self) -> Path: |
| 1808 |
return self.build_dir / "simv" |
| 1809 |
|
| 1810 |
@property |
| 1811 |
def _build_opts(self) -> List[str]: |
| 1812 |
opts = [ |
| 1813 |
"-full64", |
| 1814 |
"-debug_access+all", |
| 1815 |
"+acc+3", |
| 1816 |
"-sverilog", |
| 1817 |
"-LDFLAGS -Wl,--no-as-needed", |
| 1818 |
] |
| 1819 |
|
| 1820 |
if self.verbose: |
| 1821 |
opts += ["-diag all"] |
| 1822 |
else: |
| 1823 |
opts += ["-q"] |
| 1824 |
opts += ["-suppress=VPI-CT-NS"] |
| 1825 |
|
| 1826 |
return opts |
| 1827 |
|
| 1828 |
def _build_command(self) -> List[_Command]: |
| 1829 |
cmds: List[_Command] = [] |
| 1830 |
sources = self._sources + self._vhdl_sources + self._verilog_sources |
| 1831 |
|
| 1832 |
for source in sources: |
| 1833 |
if source.tag not in (VHDL, Verilog): |
| 1834 |
raise ValueError(f"Unsupported file type: {source.value}") |
| 1835 |
|
| 1836 |
if outdated(self.sim_file, (source.value for source in sources)) or self.always: |
| 1837 |
cmds = [ |
| 1838 |
["vcs"] |
| 1839 |
+ self._build_opts |
| 1840 |
+ ["-load", cocotb_tools.config.lib_name_path("vpi", "vcs").as_posix()] |
| 1841 |
+ [arg.value for arg in self._build_args] |
| 1842 |
+ self._get_include_options(self.includes) |
| 1843 |
+ self._get_define_options(self.defines) |
| 1844 |
+ self._get_parameter_options(self.parameters) |
| 1845 |
+ ["-top", f"{self.hdl_toplevel}"] |
| 1846 |
+ [str(source.value) for source in sources] |
| 1847 |
+ ["-o", str(self.sim_file)] |
| 1848 |
] |
| 1849 |
else: |
| 1850 |
self.log.warning("Skipping compilation of %s", self.sim_file) |
| 1851 |
|
| 1852 |
return cmds |
| 1853 |
|
| 1854 |
def _test_command(self) -> List[_Command]: |
| 1855 |
if self.pre_cmd is not None: |
| 1856 |
raise RuntimeError("pre_cmd is not implemented for Vcs.") |
| 1857 |
|
| 1858 |
verbosity_opts = [] |
| 1859 |
if self.verbose: |
| 1860 |
verbosity_opts += ["-diag all"] |
| 1861 |
else: |
| 1862 |
verbosity_opts += ["-suppress=ASLR_DETECTED_INFO"] |
| 1863 |
|
| 1864 |
cmds = [[str(self.sim_file), *verbosity_opts, *self.test_args, *self.plusargs]] |
| 1865 |
|
| 1866 |
return cmds |
| 1867 |
|
| 1868 |
|
| 1869 |
class Dsim(Runner): |
| 1870 |
"""Implementation of :class:`Runner` for Siemens DSim. |
| 1871 |
|
| 1872 |
.. admonition:: Simulator-specific Usage |
| 1873 |
|
| 1874 |
* Does not support the ``pre_cmd`` argument to :meth:`.test`. |
| 1875 |
""" |
| 1876 |
|
| 1877 |
supported_gpi_interfaces = {"verilog": ["vpi"]} |
| 1878 |
|
| 1879 |
def _simulator_in_path(self) -> None: |
| 1880 |
if shutil.which("dsim") is None: |
| 1881 |
raise SystemExit("ERROR: dsim executable not found!") |
| 1882 |
|
| 1883 |
def _get_include_options(self, includes: Sequence[PathLike]) -> _Command: |
| 1884 |
return [f"+incdir+{include}" for include in includes] |
| 1885 |
|
| 1886 |
def _get_define_options(self, defines: Mapping[str, object]) -> _Command: |
| 1887 |
return [ |
| 1888 |
f"+define+{name}={_as_sv_literal(value)}" for name, value in defines.items() |
| 1889 |
] |
| 1890 |
|
| 1891 |
def _get_parameter_options(self, parameters: Mapping[str, object]) -> _Command: |
| 1892 |
return [ |
| 1893 |
f"-defparam {name}={_as_sv_literal(value)}" |
| 1894 |
for name, value in parameters.items() |
| 1895 |
] |
| 1896 |
|
| 1897 |
@property |
| 1898 |
def sim_file(self) -> Path: |
| 1899 |
return self.build_dir / "image.so" |
| 1900 |
|
| 1901 |
def _use_external_viewer(self) -> bool: |
| 1902 |
return True |
| 1903 |
|
| 1904 |
def _waves_file(self) -> Optional[str]: |
| 1905 |
return "file.vcd" |
| 1906 |
|
| 1907 |
def _test_command(self) -> List[_Command]: |
| 1908 |
if self.pre_cmd is not None: |
| 1909 |
raise RuntimeError("pre_cmd is not implemented for DSim.") |
| 1910 |
|
| 1911 |
plusargs = self.plusargs |
| 1912 |
if self.waves or self.gui: |
| 1913 |
plusargs += [f"-waves {self._waves_file()}"] |
| 1914 |
|
| 1915 |
if self.timescale: |
| 1916 |
plusargs += ["-timescale {}/{}".format(*self.timescale)] |
| 1917 |
|
| 1918 |
return [ |
| 1919 |
[ |
| 1920 |
"dsim", |
| 1921 |
"-work", |
| 1922 |
str(self.build_dir), |
| 1923 |
"-pli_lib", |
| 1924 |
cocotb_tools.config.lib_name_path("vpi", "dsim").as_posix(), |
| 1925 |
"+acc+rwcbfsWF", |
| 1926 |
"-image", |
| 1927 |
"image", |
| 1928 |
*self.test_args, |
| 1929 |
*plusargs, |
| 1930 |
] |
| 1931 |
] |
| 1932 |
|
| 1933 |
def _build_command(self) -> List[_Command]: |
| 1934 |
sources = self._sources + self._verilog_sources |
| 1935 |
|
| 1936 |
for source in sources: |
| 1937 |
if source.tag is not Verilog: |
| 1938 |
raise ValueError( |
| 1939 |
f"{type(self).__qualname__} only supports Verilog. {str(source.value)!r} cannot be compiled." |
| 1940 |
) |
| 1941 |
|
| 1942 |
for arg in self._build_args: |
| 1943 |
if arg.tag not in (Verilog, None): |
| 1944 |
raise ValueError( |
| 1945 |
f"{type(self).__qualname__} only supports Verilog. build_args {arg!r} cannot be applied." |
| 1946 |
) |
| 1947 |
|
| 1948 |
cmds: list[_Command] = [] |
| 1949 |
if outdated(self.sim_file, (source.value for source in sources)) or self.always: |
| 1950 |
cmds = [ |
| 1951 |
[ |
| 1952 |
"dsim", |
| 1953 |
"-work", |
| 1954 |
str(self.build_dir), |
| 1955 |
"-pli_lib", |
| 1956 |
cocotb_tools.config.lib_name_path("vpi", "dsim").as_posix(), |
| 1957 |
"+acc+rwcbfsWF", |
| 1958 |
"-genimage", |
| 1959 |
"image", |
| 1960 |
] |
| 1961 |
+ self._get_define_options(self.defines) |
| 1962 |
+ self._get_include_options(self.includes) |
| 1963 |
+ self._get_parameter_options(self.parameters) |
| 1964 |
+ [arg.value for arg in self._build_args] |
| 1965 |
+ [str(source_file.value) for source_file in sources] |
| 1966 |
] |
| 1967 |
|
| 1968 |
else: |
| 1969 |
self.log.warning("Skipping compilation of %s", self.sim_file) |
| 1970 |
|
| 1971 |
return cmds |
| 1972 |
|
| 1973 |
|
| 1974 |
def get_runner(simulator_name: str) -> Runner: |
| 1975 |
"""Return an instance of a runner for *simulator_name*. |
| 1976 |
|
| 1977 |
Args: |
| 1978 |
simulator_name: Name of simulator to get runner for. |
| 1979 |
|
| 1980 |
Raises: |
| 1981 |
ValueError: If *simulator_name* is not one of the supported simulators or an alias of one. |
| 1982 |
""" |
| 1983 |
|
| 1984 |
supported_sims: Dict[str, Type[Runner]] = { |
| 1985 |
"icarus": Icarus, |
| 1986 |
"questa": Questa, |
| 1987 |
"ghdl": Ghdl, |
| 1988 |
"riviera": Riviera, |
| 1989 |
"verilator": Verilator, |
| 1990 |
"xcelium": Xcelium, |
| 1991 |
"nvc": Nvc, |
| 1992 |
"vcs": Vcs, |
| 1993 |
"dsim": Dsim, |
| 1994 |
|
| 1995 |
} |
| 1996 |
try: |
| 1997 |
return supported_sims[simulator_name]() |
| 1998 |
except KeyError: |
| 1999 |
raise ValueError( |
| 2000 |
f"Simulator {simulator_name!r} is not in supported list: {', '.join(supported_sims)}" |
| 2001 |
) from None |