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(graph): bind a Java call on an unnamed object only by repo-wide uniqueness (#4836)

Swati Ahujacff81a8757a6
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 1b04fab5e..d106732bf 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -1049,6 +1049,10 @@ class CallResolver(
return self._with_props(hit, call)
if receiver_call is not None and not (bare_fallback and strategies.chain_bare_fallback):
return None
+ if call.on_unnamed_object:
+ # A call on an object no pattern names: a tier keyed on the
+ # caller's file, class or imports would read the method as theirs.
+ return self._with_props(self._global_unique_call(file_path, call, caller_id), call)
# --- Free function call: function() ---
return self._with_props(self._resolve_bare_call(file_path, call, caller_id), call)
@@ -1901,7 +1905,6 @@ class CallResolver(
caller_id: str,
) -> ResolvedCall | None:
"""Tier 3 and what follows it: answers not grounded in this file or its imports."""
- target_name = call.target_name
# Ahead of tier 3: the caller's own hierarchy is better evidence than
# repo-wide uniqueness, and a JVM package sibling's member never answers.
inherited = self._implicit_inherited_call(file_path, call, caller_id)
@@ -1912,7 +1915,16 @@ class CallResolver(
)
if hit is not None:
return hit
- # Tier 3: global unique match, only within the same language.
+ return self._global_unique_call(file_path, call, caller_id)
+
+ def _global_unique_call(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Tier 3: the one declaration of the name repo-wide, only within the same language."""
+ target_name = call.target_name
# Uniqueness is judged before filtering data members, on purpose: filtering
# them out first would re-uniquify a name a field and a method share. A
# symbol the caller cannot name at all is no rival, so that one is dropped.
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 9419fe63d..9abf0b6ff 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -373,7 +373,8 @@ class CallSite:
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.
+ # when no receiver strategy answers, never beside one. With no receiver
+ # it means ``on_unnamed_object`` instead.
bare_name_fallback: bool = False
# Handed straight to a task scheduler (``asyncio.create_task(f())``): it runs
# later, beside its caller, so the caller neither waits for it nor repeats it.
@@ -389,6 +390,14 @@ class CallSite:
# when no argument is one. The resolver reads its declared type.
argument_names: tuple[str | None, ...] | None = None
+ @property
+ def on_unnamed_object(self) -> bool:
+ """A Java call on an object no pattern names (``a.b.m()``, ``arr[0].m()``).
+
+ Only repo-wide uniqueness binds it. A call with a receiver never is one.
+ """
+ return self.bare_name_fallback and not (self.receiver_name or self.receiver_call)
+
# Raw extractor kinds, not the TS ``HeritageKind`` (a different payload);
# test_wire_vocabulary_parity pins the difference.
diff --git a/packages/core/src/repowise/core/ingestion/parser/calls.py b/packages/core/src/repowise/core/ingestion/parser/calls.py
index 4cbc80c73..d2a701bbc 100644
--- a/packages/core/src/repowise/core/ingestion/parser/calls.py
+++ b/packages/core/src/repowise/core/ingestion/parser/calls.py
@@ -333,15 +333,21 @@ def _dedupe_calls(calls: list[tuple[tuple[int, int, str], CallSite]]) -> list[Ca
for site, call in calls:
key = (site, call.receiver_name)
existing = deduplicated.get(key)
- 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)
- ):
+ if existing is None or _richer(call, existing):
deduplicated[key] = call
return list(deduplicated.values())
+def _richer(call: CallSite, existing: CallSite) -> bool:
+ """Does *call* carry something the same-keyed *existing* record lacks?"""
+ if existing.receiver_call is None and call.receiver_call is not None:
+ return True
+ if existing.scope_name is None and call.scope_name is not None:
+ return True
+ # A bare ``m()`` beside ``a.b.m()`` on its line keeps every tier.
+ return existing.on_unnamed_object and not call.on_unnamed_object
+
+
def _extract_calls(
matches: list[dict],
config: LanguageConfig,
@@ -414,6 +420,12 @@ def _call_from_match(
return None
scope_nodes = capture_dict.get("call.scope", [])
line = site_node.start_point[0] + 1
+ on_unnamed_object = (
+ language == "java"
+ and receiver_name is None
+ and not receiver_call_nodes
+ and _java_object_is_unnamed(site_node)
+ )
arguments = _overload_arguments(language, arg_nodes)
call = CallSite(
target_name=target_name,
@@ -433,10 +445,29 @@ def _call_from_match(
# own function only (see ``python_tasks``).
spawned=language == "python" and is_fire_and_forget(site_node, src),
program_call=language == "cobol" and site_node.type == "call_statement",
+ bare_name_fallback=on_unnamed_object,
)
return (site_node.start_byte, site_node.end_byte, target_name), call
+def _java_object_is_unnamed(site_node: Node) -> bool:
+ """Does this Java call have an object, other than a qualified ``this``?
+
+ Asked only of a match with no receiver, so true only on the bare pattern's
+ copy. Where a receiver pattern names the object (``a.m()``, ``this.m()``),
+ ``_fold_receiverless_twins`` drops this copy and sets ``bare_name_fallback``
+ on the named one, which then means a bare-name fallback, not this.
+ ``Outer.this.m()`` is an implicit receiver, read as bare.
+ """
+ if site_node.type != "method_invocation":
+ return False
+ obj = site_node.child_by_field_name("object")
+ if obj is None:
+ return False
+ field = obj.child_by_field_name("field") if obj.type == "field_access" else None
+ return field is None or field.type != "this"
+
+
def _call_names(
capture_dict: dict,
site_node: Node,
diff --git a/tests/unit/ingestion/parser/golden/java.json b/tests/unit/ingestion/parser/golden/java.json
index 0aa6a85f2..036cb0be2 100644
--- a/tests/unit/ingestion/parser/golden/java.json
+++ b/tests/unit/ingestion/parser/golden/java.json
@@ -634,7 +634,7 @@
"scope_name": null,
"edge_type": "calls",
"supplied_props": null,
- "bare_name_fallback": false,
+ "bare_name_fallback": true,
"spawned": false,
"program_call": false,
"argument_types": null,
diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.py
index c2c70435c..25f11f5b4 100644
--- a/tests/unit/ingestion/test_call_resolver_strategies.py
+++ b/tests/unit/ingestion/test_call_resolver_strategies.py
@@ -1610,6 +1610,94 @@ class TestInheritedTypedReceiver:
assert self._targets(tmp_path, files, parents, language="kotlin") == []
+class TestJavaUnnamedObjectCall:
+ """``a.b.m()`` keeps only a bare site, which repo-wide uniqueness alone may bind."""
+
+ _OTHER = "package p;\npublic class Other {\n public void m(int x) {}\n}\n"
+
+ def _targets(
+ self,
+ tmp_path: Path,
+ body: str,
+ other: str | None = None,
+ *,
+ base: str | None = None,
+ heritage: bool = True,
+ ) -> list[str]:
+ """Callees of ``Use.go``; a *base* body puts ``p.Base`` above ``Use``."""
+ extends = "" if base is None else " extends Base"
+ files = {
+ "p/Use.java": f"package p;\nimport p.Other;\nclass Use{extends} {{\n Holder a;\n"
+ f" void m(int x) {{}}\n void go() {{\n {body}\n }}\n}}\n",
+ "p/Other.java": self._OTHER if other is None else other,
+ }
+ parents: dict[str, set[str]] = {}
+ if base is not None:
+ files["p/Base.java"] = f"package p;\npublic class Base {{\n{base}\n}}\n"
+ if heritage:
+ parents["p/Use.java::Use"] = {"p/Base.java::Base"}
+ parsed = _parse_all(tmp_path, {k: ("java", v) for k, v in files.items()})
+ graph = {k: set() for k in parsed} | {"p/Use.java": {"p/Other.java"}}
+ resolver = CallResolver(parsed, graph, repo_path=str(tmp_path), heritage_parents=parents)
+ calls = parsed["p/Use.java"].calls
+ return sorted(rc.callee_id for rc in resolver.resolve_file("p/Use.java", calls))
+
+ @pytest.mark.parametrize("receiver", ["a.b", "X.CONST", "\"s\"", "arr[0]"])
+ def test_a_name_two_classes_declare_is_not_the_callers_own(
+ self, tmp_path: Path, receiver: str
+ ) -> None:
+ assert self._targets(tmp_path, f"{receiver}.m(1);") == []
+
+ def test_a_repo_wide_unique_name_still_binds(self, tmp_path: Path) -> None:
+ other = "package p;\npublic class Other {\n public void only() {}\n}\n"
+ assert self._targets(tmp_path, "a.b.only();", other) == ["p/Other.java::Other::only"]
+
+ @pytest.mark.parametrize("body", ["m(1); a.b.m(2);", "a.b.m(2); m(1);"], ids=["bare-first", "bare-last"])
+ def test_a_bare_call_beside_it_keeps_every_tier(self, tmp_path: Path, body: str) -> None:
+ assert self._targets(tmp_path, body) == ["p/Use.java::Use::m"]
+
+ def test_a_this_call_keeps_the_callers_class(self, tmp_path: Path) -> None:
+ """``this`` is a named receiver, so ``Other.m`` is no rival of the caller's own."""
+ assert self._targets(tmp_path, "this.m(1);") == ["p/Use.java::Use::m"]
+
+ def test_a_local_of_the_callers_type_binds_through_its_type(self, tmp_path: Path) -> None:
+ """A named receiver resolves by its type before ``Other.m`` is weighed."""
+ assert self._targets(tmp_path, "Use u = this; u.m(1);") == ["p/Use.java::Use::m"]
+
+ def test_super_binds_the_superclass_method_in_another_file(self, tmp_path: Path) -> None:
+ base = " void m(int x) {}"
+ assert self._targets(tmp_path, "super.m(1);", base=base) == ["p/Base.java::Base::m"]
+
+ def test_super_without_heritage_data_binds_nothing(self, tmp_path: Path) -> None:
+ """``super`` never falls to a bare-name tier, so ``Use.m`` and ``Other.m`` stay out."""
+ base = " void m(int x) {}"
+ assert self._targets(tmp_path, "super.m(1);", base=base, heritage=False) == []
+
+ @pytest.mark.parametrize(
+ ("body", "flagged"),
+ [
+ ("a.b.m(1);", True),
+ ("m(1);", False),
+ ("Use.this.m(1);", False),
+ ("a.m(1);", True),
+ ("this.m(1);", True),
+ ("super.m(1);", True),
+ ],
+ ids=["field-path", "bare", "qualified-this", "named-receiver", "this", "super"],
+ )
+ def test_only_an_unnamed_object_is_flagged(
+ self, tmp_path: Path, body: str, flagged: bool
+ ) -> None:
+ source = f"class Use {{\n void go() {{\n {body}\n }}\n}}\n"
+ (call,) = _parse_all(tmp_path, {"Use.java": ("java", source)})["Use.java"].calls
+ # A named receiver's bare twin is folded into it as ``bare_name_fallback``,
+ # a fallback reading; only the receiver-less flag marks an unnamed object.
+ assert call.bare_name_fallback is flagged
+ named = ("a.m(1);", "this.m(1);", "super.m(1);")
+ assert (call.receiver_name is None) is (body not in named)
+ assert call.on_unnamed_object is (body == "a.b.m(1);")
+
+
class TestJavaReceiverRecall:
"""Java receivers the typed tiers missed: an inherited field, ``super``, a cast."""