aboutsummaryrefslogtreecommitdiffstats
path: root/pyGHDL/dom/Type.py
blob: 98dab3af063ae2c3a28c6097a3dcbd911017216f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# =============================================================================
#               ____ _   _ ____  _          _
#  _ __  _   _ / ___| | | |  _ \| |      __| | ___  _ __ ___
# | '_ \| | | | |  _| |_| | | | | |     / _` |/ _ \| '_ ` _ \
# | |_) | |_| | |_| |  _  | |_| | |___ | (_| | (_) | | | | | |
# | .__/ \__, |\____|_| |_|____/|_____(_)__,_|\___/|_| |_| |_|
# |_|    |___/
# =============================================================================
# Authors:
#   Patrick Lehmann
#
# Package module:   DOM: Interface items (e.g. generic or port)
#
# License:
# ============================================================================
#  Copyright (C) 2019-2022 Tristan Gingold
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <gnu.org/licenses>.
#
# SPDX-License-Identifier: GPL-2.0-or-later
# ============================================================================
from typing import List, Union, Iterator, Tuple, Iterable

from pyGHDL.dom.Names import SimpleName
from pyTooling.Decorators import export

from pyVHDLModel.Name import Name
from pyVHDLModel.Symbol import Symbol
from pyVHDLModel.Type import Subtype as VHDLModel_Subtype
from pyVHDLModel.Type import AnonymousType as VHDLModel_AnonymousType
from pyVHDLModel.Type import EnumeratedType as VHDLModel_EnumeratedType
from pyVHDLModel.Type import IntegerType as VHDLModel_IntegerType
from pyVHDLModel.Type import PhysicalType as VHDLModel_PhysicalType
from pyVHDLModel.Type import ArrayType as VHDLModel_ArrayType
from pyVHDLModel.Type import RecordTypeElement as VHDLModel_RecordTypeElement
from pyVHDLModel.Type import RecordType as VHDLModel_RecordType
from pyVHDLModel.Type import ProtectedType as VHDLModel_ProtectedType
from pyVHDLModel.Type import ProtectedTypeBody as VHDLModel_ProtectedTypeBody
from pyVHDLModel.Type import AccessType as VHDLModel_AccessType
from pyVHDLModel.Type import FileType as VHDLModel_FileType

from pyGHDL.libghdl import utils
from pyGHDL.libghdl._types import Iir
from pyGHDL.libghdl.vhdl import nodes, flists
from pyGHDL.dom import DOMMixin, DOMException, Position
from pyGHDL.dom.Symbol import SimpleSubtypeSymbol
from pyGHDL.dom.Literal import EnumerationLiteral, PhysicalIntegerLiteral
from pyGHDL.dom.Range import Range
from pyGHDL.dom.Subprogram import Function, Procedure


@export
class IncompleteType(VHDLModel_AnonymousType, DOMMixin):
    def __init__(self, node: Iir, identifier: str):
        super().__init__(identifier)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, node: Iir) -> "IncompleteType":
        from pyGHDL.dom._Utils import GetNameOfNode

        name = GetNameOfNode(node)

        return cls(node, name)


@export
class EnumeratedType(VHDLModel_EnumeratedType, DOMMixin):
    def __init__(self, node: Iir, identifier: str, literals: List[EnumerationLiteral]):
        super().__init__(identifier, literals)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "EnumeratedType":
        literals = []
        enumerationLiterals = nodes.Get_Enumeration_Literal_List(typeDefinitionNode)
        for enumerationLiteral in utils.flist_iter(enumerationLiterals):
            literal = EnumerationLiteral.parse(enumerationLiteral)
            literals.append(literal)

        return cls(typeDefinitionNode, typeName, literals)


@export
class IntegerType(VHDLModel_IntegerType, DOMMixin):
    def __init__(self, node: Iir, typeName: str, rng: Union[Range, "Name"]):
        super().__init__(typeName, rng)
        DOMMixin.__init__(self, node)


