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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
|
# ==================================================================================================================== #
# _____ ____ _ _ ____ _ _ __ __ _ _ #
# _ __ _ _| ____| _ \ / \ / \ | _ \ _ __ ___ (_) ___ ___| |_| \/ | ___ __| | ___| | #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) | '__/ _ \| |/ _ \/ __| __| |\/| |/ _ \ / _` |/ _ \ | #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| __/| | | (_) | | __/ (__| |_| | | | (_) | (_| | __/ | #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| |_| \___// |\___|\___|\__|_| |_|\___/ \__,_|\___|_| #
# |_| |___/ |__/ #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2017-2024 Patrick Lehmann - Boetzingen, Germany #
# Copyright 2014-2016 Technische Universität Dresden - Germany, Chair of VLSI-Design, Diagnostics and Architecture #
# #
# 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 #
# ==================================================================================================================== #
#
"""An abstract model of EDA tool projects."""
__author__ = "Patrick Lehmann"
__email__ = "Paebbels@gmail.com"
__copyright__ = "2014-2024, Patrick Lehmann, Unai Martinez-Corral"
__license__ = "Apache License, Version 2.0"
__version__ = "0.5.0"
__keywords__ = ["eda project", "model", "abstract", "xilinx", "vivado", "osvvm", "file set", "file group", "test bench", "test harness"]
from os.path import relpath as path_relpath
from pathlib import Path as pathlib_Path
from sys import version_info
from typing import Dict, Union, Optional as Nullable, List, Iterable, Generator, Tuple, Any as typing_Any, Type, Set, Any
from pyTooling.Common import getFullyQualifiedName
from pyTooling.Decorators import export
from pyTooling.MetaClasses import ExtendedType
from pyTooling.Graph import Graph, Vertex
from pySVModel import SystemVerilogVersion
from pyVHDLModel import VHDLVersion
from pySystemRDLModel import SystemRDLVersion
@export
class Attribute(metaclass=ExtendedType):
KEY: str
VALUE_TYPE: typing_Any
@staticmethod
def resolve(obj: typing_Any, key: Type['Attribute']):
if isinstance(obj, File):
return obj._fileSet[key]
elif isinstance(obj, FileSet):
return obj._design[key]
elif isinstance(obj, Design):
return obj._project[key]
else:
raise Exception("Resolution error")
@export
class FileType(ExtendedType):
"""
A :term:`meta-class` to construct *FileType* classes.
Modifications done by this meta-class:
* Register all classes of type :class:`FileType` or derived variants in a class field :attr:`FileType.FileTypes` in this meta-class.
"""
FileTypes: Dict[str, 'FileType'] = {} #: Dictionary of all classes of type :class:`FileType` or derived variants
Any: 'FileType'
def __init__(cls, name: str, bases: Tuple[type, ...], dictionary: Dict[str, typing_Any], **kwargs):
super().__init__(name, bases, dictionary, **kwargs)
cls.Any = cls
def __new__(cls, className, baseClasses, classMembers: Dict, *args, **kwargs):
fileType = super().__new__(cls, className, baseClasses, classMembers, *args, **kwargs)
cls.FileTypes[className] = fileType
return fileType
def __getattr__(cls, item) -> 'FileType':
if item[:2] != "__" and item[-2:] != "__":
return cls.FileTypes[item]
else:
return super().__getattribute__(item)
def __contains__(cls, item) -> bool:
return issubclass(item, cls)
@export
class File(metaclass=FileType, slots=True):
"""
A :term:`File` represents a file in a design. This :term:`base-class` is used
for all derived file classes.
A file can be created standalone and later associated to a fileset, design and
project. Or a fileset, design and/or project can be associated immediately
while creating a file.
:arg path: Relative or absolute path to the file.
:arg project: Project the file is associated with.
:arg design: Design the file is associated with.
:arg fileSet: Fileset the file is associated with.
"""
_path: pathlib_Path
_fileType: 'FileType'
_project: Nullable['Project']
_design: Nullable['Design']
_fileSet: Nullable['FileSet']
_attributes: Dict[Type[Attribute], typing_Any]
def __init__(
self,
path: pathlib_Path,
project: Nullable["Project"] = None,
design: Nullable["Design"] = None,
fileSet: Nullable["FileSet"] = None
):
self._fileType = getattr(FileTypes, self.__class__.__name__)
self._path = path
if project is not None:
self._project = project
self._design = design
if fileSet is not None:
self.FileSet = fileSet
elif design is not None:
self._project = design._project
self._design = design
self.FileSet = design.DefaultFileSet if fileSet is None else fileSet
elif fileSet is not None:
design = fileSet._design
if design is not None:
self._project = design._project
else:
self._project = None
self._design = design
self.FileSet = fileSet
else:
self._project = None
self._design = None
self._fileSet = None
self._attributes = {}
self._registerAttributes()
def _registerAttributes(self) -> None:
pass
@property
def FileType(self) -> 'FileType':
"""Read-only property to return the file type of this file."""
return self._fileType
@property
def Path(self) -> pathlib_Path:
"""Read-only property returning the path of this file."""
return self._path
# TODO: setter?
@property
def ResolvedPath(self) -> pathlib_Path:
"""Read-only property returning the resolved path of this file."""
if self._path.is_absolute():
return self._path.resolve()
elif self._fileSet is not None:
path = (self._fileSet.ResolvedPath / self._path).resolve()
if path.is_absolute():
return path
else:
# WORKAROUND: https://stackoverflow.com/questions/67452690/pathlib-path-relative-to-vs-os-path-relpath
return pathlib_Path(path_relpath(path, pathlib_Path.cwd()))
else:
# TODO: message and exception type
raise Exception("")
@property
def Project(self) -> Nullable['Project']:
"""Property setting or returning the project this file is used in."""
return self._project
@Project.setter
def Project(self, value: 'Project') -> None:
self._project = value
if self._fileSet is None:
self._project.DefaultDesign.DefaultFileSet.AddFile(self)
@property
def Design(self) -> Nullable['Design']:
"""Property setting or returning the design this file is used in."""
return self._design
@Design.setter
def Design(self, value: 'Design') -> None:
self._design = value
if self._fileSet is None:
self._design.DefaultFileSet.AddFile(self)
if self._project is None:
self._project = value._project
elif self._project is not value._project:
raise Exception("The design's project is not identical to the already assigned project.")
@property
def FileSet(self) -> Nullable['FileSet']:
"""Property setting or returning the fileset this file is used in."""
return self._fileSet
@FileSet.setter
def FileSet(self, value: 'FileSet') -> None:
self._fileSet = value
value._files.append(self)
def Validate(self) -> None:
"""Validate this file."""
if self._path is None:
raise Exception("Validation: File has no path.")
try:
path = self.ResolvedPath
except Exception as ex:
raise Exception(f"Validation: File '{self._path}' could not compute resolved path.") from ex
if not path.exists():
raise Exception(f"Validation: File '{self._path}' (={path}) does not exist.")
if not path.is_file():
raise Exception(f"Validation: File '{self._path}' (={path}) is not a file.")
if self._fileSet is None:
raise Exception(f"Validation: File '{self._path}' has no fileset.")
if self._design is None:
raise Exception(f"Validation: File '{self._path}' has no design.")
if self._project is None:
raise Exception(f"Validation: File '{self._path}' has no project.")
def __len__(self) -> int:
"""
Returns number of attributes set on this file.
:returns: The number if attributes set on this file.
"""
return len(self._attributes)
def __getitem__(self, key: Type[Attribute]) -> Any:
"""Index access for returning attributes on this file.
:param key: The attribute type.
:returns: The attribute's value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
try:
return self._attributes[key]
except KeyError:
try:
return key.resolve(self, key)
except KeyError:
attribute = key()
self._attributes[key] = attribute
return attribute
def __setitem__(self, key: Type[Attribute], value: typing_Any) -> None:
"""
Index access for adding or setting attributes on this file.
:param key: The attribute type.
:param value: The attributes value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
self._attributes[key] = value
def __delitem__(self, key: Type[Attribute]) -> None:
"""
Index access for deleting attributes on this file.
:param key: The attribute type.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
del self._attributes[key]
def __str__(self) -> str:
return f"{self._path}"
FileTypes = File
@export
class HumanReadableContent(metaclass=ExtendedType, mixin=True):
"""A file type representing human-readable contents."""
@export
class XMLContent(HumanReadableContent, mixin=True):
"""A file type representing XML contents."""
@export
class YAMLContent(HumanReadableContent, mixin=True):
"""A file type representing YAML contents."""
@export
class JSONContent(HumanReadableContent, mixin=True):
"""A file type representing JSON contents."""
@export
class INIContent(HumanReadableContent, mixin=True):
"""A file type representing INI contents."""
@export
class TOMLContent(HumanReadableContent, mixin=True):
"""A file type representing TOML contents."""
@export
class TCLContent(HumanReadableContent, mixin=True):
"""A file type representing content in TCL code."""
@export
class SDCContent(TCLContent, mixin=True):
"""A file type representing contents as Synopsys Design Constraints (SDC)."""
@export
class PythonContent(HumanReadableContent, mixin=True):
"""A file type representing contents as Python source code."""
@export
class TextFile(File, HumanReadableContent):
"""A text file (``*.txt``)."""
@export
class LogFile(File, HumanReadableContent):
"""A log file (``*.log``)."""
@export
class XMLFile(File, XMLContent):
"""An XML file (``*.xml``)."""
@export
class SourceFile(File):
"""Base-class of all source files."""
@export
class HDLSourceFile(SourceFile):
"""Base-class of all HDL source files."""
@export
class RDLSourceFile(SourceFile):
"""Base-class of all RDL source files."""
@export
class NetlistFile(SourceFile):
"""Base-class of all netlist source files."""
@export
class EDIFNetlistFile(NetlistFile):
"""Netlist file in EDIF (Electronic Design Interchange Format)."""
@export
class TCLSourceFile(SourceFile, TCLContent):
"""A TCL source file."""
@export
class VHDLSourceFile(HDLSourceFile, HumanReadableContent):
"""
A VHDL source file (of any language version).
:arg path: Relative or absolute path to the file.
:arg vhdlLibrary: VHDLLibrary this VHDL source file is associated wih.
:arg vhdlVersion: VHDLVersion this VHDL source file is associated wih.
:arg project: Project the file is associated with.
:arg design: Design the file is associated with.
:arg fileSet: Fileset the file is associated with.
"""
_vhdlLibrary: Nullable['VHDLLibrary']
_vhdlVersion: VHDLVersion
def __init__(self, path: pathlib_Path, vhdlLibrary: Union[str, 'VHDLLibrary'] = None, vhdlVersion: Nullable[VHDLVersion] = None, project: Nullable["Project"] = None, design: Nullable["Design"] = None, fileSet: Nullable["FileSet"] = None):
super().__init__(path, project, design, fileSet)
if isinstance(vhdlLibrary, str):
if design is not None:
try:
vhdlLibrary = design.VHDLLibraries[vhdlLibrary]
except KeyError as ex:
raise Exception(f"VHDL library '{vhdlLibrary}' not found in design '{design.Name}'.") from ex
elif project is not None:
try:
vhdlLibrary = project.DefaultDesign.VHDLLibraries[vhdlLibrary]
except KeyError as ex:
raise Exception(f"VHDL library '{vhdlLibrary}' not found in default design '{project.DefaultDesign.Name}'.") from ex
else:
raise Exception(f"Can't lookup VHDL library because neither 'project' nor 'design' is given as a parameter.")
elif isinstance(vhdlLibrary, VHDLLibrary):
self._vhdlLibrary = vhdlLibrary
vhdlLibrary.AddFile(self)
elif vhdlLibrary is None:
self._vhdlLibrary = None
else:
ex = TypeError(f"Parameter 'vhdlLibrary' is neither a 'str' nor 'VHDLibrary'.")
if version_info >= (3, 11): # pragma: no cover
ex.add_note(f"Got type '{getFullyQualifiedName(vhdlLibrary)}'.")
raise ex
self._vhdlVersion = vhdlVersion
def Validate(self) -> None:
"""Validate this VHDL source file."""
super().Validate()
try:
_ = self.VHDLLibrary
except Exception as ex:
raise Exception(f"Validation: VHDLSourceFile '{self._path}' (={self.ResolvedPath}) has no VHDLLibrary assigned.") from ex
try:
_ = self.VHDLVersion
except Exception as ex:
raise Exception(f"Validation: VHDLSourceFile '{self._path}' (={self.ResolvedPath}) has no VHDLVersion assigned.") from ex
@property
def VHDLLibrary(self) -> 'VHDLLibrary':
"""Property setting or returning the VHDL library this VHDL source file is used in."""
if self._vhdlLibrary is not None:
return self._vhdlLibrary
elif self._fileSet is not None:
return self._fileSet.VHDLLibrary
else:
raise Exception("VHDLLibrary was neither set locally nor globally.")
@VHDLLibrary.setter
def VHDLLibrary(self, value: 'VHDLLibrary') -> None:
self._vhdlLibrary = value
value._files.append(self)
@property
def VHDLVersion(self) -> VHDLVersion:
"""Property setting or returning the VHDL version this VHDL source file is used in."""
if self._vhdlVersion is not None:
return self._vhdlVersion
elif self._fileSet is not None:
return self._fileSet.VHDLVersion
else:
raise Exception("VHDLVersion was neither set locally nor globally.")
@VHDLVersion.setter
def VHDLVersion(self, value: VHDLVersion) -> None:
self._vhdlVersion = value
def __repr__(self) -> str:
return f"<VHDL file: '{self.ResolvedPath}'; lib: '{self.VHDLLibrary}'; version: {self.VHDLVersion}>"
class VerilogMixIn(metaclass=ExtendedType, mixin=True):
@property
def VerilogVersion(self) -> SystemVerilogVersion:
"""Property setting or returning the Verilog version this Verilog source file is used in."""
if self._version is not None:
return self._version
elif self._fileSet is not None:
return self._fileSet.VerilogVersion
else:
raise Exception("VerilogVersion was neither set locally nor globally.")
@VerilogVersion.setter
def VerilogVersion(self, value: SystemVerilogVersion) -> None:
self._version = value
class SystemVerilogMixIn(metaclass=ExtendedType, mixin=True):
@property
def SVVersion(self) -> SystemVerilogVersion:
"""Property setting or returning the SystemVerilog version this SystemVerilog source file is used in."""
if self._version is not None:
return self._version
elif self._fileSet is not None:
return self._fileSet.SVVersion
else:
raise Exception("SVVersion was neither set locally nor globally.")
@SVVersion.setter
def SVVersion(self, value: SystemVerilogVersion) -> None:
self._version = value
@export
class VerilogBaseFile(HDLSourceFile, HumanReadableContent):
_version: SystemVerilogVersion
def __init__(self, path: pathlib_Path, version: Nullable[SystemVerilogVersion] = None, project: Nullable["Project"] = None, design: Nullable["Design"] = None, fileSet: Nullable["FileSet"] = None):
super().__init__(path, project, design, fileSet)
self._version = version
@export
class VerilogSourceFile(VerilogBaseFile, VerilogMixIn):
"""A Verilog source file (of any language version)."""
@export
class VerilogHeaderFile(VerilogBaseFile, VerilogMixIn):
"""A Verilog header file (of any language version)."""
@export
class SystemVerilogBaseFile(VerilogBaseFile):
...
@export
class SystemVerilogSourceFile(SystemVerilogBaseFile, SystemVerilogMixIn):
"""A SystemVerilog source file (of any language version)."""
@export
class SystemVerilogHeaderFile(SystemVerilogBaseFile, SystemVerilogMixIn):
"""A SystemVerilog header file (of any language version)."""
@export
class SystemRDLSourceFile(RDLSourceFile, HumanReadableContent):
"""A SystemRDL source file (of any language version)."""
_srdlVersion: SystemRDLVersion
def __init__(self, path: pathlib_Path, srdlVersion: Nullable[SystemRDLVersion] = None, project: Nullable["Project"] = None, design: Nullable["Design"] = None, fileSet: Nullable["FileSet"] = None):
super().__init__(path, project, design, fileSet)
self._srdlVersion = srdlVersion
@property
def SystemRDLVersion(self) -> SystemRDLVersion:
"""Property setting or returning the SystemRDL version this SystemRDL source file is used in."""
if self._srdlVersion is not None:
return self._srdlVersion
elif self._fileSet is not None:
return self._fileSet.SRDLVersion
else:
raise Exception("SRDLVersion was neither set locally nor globally.")
@SystemRDLVersion.setter
def SystemRDLVersion(self, value: SystemRDLVersion) -> None:
self._srdlVersion = value
@export
class PythonSourceFile(SourceFile, PythonContent):
"""A Python source file."""
# TODO: move to a Cocotb module
@export
class CocotbPythonFile(PythonSourceFile):
"""A Python source file used by Cocotb."""
@export
class ConstraintFile(File, HumanReadableContent):
"""Base-class of all constraint files."""
@export
class ProjectFile(File):
"""Base-class of all tool-specific project files."""
@export
class CSourceFile(SourceFile):
"""Base-class of all ANSI-C source files."""
@export
class CppSourceFile(SourceFile):
"""Base-class of all ANSI-C++ source files."""
@export
class SettingFile(File):
"""Base-class of all tool-specific setting files."""
@export
class SimulationAnalysisFile(File):
"""Base-class of all tool-specific analysis files."""
@export
class SimulationElaborationFile(File):
"""Base-class of all tool-specific elaboration files."""
@export
class SimulationStartFile(File):
"""Base-class of all tool-specific simulation start-up files."""
@export
class SimulationRunFile(File):
"""Base-class of all tool-specific simulation run (execution) files."""
@export
class WaveformConfigFile(File):
"""Base-class of all tool-specific waveform configuration files."""
@export
class WaveformDatabaseFile(File):
"""Base-class of all tool-specific waveform database files."""
@export
class WaveformExchangeFile(File):
"""Base-class of all tool-independent waveform exchange files."""
@export
class FileSet(metaclass=ExtendedType, slots=True):
"""
A :term:`FileSet` represents a group of files. Filesets can have sub-filesets.
The order of insertion is preserved. A fileset can be created standalone and
later associated to another fileset, design and/or project. Or a fileset,
design and/or project can be associated immediately while creating the
fileset.
:arg name: Name of this fileset.
:arg topLevel: Name of the fileset's toplevel.
:arg directory: Path of this fileset (absolute or relative to a parent fileset or design).
:arg project: Project the file is associated with.
:arg design: Design the file is associated with.
:arg parent: Parent fileset if this fileset is nested.
:arg vhdlLibrary: Default VHDL library for files in this fileset, if not specified for the file itself.
:arg vhdlVersion: Default VHDL version for files in this fileset, if not specified for the file itself.
:arg verilogVersion: Default Verilog version for files in this fileset, if not specified for the file itself.
:arg svVersion: Default SystemVerilog version for files in this fileset, if not specified for the file itself.
:arg srdlVersion: Default SystemRDL version for files in this fileset, if not specified for the file itself.
"""
_name: str
_topLevel: Nullable[str]
_project: Nullable['Project']
_design: Nullable['Design']
_directory: pathlib_Path
_parent: Nullable['FileSet']
_fileSets: Dict[str, 'FileSet']
_files: List[File]
_set: Set
_attributes: Dict[Type[Attribute], typing_Any]
_vhdlLibraries: Dict[str, 'VHDLLibrary']
_vhdlLibrary: 'VHDLLibrary'
_vhdlVersion: VHDLVersion
_verilogVersion: SystemVerilogVersion
_svVersion: SystemVerilogVersion
_srdlVersion: SystemRDLVersion
def __init__(
self,
name: str,
topLevel: Nullable[str] = None,
directory: pathlib_Path = pathlib_Path("."),
project: Nullable["Project"] = None,
design: Nullable["Design"] = None,
parent: Nullable['FileSet'] = None,
vhdlLibrary: Union[str, 'VHDLLibrary'] = None,
vhdlVersion: Nullable[VHDLVersion] = None,
verilogVersion: Nullable[SystemVerilogVersion] = None,
svVersion: Nullable[SystemVerilogVersion] = None,
srdlVersion: Nullable[SystemRDLVersion] = None
):
self._name = name
self._topLevel = topLevel
if project is not None:
self._project = project
self._design = design if design is not None else project.DefaultDesign
elif design is not None:
self._project = design._project
self._design = design
else:
self._project = None
self._design = None
self._directory = directory
self._parent = parent
self._fileSets = {}
self._files = []
self._set = set()
if design is not None:
design._fileSets[name] = self
self._attributes = {}
self._vhdlLibraries = {}
# TODO: handle if vhdlLibrary is a string
self._vhdlLibrary = vhdlLibrary
self._vhdlVersion = vhdlVersion
self._verilogVersion = verilogVersion
self._svVersion = svVersion
self._srdlVersion = srdlVersion
@property
def Name(self) -> str:
"""Property setting or returning the fileset's name."""
return self._name
@Name.setter
def Name(self, value: str) -> None:
self._name = value
@property
def TopLevel(self) -> str:
"""Property setting or returning the fileset's toplevel."""
return self._topLevel
@TopLevel.setter
def TopLevel(self, value: str) -> None:
self._topLevel = value
@property
def Project(self) -> Nullable['Project']:
"""Property setting or returning the project this fileset is used in."""
return self._project
@Project.setter
def Project(self, value: 'Project') -> None:
self._project = value
@property
def Design(self) -> Nullable['Design']:
"""Property setting or returning the design this fileset is used in."""
if self._design is not None:
return self._design
elif self._parent is not None:
return self._parent.Design
else:
return None
# TODO: raise exception instead
# QUESTION: how to handle if design and parent is set?
@Design.setter
def Design(self, value: 'Design') -> None:
self._design = value
if self._project is None:
self._project = value._project
elif self._project is not value._project:
raise Exception("The design's project is not identical to the already assigned project.")
@property
def Directory(self) -> pathlib_Path:
"""Property setting or returning the directory this fileset is located in."""
return self._directory
@Directory.setter
def Directory(self, value: pathlib_Path) -> None:
self._directory = value
@property
def ResolvedPath(self) -> pathlib_Path:
"""Read-only property returning the resolved path of this fileset."""
if self._directory.is_absolute():
return self._directory.resolve()
else:
if self._parent is not None:
directory = self._parent.ResolvedPath
elif self._design is not None:
directory = self._design.ResolvedPath
elif self._project is not None:
directory = self._project.ResolvedPath
else:
# TODO: message and exception type
raise Exception("")
directory = (directory / self._directory).resolve()
if directory.is_absolute():
return directory
else:
# WORKAROUND: https://stackoverflow.com/questions/67452690/pathlib-path-relative-to-vs-os-path-relpath
return pathlib_Path(path_relpath(directory, pathlib_Path.cwd()))
@property
def Parent(self) -> Nullable['FileSet']:
"""Property setting or returning the parent fileset this fileset is used in."""
return self._parent
@Parent.setter
def Parent(self, value: 'FileSet') -> None:
self._parent = value
value._fileSets[self._name] = self
# TODO: check it it already exists
# QUESTION: make an Add fileset method?
@property
def FileSets(self) -> Dict[str, 'FileSet']:
"""Read-only property returning the dictionary of sub-filesets."""
return self._fileSets
def Files(self, fileType: FileType = FileTypes.Any, fileSet: Union[bool, str, 'FileSet'] = None) -> Generator[File, None, None]:
"""
Method returning the files of this fileset.
:arg fileType: A filter for file types. Default: ``Any``.
:arg fileSet: Specifies how to handle sub-filesets.
"""
if fileSet is False:
for file in self._files:
if file.FileType in fileType:
yield file
elif fileSet is None:
for fileSet in self._fileSets.values():
for file in fileSet.Files(fileType):
yield file
for file in self._files:
if file.FileType in fileType:
yield file
else:
if isinstance(fileSet, str):
fileSetName = fileSet
try:
fileSet = self._fileSets[fileSetName]
except KeyError as ex:
raise Exception(f"Fileset {fileSetName} not bound to fileset {self.Name}.") from ex
elif not isinstance(fileSet, FileSet):
raise TypeError("Parameter 'fileSet' is not of type 'str' or 'FileSet' nor value 'None'.")
for file in fileSet.Files(fileType):
yield file
def AddFileSet(self, fileSet: "FileSet") -> None:
"""
Method to add a single sub-fileset to this fileset.
:arg fileSet: A fileset to add to this fileset as sub-fileset.
"""
if not isinstance(fileSet, FileSet):
raise ValueError("Parameter 'fileSet' is not of type ProjectModel.FileSet.")
elif fileSet in self._fileSets:
raise Exception("Sub-fileset already contains this fileset.")
elif fileSet.Name in self._fileSets.keys():
raise Exception(f"Fileset already contains a sub-fileset named '{fileSet.Name}'.")
self._fileSets[fileSet.Name] = fileSet
fileSet._parent = self
def AddFileSets(self, fileSets: Iterable["FileSet"]) -> None:
"""
Method to add a multiple sub-filesets to this fileset.
:arg fileSets: An iterable of filesets to add each to the fileset.
"""
for fileSet in fileSets:
self.AddFileSet(fileSet)
@property
def FileSetCount(self) -> int:
"""Returns number of file sets excl. sub-filesets."""
return len(self._fileSets)
@property
def TotalFileSetCount(self) -> int:
"""Returns number of file sets incl. sub-filesets."""
fileSetCount = len(self._fileSets)
for fileSet in self._fileSets.values():
fileSetCount += fileSet.TotalFileSetCount
return fileSetCount
def AddFile(self, file: File) -> None:
"""
Method to add a single file to this fileset.
:arg file: A file to add to this fileset.
"""
if not isinstance(file, File):
raise TypeError("Parameter 'file' is not of type ProjectModel.File.")
elif file._fileSet is not None:
ex = ValueError(f"File '{file.Path!s}' is already part of fileset '{file.FileSet.Name}'.")
if version_info >= (3, 11): # pragma: no cover
ex.add_note(f"A file can't be assigned to another fileset.")
raise ex
elif file in self._set:
ex = ValueError(f"File '{file.Path!s}' is already part of this fileset.")
if version_info >= (3, 11): # pragma: no cover
ex.add_note(f"A file can't be added twice to a fileset.")
raise ex
self._files.append(file)
self._set.add(file)
file._fileSet = self
def AddFiles(self, files: Iterable[File]) -> None:
"""
Method to add a multiple files to this fileset.
:arg files: An iterable of files to add each to the fileset.
"""
for file in files:
self.AddFile(file)
@property
def FileCount(self) -> int:
"""Returns number of files excl. sub-filesets."""
return len(self._files)
@property
def TotalFileCount(self) -> int:
"""Returns number of files incl. the files in sub-filesets."""
fileCount = len(self._files)
for fileSet in self._fileSets.values():
fileCount += fileSet.FileCount
return fileCount
def Validate(self) -> None:
"""Validate this fileset."""
if self._name is None or self._name == "":
raise Exception("Validation: FileSet has no name.")
if self._directory is None:
raise Exception(f"Validation: FileSet '{self._name}' has no directory.")
try:
path = self.ResolvedPath
except Exception as ex:
raise Exception(f"Validation: FileSet '{self._name}' could not compute resolved path.") from ex
if not path.exists():
raise Exception(f"Validation: FileSet '{self._name}'s directory '{path}' does not exist.")
if not path.is_dir():
raise Exception(f"Validation: FileSet '{self._name}'s directory '{path}' is not a directory.")
if self._design is None:
raise Exception(f"Validation: FileSet '{self._directory}' has no design.")
if self._project is None:
raise Exception(f"Validation: FileSet '{self._directory}' has no project.")
for fileSet in self._fileSets.values():
fileSet.Validate()
for file in self._files:
file.Validate()
def GetOrCreateVHDLLibrary(self, name) -> 'VHDLLibrary':
if name in self._vhdlLibraries:
return self._vhdlLibraries[name]
elif name in self._design._vhdlLibraries:
library = self._design._vhdlLibraries[name]
self._vhdlLibraries[name] = library
return library
else:
library = VHDLLibrary(name, design=self._design, vhdlVersion=self._vhdlVersion)
self._vhdlLibraries[name] = library
return library
@property
def VHDLLibrary(self) -> 'VHDLLibrary':
"""Property setting or returning the VHDL library of this fileset."""
if self._vhdlLibrary is not None:
return self._vhdlLibrary
elif self._parent is not None:
return self._parent.VHDLLibrary
elif self._design is not None:
return self._design.VHDLLibrary
else:
raise Exception("VHDLLibrary was neither set locally nor globally.")
@VHDLLibrary.setter
def VHDLLibrary(self, value: 'VHDLLibrary') -> None:
self._vhdlLibrary = value
@property
def VHDLVersion(self) -> VHDLVersion:
"""Property setting or returning the VHDL version of this fileset."""
if self._vhdlVersion is not None:
return self._vhdlVersion
elif self._parent is not None:
return self._parent.VHDLVersion
elif self._design is not None:
return self._design.VHDLVersion
else:
raise Exception("VHDLVersion was neither set locally nor globally.")
@VHDLVersion.setter
def VHDLVersion(self, value: VHDLVersion) -> None:
self._vhdlVersion = value
@property
def VerilogVersion(self) -> SystemVerilogVersion:
"""Property setting or returning the Verilog version of this fileset."""
if self._verilogVersion is not None:
return self._verilogVersion
elif self._parent is not None:
return self._parent.VerilogVersion
elif self._design is not None:
return self._design.VerilogVersion
else:
raise Exception("VerilogVersion was neither set locally nor globally.")
@VerilogVersion.setter
def VerilogVersion(self, value: SystemVerilogVersion) -> None:
self._verilogVersion = value
@property
def SVVersion(self) -> SystemVerilogVersion:
"""Property setting or returning the SystemVerilog version of this fileset."""
if self._svVersion is not None:
return self._svVersion
elif self._parent is not None:
return self._parent.SVVersion
elif self._design is not None:
return self._design.SVVersion
else:
raise Exception("SVVersion was neither set locally nor globally.")
@SVVersion.setter
def SVVersion(self, value: SystemVerilogVersion) -> None:
self._svVersion = value
@property
def SRDLVersion(self) -> SystemRDLVersion:
if self._srdlVersion is not None:
return self._srdlVersion
elif self._parent is not None:
return self._parent.SRDLVersion
elif self._design is not None:
return self._design.SRDLVersion
else:
raise Exception("SRDLVersion was neither set locally nor globally.")
@SRDLVersion.setter
def SRDLVersion(self, value: SystemRDLVersion) -> None:
self._srdlVersion = value
def __len__(self) -> int:
"""
Returns number of attributes set on this fileset.
:returns: The number if attributes set on this fileset.
"""
return len(self._attributes)
def __getitem__(self, key: Type[Attribute]) -> Any:
"""Index access for returning attributes on this fileset.
:param key: The attribute type.
:returns: The attribute's value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
try:
return self._attributes[key]
except KeyError:
return key.resolve(self, key)
def __setitem__(self, key: Type[Attribute], value: typing_Any) -> None:
"""
Index access for adding or setting attributes on this fileset.
:param key: The attribute type.
:param value: The attributes value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
self._attributes[key] = value
def __delitem__(self, key: Type[Attribute]) -> None:
"""
Index access for deleting attributes on this fileset.
:param key: The attribute type.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
del self._attributes[key]
def __str__(self) -> str:
"""Returns the fileset's name."""
return self._name
@export
class VHDLLibrary(metaclass=ExtendedType, slots=True):
"""
A :term:`VHDLLibrary` represents a group of VHDL source files compiled into the same VHDL library.
:arg name: The VHDL libraries' name.
:arg project: Project the VHDL library is associated with.
:arg design: Design the VHDL library is associated with.
:arg vhdlVersion: Default VHDL version for files in this VHDL library, if not specified for the file itself.
"""
_name: str
_project: Nullable['Project']
_design: Nullable['Design']
_files: List[File]
_vhdlVersion: VHDLVersion
_dependencyNode: Vertex
def __init__(
self,
name: str,
project: Nullable["Project"] = None,
design: Nullable["Design"] = None,
vhdlVersion: Nullable[VHDLVersion] = None
):
self._name = name
if project is not None:
self._project = project
self._design = project._defaultDesign if design is None else design
self._dependencyNode = Vertex(value=self, graph=self._design._vhdlLibraryDependencyGraph)
if name in self._design._vhdlLibraries:
raise Exception(f"Library '{name}' already in design '{self._design.Name}'.")
else:
self._design._vhdlLibraries[name] = self
elif design is not None:
self._project = design._project
self._design = design
self._dependencyNode = Vertex(value=self, graph=design._vhdlLibraryDependencyGraph)
if name in design._vhdlLibraries:
raise Exception(f"Library '{name}' already in design '{design.Name}'.")
else:
design._vhdlLibraries[name] = self
else:
self._project = None
self._design = None
self._dependencyNode = None
self._files = []
self._vhdlVersion = vhdlVersion
@property
def Name(self) -> str:
return self._name
@property
def Project(self) -> Nullable['Project']:
"""Property setting or returning the project this VHDL library is used in."""
return self._project
@Project.setter
def Project(self, value: 'Project') -> None:
if not isinstance(value, Project):
raise TypeError("Parameter 'value' is not of type 'Project'.")
if value is None:
# TODO: unlink VHDLLibrary from project
self._project = None
else:
self._project = value
if self._design is None:
self._design = value._defaultDesign
@property
def Design(self) -> Nullable['Design']:
"""Property setting or returning the design this VHDL library is used in."""
return self._design
@Design.setter
def Design(self, value: 'Design') -> None:
if not isinstance(value, Design):
raise TypeError("Parameter 'value' is not of type 'Design'.")
if value is None:
# TODO: unlink VHDLLibrary from design
self._design = None
else:
if self._design is None:
self._design = value
self._dependencyNode = Vertex(value=self, graph=self._design._vhdlLibraryDependencyGraph)
elif self._design is not value:
# TODO: move VHDLLibrary to other design
# TODO: create new vertex in dependency graph and remove vertex from old graph
self._design = value
else:
pass
if self._project is None:
self._project = value._project
elif self._project is not value._project:
raise Exception("The design's project is not identical to the already assigned project.")
@property
def Files(self) -> Generator[File, None, None]:
"""Read-only property to return all files in this VHDL library."""
for file in self._files:
yield file
@property
def VHDLVersion(self) -> VHDLVersion:
"""Property setting or returning the VHDL version of this VHDL library."""
if self._vhdlVersion is not None:
return self._vhdlVersion
elif self._design is not None:
return self._design.VHDLVersion
else:
raise Exception("VHDLVersion is not set on VHDLLibrary nor parent object.")
@VHDLVersion.setter
def VHDLVersion(self, value: VHDLVersion) -> None:
self._vhdlVersion = value
def AddDependency(self, library: 'VHDLLibrary') -> None:
library.parent = self
def AddFile(self, vhdlFile: VHDLSourceFile) -> None:
if not isinstance(vhdlFile, VHDLSourceFile):
ex = TypeError(f"Parameter 'vhdlFile' is not a 'VHDLSourceFile'.")
if version_info >= (3, 11): # pragma: no cover
ex.add_note(f"Got type '{getFullyQualifiedName(vhdlFile)}'.")
raise ex
self._files.append(vhdlFile)
def AddFiles(self, vhdlFiles: Iterable[VHDLSourceFile]) -> None:
for vhdlFile in vhdlFiles:
if not isinstance(vhdlFile, VHDLSourceFile):
raise TypeError(f"Item '{vhdlFile}' in parameter 'vhdlFiles' is not a 'VHDLSourceFile'.")
self._files.append(vhdlFile)
@property
def FileCount(self) -> int:
"""Returns number of files."""
return len(self._files)
def __len__(self) -> int:
"""
Returns number of attributes set on this VHDL library.
:returns: The number if attributes set on this VHDL library.
"""
return len(self._attributes)
def __getitem__(self, key: Type[Attribute]) -> Any:
"""Index access for returning attributes on this VHDL library.
:param key: The attribute type.
:returns: The attribute's value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
try:
return self._attributes[key]
except KeyError:
return key.resolve(self, key)
def __setitem__(self, key: Type[Attribute], value: typing_Any) -> None:
"""
Index access for adding or setting attributes on this VHDL library.
:param key: The attribute type.
:param value: The attributes value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
self._attributes[key] = value
def __delitem__(self, key: Type[Attribute]) -> None:
"""
Index access for deleting attributes on this VHDL library.
:param key: The attribute type.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
del self._attributes[key]
def __str__(self) -> str:
"""Returns the VHDL library's name."""
return self._name
@export
class Design(metaclass=ExtendedType, slots=True):
"""
A :term:`Design` represents a group of filesets and the source files therein.
Each design contains at least one fileset - the :term:`default fileset`. For
designs with VHDL source files, a independent `VHDLLibraries` overlay structure
exists.
:arg name: The design's name.
:arg topLevel: Name of the design's toplevel.
:arg directory: Path of this design (absolute or relative to the project).
:arg project: Project the design is associated with.
:arg vhdlVersion: Default VHDL version for files in this design, if not specified for the file itself.
:arg verilogVersion: Default Verilog version for files in this design, if not specified for the file itself.
:arg svVersion: Default SystemVerilog version for files in this design, if not specified for the file itself.
:arg srdlVersion: Default SystemRDL version for files in this fileset, if not specified for the file itself.
"""
_name: str
_topLevel: Nullable[str]
_project: Nullable['Project']
_directory: pathlib_Path
_fileSets: Dict[str, FileSet]
_defaultFileSet: Nullable[FileSet]
_attributes: Dict[Type[Attribute], typing_Any]
_vhdlLibraries: Dict[str, VHDLLibrary]
_vhdlVersion: VHDLVersion
_verilogVersion: SystemVerilogVersion
_svVersion: SystemVerilogVersion
_srdlVersion: SystemRDLVersion
_externalVHDLLibraries: List
_vhdlLibraryDependencyGraph: Graph
_fileDependencyGraph: Graph
def __init__(
self,
name: str,
topLevel: Nullable[str] = None,
directory: pathlib_Path = pathlib_Path("."),
project: Nullable["Project"] = None,
vhdlVersion: Nullable[VHDLVersion] = None,
verilogVersion: Nullable[SystemVerilogVersion] = None,
svVersion: Nullable[SystemVerilogVersion] = None,
srdlVersion: Nullable[SystemRDLVersion] = None
):
self._name = name
self._topLevel = topLevel
self._project = project
if project is not None:
project._designs[name] = self
self._directory = directory
self._fileSets = {}
self._defaultFileSet = FileSet("default", project=project, design=self)
self._attributes = {}
self._vhdlLibraries = {}
self._vhdlVersion = vhdlVersion
self._verilogVersion = verilogVersion
self._svVersion = svVersion
self._srdlVersion = srdlVersion
self._externalVHDLLibraries = []
self._vhdlLibraryDependencyGraph = Graph()
self._fileDependencyGraph = Graph()
@property
def Name(self) -> str:
"""Property setting or returning the design's name."""
return self._name
@Name.setter
def Name(self, value: str) -> None:
self._name = value
@property
def TopLevel(self) -> str:
"""Property setting or returning the fileset's toplevel."""
return self._topLevel
@TopLevel.setter
def TopLevel(self, value: str) -> None:
self._topLevel = value
@property
def Project(self) -> Nullable['Project']:
"""Property setting or returning the project this design is used in."""
return self._project
@Project.setter
def Project(self, value: 'Project') -> None:
self._project = value
@property
def Directory(self) -> pathlib_Path:
"""Property setting or returning the directory this design is located in."""
return self._directory
@Directory.setter
def Directory(self, value: pathlib_Path) -> None:
self._directory = value
@property
def ResolvedPath(self) -> pathlib_Path:
"""Read-only property returning the resolved path of this fileset."""
if self._directory.is_absolute():
return self._directory.resolve()
elif self._project is not None:
path = (self._project.ResolvedPath / self._directory).resolve()
if path.is_absolute():
return path
else:
# WORKAROUND: https://stackoverflow.com/questions/67452690/pathlib-path-relative-to-vs-os-path-relpath
return pathlib_Path(path_relpath(path, pathlib_Path.cwd()))
else:
# TODO: message and exception type
raise Exception("")
@property
def DefaultFileSet(self) -> FileSet:
"""Property setting or returning the default fileset of this design."""
return self._defaultFileSet
@DefaultFileSet.setter
def DefaultFileSet(self, value: Union[str, FileSet]) -> None:
if isinstance(value, str):
if value not in self._fileSets.keys():
raise Exception(f"Fileset '{value}' is not in this design.")
self._defaultFileSet = self._fileSets[value]
elif isinstance(value, FileSet):
if value not in self.FileSets:
raise Exception(f"Fileset '{value}' is not associated to this design.")
self._defaultFileSet = value
else:
raise ValueError("Unsupported parameter type for 'value'.")
# TODO: return generator with another method
@property
def FileSets(self) -> Dict[str, FileSet]:
"""Read-only property returning the dictionary of filesets."""
return self._fileSets
def Files(self, fileType: FileType = FileTypes.Any, fileSet: Union[str, FileSet] = None) -> Generator[File, None, None]:
"""
Method returning the files of this design.
:arg fileType: A filter for file types. Default: ``Any``.
:arg fileSet: Specifies if all files from all filesets (``fileSet=None``) are files from a single fileset are returned.
"""
if fileSet is None:
for fileSet in self._fileSets.values():
for file in fileSet.Files(fileType):
yield file
else:
if isinstance(fileSet, str):
try:
fileSet = self._fileSets[fileSet]
except KeyError as ex:
raise Exception(f"Fileset {fileSet.Name} not bound to design {self.Name}.") from ex
elif not isinstance(fileSet, FileSet):
raise TypeError("Parameter 'fileSet' is not of type 'str' or 'FileSet' nor value 'None'.")
for file in fileSet.Files(fileType):
yield file
def Validate(self) -> None:
"""Validate this design."""
if self._name is None or self._name == "":
raise Exception("Validation: Design has no name.")
if self._directory is None:
raise Exception(f"Validation: Design '{self._name}' has no directory.")
try:
path = self.ResolvedPath
except Exception as ex:
raise Exception(f"Validation: Design '{self._name}' could not compute resolved path.") from ex
if not path.exists():
raise Exception(f"Validation: Design '{self._name}'s directory '{path}' does not exist.")
if not path.is_dir():
raise Exception(f"Validation: Design '{self._name}'s directory '{path}' is not a directory.")
if len(self._fileSets) == 0:
raise Exception(f"Validation: Design '{self._name}' has no fileset.")
try:
if self._defaultFileSet is not self._fileSets[self._defaultFileSet.Name]:
raise Exception(f"Validation: Design '{self._name}'s default fileset is the same as listed in filesets.")
except KeyError as ex:
raise Exception(f"Validation: Design '{self._name}'s default fileset is not in list of filesets.") from ex
if self._project is None:
raise Exception(f"Validation: Design '{self._path}' has no project.")
for fileSet in self._fileSets.values():
fileSet.Validate()
@property
def VHDLLibraries(self) -> Dict[str, VHDLLibrary]:
return self._vhdlLibraries
@property
def VHDLVersion(self) -> VHDLVersion:
if self._vhdlVersion is not None:
return self._vhdlVersion
elif self._project is not None:
return self._project.VHDLVersion
else:
raise Exception("VHDLVersion was neither set locally nor globally.")
@VHDLVersion.setter
def VHDLVersion(self, value: VHDLVersion) -> None:
self._vhdlVersion = value
@property
def VerilogVersion(self) -> SystemVerilogVersion:
if self._verilogVersion is not None:
return self._verilogVersion
elif self._project is not None:
return self._project.VerilogVersion
else:
raise Exception("VerilogVersion was neither set locally nor globally.")
@VerilogVersion.setter
def VerilogVersion(self, value: SystemVerilogVersion) -> None:
self._verilogVersion = value
@property
def SVVersion(self) -> SystemVerilogVersion:
if self._svVersion is not None:
return self._svVersion
elif self._project is not None:
return self._project.SVVersion
else:
raise Exception("SVVersion was neither set locally nor globally.")
@SVVersion.setter
def SVVersion(self, value: SystemVerilogVersion) -> None:
self._svVersion = value
@property
def SRDLVersion(self) -> SystemRDLVersion:
if self._srdlVersion is not None:
return self._srdlVersion
elif self._project is not None:
return self._project.SRDLVersion
else:
raise Exception("SRDLVersion was neither set locally nor globally.")
@SRDLVersion.setter
def SRDLVersion(self, value: SystemRDLVersion) -> None:
self._srdlVersion = value
@property
def ExternalVHDLLibraries(self) -> List:
return self._externalVHDLLibraries
def AddFileSet(self, fileSet: FileSet) -> None:
if not isinstance(fileSet, FileSet):
raise ValueError("Parameter 'fileSet' is not of type ProjectModel.FileSet.")
elif fileSet in self._fileSets:
raise Exception("Design already contains this fileset.")
elif fileSet.Name in self._fileSets.keys():
raise Exception(f"Design already contains a fileset named '{fileSet.Name}'.")
self._fileSets[fileSet.Name] = fileSet
fileSet.Design = self
fileSet._parent = self
def AddFileSets(self, fileSets: Iterable[FileSet]) -> None:
for fileSet in fileSets:
self.AddFileSet(fileSet)
@property
def FileSetCount(self) -> int:
"""Returns number of file sets excl. sub-filesets."""
return len(self._fileSets)
@property
def TotalFileSetCount(self) -> int:
"""Returns number of file sets incl. sub-filesets."""
fileSetCount = len(self._fileSets)
for fileSet in self._fileSets.values():
fileSetCount += fileSet.TotalFileSetCount
return fileSetCount
def AddFile(self, file: File) -> None:
if file.FileSet is None:
self._defaultFileSet.AddFile(file)
else:
raise ValueError(f"File '{file.Path!s}' is already part of fileset '{file.FileSet.Name}' and can't be assigned via Design to a default fileset.")
def AddFiles(self, files: Iterable[File]) -> None:
for file in files:
self.AddFile(file)
def AddVHDLLibrary(self, vhdlLibrary: VHDLLibrary) -> None:
if vhdlLibrary.Name in self._vhdlLibraries:
if self._vhdlLibraries[vhdlLibrary.Name] is vhdlLibrary:
raise Exception(f"The VHDLLibrary '{vhdlLibrary.Name}' was already added to the design.")
else:
raise Exception(f"A VHDLLibrary with same name ('{vhdlLibrary.Name}') already exists for this design.")
def __len__(self) -> int:
"""
Returns number of attributes set on this design.
:returns: The number if attributes set on this design.
"""
return len(self._attributes)
def __getitem__(self, key: Type[Attribute]) -> Any:
"""Index access for returning attributes on this design.
:param key: The attribute type.
:returns: The attribute's value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
try:
return self._attributes[key]
except KeyError:
return key.resolve(self, key)
def __setitem__(self, key: Type[Attribute], value: typing_Any) -> None:
"""
Index access for adding or setting attributes on this design.
:param key: The attribute type.
:param value: The attributes value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
self._attributes[key] = value
def __delitem__(self, key: Type[Attribute]) -> None:
"""
Index access for deleting attributes on this design.
:param key: The attribute type.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
del self._attributes[key]
def __str__(self) -> str:
return self._name
@export
class Project(metaclass=ExtendedType, slots=True):
"""
A :term:`Project` represents a group of designs and the source files therein.
:arg name: The project's name.
:arg rootDirectory: Base-path to the project.
:arg vhdlVersion: Default VHDL version for files in this project, if not specified for the file itself.
:arg verilogVersion: Default Verilog version for files in this project, if not specified for the file itself.
:arg svVersion: Default SystemVerilog version for files in this project, if not specified for the file itself.
"""
_name: str
_rootDirectory: pathlib_Path
_designs: Dict[str, Design]
_defaultDesign: Design
_attributes: Dict[Type[Attribute], typing_Any]
_vhdlVersion: VHDLVersion
_verilogVersion: SystemVerilogVersion
_svVersion: SystemVerilogVersion
_srdlVersion: SystemRDLVersion
def __init__(
self,
name: str,
rootDirectory: pathlib_Path = pathlib_Path("."),
vhdlVersion: Nullable[VHDLVersion] = None,
verilogVersion: Nullable[SystemVerilogVersion] = None,
svVersion: Nullable[SystemVerilogVersion] = None
):
self._name = name
self._rootDirectory = rootDirectory
self._designs = {}
self._defaultDesign = Design("default", project=self)
self._attributes = {}
self._vhdlVersion = vhdlVersion
self._verilogVersion = verilogVersion
self._svVersion = svVersion
@property
def Name(self) -> str:
"""Property setting or returning the project's name."""
return self._name
@property
def RootDirectory(self) -> pathlib_Path:
"""Property setting or returning the root directory this project is located in."""
return self._rootDirectory
@RootDirectory.setter
def RootDirectory(self, value: pathlib_Path) -> None:
self._rootDirectory = value
@property
def ResolvedPath(self) -> pathlib_Path:
"""Read-only property returning the resolved path of this fileset."""
path = self._rootDirectory.resolve()
if self._rootDirectory.is_absolute():
return path
else:
# WORKAROUND: https://stackoverflow.com/questions/67452690/pathlib-path-relative-to-vs-os-path-relpath
return pathlib_Path(path_relpath(path, pathlib_Path.cwd()))
# TODO: return generator with another method
@property
def Designs(self) -> Dict[str, Design]:
return self._designs
@property
def DefaultDesign(self) -> Design:
return self._defaultDesign
def Validate(self) -> None:
"""Validate this project."""
if self._name is None or self._name == "":
raise Exception("Validation: Project has no name.")
if self._rootDirectory is None:
raise Exception(f"Validation: Project '{self._name}' has no root directory.")
try:
path = self.ResolvedPath
except Exception as ex:
raise Exception(f"Validation: Project '{self._name}' could not compute resolved path.") from ex
if not path.exists():
raise Exception(f"Validation: Project '{self._name}'s directory '{path}' does not exist.")
if not path.is_dir():
raise Exception(f"Validation: Project '{self._name}'s directory '{path}' is not a directory.")
if len(self._designs) == 0:
raise Exception(f"Validation: Project '{self._name}' has no design.")
try:
if self._defaultDesign is not self._designs[self._defaultDesign.Name]:
raise Exception(f"Validation: Project '{self._name}'s default design is the same as listed in designs.")
except KeyError as ex:
raise Exception(f"Validation: Project '{self._name}'s default design is not in list of designs.") from ex
for design in self._designs.values():
design.Validate()
@property
def DesignCount(self) -> int:
"""Returns number of designs."""
return len(self._designs)
@property
def VHDLVersion(self) -> VHDLVersion:
# TODO: check for None and return exception
return self._vhdlVersion
@VHDLVersion.setter
def VHDLVersion(self, value: VHDLVersion) -> None:
self._vhdlVersion = value
@property
def VerilogVersion(self) -> SystemVerilogVersion:
# TODO: check for None and return exception
return self._verilogVersion
@VerilogVersion.setter
def VerilogVersion(self, value: SystemVerilogVersion) -> None:
self._verilogVersion = value
@property
def SVVersion(self) -> SystemVerilogVersion:
# TODO: check for None and return exception
return self._svVersion
@SVVersion.setter
def SVVersion(self, value: SystemVerilogVersion) -> None:
self._svVersion = value
@property
def SRDLVersion(self) -> SystemRDLVersion:
# TODO: check for None and return exception
return self._srdlVersion
@SRDLVersion.setter
def SRDLVersion(self, value: SystemRDLVersion) -> None:
self._srdlVersion = value
def __len__(self) -> int:
"""
Returns number of attributes set on this project.
:returns: The number if attributes set on this project.
"""
return len(self._attributes)
def __getitem__(self, key: Type[Attribute]) -> Any:
"""Index access for returning attributes on this project.
:param key: The attribute type.
:returns: The attribute's value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
try:
return self._attributes[key]
except KeyError:
return key.resolve(self, key)
def __setitem__(self, key: Type[Attribute], value: typing_Any) -> None:
"""
Index access for adding or setting attributes on this project.
:param key: The attribute type.
:param value: The attributes value.
:raises TypeError: When parameter 'key' is not a subclass of Attribute.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
self._attributes[key] = value
def __delitem__(self, key: Type[Attribute]) -> None:
"""
Index access for deleting attributes on this project.
:param key: The attribute type.
"""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
del self._attributes[key]
def __str__(self) -> str:
return self._name
|