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): let a Java member type shadow a same-named import or package type (#3669)
Swati Ahuja9c512b3353be
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.pyindex 3af1b377a..a94638c49 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py@@ -49,7 +49,7 @@ from .languages.receiver_types import (from .models import CallSite, NamedBinding, ParsedFile, Symbol, symbol_id_languagefrom .resolved_call import ResolvedCallfrom .return_types import declared_return_type, go_first_result-from .symbol_identity import id_segment_name+from .symbol_identity import id_segment_name, outer_scope, symbol_id_pathfrom .type_names import (POINTER_LIKE_MEMBERS,bare_type_name,@@ -279,7 +279,14 @@ class ReceiverTypingMixin:A C# generic spelling (``IFoo`1``) first asks for the type that carriesthat arity in its id, which exists only beside a same-file ``IFoo``;a repo-wide guess under it is not taken over the bare name's answer.++ A Java name is read in the caller's scope (``_read_java_type``) unless+ it arrives already read, as a type id."""+ if self._language_of(file_path) == "java":+ type_name = self._read_java_type(file_path, caller_id, type_name)+ if "::" in type_name:+ return self._java_member_target(file_path, call, caller_id, type_name)bare = id_segment_name(type_name)if bare != type_name:found = self._typed_receiver_lookup(file_path, call, caller_id, type_name)@@ -325,6 +332,145 @@ class ReceiverTypingMixin:index = self._get_jvm_index()return index is not None and type_file in index.same_package_files(file_path)+ def _read_java_type(self, file_path: str, scope_id: str, spelled: str) -> str:+ """*spelled* as Java reads it in *scope_id*: a member type's id, else its bare name.++ A type id passes through, already read where it was written.+ """+ if "::" in spelled:+ return spelled+ return self._java_written_type(file_path, scope_id, spelled) or bare_type_name(spelled)++ def _java_written_type(self, file_path: str, scope_id: str, spelled: str) -> str | None:+ """The type id a Java spelling names as a member type, written in *scope_id*.++ A member type of an enclosing class, declared or inherited, shadows an+ import or a package type of its name, so a bare name asks the+ enclosing classes first. ``Outer.Inner`` is the ``Inner`` of the+ ``Outer`` *file_path* sees, and ``p.Outer`` the ``Outer`` package ``p``+ declares. None leaves the name to the ordinary lookup.+ """+ qualifier, name = type_qualifier(spelled), bare_type_name(spelled)+ if not qualifier:+ return self._enclosing_member_type(file_path, scope_id, name)+ if bare_type_name(qualifier)[:1].islower():+ return self._package_type(qualifier, name, file_path)+ owner = self._java_written_type(file_path, scope_id, qualifier)+ if owner is None and not type_qualifier(qualifier):+ owner = self._visible_top_level_type(file_path, qualifier)+ return None if owner is None else self._member_type(owner, name, file_path)++ def _package_type(self, package: str, name: str, from_file: str) -> str | None:+ """The top-level type *name* of the Java package *package* that *from_file* may use."""+ index = self._get_jvm_index()+ files = index.files_for_fqn(f"{package}.{name}") if index is not None else ()+ type_id = f"{files[0]}::{name}" if len(files) == 1 else ""+ return type_id if self._accessible_type(type_id, from_file) else None++ def _enclosing_member_type(self, file_path: str, scope_id: str, name: str) -> str | None:+ """The member type *name* of the innermost class around *scope_id* that has one.++ A type parameter of the scope or a class around it shadows it, so+ that name is left to the ordinary lookup.+ """+ symbol = self._symbols_by_id.get(scope_id)+ is_type = getattr(symbol, "kind", None) in _TYPE_KINDS+ found = self._innermost_member_type(+ scope_id if is_type else self._caller_class_id(scope_id), name, file_path+ )+ # Read only on a hit: the header scan reads the file.+ if found is not None and name in self._java_type_parameters(file_path, scope_id):+ return None+ return found++ def _innermost_member_type(self, class_id: str, name: str, file_path: str) -> str | None:+ """Walk out from *class_id* through its enclosing types to the first with member *name*."""+ node = class_id+ while "::" in node:+ if getattr(self._symbols_by_id.get(node), "kind", None) in _TYPE_KINDS:+ found = self._member_type(node, name, file_path)+ if found is not None:+ return found+ node = outer_scope(node)+ return None++ def _member_type(self, type_id: str, name: str, from_file: str) -> str | None:+ """The type *name* that *type_id* declares, else the one it inherits.++ The superclass chain answers nearest first; past it, one ancestor+ (an interface) must be the only one declaring the name. An ancestor's+ member type is inherited only where *from_file* may access it.+ """+ own = f"{type_id}::{name}"+ if self._accessible_type(own, from_file):+ return own+ for owner in self._superclass_chain(type_id):+ member = f"{owner}::{name}"+ if self._inherited_member_type(member, from_file):+ return member+ hits = {+ f"{ancestor}::{name}"+ for ancestor in self._ancestors_of(type_id)+ if self._inherited_member_type(f"{ancestor}::{name}", from_file)+ }+ return next(iter(hits)) if len(hits) == 1 else None++ def _inherited_member_type(self, member_id: str, from_file: str) -> bool:+ """Whether *member_id* is a type a subclass written in *from_file* inherits.++ An accessible one that is not private: private members are not inherited.+ """+ symbol = self._symbols_by_id.get(member_id)+ return symbol is not None and symbol.visibility != "private" and (+ self._accessible_type(member_id, from_file)+ )++ def _accessible_type(self, type_id: str, from_file: str) -> bool:+ """Whether Java lets code in *from_file* use the type *type_id*.++ A private type only within its own top-level class (its file), a+ package-private one only within its package.+ """+ symbol = self._symbols_by_id.get(type_id)+ if symbol is None or symbol.kind not in _TYPE_KINDS:+ return False+ type_file = symbol_id_path(type_id)+ if symbol.visibility == "private":+ return type_file == from_file+ if symbol.visibility == "internal":+ return posixpath.dirname(type_file) == posixpath.dirname(from_file)+ return True++ def _visible_top_level_type(self, file_path: str, name: str) -> str | None:+ """The one top-level type *name* that *file_path* sees, by import, file or package."""+ found = self._class_named(file_path, name)+ if found is not None:+ return found[1]+ if name in self._externally_bound_names(file_path):+ return None+ ids = {+ identity[0]+ for path, identity, _ in self._declared_types_named(name)+ if identity[0] == f"{path}::{name}" and self._visible_java_type(file_path, name, path)+ }+ return next(iter(ids)) if len(ids) == 1 else None++ def _java_member_target(+ self, file_path: str, call: CallSite, caller_id: str, type_id: str+ ) -> tuple[str, str] | None:+ """The method *call* names on the member type *type_id*, and its scope."""+ sym_id = self._declares(type_id, call.target_name) or self._ancestor_method(+ type_id, call.target_name, caller_id, class_chain_first=True+ )+ if sym_id is None:+ return None+ type_file = symbol_id_path(type_id)+ if type_file == file_path:+ return sym_id, "same_file"+ if posixpath.dirname(type_file) == posixpath.dirname(file_path):+ return sym_id, "same_package"+ return sym_id, "import"+def _java_type_parameters(self, file_path: str, caller_id: str) -> set[str]:"""Type parameters the caller and its enclosing types declare.@@ -736,7 +882,7 @@ class ReceiverTypingMixin:)if type_name is not None and language == "python" and "::" in type_name:return self._located(file_path, type_name) # typed from a call- return None if type_name is None else self._class_named(typing_file, type_name)+ return None if type_name is None else self._class_named(typing_file, type_name, caller_id)def _chain_hop(self, found: tuple[str, str, str], field: str, language: str@@ -750,7 +896,7 @@ class ReceiverTypingMixin:fields = self._field_types_in(class_file, language).get(class_id, {})if field in fields:type_name = fields[field]- hop = None if type_name is None else self._class_named(class_file, type_name)+ hop = None if type_name is None else self._class_named(class_file, type_name, class_id)elif language == "python":hop = self._located(class_file, self._property_type_id(class_file, class_id, field))else:@@ -768,13 +914,21 @@ class ReceiverTypingMixin:return Nonereturn path, type_id, "same_file" if path == file_path else "import"- def _class_named(self, file_path: str, type_name: str) -> tuple[str, str, str] | None:+ def _class_named(+ self, file_path: str, type_name: str, scope_id: str | None = None+ ) -> tuple[str, str, str] | None:"""``(file, class id, tier)`` for the one class *type_name* names in *file_path*.The name must be imported (a re-export followed to its declaration)or declared in *file_path* itself, and name exactly one type there:- no repo-wide guess, since every hop of a chain rests on this.+ no repo-wide guess, since every hop of a chain rests on this. A Java+ member type seen from *scope_id* answers first."""+ if scope_id is not None and self._language_of(file_path) == "java":+ type_id = self._java_written_type(file_path, scope_id, type_name)+ if type_id is not None:+ return self._located(file_path, type_id)+ type_name = bare_type_name(type_name)# A chain hop asks for the type by its written name, arity aside.type_name = id_segment_name(type_name)bound = self._import_names.get(file_path, {}).get(type_name)diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 9922302e1..b465fdff4 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -1507,6 +1507,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):key = (symbol_path, symbol.parent_name, symbol.name, count)if len(self._overload_return_types.get(key, ())) > 1:return None+ if type_name is not None and language == "java":+ # Read where the method declares it, with its member types in scope.+ return self._read_java_type(symbol_path, callee_id, type_name)return type_namedef _return_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex a53257c78..f90f0d962 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -31,9 +31,9 @@ from ..type_names import (bare_type_name,is_resolvable_type_name,strip_type_arguments,- type_argument_count,type_qualifier,unwrap_pointer_like,+ written_type_key,)# A type as written before a declared name: optionally qualified, generic to two@@ -889,7 +889,8 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:Only C++ looks inside the spelling: ``shared_ptr<Foo>`` is a ``Foo`` behindthe arrow. Elsewhere the generic head is the value's real type. A C# headkeeps its arity, ``IFoo`1``, since a same-file ``IFoo`` may be another type;- the lookup falls back to the bare name.+ the lookup falls back to the bare name. A Java ``Token.Tag`` keeps its+ outer type, which picks the member type the lookup means."""if _nests_in_a_builtin(raw, language):return None, False@@ -897,9 +898,7 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:name = inner or (raw if raw.isidentifier() else bare_type_name(raw))if not is_resolvable_type_name(name, language):return None, False- if language == "csharp" and (arity := type_argument_count(raw)):- name = f"{name}`{arity}"- return name, inner is not None+ return written_type_key(name, raw, language), inner is not None# Languages whose constructor parameter lists sit at class scope, unextracted,diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.pyindex e8c37d5f0..f6176c7d6 100644--- a/packages/core/src/repowise/core/ingestion/return_types.py+++ b/packages/core/src/repowise/core/ingestion/return_types.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport re-from .type_names import bare_type_name, type_argument_count+from .type_names import bare_type_name, written_type_key_NULLISH_UNION = re.compile(r"\s*\|\s*(?:null|undefined)\b")_CPP_PREFIX = re.compile(r"^(?:(?:const|volatile|typename|class|struct)\s+)+")@@ -137,6 +137,4 @@ def normalize_return_type(raw: str, language: str) -> str | None:name = bare_type_name(value).strip()if not name.isidentifier():return None- if language == "csharp" and (arity := type_argument_count(value)):- return f"{name}`{arity}"- return name+ return written_type_key(name, value, language)diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.pyindex 59695be06..d9fdd0809 100644--- a/packages/core/src/repowise/core/ingestion/type_names.py+++ b/packages/core/src/repowise/core/ingestion/type_names.py@@ -94,6 +94,34 @@ def bare_type_name(raw: str) -> str:return text.strip()+def written_type_key(name: str, raw: str, language: str) -> str:+ """*name*, the bare type *raw* spells, as receiver lookups key it.++ A C# head keeps its arity (``IFoo`1``), since a same-file ``IFoo`` may be+ another type; a Java member type keeps its outer type (``Token.Tag``),+ which picks among same-named member types.+ """+ if language == "csharp" and (arity := type_argument_count(raw)):+ return f"{name}`{arity}"+ if language == "java":+ return java_type_path(raw) or name+ return name+++def java_type_path(raw: str) -> str | None:+ """``p.Token.Tag<X>[]`` -> ``p.Token.Tag``: a type spelled through its qualifiers.++ Kept whole because the qualifier picks which same-named type is meant: an+ outer type a member type, a package (lowercase) a top-level type. None for+ an undotted spelling or one that names no type.+ """+ text = strip_type_arguments(raw.strip()).replace(" ", "")+ parts = text.split(".")+ if len(parts) < 2 or not any(part[:1].isupper() for part in parts):+ return None+ return text if all(part.isidentifier() for part in parts) else None++def type_argument_count(raw: str) -> int:"""How many type arguments the named type in *raw* is given.diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.pyindex a2ac75278..6b81b97d6 100644--- a/tests/unit/ingestion/test_call_resolver_strategies.py+++ b/tests/unit/ingestion/test_call_resolver_strategies.py@@ -1602,6 +1602,175 @@ class TestJavaReceiverRecall:]+class TestJavaMemberTypes:+ """A member type shadows a same-named import or package type, as Java scopes it.++ ``p.Token`` nests ``Tag`` and ``Comment``; ``p.Tag`` and ``n.Comment`` are+ top-level types of the same simple names.+ """++ _TOKEN = (+ "package p;\nabstract class Token {\n"+ " static abstract class Tag extends Token {\n"+ " Tag reset() { return this; }\n String name() { return null; }\n }\n"+ " static final class StartTag extends Tag {}\n"+ " static final class Comment extends Token {\n"+ " String getData() { return null; }\n }\n}\n"+ )++ def _targets(self, tmp_path: Path, source: str) -> list[tuple[str, str]]:+ files = {+ "p/Token.java": self._TOKEN,+ "p/Tag.java": "package p;\npublic class Tag {\n public String name() { return null; }\n}\n",+ "n/Comment.java": "package n;\npublic class Comment {\n"+ " public String getData() { return null; }\n}\n",+ "p/Use.java": source,+ }+ parsed = _parse_all(tmp_path, {k: ("java", v) for k, v in files.items()})+ _link_imports(parsed, {"p/Use.java": {"n.Comment": "n/Comment.java"}})+ token, tag = "p/Token.java::Token", "p/Token.java::Token::Tag"+ parents = {tag: {token}, f"{token}::StartTag": {tag}, f"{token}::Comment": {token}}+ if "extends Token" in source:+ parents["p/Use.java::Use"] = {token}+ resolver = CallResolver(+ parsed, {k: set() for k in parsed}, repo_path=str(tmp_path), heritage_parents=parents+ )+ calls = parsed["p/Use.java"].calls+ return sorted((rc.callee_id, rc.origin) for rc in resolver.resolve_file("p/Use.java", calls))++ def test_a_qualified_type_names_the_member_type(self, tmp_path: Path) -> None:+ """``Token.Tag`` is not the package's top-level ``Tag``, nor ``Token.Comment`` the import."""+ source = (+ "package p;\nimport n.Comment;\nclass Use {\n Token.Tag pending;\n"+ " void go(Token.Comment c) {\n pending.name();\n c.getData();\n }\n}\n"+ )+ assert self._targets(tmp_path, source) == [+ ("p/Token.java::Comment::getData", "receiver_typed_same_package"),+ ("p/Token.java::Tag::name", "receiver_field_same_package"),+ ]++ def test_an_inherited_member_type_shadows_an_import(self, tmp_path: Path) -> None:+ source = (+ "package p;\nimport n.Comment;\nclass Use extends Token {\n"+ " void go(Comment c) {\n c.getData();\n }\n}\n"+ )+ assert self._targets(tmp_path, source) == [+ ("p/Token.java::Comment::getData", "receiver_typed_same_package")+ ]++ def test_a_return_type_is_read_where_its_method_declares_it(self, tmp_path: Path) -> None:+ """``reset()`` returns ``Tag`` inside ``Token``, so its ``name()`` is the member's."""+ source = (+ "package p;\nclass Use {\n void go(Token.StartTag t) {\n"+ " t.reset().name();\n }\n}\n"+ )+ assert self._targets(tmp_path, source) == [+ ("p/Token.java::Tag::name", "return_type_same_package"),+ ("p/Token.java::Tag::reset", "receiver_typed_same_package"),+ ]++ def test_a_top_level_type_answers_where_no_member_shadows_it(self, tmp_path: Path) -> None:+ source = (+ "package p;\nimport n.Comment;\nclass Use {\n"+ " void go(Tag t, Comment c) {\n t.name();\n c.getData();\n }\n}\n"+ )+ assert self._targets(tmp_path, source) == [+ ("n/Comment.java::Comment::getData", "receiver_typed_import"),+ ("p/Tag.java::Tag::name", "receiver_typed_same_package"),+ ]++ def test_a_type_parameter_shadows_a_member_type(self, tmp_path: Path) -> None:+ source = (+ "package p;\nimport n.Comment;\nclass Use extends Token {\n"+ " <Comment> void go(Comment c) {\n c.getData();\n }\n}\n"+ )+ assert ("p/Token.java::Comment::getData", "receiver_typed_same_package") not in (+ self._targets(tmp_path, source)+ )++ @pytest.mark.parametrize(+ ("outer", "inner", "returns"),+ [+ ("class Outer", "public static class Inner", "q.Outer.Inner"),+ ("public class Outer", "private static class Inner", "q.Outer.Inner"),+ ("public class Outer", "static class Inner", "Outer.Inner"),+ ],+ ids=["package-private-top-level", "private-member", "package-private-member"],+ )+ def test_a_qualified_type_the_caller_cannot_access_is_not_resolved(+ self, tmp_path: Path, outer: str, inner: str, returns: str+ ) -> None:+ """Java's access rules apply to a qualified spelling as they do to a plain name."""+ files = {+ "q/Outer.java": f"package q;\n{outer} {{\n"+ f" {inner} {{\n public void z() {{}}\n }}\n}}\n",+ "x/Factory.java": "package x;\nimport q.Outer;\npublic class Factory {\n"+ f" public static {returns} make() {{ return null; }}\n}}\n",+ "a/Use.java": "package a;\nimport x.Factory;\nclass Use {\n"+ " void go() {\n Factory.make().z();\n }\n}\n",+ }+ parsed = _parse_all(tmp_path, {k: ("java", v) for k, v in files.items()})+ _link_imports(parsed, {"a/Use.java": {"x.Factory": "x/Factory.java"}})+ _link_imports(parsed, {"x/Factory.java": {"q.Outer": "q/Outer.java"}})+ resolver = CallResolver(parsed, {k: set() for k in parsed}, repo_path=str(tmp_path))+ calls = parsed["a/Use.java"].calls+ assert "q/Outer.java::Inner::z" not in {+ rc.callee_id for rc in resolver.resolve_file("a/Use.java", calls)+ }++ def test_a_package_qualified_return_type_names_its_package_type(self, tmp_path: Path) -> None:+ """``p.Outer.Inner make()`` is ``p.Outer``'s ``Inner``, not the ``q.Inner`` imported."""+ files = {+ "p/Outer.java": "package p;\npublic class Outer {\n"+ " public static class Inner {\n public void z() {}\n }\n}\n",+ "q/Inner.java": "package q;\npublic class Inner {\n public void z() {}\n}\n",+ "x/Factory.java": "package x;\nimport q.Inner;\npublic class Factory {\n"+ " public static p.Outer.Inner make() { return null; }\n}\n",+ "a/Use.java": "package a;\nimport q.Inner;\nimport x.Factory;\nclass Use {\n"+ " void go() {\n Factory.make().z();\n }\n}\n",+ }+ parsed = _parse_all(tmp_path, {k: ("java", v) for k, v in files.items()})+ imports = {"q.Inner": "q/Inner.java", "x.Factory": "x/Factory.java"}+ _link_imports(parsed, {"a/Use.java": imports, "x/Factory.java": imports})+ resolver = CallResolver(parsed, {k: set() for k in parsed}, repo_path=str(tmp_path))+ calls = parsed["a/Use.java"].calls+ assert "p/Outer.java::Inner::z" in {+ rc.callee_id for rc in resolver.resolve_file("a/Use.java", calls)+ }++ @pytest.mark.parametrize(+ ("modifier", "inherited"),+ [("private ", False), ("", False), ("protected ", True)],+ ids=["private", "package-private-elsewhere", "protected"],+ )+ def test_only_an_accessible_superclass_member_type_shadows_an_import(+ self, tmp_path: Path, modifier: str, inherited: bool+ ) -> None:+ """``b.Base``'s nested ``Inner`` is inherited by ``a.Sub`` only if ``a`` may access it."""+ files = {+ "b/Base.java": "package b;\npublic class Base {\n"+ f" {modifier}static class Inner {{\n void z() {{}}\n }}\n}}\n",+ "c/Inner.java": "package c;\npublic class Inner {\n"+ " public void y() {}\n public void z() {}\n}\n",+ "a/Sub.java": "package a;\nimport b.Base;\nimport c.Inner;\npublic class Sub extends Base {\n"+ " void m(Inner i) {\n i.z();\n i.y();\n }\n}\n",+ }+ parsed = _parse_all(tmp_path, {k: ("java", v) for k, v in files.items()})+ _link_imports(parsed, {"a/Sub.java": {"b.Base": "b/Base.java", "c.Inner": "c/Inner.java"}})+ resolver = CallResolver(+ parsed,+ {k: set() for k in parsed},+ repo_path=str(tmp_path),+ heritage_parents={"a/Sub.java::Sub": {"b/Base.java::Base"}},+ )+ calls = parsed["a/Sub.java"].calls+ callees = sorted(rc.callee_id for rc in resolver.resolve_file("a/Sub.java", calls))+ if inherited:+ assert callees == ["b/Base.java::Inner::z"]+ else:+ assert callees == ["c/Inner.java::Inner::y", "c/Inner.java::Inner::z"]++class TestOwnerAwareModuleTier:"""The module and import-name tiers pick an owner, not just a file.diff --git a/tests/unit/ingestion/test_return_types.py b/tests/unit/ingestion/test_return_types.pyindex d83c2bc58..0b34dc2ad 100644--- a/tests/unit/ingestion/test_return_types.py+++ b/tests/unit/ingestion/test_return_types.py@@ -31,7 +31,8 @@ def test_signature_parameter_count(signature: str, expected: int | None) -> None("raw", "language", "expected"),[("Result", "java", "Result"),- ("java.util.Optional<Result>", "java", "Optional"),+ # Java keeps its qualifiers: the resolver reads them where they were written.+ ("java.util.Optional<Result>", "java", "java.util.Optional"),("const seastar::future<Result>&", "cpp", "future"),("global::System.Threading.Tasks.Task<Result>?", "csharp", "Task`1"),("IRuleBuilderOptions<T, TProperty>", "csharp", "IRuleBuilderOptions`2"),