@export
class PhysicalType(VHDLModel_PhysicalType, DOMMixin):
    def __init__(
        self,
        node: Iir,
        typeName: str,
        rng: Union[Range, Name],
        primaryUnit: str,
        units: List[Tuple[str, PhysicalIntegerLiteral]],
    ):
        super().__init__(typeName, rng, primaryUnit, units)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "PhysicalType":
        from pyGHDL.dom._Utils import GetIirKindOfNode, GetNameOfNode
        from pyGHDL.dom._Translate import GetRangeFromNode, GetName

        rangeConstraint = nodes.Get_Range_Constraint(typeDefinitionNode)
        rangeKind = GetIirKindOfNode(rangeConstraint)
        if rangeKind == nodes.Iir_Kind.Range_Expression:
            rng = GetRangeFromNode(rangeConstraint)
        elif rangeKind in (
            nodes.Iir_Kind.Attribute_Name,
            nodes.Iir_Kind.Parenthesis_Name,
        ):
            rng = GetName(rangeConstraint)
        else:
            pos = Position.parse(typeDefinitionNode)
            raise DOMException(f"Unknown range kind '{rangeKind.name}' in physical type definition at line {pos.Line}.")

        primaryUnit = nodes.Get_Primary_Unit(typeDefinitionNode)
        primaryUnitName = GetNameOfNode(primaryUnit)

        units = []
        for secondaryUnit in utils.chain_iter(nodes.Get_Unit_Chain(typeDefinitionNode)):
            secondaryUnitName = GetNameOfNode(secondaryUnit)
            if secondaryUnit == primaryUnit:
                continue

            physicalLiteral = PhysicalIntegerLiteral.parse(nodes.Get_Physical_Literal(secondaryUnit))

            units.append((secondaryUnitName, physicalLiteral))

        return cls(typeDefinitionNode, typeName, rng, primaryUnitName, units)


@export
class ArrayType(VHDLModel_ArrayType, DOMMixin):
    def __init__(self, node: Iir, identifier: str, indices: List, elementSubtype: Symbol):
        super().__init__(identifier, indices, elementSubtype)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "ArrayType":
        from pyGHDL.dom._Utils import GetIirKindOfNode
        from pyGHDL.dom._Translate import (
            GetSimpleTypeFromNode,
            GetSubtypeIndicationFromIndicationNode,
        )

        indices = []
        indexDefinitions = nodes.Get_Index_Subtype_Definition_List(typeDefinitionNode)
        for index in utils.flist_iter(indexDefinitions):
            indexKind = GetIirKindOfNode(index)
            if indexKind == nodes.Iir_Kind.Simple_Name:
                indexSubtype = GetSimpleTypeFromNode(index)
                indices.append(indexSubtype)
            else:
                raise DOMException(
                    f"Unknown kind '{indexKind.name}' for an index in the array definition of `{typeName}`."
                )

        elementSubtypeIndication = nodes.Get_Element_Subtype_Indication(typeDefinitionNode)
        elementSubtype = GetSubtypeIndicationFromIndicationNode(elementSubtypeIndication, "array declaration", typeName)

        return cls(typeDefinitionNode, typeName, indices, elementSubtype)


@export
class RecordTypeElement(VHDLModel_RecordTypeElement, DOMMixin):
    def __init__(self, node: Iir, identifiers: List[str], subtype: Symbol):
        super().__init__(identifiers, subtype)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, elementDeclarationNode: Iir, furtherIdentifiers: Iterable[str] = None) -> "RecordTypeElement":
        from pyGHDL.dom._Utils import GetNameOfNode
        from pyGHDL.dom._Translate import GetSubtypeIndicationFromNode

        elementName = GetNameOfNode(elementDeclarationNode)
        elementType = GetSubtypeIndicationFromNode(elementDeclarationNode, "record element", elementName)

        identifiers = [elementName]
        if furtherIdentifiers is not None:
            identifiers.extend(furtherIdentifiers)

        return cls(elementDeclarationNode, identifiers, elementType)


