Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(core): resolve a member call once, by its receiver first (#2779)

Raghav Chamadiya4a47f26263fe
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index fa7b88a94..7c30ff503 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -328,9 +328,6 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
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]]] = {}
-
self._init_receiver_typing_caches()
self._repo_rebound_names: dict[str, frozenset[str]] = {}
@@ -789,7 +786,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# --- Method call with receiver: receiver.method() ---
if call.receiver_name:
- return self._with_props(self._resolve_member_call(file_path, call, caller_id), call)
+ handled, hit = self._resolve_member_call(file_path, call, caller_id)
+ if not handled and call.bare_name_fallback:
+ hit = self._resolve_free_call(file_path, call, caller_id)
+ return self._with_props(hit, call)
# --- Free function call: function() ---
return self._with_props(self._resolve_free_call(file_path, call, caller_id), call)
@@ -942,26 +942,6 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return ResolvedCall(caller_id, sym_id, 0.88, line, "return_type_import")
return ResolvedCall(caller_id, sym_id, 0.75, line, "return_type_global")
- 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()``: a
- missed edge, never a wrong one.
- """
- 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,
@@ -972,16 +952,17 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
``_file_symbols`` is flat and last-wins, so a bare ``foo()`` inside
class ``A`` would bind to class ``B``'s ``foo`` when ``B`` came later in
- the file. ``_file_methods`` carries the class.
+ the file. ``_file_methods`` carries the class. A member call on its bare
+ fallback has an explicit receiver, so the caller's class is not it.
"""
parsed = self._parsed_files.get(file_path)
if parsed is None or parsed.file_info.language not in _IMPLICIT_RECEIVER_LANGUAGES:
return None
+ if call.receiver_name:
+ 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 _partial_fragment_member(self, file_path: str, caller_id: str, name: str) -> str | None:
@@ -1226,15 +1207,13 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
) -> ResolvedCall | None:
"""A bare call an ancestor of the caller's class answers.
- Asked after tier 3, so it can only add an edge. The member-shaped
- refusal is the one ``_enclosing_class_method`` already applies: several
- grammars mint a receiver-less site for ``obj.m()`` too, and reading one
- as an implicit receiver would bind the wrong class's hierarchy to the call.
+ Asked after tier 3, so it can only add an edge. A member call on its
+ bare fallback is refused, as in ``_enclosing_class_method``.
"""
lang = self._language_of(file_path)
if lang not in _IMPLICIT_RECEIVER_LANGUAGES or lang not in _INHERITED_LANGUAGES:
return None
- if (call.line, call.target_name) in self._member_shaped_sites(file_path):
+ if call.receiver_name:
return None
sym_id = self._inherited_method(caller_id, call.target_name)
if sym_id is None:
@@ -1271,8 +1250,12 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
file_path: str,
call: CallSite,
caller_id: str,
- ) -> ResolvedCall | None:
- """Resolve receiver.method() calls."""
+ ) -> tuple[bool, ResolvedCall | None]:
+ """Resolve receiver.method() calls, as ``(handled, edge)``.
+
+ A handled None is a refusal (the receiver's type is foreign), which a
+ bare-name fallback must not overrule.
+ """
receiver_name = call.receiver_name
method_name = call.target_name
assert receiver_name is not None
@@ -1280,13 +1263,13 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Every strategy below ends in a lookup keyed on the method name, so a
# name the repo declares nowhere cannot resolve.
if method_name not in self._global_symbols:
- return None
+ return False, None
# The caller's own file first, ahead of the language strategies: a
# private inner class here outranks a same-named package sibling.
own_file = self._file_methods.get(file_path, {}).get((receiver_name, method_name))
if own_file is not None and own_file != caller_id:
- return ResolvedCall(caller_id, own_file, 0.93, call.line, "receiver_same_file")
+ return True, ResolvedCall(caller_id, own_file, 0.93, call.line, "receiver_same_file")
# A language may reach a receiver no import statement mentions: a Go
# package alias spanning several files, a JVM class in the same package.
@@ -1298,13 +1281,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
or self._crate_root_call(call, caller_id)
)
if hit is not None:
- return hit
+ return True, hit
handled, hit = self._receiver_class_call(file_path, call, caller_id)
if handled:
- return hit
+ return True, hit
- return self._unclassed_receiver_call(file_path, call, caller_id)
+ hit = self._unclassed_receiver_call(file_path, call, caller_id)
+ return hit is not None, hit
def _unclassed_receiver_call(
self,
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index a0448c699..e78dc5a82 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -310,6 +310,10 @@ class CallSite:
scope_name: str | None = None
edge_type: CallSiteEdgeType = "calls" # see ``CallSiteEdgeType``
supplied_props: set[str] | None = None # prop names supplied in JSX element (None if unknown/spread)
+ # The grammar's bare-call pattern also matched this member call (Java
+ # ``obj.m()``, Ruby ``obj.m(x)``). Its bare-name reading is asked only
+ # when no receiver strategy answers, never beside one.
+ bare_name_fallback: bool = False
# Raw extractor kinds, not the TS ``HeritageKind`` (a different payload);
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 5fd19f54d..dc80bdcd9 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -26,6 +26,7 @@ from __future__ import annotations
import re
from collections.abc import Iterable
+from dataclasses import replace
from functools import cache
from pathlib import Path
@@ -604,6 +605,34 @@ def _jsx_supplied_props(site_node: Node, src: str) -> frozenset[str] | None:
return frozenset(props_set)
+def _fold_receiverless_twins(calls: list[tuple[tuple[int, int, str], CallSite]]) -> list[CallSite]:
+ """Fold the receiver-less copy of a member call into the copy with a receiver.
+
+ A grammar's bare-call pattern that leaves the object unconstrained (Java's
+ ``method_invocation``, Ruby's ``call``) matches ``obj.m()`` too. Resolved on
+ its own, that copy binds ``m`` by bare name beside whatever ``obj``'s type
+ answers, so it survives only as the member call's ``bare_name_fallback``.
+ Keyed on the call node, not the line, so a bare ``m(obj.m())`` keeps its own
+ site.
+ """
+ member_sites = {site for site, call in calls if not _is_bare(call)}
+ bare_sites = {site for site, call in calls if site in member_sites and _is_bare(call)}
+ folded: list[CallSite] = []
+ for site, call in calls:
+ if _is_bare(call):
+ if site not in member_sites:
+ folded.append(call)
+ elif call.receiver_name and site in bare_sites:
+ folded.append(replace(call, bare_name_fallback=True))
+ else:
+ folded.append(call)
+ return folded
+
+
+def _is_bare(call: CallSite) -> bool:
+ return not (call.receiver_name or call.receiver_call)
+
+
def _dedupe_calls(calls: list[CallSite]) -> list[CallSite]:
"""One call per ``(line, target, receiver)``, keeping the richest record.
@@ -1742,7 +1771,8 @@ class ASTParser:
key=lambda t: (t[0], -t[1]),
)
- calls: list[CallSite] = []
+ # Each call as ``(site, call)``; see ``_fold_receiverless_twins``.
+ calls: list[tuple[tuple[int, int, str], CallSite]] = []
for capture_dict in matches:
site_nodes = capture_dict.get("call.site", [])
@@ -1809,23 +1839,26 @@ class ASTParser:
caller_id = _find_enclosing_symbol(line, symbol_ranges)
calls.append(
- CallSite(
- target_name=target_name,
- receiver_name=receiver_name,
- caller_symbol_id=caller_id,
- 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
- else "calls"
+ (
+ (site_node.start_byte, site_node.end_byte, target_name),
+ CallSite(
+ target_name=target_name,
+ receiver_name=receiver_name,
+ caller_symbol_id=caller_id,
+ 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
+ else "calls"
+ ),
+ supplied_props=_jsx_supplied_props(site_node, src),
),
- supplied_props=_jsx_supplied_props(site_node, src),
)
)
- return _dedupe_calls(calls)
+ return _dedupe_calls(_fold_receiverless_twins(calls))
def _extract_references(
self,
diff --git a/packages/core/src/repowise/core/ingestion/queries/java.scm b/packages/core/src/repowise/core/ingestion/queries/java.scm
index c1a5ccc94..f2f1d0806 100644
--- a/packages/core/src/repowise/core/ingestion/queries/java.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/java.scm
@@ -109,24 +109,10 @@
; bare name through the flat same-file index instead of against the caller's own
; class.
;
-; ``super`` is deliberately NOT in this alternation, and the reason is narrower
-; than "super is unsafe". Capturing any receiver makes the bare twin
-; member-shaped, which suppresses ``_enclosing_class_method``'s recursion
-; refusal — the guard that emits no edge when the flat index hands a method its
-; own name. The call then falls through to the same-file tier, and THAT is only
-; wrong when the file declares the target name on MORE THAN ONE class: the flat
-; index is last-wins, so it answers with a sibling's method.
-;
-; So the hazard is a property of the file, not of the keyword, and ``this`` is
-; not immune to it — it is merely far less likely to sit in such a file.
-; Measured on caffeine: ``super`` costs 2 wrong edges (``DelegationBenchmark``
-; declares ``get`` on both ``InheritMap`` and ``DelegateMap``), while all 3
-; self-recursive ``this.add()`` sites are safe because ``IntegerSum`` is the only
-; class in its file declaring ``add`` and the ``callee != caller`` guard then
-; refuses. ``super`` is excluded because its population sits in override-heavy
-; files where sibling classes share names; that costs recall only, which is the
-; right direction to err in. If a future session adds ``super``, the fix it
-; needs first is a same-file index keyed by class, not a wider capture.
+; ``super`` stays out: ``super.m()`` arrives bare, where the caller's own class
+; answers it and the recursion refusal drops an override calling itself. No
+; member strategy answers a ``super`` receiver for Java, so capturing one would
+; only move the call onto its bare-name fallback, which skips the caller's class.
(method_invocation
object: (this) @call.receiver
name: (identifier) @call.target
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index c72aefd6f..d5e1a9c44 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -62,7 +62,11 @@ STORE_FORMAT_VERSION: int = 2
#:
#: v5: an overload signature (Python ``@overload``, TypeScript function / method
#: overload) is marked ``is_declaration`` so lookups serve the implementation.
-PARSER_SCHEMA_VERSION: int = 5
+#:
+#: 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.
+PARSER_SCHEMA_VERSION: int = 6
#: state.json key holding the store format version that wrote the store.
STORE_FORMAT_VERSION_KEY = "store_format_version"
diff --git a/tests/unit/ingestion/parser/test_java.py b/tests/unit/ingestion/parser/test_java.py
index 3ff35f59b..d6b5d5d77 100644
--- a/tests/unit/ingestion/parser/test_java.py
+++ b/tests/unit/ingestion/parser/test_java.py
@@ -110,3 +110,61 @@ class TestJavaParser:
assert all(
c.receiver_name is None for c in result.calls if c.target_name == target
), target
+
+
+TWIN_SOURCE = b"""package com.repowise.sample;
+
+import static java.lang.Math.max;
+
+public class Token extends Base {
+
+ private final TokenData data = new TokenData();
+
+ void data(String str) {
+ data.set(str);
+ this.reset();
+ reset();
+ super.reset();
+ max(1, 2);
+ set(data.set(str));
+ }
+
+ void reset() {
+ }
+}
+"""
+
+
+class TestReceiverlessTwin:
+ """The bare-call pattern leaves ``object`` unconstrained, so it also matches
+ ``obj.m()``. That copy folds into the member call as its bare-name fallback;
+ a call with no receiver pattern is kept as it is."""
+
+ def _sites(self, parser: ASTParser, target: str) -> list[tuple[int, str | None]]:
+ fi = _make_file_info("java_pkg/Token.java", "java")
+ result = parser.parse_file(fi, TWIN_SOURCE)
+ return sorted(
+ ((c.line, c.receiver_name) for c in result.calls if c.target_name == target),
+ key=lambda s: (s[0], s[1] or ""),
+ )
+
+ def test_a_member_call_arrives_once_with_its_receiver(self, parser: ASTParser) -> None:
+ assert (10, "data") in self._sites(parser, "set")
+ assert (10, None) not in self._sites(parser, "set")
+ assert (11, "this") in self._sites(parser, "reset")
+ assert (11, None) not in self._sites(parser, "reset")
+ fi = _make_file_info("java_pkg/Token.java", "java")
+ calls = parser.parse_file(fi, TWIN_SOURCE).calls
+ assert all(c.bare_name_fallback for c in calls if c.receiver_name)
+ assert not any(c.bare_name_fallback for c in calls if not c.receiver_name)
+
+ def test_genuine_receiverless_calls_are_kept(self, parser: ASTParser) -> None:
+ resets = self._sites(parser, "reset")
+ assert (12, None) in resets, "a bare reset()"
+ assert (13, None) in resets, "super.reset() has no receiver pattern"
+ assert self._sites(parser, "max") == [(14, None)], "a static-imported call"
+
+ def test_a_bare_call_sharing_a_line_with_its_member_twin_is_kept(
+ self, parser: ASTParser
+ ) -> None:
+ assert self._sites(parser, "set")[-2:] == [(15, None), (15, "data")]
diff --git a/tests/unit/ingestion/parser/test_ruby.py b/tests/unit/ingestion/parser/test_ruby.py
index dbaccf744..ca42b2153 100644
--- a/tests/unit/ingestion/parser/test_ruby.py
+++ b/tests/unit/ingestion/parser/test_ruby.py
@@ -68,3 +68,33 @@ class TestRubyParser:
fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
result = parser.parse_file(fi, RUBY_SOURCE)
assert result.parse_errors == []
+
+
+RUBY_TWIN_SOURCE = b"""\
+class Pool
+ def drain(conn)
+ conn.close(true)
+ close(conn)
+ close(conn.close(false))
+ end
+
+ def close(x)
+ end
+end
+"""
+
+
+class TestRubyReceiverlessTwin:
+ """``(call method: arguments:)`` leaves ``receiver`` unconstrained, so it
+ also matches ``conn.close(true)``. That copy folds into the member call as
+ its bare-name fallback; ``close(x)`` stays."""
+
+ def test_a_member_call_arrives_once_with_its_receiver(self, parser: ASTParser) -> None:
+ fi = _make_file_info("ruby_pkg/pool.rb", "ruby")
+ result = parser.parse_file(fi, RUBY_TWIN_SOURCE)
+ sites = sorted(
+ ((c.line, c.receiver_name) for c in result.calls if c.target_name == "close"),
+ key=lambda s: (s[0], s[1] or ""),
+ )
+ assert sites == [(3, "conn"), (4, None), (5, None), (5, "conn")]
+ assert all(c.bare_name_fallback for c in result.calls if c.receiver_name == "conn")
diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.py
index b29823f33..897a31d92 100644
--- a/tests/unit/ingestion/test_call_resolver_strategies.py
+++ b/tests/unit/ingestion/test_call_resolver_strategies.py
@@ -13,6 +13,7 @@ language reaches and in what order, and a spy states that directly.
from __future__ import annotations
+from dataclasses import replace
from datetime import datetime
from pathlib import Path
@@ -963,6 +964,25 @@ class TestForeignReceiverTypes:
)
assert _edges(parsed, tmp_path) == []
+ def test_the_refusal_holds_over_a_bare_name_fallback(self, tmp_path: Path) -> None:
+ """A refused receiver is an answer, not a miss: the bare tiers never see it."""
+ self._workspace(tmp_path)
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "crates/a/src/lib.rs": self._DECLARES,
+ "crates/b/src/lib.rs": (
+ "rust",
+ "use std::collections::HashMap;\n\npub fn run() {\n"
+ " let m = HashMap::new();\n}\n",
+ ),
+ },
+ )
+ caller = parsed["crates/b/src/lib.rs"]
+ caller.calls = [replace(c, bare_name_fallback=True) for c in caller.calls]
+ assert [c.receiver_name for c in caller.calls] == ["HashMap"]
+ assert _edges(parsed, tmp_path) == []
+
def test_the_same_call_resolves_when_the_file_rebinds_the_name(
self, tmp_path: Path
) -> None:
diff --git a/tests/unit/ingestion/test_enclosing_class_calls.py b/tests/unit/ingestion/test_enclosing_class_calls.py
index 07ef035dd..61db68f90 100644
--- a/tests/unit/ingestion/test_enclosing_class_calls.py
+++ b/tests/unit/ingestion/test_enclosing_class_calls.py
@@ -10,8 +10,8 @@ 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 call site that is really ``obj.foo()``, which the grammar's bare-call
+ pattern also matches (the parser keeps only the copy with the receiver);
* a flat hit that is a top-level function or a constructor rather than a rival
class's method.
@@ -90,7 +90,7 @@ class B {
"""
# `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.
+# pattern; only the copy with the receiver may reach the resolver.
JAVA_MEMBER_SHAPED = """
class A {
int helper() { return 1; }
@@ -191,3 +191,95 @@ class TestClassAwareTier:
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}"
)
+
+
+# jsoup's shape: `Tag` puts `set` in the file's flat index, so a bare-name
+# reading of `data.set(str)` has a wrong answer to give.
+JAVA_TOKEN_DATA = "package p;\n\nclass TokenData {\n void set(String s) { }\n}\n"
+JAVA_TOKEN = """package p;
+
+class Character {
+ private final TokenData data = new TokenData();
+
+ void data(String str) {
+ data.set(str);
+ }
+}
+
+class Tag {
+ Tag set(int n) { return this; }
+}
+"""
+
+# `o` is typed by nothing the resolver can read, so the call keeps the bare-name
+# answer the grammar's bare pattern always gave it.
+JAVA_UNTYPED_RECEIVER = """
+class A {
+ int count(Object o) { return o.size(); }
+}
+
+class Box {
+ int size() { return 0; }
+}
+"""
+
+JAVA_SAME_LINE = """
+class A {
+ int helper(int x) { return x; }
+ int run(B b) { return helper(b.helper(1)); }
+}
+
+class B {
+ int helper(int x) { return x; }
+}
+"""
+
+RUBY_POOL = """
+class Pool
+ def drain(conn)
+ close(conn)
+ end
+
+ def close(x)
+ end
+end
+"""
+
+
+class TestReceiverlessTwin:
+ """``obj.m()`` reaches the resolver once, with its receiver."""
+
+ def test_a_typed_member_call_gets_no_bare_name_edge(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "p/TokenData.java": ("java", JAVA_TOKEN_DATA),
+ "p/Token.java": ("java", JAVA_TOKEN),
+ },
+ )
+ edges = _edges(parsed, tmp_path)
+ assert _targets_of(edges, "::Character::data") == ["p/TokenData.java::TokenData::set"], (
+ f"data.set(str) must reach TokenData only; edges: {edges}"
+ )
+
+ def test_an_untyped_receiver_falls_back_to_the_bare_name(self, tmp_path: Path) -> None:
+ parsed = _parse_all(tmp_path, {"src/A.java": ("java", JAVA_UNTYPED_RECEIVER)})
+ edges = _edges(parsed, tmp_path)
+ assert ("src/A.java::A::count", "src/A.java::Box::size", 0.95, "same_file") in edges, (
+ f"o.size() must keep its bare-name edge; edges: {edges}"
+ )
+
+ def test_a_bare_call_on_its_twins_line_still_resolves(self, tmp_path: Path) -> None:
+ """``helper(b.helper(1))``: the outer call is a genuine implicit receiver."""
+ parsed = _parse_all(tmp_path, {"src/A.java": ("java", JAVA_SAME_LINE)})
+ edges = _edges(parsed, tmp_path)
+ assert "src/A.java::A::helper" in _targets_of(edges, "::A::run"), (
+ f"the outer helper() must reach A::helper; edges: {edges}"
+ )
+
+ def test_a_ruby_bare_call_still_resolves(self, tmp_path: Path) -> None:
+ parsed = _parse_all(tmp_path, {"lib/pool.rb": ("ruby", RUBY_POOL)})
+ edges = _edges(parsed, tmp_path)
+ assert _targets_of(edges, "::drain") == ["lib/pool.rb::Pool::close"], (
+ f"close(conn) must reach Pool::close; edges: {edges}"
+ )