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 literal argument types and by arity against inherited overloads (#3672)

Swati Ahujada1800487d4f
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 92ec92165..9922302e1 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -66,7 +66,13 @@ from .return_types import (
signature_parameter_count,
signature_parameter_range,
)
-from .symbol_identity import id_segment_name, outer_scope, pair_overloads, split_symbol_id
+from .symbol_identity import (
+ erased_parameter_types,
+ id_segment_name,
+ outer_scope,
+ pair_overloads,
+ split_symbol_id,
+)
from .type_names import (
csharp_extension_receiver,
is_resolvable_type_name,
@@ -191,6 +197,109 @@ def _overload_phase(admitted: tuple[int, int | None], argument_count: int) -> in
return 0 if fewest == most else 1
+_ArgumentTypes = tuple[str | None, ...] | None
+
+# The Java primitives a literal of each type widens to, nearest first.
+_JAVA_WIDENING: dict[str, tuple[str, ...]] = {
+ "boolean": ("boolean",),
+ "char": ("char", "int", "long", "float", "double"),
+ "int": ("int", "long", "float", "double"),
+ "long": ("long", "float", "double"),
+ "float": ("float", "double"),
+ "double": ("double",),
+}
+_JAVA_BOXES = {
+ "boolean": "Boolean", "char": "Character", "int": "Integer",
+ "long": "Long", "float": "Float", "double": "Double",
+}
+_JAVA_PRIMITIVES = frozenset({"byte", "short", *_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"}
+)
+# {literal: {judged parameter: how it is reached}}: 0 exactly, 1 widened, 2 boxed.
+_JAVA_LITERAL_LEVELS: dict[str, dict[str, int]] = {
+ **{
+ literal: {p: int(p != literal) for p in widened} | {_JAVA_BOXES[literal]: 2}
+ for literal, widened in _JAVA_WIDENING.items()
+ },
+ "String": {"String": 0, "CharSequence": 1},
+ "null": dict.fromkeys(_JAVA_JUDGED_PARAMETERS - _JAVA_PRIMITIVES, 1),
+}
+_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.
+
+ 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.
+ """
+ if parameter not in _JAVA_JUDGED_PARAMETERS:
+ return _UNJUDGED_LEVEL[literal]
+ return _JAVA_LITERAL_LEVELS[literal].get(parameter)
+
+
+def _closest_literal_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.
+
+ Only where the members agree on every non-literal argument's parameter:
+ there the literals 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):
+ 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
+ ]
+ if all(fit is not None for fit in fits):
+ ranked[max(fits, default=0)].append(member)
+ best = ranked[min(ranked)] if ranked else []
+ return best[0] if len(best) == 1 else None
+
+
+def _non_literals_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."""
+ return all(
+ len({_parameter_at(parameters, index, expanded) for _, parameters in members}) == 1
+ for index, literal in enumerate(argument_types)
+ if literal is None
+ )
+
+
+def _parameter_at(parameters: list[str], index: int, expanded: bool) -> str | None:
+ """The parameter type that takes argument *index*.
+
+ Through *expanded* varargs, the trailing array's element type takes the
+ argument at its position and every one after it.
+ """
+ if expanded and parameters and index >= len(parameters) - 1:
+ return parameters[-1].removesuffix("[]")
+ return parameters[index] if index < len(parameters) else None
+
+
+def _java_method_refusing(symbol: Symbol | None, argument_count: int | None) -> bool:
+ """Whether *symbol* is a Java method whose parameters cannot take *argument_count*."""
+ if symbol is None or argument_count is None:
+ return False
+ return symbol.language == "java" and symbol.kind == "method" and not _takes(symbol, argument_count)
+
+
+def _takes(symbol: Symbol, argument_count: int) -> bool:
+ """Whether *symbol*'s parameters admit *argument_count*; an unread signature does."""
+ admitted = signature_parameter_range(symbol.signature or "", symbol.language)
+ return admitted is None or _overload_phase(admitted, argument_count) is not None
+
+
def _flattened_wildcard_source(imp: Import) -> str | None:
"""The repository file whose every name *imp* forwards, or None.
@@ -911,13 +1020,63 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""
rep = self._overload_rep.get(resolved.callee_id)
if rep is None:
- return resolved
- target = self._overload_target(rep, call.argument_count)
+ return self._inherited_overload(resolved, call)
+ target = self._overload_target(rep, call.argument_count, call.argument_types)
if target == resolved.caller_id:
return None
return resolved if target == resolved.callee_id else replace(resolved, callee_id=target)
- def _pick_overload(self, rep: str, argument_count: int | None) -> str | None:
+ def _inherited_overload(self, resolved: ResolvedCall, call: CallSite) -> ResolvedCall | None:
+ """A Java callee that cannot take the call's arguments yields to an inherited overload.
+
+ ``getField(i)`` in a class that overrides only ``getField(int, Chronology)``
+ calls the one-parameter ``getField`` a superclass declares. With no
+ ancestor overload that takes the count, the edge goes: its callee
+ cannot be what the call means, and a constructor inherits none. Java
+ only, where arity is binding.
+ """
+ callee = self._symbols_by_id.get(resolved.callee_id)
+ if not _java_method_refusing(callee, call.argument_count):
+ return resolved
+ assert callee is not None
+ target = None if callee.name == callee.parent_name else self._inherited_taker(resolved, call)
+ return None if target in (None, resolved.caller_id) else replace(resolved, callee_id=target)
+
+ def _inherited_taker(self, resolved: ResolvedCall, call: CallSite) -> str | None:
+ """The ancestor overload of the callee's name that takes *call*, or None.
+
+ Java looks the name up through the whole hierarchy, so a nearer
+ declaration that cannot take the count does not hide a farther one
+ that can. The superclass chain answers nearest first; past it, one
+ other ancestor (an interface default) must be the only taker.
+ """
+ class_id = self._caller_class_id(resolved.callee_id)
+ name = self._symbols_by_id[resolved.callee_id].name
+ chain = tuple(self._superclass_chain(class_id))
+ for ancestor in chain:
+ target = self._taker_in(ancestor, name, call)
+ if target is not None:
+ return target
+ takers = {
+ self._taker_in(ancestor, name, call)
+ for ancestor in self._ancestors_of(class_id)
+ if ancestor not in chain
+ } - {None}
+ return takers.pop() if len(takers) == 1 else None
+
+ def _taker_in(self, type_id: str, name: str, call: CallSite) -> str | None:
+ """The member of *type_id*'s own *name* overloads that takes *call*, or None."""
+ declared = self._declares(type_id, name)
+ if declared is None or self._symbols_by_id[declared].kind != "method":
+ return None
+ count = call.argument_count or 0
+ rep = self._overload_rep.get(declared)
+ target = declared if rep is None else self._overload_target(rep, count, call.argument_types)
+ return target if _takes(self._symbols_by_id[target], count) else None
+
+ def _pick_overload(
+ self, rep: str, argument_count: int | None, argument_types: _ArgumentTypes = None
+ ) -> str | None:
"""The one member of *rep*'s set a call with *argument_count* arguments means.
Asked in the order the languages apply: a member of exactly that arity,
@@ -925,10 +1084,12 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
form), then one whose varargs or ``params`` expand to it. The first
phase with any candidate decides, and two candidates there are a tie.
"""
- found = self._deciding_overloads(rep, argument_count)
+ found = self._deciding_overloads(rep, argument_count, argument_types)
return found[0] if len(found) == 1 else None
- def _overload_target(self, rep: str, argument_count: int | None) -> str:
+ def _overload_target(
+ self, rep: str, argument_count: int | None, argument_types: _ArgumentTypes = None
+ ) -> str:
"""The member of *rep*'s set a call lands on.
The member ``_pick_overload`` names, else the representative when the
@@ -942,7 +1103,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
code judges as one unit and a constructor set needs for any inbound
edge at all.
"""
- found = self._deciding_overloads(rep, argument_count)
+ found = self._deciding_overloads(rep, argument_count, argument_types)
if len(found) == 1:
return found[0]
tied = self._tied_without_representative(rep, found)
@@ -954,8 +1115,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return found
return []
- def _deciding_overloads(self, rep: str, argument_count: int | None) -> list[str]:
- """The members of the first phase with any candidate for *argument_count*."""
+ def _deciding_overloads(
+ self, rep: str, argument_count: int | None, argument_types: _ArgumentTypes = None
+ ) -> 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
+ fit exactly one member's parameters (``value(true)`` over ``value(String)``).
+ """
if argument_count is None or rep in self._unranged_overload_sets:
return []
phases: dict[int, list[str]] = defaultdict(list)
@@ -963,7 +1130,19 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
phase = _overload_phase(admitted, argument_count)
if phase is not None:
phases[phase].append(member)
- return phases[min(phases)] if phases else []
+ phase = min(phases, default=None)
+ found = phases[phase] if phases else []
+ return self._literal_tie_break(found, argument_types, expanded=phase == 2)
+
+ def _literal_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."""
+ 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)
+ return found if closest is None else [closest]
def _overload_sibling_call(self, call: CallSite) -> ResolvedCall | None:
"""An overload calling another member of its own set, ``f(a)`` inside ``f(a, b)``.
@@ -977,7 +1156,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return None
if self._symbols_by_id[caller_id].name != call.target_name:
return None
- target = self._pick_overload(rep, call.argument_count)
+ target = self._pick_overload(rep, call.argument_count, call.argument_types)
if target is None or target == caller_id:
return None
return ResolvedCall(caller_id, target, 0.95, call.line, "same_file")
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 41818950e..2715ca98a 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -338,6 +338,9 @@ class CallSite:
# Handed straight to a task scheduler (``asyncio.create_task(f())``): it runs
# later, beside its caller, so the caller neither waits for it nor repeats it.
spawned: bool = False
+ # 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
# 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 3330e9f11..02b0a1522 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -91,6 +91,7 @@ from .models import (
)
from .parser_helpers import (
TYPE_HEAD_EXTRACTORS,
+ _argument_literal_types,
_build_qualified_name,
_classify_param_origin,
_collect_error_nodes,
@@ -2148,6 +2149,7 @@ class ASTParser:
line=line,
argument_count=arg_count,
receiver_call=receiver_call,
+ argument_types=_argument_literal_types(file_info.language, arg_nodes, 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 75bb65041..60e9b0438 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -336,6 +336,69 @@ def _count_arguments(arg_node: Node) -> int:
)
+# Java literal nodes and the type each one has, for the overload tie-break.
+_JAVA_LITERAL_TYPES = {
+ "true": "boolean",
+ "false": "boolean",
+ "character_literal": "char",
+ "string_literal": "String",
+ "null_literal": "null",
+}
+_JAVA_INTEGER_LITERALS = frozenset(
+ {"decimal_integer_literal", "hex_integer_literal", "octal_integer_literal", "binary_integer_literal"}
+)
+_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)."""
+ if language != "java" or not arg_nodes:
+ return None
+ return _java_literal_types(arg_nodes[0], src)
+
+
+def _java_literal_types(arg_node: 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.
+ """
+ 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
+ )
+ return types if any(types) 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]] = {
+ "-": _JAVA_SIGN_TYPES,
+ "+": _JAVA_SIGN_TYPES,
+ "~": {"char": "int", "int": "int", "long": "long"},
+ "!": {"boolean": "boolean"},
+}
+
+
+def _java_literal_type(node: Node, src: str) -> str | None:
+ if node.type == "unary_expression":
+ operator = node.child_by_field_name("operator")
+ operand = node.child_by_field_name("operand")
+ if operator is None or operand is None:
+ return None
+ literal = _java_literal_type(operand, src)
+ return _JAVA_UNARY_TYPES.get(node_text(operator, src), {}).get(literal or "")
+ if node.type in _JAVA_INTEGER_LITERALS:
+ return "long" if node_text(node, src).endswith(("l", "L")) else "int"
+ if node.type in _JAVA_FLOATING_LITERALS:
+ return "float" if node_text(node, src).endswith(("f", "F")) else "double"
+ return _JAVA_LITERAL_TYPES.get(node.type)
+
+
def _find_enclosing_symbol(
line: int,
symbol_ranges: list[tuple[int, int, str]],
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
index 598ad4319..e8127225c 100644
--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -151,10 +151,14 @@ def _erased_parameter_type(parameter: str) -> str:
return "_".join(re.split(r"\.|::", w)[-1] for w in words) + marks
+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 []]
+
+
def _parameter_types(symbol: Symbol) -> str:
"""``(String,int[])``: the erased types that split a same-count overload."""
- parameters = signature_parameters(symbol.signature or "") or []
- return "(" + ",".join(_erased_parameter_type(p) for p in parameters) + ")"
+ return "(" + ",".join(erased_parameter_types(symbol)) + ")"
# Which discriminator tells colliding members apart, per language. A build
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index f68a346e0..3a5145fc2 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -75,7 +75,8 @@ 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: Java, C# and C++ overloads of one arity carry their erased parameter
+#: 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
#: 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 18b7438fd..87e066426 100644
--- a/tests/unit/ingestion/test_overload_identity.py
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -294,7 +294,7 @@ class TestJavaOverloads:
" public S append(String s) { return emit(s); }\n"
" public S append(char c) { return emit(String.valueOf(c)); }\n"
" S emit(String s) { return this; }\n"
- " void use() { append('x'); }\n"
+ " void use(String v) { append(v); }\n"
"}\n"
)
edges = _edges(tmp_path, {"S.java": ("java", text)})
@@ -302,8 +302,8 @@ class TestJavaOverloads:
# Each overload's own call is attributed to its own node.
assert (base + "append#1(String)", base + "emit") in edges
assert (base + "append#1(char)", base + "emit") in edges
- # A count cannot choose between them: the set's representative, the
- # first declared, answers, as the shared node did before.
+ # A count cannot choose between them, nor a literal argument: the set's
+ # representative, the first declared, answers, as the shared node did before.
assert {c for a, c in edges if a == base + "use"} == {base + "append#1(String)"}
def test_a_record_keeps_its_canonical_constructor_beside_an_overload(self) -> None:
@@ -702,7 +702,8 @@ class TestNarrowingShapes:
class TestOverloadTies:
"""A tie lands on a member that admits the call.
- Call sites carry no argument types, so same-arity members tie. A tie keeps
+ Call sites carry no argument types beyond a Java literal's, so same-arity
+ members tie unless the literals fit one closest (``TestJavaLiteralArguments``). A tie keeps
the representative, the first member declared, when it is tied; a tie
among others takes the first tied member in declaration order. Before, a
tie always answered with the representative, even when its own arity
@@ -768,6 +769,64 @@ class TestOverloadTies:
base = "app/F.java::F::"
assert {c for a, c in edges if a == base + "use"} == {base + "fmt#2(String,Object[])"}
+ @pytest.mark.parametrize(
+ ("inherited", "expected"),
+ [
+ (" public int getField(int i) { return i; }\n", "app/Base.java::Base::getField#1"),
+ ("", None),
+ ],
+ ids=["inherited-overload", "none-admits"],
+ )
+ def test_java_a_callee_that_cannot_take_the_count_yields_to_an_inherited_overload(
+ self, tmp_path: Path, inherited: str, expected: str | None
+ ) -> None:
+ """``getField(i)`` beside an override of only ``getField(int, Chronology)``."""
+ base = (
+ "package app;\npublic abstract class Base {\n"
+ f"{inherited} protected abstract int getField(int i, Object chrono);\n}}\n"
+ )
+ sub = (
+ "package app;\npublic class Sub extends Base {\n"
+ " protected int getField(int i, Object chrono) { return i; }\n"
+ " int use(int i) { return getField(i); }\n}\n"
+ )
+ files = {"app/Base.java": ("java", base), "app/Sub.java": ("java", sub)}
+ parsed = {rel: _parse(rel, lang, text, tmp_path) for rel, (lang, text) in files.items()}
+ resolver = CallResolver(
+ parsed,
+ {rel: set(parsed) - {rel} for rel in parsed},
+ repo_path=str(tmp_path),
+ heritage_parents={"app/Sub.java::Sub": {"app/Base.java::Base"}},
+ )
+ callees = {rc.callee_id for rc in resolver.resolve_file("app/Sub.java", parsed["app/Sub.java"].calls)}
+ assert callees == ({expected} if expected else set())
+
+ def test_java_a_farther_ancestor_overload_takes_what_a_nearer_one_cannot(
+ self, tmp_path: Path
+ ) -> None:
+ """``f(1)``: ``Mid`` declares only ``f(int, int)``, ``Top`` the ``f(int)`` that takes it."""
+ files = {
+ "app/Top.java": "package app;\npublic class Top {\n public void f(int i) { }\n}\n",
+ "app/Mid.java": "package app;\npublic class Mid extends Top {\n"
+ " public void f(int a, int b) { }\n}\n",
+ "app/Sub.java": "package app;\npublic class Sub extends Mid {\n"
+ " public void f(int a, int b) { }\n void use() { f(1); }\n}\n",
+ }
+ parsed = {rel: _parse(rel, "java", text, tmp_path) for rel, text in files.items()}
+ resolver = CallResolver(
+ parsed,
+ {rel: set(parsed) - {rel} for rel in parsed},
+ repo_path=str(tmp_path),
+ heritage_parents={
+ "app/Sub.java::Sub": {"app/Mid.java::Mid"},
+ "app/Mid.java::Mid": {"app/Top.java::Top"},
+ },
+ )
+ calls = parsed["app/Sub.java"].calls
+ assert {rc.callee_id for rc in resolver.resolve_file("app/Sub.java", calls)} == {
+ "app/Top.java::Top::f"
+ }
+
def test_csharp_a_tie_among_other_members_takes_the_first_admitting_one(
self, tmp_path: Path
) -> None:
@@ -855,3 +914,99 @@ class TestOverloadTies:
# members type the chain only when they agree; the first one's type
# alone (Tag) is not taken.
assert (("Out.cs::Out::Use", "Cs.cs::Tag::Label") in edges) is typed
+
+
+class TestJavaLiteralArguments:
+ """Literal arguments break a same-arity tie when they fit one member closest."""
+
+ _ATTR = (
+ "package app;\npublic class Attr {\n"
+ " public Attr value(String s) { return this; }\n"
+ " public Attr value(boolean b) { return this; }\n"
+ " public Attr value(int i) { return this; }\n"
+ " public Attr value(Object o) { return this; }\n"
+ " void use(Attr a) {\n a.value(ARG);\n }\n}\n"
+ )
+
+ @pytest.mark.parametrize(
+ ("argument", "member"),
+ [
+ ("true", "value#1(boolean)"),
+ ('"x"', "value#1(String)"),
+ ("-1", "value#1(int)"),
+ ("'c'", "value#1(int)"),
+ ("1L", "value#1(Object)"),
+ # Every reference parameter takes null: still a tie, kept on the first.
+ ("null", "value#1(String)"),
+ ],
+ )
+ def test_the_closest_member_takes_the_literal(
+ self, tmp_path: Path, argument: str, member: str
+ ) -> None:
+ text = self._ATTR.replace("ARG", argument)
+ edges = _edges(tmp_path, {"app/Attr.java": ("java", text)})
+ assert edges == {("app/Attr.java::Attr::use", f"app/Attr.java::Attr::{member}")}
+
+ def test_literal_types_are_read_per_argument(self) -> None:
+ text = (
+ "class A {\n void go(int x) {\n"
+ ' f(true, 2, 3L, 1.5, 1.5f, \'c\', "s", null, -1, x);\n }\n}\n'
+ )
+ (call,) = _parse("A.java", "java", text).calls
+ assert call.argument_types == (
+ "boolean", "int", "long", "double", "float", "char", "String", "null", "int", None
+ )
+
+ def test_a_unary_operator_promotes_its_literal(self) -> None:
+ text = (
+ "class A {\n void go() {\n"
+ " f(-'a', +'a', ~'a', ~1L, !true, -1.5f, !1, -\"s\");\n }\n}\n"
+ )
+ (call,) = _parse("A.java", "java", text).calls
+ assert call.argument_types == ("int", "int", "int", "long", "boolean", "float", None, None)
+
+ def test_a_tie_that_differs_on_a_non_literal_argument_is_not_broken(
+ self, tmp_path: Path
+ ) -> None:
+ """``value(obj, 1)``: the literal fits ``(String, int)`` better, but ``obj`` decides."""
+ text = (
+ "package app;\npublic class V {\n"
+ " public V value(Object o, long l) { return this; }\n"
+ " public V value(String s, int i) { return this; }\n"
+ " void use(Object obj) {\n value(obj, 1);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/V.java": ("java", text)})
+ # The tie stays on the first declared member, as before literals were read.
+ assert edges == {("app/V.java::V::use", "app/V.java::V::value#2(Object,long)")}
+
+ def test_a_varargs_array_takes_the_trailing_arguments(self, tmp_path: Path) -> None:
+ """``add(0, node)``: both members take ``node`` as an ``N``, so the literal decides."""
+ text = (
+ "package app;\npublic class N {\n"
+ " public void add(N... nodes) { }\n"
+ " public void add(int at, N... nodes) { }\n"
+ " void use(N node) {\n add(0, node);\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/N.java": ("java", text)})
+ assert edges == {("app/N.java::N::use", "app/N.java::N::add#2")}
+
+ @pytest.mark.parametrize(
+ ("call", "member"),
+ [
+ ("f(1)", "f#1(int[])"),
+ ('f("a", "b")', "f#1(String[])"),
+ ('g("a", 1, 2)', "g#2(String,int[])"),
+ ],
+ )
+ def test_a_literal_through_varargs_is_judged_against_the_element_type(
+ self, tmp_path: Path, call: str, member: str
+ ) -> None:
+ text = (
+ "package app;\npublic class V {\n"
+ " public void f(String... xs) { }\n public void f(int... xs) { }\n"
+ " public void g(String s, String... xs) { }\n public void g(String s, int... xs) { }\n"
+ f" void use() {{\n {call};\n }}\n}}\n"
+ )
+ edges = _edges(tmp_path, {"app/V.java": ("java", text)})
+ assert edges == {("app/V.java::V::use", f"app/V.java::V::{member}")}
+