pyVHDLModel.Type

pyVHDLModel/Type.py
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# ==================================================================================================================== #
#             __     ___   _ ____  _     __  __           _      _                                                     #
#   _ __  _   \ \   / / | | |  _ \| |   |  \/  | ___   __| | ___| |                                                    #
#  | '_ \| | | \ \ / /| |_| | | | | |   | |\/| |/ _ \ / _` |/ _ \ |                                                    #
#  | |_) | |_| |\ V / |  _  | |_| | |___| |  | | (_) | (_| |  __/ |                                                    #
#  | .__/ \__, | \_/  |_| |_|____/|_____|_|  |_|\___/ \__,_|\___|_|                                                    #
#  |_|    |___/                                                                                                        #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2017-2023 Patrick Lehmann - Boetzingen, Germany                                                            #
# Copyright 2016-2017 Patrick Lehmann - Dresden, Germany                                                               #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
This module contains parts of an abstract document language model for VHDL.

Types.
"""
from typing                 import Union, List, Iterator, Iterable, Tuple

from pyTooling.Decorators   import export
from pyTooling.MetaClasses  import ExtendedType
from pyTooling.Graph        import Vertex

from pyVHDLModel.Base       import ModelEntity, NamedEntityMixin, MultipleNamedEntityMixin, DocumentedEntityMixin, ExpressionUnion, Range
from pyVHDLModel.Symbol     import Symbol
from pyVHDLModel.Name       import Name
from pyVHDLModel.Expression import EnumerationLiteral, PhysicalIntegerLiteral


@export
class BaseType(ModelEntity, NamedEntityMixin, DocumentedEntityMixin):
	"""``BaseType`` is the base-class of all type entities in this model."""

	_objectVertex: Vertex

	def __init__(self, identifier: str, documentation: str = None):
		"""
		Initializes underlying ``BaseType``.

		:param identifier: Name of the type.
		"""
		super().__init__()
		NamedEntityMixin.__init__(self, identifier)
		DocumentedEntityMixin.__init__(self, documentation)

		_objectVertex = None


@export
class Type(BaseType):
	pass


@export
class AnonymousType(Type):
	pass


@export
class FullType(BaseType):
	pass


@export
class Subtype(BaseType):
	_type:               Symbol
	_baseType:           BaseType
	_range:              Range
	_resolutionFunction: 'Function'

	def __init__(self, identifier: str, symbol: Symbol):
		super().__init__(identifier)

		self._type = symbol
		self._baseType = None
		self._range = None
		self._resolutionFunction = None

	@property
	def Type(self) -> Symbol:
		return self._type

	@property
	def BaseType(self) -> BaseType:
		return self._baseType

	@property
	def Range(self) -> Range:
		return self._range

	@property
	def ResolutionFunction(self) -> 'Function':
		return self._resolutionFunction

	def __str__(self) -> str:
		return f"subtype {self._identifier} is {self._baseType}"


@export
class ScalarType(FullType):
	"""A ``ScalarType`` is a base-class for all scalar types."""


@export
class RangedScalarType(ScalarType):
	"""A ``RangedScalarType`` is a base-class for all scalar types with a range."""

	_range:      Union[Range, Name]
	_leftBound:  ExpressionUnion
	_rightBound: ExpressionUnion

	def __init__(self, identifier: str, rng: Union[Range, Name]):
		super().__init__(identifier)
		self._range = rng

	@property
	def Range(self) -> Union[Range, Name]:
		return self._range


@export
class NumericTypeMixin(metaclass=ExtendedType, mixin=True):
	"""A ``NumericType`` is a mixin class for all numeric types."""

	def __init__(self):
		pass


@export
class DiscreteTypeMixin(metaclass=ExtendedType, mixin=True):
	"""A ``DiscreteType`` is a mixin class for all discrete types."""

	def __init__(self):
		pass


@export
class EnumeratedType(ScalarType, DiscreteTypeMixin):
	_literals: List[EnumerationLiteral]

	def __init__(self, identifier: str, literals: Iterable[EnumerationLiteral]):
		super().__init__(identifier)

		self._literals = []
		if literals is not None:
			for literal in literals:
				self._literals.append(literal)
				literal._parent = self

	@property
	def Literals(self) -> List[EnumerationLiteral]:
		return self._literals

	def __str__(self) -> str:
		return f"{self._identifier} is ({', '.join(str(l) for l in self._literals)})"


@export
class IntegerType(RangedScalarType, NumericTypeMixin, DiscreteTypeMixin):
	def __init__(self, identifier: str, rng: Union[Range, Name]):
		super().__init__(identifier, rng)

	def __str__(self) -> str:
		return f"{self._identifier} is range {self._range}"


@export
class RealType(RangedScalarType, NumericTypeMixin):
	def __init__(self, identifier: str, rng: Union[Range, Name]):
		super().__init__(identifier, rng)

	def __str__(self) -> str:
		return f"{self._identifier} is range {self._range}"


@export
class PhysicalType(RangedScalarType, NumericTypeMixin):
	_primaryUnit:    str
	_secondaryUnits: List[Tuple[str, PhysicalIntegerLiteral]]

	def __init__(self, identifier: str, rng: Union[Range, Name], primaryUnit: str, units: Iterable[Tuple[str, PhysicalIntegerLiteral]]):
		super().__init__(identifier, rng)

		self._primaryUnit = primaryUnit

		self._secondaryUnits = []  # TODO: convert to dict
		for unit in units:
			self._secondaryUnits.append(unit)
			unit[1]._parent = self

	@property
	def PrimaryUnit(self) -> str:
		return self._primaryUnit

	@property
	def SecondaryUnits(self) -> List[Tuple[str, PhysicalIntegerLiteral]]:
		return self._secondaryUnits

	def __str__(self) -> str:
		return f"{self._identifier} is range {self._range} units {self._primaryUnit}; {'; '.join(su + ' = ' + str(pu) for su, pu in self._secondaryUnits)};"


@export
class CompositeType(FullType):
	"""A ``CompositeType`` is a base-class for all composite types."""


@export
class ArrayType(CompositeType):
	_dimensions:  List[Range]
	_elementType: Symbol

	def __init__(self, identifier: str, indices: Iterable, elementSubtype: Symbol):
		super().__init__(identifier)

		self._dimensions = []
		for index in indices:
			self._dimensions.append(index)
			# index._parent = self  # FIXME: indices are provided as empty list

		self._elementType = elementSubtype
		# elementSubtype._parent = self   # FIXME: subtype is provided as None

	@property
	def Dimensions(self) -> List[Range]:
		return self._dimensions

	@property
	def ElementType(self) -> Symbol:
		return self._elementType

	def __str__(self) -> str:
		return f"{self._identifier} is array({'; '.join(str(r) for r in self._dimensions)}) of {self._elementType}"


@export
class RecordTypeElement(ModelEntity, MultipleNamedEntityMixin):
	_subtype: Symbol

	def __init__(self, identifiers: Iterable[str], subtype: Symbol):
		super().__init__()
		MultipleNamedEntityMixin.__init__(self, identifiers)

		self._subtype = subtype
		subtype._parent = self

	@property
	def Subtype(self) -> Symbol:
		return self._subtype

	def __str__(self) -> str:
		return f"{', '.join(self._identifiers)} : {self._subtype}"


@export
class RecordType(CompositeType):
	_elements: List[RecordTypeElement]

	def __init__(self, identifier: str, elements: Iterable[RecordTypeElement] = None):
		super().__init__(identifier)

		self._elements = []  # TODO: convert to dict
		if elements is not None:
			for element in elements:
				self._elements.append(element)
				element._parent = self

	@property
	def Elements(self) -> List[RecordTypeElement]:
		return self._elements

	def __str__(self) -> str:
		return f"{self._identifier} is record {'; '.join(str(re) for re in self._elements)};"


@export
class ProtectedType(FullType):
	_methods: List[Union['Procedure', 'Function']]

	def __init__(self, identifier: str, methods: Union[List, Iterator] = None):
		super().__init__(identifier)

		self._methods = []
		if methods is not None:
			for method in methods:
				self._methods.append(method)
				method._parent = self

	@property
	def Methods(self) -> List[Union['Procedure', 'Function']]:
		return self._methods


@export
class ProtectedTypeBody(FullType):
	_methods: List[Union['Procedure', 'Function']]

	def __init__(self, identifier: str, declaredItems: Union[List, Iterator] = None):
		super().__init__(identifier)

		self._methods = []
		if declaredItems is not None:
			for method in declaredItems:
				self._methods.append(method)
				method._parent = self

	# FIXME: needs to be declared items or so
	@property
	def Methods(self) -> List[Union['Procedure', 'Function']]:
		return self._methods


@export
class AccessType(FullType):
	_designatedSubtype: Symbol

	def __init__(self, identifier: str, designatedSubtype: Symbol):
		super().__init__(identifier)

		self._designatedSubtype = designatedSubtype
		designatedSubtype._parent = self

	@property
	def DesignatedSubtype(self):
		return self._designatedSubtype

	def __str__(self) -> str:
		return f"{self._identifier} is access {self._designatedSubtype}"


@export
class FileType(FullType):
	_designatedSubtype: Symbol

	def __init__(self, identifier: str, designatedSubtype: Symbol):
		super().__init__(identifier)

		self._designatedSubtype = designatedSubtype
		designatedSubtype._parent = self

	@property
	def DesignatedSubtype(self):
		return self._designatedSubtype

	def __str__(self) -> str:
		return f"{self._identifier} is access {self._designatedSubtype}"