Record each Swift coverage region's end line.

A region was only (start line, count), so a span of lines 4-5 with count 1
never marked line 5 covered. Regions are now (start_line, end_line, count).
SwiftFile.line_covered(line) is true when the innermost region containing
that line has a count above zero, so a nested zero-count region leaves its
lines uncovered. A segment is still one line. CRAP still counts each region
once, when its start line lies in the function.

Proved by the span, innermost-region, segment, xccov, and CRAP snapshot tests.
The choose fixture stays at 50% coverage and CRAP 2.5.

Co-authored-by: Robert C. Martin <[email protected]>
This commit is contained in:
Cursor Agent
2026-11-26 01:37:08 +00:00
co-authored by Robert C. Martin
parent ec077c3793
commit 3b018d8548
2 changed files with 146 additions and 14 deletions
+54 -14
View File
@@ -369,11 +369,30 @@ def _segments_percent(segments, start: int, end: int) -> float | None:
@dataclass
class SwiftFile:
"""Regions `(line, count)` or xccov summaries `(line, covered, executable)`."""
"""Code regions `(start_line, end_line, count)`, or xccov summaries.
regions: list[tuple[int, int]] = field(default_factory=list)
`line_covered` is the line question. The innermost region containing the
line is covered when its count is greater than zero, so a nested region
with count zero leaves those lines uncovered. A line in no region is
uncovered. Summaries are not regions: they still score CRAP, and
`line_covered` does not read them.
CRAP counts each region once, and only when its start line lies in the
function. A segment, used when a file has no function regions, is one
line (`start_line == end_line`).
"""
regions: list[tuple[int, int, int]] = field(default_factory=list)
summaries: list[tuple[int, int, int]] = field(default_factory=list)
def line_covered(self, line: int) -> bool:
"""True when the innermost region containing `line` has a count above zero."""
region = _innermost_region(self.regions, line)
if region is None:
return False
return region[2] > 0
def _is_llvm(data) -> bool:
if not isinstance(data, dict):
@@ -383,21 +402,21 @@ def _is_llvm(data) -> bool:
return isinstance(data.get("data"), list)
def _pair(line, count) -> tuple[int, int] | None:
def _region_count(start, end, count) -> tuple[int, int, int] | None:
try:
return int(line), int(count)
return int(start), int(end), int(count)
except (TypeError, ValueError):
return None
def _code_region(region) -> tuple[int, int] | None:
def _code_region(region) -> tuple[int, int, int] | None:
"""A code region. Branch, gap, skipped, and expansion regions are not lines."""
if not isinstance(region, list) or len(region) < 5:
return None
if len(region) >= 8 and region[7] not in (0, None):
return None
return _pair(region[0], region[4])
return _region_count(region[0], region[2], region[4])
def _segment_counts(segment) -> bool:
@@ -410,15 +429,15 @@ def _segment_counts(segment) -> bool:
return True
def _segment_region(segment) -> tuple[int, int] | None:
def _segment_region(segment) -> tuple[int, int, int] | None:
if not isinstance(segment, list) or len(segment) < 4:
return None
if not _segment_counts(segment):
return None
return _pair(segment[0], segment[2])
return _region_count(segment[0], segment[0], segment[2])
def _regions_of(values, reader) -> list[tuple[int, int]]:
def _regions_of(values, reader) -> list[tuple[int, int, int]]:
found = []
if not isinstance(values, list):
return found
@@ -438,15 +457,15 @@ def _region_file(region: list) -> int:
return 0
def _add_function_region(found: dict[int, list[tuple[int, int]]], region) -> None:
def _add_function_region(found: dict[int, list[tuple[int, int, int]]], region) -> None:
parsed = _code_region(region)
if parsed is None or not isinstance(region, list):
return
found.setdefault(_region_file(region), []).append(parsed)
def _llvm_function_regions(unit: dict) -> dict[int, list[tuple[int, int]]]:
found: dict[int, list[tuple[int, int]]] = {}
def _llvm_function_regions(unit: dict) -> dict[int, list[tuple[int, int, int]]]:
found: dict[int, list[tuple[int, int, int]]] = {}
for function in unit.get("functions") or []:
if not isinstance(function, dict):
continue
@@ -540,11 +559,32 @@ def parse_swift_coverage(text: str) -> dict[str, SwiftFile]:
return _xccov_files(data)
def _contains_line(region: tuple[int, int, int], line: int) -> bool:
start, end, _count = region
return start <= line <= end
def _region_rank(region: tuple[int, int, int]) -> tuple[int, int]:
"""Smaller span first. The same span keeps the region that starts later."""
start, end, _count = region
return (end - start, -start)
def _innermost_region(regions, line: int) -> tuple[int, int, int] | None:
containing = [region for region in regions if _contains_line(region, line)]
if not containing:
return None
return min(containing, key=_region_rank)
def _covered_regions(regions, start: int, end: int) -> tuple[int, int]:
"""Each region counts once, and only when its start line lies in the function."""
total = 0
covered = 0
for line, count in regions:
if line < start or line > end:
for region_start, _region_end, count in regions:
if region_start < start or region_start > end:
continue
total += 1
if count > 0:
+92
View File
@@ -1,8 +1,10 @@
"""Swift functions score the way a reader of the source would count branches."""
import json
from pathlib import Path
from crapper.cli import run
from crapper.coverage import SwiftFile, parse_swift_coverage
from crapper.discover import is_test_file, iter_source_files
from crapper.languages.swift import functions_in_source
from crapper.runners import llvm_cov_tool, run_coverage, swift_export_command, swift_test_binary
@@ -322,6 +324,96 @@ def test_llvm_cov_regions_join_the_swift_snapshot(tmp_path):
assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 100.0, :crap 1.0' in text
def _llvm_regions(filename: str, regions: list) -> str:
return json.dumps(
{
"type": "llvm.coverage.json.export",
"data": [
{
"files": [{"filename": filename}],
"functions": [{"regions": regions}],
}
],
}
)
def test_a_region_records_its_end_line_and_covers_that_span():
text = _llvm_regions(
"Sources/Demo/Box.swift",
[
[4, 9, 5, 2, 1, 0, 0, 0],
[2, 1, 2, 4, 0, 0, 0, 0],
[4, 1, "end", 2, 1, 0, 0, 0],
],
)
record = parse_swift_coverage(text)["Sources/Demo/Box.swift"]
assert record.regions == [(4, 5, 1), (2, 2, 0)]
assert record.line_covered(4)
assert record.line_covered(5)
assert not record.line_covered(2)
assert not record.line_covered(3)
assert not record.line_covered(6)
def test_the_innermost_region_decides_whether_a_line_is_covered():
nested = SwiftFile(regions=[(1, 6, 1), (4, 5, 0)])
assert nested.line_covered(1)
assert nested.line_covered(3)
assert not nested.line_covered(4)
assert not nested.line_covered(5)
assert nested.line_covered(6)
assert not nested.line_covered(7)
later = SwiftFile(regions=[(4, 5, 0), (5, 6, 1)])
assert not later.line_covered(4)
assert later.line_covered(5)
assert later.line_covered(6)
same = SwiftFile(regions=[(4, 5, 0), (4, 5, 1)])
assert not same.line_covered(4)
assert not same.line_covered(5)
def test_a_segment_region_is_a_single_line():
text = (_FIXTURES / "segments.json").read_text(encoding="utf-8")
record = parse_swift_coverage(text)["Sources/Demo/Box.swift"]
assert (2, 2, 1) in record.regions
assert (5, 5, 0) in record.regions
assert record.line_covered(2)
assert not record.line_covered(3)
assert not record.line_covered(5)
def test_an_xccov_summary_does_not_mark_a_line_covered():
record = SwiftFile(summaries=[(2, 1, 1)])
assert record.line_covered(2) is False
def test_a_spanning_region_still_counts_once_toward_crap(tmp_path):
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text(_BOX, encoding="utf-8")
report = tmp_path / "target" / "coverage" / "swift" / "llvm-cov.json"
report.parent.mkdir(parents=True)
report.write_text(
_llvm_regions(
"Sources/Demo/Box.swift",
[
[2, 1, 2, 4, 0, 0, 0, 0],
[4, 1, 5, 2, 1, 0, 0, 0],
],
),
encoding="utf-8",
)
text = _snapshot(tmp_path)
assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text
assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 0.0, :crap 2.0' in text
record = parse_swift_coverage(report.read_text(encoding="utf-8"))["Sources/Demo/Box.swift"]
assert record.line_covered(5)
assert not record.line_covered(2)
def test_llvm_cov_segments_are_used_when_a_function_has_no_regions(tmp_path):
_swift_project(tmp_path, "segments.json")
text = _snapshot(tmp_path)