Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

7.1 KB
Raw Blame
"""``.inl`` / ``.ipp`` / ``.tpp`` are C++ (#1600).

The convention carries inline and template implementations, and generated
binding tables pasted mid-file. None of those extensions was in the C++ spec,
so the files were excluded as "unknown type" before anything read them: the
symbols they define were absent from the index, and — the more damaging half —
so was every reference *made from inside* them, which left the macros a
generated table invokes looking unused.
"""

from __future__ import annotations

from pathlib import Path

from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
from repowise.core.ingestion.languages.registry import REGISTRY


def _build(repo: Path):
    traverser = FileTraverser(repo)
    parser = ASTParser()
    builder = GraphBuilder(repo_path=repo)
    for fi in traverser.traverse():
        builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
    return builder.build()


def _traversed(repo: Path) -> set[str]:
    return {fi.path for fi in FileTraverser(repo).traverse()}


def _callers_of(graph, symbol_id: str) -> set[str]:
    if not graph.has_node(symbol_id):
        return set()
    return {
        pred
        for pred in graph.predecessors(symbol_id)
        if graph[pred][symbol_id].get("edge_type") == "calls"
    }


class TestExtensionRegistration:
    def test_fragment_extensions_map_to_cpp(self) -> None:
        for ext in (".inl", ".ipp", ".tpp"):
            assert REGISTRY.from_extension(ext) == "cpp"

    def test_existing_cpp_extensions_not_regressed(self) -> None:
        for ext in (".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"):
            assert REGISTRY.from_extension(ext) == "cpp"


class TestFragmentIsIndexed:
    def test_symbol_defined_in_a_fragment_is_indexed(self, tmp_path: Path) -> None:
        (tmp_path / "math_impl.inl").write_text("inline int TripleValue(int v) { return v * 3; }\n")
        graph = _build(tmp_path)
        assert graph.has_node("math_impl.inl::TripleValue")

    def test_call_into_a_fragment_resolves(self, tmp_path: Path) -> None:
        (tmp_path / "math_impl.inl").write_text("inline int TripleValue(int v) { return v * 3; }\n")
        (tmp_path / "uses.cpp").write_text(
            '#include "math_impl.inl"\nint Show() { return TripleValue(3); }\n'
        )
        graph = _build(tmp_path)
        assert _callers_of(graph, "math_impl.inl::TripleValue") == {"uses.cpp::Show"}

    def test_include_of_a_fragment_is_an_import_edge(self, tmp_path: Path) -> None:
        (tmp_path / "math_impl.inl").write_text("inline int TripleValue(int v) { return v * 3; }\n")
        (tmp_path / "uses.cpp").write_text('#include "math_impl.inl"\nint Show() { return 0; }\n')
        graph = _build(tmp_path)
        assert graph.has_edge("uses.cpp", "math_impl.inl")

    def test_ipp_and_tpp_are_traversed(self, tmp_path: Path) -> None:
        (tmp_path / "a.ipp").write_text("inline int A() { return 1; }\n")
        (tmp_path / "b.tpp").write_text("template <class T> T B(T v) { return v; }\n")
        assert {"a.ipp", "b.tpp"} <= _traversed(tmp_path)


class TestGeneratedFragment:
    def test_generated_fragment_is_still_parsed(self, tmp_path: Path) -> None:
        # A .inl is not a module: it is text pasted into a hand-written TU, so
        # skipping it deletes edges from code nobody generated.
        (tmp_path / "table.inl").write_text(
            "// DO NOT EDIT - generated by tools/gen.py\nSAVE_COMPONENT(Transform)\n"
        )
        assert "table.inl" in _traversed(tmp_path)

    def test_macro_invoked_only_from_a_generated_table_has_call_sites(
        self, tmp_path: Path
    ) -> None:
        (tmp_path / "table.inl").write_text(
            "// DO NOT EDIT - generated by tools/gen.py\nSAVE_COMPONENT(Transform)\n"
        )
        (tmp_path / "save.cpp").write_text(
            "#define SAVE_COMPONENT(T) RegisterSave(#T)\n"
            "void RegisterSave(const char* n);\n"
            "void InstallAll() {\n#include \"table.inl\"\n}\n"
        )
        graph = _build(tmp_path)
        assert _callers_of(graph, "save.cpp::SAVE_COMPONENT")

    def test_generated_fragment_exemption_is_case_insensitive(self, tmp_path: Path) -> None:
        # Language detection lowercases the extension, so a ``.INL`` is C++ and
        # reaches the generated check. If the exemption compared raw suffixes
        # it would drop the file again, reproducing the bug for this spelling.
        (tmp_path / "Table.INL").write_text(
            "// DO NOT EDIT - generated by tools/gen.py\nSAVE_COMPONENT(Transform)\n"
        )
        assert "Table.INL" in _traversed(tmp_path)

    def test_generated_module_is_still_skipped(self, tmp_path: Path) -> None:
        # The exemption is for fragments only. A generated .cpp is a
        # translation unit of its own and stays out, as before.
        (tmp_path / "gen.cpp").write_text(
            "// DO NOT EDIT - generated by protoc\nint Gen() { return 1; }\n"
        )
        assert "gen.cpp" not in _traversed(tmp_path)


class TestReachabilityTreatsFragmentsAsHeaders:
    def test_fragment_counts_as_a_header(self) -> None:
        from repowise.core.analysis.dead_code.cpp_reachability import (
            _is_header,
            is_cpp_path,
        )

        for ext in (".inl", ".ipp", ".tpp"):
            assert is_cpp_path(f"src/x{ext}")
            assert _is_header(f"src/x{ext}")


class TestSharedExtensionSet:
    """The lists that had drifted now read the one exported set.

    The issue called this out directly: ``.inc`` was in the reachability pass
    and absent from the spec. Pinning each consumer keeps the next extension
    from having to be added in six places.
    """

    def test_every_consumer_covers_the_fragment_extensions(self) -> None:
        from repowise.core.analysis.dead_code.cpp_reachability import _CPP_HEADER_EXTS
        from repowise.core.ingestion.dynamic_hints.cpp import _CPP_EXTS
        from repowise.core.ingestion.external_systems.cmake import (
            _HEADER_EXTS as CMAKE_HEADER_EXTS,
        )
        from repowise.core.ingestion.graph_warmups import _CPP_MACRO_SCAN_EXTS
        from repowise.core.ingestion.languages.specs.cpp import (
            INCLUDE_FRAGMENT_EXTENSIONS,
            SPEC,
        )
        from repowise.core.ingestion.resolvers.cpp import _HEADER_EXTS

        for consumer in (
            SPEC.extensions,
            _CPP_HEADER_EXTS,
            _HEADER_EXTS,
            CMAKE_HEADER_EXTS,
            _CPP_EXTS,
            _CPP_MACRO_SCAN_EXTS,
        ):
            assert set(consumer) >= INCLUDE_FRAGMENT_EXTENSIONS

    def test_header_pairing_treats_a_fragment_as_the_implementation(
        self, tmp_path: Path
    ) -> None:
        # ``vector.inl`` holds what ``vector.h`` declares, so a consumer of the
        # header can transit into the fragment.
        (tmp_path / "vector.h").write_text("template <class T> T Get(T v);\n")
        (tmp_path / "vector.inl").write_text("template <class T> T Get(T v) { return v; }\n")
        graph = _build(tmp_path)
        pair = graph.get_edge_data("vector.h", "vector.inl")
        assert pair is not None
        assert pair.get("hint_source") == "header_source_pair"