@export
class RecordType(VHDLModel_RecordType, DOMMixin):
    def __init__(self, node: Iir, identifier: str, elements: List[RecordTypeElement] = None):
        super().__init__(identifier, elements)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "RecordType":
        from pyGHDL.dom._Utils import GetNameOfNode

        elements = []
        elementDeclarations = nodes.Get_Elements_Declaration_List(typeDefinitionNode)

        furtherIdentifiers = []
        elementCount = flists.Flast(elementDeclarations) + 1
        index = 0
        while index < elementCount:
            elementDeclaration = flists.Get_Nth_Element(elementDeclarations, index)

            # Lookahead for elements with multiple identifiers at once
            if nodes.Get_Has_Identifier_List(elementDeclaration):
                index += 1
                while index < elementCount:
                    nextNode: Iir = flists.Get_Nth_Element(elementDeclarations, index)
                    # Consecutive identifiers are found, if the subtype indication is Null
                    if nodes.Get_Subtype_Indication(nextNode) == nodes.Null_Iir:
                        furtherIdentifiers.append(GetNameOfNode(nextNode))
                    else:
                        break
                    index += 1

                    # The last consecutive identifiers has no Identifier_List flag
                    if not nodes.Get_Has_Identifier_List(nextNode):
                        break
            else:
                index += 1

            element = RecordTypeElement.parse(elementDeclaration, furtherIdentifiers)
            elements.append(element)
            furtherIdentifiers.clear()

        return cls(typeDefinitionNode, typeName, elements)


@export
class ProtectedType(VHDLModel_ProtectedType, DOMMixin):
    def __init__(self, node: Iir, identifier: str, methods: Union[List, Iterator] = None):
        super().__init__(identifier, methods)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "ProtectedType":
        from pyGHDL.dom._Utils import GetIirKindOfNode

        # FIXME: change this to a generator
        methods = []
        for item in utils.chain_iter(nodes.Get_Declaration_Chain(typeDefinitionNode)):
            kind = GetIirKindOfNode(item)
            if kind == nodes.Iir_Kind.Function_Declaration:
                methods.append(Function.parse(item))
            elif kind == nodes.Iir_Kind.Procedure_Declaration:
                methods.append(Procedure.parse(item))

        return cls(typeDefinitionNode, typeName, methods)


@export
class ProtectedTypeBody(VHDLModel_ProtectedTypeBody, DOMMixin):
    def __init__(self, node: Iir, identifier: str, declaredItems: Union[List, Iterator] = None):
        super().__init__(identifier, declaredItems)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, protectedBodyNode: Iir) -> "ProtectedTypeBody":
        from pyGHDL.dom._Utils import GetNameOfNode
        from pyGHDL.dom._Translate import GetDeclaredItemsFromChainedNodes

        typeName = GetNameOfNode(protectedBodyNode)
        declaredItems = GetDeclaredItemsFromChainedNodes(
            nodes.Get_Declaration_Chain(protectedBodyNode),
            "protected type body",
            typeName,
        )

        return cls(protectedBodyNode, typeName, declaredItems)


@export
class AccessType(VHDLModel_AccessType, DOMMixin):
    def __init__(self, node: Iir, identifier: str, designatedSubtype: Symbol):
        super().__init__(identifier, designatedSubtype)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "AccessType":
        from pyGHDL.dom._Translate import GetSubtypeIndicationFromIndicationNode

        designatedSubtypeIndication = nodes.Get_Designated_Subtype_Indication(typeDefinitionNode)
        designatedSubtype = GetSubtypeIndicationFromIndicationNode(designatedSubtypeIndication, "access type", typeName)

        return cls(typeDefinitionNode, typeName, designatedSubtype)


@export
class FileType(VHDLModel_FileType, DOMMixin):
    def __init__(self, node: Iir, identifier: str, designatedSubtype: Symbol):
        super().__init__(identifier, designatedSubtype)
        DOMMixin.__init__(self, node)

    @classmethod
    def parse(cls, typeName: str, typeDefinitionNode: Iir) -> "FileType":
        from pyGHDL.dom._Utils import GetNameOfNode

        designatedSubtypeMark = nodes.Get_File_Type_Mark(typeDefinitionNode)
        designatedSubtypeName = GetNameOfNode(designatedSubtypeMark)
        designatedSubtype = SimpleSubtypeSymbol(typeDefinitionNode, SimpleName(designatedSubtypeName))

        return cls(typeDefinitionNode, typeName, designatedSubtype)


@export
class Subtype(VHDLModel_Subtype, DOMMixin):
    def __init__(self, node: Iir, subtypeName: str):
        super().__init__(subtypeName)
        DOMMixin.__init__(self, node)