1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
|
# ==================================================================================================================== #
# _____ ____ _ _ ____ _ #
# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
# |_| |___/ |_| #
# ==================================================================================================================== #
# 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 #
# ==================================================================================================================== #
#
"""
GCC's gcov JSON code coverage format: a model of the format, read from a report and converted to the common model.
gcov writes the format with ``gcov --json-format``: gzip-compressed to a :file:`*.gcov.json.gz` file per data file, or,
with ``--stdout``, as plain JSON, one line per data file. A report is read in either form, and each JSON object in
it is validated against the JSON Schema of the format version it states (:class:`FormatVersion`), reverse-engineered
from GCC: :file:`Gcov-1.schema.json` for format 1 (GCC 9 to 13), :file:`Gcov-2.schema.json` for format 2 (GCC 14 and
later). The format's model keeps what the report states: a :class:`Document` holds :class:`DataFile` records, a data
file :class:`File` records, a file its :class:`Function` and :class:`Line` records, and a line its :class:`Branch`,
:class:`Call` and :class:`Condition` records - in format 2 with the IDs of the basic blocks they belong to. Each
record's constructor takes typed values, so the model can be built by hand: a record below the report names its parent
with the keyword parameter ``parent`` and is added to it. Its class method ``Parse`` reads the record's JSON object.
:meth:`Document.ToCoverageSummary` converts the model to the common model of :mod:`pyEDAA.Reports.CodeCoverage`:
* A file's path is relative to the directory the compiler ran in - a data file's ``current_working_directory`` -,
unless it is absolute.
* A line's ``count`` is its count; a line, which ran without taking all of its branches, is partially covered. A line
several functions share - e.g. the instantiations of a template - or several data files state - e.g. a header -
becomes one line, its counts added.
* A branch becomes a branch of its line, with its count; exceptional branches (``throw``) are branches too. A branch
leads to a basic block, not to a line, so it has no target.
* A file becomes a source file unit, its functions - by demangled name, e.g. ``Containers::Stack::Pop()`` - become
functions, each spanning its first to its last line, with its execution count.
* Calls, conditions and basic blocks have no counterpart in the common model. The format has no excluded lines.
.. rubric:: Example
.. code-block:: Python
from pathlib import Path
from pyEDAA.Reports.CodeCoverage.Gcov import Document
report = Document(Path("main.gcov.json.gz"), analyzeAndConvert=True)
summary = report.ToCoverageSummary()
print(f"{summary.FileCount} files: {summary.LineCoverage:.1%}")
"""
from __future__ import annotations
from enum import IntEnum
from gzip import BadGzipFile, decompress
from json import JSONDecodeError, JSONDecoder, loads
from pathlib import Path
from re import compile as re_compile
from typing import Any, Iterable, Optional as Nullable, Self
from zlib import error as ZLibError
from jsonschema import Draft202012Validator
from pyTooling.Common import getFullyQualifiedName, readResourceFile
from pyTooling.Decorators import export, readonly
from pyTooling.Exceptions import ToolingException
from pyTooling.MetaClasses import ExtendedType
from pyTooling.Stopwatch import Stopwatch
from pyTooling.Versioning import SemanticVersion
from pyEDAA.Reports import Resources
from pyEDAA.Reports.CodeCoverage import Branch as cc_Branch, CodeCoverageError, CoverageSummary
from pyEDAA.Reports.CodeCoverage import Document as cc_Document, File as cc_File, Function as cc_Function
from pyEDAA.Reports.CodeCoverage import Line as cc_Line, LineCoverageStatus, SourceFile as cc_SourceFile
__all__ = ["SCHEMAS"]
# A class with a property named like a class - ``Path`` - 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.
_Path = Path
@export
class FormatVersion(IntEnum):
"""
Version of the gcov JSON format, as a report's ``format_version`` states it.
GCC 9 to 13 write format 1. GCC 14 and later write format 2, which adds the IDs of the basic blocks of a line and of
a branch, and the calls and conditions of a line; GCC 15 adds the prime paths of a function to format 2.
"""
Version1 = 1 #: Format 1, written by GCC 9 to 13.
Version2 = 2 #: Format 2, written by GCC 14 and later.
@classmethod
def Parse(cls, value: str) -> Self:
"""
Convert the version, as gcov states it, to the member of that version.
gcov states the version as a string, e.g. ``"2"``.
:param value: The version, as a report's ``format_version`` states it.
:returns: The member of that version.
:raises ValueError: If parameter ``value`` is ``None``.
:raises TypeError: If parameter ``value`` isn't of type :class:`str`.
:raises ValueError: If parameter ``value`` isn't a supported format version.
"""
if value is None:
raise ValueError("Parameter 'value' is None.")
elif not isinstance(value, str):
ex = TypeError("Parameter 'value' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
raise ex
elif value not in [str(member.value) for member in cls]:
ex = ValueError("Parameter 'value' is not a supported gcov JSON format version.")
ex.add_note(f"Got value '{value}'.")
ex.add_note(f"Supported format versions: {', '.join(str(member.value) for member in cls)}.")
raise ex
return cls(int(value))
# Like '_Path': DataFile has a property named 'FormatVersion'.
_FormatVersion = FormatVersion
SCHEMAS: dict[FormatVersion, str] = {
FormatVersion.Version1: "Gcov-1.schema.json",
FormatVersion.Version2: "Gcov-2.schema.json"
} #: Per format version, the JSON Schema a JSON object of that version is validated against.
@export
class Branch(metaclass=ExtendedType, slots=True):
"""
A ``branch`` of a line: an edge from a basic block to another, and how often it was taken.
"""
_parent: Nullable[Line] #: The line the branch belongs to.
_count: int #: Number of times the branch was taken.
_throw: bool #: Whether the branch is taken by an exception.
_fallthrough: bool #: Whether the branch falls through.
_sourceBlockID: Nullable[int] #: ID of the basic block the branch starts at, in format 2.
_destinationBlockID: Nullable[int] #: ID of the basic block the branch leads to, in format 2.
def __init__(
self,
count: int,
throw: bool,
fallthrough: bool,
sourceBlockID: Nullable[int] = None,
destinationBlockID: Nullable[int] = None,
*,
parent: Nullable[Line] = None
) -> None:
"""
Initialize the branch, and add it to the branches of its line.
:param count: Number of times the branch was taken.
:param throw: Whether the branch is taken by an exception.
:param fallthrough: Whether the branch falls through.
:param sourceBlockID: Optional, ID of the basic block the branch starts at. Default: ``None``.
:param destinationBlockID: Optional, ID of the basic block the branch leads to. Default: ``None``.
:param parent: Optional, the line the branch belongs to; the branch is appended to its branches.
Default: ``None``.
:raises ValueError: If parameter ``count`` is ``None``.
:raises TypeError: If parameter ``count`` isn't of type :class:`int`.
:raises ValueError: If parameter ``count`` is negative.
:raises ValueError: If parameter ``throw`` is ``None``.
:raises TypeError: If parameter ``throw`` isn't of type :class:`bool`.
:raises ValueError: If parameter ``fallthrough`` is ``None``.
:raises TypeError: If parameter ``fallthrough`` isn't of type :class:`bool`.
:raises TypeError: If parameter ``sourceBlockID`` isn't of type :class:`int`.
:raises ValueError: If parameter ``sourceBlockID`` is negative.
:raises TypeError: If parameter ``destinationBlockID`` isn't of type :class:`int`.
:raises ValueError: If parameter ``destinationBlockID`` is negative.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Line`.
"""
if count is None:
raise ValueError("Parameter 'count' is None.")
elif not isinstance(count, int):
ex = TypeError("Parameter 'count' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(count)}'.")
raise ex
elif count < 0:
ex = ValueError("Parameter 'count' is negative.")
ex.add_note(f"Got value '{count}'.")
raise ex
if throw is None:
raise ValueError("Parameter 'throw' is None.")
elif not isinstance(throw, bool):
ex = TypeError("Parameter 'throw' is not of type 'bool'.")
ex.add_note(f"Got type '{getFullyQualifiedName(throw)}'.")
raise ex
if fallthrough is None:
raise ValueError("Parameter 'fallthrough' is None.")
elif not isinstance(fallthrough, bool):
ex = TypeError("Parameter 'fallthrough' is not of type 'bool'.")
ex.add_note(f"Got type '{getFullyQualifiedName(fallthrough)}'.")
raise ex
if sourceBlockID is not None:
if not isinstance(sourceBlockID, int):
ex = TypeError("Parameter 'sourceBlockID' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(sourceBlockID)}'.")
raise ex
elif sourceBlockID < 0:
ex = ValueError("Parameter 'sourceBlockID' is negative.")
ex.add_note(f"Got value '{sourceBlockID}'.")
raise ex
if destinationBlockID is not None:
if not isinstance(destinationBlockID, int):
ex = TypeError("Parameter 'destinationBlockID' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(destinationBlockID)}'.")
raise ex
elif destinationBlockID < 0:
ex = ValueError("Parameter 'destinationBlockID' is negative.")
ex.add_note(f"Got value '{destinationBlockID}'.")
raise ex
if parent is not None and not isinstance(parent, Line):
ex = TypeError("Parameter 'parent' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
self._parent = parent
self._count = count
self._throw = throw
self._fallthrough = fallthrough
self._sourceBlockID = sourceBlockID
self._destinationBlockID = destinationBlockID
if parent is not None:
parent._branches.append(self)
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[Line] = None) -> Self:
"""
Parse a branch from its JSON object.
:param record: The JSON object of the branch.
:param parent: Optional, the line the branch belongs to. Default: ``None``.
:returns: The branch.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
return cls(
record["count"],
record["throw"],
record["fallthrough"],
record.get("source_block_id"),
record.get("destination_block_id"),
parent=parent
)
@readonly
def Parent(self) -> Nullable[Line]:
"""
Read-only property to access the line the branch belongs to (:attr:`_parent`).
:returns: The line; ``None`` if the branch belongs to no line.
"""
return self._parent
@readonly
def Count(self) -> int:
"""
Read-only property to access the number of times the branch was taken (:attr:`_count`).
:returns: The count.
"""
return self._count
@readonly
def Throw(self) -> bool:
"""
Read-only property to access whether the branch is taken by an exception (:attr:`_throw`).
:returns: ``True``, if the branch is exceptional.
"""
return self._throw
@readonly
def Fallthrough(self) -> bool:
"""
Read-only property to access whether the branch falls through (:attr:`_fallthrough`).
:returns: ``True``, if the branch falls through.
"""
return self._fallthrough
@readonly
def SourceBlockID(self) -> Nullable[int]:
"""
Read-only property to access the ID of the basic block the branch starts at (:attr:`_sourceBlockID`).
:returns: The block's ID, unique within its function; ``None`` in format 1.
"""
return self._sourceBlockID
@readonly
def DestinationBlockID(self) -> Nullable[int]:
"""
Read-only property to access the ID of the basic block the branch leads to (:attr:`_destinationBlockID`).
:returns: The block's ID, unique within its function; ``None`` in format 1.
"""
return self._destinationBlockID
@export
class Call(metaclass=ExtendedType, slots=True):
"""
A ``call`` of a line - in format 2 -: from a basic block to the block continuing after the return.
"""
_parent: Nullable[Line] #: The line the call belongs to.
_sourceBlockID: int #: ID of the basic block the call is in.
_destinationBlockID: int #: ID of the basic block continuing after the return.
_returned: int #: Number of times the call returned.
def __init__(
self,
sourceBlockID: int,
destinationBlockID: int,
returned: int,
*,
parent: Nullable[Line] = None
) -> None:
"""
Initialize the call, and add it to the calls of its line.
:param sourceBlockID: ID of the basic block the call is in.
:param destinationBlockID: ID of the basic block continuing after the return.
:param returned: Number of times the call returned.
:param parent: Optional, the line the call belongs to; the call is appended to its calls.
Default: ``None``.
:raises ValueError: If parameter ``sourceBlockID`` is ``None``.
:raises TypeError: If parameter ``sourceBlockID`` isn't of type :class:`int`.
:raises ValueError: If parameter ``sourceBlockID`` is negative.
:raises ValueError: If parameter ``destinationBlockID`` is ``None``.
:raises TypeError: If parameter ``destinationBlockID`` isn't of type :class:`int`.
:raises ValueError: If parameter ``destinationBlockID`` is negative.
:raises ValueError: If parameter ``returned`` is ``None``.
:raises TypeError: If parameter ``returned`` isn't of type :class:`int`.
:raises ValueError: If parameter ``returned`` is negative.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Line`.
"""
if sourceBlockID is None:
raise ValueError("Parameter 'sourceBlockID' is None.")
elif not isinstance(sourceBlockID, int):
ex = TypeError("Parameter 'sourceBlockID' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(sourceBlockID)}'.")
raise ex
elif sourceBlockID < 0:
ex = ValueError("Parameter 'sourceBlockID' is negative.")
ex.add_note(f"Got value '{sourceBlockID}'.")
raise ex
if destinationBlockID is None:
raise ValueError("Parameter 'destinationBlockID' is None.")
elif not isinstance(destinationBlockID, int):
ex = TypeError("Parameter 'destinationBlockID' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(destinationBlockID)}'.")
raise ex
elif destinationBlockID < 0:
ex = ValueError("Parameter 'destinationBlockID' is negative.")
ex.add_note(f"Got value '{destinationBlockID}'.")
raise ex
if returned is None:
raise ValueError("Parameter 'returned' is None.")
elif not isinstance(returned, int):
ex = TypeError("Parameter 'returned' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(returned)}'.")
raise ex
elif returned < 0:
ex = ValueError("Parameter 'returned' is negative.")
ex.add_note(f"Got value '{returned}'.")
raise ex
if parent is not None and not isinstance(parent, Line):
ex = TypeError("Parameter 'parent' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
self._parent = parent
self._sourceBlockID = sourceBlockID
self._destinationBlockID = destinationBlockID
self._returned = returned
if parent is not None:
parent._calls.append(self)
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[Line] = None) -> Self:
"""
Parse a call from its JSON object.
:param record: The JSON object of the call.
:param parent: Optional, the line the call belongs to. Default: ``None``.
:returns: The call.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
return cls(record["source_block_id"], record["destination_block_id"], record["returned"], parent=parent)
@readonly
def Parent(self) -> Nullable[Line]:
"""
Read-only property to access the line the call belongs to (:attr:`_parent`).
:returns: The line; ``None`` if the call belongs to no line.
"""
return self._parent
@readonly
def SourceBlockID(self) -> int:
"""
Read-only property to access the ID of the basic block the call is in (:attr:`_sourceBlockID`).
:returns: The block's ID, unique within its function.
"""
return self._sourceBlockID
@readonly
def DestinationBlockID(self) -> int:
"""
Read-only property to access the ID of the basic block continuing after the return (:attr:`_destinationBlockID`).
:returns: The block's ID, unique within its function.
"""
return self._destinationBlockID
@readonly
def Returned(self) -> int:
"""
Read-only property to access the number of times the call returned (:attr:`_returned`).
:returns: The count; how often the call was made is the line's count.
"""
return self._returned
@export
class Condition(metaclass=ExtendedType, slots=True):
"""
A ``condition`` of a line - in format 2, with ``gcc -fcondition-coverage`` -: the condition outcomes of a boolean
expression (MC/DC).
"""
_parent: Nullable[Line] #: The line the condition belongs to.
_count: int #: Number of condition outcomes: twice the number of terms.
_covered: int #: Number of covered condition outcomes.
_notCoveredTrue: list[int] #: The terms, by index, never seen as true.
_notCoveredFalse: list[int] #: The terms, by index, never seen as false.
def __init__(
self,
count: int,
covered: int,
notCoveredTrue: Nullable[Iterable[int]] = None,
notCoveredFalse: Nullable[Iterable[int]] = None,
*,
parent: Nullable[Line] = None
) -> None:
"""
Initialize the condition, and add it to the conditions of its line.
:param count: Number of condition outcomes: twice the number of terms.
:param covered: Number of covered condition outcomes.
:param notCoveredTrue: Optional, the terms, by index, never seen as true. Default: none.
:param notCoveredFalse: Optional, the terms, by index, never seen as false. Default: none.
:param parent: Optional, the line the condition belongs to; the condition is appended to its conditions.
Default: ``None``.
:raises ValueError: If parameter ``count`` is ``None``.
:raises TypeError: If parameter ``count`` isn't of type :class:`int`.
:raises ValueError: If parameter ``count`` is negative.
:raises ValueError: If parameter ``covered`` is ``None``.
:raises TypeError: If parameter ``covered`` isn't of type :class:`int`.
:raises ValueError: If parameter ``covered`` is negative.
:raises TypeError: If parameter ``notCoveredTrue`` isn't iterable.
:raises TypeError: If parameter ``notCoveredTrue`` contains an element not of type :class:`int`.
:raises TypeError: If parameter ``notCoveredFalse`` isn't iterable.
:raises TypeError: If parameter ``notCoveredFalse`` contains an element not of type :class:`int`.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Line`.
"""
if count is None:
raise ValueError("Parameter 'count' is None.")
elif not isinstance(count, int):
ex = TypeError("Parameter 'count' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(count)}'.")
raise ex
elif count < 0:
ex = ValueError("Parameter 'count' is negative.")
ex.add_note(f"Got value '{count}'.")
raise ex
if covered is None:
raise ValueError("Parameter 'covered' is None.")
elif not isinstance(covered, int):
ex = TypeError("Parameter 'covered' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(covered)}'.")
raise ex
elif covered < 0:
ex = ValueError("Parameter 'covered' is negative.")
ex.add_note(f"Got value '{covered}'.")
raise ex
notCoveredTrueList: list[int] = []
if notCoveredTrue is not None:
if not isinstance(notCoveredTrue, Iterable):
ex = TypeError("Parameter 'notCoveredTrue' is not iterable.")
ex.add_note(f"Got type '{getFullyQualifiedName(notCoveredTrue)}'.")
raise ex
for term in notCoveredTrue:
if not isinstance(term, int):
ex = TypeError("Parameter 'notCoveredTrue' contains an element not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(term)}'.")
raise ex
notCoveredTrueList.append(term)
notCoveredFalseList: list[int] = []
if notCoveredFalse is not None:
if not isinstance(notCoveredFalse, Iterable):
ex = TypeError("Parameter 'notCoveredFalse' is not iterable.")
ex.add_note(f"Got type '{getFullyQualifiedName(notCoveredFalse)}'.")
raise ex
for term in notCoveredFalse:
if not isinstance(term, int):
ex = TypeError("Parameter 'notCoveredFalse' contains an element not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(term)}'.")
raise ex
notCoveredFalseList.append(term)
if parent is not None and not isinstance(parent, Line):
ex = TypeError("Parameter 'parent' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
self._parent = parent
self._count = count
self._covered = covered
self._notCoveredTrue = notCoveredTrueList
self._notCoveredFalse = notCoveredFalseList
if parent is not None:
parent._conditions.append(self)
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[Line] = None) -> Self:
"""
Parse a condition from its JSON object.
:param record: The JSON object of the condition.
:param parent: Optional, the line the condition belongs to. Default: ``None``.
:returns: The condition.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
return cls(
record["count"], record["covered"], record["not_covered_true"], record["not_covered_false"], parent=parent
)
@readonly
def Parent(self) -> Nullable[Line]:
"""
Read-only property to access the line the condition belongs to (:attr:`_parent`).
:returns: The line; ``None`` if the condition belongs to no line.
"""
return self._parent
@readonly
def Count(self) -> int:
"""
Read-only property to access the number of condition outcomes (:attr:`_count`).
:returns: The number of outcomes: twice the number of terms.
"""
return self._count
@readonly
def Covered(self) -> int:
"""
Read-only property to access the number of covered condition outcomes (:attr:`_covered`).
:returns: The number of covered outcomes.
"""
return self._covered
@readonly
def NotCoveredTrue(self) -> list[int]:
"""
Read-only property to access the terms never seen as true (:attr:`_notCoveredTrue`).
:returns: The terms' indices.
"""
return self._notCoveredTrue
@readonly
def NotCoveredFalse(self) -> list[int]:
"""
Read-only property to access the terms never seen as false (:attr:`_notCoveredFalse`).
:returns: The terms' indices.
"""
return self._notCoveredFalse
@export
class Line(metaclass=ExtendedType, slots=True):
"""
A ``line`` of a file: how often it ran, its basic blocks, branches, calls and conditions.
"""
_parent: Nullable[File] #: The file the line belongs to.
_lineNumber: int #: Line number, counted from 1.
_functionName: Nullable[str] #: Mangled name of the function the line belongs to, if the report says.
_count: int #: Number of times the line ran.
_unexecutedBlock: bool #: Whether a basic block, not only reached by exceptions, never ran.
_blockIDs: list[int] #: IDs of the basic blocks ending on this line, in format 2.
_branches: list[Branch] #: The branches.
_calls: list[Call] #: The calls, in format 2.
_conditions: list[Condition] #: The conditions, in format 2.
def __init__(
self,
lineNumber: int,
count: int,
unexecutedBlock: bool,
functionName: Nullable[str] = None,
blockIDs: Nullable[Iterable[int]] = None,
*,
parent: Nullable[File] = None
) -> None:
"""
Initialize the line, and add it to the lines of its file.
Its branches, calls and conditions are added by creating them with this line as their parent.
:param lineNumber: Line number, counted from 1.
:param count: Number of times the line ran.
:param unexecutedBlock: Whether a basic block of the line, not only reached by exceptions, never ran.
:param functionName: Optional, mangled name of the function the line belongs to. Default: ``None``.
:param blockIDs: Optional, IDs of the basic blocks ending on this line. Default: none.
:param parent: Optional, the file the line belongs to; the line is appended to its lines.
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 ValueError: If parameter ``count`` is ``None``.
:raises TypeError: If parameter ``count`` isn't of type :class:`int`.
:raises ValueError: If parameter ``count`` is negative.
:raises ValueError: If parameter ``unexecutedBlock`` is ``None``.
:raises TypeError: If parameter ``unexecutedBlock`` isn't of type :class:`bool`.
:raises TypeError: If parameter ``functionName`` isn't of type :class:`str`.
:raises TypeError: If parameter ``blockIDs`` isn't iterable.
:raises TypeError: If parameter ``blockIDs`` contains an element not of type :class:`int`.
:raises TypeError: If parameter ``parent`` isn't of type :class:`File`.
"""
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
if count is None:
raise ValueError("Parameter 'count' is None.")
elif not isinstance(count, int):
ex = TypeError("Parameter 'count' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(count)}'.")
raise ex
elif count < 0:
ex = ValueError("Parameter 'count' is negative.")
ex.add_note(f"Got value '{count}'.")
raise ex
if unexecutedBlock is None:
raise ValueError("Parameter 'unexecutedBlock' is None.")
elif not isinstance(unexecutedBlock, bool):
ex = TypeError("Parameter 'unexecutedBlock' is not of type 'bool'.")
ex.add_note(f"Got type '{getFullyQualifiedName(unexecutedBlock)}'.")
raise ex
if functionName is not None and not isinstance(functionName, str):
ex = TypeError("Parameter 'functionName' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(functionName)}'.")
raise ex
blockIDList: list[int] = []
if blockIDs is not None:
if not isinstance(blockIDs, Iterable):
ex = TypeError("Parameter 'blockIDs' is not iterable.")
ex.add_note(f"Got type '{getFullyQualifiedName(blockIDs)}'.")
raise ex
for blockID in blockIDs:
if not isinstance(blockID, int):
ex = TypeError("Parameter 'blockIDs' contains an element not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(blockID)}'.")
raise ex
blockIDList.append(blockID)
if parent is not None and not isinstance(parent, File):
ex = TypeError("Parameter 'parent' is not of type 'File'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
self._parent = parent
self._lineNumber = lineNumber
self._functionName = functionName
self._count = count
self._unexecutedBlock = unexecutedBlock
self._blockIDs = blockIDList
self._branches = []
self._calls = []
self._conditions = []
if parent is not None:
parent._lines.append(self)
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[File] = None) -> Self:
"""
Parse a line, its branches, calls and conditions from its JSON object.
:param record: The JSON object of the line.
:param parent: Optional, the file the line belongs to. Default: ``None``.
:returns: The line.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
line = cls(
record["line_number"],
record["count"],
record["unexecuted_block"],
record.get("function_name"),
record.get("block_ids"),
parent=parent
)
for branch in record["branches"]:
Branch.Parse(branch, parent=line)
for call in record.get("calls", []):
Call.Parse(call, parent=line)
for condition in record.get("conditions", []):
Condition.Parse(condition, parent=line)
return line
@readonly
def Parent(self) -> Nullable[File]:
"""
Read-only property to access the file the line belongs to (:attr:`_parent`).
:returns: The file; ``None`` if the line belongs to no 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 FunctionName(self) -> Nullable[str]:
"""
Read-only property to access the mangled name of the function the line belongs to (:attr:`_functionName`).
:returns: The function's name, or ``None`` for a line of inlined statements.
"""
return self._functionName
@readonly
def Count(self) -> int:
"""
Read-only property to access the number of times the line ran (:attr:`_count`).
:returns: The count.
"""
return self._count
@readonly
def UnexecutedBlock(self) -> bool:
"""
Read-only property to access whether a basic block of the line never ran (:attr:`_unexecutedBlock`).
A block only reached by exceptions doesn't count.
:returns: ``True``, if not every statement of the line ran.
"""
return self._unexecutedBlock
@readonly
def BlockIDs(self) -> list[int]:
"""
Read-only property to access the IDs of the basic blocks ending on this line (:attr:`_blockIDs`).
:returns: The blocks' IDs, unique within the function; empty in format 1.
"""
return self._blockIDs
@readonly
def Branches(self) -> list[Branch]:
"""
Read-only property to access the branches (:attr:`_branches`).
:returns: The branches; empty, if gcov ran without ``--branch-probabilities``.
"""
return self._branches
@readonly
def Calls(self) -> list[Call]:
"""
Read-only property to access the calls (:attr:`_calls`).
:returns: The calls; empty in format 1, or if gcov ran without ``--branch-probabilities``.
"""
return self._calls
@readonly
def Conditions(self) -> list[Condition]:
"""
Read-only property to access the conditions (:attr:`_conditions`).
:returns: The conditions; empty in format 1, or if gcov ran without ``--conditions``.
"""
return self._conditions
@export
class Function(metaclass=ExtendedType, slots=True):
"""
A ``function`` of a file: its names, its position, its basic blocks and how often it ran.
"""
_parent: Nullable[File] #: The file the function belongs to.
_name: str #: Name of the function, mangled.
_demangledName: str #: Name of the function, demangled.
_startLine: int #: The function's first line.
_startColumn: int #: The function's first column.
_endLine: int #: The function's last line.
_endColumn: int #: The function's last column.
_blocks: int #: Number of basic blocks.
_blocksExecuted: int #: Number of executed basic blocks.
_executionCount: int #: Number of times the function ran.
def __init__(
self,
name: str,
demangledName: str,
startLine: int,
startColumn: int,
endLine: int,
endColumn: int,
blocks: int,
blocksExecuted: int,
executionCount: int,
*,
parent: Nullable[File] = None
) -> None:
"""
Initialize the function, and add it to the functions of its file.
:param name: Name of the function, mangled.
:param demangledName: Name of the function, demangled.
:param startLine: The function's first line.
:param startColumn: The function's first column.
:param endLine: The function's last line.
:param endColumn: The function's last column.
:param blocks: Number of basic blocks.
:param blocksExecuted: Number of executed basic blocks.
:param executionCount: Number of times the function ran.
:param parent: Optional, the file the function belongs to; the function is added to its functions 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 ValueError: If parameter ``demangledName`` is ``None``.
:raises TypeError: If parameter ``demangledName`` isn't of type :class:`str`.
:raises ValueError: If parameter ``demangledName`` is empty.
:raises ValueError: If parameter ``startLine`` is ``None``.
:raises TypeError: If parameter ``startLine`` isn't of type :class:`int`.
:raises ValueError: If parameter ``startLine`` is negative.
:raises ValueError: If parameter ``startColumn`` is ``None``.
:raises TypeError: If parameter ``startColumn`` isn't of type :class:`int`.
:raises ValueError: If parameter ``startColumn`` is negative.
:raises ValueError: If parameter ``endLine`` is ``None``.
:raises TypeError: If parameter ``endLine`` isn't of type :class:`int`.
:raises ValueError: If parameter ``endLine`` is negative.
:raises ValueError: If parameter ``endColumn`` is ``None``.
:raises TypeError: If parameter ``endColumn`` isn't of type :class:`int`.
:raises ValueError: If parameter ``endColumn`` is negative.
:raises ValueError: If parameter ``blocks`` is ``None``.
:raises TypeError: If parameter ``blocks`` isn't of type :class:`int`.
:raises ValueError: If parameter ``blocks`` is negative.
:raises ValueError: If parameter ``blocksExecuted`` is ``None``.
:raises TypeError: If parameter ``blocksExecuted`` isn't of type :class:`int`.
:raises ValueError: If parameter ``blocksExecuted`` is negative.
:raises ValueError: If parameter ``executionCount`` is ``None``.
:raises TypeError: If parameter ``executionCount`` isn't of type :class:`int`.
:raises ValueError: If parameter ``executionCount`` is negative.
:raises TypeError: If parameter ``parent`` isn't of type :class:`File`.
:raises ValueError: If parameter ``parent`` contains a function of the same name already.
"""
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
elif name == "":
raise ValueError("Parameter 'name' is empty.")
if demangledName is None:
raise ValueError("Parameter 'demangledName' is None.")
elif not isinstance(demangledName, str):
ex = TypeError("Parameter 'demangledName' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(demangledName)}'.")
raise ex
elif demangledName == "":
raise ValueError("Parameter 'demangledName' is empty.")
if startLine is None:
raise ValueError("Parameter 'startLine' is None.")
elif not isinstance(startLine, int):
ex = TypeError("Parameter 'startLine' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(startLine)}'.")
raise ex
elif startLine < 0:
ex = ValueError("Parameter 'startLine' is negative.")
ex.add_note(f"Got value '{startLine}'.")
raise ex
if startColumn is None:
raise ValueError("Parameter 'startColumn' is None.")
elif not isinstance(startColumn, int):
ex = TypeError("Parameter 'startColumn' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(startColumn)}'.")
raise ex
elif startColumn < 0:
ex = ValueError("Parameter 'startColumn' is negative.")
ex.add_note(f"Got value '{startColumn}'.")
raise ex
if endLine is None:
raise ValueError("Parameter 'endLine' is None.")
elif not isinstance(endLine, int):
ex = TypeError("Parameter 'endLine' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(endLine)}'.")
raise ex
elif endLine < 0:
ex = ValueError("Parameter 'endLine' is negative.")
ex.add_note(f"Got value '{endLine}'.")
raise ex
if endColumn is None:
raise ValueError("Parameter 'endColumn' is None.")
elif not isinstance(endColumn, int):
ex = TypeError("Parameter 'endColumn' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(endColumn)}'.")
raise ex
elif endColumn < 0:
ex = ValueError("Parameter 'endColumn' is negative.")
ex.add_note(f"Got value '{endColumn}'.")
raise ex
if blocks is None:
raise ValueError("Parameter 'blocks' is None.")
elif not isinstance(blocks, int):
ex = TypeError("Parameter 'blocks' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(blocks)}'.")
raise ex
elif blocks < 0:
ex = ValueError("Parameter 'blocks' is negative.")
ex.add_note(f"Got value '{blocks}'.")
raise ex
if blocksExecuted is None:
raise ValueError("Parameter 'blocksExecuted' is None.")
elif not isinstance(blocksExecuted, int):
ex = TypeError("Parameter 'blocksExecuted' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(blocksExecuted)}'.")
raise ex
elif blocksExecuted < 0:
ex = ValueError("Parameter 'blocksExecuted' is negative.")
ex.add_note(f"Got value '{blocksExecuted}'.")
raise ex
if executionCount is None:
raise ValueError("Parameter 'executionCount' is None.")
elif not isinstance(executionCount, int):
ex = TypeError("Parameter 'executionCount' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(executionCount)}'.")
raise ex
elif executionCount < 0:
ex = ValueError("Parameter 'executionCount' is negative.")
ex.add_note(f"Got value '{executionCount}'.")
raise ex
if parent is not None:
if not isinstance(parent, File):
ex = TypeError("Parameter 'parent' is not of type 'File'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
elif name in parent._functions:
raise ValueError(f"Parameter 'parent' contains function '{name}' already.")
self._parent = parent
self._name = name
self._demangledName = demangledName
self._startLine = startLine
self._startColumn = startColumn
self._endLine = endLine
self._endColumn = endColumn
self._blocks = blocks
self._blocksExecuted = blocksExecuted
self._executionCount = executionCount
if parent is not None:
parent._functions[self._name] = self
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[File] = None) -> Self:
"""
Parse a function from its JSON object.
:param record: The JSON object of the function.
:param parent: Optional, the file the function belongs to. Default: ``None``.
:returns: The function.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
return cls(
record["name"],
record["demangled_name"],
record["start_line"],
record["start_column"],
record["end_line"],
record["end_column"],
record["blocks"],
record["blocks_executed"],
record["execution_count"],
parent=parent
)
@readonly
def Parent(self) -> Nullable[File]:
"""
Read-only property to access the file the function belongs to (:attr:`_parent`).
:returns: The file; ``None`` if the function belongs to no file.
"""
return self._parent
@readonly
def Name(self) -> str:
"""
Read-only property to access the mangled name of the function (:attr:`_name`).
The method ``Containers::Stack::Pop()`` is mangled to ``_ZN10Containers5Stack3PopEv``, a C function keeps its name.
:returns: The mangled name.
"""
return self._name
@readonly
def DemangledName(self) -> str:
"""
Read-only property to access the demangled name of the function (:attr:`_demangledName`).
The demangled name of ``_ZN10Containers5Stack3PopEv`` is ``Containers::Stack::Pop()``.
:returns: The demangled name.
"""
return self._demangledName
@readonly
def StartLine(self) -> int:
"""
Read-only property to access the function's first line (:attr:`_startLine`).
:returns: The line number.
"""
return self._startLine
@readonly
def StartColumn(self) -> int:
"""
Read-only property to access the function's first column (:attr:`_startColumn`).
:returns: The column number, counted from 1.
"""
return self._startColumn
@readonly
def EndLine(self) -> int:
"""
Read-only property to access the function's last line (:attr:`_endLine`).
:returns: The line number.
"""
return self._endLine
@readonly
def EndColumn(self) -> int:
"""
Read-only property to access the function's last column (:attr:`_endColumn`).
:returns: The column number, counted from 1.
"""
return self._endColumn
@readonly
def Blocks(self) -> int:
"""
Read-only property to access the number of basic blocks (:attr:`_blocks`).
:returns: The number of blocks.
"""
return self._blocks
@readonly
def BlocksExecuted(self) -> int:
"""
Read-only property to access the number of executed basic blocks (:attr:`_blocksExecuted`).
:returns: The number of executed blocks.
"""
return self._blocksExecuted
@readonly
def ExecutionCount(self) -> int:
"""
Read-only property to access the number of times the function ran (:attr:`_executionCount`).
:returns: The count.
"""
return self._executionCount
@export
class File(metaclass=ExtendedType, slots=True):
"""
A source ``file`` of a data file: its functions and lines.
A line several functions share - e.g. the instantiations of a template - is listed once per function.
"""
_parent: Nullable[DataFile] #: The data file the file belongs to.
_path: _Path #: The file's path, as the compiler named it.
_functions: dict[str, Function] #: The functions, by mangled name.
_lines: list[Line] #: The executable lines, in order; a line of several functions once per function.
def __init__(self, path: Path, *, parent: Nullable[DataFile] = None) -> None:
"""
Initialize the file, and add it to the files of its data file.
Its functions and lines are added by creating them with this file as their parent.
:param path: The file's path, as the compiler named it.
:param parent: Optional, the data file the file belongs to; the file is added to its files by :attr:`Path`.
Default: ``None``.
:raises ValueError: If parameter ``path`` is ``None``.
:raises TypeError: If parameter ``path`` isn't of type :class:`~pathlib.Path`.
:raises TypeError: If parameter ``parent`` isn't of type :class:`DataFile`.
:raises ValueError: If parameter ``parent`` contains a file of the same path already.
"""
if path is None:
raise ValueError("Parameter 'path' is None.")
elif not isinstance(path, Path):
ex = TypeError("Parameter 'path' is not of type 'Path'.")
ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
raise ex
if parent is not None:
if not isinstance(parent, DataFile):
ex = TypeError("Parameter 'parent' is not of type 'DataFile'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
elif path in parent._files:
raise ValueError(f"Parameter 'parent' contains file '{path.as_posix()}' already.")
self._parent = parent
self._path = path
self._functions = {}
self._lines = []
if parent is not None:
parent._files[self._path] = self
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[DataFile] = None) -> Self:
"""
Parse a file, its functions and lines from its JSON object.
A backslash in the path - as a report written on Windows has them - separates directories.
:param record: The JSON object of the file.
:param parent: Optional, the data file the file belongs to. Default: ``None``.
:returns: The file.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
:raises CodeCoverageError: If the file names a function twice.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
file = cls(Path(record["file"].replace("\\", "/")), parent=parent)
for function in record["functions"]:
if (name := function["name"]) in file._functions:
raise CodeCoverageError(f"gcov source file '{file._path.as_posix()}' names function '{name}' twice.")
Function.Parse(function, parent=file)
for line in record["lines"]:
Line.Parse(line, parent=file)
return file
@readonly
def Parent(self) -> Nullable[DataFile]:
"""
Read-only property to access the data file the file belongs to (:attr:`_parent`).
:returns: The data file; ``None`` if the file belongs to no data file.
"""
return self._parent
@readonly
def Path(self) -> Path:
"""
Read-only property to access the file's path (:attr:`_path`).
:returns: The path, relative to the directory the compiler ran in, unless absolute.
"""
return self._path
@readonly
def Functions(self) -> dict[str, Function]:
"""
Read-only property to access the functions (:attr:`_functions`).
:returns: The functions, by mangled name.
"""
return self._functions
@readonly
def Lines(self) -> list[Line]:
"""
Read-only property to access the executable lines (:attr:`_lines`).
:returns: The lines; a line several functions share is listed once per function.
"""
return self._lines
@export
class DataFile(metaclass=ExtendedType, slots=True):
"""
The coverage measured in a data file (GCDA): the versions of the format and of GCC, and the source files.
"""
_parent: Nullable[Coverage] #: The report the data file belongs to.
_path: _Path #: Path of the data file, as gcov was called with it.
_formatVersion: _FormatVersion #: Version of the report format.
_gccVersion: SemanticVersion #: Version of GCC.
_currentWorkingDirectory: Nullable[_Path] #: The directory the compiler ran in, if the report says.
_files: dict[_Path, File] #: The source files, by path.
def __init__(
self,
path: Path,
formatVersion: FormatVersion,
gccVersion: SemanticVersion,
currentWorkingDirectory: Nullable[Path] = None,
*,
parent: Nullable[Coverage] = None
) -> None:
"""
Initialize the data file, and add it to the data files of its report.
Its source files are added by creating them with this data file as their parent.
:param path: Path of the data file, as gcov was called with it.
:param formatVersion: Version of the report format.
:param gccVersion: Version of GCC.
:param currentWorkingDirectory: Optional, the directory the compiler ran in. Default: ``None``.
:param parent: Optional, the report the data file belongs to; the data file is appended to its
data files. Default: ``None``.
:raises ValueError: If parameter ``path`` is ``None``.
:raises TypeError: If parameter ``path`` isn't of type :class:`~pathlib.Path`.
:raises ValueError: If parameter ``formatVersion`` is ``None``.
:raises TypeError: If parameter ``formatVersion`` isn't of type :class:`FormatVersion`.
:raises ValueError: If parameter ``gccVersion`` is ``None``.
:raises TypeError: If parameter ``gccVersion`` isn't of type
:class:`~pyTooling.Versioning.SemanticVersion`.
:raises TypeError: If parameter ``currentWorkingDirectory`` isn't of type :class:`~pathlib.Path`.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Coverage`.
"""
if path is None:
raise ValueError("Parameter 'path' is None.")
elif not isinstance(path, Path):
ex = TypeError("Parameter 'path' is not of type 'Path'.")
ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
raise ex
if formatVersion is None:
raise ValueError("Parameter 'formatVersion' is None.")
elif not isinstance(formatVersion, FormatVersion):
ex = TypeError("Parameter 'formatVersion' is not of type 'FormatVersion'.")
ex.add_note(f"Got type '{getFullyQualifiedName(formatVersion)}'.")
raise ex
if gccVersion is None:
raise ValueError("Parameter 'gccVersion' is None.")
elif not isinstance(gccVersion, SemanticVersion):
ex = TypeError("Parameter 'gccVersion' is not of type 'SemanticVersion'.")
ex.add_note(f"Got type '{getFullyQualifiedName(gccVersion)}'.")
raise ex
if currentWorkingDirectory is not None and not isinstance(currentWorkingDirectory, Path):
ex = TypeError("Parameter 'currentWorkingDirectory' is not of type 'Path'.")
ex.add_note(f"Got type '{getFullyQualifiedName(currentWorkingDirectory)}'.")
raise ex
if parent is not None and not isinstance(parent, Coverage):
ex = TypeError("Parameter 'parent' is not of type 'Coverage'.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
self._parent = parent
self._path = path
self._formatVersion = formatVersion
self._gccVersion = gccVersion
self._currentWorkingDirectory = currentWorkingDirectory
self._files = {}
if parent is not None:
parent._dataFiles.append(self)
@classmethod
def Parse(cls, record: dict[str, Any], *, parent: Nullable[Coverage] = None) -> Self:
"""
Parse a data file and its source files from its JSON object.
The format version is converted by :meth:`FormatVersion.Parse`; a development build of GCC states its date and
phase behind its version, e.g. ``15.0.1 20250418 (experimental)``. A backslash in a path - as a report written on
Windows has them - separates directories.
:param record: The JSON object of the data file: a report's root object.
:param parent: Optional, the report the data file belongs to. Default: ``None``.
:returns: The data file.
:raises ValueError: If parameter ``record`` is ``None``.
:raises TypeError: If parameter ``record`` isn't of type :class:`dict`.
:raises CodeCoverageError: If the data file names a source file twice.
"""
if record is None:
raise ValueError("Parameter 'record' is None.")
elif not isinstance(record, dict):
ex = TypeError("Parameter 'record' is not of type 'dict'.")
ex.add_note(f"Got type '{getFullyQualifiedName(record)}'.")
raise ex
directory = record.get("current_working_directory")
dataFile = cls(
Path(record["data_file"].replace("\\", "/")),
FormatVersion.Parse(record["format_version"]),
SemanticVersion.Parse(record["gcc_version"].split(" ", 1)[0]),
Path(directory.replace("\\", "/")) if directory is not None else None,
parent=parent
)
for file in record["files"]:
if (path := Path(file["file"].replace("\\", "/"))) in dataFile._files:
raise CodeCoverageError(
f"gcov data file '{dataFile._path.as_posix()}' names source file '{path.as_posix()}' twice."
)
File.Parse(file, parent=dataFile)
return dataFile
@readonly
def Parent(self) -> Nullable[Coverage]:
"""
Read-only property to access the report the data file belongs to (:attr:`_parent`).
:returns: The report; ``None`` if the data file belongs to no report.
"""
return self._parent
@readonly
def Path(self) -> Path:
"""
Read-only property to access the path of the data file (:attr:`_path`).
It is the path gcov was called with, e.g. ``main.c`` for ``gcov --json-format main.c``.
:returns: The path, as gcov was called with it.
"""
return self._path
@readonly
def FormatVersion(self) -> FormatVersion:
"""
Read-only property to access the version of the report format (:attr:`_formatVersion`).
:returns: The format version.
"""
return self._formatVersion
@readonly
def GCCVersion(self) -> SemanticVersion:
"""
Read-only property to access the version of GCC (:attr:`_gccVersion`).
A development build of GCC states its date and phase behind the version, e.g. ``15.0.1 20250418 (experimental)``;
they aren't kept.
:returns: The version.
"""
return self._gccVersion
@readonly
def CurrentWorkingDirectory(self) -> Nullable[Path]:
"""
Read-only property to access the directory the compiler ran in (:attr:`_currentWorkingDirectory`).
:returns: The directory, on the machine the code was compiled on, or ``None`` if the report doesn't say.
"""
return self._currentWorkingDirectory
@readonly
def Files(self) -> dict[Path, File]:
"""
Read-only property to access the source files (:attr:`_files`).
:returns: The files, by path.
"""
return self._files
@export
class Coverage(metaclass=ExtendedType, mixin=True):
"""
The content of a report file: the data files.
The root of the format's model: a data file names it as its parent.
"""
_dataFiles: list[DataFile] #: The data files, in the order the report lists them.
def __init__(self) -> None:
"""
Initialize an empty report.
"""
self._dataFiles = []
@readonly
def DataFiles(self) -> list[DataFile]:
"""
Read-only property to access the data files (:attr:`_dataFiles`).
:returns: The data files: one of a :file:`*.gcov.json.gz` file; one per line of gcov's standard output.
"""
return self._dataFiles
@export
class Document(cc_Document, Coverage):
"""
A gcov JSON code coverage report: read into the format's model, and converted to the common model.
"""
_jsonDocuments: Nullable[list[dict[str, Any]]] #: The parsed and validated JSON objects, after :meth:`Analyze`.
def __init__(self, jsonReportFile: Path, analyzeAndConvert: bool = False) -> None:
"""
Initialize the report, and optionally read it.
:param jsonReportFile: Path to the JSON file, gzip-compressed or plain.
:param analyzeAndConvert: Optional, if true, analyze the file and convert its content. Default: ``False``.
"""
super().__init__(jsonReportFile)
Coverage.__init__(self)
self._jsonDocuments = None
if analyzeAndConvert:
self.Analyze()
self.Convert()
def Analyze(self) -> None:
"""
Read the file - decompressing it, if gzip-compressed -, parse its JSON objects and validate each against the JSON
Schema of the format version it states (:data:`SCHEMAS`).
:raises CodeCoverageError: If the file doesn't exist.
:raises CodeCoverageError: If the file can't be read.
:raises CodeCoverageError: If the file is gzip-compressed, but corrupt.
:raises CodeCoverageError: If the file isn't valid JSON.
:raises CodeCoverageError: If the file holds no JSON object.
:raises CodeCoverageError: If a JSON object states no supported format version.
:raises CodeCoverageError: If a JSON Schema can't be read.
:raises CodeCoverageError: If a JSON object isn't valid according to the JSON Schema of its format version.
"""
if not self._path.exists():
raise CodeCoverageError(f"gcov 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 gcov report file '{self._path}'.") from ex
if content[:2] == b"\x1f\x8b":
try:
content = decompress(content)
except (BadGzipFile, EOFError, ZLibError) as ex:
raise CodeCoverageError(f"gzip error in gcov report file '{self._path}'.") from ex
# gcov's standard output holds one JSON object per data file
jsonDocuments = []
try:
text = content.decode("utf-8")
decoder = JSONDecoder()
nonWhitespace = re_compile(r"\S")
position = 0
while (match := nonWhitespace.search(text, position)) is not None:
jsonDocument, position = decoder.raw_decode(text, match.start())
jsonDocuments.append(jsonDocument)
except (UnicodeDecodeError, JSONDecodeError) as ex:
raise CodeCoverageError(f"JSON syntax error in gcov report file '{self._path}'.") from ex
if len(jsonDocuments) == 0:
raise CodeCoverageError(f"gcov report file '{self._path}' holds no JSON object.")
# a note's path is prefixed by the object's index, if the file holds several
validators: dict[FormatVersion, Draft202012Validator] = {}
for index, jsonDocument in enumerate(jsonDocuments):
prefix = f"[{index}]" if len(jsonDocuments) > 1 else ""
version = jsonDocument.get("format_version") if isinstance(jsonDocument, dict) else None
try:
formatVersion = FormatVersion.Parse(version)
except (ValueError, TypeError) as cause:
ex = CodeCoverageError(f"gcov report file '{self._path}' states an unsupported format version.")
got = f"value '{version}'" if version is not None else "no value"
ex.add_note(f"Got {got} at '{prefix}/format_version'.")
ex.add_note(f"Supported format versions: {', '.join(str(member.value) for member in FormatVersion)}.")
raise ex from cause
schemaFile = SCHEMAS[formatVersion]
if (validator := validators.get(formatVersion)) is None:
try:
schema = loads(readResourceFile(Resources, schemaFile))
except (ToolingException, JSONDecodeError) as ex:
raise CodeCoverageError(f"Couldn't read JSON Schema '{schemaFile}' from package resources.") from ex
validator = validators[formatVersion] = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(jsonDocument), key=lambda error: list(error.path))
if len(errors) > 0:
ex = CodeCoverageError(f"Validation error for '{self._path}' using JSON Schema '{schemaFile}'.")
for error in errors:
ex.add_note(f"{prefix}/{'/'.join(str(part) for part in error.path)}: {error.message}")
raise ex
self._jsonDocuments = jsonDocuments
self._analysisDuration = sw.Duration
def Convert(self) -> None:
"""
Convert the parsed and validated JSON objects to the format's model.
:raises CodeCoverageError: If the JSON file was not analyzed before. |br|
Call 'Document.Analyze()' or create the document using
'Document(path, analyzeAndConvert=True)'.
:raises CodeCoverageError: If a data file names a source file twice.
:raises CodeCoverageError: If a source file names a function twice.
"""
if self._jsonDocuments is None:
ex = CodeCoverageError(f"gcov report file '{self._path}' needs to be read and analyzed by a JSON parser.")
ex.add_note("Call 'Document.Analyze()' or create the document using 'Document(path, analyzeAndConvert=True)'.")
raise ex
with Stopwatch() as sw:
for jsonDocument in self._jsonDocuments:
DataFile.Parse(jsonDocument, parent=self)
self._conversionDuration = sw.Duration
def ToCoverageSummary(self) -> CoverageSummary:
"""
Convert the format's model to the common model, and aggregate it.
A source file several data files state - e.g. a header - becomes one file: the counts of its lines and branches,
and of its functions, are added. The directories the compiler ran in become the source directories.
:returns: The report's root of the common model, named after the report file without the
extensions ``.gcov``, ``.json`` and ``.gz``.
:raises CodeCoverageError: If a file's path runs through another file.
"""
name = self._path.name.removesuffix(".gz").removesuffix(".json").removesuffix(".gcov")
directories = {
dataFile._currentWorkingDirectory for dataFile in self._dataFiles if dataFile._currentWorkingDirectory is not None
}
summary = CoverageSummary(name if name != "" else self._path.name, sourceDirectories=sorted(directories))
# per file of the common model: the counts of its lines, of its lines' branches, and of its functions
lineCounts: dict[cc_File, dict[int, int]] = {}
branchCounts: dict[cc_File, dict[int, dict[tuple[Nullable[str], int, Nullable[int], Nullable[int]], int]]] = {}
functionCounts: dict[cc_File, dict[str, tuple[int, int, int]]] = {}
for dataFile in self._dataFiles:
for file in dataFile._files.values():
commonFile = summary.GetOrAddFile(file._path)
counts = lineCounts.setdefault(commonFile, {})
branches = branchCounts.setdefault(commonFile, {})
functions = functionCounts.setdefault(commonFile, {})
for line in file._lines:
counts[line._lineNumber] = counts.get(line._lineNumber, 0) + line._count
lineBranches = branches.setdefault(line._lineNumber, {})
for index, branch in enumerate(line._branches):
key = (line._functionName, index, branch._sourceBlockID, branch._destinationBlockID)
lineBranches[key] = lineBranches.get(key, 0) + branch._count
for function in file._functions.values():
startLine, endLine, count = functions.get(
function._demangledName, (function._startLine, function._endLine, 0)
)
functions[function._demangledName] = (startLine, endLine, count + function._executionCount)
for commonFile, counts in lineCounts.items():
for number in sorted(counts):
lineBranches = branchCounts[commonFile][number]
if counts[number] == 0:
status = LineCoverageStatus.Uncovered
elif 0 in lineBranches.values():
status = LineCoverageStatus.PartiallyCovered
else:
status = LineCoverageStatus.Covered
commonLine = cc_Line(number, status, counts[number], parent=commonFile)
for count in lineBranches.values():
cc_Branch(LineCoverageStatus.Covered if count > 0 else LineCoverageStatus.Uncovered, count, parent=commonLine)
lines = commonFile._lines
lastLineNumber = commonFile._lastLineNumber
sourceFile = cc_SourceFile(
commonFile.Path.as_posix(),
file=commonFile,
startLine=next(commonFile.IterateLines(), None),
endLine=lines[lastLineNumber] if lastLineNumber > 0 else None,
parent=summary
)
for functionName, (startLine, endLine, count) in functionCounts[commonFile].items():
numbers = [number for number in range(startLine, min(endLine, lastLineNumber) + 1) if lines[number] is not None]
cc_Function(
functionName,
file=commonFile,
startLine=lines[numbers[0]] if len(numbers) > 0 else None,
endLine=lines[numbers[-1]] if len(numbers) > 0 else None,
status=LineCoverageStatus.Covered if count > 0 else LineCoverageStatus.Uncovered,
coverageCount=count,
parent=sourceFile
)
summary.Aggregate()
return summary
|