pyEDAA.Reports.CodeCoverage.UCIS.FSMs

pyEDAA/Reports/CodeCoverage/UCIS/FSMs.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
# ==================================================================================================================== #
#              _____ ____    _        _      ____                       _                                              #
#  _ __  _   _| ____|  _ \  / \      / \    |  _ \ ___ _ __   ___  _ __| |_ ___                                        #
# | '_ \| | | |  _| | | | |/ _ \    / _ \   | |_) / _ \ '_ \ / _ \| '__| __/ __|                                       #
# | |_) | |_| | |___| |_| / ___ \  / ___ \ _|  _ <  __/ |_) | (_) | |  | |_\__ \                                       #
# | .__/ \__, |_____|____/_/   \_\/_/   \_(_)_| \_\___| .__/ \___/|_|   \__|___/                                       #
# |_|    |___/                                        |_|                                                              #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2026-2026 Electronic Design Automation Abstraction (EDA²)                                                  #
#                                                                                                                      #
# 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                                                                                  #
# ==================================================================================================================== #
#
"""
The FSM coverage of the UCIS XML interchange format: an instance's ``<fsmCoverage>``, its finite state machines, their
states and transitions.
"""
from __future__                                   import annotations

from typing                                       import TYPE_CHECKING, Iterable, Optional as Nullable, Self

from lxml.etree                                   import _Element
from pyTooling.Common                             import getFullyQualifiedName
from pyTooling.Decorators                         import export, readonly

from pyEDAA.Reports.CodeCoverage.UCIS.Bins        import Bin
from pyEDAA.Reports.CodeCoverage.UCIS.Elements    import Base, MetricCoverage, ObjectAttributesMixin, UserAttribute

if TYPE_CHECKING:
	from pyEDAA.Reports.CodeCoverage.UCIS.Instances import InstanceCoverage


# A class with a property named like a class - ``Bin`` - can't name that class in the annotation of a field: the class
# body's namespace, where annotations are evaluated, binds the name to the property.
_Bin = Bin


@export
class FSMCoverage(MetricCoverage):
	"""
	An ``<fsmCoverage>`` of an instance: its finite state machines.
	"""

	_fsms: list[FSM]  #: The finite state machines.

	def __init__(
		self,
		metricMode: Nullable[str] = None,
		weight: int = 1,
		userAttributes: Nullable[Iterable[UserAttribute]] = None,
		*,
		parent: Nullable[InstanceCoverage] = None
	) -> None:
		"""
		Initialize the FSM coverage, and append it to the FSM coverages of its instance.

		Its finite state machines are added by creating them with this coverage as their parent.

		:param metricMode:     Optional, the mode in which the coverage was measured. Default: ``None``.
		:param weight:         Optional, weight of the mode in computing the coverage. Default: ``1``.
		:param userAttributes: Optional, the user-defined attributes. Default: ``None``.
		:param parent:         Optional, the instance the coverage belongs to. Default: ``None``.
		:raises TypeError:     If parameter ``userAttributes`` isn't iterable.
		:raises TypeError:     If parameter ``userAttributes`` contains an element not of type
		                       :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Elements.UserAttribute`.
		:raises TypeError:     If parameter ``metricMode`` isn't of type :class:`str`.
		:raises ValueError:    If parameter ``weight`` is ``None``.
		:raises TypeError:     If parameter ``weight`` isn't of type :class:`int`.
		:raises ValueError:    If parameter ``weight`` is negative.
		:raises TypeError:     If parameter ``parent`` isn't of type
		                       :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Instances.InstanceCoverage`.
		"""
		super().__init__(metricMode, weight, userAttributes, parent=parent)

		self._fsms = []

		if parent is not None:
			parent._fsmCoverages.append(self)

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[InstanceCoverage] = None) -> Self:
		"""
		Parse an FSM coverage and its finite state machines from its ``<fsmCoverage>`` element.

		:param element:            The ``<fsmCoverage>`` element.
		:param parent:             Optional, the instance the coverage belongs to. Default: ``None``.
		:returns:                  The FSM coverage.
		:raises CodeCoverageError: If a user-defined attribute's value isn't of the type the attribute states.
		"""
		fsmCoverage = cls(
			element.attrib.get("metricMode"),
			int(element.attrib.get("weight", "1")),
			cls._ParseUserAttributes(element),
			parent=parent
		)

		for fsmElement in element.iterfind("{*}fsm"):
			FSM.Parse(fsmElement, parent=fsmCoverage)

		return fsmCoverage

	@readonly
	def FSMs(self) -> list[FSM]:
		"""
		Read-only property to access the finite state machines (:attr:`_fsms`).

		:returns: The finite state machines, in the order the report lists them.
		"""
		return self._fsms


