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(ingestion): resolve C++ scoped calls against their qualifier (#1915)
Raghav Chamadiya354269f101dd
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 2bdba3178..d3f8c5ebe 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -138,7 +138,9 @@ _JVM_STRATEGIES = _LanguageCallStrategies(member=("_resolve_jvm_receiver_same_package",),)-_CPP_STRATEGIES = _LanguageCallStrategies(free=("_resolve_cpp_same_target",))+_CPP_STRATEGIES = _LanguageCallStrategies(+ free=("_resolve_cpp_scoped_call", "_resolve_cpp_same_target"),+)# Rust's crate-root strategy is deliberately absent: it runs for every language# today, and gating it here would drop crate-name receivers in mixed repos.@@ -536,6 +538,56 @@ class CallResolver:self._cpp_index = build_cpp_workspace_index(_Ctx(self._repo_path, self._parsed_files))return self._cpp_index+ def _collapse_declarations(self, sym_ids: list[str]) -> set[str]:+ """Fold each declaration onto the definition it was paired with.++ Two ids naming one symbol must not read as an ambiguity.+ """+ return {self._decl_to_def.get(sym_id, sym_id) for sym_id in sym_ids}++ def _resolve_cpp_scoped_call(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ ) -> ResolvedCall | None:+ """Resolve ``Qualifier::name()`` against the class the qualifier names.++ The qualifier is written at the call site, so this infers nothing: the+ repository either declares ``Qualifier::name`` or it does not. Before+ it existed only the leaf name survived extraction, and `DB::Open()`+ bound to a test class's `Open`.++ It declines rather than refusing when the pair is unknown, because a+ qualifier may equally name a NAMESPACE and C++ namespaces are recorded+ on no symbol -- so absence here is not evidence of anything.+ """+ scope = call.scope_name+ if not scope:+ return None+ candidates = self._global_methods.get((scope, call.target_name))+ if not candidates:+ return None+ # A class name is not repository-unique. Prefer a declaration this file+ # actually includes; failing that accept a repo-wide unique one, and+ # otherwise leave it, because the qualifier has not settled which.+ imported = self._import_targets.get(file_path, ())+ preferred = [+ sym_id for f, sym_id in candidates if f == file_path or f in imported+ ]+ # A header's declaration and the .cc's definition are ONE symbol, and a+ # translation unit routinely sees both, so count them after the pairing+ # redirect or every paired method reads as ambiguous.+ if len(self._collapse_declarations(preferred)) == 1:+ sym_id = preferred[0]+ elif len(self._collapse_declarations([c[1] for c in candidates])) == 1:+ sym_id = candidates[0][1]+ else:+ return None+ if sym_id == caller_id:+ return None+ return ResolvedCall(caller_id, sym_id, 0.93, call.line, "scoped_name")+def _resolve_cpp_same_target(self,file_path: str,diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 3f8c5e0bb..6be328ad5 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -282,6 +282,10 @@ class CallSite:line: int # 1-indexed line number of the callargument_count: int | None # number of arguments (None if unknown)receiver_call: CallReceiver | None = None # set only for a captured chained call+ # C++ `Ns::f()` / `Class::m()`: the qualifier as written. Kept apart from+ # ``receiver_name`` because that field routes to the member strategies,+ # and cpp has none -- a scoped call must stay on the free-call path.+ scope_name: str | None = Noneedge_type: CallSiteEdgeType = "calls" # see ``CallSiteEdgeType``@@ -401,6 +405,11 @@ ResolutionOrigin = Literal["crate_root", # 0.88 — Rust crate-scoped reference"receiver_import", # 0.88 — receiver class found in an imported file"import_merged", # 0.85 — in *some* imported file; which one is unattributed+ # 0.93 — C/C++ `Qualifier::name()`. The class is written at the call+ # site and declares the method, so nothing is inferred; it ranks with+ # `receiver_same_file` because both rest on a class NAME matching, and+ # two namespaces may spell one class name.+ "scoped_name","same_target", # 0.85 — C/C++ sibling TU of the same build target# 0.75 — the (class, method) pair exists somewhere in the repo. The member# analogue of `global_unique`, and no more than that: the strategy isdiff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 7aa09ab11..2013d6de9 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -1265,6 +1265,7 @@ class ASTParser:arg_nodes = capture_dict.get("call.arguments", [])receiver_nodes = capture_dict.get("call.receiver", [])receiver_call_nodes = capture_dict.get("call.receiver_call", [])+ scope_nodes = capture_dict.get("call.scope", [])if not site_nodes or not target_nodes:continue@@ -1286,6 +1287,7 @@ class ASTParser:if receiver_call_nodeselse None)+ scope_name = _node_text(scope_nodes[0], src).strip() if scope_nodes else Nonearg_count: int | None = Noneif arg_nodes:@@ -1302,6 +1304,7 @@ class ASTParser:line=line,argument_count=arg_count,receiver_call=receiver_call,+ scope_name=scope_name,edge_type=("references"if site_node.type in config.reference_call_node_types@@ -1314,9 +1317,13 @@ class ASTParser:for call in calls:key = (call.line, call.target_name, call.receiver_name)existing = deduplicated.get(key)- if existing is None or (- existing.receiver_call is None- and call.receiver_call is not None+ # Two patterns match a scoped call (one keeps the qualifier, one does+ # not) and both dedup to this key, so the richer record has to win+ # whichever order they arrive in.+ if (+ existing is None+ or (existing.receiver_call is None and call.receiver_call is not None)+ or (existing.scope_name is None and call.scope_name is not None)):deduplicated[key] = callreturn list(deduplicated.values())diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scmindex 5a0741869..4ec3284a4 100644--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm@@ -224,6 +224,19 @@arguments: (argument_list) @call.arguments) @call.site+; The same call again, keeping the qualifier. A tree-sitter field is required+; once named, so `::free()` (no scope) would stop matching if the capture were+; added above; both patterns therefore run and the parser's dedup keeps the one+; that carried a scope. `DB::Open()` was resolving to a test class's `Open`+; because only the leaf name survived extraction.+(call_expression+ function: (qualified_identifier+ scope: (_) @call.scope+ name: (identifier) @call.target+ )+ arguments: (argument_list) @call.arguments+) @call.site+; Chained call: obj.method1().method2(args)(call_expressionfunction: (field_expressiondiff --git a/packages/types/src/graph.ts b/packages/types/src/graph.tsindex dae64b00e..e70ebdfd6 100644--- a/packages/types/src/graph.ts+++ b/packages/types/src/graph.ts@@ -256,6 +256,7 @@ export type ResolutionOrigin =| "crate_root"| "receiver_import"| "import_merged"+ | "scoped_name"| "same_target"| "receiver_global"| "global_unique"diff --git a/packages/ui/__tests__/graph/edge-provenance.test.ts b/packages/ui/__tests__/graph/edge-provenance.test.tsindex 551cbaf8c..918bfd764 100644--- a/packages/ui/__tests__/graph/edge-provenance.test.ts+++ b/packages/ui/__tests__/graph/edge-provenance.test.ts@@ -35,6 +35,7 @@ const ALL_ORIGINS: ResolutionOrigin[] = ["crate_root","receiver_import","import_merged",+ "scoped_name","same_target","receiver_global","global_unique",diff --git a/packages/ui/src/graph/edge-provenance.ts b/packages/ui/src/graph/edge-provenance.tsindex 9d008f084..d05be7734 100644--- a/packages/ui/src/graph/edge-provenance.ts+++ b/packages/ui/src/graph/edge-provenance.ts@@ -113,6 +113,11 @@ const ORIGINS = {because: "the name is in one of the imported files, and we cannot say which",tier: "scoped",},+ scoped_name: {+ label: "Qualified at the call site",+ because: "the call names the class, and that class declares this method",+ tier: "scoped",+ },same_target: {label: "Same build target",because: "the target is a sibling translation unit of the same build target",diff --git a/tests/unit/ingestion/test_cpp_scoped_calls.py b/tests/unit/ingestion/test_cpp_scoped_calls.pynew file mode 100644index 000000000..4660e80ad--- /dev/null+++ b/tests/unit/ingestion/test_cpp_scoped_calls.py@@ -0,0 +1,102 @@+"""A C++ ``Qualifier::name()`` call must resolve against the qualifier.++``cpp.scm``'s scoped-call pattern captured only ``name: (identifier)``, so the+qualifier written at the call site was discarded and the resolver matched the+leaf name alone. Measured on leveldb before the fix: ``DB::Open(...)`` bound to+a test class's ``RecoveryTest::Open`` and ``Status::Corruption(...)`` to+``CorruptionReporter::Corruption`` -- 52 sites where the source names a class+and we answered with a different one, plus 104 on aria2.++The qualifier is read from source, so this resolves without inferring anything.+Where it cannot help it must DECLINE rather than refuse: a qualifier may name a+namespace, and C++ namespaces are recorded on no symbol.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+++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 _call_targets(graph, caller_file: str) -> set[str]:+ return {+ t+ for s, t, d in graph.edges(data=True)+ if d.get("edge_type") == "calls" and str(s).startswith(caller_file + "::")+ }+++def _decoy_repo(root: Path) -> None:+ """Two classes declare ``Open``; only one is named at the call site."""+ (root / "lib").mkdir(parents=True, exist_ok=True)+ (root / "test").mkdir(parents=True, exist_ok=True)+ (root / "lib" / "db.h").write_text(+ "#pragma once\nclass DB {\n public:\n static int Open(int flags);\n};\n"+ )+ (root / "lib" / "db.cc").write_text(+ '#include "lib/db.h"\nint DB::Open(int flags) { return flags; }\n'+ )+ # the decoy: same method name, different class, in a file the caller does+ # not name at the call site+ (root / "test" / "harness.cc").write_text(+ "class RecoveryTest {\n public:\n int Open(int f) { return f + 1; }\n};\n"+ )+ (root / "lib" / "caller.cc").write_text(+ '#include "lib/db.h"\nint Run() { return DB::Open(2); }\n'+ )+++class TestScopedCallUsesTheQualifier:+ def test_resolves_to_the_class_named_at_the_call_site(self, tmp_path: Path) -> None:+ _decoy_repo(tmp_path)+ targets = _call_targets(_build(tmp_path), "lib/caller.cc")+ assert any(t.endswith("DB::Open") for t in targets)++ def test_does_not_bind_to_a_same_named_method_on_another_class(+ self, tmp_path: Path+ ) -> None:+ _decoy_repo(tmp_path)+ targets = _call_targets(_build(tmp_path), "lib/caller.cc")+ assert not any("RecoveryTest" in t for t in targets)++ def test_declaration_and_its_definition_are_not_read_as_ambiguous(+ self, tmp_path: Path+ ) -> None:+ """The header declares ``DB::Open`` and the .cc defines it.++ A translation unit sees both, and counting them as two candidates made+ every paired method decline.+ """+ _decoy_repo(tmp_path)+ targets = _call_targets(_build(tmp_path), "lib/caller.cc")+ assert any(t.endswith("DB::Open") for t in targets)++ def test_qualifier_naming_no_known_class_still_resolves_by_other_tiers(+ self, tmp_path: Path+ ) -> None:+ """A namespace qualifier must DECLINE, not refuse.++ C++ namespaces are recorded on no symbol, so `util::Helper()` cannot be+ matched on its qualifier; the remaining tiers must still see it.+ """+ (tmp_path / "util.h").write_text(+ "#pragma once\nnamespace util {\nint Helper(int v);\n}\n"+ )+ (tmp_path / "util.cc").write_text(+ '#include "util.h"\nnamespace util {\nint Helper(int v) { return v; }\n}\n'+ )+ (tmp_path / "main.cc").write_text(+ '#include "util.h"\nint main() { return util::Helper(1); }\n'+ )+ targets = _call_targets(_build(tmp_path), "main.cc")+ assert any(t.endswith("Helper") for t in targets)