Metadata-Version: 2.4
Name: xactflow-sv
Version: 0.3.0
Summary: XactFlow importer plugin that reads a SystemVerilog module and a metadata file into an ipxact.Component.
Author: Maxime Travaillard
License-Expression: LGPL-3.0-only
Project-URL: Repository, https://github.com/IP-XACT/XactFlow-sv
Project-URL: Issues, https://github.com/IP-XACT/XactFlow-sv/issues
Keywords: IP-XACT,IEEE 1685,XML,Compiler,XactFlow,SystemVerilog,Importer
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: xactflow>=0.4.1
Requires-Dist: ipxact-compiler>=0.2.0
Requires-Dist: pyslang>=11.0.0
Requires-Dist: systemrdl-compiler>=1.32.2
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Dynamic: license-file

# xactflow-sv

A [XactFlow](https://github.com/IP-XACT/XactFlow) importer plugin that reads a SystemVerilog
module plus a JSON metadata file (and, optionally, a SystemRDL register map) and adds the
`ipxact.Component` it describes to a XactFlow `Library`, built on
[`ipxact-compiler`](https://github.com/IP-XACT/ipxact-compiler)'s
[IEEE 1685-2022](https://standards.ieee.org/ieee/1685/10307/) object model.

`ipxact-compiler` parses IP-XACT and hands back Python objects; XactFlow's `Importer` interface
is for the other direction, reading some non-IP-XACT source and adding that object model to a
`Library`. This package is one such importer: it does not write XML itself, turning the
resulting `Component` into a file is a separate exporter's job (see
[`xactflow-component`](https://github.com/IP-XACT/XactFlow-component)).

The SystemVerilog parsing and metadata-driven design was informed by
[`ipxact-sv2ipxact`](https://github.com/mtravaillard/ipxact-sv2ipxact), an earlier, experimental
standalone tool that solves a closely related problem by writing IP-XACT XML directly. This
package is a from-scratch implementation built against `ipxact-compiler`'s object model rather
than a fork of it, and its scope, dependencies, and error handling are its own.

## Installation

```bash
pip install xactflow-sv
```

For local development, `requirements-dev.txt` overrides `ipxact-compiler` and `xactflow` to
local installations. It can be modified to adapt the paths or to keep either version on PyPI.

```bash
pip install -r requirements-dev.txt -e .
```

Requires Python >= 3.9. Runtime dependencies beyond `ipxact-compiler`/`xactflow`:
[`pyslang`](https://pypi.org/project/pyslang/) for SystemVerilog parsing, and
[`systemrdl-compiler`](https://pypi.org/project/systemrdl-compiler/) for register maps.

## Usage

An importer's job stops at adding an `ipxact.Component` to a XactFlow `Library`, as a target
(`target=True`); it does not write anything out on its own, so getting an actual IP-XACT XML
file also needs an exporter, like
[`xactflow-component`](https://github.com/IP-XACT/XactFlow-component). Once both are installed,
the importer registers itself under the `xactflow.importers` entry point group as `sv`, so
it can run as one XactFlow CLI command, `--then` handing the same library straight to the
exporter in the same process:

```bash
xactflow sv my_module.sv --option metadata=my_module_ipxact.json --then component --output out/
# writes out/<vendor>_<library>_<name>_<version>.xml
```

`--lib DIR` adds the IP-XACT files under `DIR` to the library, e.g. the bus definitions the
component refers to. The component is regenerated from its source, so it replaces a document of
the same VLNV found there (`replace=True`), such as the output of a previous run, instead of
being reported as an SCR 1.1 duplicate VLNV.

Or as a library, e.g. to inspect or modify the `Component` before exporting it:

```python
from pathlib import Path

import ipxact
from xactflow import Library
from xactflow_sv import SVImporter
from xactflow_component import ComponentExporter

library = Library()  # or Library.scan("path/to/ip/library")
SVImporter().import_(Path("my_module.sv"), library, metadata="my_module_ipxact.json")

(component,) = library.targets(ipxact.Component)
component.vlnv            # VLNV
component.model.ports     # list[Port]
component.bus_interfaces  # list[BusInterface]
component.memory_maps     # list[MemoryMap]

ComponentExporter().export(library, Path("out"))  # writes out/<vendor>_<library>_<name>_<version>.xml
```

Only the module's parameters and ports are read (from its header, and its body parameters when
it has no parameter port list), with no elaboration, no package loading, no symbol resolution:
types, values, and dimension expressions are taken verbatim from the source text, matching how
IP-XACT's own expression model treats them.

### Generated component

- **VLNV**: vendor, library and version from the metadata file (or the
  [options](#options)), name from the module.
- **Model**: one view `rtl` referencing one component instantiation `<module>_rtl`, with
  `language` `systemverilog` and `moduleName` the module name.
- **Parameters**: each overridable SV parameter gives a component `parameter` (with
  `parameterId` and `resolve="user"`, holding the default value) and a `moduleParameter`
  whose value references that `parameterId`, so a design override reaches the HDL module.
  The `moduleParameter`'s `dataType` is the SV type as written (`int`, `logic [7:0]`,
  `type` for a type parameter, ...), and unpacked dimensions become `arrays` on both.
- **Ports**:
  - a vector or scalar port is a `wire` port, its packed dimensions giving the `vectors`.
    Built-in integer types get their width, e.g. `int` gives `[31:0]`;
  - a struct/typedef-typed port is a `structured` port of type `struct`, with the type name
    in `structPortTypeDefs` (its width is not known without elaboration);
  - an SV `interface` port is a `structured` port of type `interface`, with the interface
    name and its modport as role;
  - unpacked dimensions become `arrays`, `[N]` giving `[(N)-1:0]`;
  - a clock or reset wire port gets an `isClock` or `isReset` (with its `level`) qualifier,
    see [Clocks and resets](#clocks-and-resets).
- **Bus interfaces** and **memory maps**: from the metadata file (or, for the memory map,
  the `registerFile` [option](#options)), see below.
- **Reset types**: one per reset signal, other than the default one, that resets a field of
  the memory map, see [Register maps](#register-maps).

### Metadata file

A small JSON file supplies what can't be inferred from the SV source alone:

```json
{
    "vendor": "Vendor",
    "library": "Library",
    "version": "1.0",
    "busInterfaces": {
        "apb": {
            "bus": "Vendor:Library:apb4:1.0",
            "mode": "target",
            "ports": {"PSEL": "psel", "PADDR": "bus_req_i.paddr"},
            "memoryMap": "register_map_mmap"
        }
    },
    "registerFile": "register_map.rdl",
    "clocks": ["clk_i"],
    "resets": {"rst_ni": "low"}
}
```

- `vendor`/`library` are required, `version` defaults to `"1.0"`. The component's `name` always
  comes from the parsed module name, not from this file.
- `busInterfaces` maps a bus interface name to its bus VLNV, mode, and either a `ports`
  mapping of logical bus signal names onto physical SV port names, or an `interfacePort`
  naming a genuine SV `interface`-typed port that already groups its own signals. A `ports`
  value can be a plain port name or a dotted `port.field` reference into a struct-typed port
  (e.g. `bus_req_i.paddr`). For a `ports` mapping, the abstraction definition is derived by
  convention as `<bus-def-name>_rtl` at the same vendor/library/version as `bus`. Every
  `interface`-typed port in the module must be described this way; there is no fallback guess
  for its bus VLNV or mode.
- `mode` is one of (case-insensitive):

  | mode | also accepted | extra keys |
  |---|---|---|
  | `initiator` | `master` | |
  | `target` | `slave` | `memoryMap` (optional) |
  | `system` | | `group` (required) |
  | `mirroredInitiator` | `mirroredMaster` | |
  | `mirroredTarget` | `mirroredSlave` | |
  | `mirroredSystem` | | `group` (required) |
  | `monitor` | | `monitoredMode` (required), `group` (required if `monitoredMode` is a system mode) |

  `group` is the system group name from the bus definition. `monitoredMode` is the mode of
  the interface the monitor watches, any mode but `monitor`.
- `memoryMap` names the memory map a target interface gives access to. When the component has
  exactly one target interface and one memory map, that target references it by default.
- `registerFile` is a path (absolute, or relative to the metadata file) to a SystemRDL file
  describing the component's register map. It is compiled with `systemrdl-compiler`, its
  last-defined `addrmap` being the top, and becomes the component's `memory_maps`, see
  [Register maps](#register-maps). Its memory map is named `<addrmap name>_mmap`.
- `clocks` lists the clock ports, and `resets` maps each reset port to its active level,
  `low` or `high`. Both are optional, see [Clocks and resets](#clocks-and-resets).

Any other key, at the top level or in a `busInterfaces` entry, raises a `ValueError`, so a
misspelled key is not silently ignored.

### Clocks and resets

A clock port gets the `<ipxact:isClock>true</ipxact:isClock>` qualifier, and a reset port
`<ipxact:isReset level="low">true</ipxact:isReset>` (or `level="high"`), e.g. for
[`xactflow-archidesc`](https://github.com/IP-XACT/XactFlow-archidesc) to connect a design's
clock and reset to every instance.

The metadata file is the source of truth. When it has `clocks`, the clocks are exactly the
ports it lists, and when it has `resets`, the resets are exactly the ports it lists, so
`"clocks": []` turns clock detection off. A listed port must be a wire port, of any
direction.

Otherwise, an input wire port is detected from its name:

| kind | names |
|---|---|
| clock | `clk`, `clk_i`, `clock`, `clock_i` |
| active-low reset | `rst_n`, `rst_ni`, `arst_n`, `arst_ni`, `reset_n`, `reset_ni` |
| active-high reset | `rst`, `rst_i`, `arst`, `arst_i`, `reset`, `reset_i` |

The name may also have any `<prefix>_` before it (`sys_clk_i`), an uppercase letter or a
number after it for a replicated signal (`clk_iA`/`clk_iB`/`clk_iC` in a TMR design, or
`clk_0`), and any case (`CLK`, `RST_N`). Names that only contain one of these, such as
`clk_en_i` or `pclk`, are not detected; list them in the metadata file.

### Options

Given as `--option name=value` on the CLI, or as keyword arguments to `import_`, after the
library:

- `metadata`: path to the metadata file.
- `vlnv_vendor`, `vlnv_library`, `vlnv_version`, `registerFile`: instead of a metadata file,
  e.g. when a build system already knows them, `--option vlnv_vendor=V
  --option vlnv_library=L --option registerFile=regs.rdl`. They mean the same as the metadata
  file's `vendor`, `library`, `version` and `registerFile`: `vlnv_vendor` and `vlnv_library`
  are required, `vlnv_version` defaults to `"1.0"`. They cannot be used together with
  `metadata`, so the same value is never given twice. Without a metadata file, the component
  has no bus interfaces, and its clocks and resets are detected from the port names.
- `define`: preprocessor symbols to predefine before parsing, `--option define=SYM1,SYM2=4`
  on the CLI or `define=["SYM1", "SYM2=4"]` in Python.
- `include`: directories to search for `` `include `` files, in addition to the `.sv` file's
  own directory, `--option include=rtl/include,rtl/pkg` or `include=["rtl/include", ...]`.
- `module`: name of the module to import. Required when the file declares more than one
  module.

Paths given in options are relative to the current directory. Any SystemVerilog error
reported while parsing (syntax error, include file not found, unknown macro) raises a
`ValueError` with its file and line, instead of importing a partially parsed module.

### Register maps

A SystemRDL register map becomes one memory map, named `<addrmap name>_mmap`:

- When the top `addrmap` only holds `addrmap`s and `mem`s, each one becomes an address block,
  and the memory map carries the top's `name`/`desc`. Otherwise the top `addrmap` is the only
  address block, and its nested `addrmap`s and `regfile`s become register files.
- A `mem` is an address block with `usage` `memory` and its `sw` as `access`, `sw = na`
  giving `no-access`.
- An address block's `width` is its widest register's `regwidth`, or a `mem`'s `memwidth`.
- A register's `size` is its `regwidth`; `accesswidth` is not represented.
- An array address block, register or register file has an `array`, with one `dim` per
  dimension and the RDL stride as its `stride`. Its `range` is the size of one element.
- A field's `sw` gives its `access`, `onwrite` its `modifiedWriteValue`, `onread` its
  `readAction`, `donttest` a `testable` of `false`, `reset` its reset value, and `encode` its
  enumerated values.
- A field reset by a `resetsignal` other than the `field_reset` one, the default reset, has a
  reset of the reset type named after that signal, and the component declares that reset
  type in its `resetTypes`. Other resets are of IP-XACT's default reset type, `HARD`.
- A field of an `alias` register has an `aliasOf` referring to the same field of the primary
  register, instead of a width and reset of its own, and keeps its own access.
- `name` gives the `displayName` and `desc` the `description`, of every element.

The memory map is named `<addrmap name>_mmap`. What IEEE 1685-2022 cannot represent raises
an error instead of being left out, see [Known limitations](#known-limitations).

User-defined properties are not part of the memory map.

The node tree that `systemrdl-compiler` elaborates can also be converted directly, which is
supported API: `xactflow_sv.register_map.build_memory_maps_from_node(node)` takes an
`AddrmapNode` and returns the `ipxact.MemoryMap` list, compiling nothing itself. It suits a
register map that needs user-defined properties, or that another tool has already compiled,
e.g. to generate its RTL:

```python
from systemrdl import RDLCompiler, component
from systemrdl.udp import UDPDefinition
from xactflow_sv.register_map import build_memory_maps_from_node


class Owner(UDPDefinition):
    name = "owner"
    valid_components = {component.Reg}
    valid_type = str


compiler = RDLCompiler()
compiler.register_udp(Owner, soft=False)  # the RDL can then use "owner" without declaring it
compiler.compile_file("regs.rdl")
root = compiler.elaborate()

memory_maps = build_memory_maps_from_node(root.top)  # list[ipxact.MemoryMap]
```

`xactflow_sv.register_map.build_memory_maps(path, udps=..., include_dirs=..., parameters=...)`
compiles a file and converts it, with user-defined property classes to register, `` `include ``
search directories, and overrides of the top `addrmap`'s parameters. These three are only
available from Python, not from the metadata file or the CLI.

## Design notes

- **Independent stages**, each targeting `ipxact-compiler` dataclasses directly rather
  than XML: `sv_parser.py` reads the module's parameters and ports into plain dicts,
  `component_builder.py` turns those into `ipxact.Port`/`ipxact.Parameter`/the component's `Model`,
  `bus_interfaces.py` builds `ipxact.BusInterface` from the metadata's `busInterfaces`, and
  `register_map.py` builds `ipxact.MemoryMap` from a SystemRDL file. `qualifiers.py` finds
  the clock and reset ports, from the metadata file or their names.
- **`register_map.py` builds the memory map from `systemrdl-compiler`'s node tree**, straight
  into `ipxact-compiler`'s IEEE 1685-2022 dataclasses, with no intermediate XML.
- **Fails loudly instead of silently dropping data.** Constructs this package does not yet
  support (see below) raise `NotImplementedError`/`ValueError` rather than producing a
  `Component` that quietly leaves something out.

## Known limitations

- **Explicit ANSI ports** (`.name(expr)` syntax) **and non-ANSI port lists** (`module m(a, b);
  input a; ...`) **are not supported.** Only implicit ANSI-style ports are.
  A direction-less first port defaults to `inout`, per the SystemVerilog LRM.
- **Only `[left:right]` dimensions are supported**, plus the `[N]` size shorthand on an unpacked
  dimension. Indexed part-selects (`[base+:width]`/`[base-:width]`), queues (`[$]`), dynamic
  arrays (`[]`) and a zero size (`[0]`) raise an error.
- **Ports with a data type that has no bit width are not supported**: `real`, `shortreal`,
  `realtime`, `string`, `chandle`, `event`. Built-in integer types get their width as a
  vector, e.g. `int` gives `[31:0]` and `byte` gives `[7:0]`.
- **A parameter without a default value is not supported** (`parameter int N` or
  `parameter type T` with no `= ...`), as there is no value to give the component parameter.
  Parameters are read from the parameter port list (`#(...)`), or from the module body when
  the module has none, `localparam`s being skipped, per the SystemVerilog LRM.
- **A `registerFile` defining an `addrmap` that is never used under the chosen top-level
  `addrmap` is rejected**, rather than silently ignored as SystemRDL itself would. A reusable
  sub-block `addrmap` instantiated under a real top is unaffected, and so is an unused
  `addrmap` of an `` `include ``d file.
- **A register/field/register file/address block with `ispresent = false` is not supported.**
  IEEE 1685-2022 has no equivalent of `isPresent`, so there is no way to represent one as
  conditionally absent rather than silently promoting it to always-present.
- **A SystemRDL construct IEEE 1685-2022 cannot represent raises an error**, rather than
  silently producing an incomplete memory map:
  - a `mem` that is not a child of a top `addrmap` holding only `addrmap`s and `mem`s, as an
    address block or register file cannot hold a memory;
  - a `bridge` `addrmap`;
  - a field `reset` that is a reference to another field or signal;
  - an `alias` register in an array, or in an array of register files: each alias element
    refers to the primary element of the same index, which an IP-XACT reference cannot say;
  - two different reset signals with the same name, or one named `HARD`, as a reset type is
    named after its signal.

  A compiler warning raises an error too, and a compile error gives the compiler's messages,
  with their file and line.
- **A register's `accesswidth` is not represented**, its `size` is its `regwidth`.
- **`fileSets` are not generated.** The component never records which `.sv` file the module
  actually came from.

## Ideas for later

- **Give `registerFile`'s compile options (user-defined properties, include directories,
  parameter overrides) a metadata file or CLI form.** Only available from Python for now,
  see [Register maps](#register-maps).

## License

LGPL-3.0. See [LICENSE](LICENSE).
