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): resolve C++ member calls to the class's header members and its bases (#4839)
Swati Ahuja23dfda916956
diff --git a/packages/core/src/repowise/core/ingestion/call_cpp_class_scope.py b/packages/core/src/repowise/core/ingestion/call_cpp_class_scope.pynew file mode 100644index 000000000..555b4588f--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/call_cpp_class_scope.py@@ -0,0 +1,160 @@+"""C++ calls inside a member function that its class answers: its own members, then its bases."""++from __future__ import annotations++import re++from .call_inheritance import _extract_class_id+from .call_receiver_typing._shared import _FUNCTION_KINDS, _TYPE_KINDS+from .models import CallSite+from .resolved_call import ResolvedCall+from .symbol_identity import outer_scope++# ``template <typename T, class Base = X>`` ahead of the class name it heads.+_TEMPLATE_HEAD = r"template\s*<(.*?)>\s*(?:class|struct)\s+{name}\b"+# A type parameter's name; ``typename std::size_t N`` names a value, not a type.+_TYPE_PARAMETER = re.compile(r"\b(?:typename|class)\b\s*(?:\.\.\.)?\s*(\w+)\b(?!\s*::)")+++class CppClassScopeMixin:+ """The member a bare or ``this->`` C++ call names, looked up from the caller's class."""++ def _cpp_class_member_call(+ self, file_path: str, call: CallSite, caller_id: str, *, bare: bool+ ) -> ResolvedCall | None:+ """The member of the caller's class, or the one its bases declare, that *call* names.++ The class's own member wins: one in the caller's file first, which the+ same-file tiers answer, then one the class declares in its header, so+ an out-of-line body in a ``.cc`` sees what the header declares. Bases+ answer only when no class of that name declares the member anywhere,+ since an own declaration hides theirs. A bare call in a class template+ skips the bases: C++ does not look a bare name up in a dependent base+ (``Base<T>``), while ``this->m()`` does. A call landing on the caller+ is recursion, which this tier leaves edgeless.+ """+ if self._language_of(file_path) != "cpp":+ return None+ caller = self._symbols_by_id.get(caller_id)+ if caller is None or not caller.parent_name:+ return None+ here = self._declares(_extract_class_id(caller_id) or "", call.target_name)+ if here is not None:+ return self._cpp_member_beside_caller(file_path, call, here, bare=bare)+ _, class_id = self._field_owner(file_path, caller_id, "cpp")+ if getattr(self._symbols_by_id.get(class_id), "kind", None) not in _TYPE_KINDS:+ return None+ own = self._declares(class_id, call.target_name)+ if own is not None:+ return self._cpp_scope_edge(call, own, "enclosing_class" if bare else "self_scope")+ return self._cpp_base_member_call(class_id, call, bare=bare)++ def _cpp_member_beside_caller(+ self, file_path: str, call: CallSite, here: str, *, bare: bool+ ) -> ResolvedCall | None:+ """The member *here* the caller's own file declares, when no other tier answers it.++ Tier 1 and Strategy 3 answer from the caller's own file, recursion+ included, except a bare name only a bodiless declaration holds.+ """+ if not bare or call.target_name in self._file_symbols.get(file_path, {}):+ return None+ return self._cpp_scope_edge(call, here, "enclosing_class")++ def _cpp_base_member_call(+ self, class_id: str, call: CallSite, *, bare: bool+ ) -> ResolvedCall | None:+ """The one member *class_id*'s bases declare under the call's name."""+ if (self._symbols_by_id[class_id].name, call.target_name) in self._global_methods:+ return None+ if bare and self._in_class_template(class_id):+ return None+ inherited = self._ancestor_method(class_id, call.target_name, call.caller_symbol_id or "")+ if inherited is None:+ return None+ origin = "enclosing_inherited" if bare else "self_inherited"+ return self._cpp_scope_edge(call, inherited, origin)++ def _cpp_scope_edge(self, call: CallSite, sym_id: str, origin: str) -> ResolvedCall | None:+ """The edge to member function *sym_id*, none for recursion or an unsettled prototype.++ A nested type or a field (``struct sigaction act_;``) is no callee, nor+ a constructor: ``Base(x)`` in an initializer list names the type, which+ the type tiers answer. A prototype no single body pairs with is left+ to the later tiers.+ """+ caller_id = call.caller_symbol_id or ""+ symbol = self._symbols_by_id.get(sym_id)+ if symbol is None or symbol.kind not in _FUNCTION_KINDS:+ return None+ if symbol.name == symbol.parent_name:+ return None+ if self._typed_callee(sym_id, caller_id) in (None, caller_id):+ return None+ confidence = 0.90 if origin.endswith("_inherited") else 0.95+ return ResolvedCall(caller_id, sym_id, confidence, call.line, origin)++ def _cpp_followed_parents(self, type_id: str, parents: set[str]) -> list[str]:+ """The parents of a C++ *type_id* its base clause can mean.++ Heritage binds a base by bare name, so ``ext::Widget`` or a template+ parameter ``Base`` lands on a same-named repository class.+ Kept: a parent declared in the child's file or one it includes,+ directly or not, that is no template parameter of the child.+ Ceiling: a qualified external base whose bare name a reachable+ repository class shares still binds.+ """+ child_file = self._symbol_paths_by_id.get(type_id, "")+ reach = self._cpp_include_closure(child_file)+ parameters = self._cpp_template_parameters(type_id)+ return sorted(+ parent+ for parent in parents+ if self._symbol_paths_by_id.get(parent) in reach+ and getattr(self._symbols_by_id.get(parent), "name", None) not in parameters+ )++ def _cpp_include_closure(self, file_path: str) -> frozenset[str]:+ """*file_path* and every repository file its includes reach."""+ closure = self._cpp_include_closures.get(file_path)+ if closure is None:+ seen, pending = {file_path}, [file_path]+ while pending:+ fresh = set(self._import_targets.get(pending.pop(), ())) - seen+ fresh &= self._parsed_files.keys()+ seen |= fresh+ pending.extend(fresh)+ closure = self._cpp_include_closures[file_path] = frozenset(seen)+ return closure++ def _in_class_template(self, class_id: str) -> bool:+ """Is *class_id* a class template, or nested in one?"""+ scope = class_id+ while "::" in scope:+ if self._cpp_template_parameters(scope):+ return True+ scope = outer_scope(scope)+ return False++ def _cpp_template_parameters(self, class_id: str) -> frozenset[str]:+ """The type parameter names of the class template *class_id*, empty for a class.++ A template's declaration and the class it wraps are two symbols under+ one id, so the head is read from the first one's line to the body.+ """+ found = self._cpp_template_names.get(class_id)+ if found is None:+ path = self._symbol_paths_by_id.get(class_id, "")+ parsed = self._parsed_files.get(path)+ symbols = parsed.symbols if parsed else ()+ spans = [(s.start_line, s.end_line) for s in symbols if s.id == class_id]+ found = frozenset()+ if spans:+ start, end = min(spans)[0], max(e for _, e in spans)+ text = "\n".join(self._text_of(path).splitlines()[start - 1 : end]).split("{", 1)[0]+ name = re.escape(self._symbols_by_id[class_id].name)+ head = re.search(_TEMPLATE_HEAD.format(name=name), text, re.S)+ if head is not None:+ found = frozenset(_TYPE_PARAMETER.findall(head.group(1)))+ self._cpp_template_names[class_id] = found+ return founddiff --git a/packages/core/src/repowise/core/ingestion/call_inheritance.py b/packages/core/src/repowise/core/ingestion/call_inheritance.pyindex beaa54964..5da4ae59a 100644--- a/packages/core/src/repowise/core/ingestion/call_inheritance.py+++ b/packages/core/src/repowise/core/ingestion/call_inheritance.py@@ -238,6 +238,13 @@ class InheritanceMixin:file_path, _, name = class_id.partition("::")return self._file_methods.get(file_path, {}).get((name.rpartition("::")[2], method_name))+ def _followed_parents(self, type_id: str) -> list[str]:+ """*type_id*'s resolved parents a walk follows, sorted."""+ parents = self._heritage_parents.get(type_id, set())+ if getattr(self._symbols_by_id.get(type_id), "language", None) == "cpp":+ return self._cpp_followed_parents(type_id, parents)+ return sorted(parents)+def _ancestors_of(self, class_id: str) -> tuple[str, ...]:got = self._ancestors.get(class_id)if got is None:@@ -247,7 +254,7 @@ class InheritanceMixin:# branch order decides the result and must be stable.reached = heritage_ancestors(class_id,- lambda t: sorted(self._heritage_parents.get(t, ())),+ self._followed_parents,max_expand_depth=_MAX_ANCESTOR_EXPAND_DEPTH,)reached.discard(class_id)diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 8d27cb1d3..1b04fab5e 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -39,6 +39,7 @@ from .call_barrel_forwarding import ( # noqa: F401_renames_on_the_way,)from .call_cobol import CobolCallsMixin+from .call_cpp_class_scope import CppClassScopeMixinfrom .call_inheritance import ( # noqa: F401_EXTERNAL_PREFIX,_MAX_ANCESTOR_EXPAND_DEPTH,@@ -301,6 +302,7 @@ class CallResolver(OverloadSelectionMixin,BarrelForwardingMixin,InheritanceMixin,+ CppClassScopeMixin,):"""Resolve raw CallSites to symbol-level edges.@@ -342,6 +344,9 @@ class CallResolver(else return_type_chain_languages)self._ancestors: dict[str, tuple[str, ...]] = {}+ # C++: {file: files its includes reach}, {class id: template parameter names}.+ self._cpp_include_closures: dict[str, frozenset[str]] = {}+ self._cpp_template_names: dict[str, frozenset[str]] = {}self._mros: dict[str, tuple[str, ...] | None] = {}# {type name: [(file, identity, arity)]}, filled by ``_declared_types_named``.self._declared_types: dict[str, list[tuple[str, tuple[str, ...], int]]] = {}@@ -1601,6 +1606,13 @@ class CallResolver(# A parameter or local of that name hides every tier below.if self._shadowed_by_local(file_path, call, caller_id):return None+ # A C++ class member hides a same-named function, so the caller's class+ # and its bases answer ahead of the flat same-file table. A qualified+ # ``ns::f()`` names its scope, not the caller's class.+ if not call.receiver_name and not call.scope_name:+ own = self._cpp_class_member_call(file_path, call, caller_id, bare=True)+ if own is not None:+ return own# Tier 1: same-filehandled, resolved = self._same_file_free_call(file_path, call, caller_id)@@ -2238,6 +2250,10 @@ class CallResolver("""if call.receiver_name not in ("self", "this"):return None+ if self._language_of(file_path) == "cpp":+ if call.receiver_name != "this":+ return None+ return self._cpp_class_member_call(file_path, call, caller_id, bare=False)if self._language_of(file_path) not in _INHERITED_LANGUAGES:return Nonesym_id = self._inherited_method(caller_id, call.target_name)diff --git a/tests/unit/ingestion/test_cpp_class_scope_calls.py b/tests/unit/ingestion/test_cpp_class_scope_calls.pynew file mode 100644index 000000000..f9c53ef5c--- /dev/null+++ b/tests/unit/ingestion/test_cpp_class_scope_calls.py@@ -0,0 +1,253 @@+"""A bare or ``this->`` C++ call inside a member function names its class's member, or a base's.++The own-class tier looked only in the caller's file, so an out-of-line body in+a ``.cc`` never saw the members its header declares, and C++ was left out of+the inherited tier, so a member a base class declares never resolved. A+same-named method of another class in the file answered instead.+"""++from __future__ import annotations++from dataclasses import replace+from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+++def _build(repo: Path, files: dict[str, str], this_calls: frozenset[str] = frozenset()):+ """The graph of *files*; a bare call to a name in *this_calls* is read as ``this->name()``."""+ for name, text in files.items():+ (repo / name).write_text(text)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in FileTraverser(repo).traverse():+ parsed = parser.parse_file(fi, Path(fi.abs_path).read_bytes())+ parsed.calls[:] = [+ replace(c, receiver_name="this") if c.target_name in this_calls else c+ for c in parsed.calls+ ]+ builder.add_file(parsed)+ return builder.build()+++def _calls(graph, caller: str) -> dict[str, str]:+ return {+ t: d.get("resolution_origin")+ for s, t, d in graph.edges(data=True)+ if d.get("edge_type") == "calls" and s == caller+ }+++_DISK_H = """#pragma once+#include <string>+struct DiskInterface {+ virtual long Stat(const std::string& path) const = 0;+ virtual bool MakeDir(const std::string& path) = 0;+ bool MakeDirs(const std::string& path);+};+struct RealDiskInterface : public DiskInterface {+ long Stat(const std::string& path) const override;+ bool MakeDir(const std::string& path) override;+};+"""++_DISK_CC = """#include "disk.h"+bool DiskInterface::MakeDirs(const std::string& path) {+ long mtime = Stat(path);+ if (!MakeDirs(path)) return false;+ return MakeDir(path);+}+long RealDiskInterface::Stat(const std::string& path) const { return 0; }+bool RealDiskInterface::MakeDir(const std::string& path) { return true; }+"""++_BUFFER_H = """#pragma once+namespace detail {+template <typename T> class buffer {+ public:+ void set(T* data, int n) {}+ int size() const { return 0; }+};+}+"""+++class TestOwnClassAcrossFiles:+ def test_out_of_line_body_reaches_the_member_its_header_declares(self, tmp_path: Path) -> None:+ graph = _build(tmp_path, {"disk.h": _DISK_H, "disk.cc": _DISK_CC})+ calls = _calls(graph, "disk.cc::DiskInterface::MakeDirs")+ assert calls.get("disk.h::DiskInterface::MakeDir") == "enclosing_class"+ assert calls.get("disk.h::DiskInterface::Stat") == "enclosing_class"+ # The same file's derived-class bodies are not the caller's class.+ assert "disk.cc::RealDiskInterface::MakeDir" not in calls++ def test_recursion_through_the_header_draws_no_edge(self, tmp_path: Path) -> None:+ graph = _build(tmp_path, {"disk.h": _DISK_H, "disk.cc": _DISK_CC})+ calls = _calls(graph, "disk.cc::DiskInterface::MakeDirs")+ assert not any(t.endswith("::MakeDirs") for t in calls)++ def test_inline_body_reaches_a_member_defined_out_of_line(self, tmp_path: Path) -> None:+ header = (+ "#pragma once\nstruct Node {\n bool Stat(int n);\n"+ " bool StatIfNecessary(int n) { return Stat(n); }\n};\n"+ )+ files = {+ "graph.h": header,+ "graph.cc": '#include "graph.h"\nbool Node::Stat(int n) { return true; }\n',+ "other.cc": "struct Edge { bool Stat(int n) { return false; } };\n",+ }+ calls = _calls(_build(tmp_path, files), "graph.h::Node::StatIfNecessary")+ assert calls == {"graph.cc::Node::Stat": "enclosing_class"}++ def test_a_body_in_the_callers_file_beats_the_header_declaration(self, tmp_path: Path) -> None:+ # Two files define the member, so the header declaration pairs with neither.+ lexer_cc = (+ '#include "lexer.h"\nint Lexer::ReadToken() { return 1; }\n'+ "int Lexer::PeekToken() { return ReadToken(); }\n"+ )+ files = {+ "lexer.h": "#pragma once\nstruct Lexer {\n int ReadToken();\n int PeekToken();\n};\n",+ "lexer.cc": lexer_cc,+ "lexer.in.cc": lexer_cc,+ }+ calls = _calls(_build(tmp_path, files), "lexer.cc::Lexer::PeekToken")+ assert calls == {"lexer.cc::Lexer::ReadToken": "same_file"}++ def test_this_call_in_an_out_of_line_body_reaches_the_header_member(+ self, tmp_path: Path+ ) -> None:+ graph = _build(tmp_path, {"disk.h": _DISK_H, "disk.cc": _DISK_CC}, frozenset({"MakeDir"}))+ calls = _calls(graph, "disk.cc::DiskInterface::MakeDirs")+ assert calls.get("disk.h::DiskInterface::MakeDir") == "self_scope"+++_OS_H = """#pragma once+#include "buffer.h"+class ostream : private detail::buffer<char> {+ public:+ ~ostream();+ void flush() { size(); }+};+"""+++class TestInheritedMembers:+ def test_inline_bare_call_reaches_the_base_member(self, tmp_path: Path) -> None:+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "os.h": _OS_H})+ calls = _calls(graph, "os.h::ostream::flush")+ assert calls == {"buffer.h::buffer::size": "enclosing_inherited"}++ def test_out_of_line_bare_call_reaches_the_base_member(self, tmp_path: Path) -> None:+ os_cc = '#include "os.h"\nostream::~ostream() {\n flush();\n size();\n}\n'+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "os.h": _OS_H, "os.cc": os_cc})+ calls = _calls(graph, "os.cc::ostream::~ostream")+ assert calls == {+ "os.h::ostream::flush": "enclosing_class",+ "buffer.h::buffer::size": "enclosing_inherited",+ }++ def test_own_declaration_hides_the_base_member(self, tmp_path: Path) -> None:+ os_h = _OS_H.replace(" ~ostream();\n", " ~ostream();\n int size() const;\n")+ os_cc = '#include "os.h"\nint ostream::size() const { return 1; }\n'+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "os.h": os_h, "os.cc": os_cc})+ calls = _calls(graph, "os.h::ostream::flush")+ assert calls == {"os.cc::ostream::size": "enclosing_class"}++ def test_two_bases_declaring_the_member_refuse(self, tmp_path: Path) -> None:+ os_h = _OS_H.replace(+ "class ostream : private detail::buffer<char> {",+ "struct sizer {\n int size() const { return 2; }\n};\n"+ "class ostream : private detail::buffer<char>, sizer {",+ )+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "os.h": os_h})+ assert "enclosing_inherited" not in _calls(graph, "os.h::ostream::flush").values()++ def test_a_base_the_file_cannot_include_is_not_followed(self, tmp_path: Path) -> None:+ # ``ext::Widget`` binds by bare name to a repository class that+ # nothing on this file's include path declares.+ files = {+ "widget.h": "#pragma once\nclass Widget {\n public:\n int code() { return 0; }\n};\n",+ "panel.h": "#pragma once\n#include <ext/base.h>\n"+ "class Panel : public ext::Widget {\n"+ " int twice() { return code(); }\n};\n",+ }+ graph = _build(tmp_path, files)+ assert graph.has_edge("panel.h::Panel", "widget.h::Widget")+ assert "enclosing_inherited" not in _calls(graph, "panel.h::Panel::twice").values()+++_MEM_H = """#pragma once+#include "buffer.h"+template <typename T, typename Alloc = int>+class mem_buffer : public detail::buffer<T> {+ public:+ void grow(int n) { set(nullptr, n); }+};+"""+++class TestTemplates:+ def test_this_call_reaches_a_dependent_base(self, tmp_path: Path) -> None:+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "mem.h": _MEM_H}, frozenset({"set"}))+ calls = _calls(graph, "mem.h::mem_buffer::grow")+ assert calls == {"buffer.h::buffer::set": "self_inherited"}++ def test_bare_call_skips_a_dependent_base(self, tmp_path: Path) -> None:+ free_set = '#include "buffer.h"\nvoid set(void* p, int n);\n'+ mem_h = _MEM_H.replace('#include "buffer.h"\n', free_set)+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "mem.h": mem_h})+ assert "buffer.h::buffer::set" not in _calls(graph, "mem.h::mem_buffer::grow")++ def test_a_template_parameter_base_is_not_followed(self, tmp_path: Path) -> None:+ files = {+ "mixin.h": "#pragma once\nclass Mixin {\n public:\n"+ " int size() const { return 0; }\n};\n",+ "wrap.h": '#pragma once\n#include "mixin.h"\ntemplate <class Mixin>\n'+ "class wrap : public Mixin {\n int go() { return size(); }\n};\n",+ }+ graph = _build(tmp_path, files, frozenset({"size"}))+ assert _calls(graph, "wrap.h::wrap::go") == {}++ def test_a_class_nested_in_a_template_skips_its_bases_for_a_bare_call(+ self, tmp_path: Path+ ) -> None:+ outer_h = (+ '#pragma once\n#include "buffer.h"\ntemplate <typename T>\nstruct outer {\n'+ " struct inner : detail::buffer<T> {\n int g() { return size(); }\n };\n};\n"+ )+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "outer.h": outer_h})+ assert "enclosing_inherited" not in _calls(graph, "outer.h::inner::g").values()+++class TestQualifiedCalls:+ def test_a_qualified_call_is_not_the_classs_member(self, tmp_path: Path) -> None:+ os_h = _OS_H.replace("void flush() { size(); }", "void flush() { other::size(); }")+ graph = _build(tmp_path, {"buffer.h": _BUFFER_H, "os.h": os_h})+ assert "enclosing_inherited" not in _calls(graph, "os.h::ostream::flush").values()+++class TestNonCallees:+ def test_an_elaborated_field_type_is_not_a_member_function(self, tmp_path: Path) -> None:+ set_h = "#pragma once\nstruct Set {\n Set();\n struct sigaction old_act_;\n};\n"+ set_cc = '#include "set.h"\nSet::Set() { sigaction(2, 0, &old_act_); }\n'+ graph = _build(tmp_path, {"set.h": set_h, "set.cc": set_cc})+ assert "set.h::Set::sigaction" not in _calls(graph, "set.cc::Set::Set")++ def test_a_prototype_two_files_define_is_not_the_callee(self, tmp_path: Path) -> None:+ lexer_h = (+ "#pragma once\nstruct Lexer {\n int ReadEval();\n"+ " int ReadPath() { return ReadEval(); }\n};\n"+ )+ body = '#include "lexer.h"\nint Lexer::ReadEval() { return 1; }\n'+ graph = _build(tmp_path, {"lexer.h": lexer_h, "lexer.cc": body, "lexer.in.cc": body})+ assert "lexer.h::Lexer::ReadEval" not in _calls(graph, "lexer.h::Lexer::ReadPath")++ def test_a_temporary_of_the_base_type_is_not_a_member_call(self, tmp_path: Path) -> None:+ node_h = "#pragma once\nclass Node {\n public:\n Node();\n explicit Node(int v);\n};\n"+ node_cc = '#include "node.h"\nNode::Node() {}\nNode::Node(int v) {}\n'+ value_h = (+ '#pragma once\n#include "node.h"\nstruct value : public Node {\n'+ " explicit value(int v) { take(Node(v)); }\n void take(const Node& n);\n};\n"+ )+ graph = _build(tmp_path, {"node.h": node_h, "node.cc": node_cc, "value.h": value_h})+ assert "enclosing_inherited" not in _calls(graph, "value.h::value::value").values()