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(java): refuse a member call on a receiver typed with a JDK or library type (#2827)
Raghav Chamadiya372d915804ea
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.pyindex 33da777d3..5a57834db 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py@@ -11,6 +11,7 @@ from typing import NamedTuple, TypeVarfrom .languages.receiver_types import (BINDING_LANGUAGES,CALL_TYPED_LANGUAGES,+ EXTERNAL_TYPE_LANGUAGES,FRAMEWORK_DECORATOR_LANGUAGES,IMPLICIT_FIELD_LANGUAGES,RANGE_LANGUAGES,@@ -22,6 +23,7 @@ from .languages.receiver_types import (ScopeMarks,bound_types,clauses_in_span,+ external_type_name,framework_decorated_type,in_spans,merge_spans,@@ -41,7 +43,7 @@ from .models import CallSite, ParsedFile, Symbol, symbol_id_languagefrom .resolved_call import ResolvedCallfrom .return_types import declared_return_type, go_first_resultfrom .symbol_identity import id_segment_name-from .type_names import POINTER_LIKE_MEMBERS, bare_type_name+from .type_names import POINTER_LIKE_MEMBERS, bare_type_name, type_qualifier# Which symbols own a class scope, and which of them swallow one. A class span# contains every method body inside it, so both sets are needed to tell a field@@ -333,6 +335,12 @@ class ReceiverTypingMixin:)if type_name is None:return None+ builtin = external_type_name(type_name)+ if builtin is not None:+ # Typed only when a repo class shadows the builtin's name.+ if builtin not in self._known_type_names:+ return None+ type_name = builtinif "::" in type_name:# A symbol id, recorded by ``_add_call_typed_locals``.return self._call_typed_receiver(file_path, call, caller_id, type_name)@@ -365,13 +373,21 @@ class ReceiverTypingMixin:only a name neither binds reaches module scope."""body_types = self._declared_types_in(file_path, caller_id, language)- if receiver_name in body_types:- return body_types[receiver_name], "body"+ # A builtin type answers only when nothing else does, so a local+ # ``String data`` leaves ``this.data.m()``, which reaches here as+ # ``data.m()``, to the field.+ declared = body_types.get(receiver_name)+ builtin_local = external_type_name(declared) is not None+ if receiver_name in body_types and not builtin_local:+ return declared, "body"if language in IMPLICIT_FIELD_LANGUAGES:class_id = self._caller_class_id(caller_id)fields = self._field_types_in(file_path, language).get(class_id, {})- if receiver_name in fields:- return fields[receiver_name], "field"+ field = fields.get(receiver_name)+ if receiver_name in fields and not (builtin_local and external_type_name(field)):+ return field, "field"+ if builtin_local:+ return declared, "body"# Third scope: a module-level def a framework decorator turned into an# instance, which is neither in the body nor a field.if language in FRAMEWORK_DECORATOR_LANGUAGES:@@ -702,6 +718,36 @@ class ReceiverTypingMixin:self._method_name_set = frozenset(method for _, method in self._global_methods)return self._method_name_set+ def _receiver_type_is_external(self, file_path: str, call: CallSite, caller_id: str) -> bool:+ """Is ``x.m()``'s receiver declared with a type the repository does not own?++ Then the method is that type's and no name match in the repo is the+ callee. External means a builtin (``ArrayList``, ``Map.Entry``) or a name+ an import binds outside the repo; a type the repo also declares is+ never external, since an unresolved import or a shadowing ``class+ List`` may mean it. A name that merely resolves nowhere (a generic+ parameter, a wildcard import's member) is unknown, not external.++ The declared type decides, not the runtime one: ``List<E> l`` calling+ ``l.add()`` names ``List.add`` even when a repo class implements+ ``List``, and that override is a dispatch edge, not this call's target.+ """+ receiver_name = call.receiver_name or ""+ if "." in receiver_name:+ return False+ language = self._typed_receiver_language(file_path, call)+ if language not in EXTERNAL_TYPE_LANGUAGES:+ return False+ type_name, _ = self._receiver_type_and_scope(file_path, caller_id, language, receiver_name)+ if type_name is None or "::" in type_name:+ return False+ builtin = external_type_name(type_name)+ # ``Map.Entry``: the builtin head settles it, unless the repo owns the head.+ head = type_qualifier(builtin or type_name) or builtin or type_name+ if head in self._known_type_names:+ return False+ return builtin is not None or head in self._externally_bound_names(file_path)+def _externally_bound_names(self, file_path: str) -> frozenset[str]:"""Simple names this file imports from outside the repo.diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 15a0752b4..2e52aac63 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -1387,6 +1387,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):return True, hithit = self._unclassed_receiver_call(file_path, call, caller_id)+ if hit is None and self._receiver_type_is_external(file_path, call, caller_id):+ # The method is the external type's: refused, not left to a name match.+ return True, Nonereturn hit is not None, hitdef _unclassed_receiver_call(diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex a43684d64..5129b5904 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -321,6 +321,13 @@ RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)# on the scan actually finding typed fields in the language's idiom.IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "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.+# Only where nothing in the repo can add a method to a builtin type: C#+# extension methods, Kotlin and Swift extensions and Rust trait impls all can.+EXTERNAL_TYPE_LANGUAGES = frozenset({"java"})+_EXTERNAL_TYPE = "external:"+# A decorator that changes what the symbol it wraps *is*: `@shared_task` leaves# no function behind, so `add.s(...)` is a method call on `Task`. A table, since# the decorator lives in an imported framework. Ceiling: an entry earns nothing@@ -711,6 +718,8 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:raw = match.group("type")if raw not in resolved:resolved[raw] = _usable_type_name(raw, language)+ if resolved[raw][0] is None and language in EXTERNAL_TYPE_LANGUAGES:+ resolved[raw] = (_builtin_type_name(raw, language), False)type_name, unwrapped = resolved[raw]if type_name is None:continue@@ -735,6 +744,26 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:return tuple(found)+def _builtin_type_name(raw: str, language: str) -> str | None:+ """The marked builtin *raw* spells, ``Map.Entry`` for a member type, or None.++ Kept where ``_usable_type_name`` drops it, so a call on the value can be+ refused rather than left to name matching. A generic parameter (``T``) or+ any other unknown name stays dropped: unknown is not external.+ """+ if _nests_in_a_builtin(raw, language):+ return _EXTERNAL_TYPE + strip_type_arguments(raw).strip()+ name = raw if raw.isidentifier() else bare_type_name(raw)+ return _EXTERNAL_TYPE + name if name in get_builtin_types(language) else None+++def external_type_name(type_name: str | None) -> str | None:+ """The builtin a marked type names, or None for any other type."""+ if type_name is None or not type_name.startswith(_EXTERNAL_TYPE):+ return None+ return type_name[len(_EXTERNAL_TYPE) :]++class CallAssignment(NamedTuple):"""``name := receiver.target(..)`` at one line, typed later by the resolver."""@@ -812,11 +841,17 @@ def _record(types: dict[str, str | None], declaration: Declaration) -> None:A name declared with two types maps to ``None`` rather than being dropped:only "says nothing" may fall through to a wider scope, not "says somethingunusable".++ A builtin type is the weakest answer: it fills only a name nothing else+ types, so every non-builtin reading is what it was without it."""- if declaration.name not in types:- types[declaration.name] = declaration.type_name- elif types[declaration.name] != declaration.type_name:- types[declaration.name] = None+ name, type_name = declaration.name, declaration.type_name+ if name not in types or (+ external_type_name(types[name]) is not None and external_type_name(type_name) is None+ ):+ types[name] = type_name+ elif external_type_name(type_name) is None and types[name] != type_name:+ types[name] = Nonedef types_in_span(diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.pyindex 897a31d92..d58f87f16 100644--- a/tests/unit/ingestion/test_call_resolver_strategies.py+++ b/tests/unit/ingestion/test_call_resolver_strategies.py@@ -1129,3 +1129,181 @@ class TestOwnerAwareModuleTier:0.88,"module_alias",) in _edges(parsed, tmp_path)+++class TestExternalReceiverType:+ """A Java receiver declared with a type the repo does not own is refused.++ Every case declares a same-package ``TagSet`` with ``get`` and ``add``, the+ names a name-only tier would otherwise hand the call to.+ """++ _PKG = "src/org/acme/"+ _TAGSET = (+ "package org.acme;\npublic class TagSet {\n"+ " public Object get(int i) { return null; }\n"+ " public boolean add(Object o) { return true; }\n}\n"+ )++ def _caller_edges(+ self, tmp_path: Path, caller: str, **others: str+ ) -> list[tuple[str, str, float, str]]:+ files = {"TagSet.java": self._TAGSET, **others, "Caller.java": caller}+ parsed = _parse_all(tmp_path, {self._PKG + k: ("java", v) for k, v in files.items()})+ return [e for e in _edges(parsed, tmp_path) if "Caller.java" in e[0]]++ @staticmethod+ def _caller(imports: str, body: str, members: str = "") -> str:+ return (+ f"package org.acme;\n{imports}public class Caller {{\n{members}"+ f" public Object run({body}\n }}\n}}\n"+ )++ def test_an_imported_jdk_type_is_refused(self, tmp_path: Path) -> None:+ caller = self._caller(+ "import java.util.ArrayList;\n",+ "ArrayList<Object> stack) {\n return stack.get(0);",+ )+ assert self._caller_edges(tmp_path, caller) == []++ def test_a_java_lang_type_needs_no_import_to_be_refused(self, tmp_path: Path) -> None:+ caller = self._caller(+ "", ") {\n StringBuilder sb = new StringBuilder();\n return sb.add(1);"+ )+ assert self._caller_edges(tmp_path, caller) == []++ def test_a_field_of_a_jdk_type_is_refused(self, tmp_path: Path) -> None:+ caller = self._caller(+ "import java.util.List;\n",+ ") {\n return items.get(0);",+ members=" private final List<Object> items = null;\n",+ )+ assert self._caller_edges(tmp_path, caller) == []++ def test_a_member_type_of_a_jdk_type_is_refused(self, tmp_path: Path) -> None:+ caller = self._caller(+ "import java.util.Map;\n",+ "Map.Entry<String, Object> e) {\n return e.get(0);",+ )+ assert self._caller_edges(tmp_path, caller) == []++ def test_a_wildcard_imported_jdk_type_is_refused(self, tmp_path: Path) -> None:+ caller = self._caller("import java.util.*;\n", "List<Object> l) {\n return l.get(0);")+ assert self._caller_edges(tmp_path, caller) == []++ def test_a_type_imported_from_outside_the_repo_is_refused(self, tmp_path: Path) -> None:+ caller = self._caller(+ "import com.vendor.Multiset;\n",+ "Multiset<Object> m) {\n return m.add(1);",+ )+ assert self._caller_edges(tmp_path, caller) == []++ def test_the_static_type_decides_over_a_repo_subclass(self, tmp_path: Path) -> None:+ """``ArrayList l = new Elements()`` calls ``ArrayList.get``; the override is dispatch."""+ elements = (+ "package org.acme;\nimport java.util.ArrayList;\n"+ "public class Elements extends ArrayList<Object> {\n"+ " public Object get(int i) { return null; }\n}\n"+ )+ caller = self._caller(+ "import java.util.ArrayList;\n",+ ") {\n ArrayList<Object> l = new Elements();\n return l.get(0);",+ )+ edges = self._caller_edges(tmp_path, caller, **{"Elements.java": elements})+ assert not [e for e in edges if e[1].endswith("::get")]++ def test_a_repo_subclass_of_a_jdk_type_resolves(self, tmp_path: Path) -> None:+ elements = (+ "package org.acme;\nimport java.util.ArrayList;\n"+ "public class Elements extends ArrayList<Object> {\n"+ " public Object get(int i) { return null; }\n}\n"+ )+ caller = self._caller("", "Elements l) {\n return l.get(0);")+ assert (+ "src/org/acme/Caller.java::Caller::run",+ "src/org/acme/Elements.java::Elements::get",+ 0.90,+ "receiver_typed_same_package",+ ) in self._caller_edges(tmp_path, caller, **{"Elements.java": elements})++ def test_a_repo_class_shadowing_a_jdk_name_resolves(self, tmp_path: Path) -> None:+ shadow = (+ "package org.acme;\npublic class List {\n"+ " public Object get(int i) { return null; }\n}\n"+ )+ caller = self._caller("", "List l) {\n return l.get(0);")+ assert (+ "src/org/acme/Caller.java::Caller::run",+ "src/org/acme/List.java::List::get",+ 0.90,+ "receiver_typed_same_package",+ ) in self._caller_edges(tmp_path, caller, **{"List.java": shadow})++ def test_a_builtin_local_leaves_this_field_to_the_field(self, tmp_path: Path) -> None:+ """``this.data.get()`` reaches the resolver as ``data.get()``, beside a ``String data``."""+ caller = self._caller(+ "",+ ") {\n String data = null;\n return this.data.get(0);",+ members=" private final TagSet data = new TagSet();\n",+ )+ assert (+ "src/org/acme/Caller.java::Caller::run",+ "src/org/acme/TagSet.java::TagSet::get",+ 0.90,+ "receiver_field_same_package",+ ) in self._caller_edges(tmp_path, caller)++ def test_an_inner_repo_class_resolves(self, tmp_path: Path) -> None:+ outer = (+ "package org.acme;\npublic class Outer {\n public static class Inner {\n"+ " public Object get(int i) { return null; }\n }\n}\n"+ )+ caller = self._caller("", "Outer.Inner x) {\n return x.get(0);")+ assert (+ "src/org/acme/Caller.java::Caller::run",+ "src/org/acme/Outer.java::Inner::get",+ 0.90,+ "receiver_typed_same_package",+ ) in self._caller_edges(tmp_path, caller, **{"Outer.java": outer})++ def test_a_generic_parameter_is_not_refused(self, tmp_path: Path) -> None:+ """``T`` is unknown, not external: the name tiers still answer."""+ caller = self._caller(+ "",+ "Object o) {\n return run2(o);\n }\n"+ " public <T> Object run2(T x) {\n return x.get(0);",+ )+ assert [e[1] for e in self._caller_edges(tmp_path, caller) if e[1].endswith("::get")] == [+ "src/org/acme/TagSet.java::TagSet::get"+ ]++ def test_a_wildcard_imported_unknown_type_is_not_refused(self, tmp_path: Path) -> None:+ caller = self._caller("import com.vendor.*;\n", "Widget w) {\n return w.get(0);")+ assert [e[1] for e in self._caller_edges(tmp_path, caller)] == [+ "src/org/acme/TagSet.java::TagSet::get"+ ]++ def test_an_unresolved_import_of_a_repo_type_is_not_refused(self, tmp_path: Path) -> None:+ """No import-resolution phase runs here, so the import reads as external.++ The repo declaring the name is what keeps it from being refused.+ """+ caller = self._caller(+ "import org.acme.TagSet;\n", "TagSet t) {\n return t.get(0);"+ )+ assert [e[1] for e in self._caller_edges(tmp_path, caller)] == [+ "src/org/acme/TagSet.java::TagSet::get"+ ]++ def test_only_java_records_builtin_declarations(self) -> None:+ from repowise.core.ingestion.languages.receiver_types import (+ EXTERNAL_TYPE_LANGUAGES,+ scan_declarations,+ )++ assert frozenset({"java"}) == EXTERNAL_TYPE_LANGUAGES+ # Each name is a builtin of its own language.+ assert [d.type_name for d in scan_declarations("Task<Foo> t;\n", "csharp")] == []+ assert [d.type_name for d in scan_declarations("List<Foo> xs;\n", "java")] == [+ "external:List"+ ]diff --git a/tests/unit/ingestion/test_enclosing_class_calls.py b/tests/unit/ingestion/test_enclosing_class_calls.pyindex 61db68f90..c34e2cbbb 100644--- a/tests/unit/ingestion/test_enclosing_class_calls.py+++ b/tests/unit/ingestion/test_enclosing_class_calls.py@@ -215,7 +215,7 @@ class Tag {# answer the grammar's bare pattern always gave it.JAVA_UNTYPED_RECEIVER = """class A {- int count(Object o) { return o.size(); }+ <T> int count(T o) { return o.size(); }}class Box {diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.pyindex e05231d09..54b056621 100644--- a/tests/unit/ingestion/test_receiver_types.py+++ b/tests/unit/ingestion/test_receiver_types.py@@ -12,6 +12,7 @@ from repowise.core.ingestion.languages.receiver_types import (IMPLICIT_FIELD_LANGUAGES,RECEIVER_TYPE_LANGUAGES,CallAssignment,+ external_type_name,scan_call_assignments,scan_declarations,types_by_class,@@ -196,11 +197,16 @@ class TestRefusals:produced real wrong edges before this rule existed."""body = "void run() { Map.Entry<Object, Object> entry = it.next(); }"- assert "entry" not in declared_types(body, "java")+ assert external_type_name(declared_types(body, "java")["entry"]) == "Map.Entry"def test_builtin_types_are_refused(self) -> None:+ """Kept only as an external mark, which types nothing and refuses the call."""body = "void run(String name, Object value) { }"- assert declared_types(body, "java") == {}+ types = declared_types(body, "java")+ assert {name: external_type_name(t) for name, t in types.items()} == {+ "name": "String",+ "value": "Object",+ }def test_single_letter_type_parameter_is_refused(self) -> None:body = "<T> void run(T item) { item.hash(); }"