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
feat(graph): type C++ calls on member fields from the class declaration (#4825)
Swati Ahujaaa2c16f45c24
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.pyindex b7cee6293..8d4c7156d 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py@@ -60,6 +60,7 @@ from ._shared import ( # noqa: F401_store_capped,)from .callbacks import CallbackParameterTypes, _TypedCallback+from .cpp import CppFieldOwnersfrom .framework import FrameworkReceiverTypesfrom .go import GoReturnTypesfrom .java import _JAVA_TYPE_PARAMETERS, JavaTypeVisibility, _header_type_parameters # noqa: F401@@ -192,6 +193,7 @@ class ReceiverTypingMixin(RangeVariableTypes,CallbackParameterTypes,FrameworkReceiverTypes,+ CppFieldOwners,):"""Typed-receiver and C# extension strategies, with the source caches they read."""@@ -225,6 +227,10 @@ class ReceiverTypingMixin(self._framework_types: dict[str, dict[str, str]] = {}self._external_names: dict[str, frozenset[str]] = {}self._method_name_set: frozenset[str] | None = None+ # C++: {(file, class name): (header, class id) or None}, {declaration id: pure virtual}.+ self._cpp_declaring_classes: dict[tuple[str, str], tuple[str, str] | None] = {}+ self._pure_virtuals: dict[str, bool] = {}+ self._pure_virtual_name_set: frozenset[str] | None = Noneself._framework_name_set: frozenset[str] | None = Nonedef _merged_extension_methods_for(self, file_path: str) -> dict[tuple[str, str], str]:@@ -502,14 +508,16 @@ class ReceiverTypingMixin(if "::" in type_name:# A symbol id, recorded by ``_add_call_typed_locals``.return self._call_typed_receiver(file_path, call, caller_id, type_name)- if self._means_the_wrapper(file_path, caller_id, language, call, receiver_name):+ if self._means_the_wrapper(file_path, caller_id, language, call, receiver_name, scope):return Nonefound = self._typed_receiver_target(typing_file, call, caller_id, type_name)if found is None:# Last, because C# and Kotlin prefer a member to an extension.return self._extension_call(file_path, call, caller_id, type_name)[1]- sym_id, tier = found+ sym_id, tier = self._typed_callee(found[0], caller_id), found[1]+ if sym_id is None:+ return Noneif scope == "framework":return self._framework_typed_call(caller_id, sym_id, tier, call.line)if scope == "field":@@ -579,11 +587,11 @@ class ReceiverTypingMixin("""if not builtin_local and name in self._bound_names_in(file_path, caller_id, language):return None- class_id = self._caller_class_id(caller_id)- fields = self._field_types_in(file_path, language).get(class_id, {})+ class_file, class_id = self._field_owner(file_path, caller_id, language)+ fields = self._field_types_in(class_file, language).get(class_id, {})if name in fields:field = fields[name]- return None if builtin_local and external_type_name(field) else (field, "field", file_path)+ return None if builtin_local and external_type_name(field) else (field, "field", class_file)if builtin_local:return Noneinherited = self._inherited_field(file_path, caller_id, class_id, name, language)@@ -1069,6 +1077,7 @@ class ReceiverTypingMixin(language: str,call: CallSite,receiver_name: str,+ scope: str = "body",) -> bool:"""Is this call on the smart pointer itself rather than on what it holds?@@ -1077,15 +1086,19 @@ class ReceiverTypingMixin(apart. The names a dot call can reach are closed by the language, sorefusing exactly those is what keeps ``p.get()`` off a repo's own``Foo::get`` -- at the cost of an arrow call that really did mean one.- Asked only of C++, and only of a type that was unwrapped.+ Asked only of C++, and only of a type that was unwrapped. A field is+ read in its class's span, which may sit in a header."""if language != "cpp" or call.target_name not in POINTER_LIKE_MEMBERS:return False- span = self._spans_for(file_path).get(caller_id)+ owner_file, owner = file_path, caller_id+ if scope == "field":+ owner_file, owner = self._field_owner(file_path, caller_id, language)+ span = self._spans_for(owner_file).get(owner)if span is None:return Falsereturn receiver_name in unwrapped_names_in_span(- self._declarations_for(file_path, language), *span+ self._declarations_for(owner_file, language), *span)def _body_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/cpp.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/cpp.pynew file mode 100644index 000000000..5162f802b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/cpp.py@@ -0,0 +1,111 @@+"""C++ receiver typing: the class a method reads its fields from, and the callee it lands on."""++from __future__ import annotations++import re++from ..models import Symbol+from ..type_names import strip_type_arguments++# ``virtual void f() = 0;``, a trailing ``const``/``override`` included.+_PURE_VIRTUAL = re.compile(r"=\s*0\s*;")+++class CppFieldOwners:+ """The class a C++ method body reads its fields from, and the callee a typed call lands on."""++ def _field_owner(self, file_path: str, caller_id: str, language: str) -> tuple[str, str]:+ """``(file, class id)`` whose fields *caller_id* reads by bare name.++ The caller's own class, except for a C++ body defined out of line+ (``void Builder::Run() {..}`` in a ``.cc``): its class is declared in+ a header, so it is looked for there.+ """+ class_id = self._caller_class_id(caller_id)+ if language == "cpp" and class_id not in self._symbols_by_id:+ found = self._cpp_declaring_class(file_path, caller_id)+ if found is not None:+ return found+ return file_path, class_id++ def _cpp_declaring_class(self, file_path: str, caller_id: str) -> tuple[str, str] | None:+ """``(header, class id)`` an out-of-line method's class is declared in.++ Looked for in the caller's file and the files it includes directly,+ and taken only when exactly one of them declares one type of that+ name: two candidates leave the class unsettled, and a field read off+ the wrong one would type the receiver wrongly. Ceiling: the name is+ compared bare, so a namespace that only a transitive include tells+ apart is not seen.+ """+ caller = self._symbols_by_id.get(caller_id)+ owner = strip_type_arguments(caller.parent_name or "").strip() if caller else ""+ if not owner.isidentifier():+ return None+ key = (file_path, owner)+ if key not in self._cpp_declaring_classes:+ found = [+ (path, class_id)+ for path in (file_path, *sorted(self._import_targets.get(file_path, ())))+ if (class_id := self._defined_type_in(path, owner)) is not None+ ]+ self._cpp_declaring_classes[key] = found[0] if len(found) == 1 else None+ return self._cpp_declaring_classes[key]++ def _defined_type_in(self, path: str, name: str) -> str | None:+ """The one type *path* declares as *name*, unless only forward-declared."""+ class_id = self._only_type_in(path, name)+ symbol = self._symbols_by_id.get(class_id or "")+ return None if symbol is None or symbol.is_declaration else class_id++ def _typed_callee(self, sym_id: str, caller_id: str) -> str | None:+ """The callee a typed receiver's method *sym_id* stands for, or None.++ A C/C++ header declaration paired with the caller's own body is a+ recursive call. An unpaired one is the callee only as a pure virtual,+ which no body defines. Any other has a body the pairing could not+ settle (platform variants, a generated source beside its template, a+ definition the parse lost), and the declaration is not that body.+ A self call is left to ``resolve_file``, which decides on those.+ """+ symbol = self._symbols_by_id.get(sym_id)+ if symbol is None or not symbol.is_declaration or symbol.language not in ("c", "cpp"):+ return sym_id+ defined = self._decl_to_def.get(sym_id)+ if defined is not None:+ return caller_id if defined == caller_id else sym_id+ pure = self._pure_virtuals.get(sym_id)+ if pure is None:+ path = self._symbol_paths_by_id.get(sym_id, "")+ pure = self._pure_virtuals[sym_id] = _is_pure(self._text_of(path).splitlines(), symbol)+ return sym_id if pure else None++ def _pure_virtual_names(self) -> frozenset[str]:+ """Method names a C/C++ pure virtual declares and no body defines, built once.++ Those are the only bodiless names a member call may reach: a plain+ declaration nothing defines is no callee (see ``_typed_callee``), so+ admitting its name would let a receiver-name match land on it.+ """+ if self._pure_virtual_name_set is None:+ names: set[str] = set()+ for path, parsed in self._parsed_files.items():+ candidates = [+ sym+ for sym in parsed.symbols+ if sym.is_declaration+ and sym.parent_name+ and sym.language in ("c", "cpp")+ and sym.name not in self._global_symbols+ and sym.name not in names+ ]+ lines = self._text_of(path).splitlines() if candidates else []+ names.update(sym.name for sym in candidates if _is_pure(lines, sym))+ self._pure_virtual_name_set = frozenset(names)+ return self._pure_virtual_name_set+++def _is_pure(lines: list[str], symbol: Symbol) -> bool:+ """Whether *symbol*'s declaration lines end in ``= 0;``."""+ span = lines[max(symbol.start_line - 1, 0) : symbol.end_line]+ return bool(_PURE_VIRTUAL.search(" ".join(span)))diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 2253a11c8..0dfae9f5e 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -1761,11 +1761,8 @@ class CallResolver(# Every strategy below ends in a lookup keyed on the method name, so a# name the repo declares nowhere cannot resolve.- # A Go interface method spec is bodiless, so ``_global_symbols`` leaves it- # out; the method index holds it, and it is what an interface-typed- # receiver binds to.- if method_name not in self._global_symbols and not (- self._language_of(file_path) == "go" and method_name in self._method_names()+ if method_name not in self._global_symbols and not self._bodiless_callee_named(+ file_path, method_name):return False, None@@ -1813,6 +1810,18 @@ class CallResolver(return True, Nonereturn hit is not None, hit+ def _bodiless_callee_named(self, file_path: str, method_name: str) -> bool:+ """Whether a bodiless method ``_global_symbols`` leaves out can be the callee.++ A Go interface method spec and a C++ pure virtual are what an+ interface-typed receiver binds to. A C++ declaration nothing defines+ is not, so only pure virtual names are admitted there.+ """+ language = self._language_of(file_path)+ if language == "go":+ return method_name in self._method_names()+ return language == "cpp" and method_name in self._pure_virtual_names()+def _go_receiver_is_variable(self, file_path: str, call: CallSite, caller_id: str) -> bool:"""Whether a Go call's receiver is a typed local, parameter or ``var`` of the caller."""receiver_name = call.receiver_name or ""diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex 44414cb30..862f5ff38 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -373,7 +373,7 @@ RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)# writes ``self.foo.bar()``, a dotted receiver the grammar mints no call site# for, so class scope could only bind a bare local to a field. Membership rests# on the scan actually finding typed fields in the language's idiom.-IMPLICIT_FIELD_LANGUAGES = frozenset({"apex", "csharp", "dart", "java", "kotlin", "swift"})+IMPLICIT_FIELD_LANGUAGES = frozenset({"apex", "cpp", "csharp", "dart", "java", "kotlin", "swift"})# Languages whose scan keeps a declaration of a builtin type, marked external,# so the resolver can refuse a call on it instead of matching the method name.@@ -570,6 +570,12 @@ _LOCAL_NAME_SHAPES: dict[str, tuple[tuple[re.Pattern[str], ...], ...]] = {),),),+ # An `auto` local and a structured binding spell no type the scan reads,+ # but still hide a field of their name.+ "cpp": (+ (re.compile(r"(?<![\w.])auto\s*[*&]{0,2}\s*(?P<name>[a-z_]\w*)\b"),),+ (re.compile(r"(?<![\w.])auto\s*&{0,2}\s*\[(?P<lhs>[\w\s,]*)\]"),),+ ),"java": _JAVA_LAMBDA,"kotlin": ((diff --git a/tests/unit/ingestion/test_cpp_typed_receivers.py b/tests/unit/ingestion/test_cpp_typed_receivers.pyindex 9c2943a86..2cde33d3e 100644--- a/tests/unit/ingestion/test_cpp_typed_receivers.py+++ b/tests/unit/ingestion/test_cpp_typed_receivers.py@@ -109,3 +109,192 @@ class TestSmartPointerReceivers:"""``items.sendMessage()`` is not ``Peer::sendMessage`` on a vector."""_repo(tmp_path, " std::vector<Peer> items;\n return items.sendMessage(1);")assert not any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))+++def _field_repo(root: Path, run_body: str) -> None:+ """``Peer``/``Stranger`` plus a ``Host`` class holding fields, its method out of line."""+ _repo(root, " return 0;")+ (root / "lib" / "sink.h").write_text(+ "#pragma once\nclass Sink {\n public:\n virtual ~Sink() {}\n"+ " virtual void sendMessage(int n) = 0;\n};\n"+ )+ (root / "lib" / "host.h").write_text(+ '#pragma once\n#include <memory>\n#include "peer.h"\n#include "sink.h"\n'+ "class Host {\n public:\n void Run();\n int Inline() { return peer_.sendMessage(1); }\n"+ " private:\n Peer peer_;\n Peer* peer_ptr_;\n Sink* sink_;\n"+ " std::unique_ptr<Peer> owned_;\n Host* parent_;\n};\n"+ )+ (root / "lib" / "host.cc").write_text(+ '#include "host.h"\nvoid Host::Run() {\n' + run_body + "\n}\n"+ )+++def _callees(graph, caller: str) -> set[str]:+ return {+ t for s, t, d in graph.edges(data=True) if d.get("edge_type") == "calls" and s == caller+ }+++class TestFieldReceivers:+ def test_an_out_of_line_body_reads_the_field_its_header_declares(self, tmp_path: Path) -> None:+ _field_repo(tmp_path, " peer_.sendMessage(1);\n peer_ptr_->sendMessage(2);")+ callees = _callees(_build(tmp_path), "lib/host.cc::Host::Run")+ assert "lib/peer.cc::Peer::sendMessage" in callees+ assert not any("Stranger" in t for t in callees)++ def test_an_inline_body_reads_its_own_class_field(self, tmp_path: Path) -> None:+ _field_repo(tmp_path, "")+ assert "lib/peer.cc::Peer::sendMessage" in _callees(+ _build(tmp_path), "lib/host.h::Host::Inline"+ )++ def test_an_interface_pointer_field_binds_the_pure_virtual(self, tmp_path: Path) -> None:+ """The interface declares the method and nothing defines it: that is the callee."""+ _field_repo(tmp_path, " sink_->sendMessage(1);")+ callees = _callees(_build(tmp_path), "lib/host.cc::Host::Run")+ assert callees == {"lib/sink.h::Sink::sendMessage"}++ def test_a_smart_pointer_field_binds_what_it_holds(self, tmp_path: Path) -> None:+ _field_repo(tmp_path, " owned_->sendMessage(1);")+ assert "lib/peer.cc::Peer::sendMessage" in _callees(+ _build(tmp_path), "lib/host.cc::Host::Run"+ )++ def test_a_name_the_pointer_field_declares_is_refused(self, tmp_path: Path) -> None:+ """``owned_.get()`` is ``unique_ptr::get``, though ``Peer`` declares ``get``."""+ _field_repo(tmp_path, " owned_.get(1);")+ assert "lib/peer.cc::Peer::get" not in _callees(_build(tmp_path), "lib/host.cc::Host::Run")++ def test_an_auto_local_hides_the_field(self, tmp_path: Path) -> None:+ _field_repo(tmp_path, " auto peer_ = Make();\n peer_.sendMessage(1);")+ assert "lib/peer.cc::Peer::sendMessage" not in _callees(+ _build(tmp_path), "lib/host.cc::Host::Run"+ )++ def test_two_included_classes_of_the_name_refuse(self, tmp_path: Path) -> None:+ """Which ``Host`` the body belongs to is unsettled, so no field is read."""+ _field_repo(tmp_path, " peer_.sendMessage(1);")+ (tmp_path / "lib" / "other.h").write_text(+ "#pragma once\nclass Host {\n Stranger peer_;\n};\n"+ )+ (tmp_path / "lib" / "host.cc").write_text(+ '#include "host.h"\n#include "other.h"\nvoid Host::Run() {\n'+ " peer_.sendMessage(1);\n}\n"+ )+ callees = _callees(_build(tmp_path), "lib/host.cc::Host::Run")+ assert not any("sendMessage" in t for t in callees)++ def test_a_declaration_two_bodies_define_is_refused(self, tmp_path: Path) -> None:+ """Platform variants each define ``Peer::get``: which one runs is unknown."""+ _field_repo(tmp_path, " peer_ptr_->get(1);")+ for name in ("peer-posix.cc", "peer-win32.cc"):+ (tmp_path / "lib" / name).write_text(+ '#include "peer.h"\nint Peer::get(int n) { return n; }\n'+ )+ (tmp_path / "lib" / "peer.cc").write_text(+ '#include "peer.h"\nint Peer::sendMessage(int n) { return n; }\n'+ )+ callees = _callees(_build(tmp_path), "lib/host.cc::Host::Run")+ assert not any(t.endswith("::get") for t in callees)++ def test_a_call_into_its_own_body_lands_on_no_declaration(self, tmp_path: Path) -> None:+ """``parent_->Run()`` inside ``Host::Run`` recurses; the header line is not the callee."""+ _field_repo(tmp_path, " parent_->Run();")+ callees = _callees(_build(tmp_path), "lib/host.cc::Host::Run")+ assert "lib/host.h::Host::Run" not in callees++ def test_a_typed_local_hides_the_field(self, tmp_path: Path) -> None:+ _field_repo(tmp_path, " Stranger peer_;\n peer_.sendMessage(1);")+ callees = _callees(_build(tmp_path), "lib/host.cc::Host::Run")+ assert "lib/peer.cc::Stranger::sendMessage" in callees+ assert "lib/peer.cc::Peer::sendMessage" not in callees+++class TestTypedCalleeOnHeaderDeclarations:+ """A typed call lands on a header declaration only where no body could be missing."""++ @staticmethod+ def _callee(symbols, decl_to_def, sym_id, caller_id, text=""):+ from types import SimpleNamespace++ from repowise.core.ingestion.call_receiver_typing.cpp import CppFieldOwners++ owner = SimpleNamespace(+ _symbols_by_id=symbols,+ _decl_to_def=decl_to_def,+ _pure_virtuals={},+ _symbol_paths_by_id={sym_id: "a.h"},+ _text_of=lambda _path: text,+ )+ return CppFieldOwners._typed_callee(owner, sym_id, caller_id)++ @staticmethod+ def _decl(sym_id):+ from types import SimpleNamespace++ return SimpleNamespace(is_declaration=True, language="cpp", start_line=1, end_line=1)++ def test_an_unpaired_non_virtual_declaration_is_no_callee(self) -> None:+ sym = "a.h::P::f"+ assert self._callee({sym: self._decl(sym)}, {}, sym, "c.cc::Run", "int f(int n);") is None++ def test_an_unpaired_pure_virtual_is_the_callee(self) -> None:+ sym = "a.h::P::f"+ text = "virtual int f(int n) = 0;"+ assert self._callee({sym: self._decl(sym)}, {}, sym, "c.cc::Run", text) == sym++ def test_a_declaration_paired_with_the_callers_own_body_is_the_caller(self) -> None:+ sym = "a.h::P::f"+ assert (+ self._callee({sym: self._decl(sym)}, {sym: "c.cc::Run"}, sym, "c.cc::Run")+ == "c.cc::Run"+ )++ def test_a_declaration_paired_with_another_body_is_kept(self) -> None:+ sym = "a.h::P::f"+ assert self._callee({sym: self._decl(sym)}, {sym: "p.cc::P::f"}, sym, "c.cc::Run") == sym++ def test_a_typed_call_onto_an_unpaired_declaration_yields_no_edge(self, tmp_path: Path) -> None:+ (tmp_path / "lone.h").write_text("#pragma once\nclass Lone {\n public:\n int run(int n);\n};\n")+ (tmp_path / "caller.cc").write_text(+ '#include "lone.h"\nint Go() {\n Lone* l;\n return l->run(1);\n}\n'+ )+ assert _call_targets(_build(tmp_path), "caller.cc") == set()++ def test_a_typed_call_onto_a_paired_declaration_lands_on_the_definition(+ self, tmp_path: Path+ ) -> None:+ _repo(tmp_path, " Peer* peer;\n return peer->get(1);")+ assert _call_targets(_build(tmp_path), "lib/caller.cc") == {"lib/peer.cc::Peer::get"}+++def _receiver_named_like_a_class_repo(root: Path, declaration: str) -> None:+ """A ``Sink`` parameter named ``buffer``, and a class ``buffer`` declaring ``flush``."""+ (root / "lib").mkdir(parents=True, exist_ok=True)+ (root / "lib" / "buffer.h").write_text(+ "#pragma once\nclass buffer {\n public:\n " + declaration + "\n};\n"+ "class Sink {\n public:\n void write();\n};\n"+ )+ (root / "lib" / "sink.cc").write_text('#include "lib/buffer.h"\nvoid Sink::write() {}\n')+ (root / "lib" / "caller.cc").write_text(+ '#include "lib/buffer.h"\nvoid Run(Sink& buffer) {\n buffer.flush();\n}\n'+ )+++class TestBodilessMemberNames:+ """A method name only a bodiless C++ declaration carries reaches a member call as a pure virtual only."""++ def test_a_declared_never_defined_method_gets_no_edge_from_an_unrelated_receiver(+ self, tmp_path: Path+ ) -> None:+ """``buffer`` is a ``Sink``; the receiver-name tier must not land on ``buffer::flush``."""+ _receiver_named_like_a_class_repo(tmp_path, "void flush();")+ assert _call_targets(_build(tmp_path), "lib/caller.cc") == set()++ def test_a_pure_virtual_name_is_still_admitted(self, tmp_path: Path) -> None:+ """The control: an interface pointer still binds the pure virtual nothing defines."""+ _receiver_named_like_a_class_repo(tmp_path, "virtual void flush() = 0;")+ (tmp_path / "lib" / "caller.cc").write_text(+ '#include "lib/buffer.h"\nvoid Run(buffer* out) {\n out->flush();\n}\n'+ )+ assert _call_targets(_build(tmp_path), "lib/caller.cc") == {"lib/buffer.h::buffer::flush"}diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.pyindex 49827613f..a1ce04385 100644--- a/tests/unit/ingestion/test_receiver_types.py+++ b/tests/unit/ingestion/test_receiver_types.py@@ -1072,13 +1072,13 @@ class TestCppWrapperUnwrapping:assert declared_types("val c: Column<Thing> = x", "kotlin") == {"c": "Column"}-def test_cpp_is_not_a_field_language() -> None:- """C++ declares its fields in a header, away from the call that reads them.+def test_cpp_is_a_field_language() -> None:+ """C++ names a field bare, and declares it in a header away from the call.- Registering it would promise a scope the scan cannot answer from, which is- the condition that disqualified python on the same constant.+ An out-of-line body reads its fields from the class its includes declare+ (``CppFieldOwners._field_owner``), so class scope answers for it too."""- assert "cpp" not in IMPLICIT_FIELD_LANGUAGES+ assert "cpp" in IMPLICIT_FIELD_LANGUAGESdef test_c_has_no_shapes_of_its_own() -> None: