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): bind a bare call to the caller's own class, capture PHP/Luau receivers (#1630)
Raghav Chamadiya3f705b83c24b
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 1b1fcc8f2..606356829 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -34,6 +34,11 @@ from .models import CallSite, NamedBinding, ParsedFile, ResolutionOriginlog = structlog.get_logger(__name__)+# Languages with an implicit method receiver, where a bare ``foo()`` binds to+# the caller's instance. Go, Python, PHP and JS/TS spell the receiver out, so a+# bare call there is a free function and this tier would resolve it wrongly.+_IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})+def _file_language(parsed_files: dict[str, ParsedFile], symbol_id: str) -> str | None:"""Extract language from a symbol ID's file via the parsed files map."""@@ -113,6 +118,9 @@ class CallResolver:self._merged_import_symbols: dict[str, dict[str, str]] = {}self._merged_import_methods: dict[str, dict[tuple[str, str], str]] = {}+ # Lazy per-file set of (line, target) that also carry a receiver.+ self._member_shaped: dict[str, set[tuple[int, str]]] = {}+# Barrel re-export origins: {barrel_file: {name: origin_file}}self._barrel_origins: dict[str, dict[str, str]] = defaultdict(dict)@@ -573,6 +581,48 @@ class CallResolver:# --- Free function call: function() ---return self._resolve_free_call(file_path, call, caller_id)+ def _member_shaped_sites(self, file_path: str) -> set[tuple[int, str]]:+ """``(line, target)`` pairs at which this file also records a receiver.++ Several grammars match ``obj.m()`` twice — once with a receiver, once+ against the bare-call pattern — so a member call also arrives as a+ receiver-less site.++ Keyed on the line because a ``CallSite`` carries no column, so+ ``foo(bar.foo())`` suppresses the tier for its own bare ``foo()``. That+ costs the fix on that site, never a wrong edge; a column would fix it.+ """+ sites = self._member_shaped.get(file_path)+ if sites is None:+ parsed = self._parsed_files.get(file_path)+ sites = {+ (c.line, c.target_name) for c in (parsed.calls if parsed else ()) if c.receiver_name+ }+ self._member_shaped[file_path] = sites+ return sites++ def _enclosing_class_method(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ ) -> str | None:+ """The caller's own class's method of this name, or None.++ ``_file_symbols`` is flat and last-wins, so a bare ``foo()`` inside+ class ``A`` bound to class ``B``'s ``foo`` when ``B`` came later in the+ file. ``_file_methods`` already carries the class.+ """+ parsed = self._parsed_files.get(file_path)+ if parsed is None or parsed.file_info.language not in _IMPLICIT_RECEIVER_LANGUAGES:+ return None+ caller_class = _extract_class_from_symbol_id(caller_id)+ if not caller_class:+ return None+ if (call.line, call.target_name) in self._member_shaped_sites(file_path):+ return None+ return self._file_methods.get(file_path, {}).get((caller_class, call.target_name))+def _resolve_free_call(self,file_path: str,@@ -586,6 +636,12 @@ class CallResolver:file_syms = self._file_symbols.get(file_path, {})if target_name in file_syms:callee_id = file_syms[target_name]+ own = self._enclosing_class_method(file_path, call, caller_id)+ if own is not None and own != callee_id and _rivals_a_class_method(callee_id):+ if own == caller_id:+ # Recursion the flat index handed to a stranger. No edge.+ return None+ return ResolvedCall(caller_id, own, 0.95, call.line, "enclosing_class")if callee_id != caller_id: # no self-recursion edges for nowreturn ResolvedCall(caller_id, callee_id, 0.95, call.line, "same_file")@@ -771,6 +827,18 @@ class CallResolver:return None+def _rivals_a_class_method(symbol_id: str) -> bool:+ """Another class's ordinary method — the one shape that proves last-wins.++ Not a top-level function (Kotlin and C++ put these beside classes, and a+ bare call may genuinely mean one) and not a constructor (name equals its+ parent's), which ``new Entry()`` should reach even inside a class nesting+ its own ``Entry``.+ """+ parts = symbol_id.split("::")+ return len(parts) >= 3 and parts[-1] != parts[-2]++def _extract_class_from_symbol_id(symbol_id: str) -> str | None:"""Extract parent class name from a symbol ID like 'path::ClassName::method'."""parts = symbol_id.split("::")diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex a96dea56e..04506f2d9 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -330,6 +330,7 @@ EDGE_TYPE_VALUES: frozenset[str] = frozenset(get_args(EdgeType))ResolutionOrigin = Literal["same_file", # 0.95 — defined in the calling file"self_scope", # 0.95 — self/this, method on the caller's own class+ "enclosing_class", # 0.95 — bare call, bound to the caller's own class"receiver_same_file", # 0.93 — receiver names a class in this file"same_package", # 0.90 — Go/JVM sibling file, no import needed"import_scoped", # 0.90 — the name was imported from the defining filediff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 886a21d9b..70a46a784 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -275,6 +275,18 @@ def _get_language(tag: str) -> Language | None:_node_text = node_text+def _normalize_php_receiver(text: str) -> str:+ """Spell PHP's receiver the way the resolver's strategies expect.++ `self::` and `static::` are the same dispatch as `$this`, and the self/this+ strategy tests `in ("self", "this")` — so without this the whole implicit-+ receiver population misses. `parent::` needs the heritage walk and is left+ to miss rather than guessed at.+ """+ name = text.lstrip("$")+ return "this" if name in ("self", "static") else name++# ---------------------------------------------------------------------------# ASTParser# ---------------------------------------------------------------------------@@ -1107,6 +1119,8 @@ class ASTParser:line = site_node.start_point[0] + 1receiver_name = _node_text(receiver_nodes[0], src).strip() if receiver_nodes else None+ if receiver_name and file_info.language == "php":+ receiver_name = _normalize_php_receiver(receiver_name)dedup_key = (line, target_name, receiver_name)if dedup_key in seen:diff --git a/packages/core/src/repowise/core/ingestion/queries/luau.scm b/packages/core/src/repowise/core/ingestion/queries/luau.scmindex e7170382c..d752cfb0b 100644--- a/packages/core/src/repowise/core/ingestion/queries/luau.scm+++ b/packages/core/src/repowise/core/ingestion/queries/luau.scm@@ -45,3 +45,21 @@(identifier) @call.target(arguments) @call.arguments) @call.site++; Method call: obj:method(args) — the receiver sits one level below `name:`.+(function_call+ name: (method_index_expression+ table: (_) @call.receiver+ method: (identifier) @call.target+ )+ (arguments) @call.arguments+) @call.site++; Field call: obj.method(args)+(function_call+ name: (dot_index_expression+ table: (_) @call.receiver+ field: (identifier) @call.target+ )+ (arguments) @call.arguments+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/php.scm b/packages/core/src/repowise/core/ingestion/queries/php.scmindex 47f8da4f4..010e876e2 100644--- a/packages/core/src/repowise/core/ingestion/queries/php.scm+++ b/packages/core/src/repowise/core/ingestion/queries/php.scm@@ -105,14 +105,18 @@(arguments) @call.arguments) @call.site-; Method call: $obj->method(args)+; Method call: $obj->method(args). The receiver is a `variable_name` whose own+; text keeps the sigil (`$this`), which the parser normalises.(member_call_expression+ object: (_) @call.receivername: (name) @call.target(arguments) @call.arguments) @call.site-; Static call: ClassName::method(args)+; Static call: ClassName::method(args). `scope:` is a `relative_scope` for+; self/static/parent and a `name` for an explicit class.(scoped_call_expression+ scope: (_) @call.receivername: (name) @call.target(arguments) @call.arguments) @call.sitediff --git a/tests/unit/ingestion/test_enclosing_class_calls.py b/tests/unit/ingestion/test_enclosing_class_calls.pynew file mode 100644index 000000000..07ef035dd--- /dev/null+++ b/tests/unit/ingestion/test_enclosing_class_calls.py@@ -0,0 +1,193 @@+"""Behaviour pins for the class-aware same-file tier.++``_file_symbols`` is ``{file: {name: id}}`` — flat and last-wins — so a bare+``foo()`` inside class ``A`` bound to class ``B``'s ``foo`` whenever ``B`` came+later in the same file. ``_file_methods`` already carries the class, so the fix+is a lookup, not new data.++What makes it safe is the three shapes it must NOT claim, each of which reads+like the same defect and is not:++* a language without an implicit receiver, where a bare call is a module-level+ function and the caller's class is the wrong answer;+* a call site that is really ``obj.foo()``, arriving a second time without a+ receiver because the grammar's bare-call pattern matched it too;+* a flat hit that is a top-level function or a constructor rather than a rival+ class's method.++Each is pinned below, because each one silently costs correct edges.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++from repowise.core.ingestion.call_resolver import CallResolver+from repowise.core.ingestion.models import FileInfo, ParsedFile+from repowise.core.ingestion.parser import parse_file+++def _file_info(rel: str, abs_: Path, lang: str) -> FileInfo:+ return FileInfo(+ path=rel,+ abs_path=str(abs_),+ language=lang, # type: ignore[arg-type]+ size_bytes=abs_.stat().st_size,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _parse_all(tmp_path: Path, files: dict[str, tuple[str, str]]) -> dict[str, ParsedFile]:+ out: dict[str, ParsedFile] = {}+ for rel, (lang, content) in files.items():+ abs_ = tmp_path / rel+ abs_.parent.mkdir(parents=True, exist_ok=True)+ abs_.write_text(content)+ out[rel] = parse_file(_file_info(rel, abs_, lang), content.encode("utf-8"))+ return out+++def _edges(parsed: dict[str, ParsedFile], tmp_path: Path) -> list[tuple[str, str, float, str]]:+ resolver = CallResolver(parsed, {}, repo_path=str(tmp_path))+ return [+ (rc.caller_id, rc.callee_id, rc.confidence, rc.origin)+ for path, pf in parsed.items()+ for rc in resolver.resolve_file(path, pf.calls)+ ]+++def _targets_of(edges: list[tuple[str, str, float, str]], caller_suffix: str) -> list[str]:+ return [e[1] for e in edges if e[0].endswith(caller_suffix)]+++# `B` deliberately comes second: last-wins is what puts `B::helper` in the flat+# index under the bare name `helper`.+JAVA_TWO_CLASSES = """+class A {+ int helper() { return 1; }+ int run() { return helper(); }+}++class B {+ int helper() { return 2; }+}+"""++JAVA_RECURSIVE = """+class A {+ int helper() { return helper(); }+}++class B {+ int helper() { return 2; }+}+"""++# `b.helper()` matches both the receiver-bearing pattern and the bare-call+# pattern, so the same line arrives twice — once with a receiver, once without.+JAVA_MEMBER_SHAPED = """+class A {+ int helper() { return 1; }+ int run(B b) { return b.helper(); }+}++class B {+ int helper() { return 2; }+}+"""++PYTHON_TWO_CLASSES = '''+class A:+ def helper(self):+ return 1++ def run(self):+ return helper()+++class B:+ def helper(self):+ return 2+'''++KOTLIN_TOP_LEVEL_FN = """+class A {+ fun helper(): Int = 2+ fun run(): Int = helper()+}++fun helper(): Int = 1+"""++JAVA_CONSTRUCTOR = """+class Holder {+ static class Entry { }+ Object make() { return new Entry(); }+}++class Entry {+ Entry() { }+}+"""+++class TestClassAwareTier:+ def test_bare_call_binds_to_the_callers_own_class(self, tmp_path: Path) -> None:+ parsed = _parse_all(tmp_path, {"src/A.java": ("java", JAVA_TWO_CLASSES)})+ edges = _edges(parsed, tmp_path)+ hits = [e for e in edges if e[0].endswith("::A::run")]+ assert [e[1].split("::")[-2:] for e in hits] == [["A", "helper"]], (+ f"helper() inside A.run must reach A::helper, not B's; edges: {edges}"+ )+ assert hits[0][2:] == (0.95, "enclosing_class")++ def test_recursion_does_not_reach_another_class(self, tmp_path: Path) -> None:+ """The caller's own class's `helper` IS the caller — that is a self-call."""+ parsed = _parse_all(tmp_path, {"src/A.java": ("java", JAVA_RECURSIVE)})+ edges = _edges(parsed, tmp_path)+ assert _targets_of(edges, "::A::helper") == [], (+ f"recursive helper() must not edge to B::helper; edges: {edges}"+ )++ def test_a_member_shaped_site_is_not_treated_as_bare(self, tmp_path: Path) -> None:+ parsed = _parse_all(tmp_path, {"src/A.java": ("java", JAVA_MEMBER_SHAPED)})+ edges = _edges(parsed, tmp_path)+ assert not [t for t in _targets_of(edges, "::A::run") if t.endswith("::A::helper")], (+ f"b.helper() must not resolve to the caller's own helper; edges: {edges}"+ )++ def test_language_without_an_implicit_receiver_is_untouched(self, tmp_path: Path) -> None:+ """A bare `helper()` in Python is a module-level function, never `self.helper()`."""+ parsed = _parse_all(tmp_path, {"src/a.py": ("python", PYTHON_TWO_CLASSES)})+ edges = _edges(parsed, tmp_path)+ assert not [t for t in _targets_of(edges, "::A::run") if t.endswith("::A::helper")], (+ f"Python bare call must not bind to the caller's class; edges: {edges}"+ )++ def test_a_top_level_function_hit_is_left_alone(self, tmp_path: Path) -> None:+ """Kotlin puts free functions beside classes, so the flat hit may be right.++ Which of the two Kotlin would pick depends on the signatures, which the+ `(class, method)` index does not carry — so the tier declines rather+ than guessing.+ """+ parsed = _parse_all(tmp_path, {"src/A.kt": ("kotlin", KOTLIN_TOP_LEVEL_FN)})+ edges = _edges(parsed, tmp_path)+ targets = _targets_of(edges, "::A::run")+ assert targets and not any(t.endswith("::A::helper") for t in targets), (+ f"the top-level helper must keep the edge; edges: {edges}"+ )++ def test_a_constructor_hit_is_left_alone(self, tmp_path: Path) -> None:+ """`new Entry()` reaches a constructor; a same-named nested type is not a rival."""+ parsed = _parse_all(tmp_path, {"src/Holder.java": ("java", JAVA_CONSTRUCTOR)})+ edges = _edges(parsed, tmp_path)+ assert not [t for t in _targets_of(edges, "::make") if t.endswith("::Holder::Entry")], (+ f"a constructor hit must not be redirected; edges: {edges}"+ )diff --git a/tests/unit/ingestion/test_php_luau_receivers.py b/tests/unit/ingestion/test_php_luau_receivers.pynew file mode 100644index 000000000..cbc134a77--- /dev/null+++ b/tests/unit/ingestion/test_php_luau_receivers.py@@ -0,0 +1,133 @@+"""Receiver capture for PHP and Luau, whose queries recorded none at all.++Before this, `php.scm` and `luau.scm` carried no `@call.receiver`, so every+call arrived receiver-less and was resolved by bare name against a flat+per-file index — `$request->withHeader()` binding to whichever class in the+repo happened to declare `withHeader`.++The PHP half is a normalisation test as much as a capture test. PHP spells the+implicit receiver `$this` and aliases it as `self::` / `static::`, while the+resolver's self/this strategy tests `in ("self", "this")`. Capture without+normalisation therefore turns the whole implicit-receiver population — the+largest single group of correct PHP edges — into misses.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import pytest++from repowise.core.ingestion.call_resolver import CallResolver+from repowise.core.ingestion.models import FileInfo, ParsedFile+from repowise.core.ingestion.parser import parse_file+++def _parse(tmp_path: Path, rel: str, lang: str, content: str) -> dict[str, ParsedFile]:+ abs_ = tmp_path / rel+ abs_.parent.mkdir(parents=True, exist_ok=True)+ abs_.write_text(content)+ fi = FileInfo(+ path=rel,+ abs_path=str(abs_),+ language=lang, # type: ignore[arg-type]+ size_bytes=abs_.stat().st_size,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ return {rel: parse_file(fi, content.encode("utf-8"))}+++PHP_SRC = """<?php+class A {+ function caller() {+ $this->one();+ self::two();+ static::three();+ parent::four();+ $obj->five();+ B::six();+ seven();+ }+ function one() {}+ function two() {}+ function three() {}+}+"""++LUAU_SRC = """local M = {}+function M.new() return setmetatable({}, M) end+function M:run()+ self:helper()+ M.new()+ obj.other(1)+ plain(2)+end+function M:helper() end+return M+"""+++ ("target", "receiver"),+ [+ ("one", "this"), # $this-> — the sigil must be stripped+ ("two", "this"), # self:: is same-class dispatch+ ("three", "this"), # static:: likewise+ ("four", "parent"), # needs the heritage walk; left to miss, not guessed+ ("five", "obj"), # ordinary variable, sigil stripped+ ("six", "B"), # explicit class receiver+ ("seven", None), # a genuine free call keeps no receiver+ ],+)+def test_php_receiver_is_captured_and_normalised(+ tmp_path: Path, target: str, receiver: str | None+) -> None:+ parsed = _parse(tmp_path, "src/A.php", "php", PHP_SRC)+ got = {c.receiver_name for c in parsed["src/A.php"].calls if c.target_name == target}+ assert got == {receiver}, f"{target}() should carry receiver {receiver!r}, got {got}"+++def test_php_this_call_resolves_against_the_callers_own_class(tmp_path: Path) -> None:+ """The normalisation's whole purpose: `$this->one()` must reach strategy 3."""+ parsed = _parse(tmp_path, "src/A.php", "php", PHP_SRC)+ resolver = CallResolver(parsed, {}, repo_path=str(tmp_path))+ edges = [+ (rc.callee_id, rc.confidence, rc.origin)+ for rc in resolver.resolve_file("src/A.php", parsed["src/A.php"].calls)+ ]+ hits = [e for e in edges if e[0].endswith("::A::one")]+ assert hits, f"$this->one() must resolve to A::one; edges: {edges}"+ assert hits[0][1:] == (0.95, "self_scope")+++ ("target", "receiver"),+ [+ ("helper", "self"), # obj:method() — Luau spells self plainly+ ("new", "M"),+ ("other", "obj"), # obj.method()+ ("plain", None),+ ],+)+def test_luau_receiver_is_captured(tmp_path: Path, target: str, receiver: str | None) -> None:+ parsed = _parse(tmp_path, "src/m.luau", "luau", LUAU_SRC)+ got = {c.receiver_name for c in parsed["src/m.luau"].calls if c.target_name == target}+ assert got == {receiver}, f"{target}() should carry receiver {receiver!r}, got {got}"+++def test_luau_capture_does_not_duplicate_a_call_site(tmp_path: Path) -> None:+ """The new patterns must not double up with the bare-call pattern.++ A grammar that matches one call twice — once with a receiver, once without —+ resolves the receiver-less copy by bare name and mints a wrong edge beside+ the right one.+ """+ parsed = _parse(tmp_path, "src/m.luau", "luau", LUAU_SRC)+ sites = [(c.line, c.target_name) for c in parsed["src/m.luau"].calls]+ assert len(sites) == len(set(sites)), f"duplicate call sites: {sites}"