diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c723f2..ecf7fc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,32 @@ All notable changes to this project are documented in this file. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [PEP 440](https://peps.python.org/pep-0440/) for +version identifiers (`.devN` marks a development pre-release). + +## [0.3.0.dev1] - 2026-07-18 + +### Added +- `AnalysisResult.format_compile_order()` returns the human-readable, + tree-indented compile-order listing as a string, and + `AnalysisResult.print_compile_order()` prints it -- the same output the CLI + emits. `AnalysisResult` now retains the underlying `SourceFile` order (a + non-serialized `source_files` field; `to_dict()` is unchanged). The shared + rendering logic lives in `output.format_compile_order`. + +## [0.3.0.dev0] - 2026-07-18 + +Opens the 0.3.0 development cycle. + +### Fixed +- `analyse(top_file=...)` now parses and adds a top file that is not already + part of the project (file type inferred from its extension) instead of + raising "not in the project", so a testbench top level need not be listed in + the config just to produce a compile order. New + `config.add_top_file_by_path` / `config.TOP_FILE_EXT_TYPES`; added + `Resolver.verilog_include_dirs` so an auto-added Verilog top can resolve its + `` `include `` directives. ## [0.2.0] - 2026-07-11 diff --git a/examples/python_api/README.md b/examples/python_api/README.md new file mode 100644 index 0000000..805d7d2 --- /dev/null +++ b/examples/python_api/README.md @@ -0,0 +1,124 @@ +# Python API example (`hdldepends.analyse`) + +Most examples drive `hdldepends` from the command line. This one uses it as a +**Python library**: [`analyse_example.py`](analyse_example.py) imports +`hdldepends` and calls `hdldepends.analyse(...)`, which returns the compile +order in-process (no output files written) as an `AnalysisResult`. + +It shows the three things the API gives you: + +1. **A human-readable compile order** — `AnalysisResult.print_compile_order()` + prints the same tree-indented listing the CLI does, and + `format_compile_order()` returns it as a string (to log, write, or diff). +2. **A machine-readable compile order** — `result.compile_order` is a list of + plain, JSON-safe dicts, and `result.to_dict()` wraps it as `{"files": [...]}`. +3. **Auto-added testbench tops** — pointing `analyse` at a `top_file` that is + *not* in the config adds it on the fly, so simulation-only files need not be + listed just to get a compile order. + +## Layout + +``` +hdldeps.yaml config: RTL only (the testbench is intentionally omitted) +analyse_example.py the Python API walkthrough +rtl/ + counter_pkg.vhd package (work) + counter.vhd entity, uses work.counter_pkg (work) +sim/ + counter_tb.vhd testbench, instantiates work.counter (NOT in the config) +``` + +## Run it + +From the repository root (with `hdldepends` importable — e.g. after +`pip install -e .`): + +```sh +python examples/python_api/analyse_example.py +``` + +The script anchors every path to its own directory, so the working directory +you launch it from does not matter. + +## What it demonstrates + +### 1. Compile order for the config's top (`top_entity: counter`) + +```python +result = hdldepends.analyse("hdldeps.yaml", work_dir=HERE) +result.print_compile_order() +``` + +``` +compile order: + VHDL: |---work: .../rtl/counter_pkg.vhd + VHDL: work: .../rtl/counter.vhd +``` + +`counter` uses `work.counter_pkg`, so the package is emitted first and indented +one level below the top. + +### 2. The same result, machine-readable + +```python +result.compile_order # -> list[dict], JSON-safe +result.to_dict() # -> {"files": [...]} +[e["path"] for e in result.compile_order] # just the ordered paths +``` + +```json +{ + "files": [ + { "type": "VHDL", "library": "work", "path": ".../rtl/counter_pkg.vhd" }, + { "type": "VHDL", "library": "work", "path": ".../rtl/counter.vhd", "is_top": true } + ] +} +``` + +`is_top` marks the last (top) entry. When a config uses `ext_files`, those +appear first as `{"type": "EXTERNAL", ...}` entries. + +### 3. Testbench top via `top_file` (auto-added) + +```python +tb = hdldepends.analyse("hdldeps.yaml", work_dir=HERE, top_file="sim/counter_tb.vhd") +print(tb.format_compile_order()) +``` + +`sim/counter_tb.vhd` is not in `hdldeps.yaml`; `analyse` parses and adds it (its +type inferred from the `.vhd` extension), uses it as the top, and resolves its +dependencies against the project: + +``` +compile order: + VHDL: |---|---work: .../rtl/counter_pkg.vhd + VHDL: |---work: .../rtl/counter.vhd + VHDL: work: .../sim/counter_tb.vhd +``` + +## API reference + +```python +hdldepends.analyse( + config_files, # a path, or a sequence of them (TOML / JSON / YAML) + *, + top_entity=None, # top-level entity/module name + top_file=None, # top-level file; auto-added if not already in project + top_lib=None, # default VHDL library (defaults to "work") + x_tool_version=None, # Xilinx tool version (.bd/.xci variant selection) + x_device=None, # Xilinx device (.bd/.xci variant selection) + work_dir=None, # anchor for relative config paths / top_file +) -> AnalysisResult +``` + +Top-selection precedence matches the CLI: `top_file` > `top_entity` > the +config's `top_*_file` > the config's `top_entity`. + +`AnalysisResult`: + +| Member | Description | +| ------------------------- | ------------------------------------------------------ | +| `compile_order` | `list[dict]` — JSON-safe, EXTERNAL entries first | +| `to_dict()` | `{"files": compile_order}` | +| `format_compile_order()` | `str` — the tree-indented listing the CLI prints | +| `print_compile_order()` | prints `format_compile_order()` to stdout | diff --git a/examples/python_api/analyse_example.py b/examples/python_api/analyse_example.py new file mode 100644 index 0000000..166a5bb --- /dev/null +++ b/examples/python_api/analyse_example.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Use hdldepends as a Python library instead of the CLI. + +Run it from anywhere: + + python examples/python_api/analyse_example.py + +It resolves the small VHDL project in this directory with +``hdldepends.analyse`` and shows what the API gives you: + +1. a human-readable compile order -- the same tree-indented text the CLI + prints -- via ``AnalysisResult.print_compile_order()``; +2. the machine-readable, JSON-safe compile order (``compile_order`` / a list of + plain dicts, and ``to_dict()``); +3. pointing the analysis at a testbench that is NOT in the config: the API adds + it on the fly (``top_file``), so simulation-only files need not be listed. +""" + +import json +from pathlib import Path + +import hdldepends + +# This example is self-contained: resolve paths relative to THIS file so it runs +# the same regardless of the current working directory. `work_dir` is what +# relative config paths (and a relative `top_file`) are anchored to. +HERE = Path(__file__).resolve().parent +CONFIG = "hdldeps.yaml" # relative to work_dir (HERE) below +TESTBENCH = "sim/counter_tb.vhd" # deliberately NOT listed in hdldeps.yaml + + +def banner(text: str) -> None: + print("\n" + "=" * 64) + print(text) + print("=" * 64) + + +def main() -> None: + # 1. Resolve using the config's own top (top_entity: counter). + result = hdldepends.analyse(CONFIG, work_dir=HERE) + + banner("1. Compile order for the config's top (entity `counter`)") + # print_compile_order() writes the same tree-indented listing as the CLI. + result.print_compile_order() + + # 2. The same result, machine-readable. `compile_order` is a list of plain + # dicts (JSON-safe); `to_dict()` wraps it as {"files": [...]}. + banner("2. Machine-readable compile order (JSON)") + print(json.dumps(result.to_dict(), indent=2)) + + # ...or just pull out the ordered file paths: + print("\nOrdered paths:") + for entry in result.compile_order: + print(f" {entry['path']}") + + # 3. Point the analysis at a simulation testbench that is NOT in the config. + # `top_file` adds it to the project on the fly (its file type inferred + # from the extension) and uses it as the top -- so the compile order now + # ends at the testbench and pulls its dependencies (counter, counter_pkg) + # in ahead of it. + banner("3. Testbench top via `top_file` (auto-added, not in the config)") + tb_result = hdldepends.analyse(CONFIG, work_dir=HERE, top_file=TESTBENCH) + + # format_compile_order() returns the listing as a string, so you can log it, + # write it to a file, diff it, etc. Here we simply print it. + listing = tb_result.format_compile_order() + print(listing) + + +if __name__ == "__main__": + main() diff --git a/examples/python_api/hdldeps.yaml b/examples/python_api/hdldeps.yaml new file mode 100644 index 0000000..43debf2 --- /dev/null +++ b/examples/python_api/hdldeps.yaml @@ -0,0 +1,19 @@ +# Config for the Python API example (see analyse_example.py). +# +# Only the synthesisable RTL lives here. The testbench under sim/ is +# deliberately left out -- the API example adds it on the fly with `top_file`. + +# Standard libraries provided by the simulator/synthesiser; not part of the +# project's own compile order. +ignore_libs: + - ieee + - std + +# The config's default top, used when analyse() is called with no explicit top. +top_entity: counter + +# Synthesisable sources, compiled into the default `work` library. +vhdl_files: + work: + - ./rtl/counter_pkg.vhd + - ./rtl/counter.vhd diff --git a/examples/python_api/rtl/counter.vhd b/examples/python_api/rtl/counter.vhd new file mode 100644 index 0000000..356a24b --- /dev/null +++ b/examples/python_api/rtl/counter.vhd @@ -0,0 +1,30 @@ +library ieee; +use ieee.std_logic_1164.all; +use ieee.numeric_std.all; + +use work.counter_pkg.all; + +entity counter is + port ( + clk : in std_logic; + rst : in std_logic; + q : out std_logic_vector(WIDTH - 1 downto 0) + ); +end entity counter; + +architecture rtl of counter is + signal cnt : unsigned(WIDTH - 1 downto 0); +begin + process (clk) + begin + if rising_edge(clk) then + if rst = '1' then + cnt <= (others => '0'); + else + cnt <= cnt + 1; + end if; + end if; + end process; + + q <= std_logic_vector(cnt); +end architecture rtl; diff --git a/examples/python_api/rtl/counter_pkg.vhd b/examples/python_api/rtl/counter_pkg.vhd new file mode 100644 index 0000000..fd2caba --- /dev/null +++ b/examples/python_api/rtl/counter_pkg.vhd @@ -0,0 +1,8 @@ +library ieee; +use ieee.std_logic_1164.all; + +-- A tiny package the counter depends on, so the example has a real +-- intra-project dependency edge (counter uses work.counter_pkg). +package counter_pkg is + constant WIDTH : natural := 8; +end package counter_pkg; diff --git a/examples/python_api/sim/counter_tb.vhd b/examples/python_api/sim/counter_tb.vhd new file mode 100644 index 0000000..fee67f0 --- /dev/null +++ b/examples/python_api/sim/counter_tb.vhd @@ -0,0 +1,24 @@ +library ieee; +use ieee.std_logic_1164.all; + +-- Simulation-only testbench. It is deliberately NOT listed in hdldeps.yaml; +-- analyse_example.py adds it on the fly via `top_file`, showing that a +-- testbench top level need not be in the config to get a compile order. +entity counter_tb is +end entity counter_tb; + +architecture sim of counter_tb is + signal clk : std_logic := '0'; + signal rst : std_logic := '1'; + signal q : std_logic_vector(7 downto 0); +begin + dut : entity work.counter + port map ( + clk => clk, + rst => rst, + q => q + ); + + clk <= not clk after 5 ns; + rst <= '0' after 20 ns; +end architecture sim; diff --git a/src/hdldepends/api.py b/src/hdldepends/api.py index 5ad46ae..3a3b474 100644 --- a/src/hdldepends/api.py +++ b/src/hdldepends/api.py @@ -11,14 +11,14 @@ entry points. """ -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union -from .config import build_resolver +from .config import add_top_file_by_path, build_resolver from .constants import LIB_DEFAULT from .model import Name, SourceFile -from .output import compile_order_to_dicts +from .output import compile_order_to_dicts, format_compile_order, print_compile_order from .resolver import Resolver from .util import path_abs_from_dir @@ -78,11 +78,31 @@ class AnalysisResult: #: entry per compiled file, with ``is_top`` set on the last one. compile_order: List[Dict[str, Any]] + #: The underlying resolved :class:`~hdldepends.model.SourceFile` order + #: (compiled files only -- no EXTERNAL entries), retained so + #: :meth:`format_compile_order` / :meth:`print_compile_order` can render the + #: same tree-indented view the CLI prints. Deliberately excluded from + #: :meth:`to_dict` (it is not JSON-safe); ``compile_order`` above is the + #: serializable form. + source_files: List[SourceFile] = field(default_factory=list, repr=False) + def to_dict(self) -> Dict[str, Any]: """The same top-level shape as the ``compile-order-json`` file, e.g. for ``json.dump``: ``{"files": self.compile_order}``.""" return {"files": self.compile_order} + def format_compile_order(self) -> str: + """The human-readable, tree-indented compile-order listing (identical to + what the CLI prints), returned as a string. Compiled files only; the + leading EXTERNAL entries carried by :attr:`compile_order` are not shown, + matching the CLI's ``print_compile_order``.""" + return format_compile_order(self.source_files) + + def print_compile_order(self) -> None: + """Print :meth:`format_compile_order` to stdout -- the same output the + CLI emits for the resolved compile order.""" + print_compile_order(self.source_files) + def analyse( config_files: ConfigFiles, @@ -104,9 +124,11 @@ def analyse( (TOML / JSON / YAML, same as the CLI's positional ``config_file`` arguments). :param top_entity: top-level entity/module name (``--top-entity``). - :param top_file: path to the top-level file; must already be reachable - from ``config_files`` (``--top-file``). A relative path is anchored - to ``work_dir``, like relative ``config_files``. + :param top_file: path to the top-level file (``--top-file``). If it is not + already part of the project, it is parsed and added (its file type is + inferred from the extension), so a testbench top level need not be listed + in the config just to run a basic compile order. A relative path is + anchored to ``work_dir``, like relative ``config_files``. :param top_lib: default VHDL library for ``top_entity`` and for unqualified names in the config (``--top-vhdl-lib``); defaults to :data:`~hdldepends.constants.LIB_DEFAULT`. @@ -116,10 +138,12 @@ def analyse( (``--x-device``). :param work_dir: directory relative ``config_files`` and a relative ``top_file`` are resolved against; defaults to the current directory. - :raises hdldepends.errors.ConfigError: the config fails validation. + :raises hdldepends.errors.ConfigError: the config fails validation, or a + ``top_file`` not already in the project has an extension no parser + recognises. :raises OSError: a config or referenced source file can't be read. :raises ValueError: no top could be determined, or an explicitly named - top (file or entity) does not resolve to a project file. + top entity does not resolve to a project file. """ top_lib_effective = top_lib or LIB_DEFAULT files = [config_files] if isinstance(config_files, (str, Path)) else list(config_files) @@ -141,7 +165,10 @@ def analyse( loc = path_abs_from_dir(resolved_work_dir, Path(top_file)).resolve() top_file_sf = resolver.by_loc.get(loc) if top_file_sf is None: - raise ValueError(f"top file {top_file} is not in the project") + # Not listed in the config: parse and add it (inferring the file type + # from its extension), so a testbench top level need not be added to + # the config just to run a basic simulation compile order. + top_file_sf = add_top_file_by_path(resolver, loc, lib=top_lib_effective) top_entity_name = Name(top_lib_effective, top_entity) if top_entity else None top = select_top(resolver, top_file_sf, top_entity_name) @@ -152,4 +179,7 @@ def analyse( ) order = apply_forced_init_files(resolver, resolver.compile_order(top)) - return AnalysisResult(compile_order=compile_order_to_dicts(order, resolver.tag_2_ext)) + return AnalysisResult( + compile_order=compile_order_to_dicts(order, resolver.tag_2_ext), + source_files=order, + ) diff --git a/src/hdldepends/config.py b/src/hdldepends/config.py index 266b530..770aa19 100644 --- a/src/hdldepends/config.py +++ b/src/hdldepends/config.py @@ -394,6 +394,7 @@ def callback(lib, loc_str, ver): for loc, ver in inc_files: resolver.add(SourceFile(loc, FileType.VERILOG_INCLUDE, ver=ver)) inc_locs = [loc for loc, _ver in inc_files] + resolver.verilog_include_dirs = list(inc_dirs) for lib, loc, ver in vhdl: resolver.add(parse_vhdl_file(loc, lib=lib, ver=ver)) for loc, ver in verilog: @@ -407,3 +408,46 @@ def callback(lib, loc_str, ver): sf.provides.append(Name(LIB_DEFAULT, Path(loc).stem)) resolver.add(sf) return resolver + + +#: File extension -> FileType, used to pick a parser when a top file is named by +#: path but isn't already part of the project (see add_top_file_by_path). +TOP_FILE_EXT_TYPES: Dict[str, FileType] = { + ".vhd": FileType.VHDL, + ".vhdl": FileType.VHDL, + ".v": FileType.VERILOG, + ".sv": FileType.VERILOG, + ".bd": FileType.X_BD, + ".xci": FileType.X_XCI, +} + + +def add_top_file_by_path( + resolver: Resolver, loc: Path, lib: str = LIB_DEFAULT, ver: Optional[str] = None +) -> SourceFile: + """Parse ``loc`` and add it to an already-built ``resolver``, returning the + :class:`~hdldepends.model.SourceFile`. + + This restores the old ``--top-file-type`` auto-add: a top file (typically a + testbench) can be named on the command line / API without also listing it in + the config. The parser is chosen from ``loc``'s extension; an unrecognised + extension raises :class:`~hdldepends.errors.ConfigError`. + """ + ftype = TOP_FILE_EXT_TYPES.get(loc.suffix.lower()) + if ftype is None: + known = " / ".join(sorted(TOP_FILE_EXT_TYPES)) + raise ConfigError( + f"cannot infer a file type for top file {loc} from its extension " + f"{loc.suffix!r}; expected one of {known}" + ) + if ftype == FileType.VHDL: + sf = parse_vhdl_file(loc, lib=lib, ver=ver) + elif ftype == FileType.VERILOG: + inc_locs = [f.loc for f in resolver.by_loc.values() if f.ftype == FileType.VERILOG_INCLUDE] + sf = parse_verilog_file(loc, ver, resolver.verilog_include_dirs, inc_locs) + elif ftype == FileType.X_BD: + sf = parse_x_bd_file(loc, ver) + else: # FileType.X_XCI + sf = parse_x_xci_file(loc, ver) + resolver.add(sf) + return sf diff --git a/src/hdldepends/constants.py b/src/hdldepends/constants.py index 63bab99..0a24ba8 100644 --- a/src/hdldepends/constants.py +++ b/src/hdldepends/constants.py @@ -7,7 +7,7 @@ #: Installed package version (single-sourced here; ``pyproject.toml`` reads it #: back via ``[tool.setuptools.dynamic]``). Not to be confused with #: ``HDL_DEPENDS_VERSION_NUM`` below, which is the config-schema version. -__version__ = "0.2.0" +__version__ = "0.3.0.dev1" #: Separator used in config keys to attach an optional version/custom tag, #: e.g. ``vhdl_files@my_tag``. diff --git a/src/hdldepends/output.py b/src/hdldepends/output.py index b6d1c5b..fdcaa02 100644 --- a/src/hdldepends/output.py +++ b/src/hdldepends/output.py @@ -16,10 +16,19 @@ def _filter(files: List[SourceFile], ftype: Optional[FileType], lib: Optional[st yield sf -def print_compile_order(order: List[SourceFile]) -> None: - print("compile order:") +def format_compile_order(order: List[SourceFile]) -> str: + """Render ``order`` as the human-readable, tree-indented compile-order + listing (the exact text :func:`print_compile_order` writes to stdout, minus + the trailing newline). Shared by the CLI and + :meth:`hdldepends.api.AnalysisResult.format_compile_order`.""" + lines = ["compile order:"] for sf in order: - print(f" {sf.type_str + ':':14} {'|---' * sf.level}{sf.lib}: {sf.loc}") + lines.append(f" {sf.type_str + ':':14} {'|---' * sf.level}{sf.lib}: {sf.loc}") + return "\n".join(lines) + + +def print_compile_order(order: List[SourceFile]) -> None: + print(format_compile_order(order)) def write_compile_order( diff --git a/src/hdldepends/resolver.py b/src/hdldepends/resolver.py index 847bde3..f64f847 100644 --- a/src/hdldepends/resolver.py +++ b/src/hdldepends/resolver.py @@ -92,6 +92,10 @@ def __init__(self): self.ignore_components: Set[str] = set() self.skip_locs: Set[Path] = set() self.init_files: List[SourceFile] = [] + #: Verilog `include search directories gathered from the config, kept so a + #: Verilog top file added after the fact (see config.add_top_file_by_path) + #: can resolve its `include directives the same way project files do. + self.verilog_include_dirs: List[Path] = [] self.tag_2_ext: Dict[str, List[Path]] = {} self.x_tool_version: str = "" self.x_device: str = "" diff --git a/tests/test_api.py b/tests/test_api.py index c4d647a..677ea98 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -16,8 +16,8 @@ from hdldepends.config import build_resolver from hdldepends.constants import LIB_DEFAULT from hdldepends.errors import ConfigError -from hdldepends.model import Name -from hdldepends.output import write_compile_order_json +from hdldepends.model import Name, SourceFile +from hdldepends.output import format_compile_order, write_compile_order_json FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures" @@ -162,8 +162,9 @@ def test_relative_top_file_is_anchored_to_work_dir(tmp_path, monkeypatch): assert result.compile_order[-1]["path"] == str(work / "del21.vhd") # Sanity check of the contrast: without work_dir the same relative - # top_file is CWD-relative, which from `elsewhere` names no project file. - with pytest.raises(ValueError, match="is not in the project"): + # top_file is CWD-relative, which from `elsewhere` names a path that is + # neither in the project nor on disk -- the auto-add then fails to read it. + with pytest.raises(OSError): hdldepends.analyse(str(work / "hdldeps.toml"), top_file="del21.vhd") @@ -195,14 +196,52 @@ def test_top_entity_not_found_raises_value_error(tmp_path, monkeypatch): hdldepends.analyse("hdldeps.toml", top_entity="does_not_exist") -def test_top_file_not_in_project_raises_value_error(tmp_path, monkeypatch): +def test_top_file_not_in_project_is_added(tmp_path, monkeypatch): + # A top_file not listed in the config is parsed and added on the fly (its + # type inferred from the .vhd extension), so a testbench top level need not + # be added to the config just to run a compile order. work = tmp_path / "proj" shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) (work / "not_in_project.vhd").write_text("library ieee;\nentity nip is end entity;\n") monkeypatch.chdir(work) - with pytest.raises(ValueError, match="not_in_project.vhd"): - hdldepends.analyse("hdldeps.toml", top_file="not_in_project.vhd") + result = hdldepends.analyse("hdldeps.toml", top_file="not_in_project.vhd") + assert result.compile_order[-1]["path"].endswith("not_in_project.vhd") + assert result.compile_order[-1]["is_top"] is True + + +def test_added_top_file_pulls_in_config_dependencies(tmp_path, monkeypatch): + # An auto-added top file's dependencies still resolve against the project: + # a testbench that instantiates a config entity produces the full order. + work = tmp_path / "proj" + shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) + (work / "tb.vhd").write_text( + "library ieee;\n" + "entity tb is end entity;\n" + "architecture sim of tb is\n" + "begin\n" + " dut : entity work.del21\n" + " port map (\n" + " clk => clk\n" + " );\n" + "end architecture;\n" + ) + monkeypatch.chdir(work) + + result = hdldepends.analyse("hdldeps.toml", top_file="tb.vhd") + paths = [f["path"] for f in result.compile_order] + assert paths[-1].endswith("tb.vhd") + assert any(p.endswith("del21.vhd") for p in paths[:-1]) + + +def test_added_top_file_unknown_extension_raises(tmp_path, monkeypatch): + work = tmp_path / "proj" + shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) + (work / "top.qqq").write_text("nonsense\n") + monkeypatch.chdir(work) + + with pytest.raises(ConfigError, match="extension"): + hdldepends.analyse("hdldeps.toml", top_file="top.qqq") def test_no_top_anywhere_raises_value_error(tmp_path, monkeypatch): @@ -264,3 +303,64 @@ def test_x_tool_version_and_x_device_default_to_unset_on_resolver(tmp_path, monk resolver = build_resolver("hdldeps.toml", work_dir=Path("."), top_lib=LIB_DEFAULT) assert resolver.x_tool_version == "" assert resolver.x_device == "" + + +# --- AnalysisResult.format_compile_order / print_compile_order -------------- + +def test_format_compile_order_returns_indented_string(tmp_path, monkeypatch): + # del21 (the top) instantiates del211, so the resolved order is + # [del211 @ level 1, del21 @ level 0]: the dependency is tree-indented with + # "|---" and the top is not, exactly as the CLI prints it. + work = tmp_path / "proj" + shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) + monkeypatch.chdir(work) + + result = hdldepends.analyse("hdldeps.toml", top_entity="del21") + text = result.format_compile_order() + + assert isinstance(text, str) + lines = text.splitlines() + assert lines[0] == "compile order:" + dep_line = next(ln for ln in lines if ln.endswith("del211.vhd")) + top_line = next(ln for ln in lines if ln.endswith("del21.vhd")) + assert "|---" in dep_line # dependency is indented + assert "|---" not in top_line # top sits at level 0 + + +def test_format_compile_order_matches_free_function(tmp_path, monkeypatch): + # The method is faithful to the CLI: it renders the retained SourceFile + # order through the very same output.format_compile_order helper the CLI + # uses, so the two are byte-for-byte identical. + work = tmp_path / "proj" + shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) + monkeypatch.chdir(work) + + result = hdldepends.analyse("hdldeps.toml", top_entity="del21") + assert result.format_compile_order() == format_compile_order(result.source_files) + assert all(isinstance(sf, SourceFile) for sf in result.source_files) + + +def test_print_compile_order_writes_format_to_stdout(tmp_path, monkeypatch, capsys): + work = tmp_path / "proj" + shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) + monkeypatch.chdir(work) + + result = hdldepends.analyse("hdldeps.toml", top_entity="del21") + result.print_compile_order() + + out = capsys.readouterr().out + assert out == result.format_compile_order() + "\n" + + +def test_source_files_excluded_from_to_dict(tmp_path, monkeypatch): + # source_files holds live SourceFile objects for rendering only; the + # JSON-safe representation must not leak them. + work = tmp_path / "proj" + shutil.copytree(FIXTURES_DIR / "vhdl_basic", work) + monkeypatch.chdir(work) + + result = hdldepends.analyse("hdldeps.toml", top_entity="del21") + d = result.to_dict() + assert set(d.keys()) == {"files"} + # round-trips through JSON without hitting the non-serializable SourceFiles + json.dumps(d) diff --git a/tests/test_config_features.py b/tests/test_config_features.py index 93699aa..af905e4 100644 --- a/tests/test_config_features.py +++ b/tests/test_config_features.py @@ -190,9 +190,9 @@ def test_top_entity_lib_dot_name_form_names_library_explicitly(tmp_path, monkeyp def test_top_entity_multi_dot_raises_configerror_not_raw_valueerror(tmp_path, monkeypatch): - # "a.b.c" makes str_to_name raise ValueError (more than one '.'); the config - # loader must wrap it as a ConfigError naming the config file, not let the - # ValueError escape as a raw traceback. + # "a.b.c" makes str_to_name raise ValueError (more than one '.'); the + # config loader must wrap it as a ConfigError naming the config file, not + # let the ValueError escape as a raw traceback. _yaml( tmp_path, "vhdl_files:\n work:\n - ./top.vhd\ntop_entity: a.b.c\n", @@ -202,6 +202,7 @@ def test_top_entity_multi_dot_raises_configerror_not_raw_valueerror(tmp_path, mo with pytest.raises(ConfigError) as ei: build_resolver("hdldeps.yaml", work_dir=Path(".")) assert "hdldeps.yaml" in str(ei.value) + assert "invalid top_entity" in str(ei.value) assert "a.b.c" in str(ei.value) diff --git a/tests/test_examples.py b/tests/test_examples.py index b307021..2c5a6e9 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -7,6 +7,7 @@ from pathlib import Path +import hdldepends from hdldepends.config import build_resolver from hdldepends.model import Name @@ -70,3 +71,26 @@ def test_vhdl2008_ext_exclude(monkeypatch): assert [p.name for p in resolver.tag_2_ext["xdc"]] == ["pins.xdc"] assert [p.name for p in resolver.tag_2_ext["tcl"]] == ["build.tcl"] assert not any(p.suffix in (".xdc", ".tcl") for p in resolver.by_loc) + + +# --- examples/python_api (the Python API walkthrough) ---------------------- + +def test_python_api_example(): + # Drive the example the way analyse_example.py does, so the example's + # documented behaviour stays verified. + api_dir = EXAMPLES / "python_api" + + # 1. Config's own top (top_entity: counter): counter_pkg before counter. + result = hdldepends.analyse("hdldeps.yaml", work_dir=api_dir) + stems = [Path(e["path"]).stem for e in result.compile_order] + assert stems == ["counter_pkg", "counter"] + assert result.compile_order[-1]["is_top"] is True + # the human-readable listing is available as a string / via stdout + assert result.format_compile_order().startswith("compile order:") + + # 2. Testbench top via top_file -- auto-added (not in hdldeps.yaml) and its + # dependencies pulled in ahead of it. + tb = hdldepends.analyse("hdldeps.yaml", work_dir=api_dir, top_file="sim/counter_tb.vhd") + tb_stems = [Path(e["path"]).stem for e in tb.compile_order] + assert tb_stems == ["counter_pkg", "counter", "counter_tb"] + assert tb.compile_order[-1]["is_top"] is True