xactflow-archidesc 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ __version__ = "0.1.0"
2
+
3
+ import runpy
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import ipxact
8
+ from xactflow import Importer
9
+
10
+ from .design import BusInterfaceRef, Design, IPInstance, PortRef
11
+
12
+
13
+ class ArchiDescImporter(Importer):
14
+ """Runs a Python design description script and returns the ipxact.Design it describes.
15
+
16
+ The script must define a module-level variable named `design`, holding a Design. It runs
17
+ like `python script.py` would: its own folder is importable while it runs.
18
+ """
19
+
20
+ name = "archidesc"
21
+
22
+ def import_(self, source_path: Path, **options: object) -> ipxact.Design:
23
+ if options:
24
+ raise ValueError(f"the archidesc importer takes no options, got: {', '.join(options)}")
25
+ source_path = Path(source_path)
26
+ if not source_path.is_file():
27
+ raise ValueError(f"{source_path} is not a file")
28
+ sys.path.insert(0, str(source_path.parent))
29
+ try:
30
+ namespace = runpy.run_path(str(source_path))
31
+ finally:
32
+ sys.path.remove(str(source_path.parent))
33
+ if "design" not in namespace:
34
+ raise ValueError(f"{source_path} must define a module-level variable 'design'")
35
+ design = namespace["design"]
36
+ if not isinstance(design, Design):
37
+ kind = type(design)
38
+ raise ValueError(
39
+ f"{source_path}: 'design' must be a xactflow_archidesc.Design, got {kind.__module__}.{kind.__qualname__}"
40
+ )
41
+ return design.build()
42
+
43
+
44
+ __all__ = ["__version__", "ArchiDescImporter", "BusInterfaceRef", "Design", "IPInstance", "PortRef"]
@@ -0,0 +1,474 @@
1
+ """design.py: the Design object a design description script builds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import re
7
+ from dataclasses import asdict, dataclass, field
8
+ from typing import Any, Dict, FrozenSet, List, Optional, Sequence, Set, Tuple, Union
9
+ from xml.sax.saxutils import quoteattr
10
+
11
+ import ipxact
12
+ from xactflow import Library
13
+
14
+ # Namespace of the vendor extensions this importer writes.
15
+ XACTFLOW_NAMESPACE = "https://github.com/IP-XACT/XactFlow"
16
+
17
+ # IP-XACT's naming rule for an instance name (an XML Name in the schema). ":" is also allowed
18
+ # there but left out.
19
+ _INSTANCE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_.-]*")
20
+
21
+ _Direction = ipxact.Direction
22
+ _Mode = ipxact.InterfaceMode
23
+
24
+ # The directions each wire port direction can be connected to by connect().
25
+ _CONNECTABLE = {
26
+ _Direction.IN: {_Direction.OUT, _Direction.INOUT},
27
+ _Direction.OUT: {_Direction.IN, _Direction.INOUT},
28
+ _Direction.INOUT: {_Direction.IN, _Direction.OUT, _Direction.INOUT},
29
+ }
30
+
31
+ # The bus interface modes that can be connected together (IEEE 1685-2022 SCR 2.4, 2.5, 2.8, 2.9).
32
+ _MODE_PAIRS = {
33
+ frozenset((_Mode.INITIATOR, _Mode.TARGET)),
34
+ frozenset((_Mode.INITIATOR, _Mode.MIRRORED_INITIATOR)),
35
+ frozenset((_Mode.MIRRORED_TARGET, _Mode.TARGET)),
36
+ frozenset((_Mode.SYSTEM, _Mode.MIRRORED_SYSTEM)),
37
+ }
38
+
39
+ # connect_bus() picks among these modes by itself. Any other mode must be named with .bus(name).
40
+ _AUTO_MODES = {_Mode.INITIATOR, _Mode.TARGET}
41
+
42
+ # The modes that act as the target of a connection, where the address mapping goes.
43
+ _TARGET_SIDE_MODES = {_Mode.TARGET, _Mode.MIRRORED_INITIATOR}
44
+
45
+
46
+ def _find(items: Sequence[Any], name: str, owner: str, kind: str) -> Any:
47
+ """Return the item called name, or raise ValueError listing the names that do exist."""
48
+ for item in items:
49
+ if item.name == name:
50
+ return item
51
+ available = ", ".join(item.name for item in items) or "none"
52
+ raise ValueError(f"{owner} has no {kind} {name!r}. Available {kind}s: {available}")
53
+
54
+
55
+ class IPInstance:
56
+ """A handle on one component instance"""
57
+
58
+ def __init__(self, name: str, component: ipxact.Component) -> None:
59
+ self.name = name
60
+ self.component = component
61
+
62
+ def port(self, name: str) -> PortRef:
63
+ ports = self.component.model.ports if self.component.model is not None else []
64
+ port = _find(ports, name, repr(self), "port")
65
+ return PortRef(self, port.name, port)
66
+
67
+ def bus(self, name: str) -> BusInterfaceRef:
68
+ bus_interface = _find(self.component.bus_interfaces, name, repr(self), "bus interface")
69
+ return BusInterfaceRef(self, bus_interface.name, bus_interface)
70
+
71
+ def __getattr__(self, name: str) -> PortRef:
72
+ # Python only calls this for names that are not real attributes. Names starting with "_"
73
+ # are Python's own lookups, so they stay normal missing attributes.
74
+ if name.startswith("_"):
75
+ raise AttributeError(name)
76
+ return self.port(name)
77
+
78
+ def __repr__(self) -> str:
79
+ return f"IPInstance({self.name!r}, {self.component.vlnv})"
80
+
81
+
82
+ # Two refs are equal when they point at the same instance and name. The ipxact object they
83
+ # carry is left out of comparing, hashing and printing, it is only there to be read.
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class PortRef:
88
+ """One port of one component instance, used by Design.connect()."""
89
+
90
+ instance: IPInstance
91
+ name: str
92
+ port: ipxact.Port = field(compare=False, repr=False)
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class BusInterfaceRef:
97
+ """One bus interface of one component instance, used by Design.connect_bus()."""
98
+
99
+ instance: IPInstance
100
+ name: str
101
+ bus_interface: ipxact.BusInterface = field(compare=False, repr=False)
102
+
103
+
104
+ def _port_kind(ref: PortRef) -> str:
105
+ if ref.port.wire is not None:
106
+ return "wire"
107
+ return "transactional" if ref.port.transactional is not None else "structured"
108
+
109
+
110
+ def _describe(ref: PortRef) -> str:
111
+ detail = ref.port.wire.direction.value if ref.port.wire is not None else _port_kind(ref)
112
+ return f"{ref.instance.name}.{ref.name} ({detail})"
113
+
114
+
115
+ def _port_problem(source: PortRef, target: PortRef) -> Optional[str]:
116
+ """Return why the two ports cannot be connected, or None if they can.
117
+
118
+ Only wire ports have their direction checked. Two transactional or two structured ports are
119
+ connected as they are.
120
+ """
121
+ if source == target:
122
+ return "cannot connect a port to itself"
123
+ kinds = (_port_kind(source), _port_kind(target))
124
+ if kinds[0] != kinds[1]:
125
+ return f"cannot connect a {kinds[0]} port to a {kinds[1]} port"
126
+ if kinds[0] != "wire":
127
+ return None
128
+ directions = (source.port.wire.direction, target.port.wire.direction)
129
+ if _Direction.PHANTOM in directions:
130
+ return "a phantom port cannot be connected"
131
+ if directions[1] not in _CONNECTABLE[directions[0]]:
132
+ return "needs one 'in' and one 'out' port, or an 'inout' one"
133
+ return None
134
+
135
+
136
+ def _describe_bus(ref: BusInterfaceRef) -> str:
137
+ bus = ref.bus_interface
138
+ return f"{ref.instance.name}.{ref.name} ({bus.bus_type.vlnv}, {bus.mode.value})"
139
+
140
+
141
+ def _label(side: object) -> str:
142
+ """How a connect_bus() side is shown in messages: "cpu", or "cpu.bus_if" when named."""
143
+ if isinstance(side, BusInterfaceRef):
144
+ return f"{side.instance.name}.{side.name}"
145
+ return side.name if isinstance(side, IPInstance) else repr(side)
146
+
147
+
148
+ def _watches(monitor: ipxact.BusInterface, other: ipxact.BusInterface) -> bool:
149
+ return monitor.mode == _Mode.MONITOR and monitor.monitor.interface_mode == other.mode
150
+
151
+
152
+ def _can_connect(a: BusInterfaceRef, b: BusInterfaceRef) -> bool:
153
+ """Same bus type, and modes that can be connected, or a monitor of the other side's mode.
154
+
155
+ Only the bus VLNV is compared for now, not the parameter values set on the bus type.
156
+ """
157
+ bus_a, bus_b = a.bus_interface, b.bus_interface
158
+ if bus_a.bus_type.vlnv != bus_b.bus_type.vlnv:
159
+ return False
160
+ return frozenset((bus_a.mode, bus_b.mode)) in _MODE_PAIRS or _watches(bus_a, bus_b) or _watches(bus_b, bus_a)
161
+
162
+
163
+ def _no_match_reason(candidates_a: List[BusInterfaceRef], candidates_b: List[BusInterfaceRef]) -> str:
164
+ if not candidates_a or not candidates_b:
165
+ return "one side has no free bus interface to use"
166
+ same_bus = any(x.bus_interface.bus_type.vlnv == y.bus_interface.bus_type.vlnv for x in candidates_a for y in candidates_b)
167
+ return "their modes cannot be connected" if same_bus else "they share no bus type"
168
+
169
+
170
+ def _active_interface(ref: BusInterfaceRef, address_mapping: List[str]) -> ipxact.ActiveInterface:
171
+ """One side of an interconnection. The address mapping only goes on the target side."""
172
+ on_target_side = ref.bus_interface.mode in _TARGET_SIDE_MODES
173
+ return ipxact.ActiveInterface(
174
+ component_instance_ref=ref.instance.name,
175
+ bus_ref=ref.name,
176
+ vendor_extensions=list(address_mapping) if on_target_side else [],
177
+ )
178
+
179
+
180
+ def _monitor_interface(ref: BusInterfaceRef) -> ipxact.MonitorInterfaceRef:
181
+ return ipxact.MonitorInterfaceRef(component_instance_ref=ref.instance.name, bus_ref=ref.name)
182
+
183
+
184
+ @dataclass
185
+ class _InstanceRecord:
186
+ instance: IPInstance
187
+ component_instance: ipxact.ComponentInstance
188
+ call_site: str
189
+
190
+
191
+ def _caller_site() -> str:
192
+ """Return "file:line" of the code that called the public Design method."""
193
+ caller = inspect.currentframe().f_back.f_back # skip _caller_site itself, then the Design method
194
+ return f"{caller.f_code.co_filename}:{caller.f_lineno}"
195
+
196
+
197
+ def _address_mapping_extensions(where: str, base_addr: Optional[int], size: Optional[int]) -> List[str]:
198
+ """Turn connect_bus()'s base_addr and size into a vendor extension, if either is given."""
199
+ attributes = ""
200
+ for attribute, value, minimum in (("baseAddr", base_addr, 0), ("size", size, 1)):
201
+ if value is None:
202
+ continue
203
+ if isinstance(value, bool) or not isinstance(value, int):
204
+ raise TypeError(f"{where}: {attribute} must be an int, got {type(value).__name__}: {value!r}")
205
+ if value < minimum:
206
+ raise ValueError(f"{where}: {attribute} must be at least {minimum}, got: {value}")
207
+ attributes += f' {attribute}="0x{value:X}"'
208
+ if not attributes:
209
+ return []
210
+ return [f'<xactflow:addressMapping xmlns:xactflow="{XACTFLOW_NAMESPACE}"{attributes}/>']
211
+
212
+
213
+ def _check_type(value: object, expected: type, what: str) -> None:
214
+ """Raise TypeError if value is not of the expected type."""
215
+ if not isinstance(value, expected):
216
+ raise TypeError(f"{what} must be a {expected.__name__}, got {type(value).__name__}: {value!r}")
217
+
218
+
219
+ def _parse_vlnv(value: object, what: str) -> ipxact.VLNV:
220
+ _check_type(value, str, what)
221
+ fields = value.split(":")
222
+ if len(fields) != 4 or not all(fields):
223
+ raise ValueError(f"{what} must be a 'vendor:library:name:version' string, got: {value!r}")
224
+ return ipxact.VLNV(*fields)
225
+
226
+
227
+ def _expression(value: object, what: str) -> str:
228
+ """Write a Python value as an IP-XACT expression string."""
229
+ if isinstance(value, bool): # before int, since bool is an int
230
+ return "true" if value else "false"
231
+ if isinstance(value, (int, float, str)):
232
+ return str(value)
233
+ raise TypeError(f"{what} must be an int, float, bool or str, got {type(value).__name__}: {value!r}")
234
+
235
+
236
+ def _config_element_values(
237
+ where: str, component: ipxact.Component, parameters: Optional[Dict[str, object]]
238
+ ) -> Dict[str, str]:
239
+ """Turn add_ip()'s parameter overrides into configurableElementValues, keyed by parameterId.
240
+
241
+ Only a parameter with resolve="user" can be overridden. The standard says an "immediate"
242
+ one cannot be modified through configuration, and a "generated" one is set by generators.
243
+ """
244
+ if parameters is None:
245
+ return {}
246
+ _check_type(parameters, dict, f"{where}: parameters")
247
+ values = {}
248
+ for name, value in parameters.items():
249
+ parameter = _find(component.parameters, name, f"{where}: {component.vlnv}", "parameter")
250
+ if parameter.parameter_id is None or parameter.resolve != "user":
251
+ raise ValueError(
252
+ f"{where}: parameter {name!r} of {component.vlnv} cannot be overridden, it needs a "
253
+ f"parameterId and resolve=\"user\" (it has parameterId={parameter.parameter_id!r}, "
254
+ f"resolve={parameter.resolve!r}). This needs fixing in the component file"
255
+ )
256
+ values[parameter.parameter_id] = _expression(value, f"{where}: parameter {name!r}")
257
+ return values
258
+
259
+
260
+ def _transforms_extensions(where: str, transforms: Optional[List[str]]) -> List[str]:
261
+ """Turn add_ip()'s transforms into vendor extensions on the component instance.
262
+
263
+ The transformations are only recorded here, a separate transformer applies them later.
264
+ """
265
+ transforms = [] if transforms is None else transforms
266
+ if not isinstance(transforms, (list, tuple)) or not all(isinstance(t, str) and t for t in transforms):
267
+ raise TypeError(f"{where}: transforms must be a list of non-empty strings, got: {transforms!r}")
268
+ if not transforms:
269
+ return []
270
+ items = "".join(f"<xactflow:transform name={quoteattr(name)}/>" for name in transforms)
271
+ return [f'<xactflow:transforms xmlns:xactflow="{XACTFLOW_NAMESPACE}">{items}</xactflow:transforms>']
272
+
273
+
274
+ class Design:
275
+ """Describes one flat design: its component instances and how they are connected.
276
+
277
+ build() turns it into an ipxact.Design.
278
+ """
279
+
280
+ def __init__(self, vlnv: str, library: Library) -> None:
281
+ self.vlnv = _parse_vlnv(vlnv, "Design(): vlnv")
282
+ self.library = library
283
+ self._instances: Dict[str, _InstanceRecord] = {}
284
+ self._ad_hoc_connections: Dict[FrozenSet[PortRef], ipxact.AdHocConnection] = {}
285
+ self._interconnections: List[ipxact.Interconnection] = []
286
+ self._monitor_interconnections: List[ipxact.MonitorInterconnection] = []
287
+ # Names of every connection of any kind, so that no two get the same name.
288
+ self._connection_names: Set[str] = set()
289
+ # Each "in" wire port already driven, and each bus interface already connected, with the
290
+ # name of the connection using it.
291
+ self._driven_ports: Dict[PortRef, str] = {}
292
+ self._used_bus_interfaces: Dict[BusInterfaceRef, str] = {}
293
+
294
+ def add_ip(
295
+ self,
296
+ instance_name: str,
297
+ vlnv: str,
298
+ parameters: Optional[Dict[str, object]] = None,
299
+ transforms: Optional[List[str]] = None,
300
+ ) -> IPInstance:
301
+ """Add one component instance, resolving its VLNV against the library right away."""
302
+ call_site = _caller_site()
303
+ self._check_new_instance_name(instance_name, call_site)
304
+ where = f"add_ip('{instance_name}')"
305
+ component_vlnv = _parse_vlnv(vlnv, f"{where}: vlnv")
306
+ component = self._resolve_component(where, component_vlnv)
307
+
308
+ component_instance = ipxact.ComponentInstance(
309
+ instance_name=instance_name,
310
+ component_ref=ipxact.VLNVRef(
311
+ **asdict(component_vlnv),
312
+ config_element_values=_config_element_values(where, component, parameters),
313
+ ),
314
+ vendor_extensions=_transforms_extensions(where, transforms),
315
+ )
316
+ instance = IPInstance(instance_name, component)
317
+ self._instances[instance_name] = _InstanceRecord(instance, component_instance, call_site)
318
+ return instance
319
+
320
+ def connect(self, source: PortRef, target: PortRef) -> None:
321
+ """Add one ad hoc connection between two whole ports."""
322
+ for what, ref in (("connect(): source", source), ("connect(): target", target)):
323
+ _check_type(ref, PortRef, what)
324
+ self._check_instance(ref.instance, what)
325
+ where = f"connect({_describe(source)}, {_describe(target)})"
326
+ problem = _port_problem(source, target)
327
+ if problem is not None:
328
+ raise ValueError(f"{where}: {problem}")
329
+ ports = frozenset((source, target))
330
+ if ports in self._ad_hoc_connections:
331
+ raise ValueError(f"{where}: these two ports are already connected")
332
+ driven = [ref for ref in (source, target) if ref.port.wire is not None and ref.port.wire.direction == _Direction.IN]
333
+ for ref in driven:
334
+ if ref in self._driven_ports:
335
+ raise ValueError(f"{where}: {_describe(ref)} is already driven by {self._driven_ports[ref]}")
336
+
337
+ name = self._new_connection_name(f"{source.instance.name}_{source.name}_to_{target.instance.name}_{target.name}")
338
+ self._ad_hoc_connections[ports] = ipxact.AdHocConnection(
339
+ name=name,
340
+ internal_port_references=[
341
+ ipxact.InternalPortReference(component_instance_ref=ref.instance.name, port_ref=ref.name)
342
+ for ref in (source, target)
343
+ ],
344
+ )
345
+ self._driven_ports.update((ref, name) for ref in driven)
346
+
347
+ def connect_bus(
348
+ self,
349
+ a: Union[IPInstance, BusInterfaceRef],
350
+ b: Union[IPInstance, BusInterfaceRef],
351
+ *,
352
+ base_addr: Optional[int] = None,
353
+ size: Optional[int] = None,
354
+ ) -> None:
355
+ """Connect one bus interface of a to one bus interface of b.
356
+
357
+ A side given as an IPInstance uses whichever of its free initiator or target interfaces
358
+ matches. A side given as a BusInterfaceRef uses exactly that one, whatever its mode. A
359
+ monitor interface becomes a monitor interconnection, watching the other side.
360
+ """
361
+ where = f"connect_bus({_label(a)}, {_label(b)})"
362
+ address_mapping = _address_mapping_extensions(where, base_addr, size)
363
+ instance_a, candidates_a = self._bus_side(a, f"{where}: a")
364
+ instance_b, candidates_b = self._bus_side(b, f"{where}: b")
365
+ if instance_a is instance_b:
366
+ raise ValueError(f"{where}: cannot connect an instance to itself")
367
+
368
+ pairs = [(x, y) for x in candidates_a for y in candidates_b if _can_connect(x, y)]
369
+ if not pairs:
370
+ tried = ", ".join(map(_describe_bus, candidates_a + candidates_b)) or "nothing"
371
+ raise ValueError(
372
+ f"{where}: nothing to connect, {_no_match_reason(candidates_a, candidates_b)}. Tried: {tried}"
373
+ )
374
+ if len(pairs) > 1:
375
+ choices = ", ".join(f"{_label(x)} with {_label(y)}" for x, y in pairs)
376
+ raise ValueError(f"{where}: more than one possible pair ({choices}). Pick one with .bus(name)")
377
+ [(ref_a, ref_b)] = pairs
378
+
379
+ # A monitor only watches the other side, which stays free for a normal connection.
380
+ monitor = next((ref for ref in (ref_a, ref_b) if ref.bus_interface.mode == _Mode.MONITOR), None)
381
+ connected = [monitor] if monitor is not None else [ref_a, ref_b]
382
+ for ref in connected:
383
+ if ref in self._used_bus_interfaces:
384
+ raise ValueError(f"{where}: {_label(ref)} is already used by {self._used_bus_interfaces[ref]}")
385
+ has_target_side = any(ref.bus_interface.mode in _TARGET_SIDE_MODES for ref in (ref_a, ref_b))
386
+ if address_mapping and (monitor is not None or not has_target_side):
387
+ raise ValueError(f"{where}: base_addr and size need a connection with a target side")
388
+
389
+ name = self._new_connection_name(f"{instance_a.name}_to_{instance_b.name}")
390
+ if monitor is not None:
391
+ watched = ref_b if monitor is ref_a else ref_a
392
+ self._monitor_interconnections.append(
393
+ ipxact.MonitorInterconnection(
394
+ name=name,
395
+ monitored_active_interface=_monitor_interface(watched),
396
+ monitor_interfaces=[_monitor_interface(monitor)],
397
+ )
398
+ )
399
+ else:
400
+ self._interconnections.append(
401
+ ipxact.Interconnection(
402
+ name=name,
403
+ active_interface=_active_interface(ref_a, address_mapping),
404
+ other_active_interfaces=[_active_interface(ref_b, address_mapping)],
405
+ )
406
+ )
407
+ self._used_bus_interfaces.update((ref, name) for ref in connected)
408
+
409
+ def build(self) -> ipxact.Design:
410
+ """Return the ipxact.Design described so far."""
411
+ return ipxact.Design(
412
+ vlnv=self.vlnv,
413
+ component_instances=[record.component_instance for record in self._instances.values()],
414
+ interconnections=list(self._interconnections),
415
+ monitor_interconnections=list(self._monitor_interconnections),
416
+ ad_hoc_connections=list(self._ad_hoc_connections.values()),
417
+ )
418
+
419
+ def _new_connection_name(self, base: str) -> str:
420
+ """Return base, or base with a number added if a connection already has that name."""
421
+ name, number = base, 1
422
+ while name in self._connection_names:
423
+ number += 1
424
+ name = f"{base}_{number}"
425
+ self._connection_names.add(name)
426
+ return name
427
+
428
+ def _check_new_instance_name(self, instance_name: object, call_site: str) -> None:
429
+ _check_type(instance_name, str, "add_ip(): instance name")
430
+ if not _INSTANCE_NAME.fullmatch(instance_name):
431
+ raise ValueError(
432
+ f"add_ip(): instance name must start with a letter or '_', not a digit, followed by letters, "
433
+ f"digits, '_', '.' or '-' (IP-XACT naming rule), got: {instance_name!r}"
434
+ )
435
+ earlier = self._instances.get(instance_name)
436
+ if earlier is not None:
437
+ raise ValueError(
438
+ f"add_ip() at {call_site}: instance name '{instance_name}' is already used "
439
+ f"by add_ip() at {earlier.call_site}"
440
+ )
441
+
442
+ def _check_instance(self, instance: IPInstance, what: str) -> None:
443
+ """Check that instance was added to this design."""
444
+ record = self._instances.get(instance.name)
445
+ if record is None or record.instance is not instance:
446
+ raise ValueError(f"{what}: {instance!r} was not added to this design")
447
+
448
+ def _bus_side(self, side: object, what: str) -> Tuple[IPInstance, List[BusInterfaceRef]]:
449
+ """Return the instance of one connect_bus() side, and the bus interfaces to try: the one
450
+ given, or the instance's initiators and targets that no connect_bus() has used yet."""
451
+ if isinstance(side, BusInterfaceRef):
452
+ instance, candidates = side.instance, [side]
453
+ elif isinstance(side, IPInstance):
454
+ instance = side
455
+ candidates = [
456
+ ref
457
+ for ref in (BusInterfaceRef(side, bus.name, bus) for bus in side.component.bus_interfaces)
458
+ if ref.bus_interface.mode in _AUTO_MODES and ref not in self._used_bus_interfaces
459
+ ]
460
+ else:
461
+ raise TypeError(f"{what} must be an IPInstance or a BusInterfaceRef, got {type(side).__name__}: {side!r}")
462
+ self._check_instance(instance, what)
463
+ return instance, candidates
464
+
465
+ def _resolve_component(self, where: str, vlnv: ipxact.VLNV) -> ipxact.Component:
466
+ document = self.library.get(vlnv)
467
+ if document is None:
468
+ message = f"{where}: no document with VLNV {vlnv} in the library"
469
+ if self.library.diagnostics:
470
+ message += f" (library.diagnostics has {len(self.library.diagnostics)} entries, a file may have failed to load)"
471
+ raise ValueError(message)
472
+ if not isinstance(document, ipxact.Component):
473
+ raise ValueError(f"{where}: VLNV {vlnv} is a {type(document).__name__}, not a Component")
474
+ return document
File without changes
@@ -0,0 +1,186 @@
1
+ Metadata-Version: 2.4
2
+ Name: xactflow-archidesc
3
+ Version: 0.1.0
4
+ Summary: XactFlow importer plugin that serializes an architecture description into an ipxact.Design.
5
+ Author: Maxime Travaillard
6
+ License-Expression: LGPL-3.0-only
7
+ Project-URL: Repository, https://github.com/IP-XACT/XactFlow-archidesc
8
+ Project-URL: Issues, https://github.com/IP-XACT/XactFlow-archidesc/issues
9
+ Keywords: IP-XACT,IEEE 1685,XML,Compiler,XactFlow,Architecture,Design,Importer
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: xactflow
24
+ Requires-Dist: ipxact-compiler
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest; extra == "dev"
27
+ Requires-Dist: xactflow-design; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # xactflow-archidesc
31
+
32
+ A [XactFlow](https://github.com/IP-XACT/XactFlow) importer plugin that turns a design described
33
+ in a Python script (which IPs it uses, and how they are connected) into an `ipxact.Design` object,
34
+ built on [`ipxact-compiler`](https://github.com/IP-XACT/ipxact-compiler)'s
35
+ [IEEE 1685-2022](https://standards.ieee.org/ieee/1685/10307/) object model.
36
+
37
+ IP-XACT `design` files are not made to be handwritten. With this package, a short script lists
38
+ the IP instances, the bus connections between them, and any direct signal connections. The
39
+ importer runs the script and returns the `Design`, which XactFlow's `elaborate()` can then check
40
+ against the IP-XACT rules.
41
+
42
+ The full description of the format is in
43
+ [`doc/python-design-description.md`](doc/python-design-description.md). It describes the tool
44
+ as it is meant to work once finished, so the current version can differ from it in small ways.
45
+ The differences known today are listed in [Known limitations](#known-limitations).
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ pip install xactflow-archidesc
51
+ ```
52
+
53
+ For local development, `requirements-dev.txt` overrides `ipxact-compiler`, `xactflow` and
54
+ `xactflow-design` to local installations. It can be modified to adapt the paths or to keep any
55
+ of them on PyPI.
56
+
57
+ ```bash
58
+ pip install -r requirements-dev.txt -e .
59
+ ```
60
+
61
+ Requires Python >= 3.9.
62
+
63
+ ## Usage
64
+
65
+ A design script builds a `Design` from an IP library and keeps it in a module-level variable
66
+ named `design`:
67
+
68
+ ```python
69
+ from pathlib import Path
70
+
71
+ from xactflow import Library
72
+ from xactflow_archidesc import Design
73
+
74
+ library = Library.scan(Path(__file__).parent / "ip")
75
+ design = Design("example.org:soc:example:0.1", library)
76
+
77
+ cpu = design.add_ip("cpu", "example.org:ip:cpu:1.0", transforms=["tmrg"])
78
+ uart = design.add_ip("uart", "example.org:ip:uart:1.0", parameters={"BAUDRATE": 115200})
79
+ timer = design.add_ip("timer", "example.org:ip:timer:1.0")
80
+ debug = design.add_ip("debug", "example.org:ip:debug_module:1.0")
81
+ bus = design.add_ip("bus", "example.org:ip:interconnect:1.0")
82
+
83
+ design.connect_bus(cpu, bus)
84
+ design.connect_bus(bus.bus("m0"), uart, base_addr=0x4001_0000, size=0x1000)
85
+ design.connect_bus(bus, timer, base_addr=0x4002_0000, size=0x1000)
86
+
87
+ design.connect(debug.debug_req_o, cpu.debug_req_i)
88
+ design.connect(cpu.debug_resp_o, debug.debug_resp_i)
89
+ ```
90
+
91
+ A runnable version of this script, with its IP library, is in
92
+ [`tests/fixtures/soc.py`](tests/fixtures/soc.py).
93
+
94
+ In short:
95
+
96
+ - `add_ip(name, vlnv, ...)` adds an IP instance, with optional `parameters` overrides and
97
+ `transforms`.
98
+ - `connect_bus(a, b, ...)` connects a bus interface of `a` to one of `b`. It picks them by
99
+ itself, or uses the one named with `instance.bus("name")`. `base_addr`/`size` place a target
100
+ in the address map.
101
+ - `connect(source, target)` connects two ports. `instance.some_port` is short for
102
+ `instance.port("some_port")`.
103
+
104
+ Each call checks its arguments right away, so a mistake is reported on the line that made it.
105
+ All the details are in [the format description](doc/python-design-description.md#the-design-object).
106
+
107
+ Once installed, the importer registers itself under the `xactflow.importers` entry point group
108
+ as `archidesc`, so it runs as a XactFlow CLI command. With `xactflow-design` installed too,
109
+ `--then` hands the result straight to that exporter. To try it on the example of this repo,
110
+ create a virtual environment and install the package in it first. The `xactflow` command only
111
+ exists inside that environment, so activate it again in each new terminal:
112
+
113
+ ```bash
114
+ python3 -m venv .venv && source .venv/bin/activate
115
+ pip install -e ".[dev]"
116
+ xactflow archidesc tests/fixtures/soc.py --then design --output out/
117
+ ```
118
+
119
+ This writes `out/example.xml`, named after the design's VLNV name.
120
+
121
+ Or as a library, for example to elaborate the design first:
122
+
123
+ ```python
124
+ from pathlib import Path
125
+
126
+ from xactflow import Library, elaborate
127
+ from xactflow_archidesc import ArchiDescImporter
128
+ from xactflow_design import DesignExporter
129
+
130
+ design = ArchiDescImporter().import_(Path("soc.py"))
131
+ elaborated = elaborate(design, Library.scan("ip"))
132
+ DesignExporter().export(design, Path("out"))
133
+ ```
134
+
135
+ The script runs like `python soc.py` would: a helper module next to it can be imported, and a
136
+ relative path in it is read from the current folder. `Path(__file__).parent` gives paths
137
+ that do not depend on where the command is run from. The importer takes no options.
138
+
139
+ ## Design notes
140
+
141
+ - **Vendor extensions.** Two things this format records have no place in IP-XACT, so they are
142
+ written as vendor extensions in the `https://github.com/IP-XACT/XactFlow` namespace:
143
+ `<xactflow:transforms>` on a component instance, listing the transformations in order, and
144
+ `<xactflow:addressMapping baseAddr="..." size="..."/>` on the target side of a bus
145
+ connection (a target or mirrored initiator interface).
146
+ - **Transformations are not applied here.** A separate tool, a transformer, reads
147
+ `<xactflow:transforms>`, applies the transformations and returns the changed `Design`.
148
+ - **Parameter overrides follow the standard.** Only a parameter with a `parameterId` and
149
+ `resolve="user"` can be overridden. The standard says an `immediate` parameter (the default)
150
+ cannot be changed through configuration.
151
+ - **Connection names are unique.** A bus connection is named `<a>_to_<b>` and a port connection
152
+ `<instance>_<port>_to_<instance>_<port>`. A number is added when a name is already taken, by
153
+ any kind of connection.
154
+ - **Monitors.** Connecting a monitor interface adds a `monitorInterconnection`. The interface it
155
+ watches stays free for a normal connection.
156
+
157
+ ## Known limitations
158
+
159
+ - `connect_bus` compares the bus VLNV of the two interfaces, but not the parameter values set
160
+ on the bus type (a data width, for example). Comparing them needs XactFlow to evaluate
161
+ those values first. This should be changed in a future update.
162
+ - XactFlow's `elaborate()` does not use the parameter overrides from `add_ip` yet. They are
163
+ written to the design and exported, but not applied during elaboration.
164
+ - `connect` checks direction only for wire ports. Two transactional or two structured ports
165
+ are connected with no further check, only a mix of the two kinds is refused.
166
+ - `connect` does not compare port widths.
167
+ - A design describes one level only. Hierarchical designs, a real address mapping (instead of
168
+ the `addressMapping` placeholder) and protocol bridges are not handled yet, see the open
169
+ questions at the end of [the format description](doc/python-design-description.md).
170
+
171
+ ## Development
172
+
173
+ ```bash
174
+ python3 -m venv .venv
175
+ source .venv/bin/activate
176
+ pip install -r requirements-dev.txt -e .
177
+ pytest
178
+ ```
179
+
180
+ The tests use a small IP library in `tests/fixtures/library`. `tests/test_end_to_end.py` runs
181
+ the example script through the importer, elaborates the result, exports it with
182
+ `xactflow-design` and reads the file back.
183
+
184
+ ## License
185
+
186
+ LGPL-3.0. See [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ xactflow_archidesc/__init__.py,sha256=yTxSxX-tm1avfhm22FJL4vH_WLEUY4oVHe1G32RYrHk,1587
2
+ xactflow_archidesc/design.py,sha256=yscDFicctf_Ih2iXKj6NQXs90ep47AdQ_lwUI_ZSuFc,21564
3
+ xactflow_archidesc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ xactflow_archidesc-0.1.0.dist-info/licenses/LICENSE,sha256=7pB5GeyIycAXsfi2CNsglgtlmK78xP5YggvelV1l7Tw,7651
5
+ xactflow_archidesc-0.1.0.dist-info/METADATA,sha256=wPaIA7AFmsBFG1Kr-_x5kqecD07Yj06zaT31BuGu2i4,8094
6
+ xactflow_archidesc-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
7
+ xactflow_archidesc-0.1.0.dist-info/entry_points.txt,sha256=ZI-P-9ATmsHVT-KEHsRP1wE0pNr44nfpdSIe3iaXAIU,70
8
+ xactflow_archidesc-0.1.0.dist-info/top_level.txt,sha256=X3oWkPAI7KnjqGWjhz9FC62r0CV2sPm8WmG602Vqumg,19
9
+ xactflow_archidesc-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [xactflow.importers]
2
+ archidesc = xactflow_archidesc:ArchiDescImporter
@@ -0,0 +1,164 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ This version of the GNU Lesser General Public License incorporates
9
+ the terms and conditions of version 3 of the GNU General Public
10
+ License, supplemented by the additional permissions listed below.
11
+
12
+ 0. Additional Definitions.
13
+
14
+ As used herein, "this License" refers to version 3 of the GNU Lesser
15
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
16
+ General Public License.
17
+
18
+ "The Library" refers to a covered work governed by this License,
19
+ other than an Application or a Combined Work as defined below.
20
+
21
+ An "Application" is any work that makes use of an interface provided
22
+ by the Library, but which is not otherwise based on the Library.
23
+ Defining a subclass of a class defined by the Library is deemed a mode
24
+ of using an interface provided by the Library.
25
+
26
+ A "Combined Work" is a work produced by combining or linking an
27
+ Application with the Library. The particular version of the Library
28
+ with which the Combined Work was made is also called the "Linked
29
+ Version".
30
+
31
+ The "Minimal Corresponding Source" for a Combined Work means the
32
+ Corresponding Source for the Combined Work, excluding any source code
33
+ for portions of the Combined Work that, considered in isolation, are
34
+ based on the Application, and not on the Linked Version.
35
+
36
+ The "Corresponding Application Code" for a Combined Work means the
37
+ object code and/or source code for the Application, including any data
38
+ and utility programs needed for reproducing the Combined Work from the
39
+ Application, but excluding the System Libraries of the Combined Work.
40
+
41
+ 1. Exception to Section 3 of the GNU GPL.
42
+
43
+ You may convey a covered work under sections 3 and 4 of this License
44
+ without being bound by section 3 of the GNU GPL.
45
+
46
+ 2. Conveying Modified Versions.
47
+
48
+ If you modify a copy of the Library, and, in your modifications, a
49
+ facility refers to a function or data to be supplied by an Application
50
+ that uses the facility (other than as an argument passed when the
51
+ facility is invoked), then you may convey a copy of the modified
52
+ version:
53
+
54
+ a) under this License, provided that you make a good faith effort to
55
+ ensure that, in the event an Application does not supply the
56
+ function or data, the facility still operates, and performs
57
+ whatever part of its purpose remains meaningful, or
58
+
59
+ b) under the GNU GPL, with none of the additional permissions of
60
+ this License applicable to that copy.
61
+
62
+ 3. Object Code Incorporating Material from Library Header Files.
63
+
64
+ The object code form of an Application may incorporate material from
65
+ a header file that is part of the Library. You may convey such object
66
+ code under terms of your choice, provided that, if the incorporated
67
+ material is not limited to numerical parameters, data structure
68
+ layouts and accessors, or small macros, inline functions and templates
69
+ (ten or fewer lines in length), you do both of the following:
70
+
71
+ a) Give prominent notice with each copy of the object code that the
72
+ Library is used in it and that the Library and its use are
73
+ covered by this License.
74
+
75
+ b) Accompany the object code with a copy of the GNU GPL and this license
76
+ document.
77
+
78
+ 4. Combined Works.
79
+
80
+ You may convey a Combined Work under terms of your choice that,
81
+ taken together, effectively do not restrict modification of the
82
+ portions of the Library contained in the Combined Work and reverse
83
+ engineering for debugging such modifications, if you also do each of
84
+ the following:
85
+
86
+ a) Give prominent notice with each copy of the Combined Work that
87
+ the Library is used in it and that the Library and its use are
88
+ covered by this License.
89
+
90
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
91
+ document.
92
+
93
+ c) For a Combined Work that displays copyright notices during
94
+ execution, include the copyright notice for the Library among
95
+ these notices, as well as a reference directing the user to the
96
+ copies of the GNU GPL and this license document.
97
+
98
+ d) Do one of the following:
99
+
100
+ 0) Convey the Minimal Corresponding Source under the terms of this
101
+ License, and the Corresponding Application Code in a form
102
+ suitable for, and under terms that permit, the user to
103
+ recombine or relink the Application with a modified version of
104
+ the Linked Version to produce a modified Combined Work, in the
105
+ manner specified by section 6 of the GNU GPL for conveying
106
+ Corresponding Source.
107
+
108
+ 1) Use a suitable shared library mechanism for linking with the
109
+ Library. A suitable mechanism is one that (a) uses at run time
110
+ a copy of the Library already present on the user's computer
111
+ system, and (b) will operate properly with a modified version
112
+ of the Library that is interface-compatible with the Linked
113
+ Version.
114
+
115
+ e) Provide Installation Information, but only if you would otherwise
116
+ be required to provide such information under section 6 of the
117
+ GNU GPL, and only to the extent that such information is
118
+ necessary to install and execute a modified version of the
119
+ Combined Work produced by recombining or relinking the
120
+ Application with a modified version of the Linked Version. (If
121
+ you use option 4d0, the Installation Information must accompany
122
+ the Minimal Corresponding Source and Corresponding Application
123
+ Code. If you use option 4d1, you must provide the Installation
124
+ Information in the manner specified by section 6 of the GNU GPL
125
+ for conveying Corresponding Source.)
126
+
127
+ 5. Combined Libraries.
128
+
129
+ You may place library facilities that are a work based on the
130
+ Library side by side in a single library together with other library
131
+ facilities that are not Applications and are not covered by this
132
+ License, and convey such a combined library under terms of your
133
+ choice, if you do both of the following:
134
+
135
+ a) Accompany the combined library with a copy of the same work based
136
+ on the Library, uncombined with any other library facilities,
137
+ conveyed under the terms of this License.
138
+
139
+ b) Give prominent notice with the combined library that part of it
140
+ is a work based on the Library, and explaining where to find the
141
+ accompanying uncombined form of the same work.
142
+
143
+ 6. Revised Versions of the GNU Lesser General Public License.
144
+
145
+ The Free Software Foundation may publish revised and/or new versions
146
+ of the GNU Lesser General Public License from time to time. Such new
147
+ versions will be similar in spirit to the present version, but may
148
+ differ in detail to address new problems or concerns.
149
+
150
+ Each version is given a distinguishing version number. If the
151
+ Library as you received it specifies that a certain numbered version
152
+ of the GNU Lesser General Public License "or any later version"
153
+ applies to it, you have the option of following the terms and
154
+ conditions either of that published version or of any later version
155
+ published by the Free Software Foundation. If the Library as you
156
+ received it does not specify a version number of the GNU Lesser
157
+ General Public License, you may choose any version of the GNU Lesser
158
+ General Public License ever published by the Free Software Foundation.
159
+
160
+ If the Library as you received it specifies that a proxy can decide
161
+ whether future versions of the GNU Lesser General Public License shall
162
+ apply, that proxy's public statement of acceptance of any version is
163
+ permanent authorization for you to choose that version for the
164
+ Library.
@@ -0,0 +1 @@
1
+ xactflow_archidesc