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): choose Java overloads by the declared types of named arguments (#3704)

Swati Ahuja3d53ff21a5b3
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
index e03cad8c0..b83cc4c47 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -67,7 +67,11 @@ _SOURCE_CACHE_FILES = 4
# Any Java type spelling before a declared name, for ``_declares_name``; the
# words that may precede a bare name without declaring it.
-_JAVA_ANY_TYPE = r"[\w$]+(?:\.[\w$]+)*(?:<[^;{}()]*>)?(?:\[\])*"
+_JAVA_ANY_TYPE = r"[\w$]+(?:\.[\w$]+)*(?:<[^;{}()]*>)?(?:\[\])*(?:\.\.\.)?"
+# Every name a Java owner declares with any type.
+_JAVA_ANY_DECLARATION = re.compile(
+ rf"(?<![\w.@$])(?P<type>{_JAVA_ANY_TYPE})\s+(?P<name>[\w$]+)\s*(?=[=;,):])"
+)
_NOT_A_TYPE = frozenset({"return", "throw", "new", "else", "case", "yield", "assert"})
# Where a Java declaration header opens its type-parameter list: after a type's
@@ -197,6 +201,7 @@ class ReceiverTypingMixin:
self._bindings: dict[str, tuple[tuple[int, str], ...]] = {}
self._binding_positions: dict[str, tuple[tuple[int, int, str], ...]] = {}
self._bound_names: dict[tuple[str, str], frozenset[str]] = {}
+ self._declared_names: dict[tuple[str, str], frozenset[str]] = {}
self._scope_chain_cache: dict[str, dict[str, tuple[_Scope, ...]]] = {}
# {file: {name: type}} — module-level defs a framework decorator retyped.
self._framework_types: dict[str, dict[str, str]] = {}
@@ -694,13 +699,21 @@ class ReceiverTypingMixin:
return None
def _declares_name(self, file_path: str, owner_id: str, name: str) -> bool:
- """Does *owner_id*, a method or a class's own scope, declare *name* with any type?
+ """Does *owner_id*, a method or a class's own scope, declare *name* with any type?"""
+ return name in self._names_declared_by(file_path, owner_id)
+
+ def _names_declared_by(self, file_path: str, owner_id: str) -> frozenset[str]:
+ """Every name *owner_id* declares with any type.
- A scan for the one name, run only where an inherited field would
- answer: admitting every type spelling to the declaration scan slows
- it by about two thirds. Ceiling: a later declarator (``int a, x;``) is
- missed.
+ One scan per owner, asked only where an inherited field or a named
+ argument would answer: admitting every type spelling to the
+ declaration scan slows it by about two thirds. Ceiling: a later
+ declarator (``int a, x;``) is missed.
"""
+ key = (file_path, owner_id)
+ found = self._declared_names.get(key)
+ if found is not None:
+ return found
spans = self._spans_for(file_path)
start, end = spans.get(owner_id, (1, 0))
owner = self._symbols_by_id.get(owner_id)
@@ -711,14 +724,19 @@ class ReceiverTypingMixin:
and owner.kind not in _FUNCTION_KINDS
and getattr(self._symbols_by_id.get(sym_id), "kind", None) in _FUNCTION_KINDS
)
- declared = re.compile(rf"(?<![\w.@$])(?P<type>{_JAVA_ANY_TYPE})\s+{re.escape(name)}\s*[=;,):]")
lines = self._text_of(file_path).splitlines()
- return any(
- match.group("type") not in _NOT_A_TYPE
- for number in range(start, min(end, len(lines)) + 1)
- if not in_spans(bodies, number)
- for match in declared.finditer(lines[number - 1])
- )
+ names: set[str] = set()
+ for number in range(start, min(end, len(lines)) + 1):
+ if in_spans(bodies, number):
+ continue
+ names.update(
+ match.group("name")
+ for match in _JAVA_ANY_DECLARATION.finditer(lines[number - 1])
+ if match.group("type") not in _NOT_A_TYPE
+ )
+ found = frozenset(names)
+ _store_capped(self._declared_names, key, found, _BODY_TYPE_CACHE_ENTRIES)
+ return found
def _module_receiver_type(
self,
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 5fd6e6a51..6da3172b3 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -49,7 +49,7 @@ from .language_data import (
get_external_receiver_types,
get_external_return_types,
)
-from .languages.receiver_types import holds_function
+from .languages.receiver_types import external_type_name, holds_function
from .models import (
CallReceiver,
CallSite,
@@ -69,6 +69,7 @@ from .return_types import (
)
from .symbol_identity import (
erased_parameter_types,
+ erased_type,
id_segment_name,
outer_scope,
pair_overloads,
@@ -214,9 +215,11 @@ def _overload_phase(admitted: tuple[int, int | None], argument_count: int) -> in
_ArgumentTypes = tuple[str | None, ...] | None
-# The Java primitives a literal of each type widens to, nearest first.
+# The Java primitives a value of each type widens to, nearest first.
_JAVA_WIDENING: dict[str, tuple[str, ...]] = {
"boolean": ("boolean",),
+ "byte": ("byte", "short", "int", "long", "float", "double"),
+ "short": ("short", "int", "long", "float", "double"),
"char": ("char", "int", "long", "float", "double"),
"int": ("int", "long", "float", "double"),
"long": ("long", "float", "double"),
@@ -224,15 +227,18 @@ _JAVA_WIDENING: dict[str, tuple[str, ...]] = {
"double": ("double",),
}
_JAVA_BOXES = {
- "boolean": "Boolean", "char": "Character", "int": "Integer",
- "long": "Long", "float": "Float", "double": "Double",
+ "boolean": "Boolean", "byte": "Byte", "short": "Short", "char": "Character",
+ "int": "Integer", "long": "Long", "float": "Float", "double": "Double",
}
-_JAVA_PRIMITIVES = frozenset({"byte", "short", *_JAVA_WIDENING})
+_JAVA_UNBOXED = {box: primitive for primitive, box in _JAVA_BOXES.items()}
+_JAVA_PRIMITIVES = frozenset(_JAVA_WIDENING)
# Parameter types a literal is judged against; any other (``Object``, a type
# variable, a class) takes a literal by boxing, or as a ``String``'s supertype.
_JAVA_JUDGED_PARAMETERS = _JAVA_PRIMITIVES | frozenset(
- {*_JAVA_BOXES.values(), "Byte", "Short", "String", "CharSequence"}
+ {*_JAVA_BOXES.values(), "String", "CharSequence"}
)
+# Final classes: a parameter of one takes no other class.
+_JAVA_FINAL_PARAMETERS = frozenset({*_JAVA_BOXES.values(), "String"})
# {literal: {judged parameter: how it is reached}}: 0 exactly, 1 widened, 2 boxed.
_JAVA_LITERAL_LEVELS: dict[str, dict[str, int]] = {
**{
@@ -245,34 +251,82 @@ _JAVA_LITERAL_LEVELS: dict[str, dict[str, int]] = {
_UNJUDGED_LEVEL = {**dict.fromkeys(_JAVA_WIDENING, 2), "String": 1, "null": 1}
-def _literal_fit(parameter: str, literal: str) -> int | None:
- """How a Java literal reaches *parameter*: 0 exactly, 1 widened, 2 boxed; None never.
+def _argument_fit(parameter: str, argument: str) -> int | None:
+ """How near a Java argument reaches *parameter*: 0 exactly, 1 widened, 2 boxed; None never.
- A coarse form of the most-specific rule: a call ``f(true)`` takes
- ``f(boolean)`` over ``f(Object)``, and ``f('c')`` takes ``f(int)`` over it.
+ *argument* is a literal's type or a named argument's declared one; a
+ named ``String`` or primitive takes the literal path. A coarse form of the
+ most-specific rule: a call ``f(true)`` takes ``f(boolean)`` over
+ ``f(Object)``, and ``f('c')`` takes ``f(int)`` over it.
"""
+ levels = _JAVA_LITERAL_LEVELS.get(argument)
+ if levels is None:
+ return _reference_fit(parameter, argument)
+ if parameter.endswith("[]"):
+ return 1 if argument == "null" else None
if parameter not in _JAVA_JUDGED_PARAMETERS:
- return _UNJUDGED_LEVEL[literal]
- return _JAVA_LITERAL_LEVELS[literal].get(parameter)
+ return _UNJUDGED_LEVEL[argument]
+ return levels.get(parameter)
-def _closest_literal_fit(
+def _reference_fit(parameter: str, argument: str) -> int | None:
+ """How a value of class or array type *argument* reaches *parameter*.
+
+ 0 as itself; 2 unboxed, 3 unboxed and widened; None where it never can
+ (a primitive, another final class, an array it is not). An array reaches
+ a covariant array at 1 and anything else (``Object``) at 2. Any other
+ parameter may be a supertype or a type variable: 1, which an exact
+ match beats and nothing else tells apart.
+ """
+ if parameter == argument:
+ return 0
+ if parameter in _JAVA_PRIMITIVES:
+ return _unboxed_fit(parameter, argument)
+ if argument.endswith("[]"):
+ return _array_fit(parameter, argument)
+ if parameter in _JAVA_FINAL_PARAMETERS or parameter.endswith("[]"):
+ return None
+ return 1
+
+
+def _unboxed_fit(parameter: str, argument: str) -> int | None:
+ """A box reaching primitive *parameter*: 2 unboxed, 3 unboxed and widened; None never."""
+ unboxed = _JAVA_UNBOXED.get(argument)
+ if unboxed is None or parameter not in _JAVA_WIDENING[unboxed]:
+ return None
+ return 2 if parameter == unboxed else 3
+
+
+def _array_fit(parameter: str, argument: str) -> int | None:
+ """``String[]`` reaches ``Object[]`` (1, covariance) and ``Object`` (2).
+
+ A primitive array reaches no other array, and no array a final class.
+ """
+ if not parameter.endswith("[]"):
+ return None if parameter in _JAVA_FINAL_PARAMETERS else 2
+ element, takes = argument.removesuffix("[]"), parameter.removesuffix("[]")
+ if element in _JAVA_PRIMITIVES or takes in _JAVA_PRIMITIVES:
+ return None
+ return None if _argument_fit(takes, element) is None else 1
+
+
+def _closest_fit(
members: list[tuple[str, list[str]]], argument_types: tuple[str | None, ...], expanded: bool
) -> str | None:
- """The one member the literal arguments fit most closely, or None on a tie.
+ """The one member the typed arguments fit most closely, or None on a tie.
- Only where the members agree on every non-literal argument's parameter:
- there the literals are all that tells them apart. *expanded* says the
+ Only where the members agree on every untyped argument's parameter:
+ there the typed ones are all that tells them apart. *expanded* says the
members take the call through their varargs.
"""
- if not _non_literals_agree(members, argument_types, expanded):
+ if not _untyped_agree(members, argument_types, expanded):
return None
ranked: dict[int, list[str]] = defaultdict(list)
for member, parameters in members:
fits = [
- _literal_fit(_parameter_at(parameters, index, expanded) or "", literal)
- for index, literal in enumerate(argument_types)
- if literal is not None
+ _argument_fit(_parameter_taking(parameters, argument_types, index, expanded), argument)
+ for index, argument in enumerate(argument_types)
+ if argument is not None
]
if all(fit is not None for fit in fits):
ranked[max(fits, default=0)].append(member)
@@ -280,17 +334,32 @@ def _closest_literal_fit(
return best[0] if len(best) == 1 else None
-def _non_literals_agree(
+def _untyped_agree(
members: list[tuple[str, list[str]]], argument_types: tuple[str | None, ...], expanded: bool
) -> bool:
- """Whether every member takes each non-literal argument as the same parameter type."""
+ """Whether every member takes each untyped argument as the same parameter type."""
return all(
len({_parameter_at(parameters, index, expanded) for _, parameters in members}) == 1
- for index, literal in enumerate(argument_types)
- if literal is None
+ for index, argument in enumerate(argument_types)
+ if argument is None
)
+def _parameter_taking(
+ parameters: list[str], argument_types: tuple[str | None, ...], index: int, expanded: bool
+) -> str:
+ """The parameter type typed argument *index* is judged against.
+
+ An array that alone fills the varargs position is passed as the array
+ itself (``addChildren(index, children)``), not expanded into it.
+ """
+ argument = argument_types[index] or ""
+ alone = index == len(parameters) - 1 == len(argument_types) - 1
+ if expanded and alone and argument.endswith("[]"):
+ return parameters[-1]
+ return _parameter_at(parameters, index, expanded) or ""
+
+
def _parameter_at(parameters: list[str], index: int, expanded: bool) -> str | None:
"""The parameter type that takes argument *index*.
@@ -525,6 +594,8 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
self._build_indices(parsed_files)
self._follow_barrel_exports()
+ # Only a call to one of these has its named arguments typed.
+ self._overloaded_names = frozenset(self._symbols_by_id[m].name for m in self._overload_rep)
def _follow_barrel_exports(self) -> None:
"""Detect barrel/re-export files and record origin mappings.
@@ -1034,6 +1105,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if not call.caller_symbol_id:
# Module-level call — assign to synthetic __module__ symbol
call = replace(call, caller_symbol_id=f"{file_path}::__module__")
+ call = self._typed_arguments(file_path, call)
resolved = self._overload_sibling_call(call) or self._resolve_one(file_path, call)
if resolved:
@@ -1158,7 +1230,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
) -> list[str]:
"""The members of the first phase with any candidate for *argument_count*.
- A tie there is broken by *argument_types* when the literal arguments
+ A tie there is broken by *argument_types* when the typed arguments
fit exactly one member's parameters (``value(true)`` over ``value(String)``).
"""
if argument_count is None or rep in self._unranged_overload_sets:
@@ -1170,18 +1242,57 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
phases[phase].append(member)
phase = min(phases, default=None)
found = phases[phase] if phases else []
- return self._literal_tie_break(found, argument_types, expanded=phase == 2)
+ return self._typed_tie_break(found, argument_types, expanded=phase == 2)
- def _literal_tie_break(
+ def _typed_tie_break(
self, found: list[str], argument_types: _ArgumentTypes, *, expanded: bool
) -> list[str]:
- """*found* narrowed to the one member its literal arguments fit closest, if one does."""
+ """*found* narrowed to the one member its typed arguments fit closest, if one does."""
if len(found) < 2 or not argument_types:
return found
typed = [(m, erased_parameter_types(self._symbols_by_id[m])) for m in found]
- closest = _closest_literal_fit(typed, argument_types, expanded)
+ closest = _closest_fit(typed, argument_types, expanded)
return found if closest is None else [closest]
+ def _typed_arguments(self, file_path: str, call: CallSite) -> CallSite:
+ """*call* with each named argument's declared type beside its literals' types.
+
+ So ``f(start, n)`` is judged as ``f(1L, 2)`` is. Asked only of a call
+ to a name an overload set carries.
+ """
+ names = call.argument_names
+ if not names or call.target_name not in self._overloaded_names:
+ return call
+ caller_id = call.caller_symbol_id or ""
+ literals = call.argument_types or (None,) * len(names)
+ types = tuple(
+ literal or (self._argument_type(file_path, caller_id, name) if name else None)
+ for literal, name in zip(literals, names, strict=True)
+ )
+ return replace(call, argument_types=types if any(types) else None)
+
+ def _argument_type(self, file_path: str, caller_id: str, name: str) -> str | None:
+ """Argument *name*'s declared type, spelled as an overload id spells a parameter.
+
+ Read as a receiver's is, except that a local of a builtin type stands
+ (a receiver yields it to a field) and a field stands only where the
+ body declares *name* with no type the scan reads: a wrong type here
+ picks a wrong member, and nothing later checks it.
+ """
+ language = self._language_of(file_path) or ""
+ _, body_types = self._typing_scope(file_path, caller_id, language, name)
+ if name in body_types:
+ type_name = body_types[name]
+ else:
+ type_name, scope, _ = self._receiver_type_and_scope(
+ file_path, caller_id, language, name
+ )
+ if scope == "field" and self._declares_name(file_path, caller_id, name):
+ return None
+ if type_name is None or "::" in type_name:
+ return None
+ return erased_type(external_type_name(type_name) or type_name)
+
def _overload_sibling_call(self, call: CallSite) -> ResolvedCall | None:
"""An overload calling another member of its own set, ``f(a)`` inside ``f(a, b)``.
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index 947b4ea6b..4a66885cf 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -313,6 +313,21 @@ _RUST_CONSTRUCTED = re.compile(
)
_C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)
+
+# A Java primitive or primitive array, ``long start`` / ``int[] xs``. Kept as an
+# external type: no call is made on one, but an overload is chosen by it.
+_JAVA_PRIMITIVE_DECLARATION = re.compile(
+ r"(?<![\w.])(?P<type>(?:boolean|byte|char|short|int|long|float|double)(?:\[\])*(?:\.\.\.)?)"
+ r"\s+(?P<name>[a-z_]\w*)\s*(?=(?P<closer>[=;,):]))"
+)
+# A varargs parameter, ``Foo... xs``: the array it is.
+_JAVA_VARARGS_DECLARATION = re.compile(
+ rf"(?<![\w.])(?P<type>{_TYPE}\.\.\.)\s+(?P<name>[a-z_]\w*)\s*(?=(?P<closer>[,)]))"
+)
+# A pattern variable, ``x instanceof Foo f && ...``: a local wherever it ends.
+_JAVA_PATTERN_VARIABLE = re.compile(
+ rf"(?<![\w.])instanceof\s+(?:final\s+)?(?P<type>{_TYPE})\s+(?P<name>[a-z_]\w*)\b(?!\s*[.(])"
+)
# Only the field shapes reach class scope. Go is still not in
# IMPLICIT_FIELD_LANGUAGES: a field is read through its receiver (``c.parent``),
# so it types a chain hop and never a bare name.
@@ -328,7 +343,12 @@ _LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
"csharp": _C_FAMILY,
"dart": _DART_FAMILY,
"go": _GO_FAMILY,
- "java": _C_FAMILY,
+ "java": (
+ *_C_FAMILY,
+ _JAVA_PRIMITIVE_DECLARATION,
+ _JAVA_VARARGS_DECLARATION,
+ _JAVA_PATTERN_VARIABLE,
+ ),
"kotlin": _KT_FAMILY,
"python": _PY_FAMILY,
"rust": (_RUST_ANNOTATED, _RUST_CONSTRUCTED),
@@ -918,6 +938,10 @@ def _nests_in_a_builtin(raw: str, language: str) -> bool:
return bool(separator) and head in get_builtin_types(language)
+def _is_java_array(raw: str, language: str) -> bool:
+ return language == "java" and raw.endswith(("]", "..."))
+
+
def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:
"""``(bare name, unwrapped)`` for *raw*, or ``(None, False)``.
@@ -927,7 +951,7 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:
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):
+ if _nests_in_a_builtin(raw, language) or _is_java_array(raw, language):
return None, False
inner = unwrap_pointer_like(raw) if language == "cpp" else None
name = inner or (raw if raw.isidentifier() else bare_type_name(raw))
@@ -1015,6 +1039,11 @@ def _builtin_type_name(raw: str, language: str) -> str | None:
refused rather than left to name matching. A generic parameter (``T``) or
any other unknown name stays dropped: unknown is not external.
"""
+ if _is_java_array(raw, language):
+ # Any array is a builtin, ``Foo[]`` too, so no call on it reaches ``Foo``.
+ dimensions = raw.replace(" ", "").count("[]") + raw.endswith("...")
+ element = strip_type_arguments(raw.removesuffix("...")).strip()
+ return _EXTERNAL_TYPE + element + "[]" * dimensions
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)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 2715ca98a..50cb096af 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -341,6 +341,9 @@ class CallSite:
# Java: each argument's type where it is a literal (``"String"``, ``"int"``,
# ``"null"``), else None; None overall when no argument is one.
argument_types: tuple[str | None, ...] | None = None
+ # Java: each argument that is a bare name (``start``), else None; None overall
+ # when no argument is one. The resolver reads its declared type.
+ argument_names: tuple[str | None, ...] | None = None
# 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 4b6bd0331..cba0f0ccc 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -92,6 +92,7 @@ from .models import (
from .parser_helpers import (
TYPE_HEAD_EXTRACTORS,
_argument_literal_types,
+ _argument_names,
_build_qualified_name,
_classify_param_origin,
_collect_error_nodes,
@@ -118,6 +119,7 @@ from .parser_helpers import (
_objc_is_macro_enum,
_objc_message_selector,
_objc_symbol_name,
+ _overload_arguments,
_qualified_cpp_parent,
_qualified_pascal_parent,
_run_query,
@@ -2164,6 +2166,7 @@ class ASTParser:
arg_count = _count_arguments(arg_nodes[0]) if arg_nodes else None
caller_id = _find_enclosing_symbol(line, symbol_ranges)
+ arguments = _overload_arguments(file_info.language, arg_nodes)
calls.append(
(
@@ -2175,7 +2178,8 @@ class ASTParser:
line=line,
argument_count=arg_count,
receiver_call=receiver_call,
- argument_types=_argument_literal_types(file_info.language, arg_nodes, src),
+ argument_types=_argument_literal_types(arguments, src),
+ argument_names=_argument_names(arguments, src),
scope_name=scope_name,
edge_type=(
"references"
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 60e9b0438..ec99b1eb0 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -350,30 +350,38 @@ _JAVA_INTEGER_LITERALS = frozenset(
_JAVA_FLOATING_LITERALS = frozenset({"decimal_floating_point_literal", "hex_floating_point_literal"})
-def _argument_literal_types(
- language: str, arg_nodes: list[Node], src: str
-) -> tuple[str | None, ...] | None:
- """Each argument's literal type, for a language whose overloads read them (Java)."""
+def _overload_arguments(language: str, arg_nodes: list[Node]) -> list[Node]:
+ """A call's argument expressions, for a language whose overloads read them (Java).
+
+ Read from the argument list already in hand, the way ``_count_arguments``
+ counts it.
+ """
if language != "java" or not arg_nodes:
- return None
- return _java_literal_types(arg_nodes[0], src)
+ return []
+ skip_types = frozenset({"(", ")", ","})
+ return [
+ c for c in arg_nodes[0].children if c.type not in skip_types and "comment" not in c.type
+ ]
-def _java_literal_types(arg_node: Node, src: str) -> tuple[str | None, ...] | None:
+def _argument_literal_types(arguments: list[Node], src: str) -> tuple[str | None, ...] | None:
"""The type of each literal argument, None where an argument is no literal.
- None overall when no argument is a literal. Read from the argument list
- already in hand, the way ``_count_arguments`` counts it.
+ None overall when no argument is a literal.
"""
- skip_types = frozenset({"(", ")", ","})
- types = tuple(
- _java_literal_type(child, src)
- for child in arg_node.children
- if child.type not in skip_types and "comment" not in child.type
- )
+ types = tuple(_java_literal_type(argument, src) for argument in arguments)
return types if any(types) else None
+def _argument_names(arguments: list[Node], src: str) -> tuple[str | None, ...] | None:
+ """Each argument that is a bare name (a local, parameter or field), else None.
+
+ None overall when no argument is one. The resolver reads their declared types.
+ """
+ names = tuple(node_text(a, src) if a.type == "identifier" else None for a in arguments)
+ return names if any(names) else None
+
+
# A unary operator on a literal, by operand type: ``-'a'`` promotes to int.
_JAVA_SIGN_TYPES = {"char": "int", "int": "int", "long": "long", "float": "float", "double": "double"}
_JAVA_UNARY_TYPES: dict[str, dict[str, str]] = {
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
index e8127225c..5d373e8ea 100644
--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -129,7 +129,7 @@ _ANNOTATION = re.compile(r"@[\w.]+(?:\([^)]*\))?")
_FUNCTION_DECLARATOR = re.compile(r"\(\s*([*&^]+)\s*[\w$]*\s*\)")
-def _erased_parameter_type(parameter: str) -> str:
+def erased_type(parameter: str) -> str:
"""``final Map<K, V> m`` -> ``Map``, ``const std::string& s`` -> ``string&``.
Type arguments, qualifiers, modifiers, defaults and the parameter name
@@ -141,7 +141,7 @@ def _erased_parameter_type(parameter: str) -> str:
text = _ANNOTATION.sub(" ", parameter).partition("=")[0]
pointer = _FUNCTION_DECLARATOR.search(strip_type_arguments(text))
if pointer is not None:
- return _erased_parameter_type(text[: text.find("(")]) + pointer.group(1) + "fn"
+ return erased_type(text[: text.find("(")]) + pointer.group(1) + "fn"
words = [w for w in _WORD.findall(strip_type_arguments(text)) if w not in _PARAMETER_MODIFIERS]
if len(words) > 1 and words[-1] not in _BUILTIN_TYPE_WORDS:
words.pop()
@@ -153,7 +153,7 @@ def _erased_parameter_type(parameter: str) -> str:
def erased_parameter_types(symbol: Symbol) -> list[str]:
"""``["String", "int[]"]``: each parameter's erased type, as an id spells it."""
- return [_erased_parameter_type(p) for p in signature_parameters(symbol.signature or "") or []]
+ return [erased_type(p) for p in signature_parameters(symbol.signature or "") or []]
def _parameter_types(symbol: Symbol) -> str:
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index 2781e4abe..afc3b5e3c 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -75,8 +75,9 @@ STORE_FORMAT_VERSION: int = 2
#: load, and a VS Code extension test to the entry its package declares; the
#: first update writes those edges for unchanged files too.
#:
-#: v8: a Java call site records its literal arguments' types, which break a
-#: same-arity overload tie. Java, C# and C++ overloads of one arity carry their erased parameter
+#: v8: a Java call site records its literal arguments' types and its named
+#: arguments, whose declared types join them to break a same-arity overload
+#: tie. Java, C# and C++ overloads of one arity carry their erased parameter
#: types (``put#1(String)``, ``put#1(int)``), and a method in a Java enum
#: constant's body sits under the constant (``Op::PLUS::apply``), and a Java
#: ``@interface`` and its elements are an ``interface`` and its methods; the first
diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.py
index 87e066426..e819287d7 100644
--- a/tests/unit/ingestion/test_overload_identity.py
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -30,8 +30,8 @@ from repowise.core.ingestion.models import FileInfo, ParsedFile
from repowise.core.ingestion.parser import ASTParser
from repowise.core.ingestion.return_types import signature_parameter_range
from repowise.core.ingestion.symbol_identity import (
- _erased_parameter_type,
base_symbol_id,
+ erased_type,
id_segment_name,
overload_sets,
split_symbol_id,
@@ -256,7 +256,7 @@ class TestJavaOverloads:
def test_an_erased_parameter_type_never_holds_a_name_separator(
self, parameter: str, erased: str
) -> None:
- got = _erased_parameter_type(parameter)
+ got = erased_type(parameter)
assert got == erased
assert not any(sep in got for sep in (".", "/", "::", "(", ")", "#"))
@@ -1010,3 +1010,195 @@ class TestJavaLiteralArguments:
edges = _edges(tmp_path, {"app/V.java": ("java", text)})
assert edges == {("app/V.java::V::use", f"app/V.java::V::{member}")}
+
+class TestJavaNamedArguments:
+ """A named argument's declared type breaks a tie the way a literal's does."""
+
+ _MATH = (
+ "package app;\npublic class M {\n"
+ " public static int mul(int a, int b) { return a; }\n"
+ " public static long mul(long a, int b) { return a; }\n"
+ " public static long mul(long a, long b) { return a; }\n"
+ "BODY}\n"
+ )
+
+ @pytest.mark.parametrize(
+ ("body", "member"),
+ [
+ # A parameter and a local.
+ (" long use(long total) {\n int n = 2;\n return mul(total, n);\n }\n",
+ "mul#2(long,int)"),
+ # A field, read where the body declares no such name.
+ (" private long base;\n long use(int n) {\n return mul(base, n);\n }\n",
+ "mul#2(long,int)"),
+ # A local of a primitive type stands over a field of the same name.
+ (" private long n;\n long use(int a) {\n int n = 1;\n return mul(a, n);\n }\n",
+ "mul#2(int,int)"),
+ ],
+ ids=["parameter-and-local", "field", "local-over-field"],
+ )
+ def test_declared_types_choose_the_member(
+ self, tmp_path: Path, body: str, member: str
+ ) -> None:
+ text = self._MATH.replace("BODY", body)
+ edges = _edges(tmp_path, {"app/M.java": ("java", text)})
+ assert edges == {("app/M.java::M::use", f"app/M.java::M::{member}")}
+
+ def test_a_local_the_scan_cannot_type_hides_the_field(self, tmp_path: Path) -> None:
+ """``var n = ...`` shadows the field ``n``: its type is unknown, so the tie stands."""
+ body = " private long n;\n long use(int a) {\n var n = a;\n return mul(n, a);\n }\n"
+ edges = _edges(tmp_path, {"app/M.java": ("java", self._MATH.replace("BODY", body))})
+ assert edges == {("app/M.java::M::use", "app/M.java::M::mul#2(int,int)")}
+
+ def test_a_constructor_takes_its_arguments_declared_types(self, tmp_path: Path) -> None:
+ """``new Span(start, end, kind, zone)`` beside ``Span(int, int, int, int)``."""
+ text = (
+ "package app;\npublic class Span {\n"
+ " public Span(int a, int b, int c, int d) { }\n"
+ " public Span(long start, long end, Kind kind, Zone zone) { }\n"
+ " static Span of(long start, long end, Kind kind, Zone zone) {\n"
+ " return new Span(start, end, kind, zone);\n }\n}\n"
+ "class Kind { }\nclass Zone { }\n"
+ )
+ edges = _edges(tmp_path, {"app/Span.java": ("java", text)})
+ base = "app/Span.java::Span::"
+ assert (base + "of", base + "Span#4(long,long,Kind,Zone)") in edges
+ assert (base + "of", base + "Span#4(int,int,int,int)") not in edges
+
+ def test_an_array_takes_the_array_member(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class A {\n"
+ " public void f(String s) { }\n public void f(String[] xs) { }\n"
+ " void use(String[] names) {\n f(names);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/A.java": ("java", text)})
+ assert edges == {("app/A.java::A::use", "app/A.java::A::f#1(String[])")}
+
+ def test_argument_names_are_read_per_argument(self) -> None:
+ text = 'class A {\n void go(int x) {\n f(x, 1, this.y, "s", z);\n }\n}\n'
+ (call,) = _parse("A.java", "java", text).calls
+ assert call.argument_names == ("x", None, None, None, "z")
+ assert call.argument_types == (None, "int", None, "String", None)
+
+ @pytest.mark.parametrize(
+ "members",
+ [
+ " public void f(Object o) { }\n public void f(Object[] os) { }\n",
+ " public void f(Object[] os) { }\n public void f(Object o) { }\n",
+ ],
+ ids=["object-first", "array-first"],
+ )
+ def test_an_array_reaches_a_covariant_array_before_object(
+ self, tmp_path: Path, members: str
+ ) -> None:
+ text = (
+ f"package app;\npublic class A {{\n{members}"
+ " void use(String[] names) {\n f(names);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/A.java": ("java", text)})
+ assert edges == {("app/A.java::A::use", "app/A.java::A::f#1(Object[])")}
+
+ def test_a_named_primitive_never_takes_an_array(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class A {\n"
+ " public void f(int[] xs) { }\n public void f(long x) { }\n"
+ " void use(int n) {\n f(n);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/A.java": ("java", text)})
+ assert edges == {("app/A.java::A::use", "app/A.java::A::f#1(long)")}
+
+ def test_a_varargs_parameter_is_its_array_over_a_field(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class A {\n private long xs;\n"
+ " public void f(long x) { }\n public void f(int[] xs) { }\n"
+ " void use(int... xs) {\n f(xs);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/A.java": ("java", text)})
+ assert edges == {("app/A.java::A::use", "app/A.java::A::f#1(int[])")}
+
+ @pytest.mark.parametrize(
+ ("members", "member"),
+ [
+ # Phase one takes Integer as an Object, with no unboxing.
+ (" void f(int i) { }\n void f(long l) { }\n void f(Object o) { }\n",
+ "f#1(Object)"),
+ # Unboxed to int before widened to long.
+ (" void f(long l) { }\n void f(int i) { }\n", "f#1(int)"),
+ ],
+ ids=["object", "unboxed"],
+ )
+ def test_a_boxed_argument(self, tmp_path: Path, members: str, member: str) -> None:
+ text = (
+ f"package app;\npublic class A {{\n{members}"
+ " void use(Integer boxed) {\n f(boxed);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/A.java": ("java", text)})
+ assert edges == {("app/A.java::A::use", f"app/A.java::A::{member}")}
+
+ @pytest.mark.parametrize(
+ "lambda_", ["n -> mul(n, 2)", "(n) -> mul(n, 2)", "(a, n) -> mul(n, 2)"]
+ )
+ def test_a_lambda_parameter_hides_the_field(self, tmp_path: Path, lambda_: str) -> None:
+ """Read as the ``long`` field, ``n`` would pick ``mul(long, int)``.
+
+ A lambda parameter is a binding the scan reads, so ``n`` stays untyped
+ and the tie stands.
+ """
+ body = (
+ " private long n;\n"
+ f" void use(java.util.function.IntConsumer c) {{\n c = {lambda_};\n }}\n"
+ )
+ edges = _edges(tmp_path, {"app/M.java": ("java", self._MATH.replace("BODY", body))})
+ assert edges == {("app/M.java::M::use", "app/M.java::M::mul#2(int,int)")}
+
+ def test_an_instanceof_pattern_variable_is_typed(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class Shape {\n"
+ " public void f(Object o) { }\n public void f(Shape s) { }\n"
+ " void use(Object o, boolean ok) {\n"
+ " if (o instanceof Shape s && ok) {\n f(s);\n }\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/Shape.java": ("java", text)})
+ assert edges == {("app/Shape.java::Shape::use", "app/Shape.java::Shape::f#1(Shape)")}
+
+ @pytest.mark.parametrize(
+ ("loop", "member"),
+ [("for (long t : ts)", "mul#2(long,int)"), ("for (var t : ts)", "mul#2(int,int)")],
+ ids=["typed", "var"],
+ )
+ def test_a_for_each_variable(self, tmp_path: Path, loop: str, member: str) -> None:
+ """A typed loop variable is read; a ``var`` one hides the ``long`` field ``t``."""
+ body = f" private long t;\n void use(long[] ts) {{\n {loop} mul(t, 2);\n }}\n"
+ edges = _edges(tmp_path, {"app/M.java": ("java", self._MATH.replace("BODY", body))})
+ assert edges == {("app/M.java::M::use", f"app/M.java::M::{member}")}
+
+ def test_a_call_on_an_array_element_keeps_its_edge(self, tmp_path: Path) -> None:
+ """An array is a builtin type now; ``items[0].m()`` names no receiver and still binds."""
+ files = {
+ "app/B.java": ("java", "package app;\npublic class B {\n public void m() { }\n}\n"),
+ "app/A.java": (
+ "java",
+ "package app;\npublic class A {\n"
+ " void use(B[] items) {\n items[0].m();\n }\n}\n",
+ ),
+ }
+ assert ("app/A.java::A::use", "app/B.java::B::m") in _edges(tmp_path, files)
+
+ @pytest.mark.parametrize(
+ "members",
+ [
+ " void add(Node... ns) { }\n void add(int at, Node... ns) { }\n",
+ " void add(int at, Node... ns) { }\n void add(Node... ns) { }\n",
+ ],
+ ids=["shorter-first", "longer-first"],
+ )
+ def test_an_array_alone_in_the_varargs_position_is_passed_whole(
+ self, tmp_path: Path, members: str
+ ) -> None:
+ """``add(index, nodes)`` with ``Node... nodes`` passes the array, not one ``Node``."""
+ text = (
+ f"package app;\npublic class Node {{\n{members}"
+ " void use(int index, Node... nodes) {\n add(index, nodes);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/Node.java": ("java", text)})
+ assert edges == {("app/Node.java::Node::use", "app/Node.java::Node::add#2")}