pyEDAA.OSVVM.Project.Procedures

pyEDAA/OSVVM/Project/Procedures.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
# ==================================================================================================================== #
#              _____ ____    _        _      ___  ______     ____     ____  __                                         #
#  _ __  _   _| ____|  _ \  / \      / \    / _ \/ ___\ \   / /\ \   / /  \/  |                                        #
# | '_ \| | | |  _| | | | |/ _ \    / _ \  | | | \___ \\ \ / /  \ \ / /| |\/| |                                        #
# | |_) | |_| | |___| |_| / ___ \  / ___ \ | |_| |___) |\ V /    \ V / | |  | |                                        #
# | .__/ \__, |_____|____/_/   \_\/_/   \_(_)___/|____/  \_/      \_/  |_|  |_|                                        #
# |_|    |___/                                                                                                         #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2025-2025 Patrick Lehmann - Boetzingen, Germany                                                            #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
This module implements OSVVM's TCL procedures (used in OSVVM's ``*.pro`` files) as Python functions.

These functions are then registered at the :class:`TCL processor <pyEDAA.OSVVM.TCL.OsvvmProFileProcessor>`, so procedure
calls within TCL code get "redirected" to these Python functions. Each function has access to a global variable
:data:`~pyEDAA.OSVVM.Environment.osvvmContext` to preserve its state or modify the context.
"""
from pathlib import Path
from typing  import Optional as Nullable

from pyTooling.Decorators  import export
from pyVHDLModel           import VHDLVersion

from pyEDAA.OSVVM          import OSVVMException
from pyEDAA.OSVVM.Project  import osvvmContext, VHDLSourceFile, GenericValue
from pyEDAA.OSVVM.Project  import BuildName as OSVVM_BuildName, NoNullRangeWarning as OSVVM_NoNullRangeWarning


@export
def BuildName(name: str) -> int:
	try:
		buildName = OSVVM_BuildName(name)
		optionID = osvvmContext.AddOption(buildName)
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex

	return optionID

@export
def build(file: str, *options: int) -> None:
	"""
	This function implements the behavior of OSVVM's ``build`` procedure.

	The current directory of the currently active context is preserved	while the referenced ``*.pro`` file is processed.
	After processing that file, the context's current directory is restored.

	The referenced file gets appended to a list of included files maintained by the context.

	:underline:`pro-file discovery algorithm:`

	1. If the path explicitly references a ``*.pro`` file, this file is used.
	2. If the path references a directory, it checks implicitly for a ``build.pro`` file, otherwise
	3. it checks implicitly for a ``<path>.pro`` file, named like the directories name.

	:param file:            Explicit path to a ``*.pro`` file or a directory containing an implicitly searched ``*.pro`` file.
	:param options:         Optional list of option IDs.
	:raises TypeError:      If parameter proFileOrBuildDirectory is not a Path.
	:raises OSVVMException: If parameter proFileOrBuildDirectory is an absolute path.
	:raises OSVVMException: If parameter proFileOrBuildDirectory is not a *.pro file or build directory.
	:raises OSVVMException: If a TclError was caught while processing a *.pro file.

	.. seealso::

	   * :func:`BuildName`
	   * :func:`include`
	   * :func:`ChangeWorkingDirectory`
	"""
	try:
		file = Path(file)
		buildName = None

		# Preserve current directory
		currentDirectory = osvvmContext._currentDirectory

		for optionID in options:
			try:
				option = osvvmContext._options[int(optionID)]
			except KeyError as e:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} not found in option dictionary.")
				ex.__cause__ = e
				osvvmContext.LastException = ex
				raise ex

			if isinstance(option, OSVVM_BuildName):
				buildName = option.Name
			else:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} is not a BuildName.")
				ex.__cause__ = TypeError()
				osvvmContext.LastException = ex
				raise ex

		# If no build name was specified, derive a name from *.pro file.
		if buildName is None:
			buildName = file.stem

		osvvmContext.BeginBuild(buildName)
		includeFile = osvvmContext.IncludeFile(file)
		osvvmContext.EvaluateFile(includeFile)
		osvvmContext.EndBuild()

		# Restore current directory after recursively evaluating *.pro files.
		osvvmContext._currentDirectory = currentDirectory

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def include(file: str) -> None:
	"""
	This function implements the behavior of OSVVM's ``include`` procedure.

	The current directory of the currently active context is preserved	while the referenced ``*.pro`` file is processed.
	After processing that file, the context's current directory is restored.

	The referenced file gets appended to a list of included files maintained by the context.

	:underline:`pro-file discovery algorithm:`

	1. If the path explicitly references a ``*.pro`` file, this file is used.
	2. If the path references a directory, it checks implicitly for a ``build.pro`` file, otherwise
	3. it checks implicitly for a ``<path>.pro`` file, named like the directories name.

	:param file:            Explicit path to a ``*.pro`` file or a directory containing an implicitly searched ``*.pro`` file.
	:raises TypeError:      If parameter proFileOrBuildDirectory is not a Path.
	:raises OSVVMException: If parameter proFileOrBuildDirectory is an absolute path.
	:raises OSVVMException: If parameter proFileOrBuildDirectory is not a *.pro file or build directory.
	:raises OSVVMException: If a TclError was caught while processing a *.pro file.

	.. seealso::

	   * :func:`build`
	   * :func:`ChangeWorkingDirectory`
	"""
	try:
		# Preserve current directory
		currentDirectory = osvvmContext._currentDirectory

		includeFile = osvvmContext.IncludeFile(Path(file))
		osvvmContext.EvaluateFile(includeFile)

		# Restore current directory after recursively evaluating *.pro files.
		osvvmContext._currentDirectory = currentDirectory

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def library(libraryName: str, libraryPath: Nullable[str] = None) -> None:
	"""
	This function implements the behavior of OSVVM's ``library`` procedure.

	It sets the currently active VHDL library to the specified VHDL library. If no VHDL library with that name exist, a
	new VHDL library is created and set as active VHDL library.

	.. hint:: All following ``analyze`` calls will use this library as the VHDL file's VHDL library.

	.. caution:: Parameter `libraryPath` is not yet implemented.

	:param libraryName: Name of the VHDL library.
	:param libraryPath: Optional: Path where to create that VHDL library.

	.. seealso::

	   * :func:`LinkLibrary`
	   * :func:`LinkLibraryDirectory`
	"""
	try:
		if libraryPath is not None:
			ex = NotImplementedError(f"Optional parameter 'libraryPath' not yet supported.")
			osvvmContext.LastException = ex
			raise ex

		osvvmContext.SetLibrary(libraryName)

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def NoNullRangeWarning() -> int:
	try:
		option = OSVVM_NoNullRangeWarning()
		optionID = osvvmContext.AddOption(option)
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex

	return optionID


@export
def analyze(file: str, *options: int) -> None:
	try:
		file = Path(file)
		fullPath = (osvvmContext._currentDirectory / file).resolve()

		noNullRangeWarning = None
		for optionID in options:
			try:
				option = osvvmContext._options[int(optionID)]
			except KeyError as e:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} not found in option dictionary.")
				ex.__cause__ = e
				osvvmContext.LastException = ex
				raise ex

			if isinstance(option, OSVVM_NoNullRangeWarning):
				noNullRangeWarning = True
			else:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} is not a NoNullRangeWarning.")
				ex.__cause__ = TypeError()
				osvvmContext.LastException = ex
				raise ex

		if not fullPath.exists():  # pragma: no cover
			ex = OSVVMException(f"Path '{fullPath}' can't be analyzed.")
			ex.__cause__ = FileNotFoundError(fullPath)
			osvvmContext.LastException = ex
			raise ex

		if fullPath.suffix in (".vhd", ".vhdl"):
			vhdlFile = VHDLSourceFile(
				fullPath.relative_to(osvvmContext._workingDirectory, walk_up=True),
				noNullRangeWarning=noNullRangeWarning
			)
			osvvmContext.AddVHDLFile(vhdlFile)
		else:  # pragma: no cover
			ex = OSVVMException(f"Path '{fullPath}' is no VHDL file.")
			osvvmContext.LastException = ex
			raise ex

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def simulate(toplevelName: str, *options: int) -> None:
	try:
		testcase = osvvmContext.SetTestcaseToplevel(toplevelName)
		for optionID in options:
			try:
				option = osvvmContext._options[int(optionID)]
			except KeyError as e:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} not found in option dictionary.")
				ex.__cause__ = e
				osvvmContext.LastException = ex
				raise ex

			if isinstance(option, GenericValue):
				testcase.AddGeneric(option)
			else:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} is not a GenericValue.")
				ex.__cause__ = TypeError()
				osvvmContext.LastException = ex
				raise ex

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex
	# osvvmContext._testcase = None


@export
def generic(name: str, value: str) -> int:
	try:
		genericValue = GenericValue(name, value)
		optionID = osvvmContext.AddOption(genericValue)
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex

	return optionID


@export
def TestSuite(name: str) -> None:
	try:
		osvvmContext.SetTestsuite(name)
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def TestName(name: str) -> None:
	try:
		osvvmContext.AddTestcase(name)
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def RunTest(file: str, *options: int) -> None:
	try:
		file = Path(file)
		testName = file.stem

		# Analyze file
		fullPath = (osvvmContext._currentDirectory / file).resolve()

		if not fullPath.exists():  # pragma: no cover
			ex = OSVVMException(f"Path '{fullPath}' can't be analyzed.")
			ex.__cause__ = FileNotFoundError(fullPath)
			osvvmContext.LastException = ex
			raise ex

		if fullPath.suffix in (".vhd", ".vhdl"):
			vhdlFile = VHDLSourceFile(fullPath.relative_to(osvvmContext._workingDirectory, walk_up=True))
			osvvmContext.AddVHDLFile(vhdlFile)
		else:  # pragma: no cover
			ex = OSVVMException(f"Path '{fullPath}' is no VHDL file.")
			osvvmContext.LastException = ex
			raise ex

		# Add testcase
		testcase = osvvmContext.AddTestcase(testName)
		testcase.SetToplevel(testName)
		for optionID in options:
			try:
				option = osvvmContext._options[int(optionID)]
			except KeyError as e:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} not found in option dictionary.")
				ex.__cause__ = e
				osvvmContext.LastException = ex
				raise ex

			if isinstance(option, GenericValue):
				testcase.AddGeneric(option)
			else:  # pragma: no cover
				ex = OSVVMException(f"Option {optionID} is not a GenericValue.")
				ex.__cause__ = TypeError()
				osvvmContext.LastException = ex
				raise ex

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex
	# osvvmContext._testcase = None


@export
def LinkLibrary(libraryName: str, libraryPath: Nullable[str] = None):
	print(f"[LinkLibrary] {libraryPath}")


@export
def LinkLibraryDirectory(libraryDirectory: str):
	print(f"[LinkLibraryDirectory] {libraryDirectory}")


@export
def SetVHDLVersion(value: str) -> None:
	try:
		try:
			value = int(value)
		except ValueError as e:  # pragma: no cover
			ex = OSVVMException(f"Unsupported VHDL version '{value}'.")
			ex.__cause__ = e
			osvvmContext.LastException = ex
			raise ex

		match value:
			case 1987:
				osvvmContext.VHDLVersion = VHDLVersion.VHDL87
			case 1993:
				osvvmContext.VHDLVersion = VHDLVersion.VHDL93
			case 2002:
				osvvmContext.VHDLVersion = VHDLVersion.VHDL2002
			case 2008:
				osvvmContext.VHDLVersion = VHDLVersion.VHDL2008
			case 2019:
				osvvmContext.VHDLVersion = VHDLVersion.VHDL2019
			case _:  # pragma: no cover
				ex = OSVVMException(f"Unsupported VHDL version '{value}'.")
				osvvmContext.LastException = ex
				raise ex

	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex

@export
def GetVHDLVersion() -> int:
	try:
		if osvvmContext.VHDLVersion is VHDLVersion.VHDL87:
			return 1987
		elif osvvmContext.VHDLVersion is VHDLVersion.VHDL93:
			return 1993
		elif osvvmContext.VHDLVersion is VHDLVersion.VHDL2002:
			return 2002
		elif osvvmContext.VHDLVersion is VHDLVersion.VHDL2008:
			return 2008
		elif osvvmContext.VHDLVersion is VHDLVersion.VHDL2019:
			return 2019
		else:  # pragma: no cover
			ex = OSVVMException(f"Unsupported VHDL version '{osvvmContext.VHDLVersion}'.")
			osvvmContext.LastException = ex
			raise ex
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def SetCoverageAnalyzeEnable(value: bool) -> None:
	print(f"[SetCoverageAnalyzeEnable] {value}:{value.__class__.__name__}")


@export
def SetCoverageSimulateEnable(value: bool) -> None:
	print(f"[SetCoverageSimulateEnable] {value}")


@export
def FileExists(file: str) -> bool:
	try:
		return (osvvmContext._currentDirectory / file).is_file()
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex

@export
def DirectoryExists(directory: str) -> bool:
	try:
		return (osvvmContext._currentDirectory / directory).is_dir()
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex

@export
def ChangeWorkingDirectory(directory: str) -> None:
	try:
		osvvmContext._currentDirectory = (newDirectory := osvvmContext._currentDirectory / directory)
		if not newDirectory.is_dir():  # pragma: no cover
			ex = OSVVMException(f"Directory '{newDirectory}' doesn't exist.")
			ex.__cause__ = NotADirectoryError(newDirectory)
			osvvmContext.LastException = ex
			raise ex
	except Exception as ex:  # pragma: no cover
		osvvmContext.LastException = ex
		raise ex


@export
def FindOsvvmSettingsDirectory(*args):
	pass


@export
def CreateOsvvmScriptSettingsPkg(*args):
	pass


@export
def noop(*args):
	pass