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): give Java anonymous-class and Kotlin object-expression methods their own node (#3624)
Swati Ahuja1a37148e489a
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.pyindex e61595717..17e7ebf91 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py@@ -9,6 +9,7 @@ from dataclasses import replacefrom pathlib import Pathfrom typing import NamedTuple, TypeVar+from .lang_helpers.anonymous_classes import is_anonymous_memberfrom .languages.receiver_types import (BINDING_LANGUAGES,CALL_TYPED_LANGUAGES,@@ -468,9 +469,11 @@ class ReceiverTypingMixin:only a name neither binds reaches module scope. A name the body bindswith no type it can read (`{ api -> api.m() }`) is still a local, so itrefuses the field too. A field a repository ancestor declares is read- in that ancestor's file.+ in that ancestor's file. A name an anonymous class member's body+ neither types nor binds is asked of the function around it, whose+ locals it captures and whose class fields it sees."""- body_types = self._declared_types_in(file_path, caller_id, language)+ caller_id, body_types = self._typing_scope(file_path, caller_id, language, receiver_name)# 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.@@ -768,6 +771,77 @@ class ReceiverTypingMixin:ids = self._type_ids.get(file_path, {}).get(type_name, ())return ids[0] if len(ids) == 1 else None+ def _capture_host(+ self,+ file_path: str,+ caller_id: str,+ language: str,+ receiver_name: str,+ body_types: dict[str, str | None],+ ) -> str | None:+ """The function to ask about a name an anonymous member neither types nor binds."""+ host = self._capturing_function(caller_id)+ if host is None or receiver_name in body_types:+ return None+ if receiver_name in self._bound_names_in(file_path, caller_id, language):+ return None+ return host++ def _typing_scope(+ self, file_path: str, caller_id: str, language: str, receiver_name: str+ ) -> tuple[str, dict[str, str | None]]:+ """The function whose body answers for *receiver_name*, with that body's types.++ The caller's own, else, for an anonymous class member, out through each+ enclosing function until one types or binds the name.+ """+ body_types = self._declared_types_in(file_path, caller_id, language)+ host = self._capture_host(file_path, caller_id, language, receiver_name, body_types)+ while host is not None:+ body_types = self._captured_types(file_path, host, caller_id, language)+ caller_id, host = host, self._capture_host(+ file_path, host, language, receiver_name, body_types+ )+ return caller_id, body_types++ def _captured_types(+ self, file_path: str, host: str, caller_id: str, language: str+ ) -> dict[str, str | None]:+ """``{name: type}`` for the *host* locals its anonymous member *caller_id* sees.++ Those declared above the member, outside every symbol nested in the+ host, such as another anonymous class's method. A lambda is no symbol,+ so its locals still read as the host's, as they do for the host's own+ calls.+ """+ spans = self._spans_for(file_path)+ start, end = spans[host][0], spans[caller_id][0] - 1+ nested = merge_spans(+ span for sym_id, span in spans.items() if sym_id != host and start < span[0] <= end+ )+ declarations = tuple(+ d for d in self._declarations_for(file_path, language) if not in_spans(nested, d.line)+ )+ return types_in_span(declarations, start, end)++ def _capturing_function(self, caller_id: str) -> str | None:+ """The function an anonymous class member *caller_id* is declared in.++ Found by walking up the member's id to the first symbol. A class there+ (a field initializer's anonymous class) or an overloaded function,+ whose id carries a signature the holder segment does not, answers None.+ """+ caller = self._symbols_by_id.get(caller_id)+ if caller is None or not is_anonymous_member(caller):+ return None+ scope = _enclosing_id(caller_id)+ while "::" in scope:+ scope = _enclosing_id(scope)+ holder = self._symbols_by_id.get(scope)+ if holder is not None:+ return scope if holder.kind in _FUNCTION_KINDS else None+ return None+def _caller_class_id(self, caller_id: str) -> str:"""The id of the type whose method *caller_id* is.diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 65df0b194..069e131ed 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -42,6 +42,7 @@ from .call_receiver_typing import (_store_capped,)from .decorator_names import decorator_base+from .lang_helpers.anonymous_classes import is_anonymous_memberfrom .language_data import (get_builtin_methods,get_builtin_types,@@ -65,7 +66,7 @@ from .return_types import (signature_parameter_count,signature_parameter_range,)-from .symbol_identity import id_segment_name, pair_overloads, split_symbol_id+from .symbol_identity import id_segment_name, outer_scope, pair_overloads, split_symbol_idfrom .type_names import (csharp_extension_receiver,is_resolvable_type_name,@@ -574,24 +575,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):decl_key = (sym.parent_name, sym.name)if sym.is_declaration:declarations.append((path, index_id, decl_key))- # A declaration must never displace a definition already- # indexed under this name — a .cpp that forward-declares a- # helper above its own body holds both.- #- # A method declaration stays out: this index answers- # unqualified lookups from importing files, and no bare name- # can legally reach a method. The (class, method) index- # below still takes it.- if sym.parent_name is None:- file_syms.setdefault(sym.name, index_id)- top_level.setdefault(sym.name, index_id)else:definitions[decl_key].append((path, index_id))- # File-level symbol index (top-level symbols and methods)- if sym.kind not in _EXTENSION_KINDS:- file_syms[sym.name] = index_id- if sym.parent_name is None:- top_level[sym.name] = index_id+ _index_bare_name(sym, index_id, file_syms, top_level)# Method index: (class_name, method_name) → symbol_idif sym.parent_name:@@ -626,9 +612,8 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):if _is_property_accessor(sym):self._property_accessor_ids.add(index_id)# Same rules as the per-file index, for the global-unique tier.- if not (sym.is_declaration and sym.parent_name is not None) and (- sym.kind not in _EXTENSION_KINDS- ):+ bodiless_method = sym.is_declaration and sym.parent_name is not None+ if not (bodiless_method or sym.kind in _EXTENSION_KINDS or is_anonymous_member(sym)):self._global_symbols[sym.name].append(index_id)def _index_overload_sets(self, parsed: ParsedFile) -> dict[str, str]:@@ -1360,16 +1345,22 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):class ``A`` would bind to class ``B``'s ``foo`` when ``B`` came later inthe file. ``_file_methods`` carries the class. A member call on its barefallback has an explicit receiver, so the caller's class is not it.+ An anonymous class or enum-constant body (``Gson::FILTER::Filter``)+ sees its own members first, then those of the class around it."""parsed = self._parsed_files.get(file_path)if parsed is None or parsed.file_info.language not in _IMPLICIT_RECEIVER_LANGUAGES:return Noneif call.receiver_name:return None+ methods = self._file_methods.get(file_path, {})caller_class = _extract_class_from_symbol_id(caller_id)- if not caller_class:- return None- return self._file_methods.get(file_path, {}).get((caller_class, call.target_name))+ while caller_class:+ own = methods.get((caller_class, call.target_name))+ if own is not None:+ return own+ caller_class = outer_scope(caller_class)+ return Nonedef _partial_fragment_member(self, file_path: str, caller_id: str, name: str) -> str | None:"""The caller's class member *name* declared in another fragment of it.@@ -1486,10 +1477,12 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):caller_id: str,) -> tuple[bool, ResolvedCall | None]:"""Tier 1, as ``(handled, edge)``: a handled None is a refusal."""+ own = self._enclosing_class_method(file_path, call, caller_id)+ if self._is_anonymous_id(own):+ return True, _own_member_call(caller_id, own, call)callee_id = self._file_symbols.get(file_path, {}).get(call.target_name)if callee_id is None:return False, None- 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.@@ -1499,6 +1492,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):return True, ResolvedCall(caller_id, callee_id, 0.95, call.line, "same_file")return False, None+ def _is_anonymous_id(self, sym_id: str | None) -> bool:+ """Does *sym_id* name an anonymous class member?"""+ return sym_id is not None and is_anonymous_member(self._symbols_by_id[sym_id])+def _bound_import_call(self,call: CallSite,@@ -2168,6 +2165,44 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):return names+def _index_bare_name(+ sym: Symbol, index_id: str, file_syms: dict[str, str], top_level: dict[str, str]+) -> None:+ """Index *sym* under its bare name in one file's flat and top-level tables."""+ if sym.is_declaration:+ # A declaration must never displace a definition already+ # indexed under this name — a .cpp that forward-declares a+ # helper above its own body holds both.+ #+ # A method declaration stays out: this index answers+ # unqualified lookups from importing files, and no bare name+ # can legally reach a method. The (class, method) index+ # still takes it.+ if sym.parent_name is None:+ file_syms.setdefault(sym.name, index_id)+ top_level.setdefault(sym.name, index_id)+ return+ if sym.kind in _EXTENSION_KINDS:+ return+ # Top-level symbols and methods. An anonymous class member stays out: only+ # its own class body names it bare, through the (class, method) index. It+ # is never top-level, so ``top_level`` needs no such check.+ if not is_anonymous_member(sym):+ file_syms[sym.name] = index_id+ if sym.parent_name is None:+ top_level[sym.name] = index_id+++def _own_member_call(caller_id: str, own: str, call: CallSite) -> ResolvedCall | None:+ """An anonymous class body's call to its own member *own*, before any flat name.++ A same-file top-level function of the name included. Recursion: no edge.+ """+ if own == caller_id:+ return None+ return ResolvedCall(caller_id, own, 0.95, call.line, "same_file")++def _rivals_a_class_method(symbol_id: str) -> bool:"""Another class's ordinary method — the one shape that proves last-wins.@@ -2221,8 +2256,12 @@ def _extract_class_id(symbol_id: str) -> str | None:def _extract_class_from_symbol_id(symbol_id: str) -> str | None:- """Extract parent class name from a symbol ID like 'path::ClassName::method'."""+ """The parent from a symbol ID like 'path::ClassName::method'.++ Every segment between path and name, the key ``_file_methods`` uses: an+ anonymous class or enum-constant body spans several (``Op::PLUS``).+ """parts = symbol_id.split("::")if len(parts) >= 3:- return parts[-2]+ return "::".join(parts[1:-1])return Nonediff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.py b/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.pynew file mode 100644index 000000000..cdb64e5f5--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.py@@ -0,0 +1,172 @@+"""Id segments for members of anonymous classes.++Java ``new Foo() { void m() {} }`` and Kotlin ``object : Foo { fun m() {} }``+declare a class with no name. Its members are named by the declarations that+hold it and its supertype, ``Gson::FILTER::ReflectionAccessFilter::check`` for+a field initializer and ``Gson::make::Comparator::compare`` inside a method, so+an edit elsewhere in the file never renames them. Two same-typed anonymous+classes held by one declaration are told apart by a source-order ordinal on the+second and later ones, ``Comparator$2``, javac's own convention.+"""++from __future__ import annotations++from tree_sitter import Node++from ..extractors import node_text+from ..language_configs import LANGUAGE_CONFIGS+from ..models import Symbol+from ..symbol_identity import split_symbol_id, symbol_id_path+from ..type_names import bare_type_name++# Declarations that name an anonymous class they hold: a field, local or+# property, a method or function, a constructor, an enum constant.+_HOLDER_TYPES = frozenset(+ {+ "variable_declarator",+ "method_declaration",+ "constructor_declaration",+ "property_declaration",+ "function_declaration",+ "enum_constant",+ }+)++# Holders a block can declare twice: ``{ Runnable r = .. } { Runnable r = .. }``.+_VARIABLE_HOLDERS = frozenset({"variable_declarator", "property_declaration"})++# Where an ordinal is counted: the nearest method, function, constructor or+# enum constant, else the class body (field initializers, ``static {}``).+_ORDINAL_SCOPES = (_HOLDER_TYPES - _VARIABLE_HOLDERS) | {"class_body"}+++def in_anonymous_class(def_node: Node, anonymous_types: frozenset[str]) -> bool:+ """Is *def_node* a member of an anonymous class body?"""+ body = def_node.parent+ return (+ body is not None+ and body.type == "class_body"+ and body.parent is not None+ and body.parent.type in anonymous_types+ )+++def is_anonymous_member(symbol: Symbol) -> bool:+ """Is *symbol* named under an anonymous class? No bare name reaches one.++ In a language with anonymous classes only such a member has a parent of+ several segments (``Gson::FILTER::Filter``).+ """+ config = LANGUAGE_CONFIGS.get(symbol.language)+ return bool(+ config and config.anonymous_class_types and "::" in (symbol.parent_name or "")+ )+++def follow_renamed_hosts(symbols: list[Symbol]) -> None:+ """Move anonymous members under a host whose id gained an overload discriminator.++ A holder segment spells its method's bare name (``A::over::Runnable``), so+ once ``over`` reads ``over#1(int)`` its members follow it and two+ overloads' anonymous classes keep two ids. A host that is itself an+ anonymous member is not followed: a ceiling of one level.+ """+ members = [s for s in symbols if is_anonymous_member(s)]+ for host in symbols:+ base, payload = split_symbol_id(host.id)+ if payload is not None and host.kind in ("function", "method"):+ _move_members(host, base, members)+++def _move_members(host: Symbol, base: str, members: list[Symbol]) -> None:+ """Re-home the *members* declared in *host* from its *base* id to its own."""+ path = symbol_id_path(host.id)+ old, new = base[len(path) + 2 :] + "::", host.id[len(path) + 2 :] + "::"+ for member in members:+ parent = member.parent_name or ""+ if parent.startswith(old) and host.start_line <= member.start_line <= host.end_line:+ member.parent_name = new + parent[len(old) :]+ member.id = f"{path}::{member.parent_name}::{member.name}"+++def scope_segment(+ node: Node,+ child: Node,+ in_anonymous: bool,+ anonymous_types: frozenset[str],+ src: str,+) -> str | None:+ """The id segment *node* adds for a member below it, reached through *child*.++ An anonymous class names its supertype and, once inside one, each holder+ its own name.+ """+ if node.type in anonymous_types and child.type == "class_body":+ return _anonymous_class_segment(node, src)+ if in_anonymous and node.type in _HOLDER_TYPES:+ return _holder_name(node, src)+ return None+++def _holder_name(node: Node, src: str) -> str | None:+ name = node.child_by_field_name("name")+ if name is None and node.type == "property_declaration":+ # Kotlin ``val x = object : ..``: the name sits in a variable_declaration.+ declaration = next((c for c in node.children if c.type == "variable_declaration"), None)+ name = declaration.named_children[0] if declaration and declaration.named_children else None+ return node_text(name, src) or None+++def _supertype_name(node: Node, src: str) -> str:+ """``new Map.Entry<K, V>() {..}`` -> ``Entry``; Kotlin's first supertype, or ``object``."""+ type_node = node.child_by_field_name("type")+ if type_node is None:+ specifiers = next((c for c in node.children if c.type == "delegation_specifiers"), None)+ if specifiers is not None and specifiers.named_children:+ first = specifiers.named_children[0]+ type_node = next((n for n in _descendants(first) if n.type == "user_type"), first)+ return bare_type_name(node_text(type_node, src)) or "object"+++def _anonymous_class_segment(node: Node, src: str) -> str:+ """The supertype, with an ordinal on the second and later same-keyed class."""+ scope, key = _ordinal_scope(node), _ordinal_key(node, src)+ ordinal = 1+ for other in _descendants(scope):+ if other.start_byte >= node.start_byte:+ break+ if _is_anonymous_class(other, node.type) and _ordinal_scope(other) == scope:+ ordinal += _ordinal_key(other, src) == key+ return key[0] if ordinal == 1 else f"{key[0]}${ordinal}"+++def _is_anonymous_class(node: Node, anonymous_type: str) -> bool:+ return node.type == anonymous_type and any(c.type == "class_body" for c in node.children)+++def _ordinal_key(node: Node, src: str) -> tuple[str, str | None]:+ """The supertype and the nearest variable holding *node* within its scope."""+ ancestor = node.parent+ while ancestor is not None and ancestor.type not in _ORDINAL_SCOPES:+ if ancestor.type in _VARIABLE_HOLDERS:+ return _supertype_name(node, src), _holder_name(ancestor, src)+ ancestor = ancestor.parent+ return _supertype_name(node, src), None+++def _ordinal_scope(node: Node) -> Node:+ ancestor = node.parent+ while ancestor is not None and ancestor.parent is not None:+ if ancestor.type in _ORDINAL_SCOPES:+ return ancestor+ ancestor = ancestor.parent+ return ancestor if ancestor is not None else node+++def _descendants(node: Node):+ """*node* and its descendants in source order."""+ stack = [node]+ while stack:+ current = stack.pop()+ yield current+ stack.extend(reversed(current.children))diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex 9de1ba38b..cc22c18de 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -71,6 +71,10 @@ class LanguageConfig:# Node types that indicate a class context (used with "nesting" mode)parent_class_types: frozenset[str] = field(default_factory=frozenset)+ # Anonymous class expressions (Java ``new Foo() {..}``, Kotlin ``object : Foo {..}``)+ # whose members are symbols named under the declaration holding them.+ anonymous_class_types: frozenset[str] = field(default_factory=frozenset)+# Node types whose symbols are bodiless declarations. C/C++ headers declare# what a .cpp defines, so both sides land as same-named symbols; this is# what tells them apart downstream (see ``Symbol.is_declaration``).@@ -223,6 +227,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {parent_class_types=frozenset({"class_declaration", "interface_declaration", "enum_declaration", "record_declaration"}),+ anonymous_class_types=frozenset({"object_creation_expression"}),),"cpp": LanguageConfig(symbol_node_types={@@ -279,6 +284,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {modifier_node_types=frozenset({"modifiers"}),parent_extraction="nesting",parent_class_types=frozenset({"class_declaration", "object_declaration"}),+ anonymous_class_types=frozenset({"object_literal"}),),"ruby": LanguageConfig(symbol_node_types={diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 59b5d8027..a64ae6b87 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -122,7 +122,11 @@ from .parser_helpers import (_run_query,_rust_shadowed_by_type_param,_ts_nested_object_method_owner,+ follow_renamed_hosts,import_load_kind,+ in_anonymous_class,+ is_anonymous_member,+ scope_segment,)from .python_local_refs import local_refs_from_tree, parse_python_modulefrom .python_overload import is_python_overload as _is_python_overload@@ -1402,10 +1406,41 @@ def _parent_type_name(ancestor: Node, src: str) -> str | None:return _node_text(name_node, src)+def _nesting_parent(def_node: Node, config: LanguageConfig, src: str) -> str | None:+ """The class/impl ancestor naming *def_node*'s parent.++ An anonymous class is a class of its own, so its members gain segments+ below it: ``Gson::FILTER::Filter::check``.+ """+ segments: list[str] = []+ child, ancestor = def_node, def_node.parent+ while ancestor is not None:+ if ancestor.type in config.parent_class_types:+ name = _parent_type_name(ancestor, src)+ if name is not None:+ return "::".join([name, *reversed(segments)])+ else:+ segment = scope_segment(+ ancestor, child, bool(segments), config.anonymous_class_types, src+ )+ if segment is not None:+ segments.append(segment)+ child, ancestor = ancestor, ancestor.parent+ # A Kotlin top-level function's object expression: ``f::Foo``.+ return "::".join(reversed(segments)) or None++def _java_enum_constant(def_node: Node, config: LanguageConfig, src: str) -> str | None:- """The enum constant whose body declares *def_node*, before any enclosing type."""+ """The enum constant whose body declares *def_node*, before any enclosing type.++ An anonymous class is such a type: ``_find_parent`` names its members.+ """ancestor = def_node.parent- while ancestor is not None and ancestor.type not in config.parent_class_types:+ while (+ ancestor is not None+ and ancestor.type not in config.parent_class_types+ and ancestor.type not in config.anonymous_class_types+ ):if ancestor.type == "enum_constant":name = ancestor.child_by_field_name("name")return _node_text(name, src) if name else None@@ -1545,8 +1580,12 @@ class ASTParser:existing = {(s.id, symbol_discriminator(s)) for s in symbols}symbols.extend(s for s in synthetic if (s.id, symbol_discriminator(s)) not in existing)# Before calls and references are extracted, so both attribute to the- # final ids.- disambiguate_colliding_ids(symbols, lang)+ # final ids. Anonymous members go last, once the overloads holding them+ # carry their discriminators.+ anonymous = [s for s in symbols if is_anonymous_member(s)]+ disambiguate_colliding_ids([s for s in symbols if not is_anonymous_member(s)], lang)+ follow_renamed_hosts(symbols)+ disambiguate_colliding_ids(anonymous, lang)imports = self._extract_imports(matches, config, file_info, src)calls = self._extract_calls(matches, config, file_info, src, symbols)# An SFC instantiates a component by writing its tag in the markup@@ -1722,7 +1761,10 @@ class ASTParser:language,src,cpp_exports.container_ids,- keep_nested=object_owner is not None,+ # An anonymous class member is a method of its own class, even+ # inside another method's body; ``_find_parent`` names it.+ keep_nested=object_owner is not None+ or in_anonymous_class(def_node, config.anonymous_class_types),)if kind is None:return None@@ -1903,15 +1945,7 @@ class ASTParser:return Noneif config.parent_extraction in ("nesting", "impl"):- # Walk up the AST to find a class/impl ancestor- ancestor = def_node.parent- while ancestor is not None:- if ancestor.type in config.parent_class_types:- name = _parent_type_name(ancestor, src)- if name is not None:- return name- ancestor = ancestor.parent- return None+ return _nesting_parent(def_node, config, src)return None # "none" modediff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex 617ae8001..75bb65041 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -14,6 +14,12 @@ from tree_sitter import Nodefrom .extractors import node_textfrom .extractors.bindings.ts_js import is_type_only_ts_js_import+from .lang_helpers.anonymous_classes import (+ follow_renamed_hosts,+ in_anonymous_class,+ is_anonymous_member,+ scope_segment,+)from .lang_helpers.elixir import (_elixir_call_is_definitional,_elixir_is_template_definition,@@ -82,9 +88,13 @@ __all__ = ["_rust_head_type_identifier","_rust_shadowed_by_type_param","_ts_nested_object_method_owner",+ "follow_renamed_hosts","import_load_kind",+ "in_anonymous_class",+ "is_anonymous_member","prepare_objectivec_source","prepare_pascal_source",+ "scope_segment",]diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.pyindex fc89aae00..598ad4319 100644--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py@@ -85,6 +85,16 @@ def id_segment_name(segment: str) -> str:return _GENERIC_ARITY.sub("", segment)+def symbol_id_path(symbol_id: str) -> str:+ """The file path an id starts with: ``A.java::A::m`` -> ``A.java``."""+ return symbol_id.partition("::")[0]+++def outer_scope(scope: str) -> str:+ """One id segment up: ``A::m::Runnable`` -> ``A::m``, and ``A`` -> ``""``."""+ return scope.rpartition("::")[0]++def overload_sets(symbol_ids: Iterable[str]) -> dict[str, list[str]]:"""``{base id: member ids}`` for every id that carries a discriminator."""sets: dict[str, list[str]] = defaultdict(list)@@ -287,11 +297,13 @@ __all__ = ["disambiguate_colliding_ids","has_overload_identity","id_segment_name",+ "outer_scope","overload_sets","pair_overloads","split_symbol_id","symbol_discriminator","symbol_id_arity","symbol_id_discriminator",+ "symbol_id_path","untyped_symbol_id",]diff --git a/tests/unit/ingestion/test_anonymous_class_methods.py b/tests/unit/ingestion/test_anonymous_class_methods.pynew file mode 100644index 000000000..21057895c--- /dev/null+++ b/tests/unit/ingestion/test_anonymous_class_methods.py@@ -0,0 +1,404 @@+"""Java anonymous-class and Kotlin object-expression methods, end to end.++Each member is a symbol named by the declarations holding its class and the+class's supertype (``Gson::FILTER::Filter::check``), so two anonymous classes+overriding one method keep two nodes, and the calls inside them resolve with+the method as caller. Dead code never flags them.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.lang_helpers.anonymous_classes import is_anonymous_member++_FILES = {+ "src/app/Filter.java": """\+package app;++public interface Filter {+ boolean check(Class<?> c);+}+""",+ "src/app/Gson.java": """\+package app;++import java.util.Comparator;++public class Gson {+ static final Filter FILTER = new Filter() {+ public boolean check(Class<?> c) {+ return helper();+ }++ boolean helper() {+ return true;+ }+ };++ static final Filter OTHER = new Filter() {+ public boolean check(Class<?> c) {+ return go();+ }+ };++ boolean go() {+ return true;+ }++ boolean helper() {+ return false;+ }++ Object make() {+ run(new Runnable() {+ public void run() {+ go();+ }+ });+ run(new Runnable() {+ public void run() {+ helper();+ }+ });+ Comparator<String> byLength = new java.util.Comparator<String>() {+ public int compare(String a, String b) {+ return a.length() - b.length();+ }+ };+ return byLength;+ }++ void run(Runnable r) {+ r.run();+ }++ enum Op {+ PLUS {+ int apply() {+ return new Object() {+ int one() {+ return 1;+ }+ }.one();+ }+ };++ abstract int apply();+ }+}+""",+ "src/app/Alloc.java": """\+package app;++public abstract class Alloc {+ public abstract Object make();++ static Alloc create() {+ Store store = new Store();+ return new Alloc() {+ public Object make() {+ store.save();+ tidy();+ return null;+ }++ private void tidy() {}+ };+ }+}+""",+ "src/app/Store.java": """\+package app;++public class Store {+ void save() {}+}++class Disk {+ void save() {}+}+""",+ "src/app/User.java": """\+package app;++class User {+ static final Alloc INSTANCE = Alloc.create();++ Object use() {+ return User.INSTANCE.make();+ }+}+""",+ "src/app/Deck.kt": """\+package app++class Tape {+ fun play() {}+}++class Reel {+ fun play() {}+}++class Deck {+ fun watch(): Runnable {+ val tape = Tape()+ return object : Runnable {+ override fun run() {+ tape.play()+ }++ fun spin() {+ listOf(Reel()).forEach { tape -> tape.play() }+ }+ }+ }+}+""",+ "src/app/Shapes.java": """\+package app;++class Over {+ void over(int a) {+ new Runnable() {+ public void run() {+ ping();+ }+ }.run();+ }++ void over(String a) {+ new Runnable() {+ public void run() {}+ }.run();+ }++ void ping() {}+}++class Blocks {+ static { Runnable r = new Runnable() { public void run() {} }; }+ static { Runnable r = new Runnable() { public void run() {} }; }++ void m() {+ { Runnable q = new Runnable() { public void run() {} }; }+ { Runnable q = new Runnable() { public void run() {} }; }+ }+}++class Leak {+ void make2() {+ Runnable s = new Runnable() {+ public void run() {+ Bar y = null;+ }+ };+ Runnable u = new Runnable() {+ public void run() {+ y.miss();+ }+ };+ }+}++class Twice {+ Runnable outer(Bar b) {+ return new Runnable() {+ public void run() {+ new Runnable() {+ public void run() {+ b.miss();+ }+ }.run();+ }+ };+ }+}++class Bar {+ void miss() {}+}++class Baz {+ void miss() {}+}+""",+ "src/app/Clock.kt": """\+package app++fun tick() {}++class Clock {+ fun start() {+ val r = object : Runnable {+ override fun run() {+ tick()+ }++ fun tick() {}+ }+ }++ class Leaf {+ fun leaf() {}+ }+}+""",+ "src/app/Screen.kt": """\+package app++class Screen {+ val listener = object : Callback<Int>(), Closeable {+ override fun onEvent() {+ refresh()+ }+ }++ fun start() {+ val task = object : Runnable {+ override fun run() {+ refresh()+ }+ }+ post(object {+ fun tick() {}+ })+ }++ fun refresh() {}++ fun post(any: Any) {}+}++fun untilReady(): Condition = object : Condition() {+ override fun apply() = true+}+""",+}+++def _build(tmp_path: Path):+ for rel, text in _FILES.items():+ path = tmp_path / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ builder = GraphBuilder(tmp_path)+ parser = ASTParser()+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(tmp_path).traverse():+ src = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, src))+ source_map[fi.path] = src+ builder.set_source_map(source_map)+ builder.build()+ graph = builder.graph()+ report = DeadCodeAnalyzer(+ graph, {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=tmp_path+ ).analyze({"detect_unused_internals": True})+ calls = {(u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls"}+ return graph, calls, report+++GSON = "src/app/Gson.java::"+SCREEN = "src/app/Screen.kt::"+++def test_each_anonymous_method_is_its_own_node(tmp_path: Path) -> None:+ graph, _, _ = _build(tmp_path)+ lines = {+ "Gson::FILTER::Filter::check": 7,+ "Gson::FILTER::Filter::helper": 11,+ "Gson::OTHER::Filter::check": 17,+ "Gson::make::Runnable::run": 32,+ # A second same-typed class in one declaration takes javac's ordinal.+ "Gson::make::Runnable$2::run": 37,+ "Gson::make::byLength::Comparator::compare": 42,+ "Op::PLUS::apply": 55,+ "Op::PLUS::apply::Object::one": 57,+ }+ for sym, line in lines.items():+ assert graph.nodes[GSON + sym]["start_line"] == line, sym+ assert graph.nodes[GSON + sym]["kind"] == "method"+ assert graph.nodes[SCREEN + "Screen::listener::Callback::onEvent"]["start_line"] == 5+ assert graph.nodes[SCREEN + "Screen::start::task::Runnable::run"]["start_line"] == 12+ assert graph.nodes[SCREEN + "Screen::start::object::tick"]["start_line"] == 17+ # A top-level function's object expression is qualified by the function.+ assert graph.nodes[SCREEN + "untilReady::Condition::apply"]["start_line"] == 27+ assert SCREEN + "apply" not in graph+++def test_calls_resolve_from_the_anonymous_method(tmp_path: Path) -> None:+ _, calls, _ = _build(tmp_path)+ # Its own member first, then the enclosing class's.+ assert (GSON + "Gson::FILTER::Filter::check", GSON + "Gson::FILTER::Filter::helper") in calls+ assert (GSON + "Gson::OTHER::Filter::check", GSON + "Gson::go") in calls+ assert (GSON + "Gson::make::Runnable::run", GSON + "Gson::go") in calls+ assert (GSON + "Gson::make::Runnable$2::run", GSON + "Gson::helper") in calls+ assert (GSON + "Gson::make", GSON + "Gson::go") not in calls+ assert (SCREEN + "Screen::listener::Callback::onEvent", SCREEN + "Screen::refresh") in calls+ assert (SCREEN + "Screen::start::task::Runnable::run", SCREEN + "Screen::refresh") in calls+ assert (SCREEN + "Screen::start", SCREEN + "Screen::refresh") not in calls+++def test_an_anonymous_member_is_named_only_from_its_own_body(tmp_path: Path) -> None:+ _, calls, _ = _build(tmp_path)+ alloc = "src/app/Alloc.java::Alloc::"+ # A local of the method around the class types its receiver.+ assert (alloc + "create::Alloc::make", "src/app/Store.java::Store::save") in calls+ assert (alloc + "create::Alloc::make", alloc + "create::Alloc::tidy") in calls+ # A bare name from another file never reaches the anonymous override.+ assert ("src/app/User.java::User::use", alloc + "create::Alloc::make") not in calls+++def test_a_name_the_anonymous_body_binds_is_not_the_captured_one(tmp_path: Path) -> None:+ _, calls, _ = _build(tmp_path)+ deck = "src/app/Deck.kt::Deck::watch::Runnable::"+ assert (deck + "run", "src/app/Deck.kt::Tape::play") in calls+ # The lambda's own ``tape`` shadows the captured local.+ assert (deck + "spin", "src/app/Deck.kt::Tape::play") not in calls+++def test_overloads_and_sibling_blocks_keep_their_anonymous_classes_apart(tmp_path: Path) -> None:+ graph, calls, _ = _build(tmp_path)+ shapes = "src/app/Shapes.java::"+ # The host's overload discriminator is carried into the holder segment.+ for host in ("Over::over#1(int)", "Over::over#1(String)"):+ assert graph.nodes[shapes + host + "::Runnable::run"]["kind"] == "method"+ assert (shapes + "Over::over#1(int)::Runnable::run", shapes + "Over::ping") in calls+ # One name held twice in one scope, in sibling blocks or static blocks.+ for holder in ("Blocks::r", "Blocks::m::q"):+ assert shapes + holder + "::Runnable::run" in graph+ assert shapes + holder + "::Runnable$2::run" in graph+++def test_a_sibling_anonymous_body_does_not_type_a_capture(tmp_path: Path) -> None:+ _, calls, _ = _build(tmp_path)+ shapes = "src/app/Shapes.java::"+ assert (shapes + "Leak::make2::u::Runnable::run", shapes + "Bar::miss") not in calls+ # A capture two anonymous classes deep is typed by the outermost function.+ inner = shapes + "Twice::outer::Runnable::run::Runnable::run"+ assert (inner, shapes + "Bar::miss") in calls+++def test_an_anonymous_member_outranks_a_top_level_function(tmp_path: Path) -> None:+ _, calls, _ = _build(tmp_path)+ clock = "src/app/Clock.kt::"+ run = clock + "Clock::start::r::Runnable::run"+ assert (run, clock + "Clock::start::r::Runnable::tick") in calls+ assert (run, clock + "tick") not in calls+ # A named nested class keeps its bare parent, so it is no anonymous member.+ parsed = {+ fi.path: ASTParser().parse_file(fi, Path(fi.abs_path).read_bytes())+ for fi in FileTraverser(tmp_path).traverse()+ }+ leaf = next(s for s in parsed["src/app/Clock.kt"].symbols if s.name == "leaf")+ assert leaf.parent_name == "Leaf" and not is_anonymous_member(leaf)+++def test_dead_code_never_flags_the_new_methods(tmp_path: Path) -> None:+ _, _, report = _build(tmp_path)+ flagged = {f.symbol_name for f in report.findings if f.symbol_name}+ assert not flagged & {"check", "helper", "run", "compare", "one", "onEvent", "tick"}