Coverage for pyVHDLModel/Object.py: 98%
175 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.
35Objects are constants, variables, signals and files.
36"""
37from __future__ import annotations
39from typing import TYPE_CHECKING, ClassVar, Generator, Iterable, Optional as Nullable, Self
41from pyTooling.Decorators import export, readonly
42from pyTooling.MetaClasses import ExtendedType, abstractclass
43from pyTooling.Graph import Vertex
44from pyTooling.Warning import WarningCollector
46from pyVHDLModel.Base import ModelEntity, MultipleNamedEntityMixin, DocumentedEntityMixin, CopyMixin, \
47 ExpressionUnion, ReservedWord
48from pyVHDLModel.Exception import UnresolvedTypeMarkWarning
49from pyVHDLModel.Name import Name
50from pyVHDLModel.Symbol import Symbol, SubtypeSymbol
52if TYPE_CHECKING: 52 ↛ 53line 52 didn't jump to line 53 because the condition on line 52 was never true
53 from pyVHDLModel.Regions import DeclarativeRegionMixin
54 from pyVHDLModel.Visitor import Visitor
57@export
58@abstractclass
59class Obj(ModelEntity, MultipleNamedEntityMixin, DocumentedEntityMixin, CopyMixin):
60 """
61 Base-class for all objects (constants, signals, variables and files) in VHDL.
63 An object (syntax element) can define multiple objects (semantic elements) in a single declaration, thus
64 :class:`~pyVHDLModel.Base.MultipleNamedEntityMixin` is inherited. All objects can be documented, thus
65 :class:`~pyVHDLModel.Base.DocumentedEntityMixin` is inherited too.
67 Each object references a subtype via :data:`_subtype`.
69 Objects are elements in the type and object graph, thus a reference to a vertex in that graph is stored in
70 :data:`_objectVertex`.
72 .. seealso::
74 * :class:`Base constant <pyVHDLModel.Object.BaseConstant>`
75 * :class:`Variable <pyVHDLModel.Object.Variable>`
76 * :class:`Shared variable <pyVHDLModel.Object.SharedVariable>`
77 * :class:`Signal <pyVHDLModel.Object.Signal>`
78 * :class:`File <pyVHDLModel.Object.File>`
79 """
81 _OBJECT_KEYWORD: ClassVar[tuple[ReservedWord, ...]] #: The reserved words introducing this object class.
82 _USABLE_IN_OWN_INTERFACE_LIST: ClassVar[bool] = True #: Usable by a name in its own interface list.
84 _subtype: Symbol #: Reference to the object's subtype.
85 _objectVertex: Nullable[Vertex] #: The vertex representing this object in the design's object graph.
87 def __init__(self, identifiers: Iterable[str], subtype: Symbol, documentation: Nullable[str] = None, parent: Nullable[ModelEntity] = None) -> None:
88 """
89 Initializes an object.
91 :param identifiers: A list of identifiers.
92 :param subtype: Reference to the object's subtype.
93 :param documentation: Optional, the documentation comment associated with this declaration.
94 Default: ``None``, no documentation.
95 :param parent: Optional, the parent model entity of this entity. Default: ``None``, no parent.
96 """
97 super().__init__(parent)
98 MultipleNamedEntityMixin.__init__(self, identifiers)
99 DocumentedEntityMixin.__init__(self, documentation)
100 CopyMixin.__init__(self)
102 self._subtype = subtype
103 subtype.Parent = self
105 self._objectVertex = None
107 @readonly
108 def Subtype(self) -> Symbol:
109 """
110 Read-only property to access the subtype (:attr:`_subtype`).
112 :returns: The subtype.
113 """
114 return self._subtype
116 @readonly
117 def ObjectVertex(self) -> Nullable[Vertex]:
118 """
119 Read-only property to access the corresponding object vertex (:attr:`_objectVertex`).
121 The object vertex references this Object by its value field.
123 :returns: The corresponding object vertex.
124 """
125 return self._objectVertex
127 def Copy(self) -> Self:
128 """
129 Create a copy of this object declaration.
131 The copy has no parent and no object vertex. Its subtype is a copy of this declaration's subtype.
133 :returns: The new object declaration.
134 """
135 return self._ModelClass()(self._identifiers, self._subtype.Copy(), self._documentation)
137 def _SplitInParent(self) -> tuple[Self, ...]:
138 """
139 Split this object declaration by the mutator of its parent (``SplitDeclaredItem()``).
141 :returns: Tuple of declarations, one per identifier in list order, starting with this object declaration.
142 """
143 return self._parent.SplitDeclaredItem(self)
145 def IterateTypeMarks(
146 self,
147 region: DeclarativeRegionMixin
148 ) -> Generator[tuple[DeclarativeRegionMixin, ModelEntity, SubtypeSymbol], None, None]:
149 """
150 Iterate the type marks of this object: the type mark of its subtype indication.
152 :param region: The declarative region declaring this object.
153 :returns: A generator to iterate (region, place, type mark) tuples: the object's subtype indication.
154 """
155 if isinstance(self._subtype, SubtypeSymbol): 155 ↛ exitline 155 didn't return from function 'IterateTypeMarks' because the condition on line 155 was always true
156 yield region, self, self._subtype
158 def DenoteBy(
159 self,
160 name: Name,
161 region: DeclarativeRegionMixin,
162 place: ModelEntity,
163 symbol: Symbol
164 ) -> Nullable[ModelEntity]:
165 """
166 Determine the model entity a name denoting this object denotes, as a part of a type mark: this object.
168 A port or a parameter isn't usable in its own interface list (:attr:`_USABLE_IN_OWN_INTERFACE_LIST`): e.g. the
169 subtype of a port can't name another port of the same port list (``i'subtype``).
171 :param name: The name denoting this declaration, a part of the type mark.
172 :param region: The declarative region containing the type mark.
173 :param place: The declaration containing the type mark.
174 :param symbol: The type mark.
175 :returns: This object, or ``None`` if a name can't denote it here (reported as a
176 warning).
177 :raises UnhandledCriticalWarningError: If the object is a port or parameter used in its own interface list, and no
178 :class:`~pyTooling.Warning.WarningCollector` collects the
179 :exc:`~pyVHDLModel.Exception.UnresolvedTypeMarkWarning`.
180 """
181 from pyVHDLModel.Interface import InterfaceItemMixin
183 if (
184 not self._USABLE_IN_OWN_INTERFACE_LIST and isinstance(place, InterfaceItemMixin)
185 and self._parent is place._parent
186 ):
187 WarningCollector.Raise(UnresolvedTypeMarkWarning(
188 f"Prefix '{name!s}' of type mark '{symbol._name!s}' isn't usable in its own interface list.",
189 symbol=symbol,
190 place=place,
191 namespaces=(region._namespace, )
192 ))
193 return None
195 return self
197 def __str__(self) -> str:
198 """
199 Formats the object declaration.
201 **Format:** ``signal s1, s2 : bit``
203 :returns: Formatted object declaration.
204 """
205 return f"{' '.join(self._OBJECT_KEYWORD)} {', '.join(self._identifiers)} : {self._subtype}"
208@export
209class WithDefaultExpressionMixin(metaclass=ExtendedType, mixin=True):
210 """
211 A ``WithDefaultExpression`` is a mixin-class for all objects declarations accepting default expressions.
213 The default expression is referenced by :data:`_defaultExpression`. If no default expression is present, this field
214 is ``None``.
216 .. seealso::
218 * :class:`Constant <pyVHDLModel.Object.Constant>`
219 * :class:`Variable <pyVHDLModel.Object.Variable>`
220 * :class:`Signal <pyVHDLModel.Object.Signal>`
221 """
223 _defaultExpression: Nullable[ExpressionUnion] #: The default value, or ``None`` if none was given.
225 def __init__(self, defaultExpression: Nullable[ExpressionUnion] = None) -> None:
226 """
227 Initializes an object with a default expression.
229 :param defaultExpression: Optional, the default value. Default: ``None``, no default value.
230 """
231 self._defaultExpression = defaultExpression
232 if defaultExpression is not None:
233 defaultExpression.Parent = self
235 @readonly
236 def DefaultExpression(self) -> Nullable[ExpressionUnion]:
237 """
238 Read-only property to access the default expression (:attr:`_defaultExpression`).
240 :returns: The default expression, or ``None`` if not set.
241 """
242 return self._defaultExpression
244 def _VisitDefaultExpression(self, visitor: Visitor) -> None:
245 """
246 Walk the default expression, if any, after a variable assignment delimiter (``:=``) with a visitor.
248 :param visitor: The visitor receiving the events.
249 """
250 if self._defaultExpression is not None:
251 visitor.VisitVariableAssignment(self)
252 self._defaultExpression.Visit(visitor)
255@export
256@abstractclass
257class BaseConstant(Obj):
258 """
259 Base-class for all constants (normal and deferred constants) in VHDL.
261 .. seealso::
263 * :class:`Constant <pyVHDLModel.Object.Constant>`
264 * :class:`Deferred constant <pyVHDLModel.Object.DeferredConstant>`
265 """
267 _OBJECT_KEYWORD: ClassVar[tuple[ReservedWord, ...]] = (ReservedWord.Constant,) #: The reserved words introducing this object class.
270@export
271class Constant(BaseConstant, WithDefaultExpressionMixin):
272 """
273 Represents a constant.
275 As constants (always) have a default expression, the class :class:`~pyVHDLModel.Object.WithDefaultExpressionMixin` is inherited.
277 .. admonition:: Example
279 .. code-block:: VHDL
281 constant BITS : positive := 8;
283 .. seealso::
285 * :class:`Generic constant interface item <pyVHDLModel.Interface.GenericConstantInterfaceItem>`
286 * :class:`Parameter constant interface item <pyVHDLModel.Interface.ParameterConstantInterfaceItem>`
287 """
289 def __init__(
290 self,
291 identifiers: Iterable[str],
292 subtype: Symbol,
293 defaultExpression: Nullable[ExpressionUnion] = None,
294 documentation: Nullable[str] = None,
295 parent: Nullable[ModelEntity] = None
296 ) -> None:
297 """
298 Initializes a constant.
300 :param identifiers: A list of identifiers.
301 :param subtype: Reference to the object's subtype.
302 :param defaultExpression: Optional, the default value. Default: ``None``, no default value.
303 :param documentation: Optional, the documentation comment associated with this declaration.
304 Default: ``None``, no documentation.
305 :param parent: Optional, the parent model entity of this entity. Default: ``None``, no parent.
306 """
307 super().__init__(identifiers, subtype, documentation, parent)
308 WithDefaultExpressionMixin.__init__(self, defaultExpression)
310 def Copy(self) -> Self:
311 """
312 Create a copy of this constant.
314 The copy has no parent and no object vertex. Its subtype and default expression are copies of this constant's
315 subtype and default expression.
317 :returns: The new constant.
318 """
319 defaultExpression = None if self._defaultExpression is None else self._defaultExpression.Copy()
320 return self._ModelClass()(self._identifiers, self._subtype.Copy(), defaultExpression, self._documentation)
322 def Visit(self, visitor: Visitor) -> None:
323 """
324 Walk this constant declaration, its subtype and its default expression with a visitor.
326 :param visitor: The visitor receiving the events.
327 """
328 visitor.VisitConstant(self)
329 self._subtype.Visit(visitor)
330 self._VisitDefaultExpression(visitor)
331 visitor.VisitTerminator(self)
332 visitor.DepartConstant(self)
335@export
336class DeferredConstant(BaseConstant):
337 """
338 Represents a deferred constant.
340 Deferred constants are forward declarations for a (complete) constant declaration, thus it contains a
341 field :data:`_constantReference` to the complete constant declaration.
343 .. admonition:: Example
345 .. code-block:: VHDL
347 constant BITS : positive;
348 """
349 _constantReference: Nullable[Constant] #: The full declaration, or ``None`` if unlinked.
351 def __init__(
352 self,
353 identifiers: Iterable[str],
354 subtype: Symbol,
355 documentation: Nullable[str] = None,
356 parent: Nullable[ModelEntity] = None
357 ) -> None:
358 """
359 Initializes a deferred constant.
361 :param identifiers: A list of identifiers.
362 :param subtype: Reference to the object's subtype.
363 :param documentation: Optional, the documentation comment associated with this declaration.
364 Default: ``None``, no documentation.
365 :param parent: Optional, the parent model entity of this entity. Default: ``None``, no parent.
366 """
367 super().__init__(identifiers, subtype, documentation, parent)
369 self._constantReference = None
371 def Visit(self, visitor: Visitor) -> None:
372 """
373 Walk this deferred constant declaration, its subtype with a visitor.
375 :param visitor: The visitor receiving the events.
376 """
377 visitor.VisitDeferredConstant(self)
378 self._subtype.Visit(visitor)
379 visitor.VisitTerminator(self)
380 visitor.DepartDeferredConstant(self)
382 @readonly
383 def ConstantReference(self) -> Nullable[Constant]:
384 """
385 Read-only property to access the constant reference (:attr:`_constantReference`).
387 :returns: The constant reference, or ``None`` if not set.
388 """
389 return self._constantReference
391 def Copy(self) -> Self:
392 """
393 Create a copy of this deferred constant.
395 The copy has no parent and no object vertex. Its subtype is a copy of this deferred constant's subtype; the full
396 constant declaration, if linked, is the same.
398 :returns: The new deferred constant.
399 """
400 copy = self._ModelClass()(self._identifiers, self._subtype.Copy(), self._documentation)
401 copy._constantReference = self._constantReference
402 return copy
405@export
406class Variable(Obj, WithDefaultExpressionMixin):
407 """
408 Represents a variable.
410 As variables might have a default expression, the class :class:`~pyVHDLModel.Object.WithDefaultExpressionMixin` is inherited.
412 .. admonition:: Example
414 .. code-block:: VHDL
416 variable result : natural := 0;
418 .. seealso::
420 * :class:`Parameter variable interface item <pyVHDLModel.Interface.ParameterVariableInterfaceItem>`
421 """
423 _OBJECT_KEYWORD: ClassVar[tuple[ReservedWord, ...]] = (ReservedWord.Variable,) #: The reserved words introducing this object class.
425 def __init__(
426 self,
427 identifiers: Iterable[str],
428 subtype: Symbol,
429 defaultExpression: Nullable[ExpressionUnion] = None,
430 documentation: Nullable[str] = None,
431 parent: Nullable[ModelEntity] = None
432 ) -> None:
433 """
434 Initializes a variable.
436 :param identifiers: A list of identifiers.
437 :param subtype: Reference to the object's subtype.
438 :param defaultExpression: Optional, the default value. Default: ``None``, no default value.
439 :param documentation: Optional, the documentation comment associated with this declaration.
440 Default: ``None``, no documentation.
441 :param parent: Optional, the parent model entity of this entity. Default: ``None``, no parent.
442 """
443 super().__init__(identifiers, subtype, documentation, parent)
444 WithDefaultExpressionMixin.__init__(self, defaultExpression)
446 def Copy(self) -> Self:
447 """
448 Create a copy of this variable.
450 The copy has no parent and no object vertex. Its subtype and default expression are copies of this variable's
451 subtype and default expression.
453 :returns: The new variable.
454 """
455 defaultExpression = None if self._defaultExpression is None else self._defaultExpression.Copy()
456 return self._ModelClass()(self._identifiers, self._subtype.Copy(), defaultExpression, self._documentation)
458 def Visit(self, visitor: Visitor) -> None:
459 """
460 Walk this variable declaration, its subtype and its default expression with a visitor.
462 :param visitor: The visitor receiving the events.
463 """
464 visitor.VisitVariable(self)
465 self._subtype.Visit(visitor)
466 self._VisitDefaultExpression(visitor)
467 visitor.VisitTerminator(self)
468 visitor.DepartVariable(self)
471@export
472class SharedVariable(Obj):
473 """
474 Represents a shared variable.
476 .. todo:: Shared variable object not implemented.
477 """
479 _OBJECT_KEYWORD: ClassVar[tuple[ReservedWord, ...]] = (ReservedWord.Shared, ReservedWord.Variable) #: The reserved words introducing this object class.
481 def Visit(self, visitor: Visitor) -> None:
482 """
483 Walk this shared variable declaration, its subtype with a visitor.
485 :param visitor: The visitor receiving the events.
486 """
487 visitor.VisitSharedVariable(self)
488 self._subtype.Visit(visitor)
489 visitor.VisitTerminator(self)
490 visitor.DepartSharedVariable(self)
494@export
495class Signal(Obj, WithDefaultExpressionMixin):
496 """
497 Represents a signal.
499 As signals might have a default expression, the class :class:`~pyVHDLModel.Object.WithDefaultExpressionMixin` is inherited.
501 .. admonition:: Example
503 .. code-block:: VHDL
505 signal counter : unsigned(7 downto 0) := '0';
507 .. seealso::
509 * :class:`Port signal interface item <pyVHDLModel.Interface.PortSignalInterfaceItem>`
510 * :class:`Parameter signal interface item <pyVHDLModel.Interface.ParameterSignalInterfaceItem>`
511 """
513 _OBJECT_KEYWORD: ClassVar[tuple[ReservedWord, ...]] = (ReservedWord.Signal,) #: The reserved words introducing this object class.
515 def __init__(
516 self,
517 identifiers: Iterable[str],
518 subtype: Symbol,
519 defaultExpression: Nullable[ExpressionUnion] = None,
520 documentation: Nullable[str] = None,
521 parent: Nullable[ModelEntity] = None
522 ) -> None:
523 """
524 Initializes a signal.
526 :param identifiers: A list of identifiers.
527 :param subtype: Reference to the object's subtype.
528 :param defaultExpression: Optional, the default value. Default: ``None``, no default value.
529 :param documentation: Optional, the documentation comment associated with this declaration.
530 Default: ``None``, no documentation.
531 :param parent: Optional, the parent model entity of this entity. Default: ``None``, no parent.
532 """
533 super().__init__(identifiers, subtype, documentation, parent)
534 WithDefaultExpressionMixin.__init__(self, defaultExpression)
536 def Copy(self) -> Self:
537 """
538 Create a copy of this signal.
540 The copy has no parent and no object vertex. Its subtype and default expression are copies of this signal's
541 subtype and default expression.
543 :returns: The new signal.
544 """
545 defaultExpression = None if self._defaultExpression is None else self._defaultExpression.Copy()
546 return self._ModelClass()(self._identifiers, self._subtype.Copy(), defaultExpression, self._documentation)
548 def Visit(self, visitor: Visitor) -> None:
549 """
550 Walk this signal declaration, its subtype and its default expression with a visitor.
552 :param visitor: The visitor receiving the events.
553 """
554 visitor.VisitSignal(self)
555 self._subtype.Visit(visitor)
556 self._VisitDefaultExpression(visitor)
557 visitor.VisitTerminator(self)
558 visitor.DepartSignal(self)
561@export
562class File(Obj):
563 """
564 Represents a file.
566 A file declaration may open the file: the file open information names the file's logical name and optionally the
567 file open kind (IEEE Std 1076-2008, 6.4.2.5).
569 .. admonition:: Example
571 .. code-block:: VHDL
573 file input : text open read_mode is "STD_INPUT";
574 -- ^^^^^^^^^ ^^^^^^^^^^^ <- OpenKind, LogicalName
576 .. seealso::
578 * :class:`Parameter file interface item <pyVHDLModel.Interface.ParameterFileInterfaceItem>`
579 """
581 _OBJECT_KEYWORD: ClassVar[tuple[ReservedWord, ...]] = (ReservedWord.File,) #: The reserved words introducing this object class.
583 _openKind: Nullable[ExpressionUnion] #: The file open kind expression, or ``None`` if none was given.
584 _logicalName: Nullable[ExpressionUnion] #: The file logical name expression, or ``None`` if the file isn't opened.
586 def __init__(
587 self,
588 identifiers: Iterable[str],
589 subtype: Symbol,
590 documentation: Nullable[str] = None,
591 parent: Nullable[ModelEntity] = None,
592 *,
593 openKind: Nullable[ExpressionUnion] = None,
594 logicalName: Nullable[ExpressionUnion] = None
595 ) -> None:
596 """
597 Initializes a file declaration.
599 :param identifiers: A list of identifiers.
600 :param subtype: Reference to the object's subtype.
601 :param documentation: Optional, the documentation comment associated with this declaration.
602 Default: ``None``, no documentation.
603 :param parent: Optional, the parent model entity of this entity. Default: ``None``, no parent.
604 :param openKind: Optional, the file open kind expression. Default: ``None``, no file open kind (the file is
605 opened for reading, if it has a logical name).
606 :param logicalName: Optional, the file logical name expression. Default: ``None``, the file isn't opened.
607 :raises ValueError: If parameter 'openKind' is given without parameter 'logicalName'.
608 """
609 super().__init__(identifiers, subtype, documentation, parent)
611 if openKind is not None and logicalName is None:
612 ex = ValueError("Parameter 'openKind' is given without parameter 'logicalName'.")
613 ex.add_note("A file open kind is part of the file open information, which needs a file logical name.")
614 raise ex
616 self._openKind = openKind
617 if openKind is not None:
618 openKind.Parent = self
620 self._logicalName = logicalName
621 if logicalName is not None:
622 logicalName.Parent = self
624 @readonly
625 def OpenKind(self) -> Nullable[ExpressionUnion]:
626 """
627 Read-only property to access the file open kind expression (:attr:`_openKind`).
629 :returns: The file open kind expression, or ``None`` if not set.
630 """
631 return self._openKind
633 @readonly
634 def LogicalName(self) -> Nullable[ExpressionUnion]:
635 """
636 Read-only property to access the file logical name expression (:attr:`_logicalName`).
638 :returns: The file logical name expression, or ``None`` if not set.
639 """
640 return self._logicalName
642 def Copy(self) -> Self:
643 """
644 Create a copy of this file declaration.
646 The copy has no parent and no object vertex. Its subtype, file open kind and file logical name are copies of this
647 declaration's.
649 :returns: The new file declaration.
650 """
651 openKind = None if self._openKind is None else self._openKind.Copy()
652 logicalName = None if self._logicalName is None else self._logicalName.Copy()
653 return self._ModelClass()(
654 self._identifiers,
655 self._subtype.Copy(),
656 self._documentation,
657 openKind=openKind,
658 logicalName=logicalName
659 )
661 def Visit(self, visitor: Visitor) -> None:
662 """
663 Walk this file declaration, its subtype and its file open information with a visitor.
665 :param visitor: The visitor receiving the events.
666 """
667 visitor.VisitFile(self)
668 self._subtype.Visit(visitor)
669 if self._logicalName is not None:
670 if self._openKind is not None:
671 visitor.VisitOpen(self)
672 self._openKind.Visit(visitor)
674 visitor.VisitIs(self)
675 self._logicalName.Visit(visitor)
677 visitor.VisitTerminator(self)
678 visitor.DepartFile(self)