@export
class FSM(Base, ObjectAttributesMixin):
	"""
	An ``<fsm>`` of an FSM coverage: a finite state machine, the signal holding its state, its states and transitions.
	"""

	_parent:      Nullable[FSMCoverage]  #: The FSM coverage the finite state machine belongs to.
	_name:        Nullable[str]          #: Name of the signal holding the state.
	_type:        Nullable[str]          #: Declared type of the signal holding the state.
	_width:       Nullable[int]          #: Bit width of the signal holding the state.
	_states:      list[FSMState]         #: The states.
	_transitions: list[FSMTransition]    #: The transitions.

	def __init__(
		self,
		name: Nullable[str] = None,
		objectType: Nullable[str] = None,
		width: Nullable[int] = None,
		alias: Nullable[str] = None,
		excluded: bool = False,
		excludedReason: Nullable[str] = None,
		weight: int = 1,
		userAttributes: Nullable[Iterable[UserAttribute]] = None,
		*,
		parent: Nullable[FSMCoverage] = None
	) -> None:
		"""
		Initialize the finite state machine, and append it to the finite state machines of its FSM coverage.

		Its states and transitions are added by creating them with this finite state machine as their parent.

		:param name:           Optional, name of the signal holding the state, e.g. ``ctrl``. Default: ``None``.
		:param objectType:     Optional, declared type of the signal holding the state, e.g. ``reg``. Default: ``None``.
		:param width:          Optional, bit width of the signal holding the state. Default: ``None``.
		:param alias:          Optional, an alias of the finite state machine's name. Default: ``None``.
		:param excluded:       Optional, whether the finite state machine is excluded from the coverage. Default:
		                       ``False``.
		:param excludedReason: Optional, why the finite state machine is excluded. Default: ``None``.
		:param weight:         Optional, weight of the finite state machine in computing the coverage. Default: ``1``.
		:param userAttributes: Optional, the user-defined attributes. Default: ``None``.
		:param parent:         Optional, the FSM coverage the finite state machine belongs to. Default: ``None``.
		:raises TypeError:     If parameter ``userAttributes`` isn't iterable.
		:raises TypeError:     If parameter ``userAttributes`` contains an element not of type
		                       :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Elements.UserAttribute`.
		:raises TypeError:     If parameter ``alias`` isn't of type :class:`str`.
		:raises ValueError:    If parameter ``excluded`` is ``None``.
		:raises TypeError:     If parameter ``excluded`` isn't of type :class:`bool`.
		:raises TypeError:     If parameter ``excludedReason`` isn't of type :class:`str`.
		:raises ValueError:    If parameter ``weight`` is ``None``.
		:raises TypeError:     If parameter ``weight`` isn't of type :class:`int`.
		:raises ValueError:    If parameter ``weight`` is negative.
		:raises TypeError:     If parameter ``name`` or ``objectType`` isn't of type :class:`str`.
		:raises TypeError:     If parameter ``width`` isn't of type :class:`int`.
		:raises ValueError:    If parameter ``width`` is less than 1.
		:raises TypeError:     If parameter ``parent`` isn't of type :class:`FSMCoverage`.
		"""
		super().__init__(userAttributes)
		ObjectAttributesMixin.__init__(self, alias, excluded, excludedReason, weight)

		for parameterName, value in (
			("name",       name),
			("objectType", objectType)
		):
			if value is not None and not isinstance(value, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
				raise ex

		if width is not None:
			if not isinstance(width, int) or isinstance(width, bool):
				ex = TypeError("Parameter 'width' is not of type 'int'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(width)}'.")
				raise ex
			elif width < 1:
				ex = ValueError("Parameter 'width' is less than 1.")
				ex.add_note(f"Got value '{width}'.")
				raise ex

		if parent is not None and not isinstance(parent, FSMCoverage):
			ex = TypeError("Parameter 'parent' is not of type 'FSMCoverage'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex

		self._parent =      parent
		self._name =        name
		self._type =        objectType
		self._width =       width
		self._states =      []
		self._transitions = []

		if parent is not None:
			parent._fsms.append(self)

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[FSMCoverage] = None) -> Self:
		"""
		Parse a finite state machine, its states and transitions from its ``<fsm>`` element.

		:param element:            The ``<fsm>`` element.
		:param parent:             Optional, the FSM coverage the finite state machine belongs to. Default: ``None``.
		:returns:                  The finite state machine.
		:raises CodeCoverageError: If a user-defined attribute's value isn't of the type the attribute states.
		"""
		width = element.attrib.get("width")
		fsm = cls(
			element.attrib.get("name"),
			element.attrib.get("type"),
			None if width is None else int(width),
			element.attrib.get("alias"),
			cls._ParseBoolean(element.attrib.get("excluded", "false")),
			element.attrib.get("excludedReason"),
			int(element.attrib.get("weight", "1")),
			cls._ParseUserAttributes(element),
			parent=parent
		)

		for stateElement in element.iterfind("{*}state"):
			FSMState.Parse(stateElement, parent=fsm)

		for transitionElement in element.iterfind("{*}stateTransition"):
			FSMTransition.Parse(transitionElement, parent=fsm)

		return fsm

	@readonly
	def Parent(self) -> Nullable[FSMCoverage]:
		"""
		Read-only property to access the FSM coverage the finite state machine belongs to (:attr:`_parent`).

		:returns: The FSM coverage; ``None``, if the finite state machine belongs to none.
		"""
		return self._parent

	@readonly
	def Name(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the signal holding the state (:attr:`_name`).

		:returns: The name, e.g. ``ctrl``; ``None``, if the report states none.
		"""
		return self._name

	@readonly
	def Type(self) -> Nullable[str]:
		"""
		Read-only property to access the declared type of the signal holding the state (:attr:`_type`).

		:returns: The type, e.g. ``reg``; ``None``, if the report states none.
		"""
		return self._type

	@readonly
	def Width(self) -> Nullable[int]:
		"""
		Read-only property to access the bit width of the signal holding the state (:attr:`_width`).

		:returns: The width; ``None``, if the report states none.
		"""
		return self._width

	@readonly
	def States(self) -> list[FSMState]:
		"""
		Read-only property to access the states (:attr:`_states`).

		:returns: The states, in the order the report lists them.
		"""
		return self._states

	@readonly
	def Transitions(self) -> list[FSMTransition]:
		"""
		Read-only property to access the transitions (:attr:`_transitions`).

		:returns: The transitions, in the order the report lists them.
		"""
		return self._transitions


@export
class FSMState(Base):
	"""
	A ``<state>`` of a finite state machine: its name, value and bin - how often the machine was in it.
	"""

	_parent: Nullable[FSM]  #: The finite state machine the state belongs to.
	_name:   Nullable[str]  #: Name of the state.
	_value:  Nullable[str]  #: Value representing the state.
	_bin:    _Bin           #: How often the machine was in the state.

	def __init__(
		self,
		coverBin: Bin,
		name: Nullable[str] = None,
		value: Nullable[str] = None,
		userAttributes: Nullable[Iterable[UserAttribute]] = None,
		*,
		parent: Nullable[FSM] = None
	) -> None:
		"""
		Initialize the state, become its bin's parent, and append it to the states of its finite state machine.

		:param coverBin:       How often the machine was in the state.
		:param name:           Optional, name of the state, e.g. ``IDLE``. Default: ``None``.
		:param value:          Optional, value representing the state, e.g. ``4``. Default: ``None``.
		:param userAttributes: Optional, the user-defined attributes. Default: ``None``.
		:param parent:         Optional, the finite state machine the state belongs to. Default: ``None``.
		:raises TypeError:     If parameter ``userAttributes`` isn't iterable.
		:raises TypeError:     If parameter ``userAttributes`` contains an element not of type
		                       :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Elements.UserAttribute`.
		:raises ValueError:    If parameter ``coverBin`` is ``None``.
		:raises TypeError:     If parameter ``coverBin`` isn't of type :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Bins.Bin`.
		:raises TypeError:     If parameter ``name`` or ``value`` isn't of type :class:`str`.
		:raises TypeError:     If parameter ``parent`` isn't of type :class:`FSM`.
		"""
		super().__init__(userAttributes)

		if coverBin is None:
			raise ValueError("Parameter 'coverBin' is None.")
		elif not isinstance(coverBin, Bin):
			ex = TypeError("Parameter 'coverBin' is not of type 'Bin'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(coverBin)}'.")
			raise ex

		for parameterName, parameterValue in (
			("name",  name),
			("value", value)
		):
			if parameterValue is not None and not isinstance(parameterValue, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(parameterValue)}'.")
				raise ex

		if parent is not None and not isinstance(parent, FSM):
			ex = TypeError("Parameter 'parent' is not of type 'FSM'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex

		self._parent =     parent
		self._name =       name
		self._value =      value
		self._bin =        coverBin
		coverBin._parent = self

		if parent is not None:
			parent._states.append(self)

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[FSM] = None) -> Self:
		"""
		Parse a state and its bin from its ``<state>`` element.

		:param element:            The ``<state>`` element.
		:param parent:             Optional, the finite state machine the state belongs to. Default: ``None``.
		:returns:                  The state.
		:raises CodeCoverageError: If a user-defined attribute's value isn't of the type the attribute states.
		"""
		return cls(
			Bin.Parse(element.find("{*}stateBin")),
			element.attrib.get("stateName"),
			element.attrib.get("stateValue"),
			cls._ParseUserAttributes(element),
			parent=parent
		)

	@readonly
	def Parent(self) -> Nullable[FSM]:
		"""
		Read-only property to access the finite state machine the state belongs to (:attr:`_parent`).

		:returns: The finite state machine; ``None``, if the state belongs to none.
		"""
		return self._parent

	@readonly
	def Name(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the state (:attr:`_name`).

		:returns: The name, e.g. ``IDLE``; ``None``, if the report states none.
		"""
		return self._name

	@readonly
	def Value(self) -> Nullable[str]:
		"""
		Read-only property to access the value representing the state (:attr:`_value`).

		:returns: The value, as stated; ``None``, if the report states none.
		"""
		return self._value

	@readonly
	def Bin(self) -> Bin:
		"""
		Read-only property to access the state's bin (:attr:`_bin`).

		:returns: The bin, stating how often the machine was in the state.
		"""
		return self._bin


@export
class FSMTransition(Base):
	"""
	A ``<stateTransition>`` of a finite state machine: the states it passes, and its bin - how often it happened.
	"""

	_parent: Nullable[FSM]  #: The finite state machine the transition belongs to.
	_states: list[str]      #: The states the transition passes, from the first one.
	_bin:    _Bin           #: How often the transition happened.

	def __init__(
		self,
		states: Iterable[str],
		coverBin: Bin,
		userAttributes: Nullable[Iterable[UserAttribute]] = None,
		*,
		parent: Nullable[FSM] = None
	) -> None:
		"""
		Initialize the transition, become its bin's parent, and append it to the transitions of its finite state machine.

		:param states:         The states the transition passes, from the first one, e.g. ``["IDLE", "ACTIVE"]``.
		:param coverBin:       How often the transition happened.
		:param userAttributes: Optional, the user-defined attributes. Default: ``None``.
		:param parent:         Optional, the finite state machine the transition belongs to. Default: ``None``.
		:raises TypeError:     If parameter ``userAttributes`` isn't iterable.
		:raises TypeError:     If parameter ``userAttributes`` contains an element not of type
		                       :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Elements.UserAttribute`.
		:raises ValueError:    If parameter ``coverBin`` is ``None``.
		:raises TypeError:     If parameter ``coverBin`` isn't of type :class:`~pyEDAA.Reports.CodeCoverage.UCIS.Bins.Bin`.
		:raises TypeError:     If parameter ``parent`` isn't of type :class:`FSM`.
		:raises ValueError:    If parameter ``states`` is ``None``.
		:raises TypeError:     If parameter ``states`` isn't iterable.
		:raises TypeError:     If parameter ``states`` contains an element not of type :class:`str`.
		:raises ValueError:    If parameter ``states`` has less than two states.
		"""
		super().__init__(userAttributes)

		if coverBin is None:
			raise ValueError("Parameter 'coverBin' is None.")
		elif not isinstance(coverBin, Bin):
			ex = TypeError("Parameter 'coverBin' is not of type 'Bin'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(coverBin)}'.")
			raise ex

		if parent is not None and not isinstance(parent, FSM):
			ex = TypeError("Parameter 'parent' is not of type 'FSM'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex

		self._parent =     parent
		self._states =     []
		self._bin =        coverBin
		coverBin._parent = self

		if states is None:
			raise ValueError("Parameter 'states' is None.")
		elif not isinstance(states, Iterable):
			ex = TypeError("Parameter 'states' is not iterable.")
			ex.add_note(f"Got type '{getFullyQualifiedName(states)}'.")
			raise ex

		for state in states:
			if not isinstance(state, str):
				ex = TypeError("Parameter 'states' contains an element not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(state)}'.")
				raise ex

			self._states.append(state)

		if len(self._states) < 2:
			ex = ValueError("Parameter 'states' has less than two states.")
			ex.add_note(f"Got {len(self._states)} state(s).")
			raise ex

		if parent is not None:
			parent._transitions.append(self)

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[FSM] = None) -> Self:
		"""
		Parse a transition and its bin from its ``<stateTransition>`` element.

		:param element:            The ``<stateTransition>`` element.
		:param parent:             Optional, the finite state machine the transition belongs to. Default: ``None``.
		:returns:                  The transition.
		:raises CodeCoverageError: If a user-defined attribute's value isn't of the type the attribute states.
		"""
		return cls(
			[stateElement.text or "" for stateElement in element.iterfind("{*}state")],
			Bin.Parse(element.find("{*}transitionBin")),
			cls._ParseUserAttributes(element),
			parent=parent
		)

	@readonly
	def Parent(self) -> Nullable[FSM]:
		"""
		Read-only property to access the finite state machine the transition belongs to (:attr:`_parent`).

		:returns: The finite state machine; ``None``, if the transition belongs to none.
		"""
		return self._parent

	@readonly
	def States(self) -> list[str]:
		"""
		Read-only property to access the states the transition passes (:attr:`_states`).

		:returns: The states, from the first one, as the report states them.
		"""
		return self._states

	@readonly
	def Bin(self) -> Bin:
		"""
		Read-only property to access the transition's bin (:attr:`_bin`).

		:returns: The bin, stating how often the transition happened.
		"""
		return self._bin