Coverage for pyVHDLModel/Regions.py: 97%
1539 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-01 12:56 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-01 12:56 +0000
1# ==================================================================================================================== #
2# __ ___ _ ____ _ __ __ _ _ #
3# _ __ _ \ \ / / | | | _ \| | | \/ | ___ __| | ___| | #
4# | '_ \| | | \ \ / /| |_| | | | | | | |\/| |/ _ \ / _` |/ _ \ | #
5# | |_) | |_| |\ V / | _ | |_| | |___| | | | (_) | (_| | __/ | #
6# | .__/ \__, | \_/ |_| |_|____/|_____|_| |_|\___/ \__,_|\___|_| #
7# |_| |___/ #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2017-2026 Patrick Lehmann - Boetzingen, Germany #
15# Copyright 2016-2017 Patrick Lehmann - Dresden, Germany #
16# #
17# Licensed under the Apache License, Version 2.0 (the "License"); #
18# you may not use this file except in compliance with the License. #
19# You may obtain a copy of the License at #
20# #
21# http://www.apache.org/licenses/LICENSE-2.0 #
22# #
23# Unless required by applicable law or agreed to in writing, software #
24# distributed under the License is distributed on an "AS IS" BASIS, #
25# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
26# See the License for the specific language governing permissions and #
27# limitations under the License. #
28# #
29# SPDX-License-Identifier: Apache-2.0 #
30# ==================================================================================================================== #
31#
32"""
33This module contains parts of an abstract document language model for VHDL.
35tbd.
36"""
37from __future__ import annotations
39from typing import TYPE_CHECKING, Any, Callable, ClassVar, Collection, Generator, Iterable, \
40 Optional as Nullable
42from pyTooling.Common import getFullyQualifiedName, getTypeName
43from pyTooling.Decorators import export, readonly
44from pyTooling.MetaClasses import ExtendedType, expects
45from pyTooling.Warning import WarningCollector
47from pyVHDLModel.Base import ModelEntity, NamedEntityMixin, MultipleNamedEntityMixin, identifiersOf, \
48 normalizedIdentifiersOf, normalizedDeclaredNamesOf
49from pyVHDLModel.Exception import NotImplementedWarning, UnresolvedNameWarning, UnresolvedTypeMarkWarning, \
50 AlreadyInDesignError, NotAChildError, \
51 DuplicateGenericError, DuplicatePortError, DuplicateParameterError, \
52 DuplicateDeclarationError, DuplicateTypeError, DuplicateSubtypeError, \
53 DuplicateConstantError, DuplicateSignalError, DuplicateVariableError, \
54 DuplicateFileError, DuplicateComponentError, DuplicateSubprogramError
55from pyVHDLModel.Name import Name, AttributeName
56from pyVHDLModel.Namespace import Namespace
57from pyVHDLModel.Object import BaseConstant, Constant, DeferredConstant, SharedVariable, File, Variable, Signal
58from pyVHDLModel.Symbol import Symbol, SubtypeSymbol
59if TYPE_CHECKING: 59 ↛ 60line 59 didn't jump to line 60 because the condition on line 59 was never true
60 from pyVHDLModel.Interface import GenericInterfaceItemMixin, PortInterfaceItemMixin, ParameterInterfaceItemMixin, \
61 PortSignalInterfaceItem, SingleGenericDeclarationMixin, \
62 SinglePortDeclarationMixin, SingleParameterDeclarationMixin, \
63 GenericGroup, PortGroup, ParameterGroup
64 from pyVHDLModel.Type import Subtype, FullType
65 from pyVHDLModel.Visitor import Visitor
67# `pyVHDLModel.Subprogram` imports this module (Subprogram is a sequential declaration region), so
68# `Function`/`Procedure` are quoted in annotations and imported lazily where they're needed at runtime.
69# The same holds for the interface item classes of `pyVHDLModel.Interface`.
72@export
73class WithGenericsMixin(
74 metaclass=ExtendedType,
75 mixin=True,
76 expects=("_AddToNamespace", "_RemoveFromNamespace", "_ClashingDeclarations")
77):
78 """
79 A mixin-class for language constructs with a generic clause.
81 The host class provides ``_AddToNamespace(element)`` and ``_RemoveFromNamespace(element)``, called when a generic is
82 inserted or removed: :class:`~pyVHDLModel.Regions.DeclarativeRegionMixin` updates its namespace.
84 The host class also provides ``_ClashingDeclarations(item)``, called before a generic is inserted: it returns the
85 declarations sharing an identifier with the new item.
87 Indexing the generics (``_IndexGenericItems()``) needs the host's namespace ``_namespace``.
89 The generic groups (:data:`GenericGroups`) partition the generic clause: concatenated in order, they list every
90 generic exactly once, in declaration order. The mutators keep this partition.
92 .. seealso::
94 * :class:`Package <pyVHDLModel.DesignUnit.Package>`
95 * :class:`Entity <pyVHDLModel.DesignUnit.Entity>`
96 * :class:`Component <pyVHDLModel.DesignUnit.Component>`
97 * :class:`Concurrent block statement <pyVHDLModel.Concurrent.ConcurrentBlockStatement>`
98 * :class:`Subprogram <pyVHDLModel.Subprogram.Subprogram>`
99 * :class:`Generic group <pyVHDLModel.Interface.GenericGroup>`
100 """
101 _genericItems: list[GenericInterfaceItemMixin] #: List of all generics, in declaration order.
102 _genericGroups: list[GenericGroup] #: List of all generic groups, in declaration order.
104 def __init__(
105 self,
106 genericItems: Nullable[Iterable[GenericInterfaceItemMixin]] = None,
107 genericGroups: Nullable[Iterable[GenericGroup]] = None
108 ) -> None:
109 """
110 Initializes a language construct with a generic clause.
112 The language construct becomes the parent of each generic group, and each generic refers to its generic group.
113 Without generic groups, all generics form one unnamed generic group; no generics form no generic group.
115 :param genericItems: Optional, list of all generics, in declaration order. Default: ``None``, no generics.
116 :param genericGroups: Optional, list of generic groups partitioning the generics, in declaration order. Default:
117 ``None``, one unnamed generic group.
118 :raises TypeError: If parameter 'genericGroups' is ``None`` and an element of parameter 'genericItems' is not
119 of type :class:`~pyVHDLModel.Interface.GenericInterfaceItemMixin`.
120 :raises ValueError: If parameter 'genericGroups' is ``None`` and an element of parameter 'genericItems' is in a
121 generic group of another language construct.
122 :raises TypeError: If parameter 'genericGroups' is not iterable.
123 :raises TypeError: If an element of parameter 'genericGroups' is not of type
124 :class:`~pyVHDLModel.Interface.GenericGroup`.
125 :raises ValueError: If parameter 'genericGroups' doesn't list every generic of parameter 'genericItems' exactly
126 once, in declaration order.
127 """
128 from pyVHDLModel.Interface import GenericGroup
130 self._genericItems = genericItemList = []
131 if genericItems is not None:
132 for item in genericItems:
133 genericItemList.append(item)
134 item.Parent = self
136 self._genericGroups = genericGroupList = []
137 if genericGroups is None:
138 if len(genericItemList) > 0:
139 genericGroup = GenericGroup(genericItemList, parent=self)
140 genericGroupList.append(genericGroup)
141 for item in genericItemList:
142 item._group = genericGroup
144 return
146 if not isinstance(genericGroups, Iterable):
147 ex = TypeError("Parameter 'genericGroups' is not iterable.")
148 ex.add_note(f"Got type '{getFullyQualifiedName(genericGroups)}'.")
149 raise ex
151 groupedItems = []
152 for genericGroup in genericGroups:
153 if not isinstance(genericGroup, GenericGroup):
154 ex = TypeError("Element of parameter 'genericGroups' is not of type 'GenericGroup'.")
155 ex.add_note(f"Got type '{getFullyQualifiedName(genericGroup)}'.")
156 raise ex
158 genericGroupList.append(genericGroup)
159 groupedItems.extend(genericGroup._genericItems)
161 isPartition = len(groupedItems) == len(genericItemList) and all(
162 grouped is item for grouped, item in zip(groupedItems, genericItemList)
163 )
164 if not isPartition:
165 groups = " | ".join(
166 ", ".join(name for item in genericGroup._genericItems for name in identifiersOf(item))
167 for genericGroup in genericGroupList
168 )
169 generics = ", ".join(name for item in genericItemList for name in identifiersOf(item))
170 ex = ValueError("Parameter 'genericGroups' doesn't partition parameter 'genericItems'.")
171 ex.add_note(f"Got generic groups '{groups}' for generics '{generics}'.")
172 raise ex
174 for genericGroup in genericGroupList:
175 genericGroup.Parent = self
176 for item in genericGroup._genericItems:
177 item._group = genericGroup
179 @readonly
180 def GenericItems(self) -> list[GenericInterfaceItemMixin]:
181 """
182 Read-only property to access the generic items (:attr:`_genericItems`).
184 :returns: List of generic items.
185 """
186 return self._genericItems
188 @readonly
189 def GenericCount(self) -> int:
190 """
191 Read-only property to return the number of generics declared by :attr:`_genericItems`.
193 A generic constant item with several identifiers (``generic (A, B : natural)``) declares several generics.
195 :returns: The number of generics.
196 """
197 return sum(len(identifiersOf(item)) for item in self._genericItems)
199 @readonly
200 def GenericGroups(self) -> list[GenericGroup]:
201 """
202 Read-only property to access the generic groups (:attr:`_genericGroups`).
204 The generic groups partition the generic clause: concatenated in order, they list every generic exactly once, in
205 declaration order.
207 :returns: List of generic groups, in declaration order.
208 """
209 return self._genericGroups
211 def IterateSingleGenericDeclarations(
212 self,
213 predicate: Nullable[Callable[[SingleGenericDeclarationMixin | GenericInterfaceItemMixin], bool]] = None
214 ) -> Generator[SingleGenericDeclarationMixin | GenericInterfaceItemMixin, None, None]:
215 """
216 Iterate all generics per declared identifier, in declaration order.
218 A generic constant yields one single declaration per identifier: ``generic (A, B : positive)`` yields two. A
219 generic type, subprogram or package declares exactly one identifier and is yielded itself.
221 :param predicate: Optional, filter function to select the yielded generics. Default: all.
222 :returns: A generator to iterate all (selected) generics.
223 """
224 if predicate is None:
225 for item in self._genericItems:
226 if isinstance(item, MultipleNamedEntityMixin):
227 yield from item.SingleDeclarations
228 else:
229 yield item
230 else:
231 for item in self._genericItems:
232 if isinstance(item, MultipleNamedEntityMixin):
233 for singleDeclaration in item.SingleDeclarations:
234 if predicate(singleDeclaration):
235 yield singleDeclaration
236 elif predicate(item): 236 ↛ 231line 236 didn't jump to line 231 because the condition on line 236 was always true
237 yield item
239 def AddGenericItem(self, genericItem: GenericInterfaceItemMixin, group: Nullable[GenericGroup] = None) -> None:
240 """
241 Add a generic at the end of the generic clause, or at the end of a generic group.
243 The generic's parent is set to this language construct, and its identifiers are added to the language construct's
244 namespace, if it has one. Without a generic group, the generic joins the last generic group, or forms a new
245 unnamed generic group if there are no generics.
247 :param genericItem: The generic to add.
248 :param group: Optional, the generic group of this language construct to add the generic to, at
249 its end. Default: ``None``, the end of the generic clause.
250 :raises ValueError: If parameter 'genericItem' is ``None``.
251 :raises TypeError: If parameter 'genericItem' is not of type
252 :class:`~pyVHDLModel.Interface.GenericInterfaceItemMixin`.
253 :raises AlreadyInDesignError: If parameter 'genericItem' already has a parent.
254 :raises TypeError: If parameter 'group' is not of type :class:`~pyVHDLModel.Interface.GenericGroup`.
255 :raises NotAChildError: If parameter 'group' is not a generic group of this language construct.
256 :raises DuplicateGenericError: If an existing declaration of the language construct shares an identifier
257 with the generic.
259 .. seealso::
261 :meth:`InsertGenericItem`
262 |rarr| Insert a generic at a position of the generic clause.
263 :meth:`RemoveGenericItem`
264 |rarr| Remove a generic from the generic clause.
265 """
266 index = len(self._genericItems)
267 if group is not None:
268 index = 0
269 for genericGroup in self._genericGroups:
270 index += len(genericGroup._genericItems)
271 if genericGroup is group:
272 break
274 self.InsertGenericItem(index, genericItem, group)
276 def InsertGenericItem(
277 self,
278 index: int,
279 genericItem: GenericInterfaceItemMixin,
280 group: Nullable[GenericGroup] = None
281 ) -> None:
282 """
283 Insert a generic at a position of the generic clause.
285 The generic's parent is set to this language construct, and its identifiers are added to the language construct's
286 namespace, if it has one.
288 Without a generic group, the generic joins the generic group of the generic before ``index``; at index ``0``, the
289 generic group of the first generic. If there are no generics, the generic forms a new unnamed generic group. A
290 generic group given must contain ``index`` or end at it, so the generic groups stay contiguous.
292 :param index: Position, from ``0`` (first) to the length of :data:`GenericItems` (append).
293 A negative index counts from the end, as for :meth:`list.insert`: ``-1`` inserts
294 before the last generic.
295 :param genericItem: The generic to insert.
296 :param group: Optional, the generic group of this language construct to insert the generic into.
297 Default: ``None``, the generic group of the generic before ``index``.
298 :raises ValueError: If parameter 'index' is ``None``.
299 :raises TypeError: If parameter 'index' is not of type :class:`int`.
300 :raises ValueError: If parameter 'index' is out of range.
301 :raises ValueError: If parameter 'genericItem' is ``None``.
302 :raises TypeError: If parameter 'genericItem' is not of type
303 :class:`~pyVHDLModel.Interface.GenericInterfaceItemMixin`.
304 :raises AlreadyInDesignError: If parameter 'genericItem' already has a parent.
305 :raises TypeError: If parameter 'group' is not of type :class:`~pyVHDLModel.Interface.GenericGroup`.
306 :raises NotAChildError: If parameter 'group' is not a generic group of this language construct.
307 :raises ValueError: If parameter 'group' neither contains nor ends at parameter 'index'.
308 :raises DuplicateGenericError: If an existing declaration of the language construct shares an identifier
309 with the generic.
311 .. seealso::
313 :meth:`AddGenericItem`
314 |rarr| Add a generic at the end of the generic clause.
315 :meth:`RemoveGenericItem`
316 |rarr| Remove a generic from the generic clause.
317 :meth:`MoveGenericItem`
318 |rarr| Move a generic to a position of the generic clause.
319 """
320 from pyVHDLModel.Interface import GenericInterfaceItemMixin, GenericGroup
322 if index is None:
323 raise ValueError("Parameter 'index' is None.")
324 elif not isinstance(index, int):
325 ex = TypeError("Parameter 'index' is not of type 'int'.")
326 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
327 raise ex
328 elif not (-len(self._genericItems) <= index <= len(self._genericItems)):
329 ex = ValueError(f"Parameter 'index' is out of range {-len(self._genericItems)}..{len(self._genericItems)}.")
330 ex.add_note(f"Got value '{index}'.")
331 raise ex
333 if genericItem is None:
334 raise ValueError("Parameter 'genericItem' is None.")
335 elif not isinstance(genericItem, GenericInterfaceItemMixin):
336 ex = TypeError("Parameter 'genericItem' is not of type 'GenericInterfaceItemMixin'.")
337 ex.add_note(f"Got type '{getFullyQualifiedName(genericItem)}'.")
338 raise ex
339 elif genericItem._parent is not None:
340 identifiers = ", ".join(identifiersOf(genericItem))
341 ex = AlreadyInDesignError(
342 f"{getTypeName(genericItem)} '{identifiers}' already has a parent.",
343 element=genericItem,
344 parent=genericItem._parent
345 )
346 ex.add_note(f"Remove it from its {getTypeName(genericItem._parent)} first.")
347 raise ex
349 position = index if index >= 0 else len(self._genericItems) + index
350 if group is not None:
351 if not isinstance(group, GenericGroup):
352 ex = TypeError("Parameter 'group' is not of type 'GenericGroup'.")
353 ex.add_note(f"Got type '{getFullyQualifiedName(group)}'.")
354 raise ex
356 groupStart = 0
357 for genericGroup in self._genericGroups:
358 if genericGroup is group:
359 break
361 groupStart += len(genericGroup._genericItems)
362 else:
363 groupName = getTypeName(group) if group._identifier is None else f"{getTypeName(group)} '{group._identifier}'"
364 raise NotAChildError(
365 f"{groupName} is not a generic group of this {getTypeName(self)}.",
366 element=group,
367 parent=self
368 )
370 groupEnd = groupStart + len(group._genericItems)
371 if not (groupStart <= position <= groupEnd):
372 ex = ValueError(f"Parameter 'index' is outside of parameter 'group' at {groupStart}..{groupEnd}.")
373 ex.add_note(f"Got value '{index}'.")
374 raise ex
376 if len(clashes := self._ClashingDeclarations(genericItem)) > 0:
377 existingIdentifiers = normalizedIdentifiersOf(clashes[0])
378 newIdentifiers = zip(identifiersOf(genericItem), normalizedIdentifiersOf(genericItem))
379 identifier = next(name for name, normalizedName in newIdentifiers if normalizedName in existingIdentifiers)
380 ex = DuplicateGenericError(
381 f"{getTypeName(clashes[0]._parent)} already declares '{identifier}'.",
382 identifier=identifier,
383 parent=self,
384 element=genericItem,
385 existing=clashes[0]
386 )
387 ex.add_note(f"Existing declaration is of type '{getFullyQualifiedName(clashes[0])}'.")
388 raise ex
390 self._genericItems.insert(position, genericItem)
391 genericItem.Parent = self
392 if group is None:
393 self._AddToGenericGroup(position, genericItem)
394 else:
395 group._genericItems.insert(position - groupStart, genericItem)
396 genericItem._group = group
398 self._AddToNamespace(genericItem)
400 def _AddToGenericGroup(self, position: int, genericItem: GenericInterfaceItemMixin) -> None:
401 """
402 Add a generic to the generic group of the generic before ``position``.
404 At position ``0``, the generic joins the generic group of the first generic. If there are no generic groups, the
405 generic forms a new unnamed generic group.
407 :param position: Position of the generic in the generic clause, from ``0`` (first) to the length of
408 :data:`GenericItems` (last).
409 :param genericItem: The generic to add, which isn't in a generic group.
410 """
411 from pyVHDLModel.Interface import GenericGroup
413 groupStart = 0
414 for genericGroup in self._genericGroups:
415 groupEnd = groupStart + len(genericGroup._genericItems)
416 if position <= groupEnd:
417 genericGroup._genericItems.insert(position - groupStart, genericItem)
418 genericItem._group = genericGroup
419 return
421 groupStart = groupEnd
423 genericGroup = GenericGroup((genericItem, ), parent=self)
424 self._genericGroups.append(genericGroup)
425 genericItem._group = genericGroup
427 def RemoveGenericItem(self, genericItem: GenericInterfaceItemMixin) -> None:
428 """
429 Remove a generic from the generic clause.
431 The generic is detached: its parent and generic group are cleared and its identifiers are removed from the
432 language construct's namespace, if it has one. A generic group, which becomes empty, is removed from
433 :data:`GenericGroups` and its parent is cleared. The generic itself is unchanged and can be added to another
434 language construct, or inserted at another position.
436 :param genericItem: The generic to remove.
437 :raises ValueError: If parameter 'genericItem' is ``None``.
438 :raises TypeError: If parameter 'genericItem' is not of type
439 :class:`~pyVHDLModel.Interface.GenericInterfaceItemMixin`.
440 :raises NotAChildError: If parameter 'genericItem' is not a generic of this language construct.
441 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the generic isn't declared in it.
442 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the generic refers to another
443 element, e.g. a duplicate declaration.
445 .. seealso::
447 :meth:`AddGenericItem`
448 |rarr| Add a generic at the end of the generic clause.
449 :meth:`InsertGenericItem`
450 |rarr| Insert a generic at a position of the generic clause.
451 :meth:`MoveGenericItem`
452 |rarr| Move a generic to a position of the generic clause.
453 """
454 from pyVHDLModel.Interface import GenericInterfaceItemMixin
456 if genericItem is None:
457 raise ValueError("Parameter 'genericItem' is None.")
458 elif not isinstance(genericItem, GenericInterfaceItemMixin):
459 ex = TypeError("Parameter 'genericItem' is not of type 'GenericInterfaceItemMixin'.")
460 ex.add_note(f"Got type '{getFullyQualifiedName(genericItem)}'.")
461 raise ex
463 for index, item in enumerate(self._genericItems):
464 if item is genericItem:
465 break
466 else:
467 identifiers = ", ".join(identifiersOf(genericItem))
468 raise NotAChildError(
469 f"{getTypeName(genericItem)} '{identifiers}' is not a generic of this {getTypeName(self)}.",
470 element=genericItem,
471 parent=self
472 )
474 self._RemoveFromNamespace(genericItem)
475 del self._genericItems[index]
476 self._RemoveFromGenericGroup(genericItem)
477 genericItem._parent = None
479 def _RemoveFromGenericGroup(self, genericItem: GenericInterfaceItemMixin) -> None:
480 """
481 Remove a generic from its generic group and clear the generic's group.
483 A generic group, which becomes empty, is removed from :data:`GenericGroups` and its parent is cleared.
485 :param genericItem: The generic to remove from its generic group.
486 """
487 genericGroup = genericItem._group
488 groupItems = genericGroup._genericItems
489 for index, item in enumerate(groupItems): 489 ↛ 494line 489 didn't jump to line 494 because the loop on line 489 didn't complete
490 if item is genericItem:
491 del groupItems[index]
492 break
494 if len(groupItems) == 0:
495 self._genericGroups.remove(genericGroup)
496 genericGroup._parent = None
498 genericItem._group = None
500 def MoveGenericItem(self, genericItem: GenericInterfaceItemMixin, index: int) -> None:
501 """
502 Move a generic to a position of the generic clause.
504 The generic stays a generic of this language construct: only the order of the generic clause changes. A generic
505 subprogram is an overload: if the language construct's namespace is indexed, it refers to the overload declared
506 last afterwards.
508 The generic leaves its generic group, like :meth:`RemoveGenericItem`, and joins a generic group, like
509 :meth:`InsertGenericItem` without a generic group: the generic group of the generic before its new position; at
510 index ``0``, the generic group of the first generic. A move to the generic's current position changes nothing.
512 :param genericItem: The generic to move.
513 :param index: Position of the generic after the move, from ``0`` (first) to the length of
514 :data:`GenericItems` minus one (last). A negative index counts from the end, as for a
515 :class:`list` index: ``-1`` moves the generic to the end.
516 :raises ValueError: If parameter 'genericItem' is ``None``.
517 :raises TypeError: If parameter 'genericItem' is not of type
518 :class:`~pyVHDLModel.Interface.GenericInterfaceItemMixin`.
519 :raises NotAChildError: If parameter 'genericItem' is not a generic of this language construct.
520 :raises ValueError: If parameter 'index' is ``None``.
521 :raises TypeError: If parameter 'index' is not of type :class:`int`.
522 :raises ValueError: If parameter 'index' is out of range.
523 :raises NotInNamespaceError: If the namespace is indexed, and the identifier of a generic subprogram refers to an
524 element, which is no overload, e.g. a duplicate declaration.
526 .. seealso::
528 :meth:`InsertGenericItem`
529 |rarr| Insert a generic at a position of the generic clause.
530 :meth:`RemoveGenericItem`
531 |rarr| Remove a generic from the generic clause.
532 """
533 from pyVHDLModel.Interface import GenericInterfaceItemMixin
534 from pyVHDLModel.Subprogram import Function, Procedure
536 if genericItem is None:
537 raise ValueError("Parameter 'genericItem' is None.")
538 elif not isinstance(genericItem, GenericInterfaceItemMixin):
539 ex = TypeError("Parameter 'genericItem' is not of type 'GenericInterfaceItemMixin'.")
540 ex.add_note(f"Got type '{getFullyQualifiedName(genericItem)}'.")
541 raise ex
543 for currentIndex, item in enumerate(self._genericItems):
544 if item is genericItem:
545 break
546 else:
547 identifiers = ", ".join(identifiersOf(genericItem))
548 raise NotAChildError(
549 f"{getTypeName(genericItem)} '{identifiers}' is not a generic of this {getTypeName(self)}.",
550 element=genericItem,
551 parent=self
552 )
554 if index is None:
555 raise ValueError("Parameter 'index' is None.")
556 elif not isinstance(index, int):
557 ex = TypeError("Parameter 'index' is not of type 'int'.")
558 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
559 raise ex
560 elif not (-len(self._genericItems) <= index < len(self._genericItems)):
561 ex = ValueError(f"Parameter 'index' is out of range {-len(self._genericItems)}..{len(self._genericItems) - 1}.")
562 ex.add_note(f"Got value '{index}'.")
563 raise ex
565 newIndex = index if index >= 0 else len(self._genericItems) + index
566 if newIndex == currentIndex:
567 return
569 isOverload = isinstance(genericItem, (Function, Procedure))
570 if isOverload:
571 self._RemoveFromNamespace(genericItem)
573 del self._genericItems[currentIndex]
574 self._genericItems.insert(newIndex, genericItem)
575 self._RemoveFromGenericGroup(genericItem)
576 self._AddToGenericGroup(newIndex, genericItem)
578 if isOverload:
579 self._AddToNamespace(genericItem)
581 def SplitGenericItem(
582 self,
583 genericItem: GenericInterfaceItemMixin
584 ) -> tuple[GenericInterfaceItemMixin, ...]:
585 """
586 Split a generic with an identifier list into one generic per identifier.
588 The generic keeps its first identifier. For every other identifier, a new generic is created by its
589 ``Copy()`` and inserted right after it, in list order, in the generic clause and in the generic's generic group;
590 its parent is set to this language construct. If the language construct has a namespace, the entries of the other
591 identifiers refer to the new generics. A generic declaring one identifier is unchanged.
593 :param genericItem: The generic to split.
594 :returns: Tuple of generics, one per identifier in list order, starting with the split
595 generic.
596 :raises ValueError: If parameter 'genericItem' is ``None``.
597 :raises TypeError: If parameter 'genericItem' is not of type
598 :class:`~pyVHDLModel.Interface.GenericInterfaceItemMixin`.
599 :raises NotAChildError: If parameter 'genericItem' is not a generic of this language construct.
600 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the generic refers to another
601 element, e.g. a duplicate declaration.
603 .. seealso::
605 :meth:`~pyVHDLModel.Base.MultipleNamedEntityMixin.Split`
606 |rarr| Split a declaration with an identifier list.
607 :meth:`RemoveGenericItem`
608 |rarr| Remove a generic from the generic clause.
609 """
610 from pyVHDLModel.Interface import GenericInterfaceItemMixin
612 if genericItem is None:
613 raise ValueError("Parameter 'genericItem' is None.")
614 elif not isinstance(genericItem, GenericInterfaceItemMixin):
615 ex = TypeError("Parameter 'genericItem' is not of type 'GenericInterfaceItemMixin'.")
616 ex.add_note(f"Got type '{getFullyQualifiedName(genericItem)}'.")
617 raise ex
619 for index, item in enumerate(self._genericItems):
620 if item is genericItem:
621 break
622 else:
623 identifiers = ", ".join(identifiersOf(genericItem))
624 raise NotAChildError(
625 f"{getTypeName(genericItem)} '{identifiers}' is not a generic of this {getTypeName(self)}.",
626 element=genericItem,
627 parent=self
628 )
630 if not isinstance(genericItem, MultipleNamedEntityMixin) or len(genericItem._identifiers) == 1:
631 return (genericItem, )
633 genericGroup = genericItem._group
634 groupItems = genericGroup._genericItems
635 for groupIndex, item in enumerate(groupItems): 635 ↛ 639line 635 didn't jump to line 639 because the loop on line 635 didn't complete
636 if item is genericItem:
637 break
639 declarations = genericItem._SplitCopies()
640 self._RemoveFromNamespace(genericItem)
641 genericItem._KeepIdentifier(0)
642 self._genericItems[index + 1:index + 1] = declarations
643 groupItems[groupIndex + 1:groupIndex + 1] = declarations
644 self._AddToNamespace(genericItem)
645 for declaration in declarations:
646 declaration.Parent = self
647 declaration._group = genericGroup
648 self._AddToNamespace(declaration)
650 return (genericItem, *declarations)
652 @expects("_namespace")
653 def _IndexGenericItems(self) -> None:
654 """Add the generics to the host's namespace; a generic subprogram is an overload."""
655 from pyVHDLModel.Subprogram import Function, Procedure
657 for item in self._genericItems:
658 overloadable = isinstance(item, (Function, Procedure))
659 for normalizedIdentifier in normalizedIdentifiersOf(item):
660 self._namespace.AddElement(normalizedIdentifier, item, overloadable=overloadable)
662 def _VisitGenericClause(self, visitor: Visitor) -> None:
663 """
664 Walk the generic clause, if there are generics, with a visitor.
666 The generics are separated by semicolons.
668 :param visitor: The visitor receiving the events.
669 """
670 if len(self._genericItems) == 0:
671 return
673 visitor.VisitGenericClause(self)
674 for index, item in enumerate(self._genericItems):
675 if index > 0:
676 visitor.VisitInterfaceListSeparator(self)
678 item.Visit(visitor)
680 visitor.DepartGenericClause(self)
683@export
684class WithPortsMixin(
685 metaclass=ExtendedType,
686 mixin=True,
687 expects=("_AddToNamespace", "_RemoveFromNamespace", "_ClashingDeclarations")
688):
689 """
690 A mixin-class for language constructs with a port clause.
692 The host class provides ``_AddToNamespace(element)`` and ``_RemoveFromNamespace(element)``, called when a port is
693 inserted or removed: :class:`~pyVHDLModel.Regions.DeclarativeRegionMixin` updates its namespace.
695 The host class also provides ``_ClashingDeclarations(item)``, called before a port is inserted: it returns the
696 declarations sharing an identifier with the new item.
698 Indexing the ports (``_IndexPortItems()``) needs the host's namespace ``_namespace``.
700 The port groups (:data:`PortGroups`) partition the port clause: concatenated in order, they list every port exactly
701 once, in declaration order. The mutators keep this partition.
703 .. seealso::
705 * :class:`Concurrent block statement <pyVHDLModel.Concurrent.ConcurrentBlockStatement>`
706 * :class:`Entity <pyVHDLModel.DesignUnit.Entity>`
707 * :class:`Component <pyVHDLModel.DesignUnit.Component>`
708 * :class:`Port group <pyVHDLModel.Interface.PortGroup>`
709 """
710 _portItems: list[PortInterfaceItemMixin] #: List of all ports, in declaration order.
711 _portGroups: list[PortGroup] #: List of all port groups, in declaration order.
713 def __init__(
714 self,
715 portItems: Nullable[Iterable[PortInterfaceItemMixin]] = None,
716 portGroups: Nullable[Iterable[PortGroup]] = None
717 ) -> None:
718 """
719 Initializes a language construct with a port clause.
721 The language construct becomes the parent of each port group, and each port refers to its port group. Without
722 port groups, all ports form one unnamed port group; no ports form no port group.
724 :param portItems: Optional, list of all ports, in declaration order. Default: ``None``, no ports.
725 :param portGroups: Optional, list of port groups partitioning the ports, in declaration order. Default:
726 ``None``, one unnamed port group.
727 :raises TypeError: If parameter 'portGroups' is ``None`` and an element of parameter 'portItems' is not of type
728 :class:`~pyVHDLModel.Interface.PortSignalInterfaceItem`.
729 :raises ValueError: If parameter 'portGroups' is ``None`` and an element of parameter 'portItems' is in a port
730 group of another language construct.
731 :raises TypeError: If parameter 'portGroups' is not iterable.
732 :raises TypeError: If an element of parameter 'portGroups' is not of type
733 :class:`~pyVHDLModel.Interface.PortGroup`.
734 :raises ValueError: If parameter 'portGroups' doesn't list every port of parameter 'portItems' exactly once,
735 in declaration order.
736 """
737 from pyVHDLModel.Interface import PortGroup
739 self._portItems = portItemList = []
740 if portItems is not None:
741 for item in portItems:
742 portItemList.append(item)
743 item.Parent = self
745 self._portGroups = portGroupList = []
746 if portGroups is None:
747 if len(portItemList) > 0:
748 portGroup = PortGroup(portItemList, parent=self)
749 portGroupList.append(portGroup)
750 for item in portItemList:
751 item._group = portGroup
753 return
755 if not isinstance(portGroups, Iterable):
756 ex = TypeError("Parameter 'portGroups' is not iterable.")
757 ex.add_note(f"Got type '{getFullyQualifiedName(portGroups)}'.")
758 raise ex
760 groupedItems = []
761 for portGroup in portGroups:
762 if not isinstance(portGroup, PortGroup):
763 ex = TypeError("Element of parameter 'portGroups' is not of type 'PortGroup'.")
764 ex.add_note(f"Got type '{getFullyQualifiedName(portGroup)}'.")
765 raise ex
767 portGroupList.append(portGroup)
768 groupedItems.extend(portGroup._portItems)
770 isPartition = len(groupedItems) == len(portItemList) and all(
771 grouped is item for grouped, item in zip(groupedItems, portItemList)
772 )
773 if not isPartition:
774 groups = " | ".join(
775 ", ".join(name for item in portGroup._portItems for name in item._identifiers) for portGroup in portGroupList
776 )
777 ports = ", ".join(name for item in portItemList for name in item._identifiers)
778 ex = ValueError("Parameter 'portGroups' doesn't partition parameter 'portItems'.")
779 ex.add_note(f"Got port groups '{groups}' for ports '{ports}'.")
780 raise ex
782 for portGroup in portGroupList:
783 portGroup.Parent = self
784 for item in portGroup._portItems:
785 item._group = portGroup
787 @readonly
788 def PortItems(self) -> list[PortInterfaceItemMixin]:
789 """
790 Read-only property to access the port items (:attr:`_portItems`).
792 :returns: List of port items.
793 """
794 return self._portItems
796 @readonly
797 def PortCount(self) -> int:
798 """
799 Read-only property to return the number of ports declared by :attr:`_portItems`.
801 A port item with several identifiers (``port (a, b : in bit)``) declares several ports.
803 :returns: The number of ports.
804 """
805 return sum(len(item._identifiers) for item in self._portItems)
807 @readonly
808 def PortGroups(self) -> list[PortGroup]:
809 """
810 Read-only property to access the port groups (:attr:`_portGroups`).
812 The port groups partition the port clause: concatenated in order, they list every port exactly once, in
813 declaration order.
815 :returns: List of port groups, in declaration order.
816 """
817 return self._portGroups
819 def IterateSinglePortDeclarations(
820 self,
821 predicate: Nullable[Callable[[SinglePortDeclarationMixin], bool]] = None
822 ) -> Generator[SinglePortDeclarationMixin, None, None]:
823 """
824 Iterate all ports per declared identifier, in declaration order.
826 A port yields one single declaration per identifier: ``port (a, b : in bit)`` yields two.
828 :param predicate: Optional, filter function to select the yielded ports. Default: all.
829 :returns: A generator to iterate all (selected) ports.
830 """
831 if predicate is None:
832 for item in self._portItems:
833 yield from item.SingleDeclarations
834 else:
835 for item in self._portItems:
836 for singleDeclaration in item.SingleDeclarations:
837 if predicate(singleDeclaration):
838 yield singleDeclaration
840 def AddPortItem(self, portItem: PortSignalInterfaceItem, group: Nullable[PortGroup] = None) -> None:
841 """
842 Add a port at the end of the port clause, or at the end of a port group.
844 The port's parent is set to this language construct, and its identifiers are added to the language construct's
845 namespace, if it has one. Without a port group, the port joins the last port group, or forms a new unnamed port
846 group if there are no ports.
848 :param portItem: The port to add.
849 :param group: Optional, the port group of this language construct to add the port to, at its end.
850 Default: ``None``, the end of the port clause.
851 :raises ValueError: If parameter 'portItem' is ``None``.
852 :raises TypeError: If parameter 'portItem' is not of type
853 :class:`~pyVHDLModel.Interface.PortSignalInterfaceItem`.
854 :raises AlreadyInDesignError: If parameter 'portItem' already has a parent.
855 :raises TypeError: If parameter 'group' is not of type :class:`~pyVHDLModel.Interface.PortGroup`.
856 :raises NotAChildError: If parameter 'group' is not a port group of this language construct.
857 :raises DuplicatePortError: If an existing declaration of the language construct shares an identifier
858 with the port.
860 .. seealso::
862 :meth:`InsertPortItem`
863 |rarr| Insert a port at a position of the port clause.
864 :meth:`RemovePortItem`
865 |rarr| Remove a port from the port clause.
866 """
867 index = len(self._portItems)
868 if group is not None:
869 index = 0
870 for portGroup in self._portGroups:
871 index += len(portGroup._portItems)
872 if portGroup is group:
873 break
875 self.InsertPortItem(index, portItem, group)
877 def InsertPortItem(self, index: int, portItem: PortSignalInterfaceItem, group: Nullable[PortGroup] = None) -> None:
878 """
879 Insert a port at a position of the port clause.
881 The port's parent is set to this language construct, and its identifiers are added to the language construct's
882 namespace, if it has one.
884 Without a port group, the port joins the port group of the port before ``index``; at index ``0``, the port group
885 of the first port. If there are no ports, the port forms a new unnamed port group. A port group given must
886 contain ``index`` or end at it, so the port groups stay contiguous.
888 :param index: Position, from ``0`` (first) to the length of :data:`PortItems` (append).
889 A negative index counts from the end, as for :meth:`list.insert`: ``-1`` inserts
890 before the last port.
891 :param portItem: The port to insert.
892 :param group: Optional, the port group of this language construct to insert the port into.
893 Default: ``None``, the port group of the port before ``index``.
894 :raises ValueError: If parameter 'index' is ``None``.
895 :raises TypeError: If parameter 'index' is not of type :class:`int`.
896 :raises ValueError: If parameter 'index' is out of range.
897 :raises ValueError: If parameter 'portItem' is ``None``.
898 :raises TypeError: If parameter 'portItem' is not of type
899 :class:`~pyVHDLModel.Interface.PortSignalInterfaceItem`.
900 :raises AlreadyInDesignError: If parameter 'portItem' already has a parent.
901 :raises TypeError: If parameter 'group' is not of type :class:`~pyVHDLModel.Interface.PortGroup`.
902 :raises NotAChildError: If parameter 'group' is not a port group of this language construct.
903 :raises ValueError: If parameter 'group' neither contains nor ends at parameter 'index'.
904 :raises DuplicatePortError: If an existing declaration of the language construct shares an identifier
905 with the port.
907 .. seealso::
909 :meth:`AddPortItem`
910 |rarr| Add a port at the end of the port clause.
911 :meth:`RemovePortItem`
912 |rarr| Remove a port from the port clause.
913 :meth:`MovePortItem`
914 |rarr| Move a port to a position of the port clause.
915 """
916 from pyVHDLModel.Interface import PortSignalInterfaceItem, PortGroup
918 if index is None: 918 ↛ 919line 918 didn't jump to line 919 because the condition on line 918 was never true
919 raise ValueError("Parameter 'index' is None.")
920 elif not isinstance(index, int): 920 ↛ 921line 920 didn't jump to line 921 because the condition on line 920 was never true
921 ex = TypeError("Parameter 'index' is not of type 'int'.")
922 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
923 raise ex
924 elif not (-len(self._portItems) <= index <= len(self._portItems)):
925 ex = ValueError(f"Parameter 'index' is out of range {-len(self._portItems)}..{len(self._portItems)}.")
926 ex.add_note(f"Got value '{index}'.")
927 raise ex
929 if portItem is None:
930 raise ValueError("Parameter 'portItem' is None.")
931 elif not isinstance(portItem, PortSignalInterfaceItem):
932 ex = TypeError("Parameter 'portItem' is not of type 'PortSignalInterfaceItem'.")
933 ex.add_note(f"Got type '{getFullyQualifiedName(portItem)}'.")
934 raise ex
935 elif portItem._parent is not None:
936 identifiers = ", ".join(identifiersOf(portItem))
937 ex = AlreadyInDesignError(
938 f"{getTypeName(portItem)} '{identifiers}' already has a parent.",
939 element=portItem,
940 parent=portItem._parent
941 )
942 ex.add_note(f"Remove it from its {getTypeName(portItem._parent)} first.")
943 raise ex
945 position = index if index >= 0 else len(self._portItems) + index
946 if group is not None:
947 if not isinstance(group, PortGroup):
948 ex = TypeError("Parameter 'group' is not of type 'PortGroup'.")
949 ex.add_note(f"Got type '{getFullyQualifiedName(group)}'.")
950 raise ex
952 groupStart = 0
953 for portGroup in self._portGroups:
954 if portGroup is group:
955 break
957 groupStart += len(portGroup._portItems)
958 else:
959 groupName = getTypeName(group) if group._identifier is None else f"{getTypeName(group)} '{group._identifier}'"
960 raise NotAChildError(
961 f"{groupName} is not a port group of this {getTypeName(self)}.",
962 element=group,
963 parent=self
964 )
966 groupEnd = groupStart + len(group._portItems)
967 if not (groupStart <= position <= groupEnd):
968 ex = ValueError(f"Parameter 'index' is outside of parameter 'group' at {groupStart}..{groupEnd}.")
969 ex.add_note(f"Got value '{index}'.")
970 raise ex
972 if len(clashes := self._ClashingDeclarations(portItem)) > 0:
973 existingIdentifiers = normalizedIdentifiersOf(clashes[0])
974 newIdentifiers = zip(identifiersOf(portItem), normalizedIdentifiersOf(portItem))
975 identifier = next(name for name, normalizedName in newIdentifiers if normalizedName in existingIdentifiers)
976 ex = DuplicatePortError(
977 f"{getTypeName(clashes[0]._parent)} already declares '{identifier}'.",
978 identifier=identifier,
979 parent=self,
980 element=portItem,
981 existing=clashes[0]
982 )
983 ex.add_note(f"Existing declaration is of type '{getFullyQualifiedName(clashes[0])}'.")
984 raise ex
986 self._portItems.insert(position, portItem)
987 portItem.Parent = self
988 if group is None:
989 self._AddToPortGroup(position, portItem)
990 else:
991 group._portItems.insert(position - groupStart, portItem)
992 portItem._group = group
994 self._AddToNamespace(portItem)
996 def _AddToPortGroup(self, position: int, portItem: PortSignalInterfaceItem) -> None:
997 """
998 Add a port to the port group of the port before ``position``; at position ``0``, the port group of the first port.
1000 If there are no port groups, the port forms a new unnamed port group.
1002 :param position: Position of the port in the port clause, from ``0`` (first) to the length of :data:`PortItems`
1003 (last).
1004 :param portItem: The port to add, which isn't in a port group.
1005 """
1006 from pyVHDLModel.Interface import PortGroup
1008 groupStart = 0
1009 for portGroup in self._portGroups:
1010 groupEnd = groupStart + len(portGroup._portItems)
1011 if position <= groupEnd:
1012 portGroup._portItems.insert(position - groupStart, portItem)
1013 portItem._group = portGroup
1014 return
1016 groupStart = groupEnd
1018 portGroup = PortGroup((portItem, ), parent=self)
1019 self._portGroups.append(portGroup)
1020 portItem._group = portGroup
1022 def RemovePortItem(self, portItem: PortSignalInterfaceItem) -> None:
1023 """
1024 Remove a port from the port clause.
1026 The port is detached: its parent and port group are cleared and its identifiers are removed from the language
1027 construct's namespace, if it has one. A port group, which becomes empty, is removed from :data:`PortGroups` and its
1028 parent is cleared. The port itself is unchanged and can be added to another language construct, or inserted at
1029 another position.
1031 :param portItem: The port to remove.
1032 :raises ValueError: If parameter 'portItem' is ``None``.
1033 :raises TypeError: If parameter 'portItem' is not of type
1034 :class:`~pyVHDLModel.Interface.PortSignalInterfaceItem`.
1035 :raises NotAChildError: If parameter 'portItem' is not a port of this language construct.
1036 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the port isn't declared in it.
1037 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the port refers to another
1038 element, e.g. a duplicate declaration.
1040 .. seealso::
1042 :meth:`AddPortItem`
1043 |rarr| Add a port at the end of the port clause.
1044 :meth:`InsertPortItem`
1045 |rarr| Insert a port at a position of the port clause.
1046 :meth:`MovePortItem`
1047 |rarr| Move a port to a position of the port clause.
1048 """
1049 from pyVHDLModel.Interface import PortSignalInterfaceItem
1051 if portItem is None:
1052 raise ValueError("Parameter 'portItem' is None.")
1053 elif not isinstance(portItem, PortSignalInterfaceItem):
1054 ex = TypeError("Parameter 'portItem' is not of type 'PortSignalInterfaceItem'.")
1055 ex.add_note(f"Got type '{getFullyQualifiedName(portItem)}'.")
1056 raise ex
1058 for index, item in enumerate(self._portItems):
1059 if item is portItem:
1060 break
1061 else:
1062 identifiers = ", ".join(identifiersOf(portItem))
1063 raise NotAChildError(
1064 f"{getTypeName(portItem)} '{identifiers}' is not a port of this {getTypeName(self)}.",
1065 element=portItem,
1066 parent=self
1067 )
1069 self._RemoveFromNamespace(portItem)
1070 del self._portItems[index]
1071 self._RemoveFromPortGroup(portItem)
1072 portItem._parent = None
1074 def _RemoveFromPortGroup(self, portItem: PortSignalInterfaceItem) -> None:
1075 """
1076 Remove a port from its port group and clear the port's group.
1078 A port group, which becomes empty, is removed from :data:`PortGroups` and its parent is cleared.
1080 :param portItem: The port to remove from its port group.
1081 """
1082 portGroup = portItem._group
1083 groupItems = portGroup._portItems
1084 for index, item in enumerate(groupItems): 1084 ↛ 1089line 1084 didn't jump to line 1089 because the loop on line 1084 didn't complete
1085 if item is portItem:
1086 del groupItems[index]
1087 break
1089 if len(groupItems) == 0:
1090 self._portGroups.remove(portGroup)
1091 portGroup._parent = None
1093 portItem._group = None
1095 def MovePortItem(self, portItem: PortSignalInterfaceItem, index: int) -> None:
1096 """
1097 Move a port to a position of the port clause.
1099 The port stays a port of this language construct: only the order of the port clause changes. The port leaves its
1100 port group, like :meth:`RemovePortItem`, and joins a port group, like :meth:`InsertPortItem` without a port group:
1101 the port group of the port before its new position; at index ``0``, the port group of the first port. A move to
1102 the port's current position changes nothing.
1104 :param portItem: The port to move.
1105 :param index: Position of the port after the move, from ``0`` (first) to the length of :data:`PortItems`
1106 minus one (last). A negative index counts from the end, as for a :class:`list` index:
1107 ``-1`` moves the port to the end.
1108 :raises ValueError: If parameter 'portItem' is ``None``.
1109 :raises TypeError: If parameter 'portItem' is not of type
1110 :class:`~pyVHDLModel.Interface.PortSignalInterfaceItem`.
1111 :raises NotAChildError: If parameter 'portItem' is not a port of this language construct.
1112 :raises ValueError: If parameter 'index' is ``None``.
1113 :raises TypeError: If parameter 'index' is not of type :class:`int`.
1114 :raises ValueError: If parameter 'index' is out of range.
1116 .. seealso::
1118 :meth:`InsertPortItem`
1119 |rarr| Insert a port at a position of the port clause.
1120 :meth:`RemovePortItem`
1121 |rarr| Remove a port from the port clause.
1122 """
1123 from pyVHDLModel.Interface import PortSignalInterfaceItem
1125 if portItem is None:
1126 raise ValueError("Parameter 'portItem' is None.")
1127 elif not isinstance(portItem, PortSignalInterfaceItem):
1128 ex = TypeError("Parameter 'portItem' is not of type 'PortSignalInterfaceItem'.")
1129 ex.add_note(f"Got type '{getFullyQualifiedName(portItem)}'.")
1130 raise ex
1132 for currentIndex, item in enumerate(self._portItems):
1133 if item is portItem:
1134 break
1135 else:
1136 identifiers = ", ".join(identifiersOf(portItem))
1137 raise NotAChildError(
1138 f"{getTypeName(portItem)} '{identifiers}' is not a port of this {getTypeName(self)}.",
1139 element=portItem,
1140 parent=self
1141 )
1143 if index is None: 1143 ↛ 1144line 1143 didn't jump to line 1144 because the condition on line 1143 was never true
1144 raise ValueError("Parameter 'index' is None.")
1145 elif not isinstance(index, int): 1145 ↛ 1146line 1145 didn't jump to line 1146 because the condition on line 1145 was never true
1146 ex = TypeError("Parameter 'index' is not of type 'int'.")
1147 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
1148 raise ex
1149 elif not (-len(self._portItems) <= index < len(self._portItems)):
1150 ex = ValueError(f"Parameter 'index' is out of range {-len(self._portItems)}..{len(self._portItems) - 1}.")
1151 ex.add_note(f"Got value '{index}'.")
1152 raise ex
1154 newIndex = index if index >= 0 else len(self._portItems) + index
1155 if newIndex == currentIndex:
1156 return
1158 del self._portItems[currentIndex]
1159 self._portItems.insert(newIndex, portItem)
1160 self._RemoveFromPortGroup(portItem)
1161 self._AddToPortGroup(newIndex, portItem)
1163 def SplitPortItem(
1164 self,
1165 portItem: PortSignalInterfaceItem
1166 ) -> tuple[PortSignalInterfaceItem, ...]:
1167 """
1168 Split a port with an identifier list into one port per identifier.
1170 The port keeps its first identifier. For every other identifier, a new port is created by its
1171 ``Copy()`` and inserted right after it, in list order, in the port clause and in the port's port group; its parent
1172 is set to this language construct. If the language construct has a namespace, the entries of the other identifiers
1173 refer to the new ports. A port declaring one identifier is unchanged.
1175 :param portItem: The port to split.
1176 :returns: Tuple of ports, one per identifier in list order, starting with the split
1177 port.
1178 :raises ValueError: If parameter 'portItem' is ``None``.
1179 :raises TypeError: If parameter 'portItem' is not of type
1180 :class:`~pyVHDLModel.Interface.PortSignalInterfaceItem`.
1181 :raises NotAChildError: If parameter 'portItem' is not a port of this language construct.
1182 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the port refers to another
1183 element, e.g. a duplicate declaration.
1185 .. seealso::
1187 :meth:`~pyVHDLModel.Base.MultipleNamedEntityMixin.Split`
1188 |rarr| Split a declaration with an identifier list.
1189 :meth:`RemovePortItem`
1190 |rarr| Remove a port from the port clause.
1191 """
1192 from pyVHDLModel.Interface import PortSignalInterfaceItem
1194 if portItem is None:
1195 raise ValueError("Parameter 'portItem' is None.")
1196 elif not isinstance(portItem, PortSignalInterfaceItem):
1197 ex = TypeError("Parameter 'portItem' is not of type 'PortSignalInterfaceItem'.")
1198 ex.add_note(f"Got type '{getFullyQualifiedName(portItem)}'.")
1199 raise ex
1201 for index, item in enumerate(self._portItems):
1202 if item is portItem:
1203 break
1204 else:
1205 identifiers = ", ".join(identifiersOf(portItem))
1206 raise NotAChildError(
1207 f"{getTypeName(portItem)} '{identifiers}' is not a port of this {getTypeName(self)}.",
1208 element=portItem,
1209 parent=self
1210 )
1212 if not isinstance(portItem, MultipleNamedEntityMixin) or len(portItem._identifiers) == 1:
1213 return (portItem, )
1215 portGroup = portItem._group
1216 groupItems = portGroup._portItems
1217 for groupIndex, item in enumerate(groupItems): 1217 ↛ 1221line 1217 didn't jump to line 1221 because the loop on line 1217 didn't complete
1218 if item is portItem:
1219 break
1221 declarations = portItem._SplitCopies()
1222 self._RemoveFromNamespace(portItem)
1223 portItem._KeepIdentifier(0)
1224 self._portItems[index + 1:index + 1] = declarations
1225 groupItems[groupIndex + 1:groupIndex + 1] = declarations
1226 self._AddToNamespace(portItem)
1227 for declaration in declarations:
1228 declaration.Parent = self
1229 declaration._group = portGroup
1230 self._AddToNamespace(declaration)
1232 return (portItem, *declarations)
1234 @expects("_namespace")
1235 def _IndexPortItems(self) -> None:
1236 """Add the ports to the host's namespace."""
1237 for item in self._portItems:
1238 for normalizedIdentifier in normalizedIdentifiersOf(item):
1239 self._namespace.AddElement(normalizedIdentifier, item)
1241 def _VisitPortClause(self, visitor: Visitor) -> None:
1242 """
1243 Walk the port clause, if there are ports, with a visitor.
1245 The ports are separated by semicolons.
1247 :param visitor: The visitor receiving the events.
1248 """
1249 if len(self._portItems) == 0:
1250 return
1252 visitor.VisitPortClause(self)
1253 for index, item in enumerate(self._portItems):
1254 if index > 0:
1255 visitor.VisitInterfaceListSeparator(self)
1257 item.Visit(visitor)
1259 visitor.DepartPortClause(self)
1262@export
1263class WithParametersMixin(
1264 metaclass=ExtendedType,
1265 mixin=True,
1266 expects=("_AddToNamespace", "_RemoveFromNamespace", "_ClashingDeclarations", "_ParameterItemsChanged")
1267):
1268 """
1269 A mixin-class for language constructs with a parameter list.
1271 The host class provides ``_AddToNamespace(element)`` and ``_RemoveFromNamespace(element)``, called when a parameter is
1272 inserted or removed: :class:`~pyVHDLModel.Regions.DeclarativeRegionMixin` updates its namespace, a language construct
1273 without a namespace implements both as no-operations.
1275 The host class also provides ``_ClashingDeclarations(item)``, called before a parameter is inserted: it returns the
1276 declarations sharing an identifier with the new item.
1278 The host class provides ``_ParameterItemsChanged()`` too, called after a parameter is inserted, removed or moved:
1279 :class:`~pyVHDLModel.Subprogram.Subprogram` clears its signature.
1281 Indexing the parameters (``_IndexParameterItems()``) needs the host's namespace ``_namespace``.
1283 The parameter groups (:data:`ParameterGroups`) partition the parameter list: concatenated in order, they list every
1284 parameter exactly once, in declaration order. The mutators keep this partition.
1286 .. seealso::
1288 * :class:`Subprogram <pyVHDLModel.Subprogram.Subprogram>`
1289 * :class:`Parameter group <pyVHDLModel.Interface.ParameterGroup>`
1290 """
1291 _parameterItems: list[ParameterInterfaceItemMixin] #: List of all parameters, in declaration order.
1292 _parameterGroups: list[ParameterGroup] #: List of all parameter groups, in declaration order.
1294 def __init__(
1295 self,
1296 parameterItems: Nullable[Iterable[ParameterInterfaceItemMixin]] = None,
1297 parameterGroups: Nullable[Iterable[ParameterGroup]] = None
1298 ) -> None:
1299 """
1300 Initializes a language construct with a parameter list.
1302 The language construct becomes the parent of each parameter group, and each parameter refers to its parameter
1303 group. Without parameter groups, all parameters form one unnamed parameter group; no parameters form no parameter
1304 group.
1306 :param parameterItems: Optional, list of all parameters, in declaration order. Default: ``None``, no parameters.
1307 :param parameterGroups: Optional, list of parameter groups partitioning the parameters, in declaration order.
1308 Default: ``None``, one unnamed parameter group.
1309 :raises TypeError: If parameter 'parameterGroups' is ``None`` and an element of parameter 'parameterItems' is
1310 not of type :class:`~pyVHDLModel.Interface.ParameterInterfaceItemMixin`.
1311 :raises ValueError: If parameter 'parameterGroups' is ``None`` and an element of parameter 'parameterItems' is
1312 in a parameter group of another language construct.
1313 :raises TypeError: If parameter 'parameterGroups' is not iterable.
1314 :raises TypeError: If an element of parameter 'parameterGroups' is not of type
1315 :class:`~pyVHDLModel.Interface.ParameterGroup`.
1316 :raises ValueError: If parameter 'parameterGroups' doesn't list every parameter of parameter 'parameterItems'
1317 exactly once, in declaration order.
1318 """
1319 from pyVHDLModel.Interface import ParameterGroup
1321 self._parameterItems = parameterItemList = []
1322 if parameterItems is not None:
1323 for item in parameterItems:
1324 parameterItemList.append(item)
1325 item.Parent = self
1327 self._parameterGroups = parameterGroupList = []
1328 if parameterGroups is None:
1329 if len(parameterItemList) > 0:
1330 parameterGroup = ParameterGroup(parameterItemList, parent=self)
1331 parameterGroupList.append(parameterGroup)
1332 for item in parameterItemList:
1333 item._group = parameterGroup
1335 return
1337 if not isinstance(parameterGroups, Iterable):
1338 ex = TypeError("Parameter 'parameterGroups' is not iterable.")
1339 ex.add_note(f"Got type '{getFullyQualifiedName(parameterGroups)}'.")
1340 raise ex
1342 groupedItems = []
1343 for parameterGroup in parameterGroups:
1344 if not isinstance(parameterGroup, ParameterGroup):
1345 ex = TypeError("Element of parameter 'parameterGroups' is not of type 'ParameterGroup'.")
1346 ex.add_note(f"Got type '{getFullyQualifiedName(parameterGroup)}'.")
1347 raise ex
1349 parameterGroupList.append(parameterGroup)
1350 groupedItems.extend(parameterGroup._parameterItems)
1352 isPartition = len(groupedItems) == len(parameterItemList) and all(
1353 grouped is item for grouped, item in zip(groupedItems, parameterItemList)
1354 )
1355 if not isPartition:
1356 groups = " | ".join(
1357 ", ".join(name for item in parameterGroup._parameterItems for name in item._identifiers)
1358 for parameterGroup in parameterGroupList
1359 )
1360 parameters = ", ".join(name for item in parameterItemList for name in item._identifiers)
1361 ex = ValueError("Parameter 'parameterGroups' doesn't partition parameter 'parameterItems'.")
1362 ex.add_note(f"Got parameter groups '{groups}' for parameters '{parameters}'.")
1363 raise ex
1365 for parameterGroup in parameterGroupList:
1366 parameterGroup.Parent = self
1367 for item in parameterGroup._parameterItems:
1368 item._group = parameterGroup
1370 @readonly
1371 def ParameterItems(self) -> list[ParameterInterfaceItemMixin]:
1372 """
1373 Read-only property to access the parameter items (:attr:`_parameterItems`).
1375 :returns: List of parameter items.
1376 """
1377 return self._parameterItems
1379 @readonly
1380 def ParameterCount(self) -> int:
1381 """
1382 Read-only property to return the number of parameters declared by :attr:`_parameterItems`.
1384 A parameter item with several identifiers (``procedure p(a, b : in bit)``) declares several parameters.
1386 :returns: The number of parameters.
1387 """
1388 return sum(len(item._identifiers) for item in self._parameterItems)
1390 @readonly
1391 def ParameterGroups(self) -> list[ParameterGroup]:
1392 """
1393 Read-only property to access the parameter groups (:attr:`_parameterGroups`).
1395 The parameter groups partition the parameter list: concatenated in order, they list every parameter exactly once,
1396 in declaration order.
1398 :returns: List of parameter groups, in declaration order.
1399 """
1400 return self._parameterGroups
1402 def IterateSingleParameterDeclarations(
1403 self,
1404 predicate: Nullable[Callable[[SingleParameterDeclarationMixin], bool]] = None
1405 ) -> Generator[SingleParameterDeclarationMixin, None, None]:
1406 """
1407 Iterate all parameters per declared identifier, in declaration order.
1409 A parameter yields one single declaration per identifier: ``(a, b : in integer)`` yields two.
1411 :param predicate: Optional, filter function to select the yielded parameters. Default: all.
1412 :returns: A generator to iterate all (selected) parameters.
1413 """
1414 if predicate is None:
1415 for item in self._parameterItems:
1416 yield from item.SingleDeclarations
1417 else:
1418 for item in self._parameterItems:
1419 for singleDeclaration in item.SingleDeclarations:
1420 if predicate(singleDeclaration):
1421 yield singleDeclaration
1423 def AddParameterItem(
1424 self,
1425 parameterItem: ParameterInterfaceItemMixin,
1426 group: Nullable[ParameterGroup] = None
1427 ) -> None:
1428 """
1429 Add a parameter at the end of the parameter list, or at the end of a parameter group.
1431 The parameter's parent is set to this language construct, and its identifiers are added to the language construct's
1432 namespace, if it has one. Without a parameter group, the parameter joins the last parameter group, or forms a new
1433 unnamed parameter group if there are no parameters.
1435 :param parameterItem: The parameter to add.
1436 :param group: Optional, the parameter group of this language construct to add the parameter to,
1437 at its end. Default: ``None``, the end of the parameter list.
1438 :raises ValueError: If parameter 'parameterItem' is ``None``.
1439 :raises TypeError: If parameter 'parameterItem' is not of type
1440 :class:`~pyVHDLModel.Interface.ParameterInterfaceItemMixin`.
1441 :raises AlreadyInDesignError: If parameter 'parameterItem' already has a parent.
1442 :raises TypeError: If parameter 'group' is not of type :class:`~pyVHDLModel.Interface.ParameterGroup`.
1443 :raises NotAChildError: If parameter 'group' is not a parameter group of this language construct.
1444 :raises DuplicateParameterError: If an existing declaration of the language construct shares an identifier
1445 with the parameter.
1447 .. seealso::
1449 :meth:`InsertParameterItem`
1450 |rarr| Insert a parameter at a position of the parameter list.
1451 :meth:`RemoveParameterItem`
1452 |rarr| Remove a parameter from the parameter list.
1453 """
1454 index = len(self._parameterItems)
1455 if group is not None:
1456 index = 0
1457 for parameterGroup in self._parameterGroups:
1458 index += len(parameterGroup._parameterItems)
1459 if parameterGroup is group:
1460 break
1462 self.InsertParameterItem(index, parameterItem, group)
1464 def InsertParameterItem(
1465 self,
1466 index: int,
1467 parameterItem: ParameterInterfaceItemMixin,
1468 group: Nullable[ParameterGroup] = None
1469 ) -> None:
1470 """
1471 Insert a parameter at a position of the parameter list.
1473 The parameter's parent is set to this language construct, and its identifiers are added to the language construct's
1474 namespace, if it has one.
1476 Without a parameter group, the parameter joins the parameter group of the parameter before ``index``; at index
1477 ``0``, the parameter group of the first parameter. If there are no parameters, the parameter forms a new unnamed
1478 parameter group. A parameter group given must contain ``index`` or end at it, so the parameter groups stay
1479 contiguous.
1481 :param index: Position, from ``0`` (first) to the length of :data:`ParameterItems` (append).
1482 A negative index counts from the end, as for :meth:`list.insert`: ``-1`` inserts
1483 before the last parameter.
1484 :param parameterItem: The parameter to insert.
1485 :param group: Optional, the parameter group of this language construct to insert the parameter
1486 into. Default: ``None``, the parameter group of the parameter before ``index``.
1487 :raises ValueError: If parameter 'index' is ``None``.
1488 :raises TypeError: If parameter 'index' is not of type :class:`int`.
1489 :raises ValueError: If parameter 'index' is out of range.
1490 :raises ValueError: If parameter 'parameterItem' is ``None``.
1491 :raises TypeError: If parameter 'parameterItem' is not of type
1492 :class:`~pyVHDLModel.Interface.ParameterInterfaceItemMixin`.
1493 :raises AlreadyInDesignError: If parameter 'parameterItem' already has a parent.
1494 :raises TypeError: If parameter 'group' is not of type :class:`~pyVHDLModel.Interface.ParameterGroup`.
1495 :raises NotAChildError: If parameter 'group' is not a parameter group of this language construct.
1496 :raises ValueError: If parameter 'group' neither contains nor ends at parameter 'index'.
1497 :raises DuplicateParameterError: If an existing declaration of the language construct shares an identifier
1498 with the parameter.
1500 .. seealso::
1502 :meth:`AddParameterItem`
1503 |rarr| Add a parameter at the end of the parameter list.
1504 :meth:`RemoveParameterItem`
1505 |rarr| Remove a parameter from the parameter list.
1506 :meth:`MoveParameterItem`
1507 |rarr| Move a parameter to a position of the parameter list.
1508 """
1509 from pyVHDLModel.Interface import ParameterInterfaceItemMixin, ParameterGroup
1511 if index is None: 1511 ↛ 1512line 1511 didn't jump to line 1512 because the condition on line 1511 was never true
1512 raise ValueError("Parameter 'index' is None.")
1513 elif not isinstance(index, int): 1513 ↛ 1514line 1513 didn't jump to line 1514 because the condition on line 1513 was never true
1514 ex = TypeError("Parameter 'index' is not of type 'int'.")
1515 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
1516 raise ex
1517 elif not (-len(self._parameterItems) <= index <= len(self._parameterItems)):
1518 ex = ValueError(f"Parameter 'index' is out of range {-len(self._parameterItems)}..{len(self._parameterItems)}.")
1519 ex.add_note(f"Got value '{index}'.")
1520 raise ex
1522 if parameterItem is None:
1523 raise ValueError("Parameter 'parameterItem' is None.")
1524 elif not isinstance(parameterItem, ParameterInterfaceItemMixin):
1525 ex = TypeError("Parameter 'parameterItem' is not of type 'ParameterInterfaceItemMixin'.")
1526 ex.add_note(f"Got type '{getFullyQualifiedName(parameterItem)}'.")
1527 raise ex
1528 elif parameterItem._parent is not None:
1529 identifiers = ", ".join(identifiersOf(parameterItem))
1530 ex = AlreadyInDesignError(
1531 f"{getTypeName(parameterItem)} '{identifiers}' already has a parent.",
1532 element=parameterItem,
1533 parent=parameterItem._parent
1534 )
1535 ex.add_note(f"Remove it from its {getTypeName(parameterItem._parent)} first.")
1536 raise ex
1538 position = index if index >= 0 else len(self._parameterItems) + index
1539 if group is not None:
1540 if not isinstance(group, ParameterGroup):
1541 ex = TypeError("Parameter 'group' is not of type 'ParameterGroup'.")
1542 ex.add_note(f"Got type '{getFullyQualifiedName(group)}'.")
1543 raise ex
1545 groupStart = 0
1546 for parameterGroup in self._parameterGroups:
1547 if parameterGroup is group:
1548 break
1550 groupStart += len(parameterGroup._parameterItems)
1551 else:
1552 groupName = getTypeName(group) if group._identifier is None else f"{getTypeName(group)} '{group._identifier}'"
1553 raise NotAChildError(
1554 f"{groupName} is not a parameter group of this {getTypeName(self)}.",
1555 element=group,
1556 parent=self
1557 )
1559 groupEnd = groupStart + len(group._parameterItems)
1560 if not (groupStart <= position <= groupEnd):
1561 ex = ValueError(f"Parameter 'index' is outside of parameter 'group' at {groupStart}..{groupEnd}.")
1562 ex.add_note(f"Got value '{index}'.")
1563 raise ex
1565 if len(clashes := self._ClashingDeclarations(parameterItem)) > 0:
1566 existingIdentifiers = normalizedIdentifiersOf(clashes[0])
1567 newIdentifiers = zip(identifiersOf(parameterItem), normalizedIdentifiersOf(parameterItem))
1568 identifier = next(name for name, normalizedName in newIdentifiers if normalizedName in existingIdentifiers)
1569 ex = DuplicateParameterError(
1570 f"{getTypeName(clashes[0]._parent)} already declares '{identifier}'.",
1571 identifier=identifier,
1572 parent=self,
1573 element=parameterItem,
1574 existing=clashes[0]
1575 )
1576 ex.add_note(f"Existing declaration is of type '{getFullyQualifiedName(clashes[0])}'.")
1577 raise ex
1579 self._parameterItems.insert(position, parameterItem)
1580 parameterItem.Parent = self
1581 if group is None:
1582 self._AddToParameterGroup(position, parameterItem)
1583 else:
1584 group._parameterItems.insert(position - groupStart, parameterItem)
1585 parameterItem._group = group
1587 self._AddToNamespace(parameterItem)
1588 self._ParameterItemsChanged()
1590 def _AddToParameterGroup(self, position: int, parameterItem: ParameterInterfaceItemMixin) -> None:
1591 """
1592 Add a parameter to the parameter group of the parameter before ``position``.
1594 At position ``0``, the parameter joins the parameter group of the first parameter. If there are no parameter
1595 groups, the parameter forms a new unnamed parameter group.
1597 :param position: Position of the parameter in the parameter list, from ``0`` (first) to the length of
1598 :data:`ParameterItems` (last).
1599 :param parameterItem: The parameter to add, which isn't in a parameter group.
1600 """
1601 from pyVHDLModel.Interface import ParameterGroup
1603 groupStart = 0
1604 for parameterGroup in self._parameterGroups:
1605 groupEnd = groupStart + len(parameterGroup._parameterItems)
1606 if position <= groupEnd:
1607 parameterGroup._parameterItems.insert(position - groupStart, parameterItem)
1608 parameterItem._group = parameterGroup
1609 return
1611 groupStart = groupEnd
1613 parameterGroup = ParameterGroup((parameterItem, ), parent=self)
1614 self._parameterGroups.append(parameterGroup)
1615 parameterItem._group = parameterGroup
1617 def RemoveParameterItem(self, parameterItem: ParameterInterfaceItemMixin) -> None:
1618 """
1619 Remove a parameter from the parameter list.
1621 The parameter is detached: its parent and parameter group are cleared and its identifiers are removed from the
1622 language construct's namespace, if it has one. A parameter group, which becomes empty, is removed from
1623 :data:`ParameterGroups` and its parent is cleared. The parameter itself is unchanged and can be added to another
1624 language construct, or inserted at another position.
1626 :param parameterItem: The parameter to remove.
1627 :raises ValueError: If parameter 'parameterItem' is ``None``.
1628 :raises TypeError: If parameter 'parameterItem' is not of type
1629 :class:`~pyVHDLModel.Interface.ParameterInterfaceItemMixin`.
1630 :raises NotAChildError: If parameter 'parameterItem' is not a parameter of this language construct.
1631 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the parameter isn't declared in it.
1632 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the parameter refers to another
1633 element, e.g. a duplicate declaration.
1635 .. seealso::
1637 :meth:`AddParameterItem`
1638 |rarr| Add a parameter at the end of the parameter list.
1639 :meth:`InsertParameterItem`
1640 |rarr| Insert a parameter at a position of the parameter list.
1641 :meth:`MoveParameterItem`
1642 |rarr| Move a parameter to a position of the parameter list.
1643 """
1644 from pyVHDLModel.Interface import ParameterInterfaceItemMixin
1646 if parameterItem is None:
1647 raise ValueError("Parameter 'parameterItem' is None.")
1648 elif not isinstance(parameterItem, ParameterInterfaceItemMixin):
1649 ex = TypeError("Parameter 'parameterItem' is not of type 'ParameterInterfaceItemMixin'.")
1650 ex.add_note(f"Got type '{getFullyQualifiedName(parameterItem)}'.")
1651 raise ex
1653 for index, item in enumerate(self._parameterItems):
1654 if item is parameterItem:
1655 break
1656 else:
1657 identifiers = ", ".join(identifiersOf(parameterItem))
1658 raise NotAChildError(
1659 f"{getTypeName(parameterItem)} '{identifiers}' is not a parameter of this {getTypeName(self)}.",
1660 element=parameterItem,
1661 parent=self
1662 )
1664 self._RemoveFromNamespace(parameterItem)
1665 del self._parameterItems[index]
1666 self._RemoveFromParameterGroup(parameterItem)
1667 parameterItem._parent = None
1668 self._ParameterItemsChanged()
1670 def _RemoveFromParameterGroup(self, parameterItem: ParameterInterfaceItemMixin) -> None:
1671 """
1672 Remove a parameter from its parameter group and clear the parameter's group.
1674 A parameter group, which becomes empty, is removed from :data:`ParameterGroups` and its parent is cleared.
1676 :param parameterItem: The parameter to remove from its parameter group.
1677 """
1678 parameterGroup = parameterItem._group
1679 groupItems = parameterGroup._parameterItems
1680 for index, item in enumerate(groupItems): 1680 ↛ 1685line 1680 didn't jump to line 1685 because the loop on line 1680 didn't complete
1681 if item is parameterItem:
1682 del groupItems[index]
1683 break
1685 if len(groupItems) == 0:
1686 self._parameterGroups.remove(parameterGroup)
1687 parameterGroup._parent = None
1689 parameterItem._group = None
1691 def MoveParameterItem(self, parameterItem: ParameterInterfaceItemMixin, index: int) -> None:
1692 """
1693 Move a parameter to a position of the parameter list.
1695 The parameter stays a parameter of this language construct: only the order of the parameter list changes.
1697 The parameter leaves its parameter group, like :meth:`RemoveParameterItem`, and joins a parameter group, like
1698 :meth:`InsertParameterItem` without a parameter group: the parameter group of the parameter before its new
1699 position; at index ``0``, the parameter group of the first parameter. A move to the parameter's current position
1700 changes nothing.
1702 :param parameterItem: The parameter to move.
1703 :param index: Position of the parameter after the move, from ``0`` (first) to the length of
1704 :data:`ParameterItems` minus one (last). A negative index counts from the end, as for a
1705 :class:`list` index: ``-1`` moves the parameter to the end.
1706 :raises ValueError: If parameter 'parameterItem' is ``None``.
1707 :raises TypeError: If parameter 'parameterItem' is not of type
1708 :class:`~pyVHDLModel.Interface.ParameterInterfaceItemMixin`.
1709 :raises NotAChildError: If parameter 'parameterItem' is not a parameter of this language construct.
1710 :raises ValueError: If parameter 'index' is ``None``.
1711 :raises TypeError: If parameter 'index' is not of type :class:`int`.
1712 :raises ValueError: If parameter 'index' is out of range.
1714 .. seealso::
1716 :meth:`InsertParameterItem`
1717 |rarr| Insert a parameter at a position of the parameter list.
1718 :meth:`RemoveParameterItem`
1719 |rarr| Remove a parameter from the parameter list.
1720 """
1721 from pyVHDLModel.Interface import ParameterInterfaceItemMixin
1723 if parameterItem is None:
1724 raise ValueError("Parameter 'parameterItem' is None.")
1725 elif not isinstance(parameterItem, ParameterInterfaceItemMixin):
1726 ex = TypeError("Parameter 'parameterItem' is not of type 'ParameterInterfaceItemMixin'.")
1727 ex.add_note(f"Got type '{getFullyQualifiedName(parameterItem)}'.")
1728 raise ex
1730 for currentIndex, item in enumerate(self._parameterItems):
1731 if item is parameterItem:
1732 break
1733 else:
1734 identifiers = ", ".join(identifiersOf(parameterItem))
1735 raise NotAChildError(
1736 f"{getTypeName(parameterItem)} '{identifiers}' is not a parameter of this {getTypeName(self)}.",
1737 element=parameterItem,
1738 parent=self
1739 )
1741 if index is None: 1741 ↛ 1742line 1741 didn't jump to line 1742 because the condition on line 1741 was never true
1742 raise ValueError("Parameter 'index' is None.")
1743 elif not isinstance(index, int): 1743 ↛ 1744line 1743 didn't jump to line 1744 because the condition on line 1743 was never true
1744 ex = TypeError("Parameter 'index' is not of type 'int'.")
1745 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
1746 raise ex
1747 elif not (-len(self._parameterItems) <= index < len(self._parameterItems)):
1748 ex = ValueError(
1749 f"Parameter 'index' is out of range {-len(self._parameterItems)}..{len(self._parameterItems) - 1}."
1750 )
1751 ex.add_note(f"Got value '{index}'.")
1752 raise ex
1754 newIndex = index if index >= 0 else len(self._parameterItems) + index
1755 if newIndex == currentIndex:
1756 return
1758 del self._parameterItems[currentIndex]
1759 self._parameterItems.insert(newIndex, parameterItem)
1760 self._RemoveFromParameterGroup(parameterItem)
1761 self._AddToParameterGroup(newIndex, parameterItem)
1762 self._ParameterItemsChanged()
1764 def SplitParameterItem(
1765 self,
1766 parameterItem: ParameterInterfaceItemMixin
1767 ) -> tuple[ParameterInterfaceItemMixin, ...]:
1768 """
1769 Split a parameter with an identifier list into one parameter per identifier.
1771 The parameter keeps its first identifier. For every other identifier, a new parameter is created by its
1772 ``Copy()`` and inserted right after it, in list order, in the parameter list and in the parameter's parameter
1773 group; its parent is set to this language construct. If the language construct has a namespace, the entries of the
1774 other identifiers refer to the new parameters. A parameter declaring one identifier is unchanged.
1776 :param parameterItem: The parameter to split.
1777 :returns: Tuple of parameters, one per identifier in list order, starting with the split
1778 parameter.
1779 :raises ValueError: If parameter 'parameterItem' is ``None``.
1780 :raises TypeError: If parameter 'parameterItem' is not of type
1781 :class:`~pyVHDLModel.Interface.ParameterInterfaceItemMixin`.
1782 :raises NotAChildError: If parameter 'parameterItem' is not a parameter of this language construct.
1783 :raises NotInNamespaceError: If the namespace is indexed, and an identifier of the parameter refers to another
1784 element, e.g. a duplicate declaration.
1786 .. seealso::
1788 :meth:`~pyVHDLModel.Base.MultipleNamedEntityMixin.Split`
1789 |rarr| Split a declaration with an identifier list.
1790 :meth:`RemoveParameterItem`
1791 |rarr| Remove a parameter from the parameter list.
1792 """
1793 from pyVHDLModel.Interface import ParameterInterfaceItemMixin
1795 if parameterItem is None:
1796 raise ValueError("Parameter 'parameterItem' is None.")
1797 elif not isinstance(parameterItem, ParameterInterfaceItemMixin):
1798 ex = TypeError("Parameter 'parameterItem' is not of type 'ParameterInterfaceItemMixin'.")
1799 ex.add_note(f"Got type '{getFullyQualifiedName(parameterItem)}'.")
1800 raise ex
1802 for index, item in enumerate(self._parameterItems):
1803 if item is parameterItem:
1804 break
1805 else:
1806 identifiers = ", ".join(identifiersOf(parameterItem))
1807 raise NotAChildError(
1808 f"{getTypeName(parameterItem)} '{identifiers}' is not a parameter of this {getTypeName(self)}.",
1809 element=parameterItem,
1810 parent=self
1811 )
1813 if not isinstance(parameterItem, MultipleNamedEntityMixin) or len(parameterItem._identifiers) == 1:
1814 return (parameterItem, )
1816 parameterGroup = parameterItem._group
1817 groupItems = parameterGroup._parameterItems
1818 for groupIndex, item in enumerate(groupItems): 1818 ↛ 1822line 1818 didn't jump to line 1822 because the loop on line 1818 didn't complete
1819 if item is parameterItem:
1820 break
1822 declarations = parameterItem._SplitCopies()
1823 self._RemoveFromNamespace(parameterItem)
1824 parameterItem._KeepIdentifier(0)
1825 self._parameterItems[index + 1:index + 1] = declarations
1826 groupItems[groupIndex + 1:groupIndex + 1] = declarations
1827 self._AddToNamespace(parameterItem)
1828 for declaration in declarations:
1829 declaration.Parent = self
1830 declaration._group = parameterGroup
1831 self._AddToNamespace(declaration)
1832 self._ParameterItemsChanged()
1834 return (parameterItem, *declarations)
1836 @expects("_namespace")
1837 def _IndexParameterItems(self) -> None:
1838 """Add the parameters to the host's namespace."""
1839 for item in self._parameterItems:
1840 for normalizedIdentifier in normalizedIdentifiersOf(item):
1841 self._namespace.AddElement(normalizedIdentifier, item)
1843 def _VisitFormalParameterList(self, visitor: Visitor) -> None:
1844 """
1845 Walk the formal parameter list, if there are parameters, with a visitor.
1847 The parameters are separated by semicolons.
1849 :param visitor: The visitor receiving the events.
1850 """
1851 if len(self._parameterItems) == 0:
1852 return
1854 visitor.VisitFormalParameterList(self)
1855 for index, item in enumerate(self._parameterItems):
1856 if index > 0:
1857 visitor.VisitInterfaceListSeparator(self)
1859 item.Visit(visitor)
1861 visitor.DepartFormalParameterList(self)
1864@export
1865class DeclarativeRegionMixin(
1866 metaclass=ExtendedType,
1867 mixin=True,
1868 expects=(
1869 "_namespace",
1870 "_Declarations",
1871 "IndexDeclaredItems",
1872 "_Labels",
1873 "_IterateStatementRegions"
1874 )
1875):
1876 """
1877 A mixin-class for language constructs forming a declarative region.
1879 A declarative region (IEEE Std 1076-2008, 12.1) has a namespace, nested in the namespace of the enclosing declarative
1880 region. It carries what all regions share: looking up names (:meth:`LookupName`, :meth:`ResolveTypeMark`), the
1881 declaration order (:meth:`Precedes`), the nested regions (:meth:`IterateDeclarationRegions`), and adding interface
1882 items to the region's namespace.
1884 The host class provides the namespace ``_namespace`` and the methods ``_Declarations()`` and
1885 ``IndexDeclaredItems()``. A language construct with a declarative part gets them from
1886 :class:`DeclarationRegionMixin` and its derived region mixin-classes; a component declaration, a declarative region
1887 without a declarative part, provides them itself.
1889 An interface item shares the declarative region of the declarative part beside it - VHDL rejects
1890 ``port (g : in bit)`` beside ``generic (g : integer)``, ``signal x`` beside ``port (x : in bit)``, and a
1891 subprogram variable named like one of its parameters, all as "identifier already used for a
1892 declaration". So they belong in the region's *own* namespace, not a separate one.
1894 Which of the three a region has is known statically by the class that declares them, so each derived
1895 class calls the ones it needs from its own ``IndexDeclaredItems()`` before delegating upwards.
1896 Interface items are added to the namespace only - ``GenericItems``/``PortItems``/``ParameterItems``
1897 already expose them as ordered lists, so no extra lookup table is needed.
1899 A statement label is declared implicitly in the declarative region enclosing the statement, so the host provides the
1900 labeled statements of the region by ``_Labels()``: a host with statements gets it from its statements mixin
1901 (e.g. :class:`~pyVHDLModel.Concurrent.ConcurrentStatementsMixin`), a host without statements from
1902 :class:`WithoutStatementsMixin`. The same holds for the declarative regions nested in the statements
1903 (``_IterateStatementRegions()``), which :meth:`IterateDeclarationRegions` walks.
1905 .. seealso::
1907 * :class:`Declaration region mixin <pyVHDLModel.Regions.DeclarationRegionMixin>`
1908 * :class:`Component <pyVHDLModel.DesignUnit.Component>`
1909 * :class:`Namespace <pyVHDLModel.Namespace.Namespace>`
1910 """
1911 _areDeclaredItemsIndexed: bool #: ``True`` if ``IndexDeclaredItems()`` filled the namespace.
1913 def __init__(self) -> None:
1914 """
1915 Initializes a declarative region, which isn't indexed yet.
1916 """
1917 self._areDeclaredItemsIndexed = False
1919 def IterateDeclarationRegions(self) -> Generator[DeclarativeRegionMixin, None, None]:
1920 """
1921 Iterate this declarative region and all declarative regions nested in it.
1923 Nested regions are declarations (e.g. subprograms, generic subprograms, protected types, packages) and concurrent
1924 statements (blocks, processes, generate statements and their branches), each followed by the regions nested in it.
1926 :returns: A generator to iterate the declarative regions, this region first.
1927 """
1928 yield self
1930 for item in self._Declarations():
1931 if isinstance(item, DeclarativeRegionMixin):
1932 yield from item.IterateDeclarationRegions()
1934 yield from self._IterateStatementRegions()
1936 def Precedes(self, item: Nullable[ModelEntity], anchor: ModelEntity, inclusive: bool) -> bool:
1937 """
1938 Check if an item precedes an anchor in this declarative region.
1940 An item, which isn't a declaration of this region (e.g. a use clause of the context clause), precedes every anchor.
1942 :param item: The item in declaration order, or ``None`` for the implicit use clause.
1943 :param anchor: A declaration of this region, e.g. the one containing the place of a lookup.
1944 :param inclusive: ``True``, if the anchor precedes itself, i.e. the place is nested inside the anchor.
1945 :returns: ``True``, if the item precedes the anchor.
1946 """
1947 itemIndex = None
1948 anchorIndex = None
1949 for index, declaration in enumerate(self._Declarations()):
1950 if declaration is item:
1951 itemIndex = index
1953 if declaration is anchor:
1954 anchorIndex = index
1956 if itemIndex is None or anchorIndex is None:
1957 return True
1959 return itemIndex < anchorIndex or (inclusive and itemIndex == anchorIndex)
1961 def LookupName(
1962 self,
1963 place: ModelEntity,
1964 symbol: Symbol,
1965 name: Name,
1966 warningType: type[UnresolvedNameWarning]
1967 ) -> tuple[ModelEntity, ...]:
1968 """
1969 Look up the declarations a simple name or an expanded name denotes at a place in this region.
1971 A simple name is looked up at the place (:meth:`~pyVHDLModel.Namespace.Namespace.Lookup`). An expanded name
1972 ``pkg.T`` or ``lib.pkg.T`` resolves its prefix: ``pkg`` to a package visible at the place, else to an enclosing
1973 declarative region of that name (e.g. the package or entity containing the place); ``lib.pkg`` by the library
1974 (``work`` or a library whose name is visible in the design unit containing the place,
1975 :meth:`~pyVHDLModel.DesignUnit.DesignUnit.IsLibraryVisible`) and the package's name. Then the suffix is searched
1976 among the declarations of the package (:meth:`~pyVHDLModel.DesignUnit.Package.FindMemberDeclarations`), e.g. of a
1977 package instantiation, or of the region (:meth:`~pyVHDLModel.Namespace.Namespace.FindDeclarations`). An
1978 operator symbol (:attr:`~pyVHDLModel.Name.Name.IsOperatorSymbol`) is looked up by the operator's designator, without
1979 the quotation marks, e.g. ``"="`` as ``=``.
1981 A failure is reported as a warning of the given type, whose label names the kind of name in the message
1982 (e.g. ``Type mark``); then no declaration is returned. A name, which is a part of the symbol's name (e.g. the prefix
1983 ``s`` of the type mark ``s'subtype``), is reported as a prefix of the symbol's name.
1985 :param place: The declaration containing the name.
1986 :param symbol: The symbol containing the name.
1987 :param name: The simple name or expanded name: the symbol's name or a part of it.
1988 :param warningType: The warning class reporting a failure.
1989 :returns: Tuple of the directly visible declarations, empty if none is.
1990 :raises UnhandledCriticalWarningError: If the name isn't visible, is ambiguous, or has a prefix, which isn't a
1991 visible package or an enclosing region, and no
1992 :class:`~pyTooling.Warning.WarningCollector` collects the warning.
1993 """
1994 from pyVHDLModel.DesignUnit import DesignUnit, Package
1996 namespace = self._namespace
1997 label = warningType._LABEL
1998 normalizedIdentifier = name._normalizedIdentifier[1:-1] if name.IsOperatorSymbol else name._normalizedIdentifier
1999 if name is symbol._name:
2000 subject = f"{label} '{name!s}'"
2001 else:
2002 subject = f"Prefix '{name!s}' of {label.lower()} '{symbol._name!s}'"
2004 if (prefix := name._prefix) is None:
2005 result = namespace.Lookup(normalizedIdentifier, place)
2006 if result.HasConflicts:
2007 WarningCollector.Raise(warningType(
2008 f"{subject} is ambiguous: use clauses import conflicting declarations.",
2009 symbol=symbol,
2010 place=place,
2011 namespaces=result._searchedNamespaces,
2012 conflicts=result._conflicts
2013 ))
2014 return ()
2016 declarations = result._declarations
2017 searchedNamespaces = result._searchedNamespaces
2018 else:
2019 searchedNamespaces = []
2020 searchedPackage = None
2021 if prefix._prefix is None:
2022 result = namespace.Lookup(prefix._normalizedIdentifier, place)
2023 packages = [declaration for declaration in result._declarations if isinstance(declaration, Package)]
2024 if len(packages) > 0:
2025 searchedPackage = packages[0]
2026 searchedNamespaces.append(searchedPackage._namespace)
2027 else:
2028 # An enclosing declarative region of that name, e.g. the package declaring the place.
2029 enclosingNamespace = namespace
2030 while enclosingNamespace is not None:
2031 namespaceName = enclosingNamespace._name
2032 if namespaceName is not None and namespaceName.lower() == prefix._normalizedIdentifier:
2033 searchedNamespaces.append(enclosingNamespace)
2035 enclosingNamespace = enclosingNamespace._parentNamespace
2036 elif prefix._prefix._prefix is None: 2036 ↛ 2050line 2036 didn't jump to line 2050 because the condition on line 2036 was always true
2037 libraryIdentifier = prefix._prefix._normalizedIdentifier
2038 designUnit = place.GetAncestor(DesignUnit)
2039 if libraryIdentifier == "work":
2040 library = designUnit._parent
2041 elif designUnit.IsLibraryVisible(libraryIdentifier):
2042 library = designUnit._parent._parent._libraries.get(libraryIdentifier)
2043 else:
2044 library = None
2046 if library is not None and (package := library._packages.get(prefix._normalizedIdentifier)) is not None:
2047 searchedPackage = package
2048 searchedNamespaces.append(package._namespace)
2050 if len(searchedNamespaces) == 0:
2051 WarningCollector.Raise(warningType(
2052 f"Prefix '{prefix!s}' of {label.lower()} '{symbol._name!s}' isn't a visible package or an enclosing region.",
2053 symbol=symbol,
2054 place=place,
2055 namespaces=(namespace, )
2056 ))
2057 return ()
2059 declarations = ()
2060 if searchedPackage is not None:
2061 declarations = searchedPackage.FindMemberDeclarations(normalizedIdentifier)
2062 else:
2063 for searchedNamespace in searchedNamespaces:
2064 if len(declarations := searchedNamespace.FindDeclarations(normalizedIdentifier)) > 0:
2065 break
2067 if len(declarations) == 0:
2068 # An unlabeled region (e.g. a process) has no name; a package body has the name of its package.
2069 names = []
2070 for searchedNamespace in searchedNamespaces:
2071 namespaceName = "?" if searchedNamespace._name is None else searchedNamespace._name
2072 if len(names) == 0 or names[-1] != namespaceName:
2073 names.append(namespaceName)
2075 WarningCollector.Raise(warningType(
2076 f"{subject} not found in: {', '.join(names)}.",
2077 symbol=symbol,
2078 place=place,
2079 namespaces=tuple(searchedNamespaces)
2080 ))
2082 return declarations
2084 def ResolveTypeMark(
2085 self,
2086 place: ModelEntity,
2087 symbol: SubtypeSymbol
2088 ) -> None:
2089 """
2090 Resolve a type mark at its place in this region and set the symbol's reference.
2092 .. rubric:: Algorithm
2094 1. Clear the symbol's reference.
2095 2. Look up the type mark's name (:meth:`LookupName`).
2096 3. An alias of a type is replaced by the type its name references, the copy of a generic type in a package
2097 instantiation by its actual (:meth:`PackageInstantiation.MapToInstance
2098 <pyVHDLModel.Instantiation.PackageInstantiation.MapToInstance>`).
2099 4. If the declaration is a type, a subtype or a generic type, it becomes the symbol's reference. A full type, which
2100 follows the place in the same region, is visible by its incomplete type declaration only to an access type.
2102 An attribute name denoting a type (e.g. ``s'subtype``, ``A'element``) is resolved part by part
2103 (:meth:`~pyVHDLModel.Name.Name.Denote`); the type it denotes becomes the symbol's reference.
2105 :param place: The declaration containing the type mark.
2106 :param symbol: The type mark.
2107 :raises UnhandledCriticalWarningError: If the type mark isn't visible, is ambiguous, has a prefix, which isn't a
2108 visible package, denotes no type, or denotes an incomplete type outside of an
2109 access type, and no :class:`~pyTooling.Warning.WarningCollector` collects
2110 the :exc:`~pyVHDLModel.Exception.UnresolvedTypeMarkWarning`.
2111 """
2112 from pyVHDLModel.Declaration import Alias
2113 from pyVHDLModel.Interface import GenericTypeInterfaceItem
2114 from pyVHDLModel.Type import AccessType, BaseType, FullType
2116 symbol._reference = None
2117 name = symbol._name
2118 if isinstance(name, AttributeName):
2119 if (typeOrSubtype := name.Denote(self, place, symbol)) is not None:
2120 symbol._reference = typeOrSubtype
2122 return
2124 if len(declarations := self.LookupName(place, symbol, name, UnresolvedTypeMarkWarning)) == 0:
2125 return
2127 declaration = declarations[0]
2128 if isinstance(declaration, Alias) and isinstance(declaration._name._reference, BaseType):
2129 declaration = declaration._name._reference
2130 elif isinstance(declaration, GenericTypeInterfaceItem) and declaration._original is not None:
2131 # The copy of a generic type in a package instantiation denotes the actual (IEEE Std 1076-2008, 4.9).
2132 declaration = declaration._parent.MapToInstance(declaration)
2134 if not isinstance(declaration, BaseType):
2135 WarningCollector.Raise(UnresolvedTypeMarkWarning(
2136 f"Type mark '{name!s}' doesn't denote a type or subtype (found: {declaration.__class__.__name__}).",
2137 symbol=symbol,
2138 place=place,
2139 namespaces=(self._namespace, )
2140 ))
2141 return
2142 elif (
2143 isinstance(declaration, FullType) and not isinstance(place, AccessType)
2144 and declaration._parent is (region := place._parent)
2145 ):
2146 if isinstance(region, DeclarativeRegionMixin): 2146 ↛ 2157line 2146 didn't jump to line 2157 because the condition on line 2146 was always true
2147 declarationsOfRegion = region._Declarations()
2148 if declarationsOfRegion.index(declaration) > declarationsOfRegion.index(place):
2149 WarningCollector.Raise(UnresolvedTypeMarkWarning(
2150 f"Type mark '{name!s}' denotes an incomplete type, which only an access type may use.",
2151 symbol=symbol,
2152 place=place,
2153 namespaces=(self._namespace, )
2154 ))
2155 return
2157 symbol._reference = declaration
2159 def _ConnectParentNamespace(self, parent: ModelEntity) -> None:
2160 """
2161 Connect this region's namespace to the namespace of the enclosing declarative region.
2163 A declaration of this region then hides a same-named declaration of the enclosing region. A parent, which isn't a
2164 declarative region (e.g. a subprogram of an interface list), has no namespace to connect to.
2166 :param parent: The new parent of this region.
2167 """
2168 if isinstance(parent, DeclarativeRegionMixin): 2168 ↛ exitline 2168 didn't return from function '_ConnectParentNamespace' because the condition on line 2168 was always true
2169 self._namespace.ParentNamespace = parent._namespace
2171 def _AddToNamespace(self, element: NamedEntityMixin | MultipleNamedEntityMixin) -> None:
2172 """
2173 Add an element's identifiers to this region's namespace.
2175 Nothing is added to a region not indexed yet: :meth:`IndexDeclaredItems` adds the element later. A generic
2176 subprogram is an overload (:meth:`_AddOverloadToNamespace`).
2178 :param element: The named element to add, e.g. an interface item.
2179 """
2180 from pyVHDLModel.Subprogram import Function, Procedure
2182 if not self._areDeclaredItemsIndexed:
2183 return
2184 elif isinstance(element, (Function, Procedure)):
2185 self._AddOverloadToNamespace(element)
2186 return
2188 for normalizedIdentifier in normalizedIdentifiersOf(element):
2189 self._namespace.AddElement(normalizedIdentifier, element)
2191 def _RemoveFromNamespace(self, element: NamedEntityMixin | MultipleNamedEntityMixin) -> None:
2192 """
2193 Remove an element's identifiers from this region's namespace.
2195 Nothing is removed from a region not indexed yet, as its namespace doesn't contain the element. A generic
2196 subprogram is an overload (:meth:`_RemoveOverloadFromNamespace`). The namespace is checked for every identifier
2197 before it's changed.
2199 :param element: The named element to remove, e.g. an interface item.
2200 :raises NotInNamespaceError: If the region is indexed, and an identifier of the element isn't declared in the
2201 namespace.
2202 :raises NotInNamespaceError: If the region is indexed, and an identifier of the element refers to another element,
2203 e.g. a duplicate declaration.
2204 """
2205 from pyVHDLModel.Subprogram import Function, Procedure
2207 if not self._areDeclaredItemsIndexed:
2208 return
2209 elif isinstance(element, (Function, Procedure)):
2210 self._RemoveOverloadFromNamespace(element)
2211 return
2213 normalizedIdentifiers = normalizedIdentifiersOf(element)
2214 elements = self._namespace.Elements
2215 for normalizedIdentifier in normalizedIdentifiers:
2216 if elements.get(normalizedIdentifier) is not element:
2217 # raises NotInNamespaceError, naming the reason
2218 self._namespace.RemoveElement(normalizedIdentifier, element)
2220 for normalizedIdentifier in normalizedIdentifiers:
2221 self._namespace.RemoveElement(normalizedIdentifier, element)
2223 def _AddOverloadToNamespace(self, item: NamedEntityMixin | MultipleNamedEntityMixin) -> None:
2224 """
2225 Add a function or procedure to the namespace, if it's the overload declared last.
2227 The namespace keeps one entry per identifier: the overload declared last, as after :meth:`IndexDeclaredItems`, which
2228 adds interface items first, then declared items (:meth:`_Declarations`).
2230 :param item: The function or procedure, already an interface item or declared item of this region.
2231 """
2232 from pyVHDLModel.Subprogram import Function, Procedure
2234 normalizedIdentifier = item._normalizedIdentifier
2235 overloads = [
2236 declaration for declaration in self._Declarations()
2237 if isinstance(declaration, (Function, Procedure)) and declaration._normalizedIdentifier == normalizedIdentifier
2238 ]
2239 if overloads[-1] is item:
2240 self._namespace.AddElement(normalizedIdentifier, item, overloadable=True)
2242 def _RemoveOverloadFromNamespace(self, item: NamedEntityMixin | MultipleNamedEntityMixin) -> None:
2243 """
2244 Remove a function or procedure from the namespace.
2246 Removing the overload the namespace refers to, the namespace refers to the remaining overload declared last
2247 (:meth:`_Declarations`), or the identifier is removed, if no overload remains. Removing another overload leaves the
2248 namespace unchanged. The namespace is checked before it's changed.
2250 :param item: The function or procedure, still an interface item or declared item of this region.
2251 :raises NotInNamespaceError: If the identifier isn't declared in the namespace.
2252 :raises NotInNamespaceError: If the identifier refers to an element, which is no overload, e.g. a duplicate
2253 declaration.
2254 """
2255 from pyVHDLModel.Subprogram import Function, Procedure
2257 normalizedIdentifier = item._normalizedIdentifier
2258 entry = self._namespace.Elements.get(normalizedIdentifier)
2259 if entry is item:
2260 remaining = [
2261 declaration for declaration in self._Declarations()
2262 if declaration is not item
2263 and isinstance(declaration, (Function, Procedure))
2264 and declaration._normalizedIdentifier == normalizedIdentifier
2265 ]
2266 if len(remaining) == 0:
2267 self._namespace.RemoveElement(normalizedIdentifier, item)
2268 else:
2269 self._namespace.AddElement(normalizedIdentifier, remaining[-1], overloadable=True)
2270 elif entry is None or not entry.IsOverloadable:
2271 # raises NotInNamespaceError, naming the reason
2272 self._namespace.RemoveElement(normalizedIdentifier, item)
2274 def _SharedRegions(self) -> tuple[DeclarativeRegionMixin, ...]:
2275 """
2276 Return the other language constructs forming one declarative region with this one.
2278 An entity and each of its architectures form one declarative region, as do a package and its body. Derived classes
2279 override it.
2281 :returns: Tuple of declarative regions.
2282 """
2283 return ()
2285 def _MayShareIdentifier(self, item: ModelEntity, existing: ModelEntity) -> bool:
2286 """
2287 Check if two declarations may share an identifier in one declarative region.
2289 Subprograms are overloadable. A protected type body completes its protected type, a full type completes its
2290 incomplete type, and a constant completes its deferred constant.
2292 :param item: The new declaration.
2293 :param existing: The existing declaration.
2294 :returns: ``True``, if both declarations may share an identifier.
2295 """
2296 from pyVHDLModel.Interface import InterfaceItemMixin
2297 from pyVHDLModel.Type import FullType, AnonymousType, ProtectedType, ProtectedTypeBody
2299 return (
2300 (item.IsOverloadable and existing.IsOverloadable)
2301 or (isinstance(item, ProtectedTypeBody) and isinstance(existing, ProtectedType))
2302 or (isinstance(item, ProtectedType) and isinstance(existing, ProtectedTypeBody))
2303 or (isinstance(item, FullType) and isinstance(existing, AnonymousType))
2304 or (isinstance(item, AnonymousType) and isinstance(existing, FullType))
2305 or (
2306 isinstance(item, Constant) and not isinstance(item, InterfaceItemMixin)
2307 and isinstance(existing, DeferredConstant)
2308 )
2309 or (
2310 isinstance(item, DeferredConstant)
2311 and isinstance(existing, Constant) and not isinstance(existing, InterfaceItemMixin)
2312 )
2313 )
2315 def _ClashingDeclarations(self, item: ModelEntity) -> tuple[ModelEntity, ...]:
2316 """
2317 Return the declarations sharing an identifier with the given item, which may not share it.
2319 The declarations (:meth:`_Declarations`) and the labeled statements (``_Labels()``) of this declarative region and
2320 of the language constructs sharing it (:meth:`_SharedRegions`) are searched: a statement label is declared
2321 implicitly. Items imported into the namespace (e.g. by a use clause) are no declarations.
2323 :param item: The new declaration, or the new labeled statement.
2324 :returns: Tuple of clashing declarations, interface items first, then declared items in declaration order, then
2325 labeled statements.
2326 """
2327 if len(names := set(normalizedDeclaredNamesOf(item))) == 0:
2328 return ()
2330 return tuple(
2331 declaration
2332 for region in (self, *self._SharedRegions())
2333 for declaration in region._DeclarationsNamed(names)
2334 if declaration is not item and not self._MayShareIdentifier(item, declaration)
2335 )
2337 def _DeclarationsNamed(self, names: set[str]) -> list[ModelEntity]:
2338 """
2339 Return the declarations (:meth:`_Declarations`) and the labeled statements (``_Labels()``) of this declarative
2340 region declaring one of the given names.
2342 A region with a declarative part finds its declared items by an index (:class:`DeclarationRegionMixin`).
2344 :param names: The normalized names.
2345 :returns: List of declarations, in the order of :meth:`_Declarations`, then labeled statements.
2346 """
2347 return [
2348 declaration
2349 for declaration in (*self._Declarations(), *self._Labels())
2350 if not names.isdisjoint(normalizedDeclaredNamesOf(declaration))
2351 ]
2354@export
2355class DeclarativePartMixin(
2356 metaclass=ExtendedType,
2357 mixin=True,
2358 expects=(
2359 "_namespace",
2360 "_functions",
2361 "_procedures",
2362 "_declaredItems",
2363 "_areDeclaredItemsIndexed",
2364 "_Declarations",
2365 "_IndexDeclaredItem",
2366 "_UnindexDeclaredItem",
2367 "IndexDeclaredItems",
2368 "_ClashingDeclarations",
2369 "_AddOverloadToNamespace",
2370 "_RemoveOverloadFromNamespace"
2371 )
2372):
2373 """
2374 A mixin-class for language constructs with a declarative part.
2376 A declarative part lists the declared items of a declarative region, e.g. the declarations of an architecture before
2377 its ``begin``. It carries the mutators for declared items (e.g. :meth:`AddDeclaredItem`) and the hooks for declared
2378 items no region handles itself.
2380 The host class provides the declared items ``_declaredItems``, the lookup tables ``_functions`` and ``_procedures``,
2381 and the methods ``_IndexDeclaredItem(item)``, ``_UnindexDeclaredItem(item)`` and ``IndexDeclaredItems()``. The
2382 declarative region the declared items belong to (:class:`DeclarativeRegionMixin`) provides the namespace and the
2383 checks for clashing declarations.
2385 .. seealso::
2387 * :class:`Declaration region mixin <pyVHDLModel.Regions.DeclarationRegionMixin>`
2388 * :class:`Declarative region mixin <pyVHDLModel.Regions.DeclarativeRegionMixin>`
2389 """
2390 _DECLARED_ITEM_TYPES: ClassVar[tuple[type, ...]] #: Accepted classes of declared items (:mod:`pyVHDLModel`).
2392 _declaredItemsByName: Nullable[dict[str, list[ModelEntity]]] #: Declared items by normalized name, or ``None``.
2394 def __init__(self) -> None:
2395 """
2396 Initializes a declarative part: its index of declared items by name is built on first use.
2397 """
2398 self._declaredItemsByName = None
2400 def _InterfaceDeclarations(self) -> tuple[ModelEntity, ...]:
2401 """
2402 Return the interface items sharing the declarative region of this declarative part.
2404 Host classes with interface items override this method, e.g. an entity returns its generics and ports;
2405 :meth:`_Declarations` lists them first.
2407 :returns: An empty tuple.
2408 """
2409 return ()
2411 def _DeclaredItemsNamed(self, names: Collection[str]) -> list[ModelEntity]:
2412 """
2413 Return the declared items declaring one of the given names, found by an index (:attr:`_declaredItemsByName`).
2415 The index is built from the declared items on first use. Appending a declared item extends it; inserting one
2416 elsewhere, removing, moving or splitting one drops it, so it's built again on the next use.
2418 :param names: The normalized names, each once.
2419 :returns: List of declared items, in declaration order.
2420 """
2421 if (index := self._declaredItemsByName) is None:
2422 self._declaredItemsByName = index = {}
2423 for item in self._declaredItems:
2424 for name in normalizedDeclaredNamesOf(item):
2425 if (items := index.get(name)) is None:
2426 index[name] = [item]
2427 else:
2428 items.append(item)
2430 if len(names) == 1:
2431 return list(index.get(next(iter(names)), ()))
2433 found = {id(item) for name in names for item in index.get(name, ())}
2434 if len(found) == 0:
2435 return []
2437 return [item for item in self._declaredItems if id(item) in found]
2439 def _IndexOtherDeclaredItem(self, item: ModelEntity) -> None:
2440 """
2441 Hook for declared items the region doesn't handle itself. Derived classes may override it.
2443 An alias, an attribute declaration and a package (also a package instantiation) declared in the region are added to
2444 the namespace, without a lookup table.
2446 :param item: The declared item.
2447 """
2448 from pyVHDLModel.Declaration import Alias, Attribute
2449 from pyVHDLModel.DesignUnit import Package
2451 if isinstance(item, (Alias, Attribute, Package)):
2452 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=item.IsOverloadable)
2454 def _UnindexOtherDeclaredItem(self, item: ModelEntity) -> None:
2455 """
2456 Hook to remove declared items the region doesn't handle itself. Derived classes may override it.
2458 An alias, an attribute declaration and a package are removed from the namespace.
2460 :param item: The declared item.
2461 :raises NotInNamespaceError: If the item is an alias, an attribute declaration or a package, which isn't declared
2462 in the namespace.
2463 """
2464 from pyVHDLModel.Declaration import Alias, Attribute
2465 from pyVHDLModel.DesignUnit import Package
2467 if isinstance(item, (Alias, Attribute, Package)): 2467 ↛ 2468line 2467 didn't jump to line 2468 because the condition on line 2467 was never true
2468 self._namespace.RemoveElement(item._normalizedIdentifier, item)
2470 def _RemoveDeclaredItemsFromNamespace(self) -> None:
2471 """
2472 Remove all declared items of this region from its namespace.
2474 Interface items of this region and items imported from elsewhere (e.g. by a use clause) are kept.
2475 """
2476 from pyVHDLModel.Interface import InterfaceItemMixin
2478 for normalizedIdentifier, element in list(self._namespace.Elements.items()):
2479 if not isinstance(element, InterfaceItemMixin) and element._parent is self:
2480 self._namespace.RemoveElement(normalizedIdentifier, element)
2482 def _RemoveDeclaredItemEntries(
2483 self,
2484 lookupTable: dict[str, Any],
2485 item: NamedEntityMixin | MultipleNamedEntityMixin
2486 ) -> None:
2487 """
2488 Remove a declared item's entries from a lookup table and from the namespace.
2490 Every identifier is checked before anything is removed.
2492 :param lookupTable: The lookup table matching the declared item's kind.
2493 :param item: The declared item.
2494 :raises NotInNamespaceError: If an identifier of the declared item isn't declared in the namespace.
2495 :raises NotInNamespaceError: If an identifier of the declared item refers to another element, e.g. a duplicate
2496 declaration.
2497 """
2498 normalizedIdentifiers = normalizedIdentifiersOf(item)
2499 elements = self._namespace.Elements
2500 for normalizedIdentifier in normalizedIdentifiers:
2501 if elements.get(normalizedIdentifier) is not item:
2502 # raises NotInNamespaceError, naming the reason
2503 self._namespace.RemoveElement(normalizedIdentifier, item)
2505 for normalizedIdentifier in normalizedIdentifiers:
2506 del lookupTable[normalizedIdentifier]
2507 self._namespace.RemoveElement(normalizedIdentifier, item)
2509 def _IndexOverload(self, item: NamedEntityMixin | MultipleNamedEntityMixin) -> None:
2510 """
2511 Add an inserted function or procedure to its lookup table and to the namespace.
2513 The list of overloads follows the declaration order. The namespace is updated by :meth:`_AddOverloadToNamespace`.
2515 :param item: The inserted function or procedure.
2516 """
2517 from pyVHDLModel.Subprogram import Function, Procedure
2519 kind = Function if isinstance(item, Function) else Procedure
2520 lookupTable = self._functions if kind is Function else self._procedures
2521 normalizedIdentifier = item._normalizedIdentifier
2522 lookupTable[normalizedIdentifier] = [
2523 declaration for declaration in self._declaredItems
2524 if isinstance(declaration, kind) and declaration._normalizedIdentifier == normalizedIdentifier
2525 ]
2527 self._AddOverloadToNamespace(item)
2529 def _UnindexOverload(self, item: NamedEntityMixin | MultipleNamedEntityMixin) -> None:
2530 """
2531 Remove a function or procedure from its lookup table and from the namespace.
2533 The namespace is updated first, by :meth:`_RemoveOverloadFromNamespace`.
2535 :param item: The function or procedure to remove, still a declared item of this region.
2536 :raises NotInNamespaceError: If the identifier isn't declared in the namespace.
2537 :raises NotInNamespaceError: If the identifier refers to an element, which is no overload, e.g. a duplicate
2538 declaration.
2539 """
2540 from pyVHDLModel.Subprogram import Function
2542 self._RemoveOverloadFromNamespace(item)
2544 normalizedIdentifier = item._normalizedIdentifier
2545 lookupTable = self._functions if isinstance(item, Function) else self._procedures
2546 overloads = lookupTable[normalizedIdentifier]
2547 overloads.remove(item)
2548 if len(overloads) == 0:
2549 del lookupTable[normalizedIdentifier]
2551 def _DeclaredItemsSharingIdentifiers(self, declaredItem: ModelEntity) -> list[ModelEntity]:
2552 """
2553 Return the other declared items of this region sharing an identifier with the given declared item.
2555 :param declaredItem: The declared item.
2556 :returns: List of declared items, in declaration order.
2557 """
2558 if not isinstance(declaredItem, (NamedEntityMixin, MultipleNamedEntityMixin)):
2559 return []
2561 return [
2562 item for item in self._DeclaredItemsNamed(normalizedIdentifiersOf(declaredItem))
2563 if item is not declaredItem and isinstance(item, (NamedEntityMixin, MultipleNamedEntityMixin))
2564 ]
2566 def AddDeclaredItem(self, declaredItem: ModelEntity) -> None:
2567 """
2568 Add a declared item at the end of the declarative region.
2570 The declared item's parent is set to this declarative region. If the region is indexed, its identifiers are added
2571 to the region's namespace and to the lookup table matching its kind.
2573 :param declaredItem: The declared item to add.
2574 :raises ValueError: If parameter 'declaredItem' is ``None``.
2575 :raises TypeError: If parameter 'declaredItem' is not a declaration allowed in this declarative
2576 region.
2577 :raises AlreadyInDesignError: If parameter 'declaredItem' already has a parent.
2578 :raises DuplicateDeclarationError: If an existing declaration of the declarative region shares an
2579 identifier with the declared item.
2581 .. seealso::
2583 :meth:`InsertDeclaredItem`
2584 |rarr| Insert a declared item at a position of the declarative region.
2585 :meth:`RemoveDeclaredItem`
2586 |rarr| Remove a declared item from the declarative region.
2587 """
2588 self.InsertDeclaredItem(len(self._declaredItems), declaredItem)
2590 def InsertDeclaredItem(self, index: int, declaredItem: ModelEntity) -> None:
2591 """
2592 Insert a declared item at a position of the declarative region.
2594 The declared item's parent is set to this declarative region. If the region is indexed, its identifiers are added
2595 to the region's namespace and to the lookup table matching its kind.
2597 An identifier is declared once per declarative region: interface items and declared items count, including those of
2598 the language construct sharing the declarative region (an entity and its architecture, a package and its body).
2599 Subprograms are overloadable: a subprogram may share its identifier with other subprograms. A protected type body
2600 may share its identifier with its protected type, a full type with its incomplete type declaration, and a constant
2601 with its deferred constant. Items imported into the namespace (e.g. by a use clause) are hidden.
2603 :param index: Position, from ``0`` (first) to the number of declared items (append).
2604 A negative index counts from the end, as for :meth:`list.insert`: ``-1``
2605 inserts before the last declared item.
2606 :param declaredItem: The declared item to insert.
2607 :raises ValueError: If parameter 'index' is ``None``.
2608 :raises TypeError: If parameter 'index' is not of type :class:`int`.
2609 :raises ValueError: If parameter 'index' is out of range.
2610 :raises ValueError: If parameter 'declaredItem' is ``None``.
2611 :raises TypeError: If parameter 'declaredItem' is not a declaration allowed in this declarative
2612 region.
2613 :raises AlreadyInDesignError: If parameter 'declaredItem' already has a parent.
2614 :raises DuplicateDeclarationError: If an existing declaration of the declarative region shares an
2615 identifier with the declared item.
2617 .. seealso::
2619 :meth:`AddDeclaredItem`
2620 |rarr| Add a declared item at the end of the declarative region.
2621 :meth:`InsertDeclaredItemBefore`
2622 |rarr| Insert a declared item before another declared item.
2623 :meth:`InsertDeclaredItemAfter`
2624 |rarr| Insert a declared item after another declared item.
2625 :meth:`RemoveDeclaredItem`
2626 |rarr| Remove a declared item from the declarative region.
2627 :meth:`MoveDeclaredItem`
2628 |rarr| Move a declared item to a position of the declarative region.
2629 """
2630 from pyVHDLModel.DesignUnit import Component
2631 from pyVHDLModel.Interface import InterfaceItemMixin
2632 from pyVHDLModel.Subprogram import Function, Procedure
2633 from pyVHDLModel.Type import BaseType, Subtype
2635 if index is None:
2636 raise ValueError("Parameter 'index' is None.")
2637 elif not isinstance(index, int):
2638 ex = TypeError("Parameter 'index' is not of type 'int'.")
2639 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
2640 raise ex
2641 elif not (-len(self._declaredItems) <= index <= len(self._declaredItems)):
2642 ex = ValueError(f"Parameter 'index' is out of range {-len(self._declaredItems)}..{len(self._declaredItems)}.")
2643 ex.add_note(f"Got value '{index}'.")
2644 raise ex
2646 if declaredItem is None:
2647 raise ValueError("Parameter 'declaredItem' is None.")
2648 elif not isinstance(declaredItem, self._DECLARED_ITEM_TYPES) or isinstance(declaredItem, InterfaceItemMixin):
2649 ex = TypeError(f"Parameter 'declaredItem' is not a declaration allowed in {getTypeName(self)}.")
2650 ex.add_note(f"Got type '{getFullyQualifiedName(declaredItem)}'.")
2651 raise ex
2652 elif declaredItem._parent is not None:
2653 identifiers = ""
2654 if isinstance(declaredItem, (NamedEntityMixin, MultipleNamedEntityMixin)):
2655 identifiers = f" '{', '.join(identifiersOf(declaredItem))}'"
2656 ex = AlreadyInDesignError(
2657 f"{getTypeName(declaredItem)}{identifiers} already has a parent.",
2658 element=declaredItem,
2659 parent=declaredItem._parent
2660 )
2661 ex.add_note(f"Remove it from its {getTypeName(declaredItem._parent)} first.")
2662 raise ex
2664 if len(clashes := self._ClashingDeclarations(declaredItem)) > 0:
2665 existingIdentifiers = normalizedDeclaredNamesOf(clashes[0])
2666 newIdentifiers = zip(identifiersOf(declaredItem), normalizedIdentifiersOf(declaredItem))
2667 identifier = next(name for name, normalizedName in newIdentifiers if normalizedName in existingIdentifiers)
2669 if isinstance(declaredItem, Subtype):
2670 errorClass = DuplicateSubtypeError
2671 elif isinstance(declaredItem, BaseType):
2672 errorClass = DuplicateTypeError
2673 elif isinstance(declaredItem, (Function, Procedure)):
2674 errorClass = DuplicateSubprogramError
2675 elif isinstance(declaredItem, BaseConstant):
2676 errorClass = DuplicateConstantError
2677 elif isinstance(declaredItem, Signal):
2678 errorClass = DuplicateSignalError
2679 elif isinstance(declaredItem, (Variable, SharedVariable)):
2680 errorClass = DuplicateVariableError
2681 elif isinstance(declaredItem, File):
2682 errorClass = DuplicateFileError
2683 elif isinstance(declaredItem, Component):
2684 errorClass = DuplicateComponentError
2685 else:
2686 errorClass = DuplicateDeclarationError
2687 region = clashes[0]._parent
2688 while not isinstance(region, DeclarativeRegionMixin):
2689 region = region._parent
2690 ex = errorClass(
2691 f"{getTypeName(region)} already declares '{identifier}'.",
2692 identifier=identifier,
2693 namespace=self._namespace,
2694 element=declaredItem,
2695 existing=clashes[0]
2696 )
2697 ex.add_note(f"Existing declaration is of type '{getFullyQualifiedName(clashes[0])}'.")
2698 raise ex
2700 if (byName := self._declaredItemsByName) is not None:
2701 if index == len(self._declaredItems):
2702 for name in normalizedDeclaredNamesOf(declaredItem):
2703 if (items := byName.get(name)) is None:
2704 byName[name] = [declaredItem]
2705 else:
2706 items.append(declaredItem)
2707 else:
2708 self._declaredItemsByName = None
2710 self._declaredItems.insert(index, declaredItem)
2711 declaredItem.Parent = self
2712 if self._areDeclaredItemsIndexed:
2713 if isinstance(declaredItem, (Function, Procedure)):
2714 self._IndexOverload(declaredItem)
2715 else:
2716 self._IndexDeclaredItem(declaredItem)
2718 def InsertDeclaredItemBefore(self, declaredItem: ModelEntity, before: ModelEntity) -> None:
2719 """
2720 Insert a declared item before another declared item.
2722 The declared item's parent is set to this declarative region. If the region is indexed, its identifiers are added
2723 to the region's namespace and to the lookup table matching its kind.
2725 :param declaredItem: The declared item to insert.
2726 :param before: The declared item of this declarative region to insert before.
2727 :raises ValueError: If parameter 'declaredItem' is ``None``.
2728 :raises TypeError: If parameter 'declaredItem' is not a declaration allowed in this declarative
2729 region.
2730 :raises AlreadyInDesignError: If parameter 'declaredItem' already has a parent.
2731 :raises ValueError: If parameter 'before' is ``None``.
2732 :raises TypeError: If parameter 'before' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
2733 :raises NotAChildError: If parameter 'before' is not a declared item of this declarative region.
2734 :raises DuplicateDeclarationError: If an existing declaration of the declarative region shares an
2735 identifier with the declared item.
2737 .. seealso::
2739 :meth:`InsertDeclaredItem`
2740 |rarr| Insert a declared item at a position of the declarative region.
2741 :meth:`InsertDeclaredItemAfter`
2742 |rarr| Insert a declared item after another declared item.
2743 """
2744 if before is None:
2745 raise ValueError("Parameter 'before' is None.")
2746 elif not isinstance(before, ModelEntity):
2747 ex = TypeError("Parameter 'before' is not of type 'ModelEntity'.")
2748 ex.add_note(f"Got type '{getFullyQualifiedName(before)}'.")
2749 raise ex
2751 for index, item in enumerate(self._declaredItems):
2752 if item is before:
2753 break
2754 else:
2755 identifiers = ""
2756 if isinstance(before, (NamedEntityMixin, MultipleNamedEntityMixin)): 2756 ↛ 2758line 2756 didn't jump to line 2758 because the condition on line 2756 was always true
2757 identifiers = f" '{', '.join(identifiersOf(before))}'"
2758 raise NotAChildError(
2759 f"{getTypeName(before)}{identifiers} is not a declared item of this {getTypeName(self)}.",
2760 element=before,
2761 parent=self
2762 )
2764 self.InsertDeclaredItem(index, declaredItem)
2766 def InsertDeclaredItemAfter(self, declaredItem: ModelEntity, after: ModelEntity) -> None:
2767 """
2768 Insert a declared item after another declared item.
2770 The declared item's parent is set to this declarative region. If the region is indexed, its identifiers are added
2771 to the region's namespace and to the lookup table matching its kind.
2773 :param declaredItem: The declared item to insert.
2774 :param after: The declared item of this declarative region to insert after.
2775 :raises ValueError: If parameter 'declaredItem' is ``None``.
2776 :raises TypeError: If parameter 'declaredItem' is not a declaration allowed in this declarative
2777 region.
2778 :raises AlreadyInDesignError: If parameter 'declaredItem' already has a parent.
2779 :raises ValueError: If parameter 'after' is ``None``.
2780 :raises TypeError: If parameter 'after' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
2781 :raises NotAChildError: If parameter 'after' is not a declared item of this declarative region.
2782 :raises DuplicateDeclarationError: If an existing declaration of the declarative region shares an
2783 identifier with the declared item.
2785 .. seealso::
2787 :meth:`InsertDeclaredItem`
2788 |rarr| Insert a declared item at a position of the declarative region.
2789 :meth:`InsertDeclaredItemBefore`
2790 |rarr| Insert a declared item before another declared item.
2791 """
2792 if after is None:
2793 raise ValueError("Parameter 'after' is None.")
2794 elif not isinstance(after, ModelEntity):
2795 ex = TypeError("Parameter 'after' is not of type 'ModelEntity'.")
2796 ex.add_note(f"Got type '{getFullyQualifiedName(after)}'.")
2797 raise ex
2799 for index, item in enumerate(self._declaredItems):
2800 if item is after:
2801 break
2802 else:
2803 identifiers = ""
2804 if isinstance(after, (NamedEntityMixin, MultipleNamedEntityMixin)): 2804 ↛ 2805line 2804 didn't jump to line 2805 because the condition on line 2804 was never true
2805 identifiers = f" '{', '.join(identifiersOf(after))}'"
2806 raise NotAChildError(
2807 f"{getTypeName(after)}{identifiers} is not a declared item of this {getTypeName(self)}.",
2808 element=after,
2809 parent=self
2810 )
2812 self.InsertDeclaredItem(index + 1, declaredItem)
2814 def RemoveDeclaredItem(self, declaredItem: ModelEntity) -> None:
2815 """
2816 Remove a declared item from the declarative region.
2818 The declared item is detached: its parent is cleared. If the region is indexed, the declared item's identifiers are
2819 removed from the region's namespace and from the lookup table matching its kind first; they are checked before
2820 anything is changed. The declared item itself is unchanged and can be added to another declarative region, or
2821 inserted at another position.
2823 The namespace refers to the overload declared last: removing it, the namespace refers to the remaining overload
2824 declared last. If another declaration shares an identifier with the declared item (e.g. a duplicate declaration
2825 read by a parser), the region is indexed again (:meth:`IndexDeclaredItems`) after the removal.
2827 :param declaredItem: The declared item to remove.
2828 :raises ValueError: If parameter 'declaredItem' is ``None``.
2829 :raises TypeError: If parameter 'declaredItem' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
2830 :raises NotAChildError: If parameter 'declaredItem' is not a declared item of this declarative region.
2831 :raises NotInNamespaceError: If the region is indexed, and an identifier of the declared item isn't declared in
2832 its namespace.
2833 :raises NotInNamespaceError: If the region is indexed, and an identifier of the declared item refers to another
2834 declaration, e.g. a duplicate declaration.
2836 .. seealso::
2838 :meth:`AddDeclaredItem`
2839 |rarr| Add a declared item at the end of the declarative region.
2840 :meth:`InsertDeclaredItem`
2841 |rarr| Insert a declared item at a position of the declarative region.
2842 :meth:`MoveDeclaredItem`
2843 |rarr| Move a declared item to a position of the declarative region.
2844 """
2845 from pyVHDLModel.Subprogram import Function, Procedure
2847 if declaredItem is None:
2848 raise ValueError("Parameter 'declaredItem' is None.")
2849 elif not isinstance(declaredItem, ModelEntity):
2850 ex = TypeError("Parameter 'declaredItem' is not of type 'ModelEntity'.")
2851 ex.add_note(f"Got type '{getFullyQualifiedName(declaredItem)}'.")
2852 raise ex
2854 for index, item in enumerate(self._declaredItems):
2855 if item is declaredItem:
2856 break
2857 else:
2858 identifiers = ""
2859 if isinstance(declaredItem, (NamedEntityMixin, MultipleNamedEntityMixin)): 2859 ↛ 2861line 2859 didn't jump to line 2861 because the condition on line 2859 was always true
2860 identifiers = f" '{', '.join(identifiersOf(declaredItem))}'"
2861 raise NotAChildError(
2862 f"{getTypeName(declaredItem)}{identifiers} is not a declared item of this {getTypeName(self)}.",
2863 element=declaredItem,
2864 parent=self
2865 )
2867 reindex = False
2868 if self._areDeclaredItemsIndexed:
2869 isOverload = isinstance(declaredItem, (Function, Procedure))
2870 reindex = any(
2871 not (isOverload and isinstance(item, (Function, Procedure)))
2872 for item in self._DeclaredItemsSharingIdentifiers(declaredItem)
2873 )
2874 self._UnindexDeclaredItem(declaredItem)
2876 del self._declaredItems[index]
2877 self._declaredItemsByName = None
2878 declaredItem._parent = None
2880 if reindex:
2881 self.IndexDeclaredItems()
2883 def MoveDeclaredItem(self, declaredItem: ModelEntity, index: int) -> None:
2884 """
2885 Move a declared item to a position of the declarative region.
2887 The declared item stays a declared item of this declarative region: only the order of the declared items changes.
2889 If the region is indexed, the lookup tables and the namespace follow the new order: a list of overloads (e.g. in
2890 ``Functions``) follows the declaration order, and the namespace refers to the overload declared last. If
2891 another declaration shares an identifier with the declared item (e.g. a duplicate declaration read by a parser),
2892 the region is indexed again (:meth:`IndexDeclaredItems`) after the move.
2894 :param declaredItem: The declared item to move.
2895 :param index: Position of the declared item after the move, from ``0`` (first) to the number of
2896 declared items minus one (last). A negative index counts from the end, as for a
2897 :class:`list` index: ``-1`` moves the declared item to the end.
2898 :raises ValueError: If parameter 'declaredItem' is ``None``.
2899 :raises TypeError: If parameter 'declaredItem' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
2900 :raises NotAChildError: If parameter 'declaredItem' is not a declared item of this declarative region.
2901 :raises ValueError: If parameter 'index' is ``None``.
2902 :raises TypeError: If parameter 'index' is not of type :class:`int`.
2903 :raises ValueError: If parameter 'index' is out of range.
2905 .. seealso::
2907 :meth:`MoveDeclaredItemBefore`
2908 |rarr| Move a declared item before another declared item.
2909 :meth:`MoveDeclaredItemAfter`
2910 |rarr| Move a declared item after another declared item.
2911 :meth:`InsertDeclaredItem`
2912 |rarr| Insert a declared item at a position of the declarative region.
2913 :meth:`RemoveDeclaredItem`
2914 |rarr| Remove a declared item from the declarative region.
2915 """
2916 from pyVHDLModel.Subprogram import Function, Procedure
2918 if declaredItem is None:
2919 raise ValueError("Parameter 'declaredItem' is None.")
2920 elif not isinstance(declaredItem, ModelEntity):
2921 ex = TypeError("Parameter 'declaredItem' is not of type 'ModelEntity'.")
2922 ex.add_note(f"Got type '{getFullyQualifiedName(declaredItem)}'.")
2923 raise ex
2925 for currentIndex, item in enumerate(self._declaredItems):
2926 if item is declaredItem:
2927 break
2928 else:
2929 identifiers = ""
2930 if isinstance(declaredItem, (NamedEntityMixin, MultipleNamedEntityMixin)): 2930 ↛ 2932line 2930 didn't jump to line 2932 because the condition on line 2930 was always true
2931 identifiers = f" '{', '.join(identifiersOf(declaredItem))}'"
2932 raise NotAChildError(
2933 f"{getTypeName(declaredItem)}{identifiers} is not a declared item of this {getTypeName(self)}.",
2934 element=declaredItem,
2935 parent=self
2936 )
2938 if index is None:
2939 raise ValueError("Parameter 'index' is None.")
2940 elif not isinstance(index, int):
2941 ex = TypeError("Parameter 'index' is not of type 'int'.")
2942 ex.add_note(f"Got type '{getFullyQualifiedName(index)}'.")
2943 raise ex
2944 elif not (-len(self._declaredItems) <= index < len(self._declaredItems)):
2945 ex = ValueError(f"Parameter 'index' is out of range {-len(self._declaredItems)}..{len(self._declaredItems) - 1}.")
2946 ex.add_note(f"Got value '{index}'.")
2947 raise ex
2949 newIndex = index if index >= 0 else len(self._declaredItems) + index
2950 if newIndex == currentIndex:
2951 return
2953 reindex = False
2954 overloads = False
2955 if self._areDeclaredItemsIndexed and len(sharingItems := self._DeclaredItemsSharingIdentifiers(declaredItem)) > 0:
2956 isOverload = isinstance(declaredItem, (Function, Procedure))
2957 reindex = any(not (isOverload and isinstance(item, (Function, Procedure))) for item in sharingItems)
2958 overloads = not reindex
2960 if overloads:
2961 self._RemoveOverloadFromNamespace(declaredItem)
2963 del self._declaredItems[currentIndex]
2964 self._declaredItems.insert(newIndex, declaredItem)
2965 self._declaredItemsByName = None
2967 if reindex:
2968 self.IndexDeclaredItems()
2969 elif overloads:
2970 self._IndexOverload(declaredItem)
2972 def MoveDeclaredItemBefore(self, declaredItem: ModelEntity, before: ModelEntity) -> None:
2973 """
2974 Move a declared item before another declared item.
2976 The declared item stays a declared item of this declarative region: only the order of the declared items changes,
2977 as for :meth:`MoveDeclaredItem`. Moving a declared item before itself keeps it in place.
2979 :param declaredItem: The declared item to move.
2980 :param before: The declared item of this declarative region to move before.
2981 :raises ValueError: If parameter 'declaredItem' is ``None``.
2982 :raises TypeError: If parameter 'declaredItem' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
2983 :raises NotAChildError: If parameter 'declaredItem' is not a declared item of this declarative region.
2984 :raises ValueError: If parameter 'before' is ``None``.
2985 :raises TypeError: If parameter 'before' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
2986 :raises NotAChildError: If parameter 'before' is not a declared item of this declarative region.
2988 .. seealso::
2990 :meth:`MoveDeclaredItem`
2991 |rarr| Move a declared item to a position of the declarative region.
2992 :meth:`MoveDeclaredItemAfter`
2993 |rarr| Move a declared item after another declared item.
2994 """
2995 if before is None:
2996 raise ValueError("Parameter 'before' is None.")
2997 elif not isinstance(before, ModelEntity):
2998 ex = TypeError("Parameter 'before' is not of type 'ModelEntity'.")
2999 ex.add_note(f"Got type '{getFullyQualifiedName(before)}'.")
3000 raise ex
3002 for index, item in enumerate(self._declaredItems):
3003 if item is before:
3004 break
3005 else:
3006 identifiers = ""
3007 if isinstance(before, (NamedEntityMixin, MultipleNamedEntityMixin)): 3007 ↛ 3009line 3007 didn't jump to line 3009 because the condition on line 3007 was always true
3008 identifiers = f" '{', '.join(identifiersOf(before))}'"
3009 raise NotAChildError(
3010 f"{getTypeName(before)}{identifiers} is not a declared item of this {getTypeName(self)}.",
3011 element=before,
3012 parent=self
3013 )
3015 precedes = any(item is declaredItem for item in self._declaredItems[:index])
3016 self.MoveDeclaredItem(declaredItem, index - 1 if precedes else index)
3018 def MoveDeclaredItemAfter(self, declaredItem: ModelEntity, after: ModelEntity) -> None:
3019 """
3020 Move a declared item after another declared item.
3022 The declared item stays a declared item of this declarative region: only the order of the declared items changes,
3023 as for :meth:`MoveDeclaredItem`. Moving a declared item after itself keeps it in place.
3025 :param declaredItem: The declared item to move.
3026 :param after: The declared item of this declarative region to move after.
3027 :raises ValueError: If parameter 'declaredItem' is ``None``.
3028 :raises TypeError: If parameter 'declaredItem' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
3029 :raises NotAChildError: If parameter 'declaredItem' is not a declared item of this declarative region.
3030 :raises ValueError: If parameter 'after' is ``None``.
3031 :raises TypeError: If parameter 'after' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
3032 :raises NotAChildError: If parameter 'after' is not a declared item of this declarative region.
3034 .. seealso::
3036 :meth:`MoveDeclaredItem`
3037 |rarr| Move a declared item to a position of the declarative region.
3038 :meth:`MoveDeclaredItemBefore`
3039 |rarr| Move a declared item before another declared item.
3040 """
3041 if after is None:
3042 raise ValueError("Parameter 'after' is None.")
3043 elif not isinstance(after, ModelEntity): 3043 ↛ 3044line 3043 didn't jump to line 3044 because the condition on line 3043 was never true
3044 ex = TypeError("Parameter 'after' is not of type 'ModelEntity'.")
3045 ex.add_note(f"Got type '{getFullyQualifiedName(after)}'.")
3046 raise ex
3048 for index, item in enumerate(self._declaredItems):
3049 if item is after:
3050 break
3051 else:
3052 identifiers = ""
3053 if isinstance(after, (NamedEntityMixin, MultipleNamedEntityMixin)): 3053 ↛ 3055line 3053 didn't jump to line 3055 because the condition on line 3053 was always true
3054 identifiers = f" '{', '.join(identifiersOf(after))}'"
3055 raise NotAChildError(
3056 f"{getTypeName(after)}{identifiers} is not a declared item of this {getTypeName(self)}.",
3057 element=after,
3058 parent=self
3059 )
3061 precedes = any(item is declaredItem for item in self._declaredItems[:index + 1])
3062 self.MoveDeclaredItem(declaredItem, index if precedes else index + 1)
3064 def SplitDeclaredItem(self, declaredItem: ModelEntity) -> tuple[ModelEntity, ...]:
3065 """
3066 Split a declared item with an identifier list into one declaration per identifier.
3068 The declared item keeps its first identifier. For every other identifier, a new declaration is created by its
3069 ``Copy()`` and inserted right after it, in list order; its parent is set to this declarative region. If the region
3070 is indexed, the namespace and lookup table entries of the other identifiers refer to the new declarations; they
3071 are checked before anything is changed. A declared item declaring one identifier is unchanged.
3073 :param declaredItem: The declared item to split.
3074 :returns: Tuple of declarations, one per identifier in list order, starting with the split
3075 declared item.
3076 :raises ValueError: If parameter 'declaredItem' is ``None``.
3077 :raises TypeError: If parameter 'declaredItem' is not of type :class:`~pyVHDLModel.Base.ModelEntity`.
3078 :raises NotAChildError: If parameter 'declaredItem' is not a declared item of this declarative region.
3079 :raises NotInNamespaceError: If the region is indexed, and an identifier of the declared item refers to another
3080 declaration, e.g. a duplicate declaration.
3082 .. seealso::
3084 :meth:`~pyVHDLModel.Base.MultipleNamedEntityMixin.Split`
3085 |rarr| Split a declaration with an identifier list.
3086 :meth:`RemoveDeclaredItem`
3087 |rarr| Remove a declared item from the declarative region.
3088 """
3089 if declaredItem is None:
3090 raise ValueError("Parameter 'declaredItem' is None.")
3091 elif not isinstance(declaredItem, ModelEntity):
3092 ex = TypeError("Parameter 'declaredItem' is not of type 'ModelEntity'.")
3093 ex.add_note(f"Got type '{getFullyQualifiedName(declaredItem)}'.")
3094 raise ex
3096 for index, item in enumerate(self._declaredItems):
3097 if item is declaredItem:
3098 break
3099 else:
3100 identifiers = ""
3101 if isinstance(declaredItem, (NamedEntityMixin, MultipleNamedEntityMixin)): 3101 ↛ 3103line 3101 didn't jump to line 3103 because the condition on line 3101 was always true
3102 identifiers = f" '{', '.join(identifiersOf(declaredItem))}'"
3103 raise NotAChildError(
3104 f"{getTypeName(declaredItem)}{identifiers} is not a declared item of this {getTypeName(self)}.",
3105 element=declaredItem,
3106 parent=self
3107 )
3109 if not isinstance(declaredItem, MultipleNamedEntityMixin) or len(declaredItem._identifiers) == 1:
3110 return (declaredItem, )
3112 if self._areDeclaredItemsIndexed:
3113 self._UnindexDeclaredItem(declaredItem)
3115 declarations = declaredItem._SplitCopies()
3116 declaredItem._KeepIdentifier(0)
3117 self._declaredItems[index + 1:index + 1] = declarations
3118 for declaration in declarations:
3119 declaration.Parent = self
3121 self._declaredItemsByName = None
3123 if self._areDeclaredItemsIndexed:
3124 self._IndexDeclaredItem(declaredItem)
3125 for declaration in declarations:
3126 self._IndexDeclaredItem(declaration)
3128 return (declaredItem, *declarations)
3130 def _VisitDeclaredItems(self, visitor: Visitor) -> None:
3131 """
3132 Walk the declared items in declaration order with a visitor.
3134 :param visitor: The visitor receiving the events.
3135 """
3136 for item in self._declaredItems:
3137 item.Visit(visitor)
3140@export
3141class DeclarationRegionMixin(DeclarativeRegionMixin, DeclarativePartMixin, mixin=True):
3142 """
3143 A base-class for the concurrent, sequential and protected type declaration region mixins.
3145 It combines a declarative region (:class:`DeclarativeRegionMixin`) with its declarative part
3146 (:class:`DeclarativePartMixin`).
3148 The derived region mixin-class provides the namespace ``_namespace``, the declared items ``_declaredItems`` and the
3149 lookup tables ``_functions`` and ``_procedures``; it or the host class provides the methods ``_Declarations()``,
3150 ``_IndexDeclaredItem(item)``, ``_UnindexDeclaredItem(item)`` and ``IndexDeclaredItems()``.
3152 .. seealso::
3154 * :class:`Concurrent declaration region mixin <pyVHDLModel.Regions.ConcurrentDeclarationRegionMixin>`
3155 * :class:`Sequential declaration region mixin <pyVHDLModel.Regions.SequentialDeclarationRegionMixin>`
3156 * :class:`Protected type declaration region mixin <pyVHDLModel.Regions.ProtectedTypeDeclarationRegionMixin>`
3157 """
3159 def __init__(self) -> None:
3160 """
3161 Initializes a declaration region: a declarative region, which isn't indexed yet, and its declarative part.
3162 """
3163 DeclarativeRegionMixin.__init__(self)
3164 DeclarativePartMixin.__init__(self)
3166 def _DeclarationsNamed(self, names: set[str]) -> list[ModelEntity]:
3167 """
3168 Return the declarations and the labeled statements of this declaration region declaring one of the given names.
3170 The interface items (:meth:`~DeclarativePartMixin._InterfaceDeclarations`) and the labeled statements are searched,
3171 the declared items are found by their index (:meth:`~DeclarativePartMixin._DeclaredItemsNamed`), so a check for a
3172 new declaration doesn't visit every declared item.
3174 :param names: The normalized names.
3175 :returns: List of declarations, interface items first, then declared items in declaration order, then labeled
3176 statements.
3177 """
3178 return [
3179 *(
3180 declaration
3181 for declaration in self._InterfaceDeclarations()
3182 if not names.isdisjoint(normalizedDeclaredNamesOf(declaration))
3183 ),
3184 *self._DeclaredItemsNamed(names),
3185 *(
3186 statement
3187 for statement in self._Labels()
3188 if not names.isdisjoint(normalizedDeclaredNamesOf(statement))
3189 )
3190 ]
3193@export
3194class WithoutStatementsMixin(metaclass=ExtendedType, mixin=True):
3195 """
3196 A mixin-class for language constructs with a declarative region, but without statements.
3198 It provides the labeled statements ``_Labels()`` and the nested declarative regions ``_IterateStatementRegions()`` the
3199 declaration region expects from its host class: none.
3201 .. seealso::
3203 * :class:`Package <pyVHDLModel.DesignUnit.Package>`
3204 * :class:`Package body <pyVHDLModel.DesignUnit.PackageBody>`
3205 * :class:`Protected type <pyVHDLModel.Type.ProtectedType>`
3206 * :class:`Protected type body <pyVHDLModel.Type.ProtectedTypeBody>`
3207 * :class:`Component <pyVHDLModel.DesignUnit.Component>`
3208 """
3210 def _Labels(self) -> tuple[ModelEntity, ...]:
3211 """
3212 Return the labeled statements, whose labels are declared in this declarative region.
3214 :returns: An empty tuple.
3215 """
3216 return ()
3218 def _IterateStatementRegions(self) -> Generator[DeclarativeRegionMixin, None, None]:
3219 """
3220 Iterate the declarative regions nested in the statements of this declarative region.
3222 :returns: An empty generator.
3223 """
3224 yield from ()
3227@export
3228class ConcurrentDeclarationRegionMixin(DeclarationRegionMixin, mixin=True):
3229 # FIXME: define list prefix type e.g. via Union
3230 """
3231 A mixin-class for concurrent declaration regions.
3233 Entities, architectures, packages, blocks and generate bodies declare items concurrently. Beside
3234 the namespace, the region keeps a lookup table per kind of declared item (:data:`Types`,
3235 :data:`Signals`, :data:`Constants`, ...).
3237 .. seealso::
3239 * :class:`Concurrent block statement <pyVHDLModel.Concurrent.ConcurrentBlockStatement>`
3240 * :class:`Generate branch <pyVHDLModel.Concurrent.GenerateBranch>`
3241 * :class:`Concurrent case <pyVHDLModel.Concurrent.ConcurrentCase>`
3242 * :class:`For generate statement <pyVHDLModel.Concurrent.ForGenerateStatement>`
3243 * :class:`Package <pyVHDLModel.DesignUnit.Package>`
3244 * :class:`Package body <pyVHDLModel.DesignUnit.PackageBody>`
3245 * :class:`Entity <pyVHDLModel.DesignUnit.Entity>`
3246 * :class:`Architecture <pyVHDLModel.DesignUnit.Architecture>`
3247 * :class:`Sequential declaration region <pyVHDLModel.Regions.SequentialDeclarationRegionMixin>`
3248 * :class:`Namespace <pyVHDLModel.Namespace.Namespace>`
3249 """
3250 _declaredItems: list #: List of all declared items in this concurrent declaration region.
3251 _namespace: Namespace #: The namespace of this concurrent declaration region.
3253 # _attributes: dict[str, Attribute]
3254 # _aliases: dict[str, Alias]
3255 _types: dict[str, FullType] #: Dictionary of all types declared in this concurrent declaration region.
3256 _subtypes: dict[str, Subtype] #: Dictionary of all subtypes declared in this concurrent declaration region.
3257 # _objects: dict[str, Union[Constant, Variable, Signal]]
3258 _constants: dict[str, Constant] #: Dictionary of all constants declared in this concurrent declaration region.
3259 _signals: dict[str, Signal] #: Dictionary of all signals declared in this concurrent declaration region.
3260 _sharedVariables: dict[str, SharedVariable] #: Dictionary of all shared variables declared in this concurrent declaration region.
3261 _files: dict[str, File] #: Dictionary of all files declared in this concurrent declaration region.
3262 # _subprograms: dict[str, list[Subprogram]] #: Dictionary of all subprograms declared in this concurrent declaration region.
3263 # FIXME: overloads are only collected into a list, not matched/resolved by signature.
3264 _functions: dict[str, list[Function]] #: Dictionary of all functions declared in this concurrent declaration region, indexed by name; each entry is a list of overloads.
3265 _procedures: dict[str, list[Procedure]] #: Dictionary of all procedures declared in this concurrent declaration region, indexed by name; each entry is a list of overloads.
3266 _components: dict[str, Any] #: Dictionary of all components declared in this concurrent declaration region.
3268 def __init__(
3269 self,
3270 namespaceName: Nullable[str] = None,
3271 declaredItems: Nullable[Iterable] = None,
3272 sharesRegionWithParent: bool = False
3273 ) -> None:
3274 # TODO: extract to mixin
3275 """
3276 Initializes a concurrent declaration region.
3278 :param namespaceName: Optional, name of this region's namespace, usually the host's label or identifier.
3279 Default: ``None``.
3280 :param declaredItems: Optional, list of all declared items in this concurrent declaration region.
3281 Default: ``None``, no declared items.
3282 :param sharesRegionWithParent: Optional, ``True`` if this region continues its parent's declarative region (an
3283 architecture its entity's, a package body its package's). Default: ``False``.
3284 """
3285 DeclarationRegionMixin.__init__(self)
3287 self._namespace = Namespace(namespaceName, sharesRegionWithParent=sharesRegionWithParent)
3289 self._declaredItems = declaredItemList = [] # TODO: convert to dict
3290 if declaredItems is not None:
3291 for item in declaredItems:
3292 declaredItemList.append(item)
3293 item.Parent = self
3295 self._types = {}
3296 self._subtypes = {}
3297 # self._objects = {}
3298 self._constants = {}
3299 self._signals = {}
3300 self._sharedVariables = {}
3301 self._files = {}
3302 # self._subprograms = {}
3303 self._functions = {}
3304 self._procedures = {}
3305 self._components = {}
3307 @readonly
3308 def DeclaredItems(self) -> list:
3309 """
3310 Read-only property to access the declared items (:attr:`_declaredItems`).
3312 :returns: List of declared items.
3313 """
3314 return self._declaredItems
3316 @readonly
3317 def Types(self) -> dict[str, FullType]:
3318 """
3319 Read-only property to access the types (:attr:`_types`).
3321 :returns: Dictionary of types, indexed by normalized identifier.
3322 """
3323 return self._types
3325 @readonly
3326 def Subtypes(self) -> dict[str, Subtype]:
3327 """
3328 Read-only property to access the subtypes (:attr:`_subtypes`).
3330 :returns: Dictionary of subtypes, indexed by normalized identifier.
3331 """
3332 return self._subtypes
3334 # @readonly
3335 # def Objects(self) -> dict[str, Union[Constant, SharedVariable, Signal, File]]:
3336 # return self._objects
3338 @readonly
3339 def Constants(self) -> dict[str, Constant]:
3340 """
3341 Read-only property to access the constants (:attr:`_constants`).
3343 :returns: Dictionary of constants, indexed by normalized identifier.
3344 """
3345 return self._constants
3347 @readonly
3348 def Signals(self) -> dict[str, Signal]:
3349 """
3350 Read-only property to access the signals (:attr:`_signals`).
3352 :returns: Dictionary of signals, indexed by normalized identifier.
3353 """
3354 return self._signals
3356 @readonly
3357 def SharedVariables(self) -> dict[str, SharedVariable]:
3358 """
3359 Read-only property to access the shared variables (:attr:`_sharedVariables`).
3361 :returns: Dictionary of shared variables, indexed by normalized identifier.
3362 """
3363 return self._sharedVariables
3365 @readonly
3366 def Files(self) -> dict[str, File]:
3367 """
3368 Read-only property to access the files (:attr:`_files`).
3370 :returns: Dictionary of files, indexed by normalized identifier.
3371 """
3372 return self._files
3374 # @readonly
3375 # def Subprograms(self) -> dict[str, Subprogram]:
3376 # return self._subprograms
3378 @readonly
3379 def Functions(self) -> dict[str, list[Function]]:
3380 """
3381 Read-only property to access the functions (:attr:`_functions`).
3383 :returns: Dictionary of functions, indexed by normalized identifier; each entry is a list of overloads.
3384 """
3385 return self._functions
3387 @readonly
3388 def Procedures(self) -> dict[str, list[Procedure]]:
3389 """
3390 Read-only property to access the procedures (:attr:`_procedures`).
3392 :returns: Dictionary of procedures, indexed by normalized identifier; each entry is a list of overloads.
3393 """
3394 return self._procedures
3396 @readonly
3397 def Components(self) -> dict[str, Any]:
3398 """
3399 Read-only property to access the components (:attr:`_components`).
3401 :returns: Dictionary of components, indexed by normalized identifier.
3402 """
3403 return self._components
3405 def _Declarations(self) -> tuple[ModelEntity, ...]:
3406 """
3407 Return all declarations of this declarative region.
3409 A host class with interface items provides them (:meth:`~DeclarativePartMixin._InterfaceDeclarations`); they are
3410 listed first.
3412 :returns: Tuple of declarations: the interface items, then the declared items in declaration order.
3413 """
3414 return (*self._InterfaceDeclarations(), *self._declaredItems)
3416 def IndexDeclaredItems(self) -> None:
3417 """
3418 Index declared items listed in the concurrent declaration region.
3420 .. rubric:: Algorithm
3422 1. Clear all lookup tables and remove all declared items from :attr:`_namespace`. Interface items and imported
3423 items stay in the namespace.
3424 2. Iterate all declared items:
3426 * Every declared item is added to :attr:`_namespace`, except a protected type body.
3427 * If the declared item is a :class:`~pyVHDLModel.Type.ProtectedTypeBody`, skip it: it completes its protected
3428 type.
3429 * If the declared item is a :class:`~pyVHDLModel.Type.FullType`, then add an entry to :attr:`_types`.
3430 * If the declared item is a :class:`~pyVHDLModel.Type.Subtype`, then add an entry to :attr:`_subtypes`.
3431 * If the declared item is a :class:`~pyVHDLModel.Subprogram.Function`, then add an entry to :attr:`_functions`.
3432 * If the declared item is a :class:`~pyVHDLModel.Subprogram.Procedure`, then add an entry to :attr:`_procedures`.
3433 * If the declared item is a :class:`~pyVHDLModel.Object.Constant`, then add an entry to :attr:`_constants`.
3434 * If the declared item is a :class:`~pyVHDLModel.Object.Signal`, then add an entry to :attr:`_signals`.
3435 * If the declared item is a :class:`~pyVHDLModel.Object.Variable`, TODO.
3436 * If the declared item is a :class:`~pyVHDLModel.Object.SharedVariable`, then add an entry to :attr:`_sharedVariables`.
3437 * If the declared item is a :class:`~pyVHDLModel.Object.File`, then add an entry to :attr:`_files`.
3438 * If the declared item is neither of these types, call :meth:`_IndexOtherDeclaredItem`. |br|
3439 Derived classes may override this virtual function.
3441 Indexing again yields the same lookup tables and namespace.
3443 .. seealso::
3445 :meth:`pyVHDLModel.Design.IndexPackages`
3446 Iterate all packages in the design and index declared items.
3447 :meth:`pyVHDLModel.Library.IndexPackages`
3448 Iterate all packages in the library and index declared items.
3449 :meth:`pyVHDLModel.DesignUnit.Package._IndexOtherDeclaredItem`
3450 Index the deferred constants of a package.
3452 :raises UnhandledCriticalWarningError: If an identifier is declared twice in a declarative region and no
3453 :class:`~pyTooling.Warning.WarningCollector` collects the
3454 :exc:`~pyVHDLModel.Exception.DuplicateDeclarationWarning`.
3455 """
3456 self._types.clear()
3457 self._subtypes.clear()
3458 self._constants.clear()
3459 self._signals.clear()
3460 self._sharedVariables.clear()
3461 self._files.clear()
3462 self._functions.clear()
3463 self._procedures.clear()
3464 self._components.clear()
3465 self._RemoveDeclaredItemsFromNamespace()
3467 for item in self._declaredItems:
3468 self._IndexDeclaredItem(item)
3470 self._areDeclaredItemsIndexed = True
3472 def _IndexDeclaredItem(self, item: ModelEntity) -> None:
3473 """
3474 Add a declared item to the namespace and to the lookup table matching its kind.
3476 :param item: The declared item.
3477 """
3478 from pyVHDLModel.DesignUnit import Component
3479 from pyVHDLModel.Subprogram import Function, Procedure
3480 from pyVHDLModel.Type import Subtype, FullType, ProtectedTypeBody
3482 if isinstance(item, ProtectedTypeBody):
3483 # A protected type body completes its protected type.
3484 pass
3485 elif isinstance(item, FullType):
3486 self._types[item._normalizedIdentifier] = item
3487 self._namespace.AddElement(item._normalizedIdentifier, item)
3488 elif isinstance(item, Subtype):
3489 self._subtypes[item._normalizedIdentifier] = item
3490 self._namespace.AddElement(item._normalizedIdentifier, item)
3491 elif isinstance(item, Function):
3492 # FIXME: overloads are only appended to a list, not matched/resolved by signature (no
3493 # real overload resolution yet).
3494 if (overloads := self._functions.get(item._normalizedIdentifier)) is None:
3495 self._functions[item._normalizedIdentifier] = [item]
3496 else:
3497 overloads.append(item)
3499 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=True)
3500 elif isinstance(item, Procedure):
3501 # FIXME: overloads are only appended to a list, not matched/resolved by signature (no
3502 # real overload resolution yet).
3503 if (overloads := self._procedures.get(item._normalizedIdentifier)) is None:
3504 self._procedures[item._normalizedIdentifier] = [item]
3505 else:
3506 overloads.append(item)
3508 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=True)
3509 elif isinstance(item, Constant):
3510 for normalizedIdentifier in item._normalizedIdentifiers:
3511 self._constants[normalizedIdentifier] = item
3512 self._namespace.AddElement(normalizedIdentifier, item)
3513 # self._objects[normalizedIdentifier] = item
3514 elif isinstance(item, Signal):
3515 for normalizedIdentifier in item._normalizedIdentifiers:
3516 self._signals[normalizedIdentifier] = item
3517 self._namespace.AddElement(normalizedIdentifier, item)
3518 elif isinstance(item, Variable):
3519 # TODO: variables declared in a concurrent declaration region (e.g. shared variables outside a
3520 # protected type) are not yet indexed into a dedicated namespace/lookup table.
3521 identifiers = ", ".join(f"'{i}'" for i in item._identifiers)
3522 WarningCollector.Raise(
3523 NotImplementedWarning(f"IndexDeclaredItems: variable(s) {identifiers} are not yet indexed.", item=item)
3524 )
3525 elif isinstance(item, SharedVariable):
3526 for normalizedIdentifier in item._normalizedIdentifiers:
3527 self._sharedVariables[normalizedIdentifier] = item
3528 self._namespace.AddElement(normalizedIdentifier, item)
3529 elif isinstance(item, File):
3530 for normalizedIdentifier in item._normalizedIdentifiers:
3531 self._files[normalizedIdentifier] = item
3532 self._namespace.AddElement(normalizedIdentifier, item)
3533 elif isinstance(item, Component):
3534 self._components[item._normalizedIdentifier] = item
3535 self._namespace.AddElement(item._normalizedIdentifier, item)
3536 else:
3537 self._IndexOtherDeclaredItem(item)
3539 def _UnindexDeclaredItem(self, item: ModelEntity) -> None:
3540 """
3541 Remove a declared item from the namespace and from the lookup table matching its kind.
3543 :param item: The declared item.
3544 """
3545 from pyVHDLModel.DesignUnit import Component
3546 from pyVHDLModel.Subprogram import Function, Procedure
3547 from pyVHDLModel.Type import Subtype, FullType, ProtectedTypeBody
3549 if isinstance(item, ProtectedTypeBody): 3549 ↛ 3550line 3549 didn't jump to line 3550 because the condition on line 3549 was never true
3550 pass
3551 elif isinstance(item, FullType):
3552 self._RemoveDeclaredItemEntries(self._types, item)
3553 elif isinstance(item, Subtype): 3553 ↛ 3554line 3553 didn't jump to line 3554 because the condition on line 3553 was never true
3554 self._RemoveDeclaredItemEntries(self._subtypes, item)
3555 elif isinstance(item, (Function, Procedure)):
3556 self._UnindexOverload(item)
3557 elif isinstance(item, Constant):
3558 self._RemoveDeclaredItemEntries(self._constants, item)
3559 elif isinstance(item, Signal):
3560 self._RemoveDeclaredItemEntries(self._signals, item)
3561 elif isinstance(item, Variable): 3561 ↛ 3562line 3561 didn't jump to line 3562 because the condition on line 3561 was never true
3562 pass
3563 elif isinstance(item, SharedVariable):
3564 self._RemoveDeclaredItemEntries(self._sharedVariables, item)
3565 elif isinstance(item, File):
3566 self._RemoveDeclaredItemEntries(self._files, item)
3567 elif isinstance(item, Component):
3568 self._RemoveDeclaredItemEntries(self._components, item)
3569 else:
3570 self._UnindexOtherDeclaredItem(item)
3573@export
3574class SequentialDeclarationRegionMixin(DeclarationRegionMixin, mixin=True):
3575 """
3576 A mixin-class for sequential declaration regions: process statements and subprogram bodies.
3578 .. note::
3580 VHDL's ``process_declarative_item`` and ``subprogram_declarative_item`` rules are identical, so both
3581 regions share this implementation. Compared to a concurrent region
3582 (:class:`ConcurrentDeclarationRegionMixin`, ``block_declarative_item``), a sequential region can
3583 declare a **variable**, but no signal, shared variable, component or mode view, and none of the
3584 specifications.
3586 .. seealso::
3588 * :class:`Process statement <pyVHDLModel.Concurrent.ProcessStatement>`
3589 * :class:`Subprogram <pyVHDLModel.Subprogram.Subprogram>`
3590 * :class:`Concurrent declaration region <pyVHDLModel.Regions.ConcurrentDeclarationRegionMixin>`
3591 * :class:`Namespace <pyVHDLModel.Namespace.Namespace>`
3592 """
3594 _declaredItems: list #: List of all declared items in this sequential declaration region.
3595 _namespace: Namespace #: The namespace of this sequential declaration region.
3597 _types: dict[str, FullType] #: Dictionary of all types declared in this sequential declaration region.
3598 _subtypes: dict[str, Subtype] #: Dictionary of all subtypes declared in this sequential declaration region.
3599 _constants: dict[str, Constant] #: Dictionary of all constants declared in this sequential declaration region.
3600 _variables: dict[str, Variable] #: Dictionary of all variables declared in this sequential declaration region.
3601 _files: dict[str, File] #: Dictionary of all files declared in this sequential declaration region.
3602 # FIXME: overloads are only collected into a list, not matched/resolved by signature.
3603 _functions: dict[str, list[Function]] #: Dictionary of all functions declared in this sequential declaration region, indexed by name; each entry is a list of overloads.
3604 _procedures: dict[str, list[Procedure]] #: Dictionary of all procedures declared in this sequential declaration region, indexed by name; each entry is a list of overloads.
3606 def __init__(self, namespaceName: Nullable[str] = None, declaredItems: Nullable[Iterable] = None) -> None:
3607 """
3608 Initialize a sequential declaration region.
3610 :param namespaceName: Optional, name of this region's namespace, usually the host's label or identifier.
3611 Default: ``None``.
3612 :param declaredItems: Optional, the items declared in this region. Default: ``None``, no declared items.
3613 """
3614 DeclarationRegionMixin.__init__(self)
3616 self._namespace = Namespace(namespaceName)
3618 self._declaredItems = declaredItemList = [] # TODO: convert to dict
3619 if declaredItems is not None:
3620 for item in declaredItems:
3621 declaredItemList.append(item)
3622 item.Parent = self
3624 self._types = {}
3625 self._subtypes = {}
3626 self._constants = {}
3627 self._variables = {}
3628 self._files = {}
3629 self._functions = {}
3630 self._procedures = {}
3632 @readonly
3633 def DeclaredItems(self) -> list:
3634 """
3635 Read-only property to access the declared items (:attr:`_declaredItems`).
3637 :returns: List of declared items.
3638 """
3639 return self._declaredItems
3641 @readonly
3642 def Namespace(self) -> Namespace:
3643 """
3644 Read-only property to access this region's namespace (:attr:`_namespace`).
3646 :returns: The namespace.
3647 """
3648 return self._namespace
3650 @readonly
3651 def Types(self) -> dict[str, FullType]:
3652 """
3653 Read-only property to access the declared types (:attr:`_types`).
3655 :returns: Dictionary of types, indexed by normalized identifier.
3656 """
3657 return self._types
3659 @readonly
3660 def Subtypes(self) -> dict[str, Subtype]:
3661 """
3662 Read-only property to access the declared subtypes (:attr:`_subtypes`).
3664 :returns: Dictionary of subtypes, indexed by normalized identifier.
3665 """
3666 return self._subtypes
3668 @readonly
3669 def Constants(self) -> dict[str, Constant]:
3670 """
3671 Read-only property to access the declared constants (:attr:`_constants`).
3673 :returns: Dictionary of constants, indexed by normalized identifier.
3674 """
3675 return self._constants
3677 @readonly
3678 def Variables(self) -> dict[str, Variable]:
3679 """
3680 Read-only property to access the declared variables (:attr:`_variables`).
3682 :returns: Dictionary of variables, indexed by normalized identifier.
3683 """
3684 return self._variables
3686 @readonly
3687 def Files(self) -> dict[str, File]:
3688 """
3689 Read-only property to access the declared files (:attr:`_files`).
3691 :returns: Dictionary of files, indexed by normalized identifier.
3692 """
3693 return self._files
3695 @readonly
3696 def Functions(self) -> dict[str, list[Function]]:
3697 """
3698 Read-only property to access the declared functions (:attr:`_functions`).
3700 :returns: Dictionary of functions, indexed by normalized identifier; each entry is a list of overloads.
3701 """
3702 return self._functions
3704 @readonly
3705 def Procedures(self) -> dict[str, list[Procedure]]:
3706 """
3707 Read-only property to access the declared procedures (:attr:`_procedures`).
3709 :returns: Dictionary of procedures, indexed by normalized identifier; each entry is a list of overloads.
3710 """
3711 return self._procedures
3713 def _Declarations(self) -> tuple[ModelEntity, ...]:
3714 """
3715 Return all declarations of this declarative region.
3717 A host class with interface items provides them (:meth:`~DeclarativePartMixin._InterfaceDeclarations`); they are
3718 listed first.
3720 :returns: Tuple of declarations: the interface items, then the declared items in declaration order.
3721 """
3722 return (*self._InterfaceDeclarations(), *self._declaredItems)
3724 def IndexDeclaredItems(self) -> None:
3725 """
3726 Index declared items listed in the sequential declaration region.
3728 All lookup tables are cleared and all declared items are removed from :attr:`_namespace` first. Then every declared
3729 item is added to :attr:`_namespace`, and additionally to the lookup table matching its kind. Items of an unhandled
3730 kind are passed to :meth:`_IndexOtherDeclaredItem`. A protected type body completes its protected type, so it's
3731 skipped. Indexing again yields the same lookup tables and namespace.
3733 .. seealso::
3735 :meth:`~pyVHDLModel.Regions.ConcurrentDeclarationRegionMixin.IndexDeclaredItems`
3736 The same algorithm for a concurrent declaration region.
3738 :raises UnhandledCriticalWarningError: If an identifier is declared twice in a declarative region and no
3739 :class:`~pyTooling.Warning.WarningCollector` collects the
3740 :exc:`~pyVHDLModel.Exception.DuplicateDeclarationWarning`.
3741 """
3742 self._types.clear()
3743 self._subtypes.clear()
3744 self._constants.clear()
3745 self._variables.clear()
3746 self._files.clear()
3747 self._functions.clear()
3748 self._procedures.clear()
3749 self._RemoveDeclaredItemsFromNamespace()
3751 for item in self._declaredItems:
3752 self._IndexDeclaredItem(item)
3754 self._areDeclaredItemsIndexed = True
3756 def _IndexDeclaredItem(self, item: ModelEntity) -> None:
3757 """
3758 Add a declared item to the namespace and to the lookup table matching its kind.
3760 :param item: The declared item.
3761 """
3762 from pyVHDLModel.Subprogram import Function, Procedure
3763 from pyVHDLModel.Type import Subtype, FullType, ProtectedTypeBody
3765 if isinstance(item, ProtectedTypeBody):
3766 # A protected type body completes its protected type.
3767 pass
3768 elif isinstance(item, FullType):
3769 self._types[item._normalizedIdentifier] = item
3770 self._namespace.AddElement(item._normalizedIdentifier, item)
3771 elif isinstance(item, Subtype):
3772 self._subtypes[item._normalizedIdentifier] = item
3773 self._namespace.AddElement(item._normalizedIdentifier, item)
3774 elif isinstance(item, Function):
3775 # FIXME: overloads are only appended to a list, not matched/resolved by signature (no
3776 # real overload resolution yet).
3777 if (overloads := self._functions.get(item._normalizedIdentifier)) is None: 3777 ↛ 3780line 3777 didn't jump to line 3780 because the condition on line 3777 was always true
3778 self._functions[item._normalizedIdentifier] = [item]
3779 else:
3780 overloads.append(item)
3782 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=True)
3783 elif isinstance(item, Procedure):
3784 # FIXME: overloads are only appended to a list, not matched/resolved by signature (no
3785 # real overload resolution yet).
3786 if (overloads := self._procedures.get(item._normalizedIdentifier)) is None:
3787 self._procedures[item._normalizedIdentifier] = [item]
3788 else:
3789 overloads.append(item)
3791 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=True)
3792 elif isinstance(item, Constant):
3793 for normalizedIdentifier in item._normalizedIdentifiers:
3794 self._constants[normalizedIdentifier] = item
3795 self._namespace.AddElement(normalizedIdentifier, item)
3796 elif isinstance(item, Variable):
3797 for normalizedIdentifier in item._normalizedIdentifiers:
3798 self._variables[normalizedIdentifier] = item
3799 self._namespace.AddElement(normalizedIdentifier, item)
3800 elif isinstance(item, File):
3801 for normalizedIdentifier in item._normalizedIdentifiers:
3802 self._files[normalizedIdentifier] = item
3803 self._namespace.AddElement(normalizedIdentifier, item)
3804 else:
3805 self._IndexOtherDeclaredItem(item)
3807 def _UnindexDeclaredItem(self, item: ModelEntity) -> None:
3808 """
3809 Remove a declared item from the namespace and from the lookup table matching its kind.
3811 :param item: The declared item.
3812 """
3813 from pyVHDLModel.Subprogram import Function, Procedure
3814 from pyVHDLModel.Type import Subtype, FullType, ProtectedTypeBody
3816 if isinstance(item, ProtectedTypeBody): 3816 ↛ 3817line 3816 didn't jump to line 3817 because the condition on line 3816 was never true
3817 pass
3818 elif isinstance(item, FullType): 3818 ↛ 3819line 3818 didn't jump to line 3819 because the condition on line 3818 was never true
3819 self._RemoveDeclaredItemEntries(self._types, item)
3820 elif isinstance(item, Subtype): 3820 ↛ 3821line 3820 didn't jump to line 3821 because the condition on line 3820 was never true
3821 self._RemoveDeclaredItemEntries(self._subtypes, item)
3822 elif isinstance(item, (Function, Procedure)):
3823 self._UnindexOverload(item)
3824 elif isinstance(item, Constant): 3824 ↛ 3825line 3824 didn't jump to line 3825 because the condition on line 3824 was never true
3825 self._RemoveDeclaredItemEntries(self._constants, item)
3826 elif isinstance(item, Variable): 3826 ↛ 3828line 3826 didn't jump to line 3828 because the condition on line 3826 was always true
3827 self._RemoveDeclaredItemEntries(self._variables, item)
3828 elif isinstance(item, File):
3829 self._RemoveDeclaredItemEntries(self._files, item)
3830 else:
3831 self._UnindexOtherDeclaredItem(item)
3834@export
3835class ProtectedTypeDeclarationRegionMixin(DeclarationRegionMixin, mixin=True):
3836 """
3837 A mixin-class for the declarative region of a protected type declaration.
3839 VHDL's ``protected_type_declarative_item`` rule admits subprogram declarations only, making this the
3840 narrowest declarative region in the language. A protected type *body* differs: its declarative part
3841 matches a subprogram's, so it uses :class:`SequentialDeclarationRegionMixin`.
3843 .. seealso::
3845 * :class:`Protected type <pyVHDLModel.Type.ProtectedType>`
3846 * :class:`Protected type body <pyVHDLModel.Type.ProtectedTypeBody>`
3847 * :class:`Sequential declaration region <pyVHDLModel.Regions.SequentialDeclarationRegionMixin>`
3848 * :class:`Namespace <pyVHDLModel.Namespace.Namespace>`
3849 """
3851 _declaredItems: list #: List of all declared items in this protected type declaration.
3852 _namespace: Namespace #: The namespace of this protected type declaration.
3854 # FIXME: overloads are only collected into a list, not matched/resolved by signature.
3855 _functions: dict[str, list[Function]] #: All declared functions, indexed by name; each is a list of overloads.
3856 _procedures: dict[str, list[Procedure]] #: All declared procedures by name; each is a list of overloads.
3858 def __init__(self, namespaceName: Nullable[str] = None, declaredItems: Nullable[Iterable] = None) -> None:
3859 """
3860 Initialize a protected type declaration region.
3862 :param namespaceName: Optional, name of this region's namespace, usually the protected type's identifier.
3863 Default: ``None``.
3864 :param declaredItems: Optional, the items declared in this region. Default: ``None``, no declared items.
3865 """
3866 DeclarationRegionMixin.__init__(self)
3868 self._namespace = Namespace(namespaceName)
3870 self._declaredItems = declaredItemList = [] # TODO: convert to dict
3871 if declaredItems is not None:
3872 for item in declaredItems:
3873 declaredItemList.append(item)
3874 item.Parent = self
3876 self._functions = {}
3877 self._procedures = {}
3879 @readonly
3880 def DeclaredItems(self) -> list:
3881 """
3882 Read-only property to access the declared items (:attr:`_declaredItems`).
3884 :returns: List of all declared items.
3885 """
3886 return self._declaredItems
3888 @readonly
3889 def Functions(self) -> dict[str, list[Function]]:
3890 """
3891 Read-only property to access the declared functions (:attr:`_functions`).
3893 :returns: Dictionary of all functions, indexed by name; each entry is a list of overloads.
3894 """
3895 return self._functions
3897 @readonly
3898 def Procedures(self) -> dict[str, list[Procedure]]:
3899 """
3900 Read-only property to access the declared procedures (:attr:`_procedures`).
3902 :returns: Dictionary of all procedures, indexed by name; each entry is a list of overloads.
3903 """
3904 return self._procedures
3906 def _Declarations(self) -> tuple[ModelEntity, ...]:
3907 """
3908 Return all declarations of this declarative region.
3910 A host class with interface items provides them (:meth:`~DeclarativePartMixin._InterfaceDeclarations`); they are
3911 listed first.
3913 :returns: Tuple of declarations: the interface items, then the declared items in declaration order.
3914 """
3915 return (*self._InterfaceDeclarations(), *self._declaredItems)
3917 def IndexDeclaredItems(self) -> None:
3918 """
3919 Index declared items listed in the protected type declaration.
3921 Both lookup tables are cleared and all declared items are removed from :attr:`_namespace` first. Only subprogram
3922 declarations are legal here, so anything else is passed to :meth:`_IndexOtherDeclaredItem`. Indexing again yields
3923 the same lookup tables and namespace.
3925 .. seealso::
3927 :meth:`~pyVHDLModel.Regions.SequentialDeclarationRegionMixin.IndexDeclaredItems`
3928 The same algorithm for the protected type's body.
3930 :raises UnhandledCriticalWarningError: If an identifier is declared twice in a declarative region and no
3931 :class:`~pyTooling.Warning.WarningCollector` collects the
3932 :exc:`~pyVHDLModel.Exception.DuplicateDeclarationWarning`.
3933 """
3934 self._functions.clear()
3935 self._procedures.clear()
3936 self._RemoveDeclaredItemsFromNamespace()
3938 for item in self._declaredItems:
3939 self._IndexDeclaredItem(item)
3941 self._areDeclaredItemsIndexed = True
3943 def _IndexDeclaredItem(self, item: ModelEntity) -> None:
3944 """
3945 Add a declared item to the namespace and to the lookup table matching its kind.
3947 :param item: The declared item.
3948 """
3949 from pyVHDLModel.Subprogram import Function, Procedure
3951 if isinstance(item, Function):
3952 # FIXME: overloads are only appended to a list, not matched/resolved by signature (no
3953 # real overload resolution yet).
3954 if (overloads := self._functions.get(item._normalizedIdentifier)) is None: 3954 ↛ 3957line 3954 didn't jump to line 3957 because the condition on line 3954 was always true
3955 self._functions[item._normalizedIdentifier] = [item]
3956 else:
3957 overloads.append(item)
3959 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=True)
3960 elif isinstance(item, Procedure): 3960 ↛ 3970line 3960 didn't jump to line 3970 because the condition on line 3960 was always true
3961 # FIXME: overloads are only appended to a list, not matched/resolved by signature (no
3962 # real overload resolution yet).
3963 if (overloads := self._procedures.get(item._normalizedIdentifier)) is None:
3964 self._procedures[item._normalizedIdentifier] = [item]
3965 else:
3966 overloads.append(item)
3968 self._namespace.AddElement(item._normalizedIdentifier, item, overloadable=True)
3969 else:
3970 self._IndexOtherDeclaredItem(item)
3972 def _UnindexDeclaredItem(self, item: ModelEntity) -> None:
3973 """
3974 Remove a declared item from the namespace and from the lookup table matching its kind.
3976 :param item: The declared item.
3977 """
3978 from pyVHDLModel.Subprogram import Function, Procedure
3980 if isinstance(item, (Function, Procedure)): 3980 ↛ 3983line 3980 didn't jump to line 3983 because the condition on line 3980 was always true
3981 self._UnindexOverload(item)
3982 else:
3983 self._UnindexOtherDeclaredItem(item)