pyEDAA.Reports.CodeCoverage.JaCoCo

pyEDAA/Reports/CodeCoverage/JaCoCo.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
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
# ==================================================================================================================== #
#              _____ ____    _        _      ____                       _                                              #
#  _ __  _   _| ____|  _ \  / \      / \    |  _ \ ___ _ __   ___  _ __| |_ ___                                        #
# | '_ \| | | |  _| | | | |/ _ \    / _ \   | |_) / _ \ '_ \ / _ \| '__| __/ __|                                       #
# | |_) | |_| | |___| |_| / ___ \  / ___ \ _|  _ <  __/ |_) | (_) | |  | |_\__ \                                       #
# | .__/ \__, |_____|____/_/   \_\/_/   \_(_)_| \_\___| .__/ \___/|_|   \__|___/                                       #
# |_|    |___/                                        |_|                                                              #
# ==================================================================================================================== #
# 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                                                                                  #
# ==================================================================================================================== #
#
"""
JaCoCo's XML code coverage format: a model of the format, read from a report and converted to the common model.

JaCoCo - the Java code coverage library - writes its XML report with ``jacococli.jar report --xml``, Maven's goals
``report`` and ``report-aggregate``, Ant's task ``report`` or Gradle's task ``jacocoTestReport``. A report names its
DTD by a public identifier, e.g. ``-//JACOCO//DTD Report 1.1//EN``, whose version (:class:`FormatVersion`) chooses the
XML schema a report is validated against: :file:`JaCoCo-1.1.xsd`, a translation of JaCoCo's DTD ``report.dtd``. The
format's model keeps what the report states: a :class:`Document` holds :class:`SessionInfo` elements, :class:`Group`
elements - nested -, and :class:`Package` elements; a package holds :class:`Class` elements with their :class:`Method`
elements, and :class:`SourceFile` elements with their :class:`Line` elements. Every element but a line and a session
states its :class:`Counter` elements. Each element's constructor takes typed values, so the model can be built by hand:
an element below the report names its parent with the keyword parameter ``parent`` and is added to it. Its class method
``Parse`` reads the element's XML element.

:meth:`Document.ToCoverageSummary` converts the model to the common model of :mod:`pyEDAA.Reports.CodeCoverage`:

* A source file's path is its package's name in VM notation - e.g. ``my/pack`` - and its name, relative to a source
  directory, which the report doesn't name.
* A line ran, if it has a covered instruction - partially covered, if it has a missed branch. Its missed and covered
  branches become as many branches. The format has no counts, no branch targets and no excluded lines.
* The packages, classes and methods become units of the logical hierarchy; a package's name is split at ``/`` into
  nested packages. A method spans its first line and the next lines of its file, as many as its ``LINE`` counter
  counts; a class spans its methods. The groups have no counterpart.

.. rubric:: Example

.. code-block:: Python

   from pathlib import Path
   from pyEDAA.Reports.CodeCoverage.JaCoCo import Document

   report = Document(Path("jacocoTestReport.xml"), analyzeAndConvert=True)
   summary = report.ToCoverageSummary()
   for unit in summary.IterateUnits():
     print(f"{unit.QualifiedName}: {unit.LineCoverage:.1%}")
"""
from __future__                  import annotations

from datetime                    import datetime, timedelta, timezone
from io                          import BytesIO
from itertools                   import islice
from pathlib                     import Path
from re                          import compile as re_compile
from typing                      import Generator, Generic, Optional as Nullable, Self, TypeVar

from lxml.etree                  import XMLParser, XMLSchema, XMLSchemaParseError, XMLSyntaxError
from lxml.etree                  import _Element, _ElementTree, parse
from pyTooling.Common            import getFullyQualifiedName, getResourceFile, StringEnum
from pyTooling.Decorators        import export, readonly
from pyTooling.Exceptions        import ToolingException
from pyTooling.MetaClasses       import ExtendedType, abstractclass
from pyTooling.Stopwatch         import Stopwatch

from pyEDAA.Reports              import Resources
from pyEDAA.Reports.CodeCoverage import Branch as cc_Branch, Class as cc_Class, CodeCoverageError
from pyEDAA.Reports.CodeCoverage import CoverageSummary, Document as cc_Document, Line as cc_Line
from pyEDAA.Reports.CodeCoverage import LineCoverageStatus, Method as cc_Method, Package as cc_Package
from pyEDAA.Reports.CodeCoverage import Unit as cc_Unit


__all__ = ["PUBLIC_IDENTIFIER", "SCHEMAS"]

#: Pattern of the DTD's public identifier a report states, capturing the version, e.g. ``1.1``.
PUBLIC_IDENTIFIER = re_compile(r"-//JACOCO//DTD Report (\S+)//EN")

ParentType = TypeVar("ParentType", bound="Report | Group")
"""A type variable for the parent of a :class:`Group` or :class:`Package`: a :class:`Report` or a :class:`Group`."""


@export
class FormatVersion(StringEnum):
	"""
	Version of the JaCoCo XML format: the version of the DTD, whose public identifier a report states.
	"""

	Version1_1 = "1.1"  #: Format 1.1, public identifier ``-//JACOCO//DTD Report 1.1//EN``.


# A class with a property named like a class - ``FormatVersion`` - 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.
_FormatVersion = FormatVersion

SCHEMAS: dict[FormatVersion, str] = {
	FormatVersion.Version1_1: "JaCoCo-1.1.xsd"
}  #: Per format version, the XML schema a report of that version is validated against.


@export
class CounterType(StringEnum):
	"""
	Kind of items a ``<counter>`` counts, as its ``type`` states.
	"""

	Instruction = "INSTRUCTION"  #: Java bytecode instructions.
	Branch =      "BRANCH"       #: Branches of ``if`` and ``switch`` statements.
	Line =        "LINE"         #: Source lines with at least one instruction.
	Complexity =  "COMPLEXITY"   #: Cyclomatic complexity: paths, which in linear combination generate all paths.
	Method =      "METHOD"       #: Methods - also constructors and static initializers - with at least one instruction.
	Class =       "CLASS"        #: Classes with at least one method.


