diff --git a/src/crapper/coverage.py b/src/crapper/coverage.py index 5adf756..c8d261b 100644 --- a/src/crapper/coverage.py +++ b/src/crapper/coverage.py @@ -469,6 +469,29 @@ def _filename_at(names, index: int) -> str | None: return None +def _unit_filenames(unit: dict) -> list: + """Unit file names in file-id order. A hole stays None so later ids do not slide.""" + + names = [] + for file in unit.get("files") or []: + name = None + if isinstance(file, dict): + candidate = file.get("filename") + if isinstance(candidate, str): + name = candidate + names.append(name) + return names + + +def _region_names(function: dict, unit_names: list) -> list: + """Function filenames when the export wrote them, otherwise the unit file list.""" + + names = function.get("filenames") + if isinstance(names, list) and names: + return names + return unit_names + + def _add_function_region(found: dict[str, list[tuple[int, int, int]]], names, region) -> None: parsed = _code_region(region) if parsed is None or not isinstance(region, list): @@ -480,10 +503,11 @@ def _add_function_region(found: dict[str, list[tuple[int, int, int]]], names, re def _llvm_function_regions(unit: dict) -> dict[str, list[tuple[int, int, int]]]: found: dict[str, list[tuple[int, int, int]]] = {} + unit_names = _unit_filenames(unit) for function in unit.get("functions") or []: if not isinstance(function, dict): continue - names = function.get("filenames") + names = _region_names(function, unit_names) for region in function.get("regions") or []: _add_function_region(found, names, region) return found diff --git a/tests/test_swift.py b/tests/test_swift.py index 1733527..a2025a0 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -360,7 +360,7 @@ def test_a_function_region_follows_that_functions_filenames(): assert not entry.line_covered(5) -def test_a_region_with_no_function_filenames_is_not_placed_by_unit_index(): +def test_a_region_without_function_filenames_uses_the_unit_file_list(): text = json.dumps( { "type": "llvm.coverage.json.export", @@ -370,14 +370,20 @@ def test_a_region_with_no_function_filenames_is_not_placed_by_unit_index(): {"filename": "First.swift"}, {"filename": "Second.swift"}, ], - "functions": [{"regions": [[4, 1, 5, 1, 1, 0, 0, 0]]}], + "functions": [ + {"regions": [[4, 1, 5, 1, 1, 0, 0, 0]]}, + {"filenames": [], "regions": [[1, 1, 1, 2, 1, 1, 0, 0]]}, + ], } ], } ) files = parse_swift_coverage(text) - assert not files["First.swift"].line_covered(4) - assert not files["First.swift"].line_covered(5) + assert files["First.swift"].line_covered(4) + assert files["First.swift"].line_covered(5) + assert not files["First.swift"].line_covered(1) + assert files["Second.swift"].regions == [(1, 1, 1)] + assert files["Second.swift"].line_covered(1) assert not files["Second.swift"].line_covered(5)