-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path__init__.py
1499 lines (1210 loc) · 48.2 KB
/
__init__.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
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
# ==================================================================================================================== #
# _____ ____ _ _ ____ _ _ __ __ _ _ #
# _ __ _ _| ____| _ \ / \ / \ | _ \ _ __ ___ (_) ___ ___| |_| \/ | ___ __| | ___| | #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) | '__/ _ \| |/ _ \/ __| __| |\/| |/ _ \ / _` |/ _ \ | #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| __/| | | (_) | | __/ (__| |_| | | | (_) | (_| | __/ | #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| |_| \___// |\___|\___|\__|_| |_|\___/ \__,_|\___|_| #
# |_| |___/ |__/ #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2017-2022 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__ = "[email protected]"
__copyright__ = "2014-2022, Patrick Lehmann, Unai Martinez-Corral"
__license__ = "Apache License, Version 2.0"
__version__ = "0.4.3"
__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 typing import Dict, Union, Optional as Nullable, List, Iterable, Generator, Tuple, Any as typing_Any, Type
from pyTooling.Decorators import export
from pyTooling.MetaClasses import ExtendedType
from pyTooling.Graph import Graph, Vertex
from pySVModel import VerilogVersion, SystemVerilogVersion
from pyVHDLModel import VHDLVersion
@export
class Attribute:
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: 'Project' = None,
design: 'Design' = None,
fileSet: '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):
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):
"""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 __getitem__(self, key: Type[Attribute]):
"""Index access for returning attributes on this file."""
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):
"""Index access for setting attributes on this file."""
if not issubclass(key, Attribute):
raise TypeError("Parameter 'key' is not an 'Attribute'.")
self._attributes[key] = value
FileTypes = File
@export
class HumanReadableContent(metaclass=ExtendedType, mixin=True):
"""A file type representing human-readable contents."""
@export
class XMLContent(HumanReadableContent):
"""A file type representing XML contents."""
@export
class YAMLContent(HumanReadableContent):
"""A file type representing YAML contents."""
@export
class JSONContent(HumanReadableContent):
"""A file type representing JSON contents."""
@export
class INIContent(HumanReadableContent):
"""A file type representing INI contents."""
@export
class TOMLContent(HumanReadableContent):
"""A file type representing TOML contents."""
@export
class TCLContent(HumanReadableContent):
"""A file type representing content in TCL code."""
@export
class SDCContent(TCLContent):
"""A file type representing contents as Synopsys Design Constraints (SDC)."""
@export
class PythonContent(HumanReadableContent):
"""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 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: 'VHDLLibrary'
_vhdlVersion: VHDLVersion
def __init__(self, path: pathlib_Path, vhdlLibrary: Union[str, 'VHDLLibrary'] = None, vhdlVersion: VHDLVersion = None, project: 'Project' = None, design: 'Design' = None, fileSet: '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:
raise TypeError(f"Parameter 'vhdlLibrary' is neither a 'str' nor 'VHDLibrary'.")
self._vhdlVersion = vhdlVersion
def Validate(self):
"""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}>"
@export
class VerilogSourceFile(HDLSourceFile, HumanReadableContent):
"""A Verilog source file (of any language version)."""
_verilogVersion: VerilogVersion
def __init__(self, path: pathlib_Path, verilogVersion: VerilogVersion = None, project: 'Project' = None, design: 'Design' = None, fileSet: 'FileSet' = None):
super().__init__(path, project, design, fileSet)
self._verilogVersion = verilogVersion
@property
def VerilogVersion(self) -> VerilogVersion:
"""Property setting or returning the Verilog version this Verilog source file is used in."""
if self._verilogVersion is not None:
return self._verilogVersion
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: VerilogVersion) -> None:
self._verilogVersion = value
@export
class SystemVerilogSourceFile(HDLSourceFile, HumanReadableContent):
"""A SystemVerilog source file (of any language version)."""
_svVersion: SystemVerilogVersion
def __init__(self, path: pathlib_Path, svVersion: SystemVerilogVersion = None, project: 'Project' = None, design: 'Design' = None, fileSet: 'FileSet' = None):
super().__init__(path, project, design, fileSet)
self._svVersion = svVersion
@property
def SVVersion(self) -> SystemVerilogVersion:
"""Property setting or returning the SystemVerilog version this SystemVerilog source file is used in."""
if self._svVersion is not None:
return self._svVersion
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._svVersion = 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.
"""
_name: str
_topLevel: Nullable[str]
_project: Nullable['Project']
_design: Nullable['Design']
_directory: pathlib_Path
_parent: Nullable['FileSet']
_fileSets: Dict[str, 'FileSet']
_files: List[File]
_attributes: Dict[Type[Attribute], typing_Any]
_vhdlLibraries: Dict[str, 'VHDLLibrary']
_vhdlLibrary: 'VHDLLibrary'
_vhdlVersion: VHDLVersion
_verilogVersion: VerilogVersion
_svVersion: SystemVerilogVersion
def __init__(
self,
name: str,
topLevel: str = None,
directory: pathlib_Path = pathlib_Path("."),
project: 'Project' = None,
design: 'Design' = None,
parent: Nullable['FileSet'] = None,
vhdlLibrary: Union[str, 'VHDLLibrary'] = None,
vhdlVersion: VHDLVersion = None,
verilogVersion: VerilogVersion = None,
svVersion: SystemVerilogVersion = 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 = []
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
@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 AddFile(self, file: File) -> None:
"""
Method to add a single file to this fileset.
:arg file: A file to add to this fileset.
"""
self._files.append(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 to the fileset.
"""
for file in files:
self._files.append(file)
file._fileSet = self
def Validate(self):
"""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._path}' has no design.")
if self._project is None:
raise Exception(f"Validation: FileSet '{self._path}' has no project.")
for fileSet in self._fileSets.values():
fileSet.Validate()
for file in self._files:
file.Validate()
def __len__(self):
"""Returns number of files incl. the files in the sub-filesets."""
fileCount = self._files.__len__()
for fileSet in self._fileSets:
fileCount += fileSet.__len__()
return fileCount
def __getitem__(self, key: Type[Attribute]):
"""Index access for returning attributes on this file."""
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):
"""Index access for setting attributes on this file."""
self._attributes[key] = value
def GetOrCreateVHDLLibrary(self, name):
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) -> VerilogVersion:
"""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: VerilogVersion) -> 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
def __str__(self):
"""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: 'Project' = None,
design: 'Design' = None,
vhdlVersion: 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'):
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