@export
class CountersMixin(metaclass=ExtendedType, mixin=True):
	"""
	A mixin-class adding the counters an element states: per kind of items, how many were missed and covered.
	"""

	_counters: dict[CounterType, Counter]  #: The counters, by kind.

	def __init__(self) -> None:
		"""
		Initialize the counters to none.

		A counter is added by creating it with the element as its parent.
		"""
		self._counters = {}

	@readonly
	def Counters(self) -> dict[CounterType, Counter]:
		"""
		Read-only property to access the counters (:attr:`_counters`).

		:returns: The counters, by kind; a kind without items has no counter.
		"""
		return self._counters


@export
@abstractclass
class Base(metaclass=ExtendedType, slots=True):
	"""
	Base-class of the named elements below the report.

	Packages and classes are named elements.
	"""

	_name: str  #: Name of the element.

	def __init__(self, name: str) -> None:
		"""
		Initialize the name of the element.

		:param name:        Name of the element.
		:raises ValueError: If parameter ``name`` is ``None``.
		:raises TypeError:  If parameter ``name`` isn't of type :class:`str`.
		"""
		if name is None:
			raise ValueError("Parameter 'name' is None.")
		elif not isinstance(name, str):
			ex = TypeError("Parameter 'name' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
			raise ex

		self._name = name

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

		:returns: The name.
		"""
		return self._name


@export
class Counter(metaclass=ExtendedType, slots=True):
	"""
	A ``<counter>`` of an element: how many items of a kind were missed and covered.
	"""

	_parent:       Nullable[CountersMixin]  #: The element the counter belongs to.
	_type:         CounterType              #: Kind of items the counter counts.
	_missedCount:  int                      #: Number of missed items.
	_coveredCount: int                      #: Number of covered items.

	def __init__(
		self,
		counterType:  CounterType,
		missedCount:  int,
		coveredCount: int,
		*,
		parent:       Nullable[CountersMixin] = None
	) -> None:
		"""
		Initialize the counter, and add it to the counters of its element.

		:param counterType:  Kind of items the counter counts.
		:param missedCount:  Number of missed items.
		:param coveredCount: Number of covered items.
		:param parent:       Optional, the element the counter belongs to; the counter is added to its counters by
		                     :attr:`Type`. Default: ``None``.
		:raises ValueError:  If parameter ``counterType`` is ``None``.
		:raises TypeError:   If parameter ``counterType`` isn't of type :class:`CounterType`.
		:raises ValueError:  If parameter ``missedCount`` is ``None``.
		:raises TypeError:   If parameter ``missedCount`` isn't of type :class:`int`.
		:raises ValueError:  If parameter ``missedCount`` is negative.
		:raises ValueError:  If parameter ``coveredCount`` is ``None``.
		:raises TypeError:   If parameter ``coveredCount`` isn't of type :class:`int`.
		:raises ValueError:  If parameter ``coveredCount`` is negative.
		:raises TypeError:   If parameter ``parent`` isn't of type :class:`CountersMixin`.
		"""
		if counterType is None:
			raise ValueError("Parameter 'counterType' is None.")
		elif not isinstance(counterType, CounterType):
			ex = TypeError("Parameter 'counterType' is not of type 'CounterType'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(counterType)}'.")
			raise ex

		if missedCount is None:
			raise ValueError("Parameter 'missedCount' is None.")
		elif not isinstance(missedCount, int):
			ex = TypeError("Parameter 'missedCount' is not of type 'int'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(missedCount)}'.")
			raise ex
		elif missedCount < 0:
			ex = ValueError("Parameter 'missedCount' is negative.")
			ex.add_note(f"Got value '{missedCount}'.")
			raise ex

		if coveredCount is None:
			raise ValueError("Parameter 'coveredCount' is None.")
		elif not isinstance(coveredCount, int):
			ex = TypeError("Parameter 'coveredCount' is not of type 'int'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(coveredCount)}'.")
			raise ex
		elif coveredCount < 0:
			ex = ValueError("Parameter 'coveredCount' is negative.")
			ex.add_note(f"Got value '{coveredCount}'.")
			raise ex

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

		self._parent =       parent
		self._type =         counterType
		self._missedCount =  missedCount
		self._coveredCount = coveredCount

		if parent is not None:
			parent._counters[self._type] = self

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

		:param element: The ``<counter>`` element.
		:param parent:  Optional, the element the counter belongs to. Default: ``None``.
		:returns:       The counter.
		"""
		return cls(
			CounterType(element.attrib["type"]),
			int(element.attrib["missed"]),
			int(element.attrib["covered"]),
			parent=parent
		)

	@readonly
	def Parent(self) -> Nullable[CountersMixin]:
		"""
		Read-only property to access the element the counter belongs to (:attr:`_parent`).

		:returns: The element; ``None`` if the counter belongs to no element.
		"""
		return self._parent

	@readonly
	def Type(self) -> CounterType:
		"""
		Read-only property to access the kind of items the counter counts (:attr:`_type`).

		:returns: The kind of items.
		"""
		return self._type

	@readonly
	def MissedCount(self) -> int:
		"""
		Read-only property to access the number of missed items (:attr:`_missedCount`).

		:returns: The number of missed items.
		"""
		return self._missedCount

	@readonly
	def CoveredCount(self) -> int:
		"""
		Read-only property to access the number of covered items (:attr:`_coveredCount`).

		:returns: The number of covered items.
		"""
		return self._coveredCount


@export
class SessionInfo(metaclass=ExtendedType, slots=True):
	"""
	A ``<sessioninfo>`` of the report: a session, which contributed execution data - its ID, its start and its dump.
	"""

	_parent:    Nullable[Report]  #: The report the session belongs to.
	_sessionID: str               #: ID of the session.
	_start:     datetime          #: Time the session started.
	_dump:      datetime          #: Time the session's execution data was dumped.

	def __init__(self, sessionID: str, start: datetime, dump: datetime, *, parent: Nullable[Report] = None) -> None:
		"""
		Initialize the session, and append it to the sessions of its report.

		:param sessionID:   ID of the session, e.g. the host's name and a random number.
		:param start:       Time the session started.
		:param dump:        Time the session's execution data was dumped.
		:param parent:      Optional, the report the session belongs to; the session is appended to its sessions.
		                    Default: ``None``.
		:raises ValueError: If parameter ``sessionID`` is ``None``.
		:raises TypeError:  If parameter ``sessionID`` isn't of type :class:`str`.
		:raises ValueError: If parameter ``start`` is ``None``.
		:raises TypeError:  If parameter ``start`` isn't of type :class:`~datetime.datetime`.
		:raises ValueError: If parameter ``dump`` is ``None``.
		:raises TypeError:  If parameter ``dump`` isn't of type :class:`~datetime.datetime`.
		:raises TypeError:  If parameter ``parent`` isn't of type :class:`Report`.
		"""
		if sessionID is None:
			raise ValueError("Parameter 'sessionID' is None.")
		elif not isinstance(sessionID, str):
			ex = TypeError("Parameter 'sessionID' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(sessionID)}'.")
			raise ex

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

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

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

		self._parent =    parent
		self._sessionID = sessionID
		self._start =     start
		self._dump =      dump

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

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

		The times are stated in milliseconds since the epoch.

		:param element: The ``<sessioninfo>`` element.
		:param parent:  Optional, the report the session belongs to. Default: ``None``.
		:returns:       The session.
		"""
		epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
		return cls(
			element.attrib["id"],
			epoch + timedelta(milliseconds=int(element.attrib["start"])),
			epoch + timedelta(milliseconds=int(element.attrib["dump"])),
			parent=parent
		)

	@readonly
	def Parent(self) -> Nullable[Report]:
		"""
		Read-only property to access the report the session belongs to (:attr:`_parent`).

		:returns: The report; ``None`` if the session belongs to no report.
		"""
		return self._parent

	@readonly
	def SessionID(self) -> str:
		"""
		Read-only property to access the ID of the session (:attr:`_sessionID`).

		JaCoCo's agent names a session by the host's name and a random number, e.g. ``dffa20ef8728-f9da5560``.

		:returns: The ID.
		"""
		return self._sessionID

	@readonly
	def Start(self) -> datetime:
		"""
		Read-only property to access the time the session started (:attr:`_start`).

		:returns: The time, with time zone UTC, if read from a report.
		"""
		return self._start

	@readonly
	def Dump(self) -> datetime:
		"""
		Read-only property to access the time the session's execution data was dumped (:attr:`_dump`).

		:returns: The time, with time zone UTC, if read from a report.
		"""
		return self._dump


@export
class Method(Base, CountersMixin):
	"""
	A ``<method>`` of a class: its descriptor, its first line and its counters.
	"""

	_parent:     Nullable[Class]  #: The class the method belongs to.
	_descriptor: str              #: Descriptor of the method: the types of its parameters and result, in VM notation.
	_lineNumber: Nullable[int]    #: The method's first source line, if the report says.

	def __init__(
		self,
		name:       str,
		descriptor: str,
		lineNumber: Nullable[int] = None,
		*,
		parent:     Nullable[Class] = None
	) -> None:
		"""
		Initialize the method, and add it to the methods of its class.

		Its counters are added by creating them with this method as their parent.

		:param name:        Name of the method, e.g. ``absolute``; ``<init>`` for a constructor.
		:param descriptor:  Descriptor of the method, e.g. ``(I)I`` for a method taking and returning an ``int``.
		:param lineNumber:  Optional, the method's first source line. Default: ``None``.
		:param parent:      Optional, the class the method belongs to; the method is added to its methods by
		                    :attr:`Name` and :attr:`Descriptor`. Default: ``None``.
		:raises ValueError: If parameter ``name`` is ``None``.
		:raises TypeError:  If parameter ``name`` isn't of type :class:`str`.
		:raises ValueError: If parameter ``name`` is empty.
		:raises ValueError: If parameter ``descriptor`` is ``None``.
		:raises TypeError:  If parameter ``descriptor`` isn't of type :class:`str`.
		:raises ValueError: If parameter ``descriptor`` is empty.
		:raises TypeError:  If parameter ``lineNumber`` isn't of type :class:`int`.
		:raises ValueError: If parameter ``lineNumber`` is less than 1.
		:raises TypeError:  If parameter ``parent`` isn't of type :class:`Class`.
		"""
		super().__init__(name)
		CountersMixin.__init__(self)

		if name == "":
			raise ValueError("Parameter 'name' is empty.")

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

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

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

		self._parent =     parent
		self._descriptor = descriptor
		self._lineNumber = lineNumber

		if parent is not None:
			parent._methods[f"{self._name}{self._descriptor}"] = self

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

		:param element:            The ``<method>`` element.
		:param parent:             Optional, the class the method belongs to. Default: ``None``.
		:returns:                  The method.
		:raises CodeCoverageError: If the method states a counter twice.
		"""
		method = cls(
			element.attrib["name"],
			element.attrib["desc"],
			int(line) if (line := element.attrib.get("line")) is not None else None,
			parent=parent
		)

		for counterElement in element.iterfind("counter"):
			if (counterType := CounterType(counterElement.attrib["type"])) in method._counters:
				raise CodeCoverageError(
					f"JaCoCo method '{method._name}{method._descriptor}' states counter '{counterType}' twice."
				)

			Counter.Parse(counterElement, parent=method)

		return method

	@readonly
	def Parent(self) -> Nullable[Class]:
		"""
		Read-only property to access the class the method belongs to (:attr:`_parent`).

		:returns: The class; ``None`` if the method belongs to no class.
		"""
		return self._parent

	@readonly
	def Descriptor(self) -> str:
		"""
		Read-only property to access the descriptor of the method (:attr:`_descriptor`).

		The descriptor ``([Ljava/lang/String;)V`` is of a method taking a ``String[]`` and returning ``void``.

		:returns: The descriptor, in VM notation.
		"""
		return self._descriptor

	@readonly
	def LineNumber(self) -> Nullable[int]:
		"""
		Read-only property to access the method's first source line (:attr:`_lineNumber`).

		A method of a class compiled without debug information has none.

		:returns: The line number, or ``None`` if the report doesn't say.
		"""
		return self._lineNumber


@export
class Class(Base, CountersMixin):
	"""
	A ``<class>`` of a package: its source file, its methods and its counters.
	"""

	_parent:         Nullable[Package]  #: The package the class belongs to.
	_sourceFileName: Nullable[str]      #: Name of the class' source file, if the report says.
	_methods:        dict[str, Method]  #: The methods, by name and descriptor.

	def __init__(self, name: str, sourceFileName: Nullable[str] = None, *, parent: Nullable[Package] = None) -> None:
		"""
		Initialize the class, and add it to the classes of its package.

		Its methods and counters are added by creating them with this class as their parent.

		:param name:           Fully qualified name of the class in VM notation, e.g. ``my/pack/MyClass``.
		:param sourceFileName: Optional, name of the class' source file, e.g. ``MyClass.java``. Default: ``None``.
		:param parent:         Optional, the package the class belongs to; the class is added to its classes by
		                       :attr:`Name`. Default: ``None``.
		:raises ValueError:    If parameter ``name`` is ``None``.
		:raises TypeError:     If parameter ``name`` isn't of type :class:`str`.
		:raises ValueError:    If parameter ``name`` is empty.
		:raises TypeError:     If parameter ``sourceFileName`` isn't of type :class:`str`.
		:raises TypeError:     If parameter ``parent`` isn't of type :class:`Package`.
		"""
		super().__init__(name)
		CountersMixin.__init__(self)

		if name == "":
			raise ValueError("Parameter 'name' is empty.")

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

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

		self._parent =         parent
		self._sourceFileName = sourceFileName
		self._methods =        {}

		if parent is not None:
			parent._classes[self._name] = self

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

		:param element:            The ``<class>`` element.
		:param parent:             Optional, the package the class belongs to. Default: ``None``.
		:returns:                  The class.
		:raises CodeCoverageError: If the class states a method twice.
		:raises CodeCoverageError: If the class states a counter twice.
		"""
		klass = cls(element.attrib["name"], element.attrib.get("sourcefilename"), parent=parent)

		for methodElement in element.iterfind("method"):
			if (key := f"{methodElement.attrib['name']}{methodElement.attrib['desc']}") in klass._methods:
				raise CodeCoverageError(f"JaCoCo class '{klass._name}' states method '{key}' twice.")

			Method.Parse(methodElement, parent=klass)

		for counterElement in element.iterfind("counter"):
			if (counterType := CounterType(counterElement.attrib["type"])) in klass._counters:
				raise CodeCoverageError(f"JaCoCo class '{klass._name}' states counter '{counterType}' twice.")

			Counter.Parse(counterElement, parent=klass)

		return klass

	@readonly
	def Parent(self) -> Nullable[Package]:
		"""
		Read-only property to access the package the class belongs to (:attr:`_parent`).

		:returns: The package; ``None`` if the class belongs to no package.
		"""
		return self._parent

	@readonly
	def SourceFileName(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the class' source file (:attr:`_sourceFileName`).

		A class compiled without debug information names no source file.

		:returns: The name of a :class:`SourceFile` of the class' package, or ``None`` if the report doesn't say.
		"""
		return self._sourceFileName

	@readonly
	def Methods(self) -> dict[str, Method]:
		"""
		Read-only property to access the methods (:attr:`_methods`).

		A method is keyed by its name and descriptor, e.g. ``absolute(I)I``.

		:returns: The methods, by name and descriptor.
		"""
		return self._methods


@export
class Line(metaclass=ExtendedType, slots=True):
	"""
	A ``<line>`` of a source file: its missed and covered instructions and branches.
	"""

	_parent:                  Nullable[SourceFile]  #: The source file the line belongs to.
	_lineNumber:              int                   #: Line number, counted from 1.
	_missedInstructionCount:  Nullable[int]         #: Number of missed instructions, if the report says.
	_coveredInstructionCount: Nullable[int]         #: Number of covered instructions, if the report says.
	_missedBranchCount:       Nullable[int]         #: Number of missed branches, if the report says.
	_coveredBranchCount:      Nullable[int]         #: Number of covered branches, if the report says.

	def __init__(
		self,
		lineNumber:              int,
		missedInstructionCount:  Nullable[int] = None,
		coveredInstructionCount: Nullable[int] = None,
		missedBranchCount:       Nullable[int] = None,
		coveredBranchCount:      Nullable[int] = None,
		*,
		parent:                  Nullable[SourceFile] = None
	) -> None:
		"""
		Initialize the line, and add it to the lines of its source file.

		:param lineNumber:              Line number, counted from 1.
		:param missedInstructionCount:  Optional, number of missed instructions. Default: ``None``.
		:param coveredInstructionCount: Optional, number of covered instructions. Default: ``None``.
		:param missedBranchCount:       Optional, number of missed branches. Default: ``None``.
		:param coveredBranchCount:      Optional, number of covered branches. Default: ``None``.
		:param parent:                  Optional, the source file the line belongs to; the line is added to its lines by
		                                :attr:`LineNumber`. Default: ``None``.
		:raises ValueError:             If parameter ``lineNumber`` is ``None``.
		:raises TypeError:              If parameter ``lineNumber`` isn't of type :class:`int`.
		:raises ValueError:             If parameter ``lineNumber`` is less than 1.
		:raises TypeError:              If parameter ``missedInstructionCount`` isn't of type :class:`int`.
		:raises ValueError:             If parameter ``missedInstructionCount`` is negative.
		:raises TypeError:              If parameter ``coveredInstructionCount`` isn't of type :class:`int`.
		:raises ValueError:             If parameter ``coveredInstructionCount`` is negative.
		:raises TypeError:              If parameter ``missedBranchCount`` isn't of type :class:`int`.
		:raises ValueError:             If parameter ``missedBranchCount`` is negative.
		:raises TypeError:              If parameter ``coveredBranchCount`` isn't of type :class:`int`.
		:raises ValueError:             If parameter ``coveredBranchCount`` is negative.
		:raises TypeError:              If parameter ``parent`` isn't of type :class:`SourceFile`.
		"""
		if lineNumber is None:
			raise ValueError("Parameter 'lineNumber' is None.")
		elif not isinstance(lineNumber, int):
			ex = TypeError("Parameter 'lineNumber' is not of type 'int'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(lineNumber)}'.")
			raise ex
		elif lineNumber < 1:
			ex = ValueError("Parameter 'lineNumber' is less than 1.")
			ex.add_note(f"Got value '{lineNumber}'.")
			raise ex

		for name, count in (
			("missedInstructionCount",  missedInstructionCount),
			("coveredInstructionCount", coveredInstructionCount),
			("missedBranchCount",       missedBranchCount),
			("coveredBranchCount",      coveredBranchCount)
		):
			if count is not None:
				if not isinstance(count, int):
					ex = TypeError(f"Parameter '{name}' is not of type 'int'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(count)}'.")
					raise ex
				elif count < 0:
					ex = ValueError(f"Parameter '{name}' is negative.")
					ex.add_note(f"Got value '{count}'.")
					raise ex

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

		self._parent =                  parent
		self._lineNumber =              lineNumber
		self._missedInstructionCount =  missedInstructionCount
		self._coveredInstructionCount = coveredInstructionCount
		self._missedBranchCount =       missedBranchCount
		self._coveredBranchCount =      coveredBranchCount

		if parent is not None:
			parent._lines[self._lineNumber] = self

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

		:param element: The ``<line>`` element.
		:param parent:  Optional, the source file the line belongs to. Default: ``None``.
		:returns:       The line.
		"""
		attributes = element.attrib
		return cls(
			int(attributes["nr"]),
			int(attributes["mi"]) if "mi" in attributes else None,
			int(attributes["ci"]) if "ci" in attributes else None,
			int(attributes["mb"]) if "mb" in attributes else None,
			int(attributes["cb"]) if "cb" in attributes else None,
			parent=parent
		)

	@readonly
	def Parent(self) -> Nullable[SourceFile]:
		"""
		Read-only property to access the source file the line belongs to (:attr:`_parent`).

		:returns: The source file; ``None`` if the line belongs to no source file.
		"""
		return self._parent

	@readonly
	def LineNumber(self) -> int:
		"""
		Read-only property to access the line number (:attr:`_lineNumber`).

		:returns: The line number, counted from 1.
		"""
		return self._lineNumber

	@readonly
	def MissedInstructionCount(self) -> Nullable[int]:
		"""
		Read-only property to access the number of missed instructions (:attr:`_missedInstructionCount`).

		:returns: The number, or ``None`` if the report doesn't say.
		"""
		return self._missedInstructionCount

	@readonly
	def CoveredInstructionCount(self) -> Nullable[int]:
		"""
		Read-only property to access the number of covered instructions (:attr:`_coveredInstructionCount`).

		:returns: The number, or ``None`` if the report doesn't say.
		"""
		return self._coveredInstructionCount

	@readonly
	def MissedBranchCount(self) -> Nullable[int]:
		"""
		Read-only property to access the number of missed branches (:attr:`_missedBranchCount`).

		:returns: The number, or ``None`` if the report doesn't say.
		"""
		return self._missedBranchCount

	@readonly
	def CoveredBranchCount(self) -> Nullable[int]:
		"""
		Read-only property to access the number of covered branches (:attr:`_coveredBranchCount`).

		:returns: The number, or ``None`` if the report doesn't say.
		"""
		return self._coveredBranchCount


@export
class SourceFile(Base, CountersMixin):
	"""
	A ``<sourcefile>`` of a package: its lines and its counters.
	"""

	_parent: Nullable[Package]  #: The package the source file belongs to.
	_lines:  dict[int, Line]    #: The lines with instructions, by number.

	def __init__(self, name: str, *, parent: Nullable[Package] = None) -> None:
		"""
		Initialize the source file, and add it to the source files of its package.

		Its lines and counters are added by creating them with this source file as their parent.

		:param name:        Name of the source file, without the package's directory, e.g. ``MyClass.java``.
		:param parent:      Optional, the package the source file belongs to; the source file is added to its source
		                    files by :attr:`Name`. Default: ``None``.
		:raises ValueError: If parameter ``name`` is ``None``.
		:raises TypeError:  If parameter ``name`` isn't of type :class:`str`.
		:raises ValueError: If parameter ``name`` is empty.
		:raises TypeError:  If parameter ``parent`` isn't of type :class:`Package`.
		"""
		super().__init__(name)
		CountersMixin.__init__(self)

		if name == "":
			raise ValueError("Parameter 'name' is empty.")

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

		self._parent = parent
		self._lines =  {}

		if parent is not None:
			parent._sourceFiles[self._name] = self

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[Package] = None) -> Self:
		"""
		Parse a source file, its lines and counters from its ``<sourcefile>`` element.

		:param element:            The ``<sourcefile>`` element.
		:param parent:             Optional, the package the source file belongs to. Default: ``None``.
		:returns:                  The source file.
		:raises CodeCoverageError: If the source file states a line twice.
		:raises CodeCoverageError: If the source file states a counter twice.
		"""
		sourceFile = cls(element.attrib["name"], parent=parent)

		for lineElement in element.iterfind("line"):
			if (lineNumber := int(lineElement.attrib["nr"])) in sourceFile._lines:
				raise CodeCoverageError(f"JaCoCo source file '{sourceFile._name}' states line {lineNumber} twice.")

			Line.Parse(lineElement, parent=sourceFile)

		for counterElement in element.iterfind("counter"):
			if (counterType := CounterType(counterElement.attrib["type"])) in sourceFile._counters:
				raise CodeCoverageError(f"JaCoCo source file '{sourceFile._name}' states counter '{counterType}' twice.")

			Counter.Parse(counterElement, parent=sourceFile)

		return sourceFile

	@readonly
	def Parent(self) -> Nullable[Package]:
		"""
		Read-only property to access the package the source file belongs to (:attr:`_parent`).

		:returns: The package; ``None`` if the source file belongs to no package.
		"""
		return self._parent

	@readonly
	def Lines(self) -> dict[int, Line]:
		"""
		Read-only property to access the lines with instructions (:attr:`_lines`).

		:returns: The lines, by number.
		"""
		return self._lines


@export
class Package(Base, CountersMixin, Generic[ParentType]):
	"""
	A ``<package>`` of the report or of a group: its classes and source files, and its counters.
	"""

	_parent:      Nullable[ParentType]   #: The report or group the package belongs to.
	_classes:     dict[str, Class]       #: The classes, by name.
	_sourceFiles: dict[str, SourceFile]  #: The source files, by name.

	def __init__(self, name: str, *, parent: Nullable[ParentType] = None) -> None:
		"""
		Initialize the package, and add it to the packages of its report or group.

		Its classes, source files and counters are added by creating them with this package as their parent.

		:param name:        Name of the package in VM notation, e.g. ``my/pack``; empty for the default package.
		:param parent:      Optional, the report or group the package belongs to; the package is added to its packages
		                    by :attr:`Name`. Default: ``None``.
		:raises ValueError: If parameter ``name`` is ``None``.
		:raises TypeError:  If parameter ``name`` isn't of type :class:`str`.
		:raises TypeError:  If parameter ``parent`` isn't of type :class:`Report` or :class:`Group`.
		"""
		super().__init__(name)
		CountersMixin.__init__(self)

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

		self._parent =      parent
		self._classes =     {}
		self._sourceFiles = {}

		if parent is not None:
			parent._packages[self._name] = self

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[ParentType] = None) -> Self:
		"""
		Parse a package, its classes, source files and counters from its ``<package>`` element.

		:param element:            The ``<package>`` element.
		:param parent:             Optional, the report or group the package belongs to. Default: ``None``.
		:returns:                  The package.
		:raises CodeCoverageError: If the package states a class or source file twice.
		:raises CodeCoverageError: If the package states a counter twice.
		"""
		package = cls(element.attrib["name"], parent=parent)

		for classElement in element.iterfind("class"):
			if (name := classElement.attrib["name"]) in package._classes:
				raise CodeCoverageError(f"JaCoCo package '{package._name}' states class '{name}' twice.")

			Class.Parse(classElement, parent=package)

		for sourceFileElement in element.iterfind("sourcefile"):
			if (name := sourceFileElement.attrib["name"]) in package._sourceFiles:
				raise CodeCoverageError(f"JaCoCo package '{package._name}' states source file '{name}' twice.")

			SourceFile.Parse(sourceFileElement, parent=package)

		for counterElement in element.iterfind("counter"):
			if (counterType := CounterType(counterElement.attrib["type"])) in package._counters:
				raise CodeCoverageError(f"JaCoCo package '{package._name}' states counter '{counterType}' twice.")

			Counter.Parse(counterElement, parent=package)

		return package

	@readonly
	def Parent(self) -> Nullable[ParentType]:
		"""
		Read-only property to access the report or group the package belongs to (:attr:`_parent`).

		:returns: The :class:`Report` or :class:`Group`; ``None`` if the package belongs to none.
		"""
		return self._parent

	@readonly
	def Classes(self) -> dict[str, Class]:
		"""
		Read-only property to access the classes (:attr:`_classes`).

		A class is keyed by its name, e.g. ``my/pack/MyClass``, a nested class by its binary name, e.g.
		``my/pack/MyClass$Inner``.

		:returns: The classes, by name.
		"""
		return self._classes

	@readonly
	def SourceFiles(self) -> dict[str, SourceFile]:
		"""
		Read-only property to access the source files (:attr:`_sourceFiles`).

		A source file is keyed by its name, e.g. ``MyClass.java``.

		:returns: The source files, by name.
		"""
		return self._sourceFiles


@export
class Group(Base, CountersMixin, Generic[ParentType]):
	"""
	A ``<group>`` of the report or of a group: its groups or packages, and its counters.

	JaCoCo groups packages, e.g. by module, if Maven's goal ``report-aggregate`` or Ant's task ``report`` asks for it.
	"""

	_parent:   Nullable[ParentType]       #: The report or group the group belongs to.
	_groups:   dict[str, Group[Group]]    #: The groups, by name.
	_packages: dict[str, Package[Group]]  #: The packages, by name.

	def __init__(self, name: str, *, parent: Nullable[ParentType] = None) -> None:
		"""
		Initialize the group, and add it to the groups of its report or group.

		Its groups, packages and counters are added by creating them with this group as their parent.

		:param name:        Name of the group, e.g. of a module.
		:param parent:      Optional, the report or group the group belongs to; the group is added to its groups by
		                    :attr:`Name`. Default: ``None``.
		:raises ValueError: If parameter ``name`` is ``None``.
		:raises TypeError:  If parameter ``name`` isn't of type :class:`str`.
		:raises ValueError: If parameter ``name`` is empty.
		:raises TypeError:  If parameter ``parent`` isn't of type :class:`Report` or :class:`Group`.
		"""
		super().__init__(name)
		CountersMixin.__init__(self)

		if name == "":
			raise ValueError("Parameter 'name' is empty.")

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

		self._parent =   parent
		self._groups =   {}
		self._packages = {}

		if parent is not None:
			parent._groups[self._name] = self

	@classmethod
	def Parse(cls, element: _Element, *, parent: Nullable[ParentType] = None) -> Self:
		"""
		Parse a group, its groups, packages and counters from its ``<group>`` element.

		:param element:            The ``<group>`` element.
		:param parent:             Optional, the report or group the group belongs to. Default: ``None``.
		:returns:                  The group.
		:raises CodeCoverageError: If the group states a group or package twice.
		:raises CodeCoverageError: If the group states a counter twice.
		"""
		group = cls(element.attrib["name"], parent=parent)

		for groupElement in element.iterfind("group"):
			if (name := groupElement.attrib["name"]) in group._groups:
				raise CodeCoverageError(f"JaCoCo group '{group._name}' states group '{name}' twice.")

			Group.Parse(groupElement, parent=group)

		for packageElement in element.iterfind("package"):
			if (name := packageElement.attrib["name"]) in group._packages:
				raise CodeCoverageError(f"JaCoCo group '{group._name}' states package '{name}' twice.")

			Package.Parse(packageElement, parent=group)

		for counterElement in element.iterfind("counter"):
			if (counterType := CounterType(counterElement.attrib["type"])) in group._counters:
				raise CodeCoverageError(f"JaCoCo group '{group._name}' states counter '{counterType}' twice.")

			Counter.Parse(counterElement, parent=group)

		return group

	@readonly
	def Parent(self) -> Nullable[ParentType]:
		"""
		Read-only property to access the report or group the group belongs to (:attr:`_parent`).

		:returns: The :class:`Report` or :class:`Group`; ``None`` if the group belongs to none.
		"""
		return self._parent

	@readonly
	def Groups(self) -> dict[str, Group[Group]]:
		"""
		Read-only property to access the groups (:attr:`_groups`).

		:returns: The groups, by name.
		"""
		return self._groups

	@readonly
	def Packages(self) -> dict[str, Package[Group]]:
		"""
		Read-only property to access the packages (:attr:`_packages`).

		:returns: The packages, by name.
		"""
		return self._packages


@export
class Report(CountersMixin, mixin=True):
	"""
	The root element ``<report>``: its name, the sessions, the groups or packages, and the counters.

	The root of the format's model: a session, a group, a package or a counter names it as its parent.
	"""

	_name:          Nullable[str]               #: Name of the report, e.g. of the project measured.
	_formatVersion: Nullable[_FormatVersion]    #: Version of the report format.
	_sessionInfos:  list[SessionInfo]           #: The sessions, which contributed execution data.
	_groups:        dict[str, Group[Report]]    #: The groups, by name.
	_packages:      dict[str, Package[Report]]  #: The packages, by name.

	def __init__(self) -> None:
		"""
		Initialize an empty report.
		"""
		CountersMixin.__init__(self)

		self._name =          None
		self._formatVersion = None
		self._sessionInfos =  []
		self._groups =        {}
		self._packages =      {}

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

		The name is chosen by the tool writing the report, e.g. the name of the project measured.

		:returns: The name; ``None`` before the report was converted.
		"""
		return self._name

	@readonly
	def FormatVersion(self) -> Nullable[FormatVersion]:
		"""
		Read-only property to access the version of the report format (:attr:`_formatVersion`).

		:returns: The format version; ``None`` before the report was analyzed.
		"""
		return self._formatVersion

	@readonly
	def SessionInfos(self) -> list[SessionInfo]:
		"""
		Read-only property to access the sessions, which contributed execution data (:attr:`_sessionInfos`).

		:returns: The sessions, in the order the report lists them.
		"""
		return self._sessionInfos

	@readonly
	def Groups(self) -> dict[str, Group[Report]]:
		"""
		Read-only property to access the groups (:attr:`_groups`).

		:returns: The groups, by name; empty, if the report has packages.
		"""
		return self._groups

	@readonly
	def Packages(self) -> dict[str, Package[Report]]:
		"""
		Read-only property to access the packages (:attr:`_packages`).

		:returns: The packages, by name; empty, if the report has groups.
		"""
		return self._packages


@export
class Document(cc_Document, Report):
	"""
	A JaCoCo XML code coverage report: read into the format's model, and converted to the common model.
	"""

	_xmlDocument: Nullable[_ElementTree]  #: The parsed and validated XML document, after :meth:`Analyze`.

	def __init__(self, xmlReportFile: Path, analyzeAndConvert: bool = False) -> None:
		"""
		Initialize the report, and optionally read it.

		:param xmlReportFile:     Path to the JaCoCo XML file.
		:param analyzeAndConvert: Optional, if true, analyze the file and convert its content. Default: ``False``.
		"""
		super().__init__(xmlReportFile)
		Report.__init__(self)

		self._xmlDocument = None

		if analyzeAndConvert:
			self.Analyze()
			self.Convert()

	def Analyze(self) -> None:
		"""
		Parse the XML file, read the format version from the DTD's public identifier, and validate the file against the
		XML schema of that version (:data:`SCHEMAS`).

		:raises CodeCoverageError: If the file doesn't exist.
		:raises CodeCoverageError: If the file can't be read.
		:raises CodeCoverageError: If the file isn't well-formed XML.
		:raises CodeCoverageError: If the root element isn't ``<report>``.
		:raises CodeCoverageError: If the file states no public identifier of a supported format version.
		:raises CodeCoverageError: If the XML schema can't be located or parsed.
		:raises CodeCoverageError: If the file isn't valid according to the XML schema.
		"""
		if not self._path.exists():
			raise CodeCoverageError(f"JaCoCo report file '{self._path}' does not exist.") \
				from FileNotFoundError(f"File '{self._path}' not found.")

		with Stopwatch() as sw:
			try:
				content = self._path.read_bytes()
			except OSError as ex:
				raise CodeCoverageError(f"Couldn't read JaCoCo report file '{self._path}'.") from ex

			try:
				xmlDocument = parse(BytesIO(content), XMLParser(ns_clean=True), base_url=str(self._path))
			except XMLSyntaxError as ex:
				raise CodeCoverageError(f"XML syntax error in JaCoCo report file '{self._path}'.") from ex

			rootElement: _Element = xmlDocument.getroot()
			if rootElement.tag != "report":
				ex = CodeCoverageError(f"Root element of '{self._path}' is not '<report>'.")
				ex.add_note(f"Got root element '<{rootElement.tag}>'.")
				raise ex

			publicID = xmlDocument.docinfo.public_id
			match = PUBLIC_IDENTIFIER.fullmatch(publicID) if publicID is not None else None
			if match is None or match[1] not in [member.value for member in FormatVersion]:
				ex = CodeCoverageError(f"JaCoCo report file '{self._path}' states an unsupported format version.")
				ex.add_note(f"Got public identifier '{publicID}'." if publicID is not None else "Got no public identifier.")
				ex.add_note(f"Supported format versions: {', '.join(member.value for member in FormatVersion)}.")
				raise ex

			formatVersion = FormatVersion(match[1])
			schemaFile = SCHEMAS[formatVersion]
			try:
				schemaResourceFile = getResourceFile(Resources, schemaFile)
			except ToolingException as ex:
				raise CodeCoverageError(f"Couldn't locate XML Schema '{schemaFile}' in package resources.") from ex

			try:
				xmlSchema = XMLSchema(parse(schemaResourceFile, XMLParser(ns_clean=True)))
			except (XMLSyntaxError, XMLSchemaParseError) as ex:
				raise CodeCoverageError(f"Error while parsing XML Schema '{schemaFile}'.") from ex

			if not xmlSchema.validate(xmlDocument):
				ex = CodeCoverageError(f"Validation error for '{self._path}' using XSD schema '{schemaFile}'.")
				for logEntry in xmlSchema.error_log:
					ex.add_note(str(logEntry))
				raise ex

			self._xmlDocument =   xmlDocument
			self._formatVersion = formatVersion

		self._analysisDuration = sw.Duration

	def Convert(self) -> None:
		"""
		Convert the parsed and validated XML document to the format's model.

		:raises CodeCoverageError: If the XML file was not analyzed before. |br|
		                           Call 'Document.Analyze()' or create the document using
		                           'Document(path, analyzeAndConvert=True)'.
		:raises CodeCoverageError: If an element states a child element twice.
		"""
		if self._xmlDocument is None:
			ex = CodeCoverageError(f"JaCoCo report file '{self._path}' needs to be read and analyzed by an XML parser.")
			ex.add_note("Call 'Document.Analyze()' or create the document using 'Document(path, analyzeAndConvert=True)'.")
			raise ex

		with Stopwatch() as sw:
			root: _Element = self._xmlDocument.getroot()
			self._name = root.attrib["name"]

			for sessionInfoElement in root.iterfind("sessioninfo"):
				SessionInfo.Parse(sessionInfoElement, parent=self)

			for groupElement in root.iterfind("group"):
				if (name := groupElement.attrib["name"]) in self._groups:
					raise CodeCoverageError(f"JaCoCo report '{self._name}' states group '{name}' twice.")

				Group.Parse(groupElement, parent=self)

			for packageElement in root.iterfind("package"):
				if (name := packageElement.attrib["name"]) in self._packages:
					raise CodeCoverageError(f"JaCoCo report '{self._name}' states package '{name}' twice.")

				Package.Parse(packageElement, parent=self)

			for counterElement in root.iterfind("counter"):
				if (counterType := CounterType(counterElement.attrib["type"])) in self._counters:
					raise CodeCoverageError(f"JaCoCo report '{self._name}' states counter '{counterType}' twice.")

				Counter.Parse(counterElement, parent=self)

		self._conversionDuration = sw.Duration

	def ToCoverageSummary(self) -> CoverageSummary:
		"""
		Convert the format's model to the common model, and aggregate it.

		The packages of all groups are converted. A source file's path is its package's name and its name. A line's
		missed and covered branches become as many branches. A method spans its first line and the next lines of its file,
		as many as its ``LINE`` counter counts; a class spans its methods.

		:returns:                  The report's root of the common model, named after the report - or, if the report's
		                           name is empty, after the report file.
		:raises CodeCoverageError: If two packages of the same name state a source file of the same name.
		:raises CodeCoverageError: If a file's path runs through another file.
		"""
		def iteratePackages(element: Report | Group) -> Generator[Package, None, None]:
			"""
			Nested function for recursion.

			:param element: The report or a group.
			:returns:       A generator of the packages of the element and of its groups.
			"""
			for group in element._groups.values():
				yield from iteratePackages(group)

			yield from element._packages.values()

		def getStatus(element: CountersMixin, counterType: CounterType) -> LineCoverageStatus:
			"""
			Nested function returning the coverage state of a class or method by its ``CLASS`` or ``METHOD`` counter.

			:param element:     The class or method.
			:param counterType: The counter's kind.
			:returns:           Covered, if the counter counts a covered item, otherwise uncovered; unknown, if the element
			                    has no such counter.
			"""
			if (counter := element._counters.get(counterType)) is None:
				return LineCoverageStatus.Unknown

			return LineCoverageStatus.Covered if counter._coveredCount > 0 else LineCoverageStatus.Uncovered

		summary = CoverageSummary(self._name if self._name is not None and self._name != "" else self._path.stem)

		for package in iteratePackages(self):
			for sourceFile in package._sourceFiles.values():
				file = summary.GetOrAddFile(Path(package._name) / sourceFile._name)
				for number in sorted(sourceFile._lines):
					line = sourceFile._lines[number]
					missedBranchCount =  line._missedBranchCount if line._missedBranchCount is not None else 0
					coveredBranchCount = line._coveredBranchCount if line._coveredBranchCount is not None else 0
					branches =           [cc_Branch(LineCoverageStatus.Covered) for _ in range(coveredBranchCount)]
					branches.extend(cc_Branch(LineCoverageStatus.Uncovered) for _ in range(missedBranchCount))
					if line._coveredInstructionCount is None:
						status = LineCoverageStatus.Unknown
					elif line._coveredInstructionCount == 0:
						status = LineCoverageStatus.Uncovered
					elif missedBranchCount > 0:
						status = LineCoverageStatus.PartiallyCovered
					else:
						status = LineCoverageStatus.Covered
					cc_Line(number, status, None, branches, parent=file)

		for package in iteratePackages(self):
			parent: cc_Unit | CoverageSummary = summary
			for part in (part for part in package._name.split("/") if part != ""):
				parent = parent._units[part] if part in parent._units else cc_Package(part, parent=parent)

			for klass in package._classes.values():
				file = None
				if klass._sourceFileName is not None and klass._sourceFileName in package._sourceFiles:
					file = summary.GetOrAddFile(Path(package._name) / klass._sourceFileName)

				# per method with a first line in the file: its first and last line
				spans: dict[str, tuple[cc_Line, cc_Line]] = {}
				for key, method in klass._methods.items():
					if (
						file is None or method._lineNumber is None or method._lineNumber > file._lastLineNumber or
						(startLine := file._lines[method._lineNumber]) is None
					):
						continue

					counter =    method._counters.get(CounterType.Line)
					lineCount =  counter._missedCount + counter._coveredCount if counter is not None else 1
					lines =      list(islice(file.IterateLines(startLine), max(lineCount, 1)))
					spans[key] = (startLine, lines[-1])

				if (classUnit := parent._units.get(name := klass._name.rpartition("/")[2])) is None:
					classUnit = cc_Class(
						name,
						file=file,
						startLine=min((span[0] for span in spans.values()), key=lambda line: line._lineNumber, default=None),
						endLine=max((span[1] for span in spans.values()), key=lambda line: line._lineNumber, default=None),
						status=getStatus(klass, CounterType.Class),
						parent=parent
					)

				for key, method in klass._methods.items():
					if key not in classUnit._units:
						cc_Method(
							key,
							file=file,
							startLine=spans[key][0] if key in spans else None,
							endLine=spans[key][1] if key in spans else None,
							status=getStatus(method, CounterType.Method),
							parent=classUnit
						)

		summary.Aggregate()
		return summary