Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(graph): name the class, not Class<T>, as the parent of an out-of-line C++ template member (#4817)
Swati Ahuja2c11e02d40d1
diff --git a/packages/core/src/repowise/core/ingestion/parser/symbols.py b/packages/core/src/repowise/core/ingestion/parser/symbols.pyindex 11a38dc51..cee106a76 100644--- a/packages/core/src/repowise/core/ingestion/parser/symbols.py+++ b/packages/core/src/repowise/core/ingestion/parser/symbols.py@@ -47,6 +47,7 @@ from ..parser_helpers import (_qualified_cpp_parent,_qualified_pascal_parent,_ts_nested_object_method_owner,+ cpp_template_type_name,follow_renamed_hosts,in_anonymous_class,is_anonymous_member,@@ -167,6 +168,8 @@ def _parent_type_name(ancestor: Node, src: str) -> str | None:)if name_node is None:return None+ if name_node.type == "template_type":+ return cpp_template_type_name(name_node, src)# For Rust impl blocks with generic types (e.g. impl<T> Foo<T>),# extract only the base type name, not the full generic signature.if name_node.type in ("generic_type", "scoped_type_identifier"):diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex bc029e3b1..357f1db20 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -7,6 +7,7 @@ No imports from ``parser``, so there is no import cycle.from __future__ import annotations+import refrom pathlib import Pathimport structlog@@ -93,6 +94,7 @@ __all__ = ["_rust_head_type_identifier","_rust_shadowed_by_type_param","_ts_nested_object_method_owner",+ "cpp_template_type_name","follow_renamed_hosts","import_load_kind","in_anonymous_class",@@ -292,12 +294,66 @@ def _qualified_cpp_parent(name_node: Node, src: str) -> str | None:scope = parent.child_by_field_name("scope")if scope is None:return None+ if scope.type == "template_type":+ return cpp_template_type_name(scope, src)text = node_text(scope, src).strip()# ``scope`` may itself be a qualified path (``NS::Foo``); take the# last component — that's the immediate enclosing type.return text.rsplit("::", 1)[-1] or None+_CPP_SPACE_RUN = re.compile(r"\s+")+_CPP_BRACKET_SPACE = re.compile(r"(?<=<) | (?=>)")+++def cpp_template_type_name(node: Node, src: str) -> str:+ """The class a C++ ``Name<Args>`` scope or class head names.++ A member of the primary template, defined out of line, spells the+ template's own parameters (``parse_context<Char>::f``) and belongs to+ ``parse_context``, where a ``ctx.f()`` receiver lookup finds it. Any other+ argument list is an explicit or partial specialization, a class of its+ own: it keeps its arguments, on one line, so its members never merge with+ the primary's.+ """+ name = node.child_by_field_name("name")+ arguments = node.child_by_field_name("arguments")+ if name is None or arguments is None:+ return _CPP_SPACE_RUN.sub(" ", node_text(node, src).strip())+ if _spells_enclosing_parameters(node, arguments, src):+ return node_text(name, src)+ return _CPP_BRACKET_SPACE.sub("", _CPP_SPACE_RUN.sub(" ", node_text(node, src).strip()))+++def _spells_enclosing_parameters(node: Node, arguments: Node, src: str) -> bool:+ """Do *arguments* name an enclosing ``template <...>``'s parameters, in order?"""+ spelled = [+ node_text(arg, src).replace(" ", "").removesuffix("...") for arg in arguments.named_children+ ]+ ancestor = node.parent+ while ancestor is not None:+ if ancestor.type == "template_declaration":+ parameters = ancestor.child_by_field_name("parameters")+ if parameters is not None and spelled == _template_parameter_names(parameters, src):+ return True+ ancestor = ancestor.parent+ return False+++def _template_parameter_names(parameters: Node, src: str) -> list[str | None]:+ """``template <typename T, int N, typename... Ts>`` -> ``["T", "N", "Ts"]``."""+ names: list[str | None] = []+ for parameter in parameters.named_children:+ # ``template <typename> class C`` names C in its trailing ``class C``.+ if parameter.type == "template_template_parameter_declaration":+ parameter = parameter.named_children[-1]+ name = parameter.child_by_field_name("name") or parameter.child_by_field_name("declarator")+ if name is None:+ name = next((c for c in parameter.named_children if c.type in ("type_identifier", "identifier")), None)+ names.append(node_text(name, src).lstrip("*&. ") if name is not None else None)+ return names++def _build_qualified_name(file_path: str, parent_name: str | None, name: str) -> str:module = Path(file_path).with_suffix("").as_posix().replace("/", ".")if parent_name:diff --git a/tests/unit/ingestion/test_cpp_template_member_parent.py b/tests/unit/ingestion/test_cpp_template_member_parent.pynew file mode 100644index 000000000..fad215c35--- /dev/null+++ b/tests/unit/ingestion/test_cpp_template_member_parent.py@@ -0,0 +1,109 @@+"""A C++ member defined out of line belongs to its class, not to ``Class<T>``.++``template <typename T> void Box<T>::f()`` read its parent off the scope's text,+so the member's parent was ``Box<T>`` and a receiver typed ``Box`` never found+it. A specialization's members keep their arguments (a class of their own), on+one line: a multi-line argument list put newlines into symbol ids.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.models import FileInfo+++def _symbols(tmp_path: Path, source: str):+ path = tmp_path / "box.h"+ path.write_text(source)+ info = FileInfo(+ path="box.h", abs_path=str(path), language="cpp", size_bytes=len(source),+ git_hash="", last_modified=0.0, is_test=False, is_config=False, is_api_contract=False,+ is_entry_point=False,+ )+ return ASTParser().parse_file(info, source.encode()).symbols+++def _parents(tmp_path: Path, source: str) -> dict[str, str | None]:+ return {s.id.split("::", 1)[1]: s.parent_name for s in _symbols(tmp_path, source) if s.kind == "method"}+++class TestOutOfLineTemplateMember:+ def test_a_primary_template_member_names_the_bare_class(self, tmp_path: Path) -> None:+ parents = _parents(+ tmp_path,+ "template <typename T> struct Box { void f(); };\n"+ "template <typename T> void Box<T>::f() {}\n",+ )+ assert parents == {"Box::f": "Box"}++ def test_parameter_packs_and_non_type_parameters_still_spell_the_primary(+ self, tmp_path: Path+ ) -> None:+ parents = _parents(+ tmp_path,+ "template <typename T, int N, typename... Ts> struct Box { void f(); };\n"+ "template <typename T, int N, typename... Ts> void Box<T, N, Ts...>::f() {}\n",+ )+ assert parents == {"Box::f": "Box"}++ def test_defaults_and_template_template_parameters_still_spell_the_primary(+ self, tmp_path: Path+ ) -> None:+ parents = _parents(+ tmp_path,+ "template <template <typename> class C, typename T = int> struct Box { Box(); };\n"+ "template <template <typename> class C, typename T> Box<C, T>::Box() {}\n",+ )+ assert parents == {"Box::Box": "Box"}++ def test_a_namespace_qualified_scope(self, tmp_path: Path) -> None:+ parents = _parents(tmp_path, "template <typename T> void ns::Box<T>::f() {}\n")+ assert parents == {"Box::f": "Box"}++ def test_a_member_template_of_a_class_template(self, tmp_path: Path) -> None:+ parents = _parents(+ tmp_path,+ "template <typename T> struct Box { template <typename U> void f(U u); };\n"+ "template <typename T> template <typename U> void Box<T>::f(U u) {}\n",+ )+ assert parents == {"Box::f": "Box"}++ def test_an_explicit_specialization_member_keeps_its_arguments(self, tmp_path: Path) -> None:+ """``Box<int>::f`` is another function; merging it into ``Box::f`` would be a wrong edge."""+ parents = _parents(tmp_path, "template <> void Box<ns::Item>::f() {}\n")+ assert parents == {"Box<ns::Item>::f": "Box<ns::Item>"}++ def test_a_partial_specialization_keeps_its_arguments_on_one_line(self, tmp_path: Path) -> None:+ ids = [+ s.id+ for s in _symbols(+ tmp_path,+ "template <typename T>\nstruct Box<\n T*,\n int> {\n void f() {}\n};\n"+ "template <typename T> void Box<T*, long>::g() {}\n",+ )+ ]+ assert ids == ["box.h::Box<T*, int>::f", "box.h::Box<T*, long>::g"]+++def test_a_receiver_typed_by_the_class_reaches_the_out_of_line_member(tmp_path: Path) -> None:+ (tmp_path / "box.h").write_text(+ "#pragma once\n"+ "template <typename T> class Box {\n public:\n void f(int n);\n};\n"+ "template <typename T> void Box<T>::f(int n) {}\n"+ "template <> void Box<char>::f(int n) {}\n"+ )+ (tmp_path / "use.cc").write_text('#include "box.h"\nvoid g(Box<int>& b) { b.f(1); }\n')+ builder = GraphBuilder(repo_path=tmp_path)+ parser = ASTParser()+ for fi in FileTraverser(tmp_path).traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ graph = builder.build()+ targets = {+ t for s, t, d in graph.edges(data=True)+ if d.get("edge_type") == "calls" and str(s).startswith("use.cc::")+ }+ # The declaration and the out-of-line definition are one node.+ assert targets == {"box.h::Box::f"}+ assert not any("Box<T>" in str(n) for n in graph.nodes)diff --git a/tests/unit/ingestion/test_cpp_template_parameter_helpers.py b/tests/unit/ingestion/test_cpp_template_parameter_helpers.pynew file mode 100644index 000000000..9fda49fda--- /dev/null+++ b/tests/unit/ingestion/test_cpp_template_parameter_helpers.py@@ -0,0 +1,61 @@+"""Direct tests for the C++ template-parameter helpers behind out-of-line member parents."""++from __future__ import annotations++import tree_sitter_cpp+from tree_sitter import Language, Node, Parser++from repowise.core.ingestion.parser_helpers import (+ _spells_enclosing_parameters,+ _template_parameter_names,+)++_PARSER = Parser(Language(tree_sitter_cpp.language()))+++def _walk(node: Node):+ yield node+ for child in node.children:+ yield from _walk(child)+++def _parameters(source: str) -> tuple[Node, str]:+ src = source+ root = _PARSER.parse(src.encode()).root_node+ decl = next(n for n in _walk(root) if n.type == "template_declaration")+ return decl.child_by_field_name("parameters"), src+++class TestTemplateParameterNames:+ def test_unnamed_typename_is_none(self) -> None:+ params, src = _parameters("template <typename> struct S {};")+ assert _template_parameter_names(params, src) == [None]++ def test_default_argument_keeps_the_name(self) -> None:+ params, src = _parameters("template <class T = int> struct S {};")+ assert _template_parameter_names(params, src) == ["T"]++ def test_non_type_pointer_declarator_strips_the_star(self) -> None:+ params, src = _parameters("template <int *P> struct S {};")+ assert _template_parameter_names(params, src) == ["P"]++ def test_mixed_list_and_pack(self) -> None:+ params, src = _parameters("template <typename T, int N, typename... Ts> struct S {};")+ assert _template_parameter_names(params, src) == ["T", "N", "Ts"]+++class TestSpellsEnclosingParameters:+ def test_no_enclosing_template_declaration_is_false(self) -> None:+ src = "void Box<T>::f() {}"+ root = _PARSER.parse(src.encode()).root_node+ scope = next(n for n in _walk(root) if n.type == "template_type")+ arguments = scope.child_by_field_name("arguments")+ assert not any(a.type == "template_declaration" for a in _ancestors(scope))+ assert _spells_enclosing_parameters(scope, arguments, src) is False+++def _ancestors(node: Node):+ node = node.parent+ while node is not None:+ yield node+ node = node.parent