# ==================================================================================================================== #
# _____ ____ _ _ ____ _ #
# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
# |_| |___/ |_| #
# ==================================================================================================================== #
# 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 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, \
Document as cc_Document, File as cc_File, Function as cc_Function, \
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
# 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.
[docs]
@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.
[docs]
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)
[docs]
@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
[docs]
@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.
[docs]
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)
[docs]
@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
[docs]
@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.
[docs]
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)
[docs]
@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
[docs]
@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.
[docs]
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)
[docs]
@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
[docs]
@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.
[docs]
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
[docs]
@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
[docs]
@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.
[docs]
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
[docs]
@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
[docs]
@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.
[docs]
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)
[docs]
@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
[docs]
@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.
[docs]
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
[docs]
@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`.
[docs]
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()
[docs]
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.")
from jsonschema import Draft202012Validator
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
[docs]
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
[docs]
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