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(cpp): give each C++ overload its own symbol (#2829)
Raghav Chamadiyae009b7961436
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 3831249eb..186b7aa27 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -1404,15 +1404,9 @@ class DeadCodeAnalyzer:# ``method_implements`` / ``reads`` / ``extends`` /# ``implements`` / ``type_use`` edge means somewhere in# the codebase actually uses this symbol — even if the- # file-level ``imported_names`` machinery missed it- if (- unsatisfied_guard is None- and self.graph.has_node(sym_id)- and any(- self.graph[pred][sym_id].get("edge_type") in REACHABILITY_USE_EDGE_TYPES- for pred in self.graph.predecessors(sym_id)- )- ):+ # file-level ``imported_names`` machinery missed it. A use of one+ # member of an overload set uses the set.+ if unsatisfied_guard is None and self._has_inbound_use(sym_id):return True, Noneif self._member_is_used(sym_id, sym.get("language")):diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 2e52aac63..317c634ae 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -497,6 +497,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):self._index_file(path, parsed, definitions, declarations, extensions)self._decl_to_def = self._link_declarations(declarations, definitions)+ self._pair_overload_members()self._index_extension_methods(extensions)def _index_file(@@ -593,6 +594,32 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):self._overload_rep.update(representatives)return representatives+ def _pair_overload_members(self) -> None:+ """Pair each member of a declared overload set with its definition.++ ``_link_declarations`` pairs a declared set with a defined one by their+ representatives; the other members pair here by parameter count, so+ each declaration records its definition. The definition also admits+ the defaults its declaration writes: C++ writes them on the header+ declaration only, so ``f(int, int)`` alone would refuse the one-argument+ call ``f(int, int = 0)`` admits.+ """+ for declared, defined in list(self._decl_to_def.items()):+ declared_members = self._overload_members.get(declared, ())+ defined_members = self._overload_members.get(defined, ())+ by_count = {split_symbol_id(member)[1]: member for member, _ in defined_members}+ floors: dict[str, int] = {}+ for member, (fewest, _most) in declared_members:+ target = by_count.get(split_symbol_id(member)[1])+ if target is not None:+ self._decl_to_def.setdefault(member, target)+ floors[target] = min(fewest, floors.get(target, fewest))+ if floors:+ self._overload_members[defined] = tuple(+ (member, (min(fewest, floors.get(member, fewest)), most))+ for member, (fewest, most) in defined_members+ )+def _index_extension_methods(self, candidates: dict[tuple[str, str], set[tuple[str, str]]]) -> None:diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scmindex e3d72665f..4c1aba361 100644--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm@@ -193,16 +193,6 @@)) @symbol.def-; Template function: template<typename T> T func(T x) { ... }-(template_declaration- (function_definition- declarator: (function_declarator- declarator: (identifier) @symbol.name- parameters: (parameter_list) @symbol.params- )- )-) @symbol.def-; typedef struct { ... } MyType;(type_definitiontype: (struct_specifier)diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.pyindex c9f5a9ddb..031c992da 100644--- a/packages/core/src/repowise/core/ingestion/return_types.py+++ b/packages/core/src/repowise/core/ingestion/return_types.py@@ -25,9 +25,11 @@ _PAIRS = {"(": ")", "[": "]", "{": "}", "<": ">"}def _top_level_parameters(signature: str) -> list[str] | None:"""The top-level parameter texts of a stored callable signature.- ``[]`` for an empty list, None when the signature has no closed list.+ ``[]`` for an empty list, None when the signature has no closed list. A+ C/C++ ``(void)`` list is empty, and ``operator()(int)`` lists ``int``."""- start = signature.find("(")+ operator = signature.find("operator()")+ start = signature.find("(", 0 if operator < 0 else operator + len("operator()"))if start < 0:return Nonepieces: list[str] = []@@ -37,7 +39,7 @@ def _top_level_parameters(signature: str) -> list[str] | None:for char in signature[start + 1 :]:if char == ")" and not closers:pieces.append("".join(current))- return pieces if content else []+ return pieces if content and [p.strip() for p in pieces] != ["void"] else []if char in _PAIRS:closers.append(_PAIRS[char])elif closers and char == closers[-1]:@@ -61,9 +63,9 @@ def signature_parameter_count(signature: str) -> int | None:def signature_parameter_range(signature: str, language: str) -> tuple[int, int | None] | None:"""``(fewest, most)`` arguments a call may pass; ``most`` is None when open.- Java ``T...`` and C# ``params`` leave the top open, a C# default lowers- the floor, and a C# extension method is also called on its receiver, one- argument short of its declared list.+ Java ``T...``, C# ``params``, C ``...`` and a C++ parameter pack leave the+ top open, a C# or C++ default lowers the floor, and a C# extension method+ is also called on its receiver, one argument short of its declared list."""parameters = _top_level_parameters(signature)if parameters is None:@@ -72,12 +74,13 @@ def signature_parameter_range(signature: str, language: str) -> tuple[int, int |fewest = most = len(texts)if not texts:return 0, 0- if language == "java" and "..." in texts[-1]:+ if language in ("java", "cpp") and "..." in texts[-1]:fewest, most = fewest - 1, None+ if language in ("csharp", "cpp"):+ fewest -= sum(1 for text in texts if "=" in text)if language == "csharp":if texts[-1].startswith("params "):fewest, most = fewest - 1, None- fewest -= sum(1 for text in texts if "=" in text)if texts[0].startswith("this "):fewest -= 1return max(fewest, 0), mostdiff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.pyindex ece680cb0..4d5dea144 100644--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py@@ -88,6 +88,7 @@ def _parameter_count(symbol: Symbol) -> str | None:_DISCRIMINATORS: dict[str, Callable[[Symbol], str | None]] = {"java": _parameter_count,"csharp": _parameter_count,+ "cpp": _parameter_count,}# Languages where a type may share its name with a sibling of another arity.diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.pyindex 01dcc20c2..0906ea5ab 100644--- a/packages/core/src/repowise/core/upgrade/version.py+++ b/packages/core/src/repowise/core/upgrade/version.py@@ -66,9 +66,10 @@ STORE_FORMAT_VERSION: int = 2#: v6: a member call a bare-call pattern also matched (Java ``obj.m()``, Ruby#: ``obj.m(x)``) is kept once, with its receiver and ``bare_name_fallback``, so#: a cached receiver-less copy no longer resolves by bare name beside it. Also,-#: Java and C# overloads of different arity get their own ids (``notNull#1``,+#: Java, C# and C++ overloads of different arity get their own ids (``notNull#1``,#: ``notNull#2``) and a C# generic type beside a same-named one gets its arity-#: (``IFoo`1``); the first update re-keys symbols and graph nodes repo-wide.+#: (``IFoo`1``); the first update re-keys symbols and graph nodes repo-wide. A+#: C++ template function is one ``function`` symbol, no longer also a ``class``.PARSER_SCHEMA_VERSION: int = 6#: state.json key holding the store format version that wrote the store.diff --git a/tests/unit/dead_code/test_overload_unit.py b/tests/unit/dead_code/test_overload_unit.pyindex 59ed3be22..133213b96 100644--- a/tests/unit/dead_code/test_overload_unit.py+++ b/tests/unit/dead_code/test_overload_unit.py@@ -78,3 +78,30 @@ def test_a_constructor_overload_rescues_its_class() -> None:found = _unused(_graph(symbols, [("src/Main.cs::Main::Run", "Inner::Inner#2")]))assert ("Inner", 3) not in foundassert ("Spare", 30) in found+++def test_a_call_to_one_cpp_overload_uses_the_exported_set() -> None:+ """C++ free functions are exports; a call to ``pad#3`` uses ``pad#1`` too."""+ g = nx.DiGraph()+ g.add_node("util.cpp", language="cpp")+ g.add_node("main.cpp", language="cpp")+ for sym_id, line in (("util.cpp::pad#1", 2), ("util.cpp::pad#3", 3), ("util.cpp::spare", 4)):+ g.add_node(+ sym_id,+ node_type="symbol",+ file_path="util.cpp",+ name=sym_id.rpartition("::")[2].partition("#")[0],+ kind="function",+ language="cpp",+ visibility="public",+ decorators=[],+ start_line=line,+ end_line=line,+ )+ g.add_edge("util.cpp", sym_id, edge_type="defines")+ g.add_edge("main.cpp::main", "util.cpp::pad#3", edge_type="calls")+ config = {**_CONFIG, "detect_unused_exports": True}+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(config)+ assert sorted(f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT) == [+ "spare"+ ]diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.pyindex 68e31df25..da3214f04 100644--- a/tests/unit/ingestion/test_overload_identity.py+++ b/tests/unit/ingestion/test_overload_identity.py@@ -1,6 +1,6 @@"""Overloads and same-named generic siblings get their own symbol ids.-Java and C# let one scope declare a name more than once. The ids used to+Java, C# and C++ let one scope declare a name more than once. The ids used tocollide, so the graph kept one node per overload set (whichever declaration waswritten last) and every call to any overload drew an edge to that one line. Acolliding member now carries a discriminator, ``#<parameter count>``, and a C#@@ -163,6 +163,14 @@ class TestIdGrammar:("Ext(this Order o, bool round) -> int", "csharp", (1, 2)),("f(Map<K, V> m) -> void", "java", (1, 1)),("noparens", "java", None),+ ("f(int a, int b = 2) -> void", "cpp", (1, 2)),+ ("log(const char* fmt, ...) -> void", "cpp", (1, None)),+ ("emit(int level, Args&&... args) -> void", "cpp", (1, None)),+ ("v(void) -> void", "cpp", (0, 0)),+ ("operator()(int a, int b) -> bool", "cpp", (2, 2)),+ ("operator<<(std::ostream& os, const A& a) -> std::ostream", "cpp", (2, 2)),+ ("g(int (*fp)(int, int), int n) -> void", "cpp", (2, 2)),+ ("print(FMT_STRING(Char, N) fmt, T&&... args) -> void", "cpp", (1, None)),],)def test_parameter_range(self, signature: str, language: str, expected) -> None:@@ -326,12 +334,157 @@ class TestCSharpGenericSiblings:assert ("C.cs::C::Four", "H.cs::H::Sum#2") in edges+SHAPES_H = """namespace geo {+class Shape {+ public:+ Shape();+ Shape(int w, int h = 1);+ void scale(int f);+ void scale(int fx, int fy);+ int area() const;+ int area();+ template <typename T> void put(T x);+ template <typename T> void put(T* x);+ void reset(void);+ void reset(int to);+ void once();+};+inline void Shape::scale(int f) { scale(f, f); }+inline void Shape::reset() {}+}+"""++SHAPES_CPP = """#include "shapes.h"+namespace geo {+Shape::Shape() {}+Shape::Shape(int w, int h) {}+void Shape::scale(int fx, int fy) {}+int Shape::area() const { return 0; }+int Shape::area() { return 1; }+}+"""+++class TestCppOverloads:+ def test_colliding_members_get_their_parameter_count(self) -> None:+ ids = set(_ids(_parse("shapes.h", "cpp", SHAPES_H)))+ base = "shapes.h::Shape::"+ assert {base + "Shape#0", base + "Shape#2", base + "scale#1", base + "scale#2"} <= ids+ # Same arity stays one id: template overloads and const overloads.+ assert {base + "put", base + "area"} <= ids+ assert base + "once" in ids++ def test_an_in_class_declaration_and_its_inline_definition_share_an_id(self) -> None:+ """``(void)`` and ``()`` both declare no parameters."""+ parsed = _parse("shapes.h", "cpp", SHAPES_H)+ by_id: dict[str, list[bool]] = {}+ for symbol in parsed.symbols:+ by_id.setdefault(symbol.id, []).append(symbol.is_declaration)+ assert sorted(by_id["shapes.h::Shape::scale#1"]) == [False, True]+ assert sorted(by_id["shapes.h::Shape::reset#0"]) == [False, True]+ graph = _graph({"shapes.h": ("cpp", SHAPES_H)})+ assert graph.nodes["shapes.h::Shape::scale#1"]["is_declaration"] is False++ def test_a_header_declared_set_resolves_to_its_out_of_line_definitions(self, tmp_path: Path) -> None:+ header = (+ "class Pen {\n public:\n void shift(int x);\n void shift(int x, int y = 0, int z = 0);\n"+ " void lift();\n};\n"+ )+ source = (+ '#include "pen.h"\n'+ "void Pen::shift(int x) {}\n"+ "void Pen::shift(int x, int y, int z) {}\n"+ "void Pen::lift() {}\n"+ )+ caller = '#include "pen.h"\nvoid draw(Pen& p) {\n p.shift(1);\n p.shift(1, 2);\n p.lift();\n}\n'+ edges = _edges(+ tmp_path, {"pen.h": ("cpp", header), "pen.cpp": ("cpp", source), "draw.cpp": ("cpp", caller)}+ )+ assert {+ ("draw.cpp::draw", "pen.cpp::Pen::shift#1"),+ ("draw.cpp::draw", "pen.cpp::Pen::shift#3"),+ ("draw.cpp::draw", "pen.cpp::Pen::lift"),+ } == {edge for edge in edges if edge[0] == "draw.cpp::draw"}++ def test_each_declared_member_records_its_definition(self, tmp_path: Path) -> None:+ """Defaults written on the declaration carry to the out-of-line definition."""+ (tmp_path / "util.h").write_text("int pad(int a);\nint pad(int a, int b = 0, int c = 0);\n")+ (tmp_path / "util.cpp").write_text(+ '#include "util.h"\nint pad(int a) { return a; }\nint pad(int a, int b, int c) { return a; }\n'+ )+ (tmp_path / "main.cpp").write_text('#include "util.h"\nint main() { return pad(1, 2); }\n')+ builder = GraphBuilder(repo_path=tmp_path)+ for info in FileTraverser(tmp_path).traverse():+ builder.add_file(_PARSER.parse_file(info, Path(info.abs_path).read_bytes()))+ graph = builder.build()+ assert graph.nodes["util.h::pad#1"]["defined_by"] == "util.cpp::pad#1"+ assert graph.nodes["util.h::pad#3"]["defined_by"] == "util.cpp::pad#3"+ assert graph.has_edge("main.cpp::main", "util.cpp::pad#3")++ def test_a_set_split_between_header_and_source_keeps_its_pairing(self, tmp_path: Path) -> None:+ """One overload inline in the header, one in the .cpp: the .cpp body takes the call."""+ caller = '#include "shapes.h"\nvoid draw(geo::Shape& s) {\n s.scale(2, 3);\n}\n'+ edges = _edges(+ tmp_path,+ {"shapes.h": ("cpp", SHAPES_H), "shapes.cpp": ("cpp", SHAPES_CPP), "draw.cpp": ("cpp", caller)},+ )+ assert ("draw.cpp::draw", "shapes.cpp::Shape::scale") in edges++ def test_defaults_and_variadics_admit_their_argument_counts(self, tmp_path: Path) -> None:+ source = (+ "int pad(int a, int b = 0) { return a; }\n"+ "int pad(int a, int b, int c) { return a; }\n"+ "void log(const char* fmt, ...) {}\n"+ "void log(int level) {}\n"+ "template <typename... Args> void emit(int level, Args&&... args) {}\n"+ "void emit() {}\n"+ "void run() {\n pad(1);\n pad(1, 2, 3);\n log(1);\n log(\"x\", 1, 2);\n"+ " emit();\n emit(1, 2, 3);\n}\n"+ )+ edges = _edges(tmp_path, {"u.cpp": ("cpp", source)})+ assert {+ ("u.cpp::run", "u.cpp::pad#2"),+ ("u.cpp::run", "u.cpp::pad#3"),+ ("u.cpp::run", "u.cpp::log#1"),+ ("u.cpp::run", "u.cpp::log#2"),+ ("u.cpp::run", "u.cpp::emit#0"),+ ("u.cpp::run", "u.cpp::emit#2"),+ } <= edges++ def test_a_template_function_is_a_function(self) -> None:+ """A one-line template definition used to come out as a ``class``."""+ source = (+ "template <typename T> T two(T x, T y) { return x; }\n"+ "template <typename T> T two(T x) { return x; }\n"+ "template <typename T>\nT one(T x) { return x; }\n"+ )+ parsed = _parse("t.h", "cpp", source)+ assert [(s.id, s.kind) for s in parsed.symbols] == [+ ("t.h::two#2", "function"),+ ("t.h::two#1", "function"),+ ("t.h::one", "function"),+ ]++ def test_operator_overloads(self) -> None:+ source = (+ "V V::operator-() const { return *this; }\n"+ "V V::operator-(const V& o) const { return o; }\n"+ "bool Cmp::operator()(int a) const { return a; }\n"+ "bool Cmp::operator()(int a, int b) const { return a < b; }\n"+ "bool Cmp::operator==(const Cmp& o) const { return true; }\n"+ )+ ids = set(_ids(_parse("v.cpp", "cpp", source)))+ assert {"v.cpp::V::operator-#0", "v.cpp::V::operator-#1"} <= ids+ assert {"v.cpp::Cmp::operator()#1", "v.cpp::Cmp::operator()#2"} <= ids+ assert "v.cpp::Cmp::operator==" in ids++class TestOtherLanguagesAreUntouched:@pytest.mark.parametrize(("rel", "language", "text"),[("m.py", "python", "def f(a):\n pass\n\ndef f(a, b):\n pass\n"),- ("m.cpp", "cpp", "int f(int a) { return a; }\nint f(int a, int b) { return a; }\n"),+ ("m.c", "c", "int f(int a) { return a; }\nint f(int a, int b) { return a; }\n"),("m.kt", "kotlin", "class K {\n fun f(a: Int) {}\n fun f(a: Int, b: Int) {}\n}\n"),],)@@ -356,7 +509,7 @@ def test_fixture_ids_carry_a_discriminator_only_on_collision() -> None:checked += 1if symbol.id == base and "`" not in symbol.id:continue- assert symbol.language in ("java", "csharp"), symbol.id+ assert symbol.language in ("java", "csharp", "cpp"), symbol.idassert bases.count(base) > 1 or "`" in symbol.id, symbol.idassert checked > 500