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): pick a Kotlin overload by the exact type of its arguments (#4831)

Swati Ahuja94541ab83a2b
diff --git a/packages/core/src/repowise/core/ingestion/call_overload_selection.py b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
index 2f63d13ef..2e38e3d1b 100644
--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py
+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
@@ -305,6 +305,30 @@ def _exact_apex_fit(
return None if any(takes(parameters, may_take) for parameters in others) else exact[0]
+def _exact_kotlin_fit(
+ members: list[tuple[str, list[str]]], argument_types: tuple[str | None, ...]
+) -> str | None:
+ """The one Kotlin member whose parameters are exactly the typed arguments' types.
+
+ Kotlin converts no argument implicitly, and of the members an argument
+ could reach through a supertype the exact one is the most specific, so
+ an exact match decides. Only where the members agree on every untyped
+ argument, which may be one the exact member cannot take. An ``Any``
+ argument is left out: a smart cast may have narrowed it.
+ """
+ if not _untyped_agree(members, argument_types, False):
+ return None
+ typed = [(index, argument.rstrip("?")) for index, argument in enumerate(argument_types) if argument]
+ if any(argument == "Any" for _, argument in typed):
+ return None
+ exact = [
+ member
+ for member, parameters in members
+ if all(index < len(parameters) and parameters[index].rstrip("?") == argument for index, argument in typed)
+ ]
+ return exact[0] if len(exact) == 1 else None
+
+
def _apex_may_take(parameter: str, argument: str, repo_types: frozenset[str]) -> bool:
"""Could an Apex parameter of type *parameter* take an argument of type *argument*?
@@ -779,8 +803,11 @@ class OverloadSelectionMixin:
if self._symbols_by_id[found[0]].language == "csharp":
return self._csharp_takers(found, argument_types)
typed = [(m, erased_parameter_types(self._symbols_by_id[m])) for m in found]
- if self._symbols_by_id[found[0]].language == "apex":
+ language = self._symbols_by_id[found[0]].language
+ if language == "apex":
closest = _exact_apex_fit(typed, argument_types, self._folded_type_names())
+ elif language == "kotlin":
+ closest = _exact_kotlin_fit(typed, argument_types)
else:
closest = _closest_fit(typed, argument_types, expanded, self._jvm_lambda_type_map())
return found if closest is None else [closest]
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 51710016d..816a188a1 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -453,11 +453,13 @@ _APEX_LITERAL_TYPES = {
def _overload_arguments(language: str, arg_nodes: list[Node]) -> list[Node]:
- """A call's argument expressions, for a language whose overloads read them (Java, Apex).
+ """A call's argument expressions, for a language whose overloads read them (Java, Apex, Kotlin).
Read from the argument list already in hand, the way ``_count_arguments``
counts it.
"""
+ if language == "kotlin":
+ return _kotlin_positional_arguments(arg_nodes)
if language not in ("java", "apex", "csharp") or not arg_nodes:
return []
skip_types = frozenset({"(", ")", ","})
@@ -472,6 +474,69 @@ def _overload_arguments(language: str, arg_nodes: list[Node]) -> list[Node]:
return arguments
+def _kotlin_positional_arguments(arg_nodes: list[Node]) -> list[Node]:
+ """Each Kotlin argument's expression, in order, or none at all.
+
+ A named or spread argument, or a trailing lambda, takes a parameter its
+ position does not say, so such a call is not read.
+ """
+ arguments = arg_nodes[0] if arg_nodes else None
+ if arguments is None or arguments.type != "value_arguments" or _kotlin_trailing_lambda(arguments):
+ return []
+ found = []
+ for argument in arguments.named_children:
+ if argument.type != "value_argument":
+ continue
+ parts = argument.named_children
+ if len(parts) != 1 or parts[0].type == "spread_expression":
+ return []
+ found.append(parts[0])
+ return found
+
+
+# Kotlin literals whose type no expected type changes; an unsuffixed integer
+# is an ``Int`` only where an ``Int`` overload exists, which is the one asked.
+_KOTLIN_LITERAL_TYPES = {"string_literal": "String", "character_literal": "Char"}
+_KOTLIN_BOOLEANS = frozenset({"true", "false"})
+# Kotlin's grammar reads these keywords as identifiers; they name no variable.
+_NOT_NAMES = frozenset({b"true", b"false", b"null", b"this"})
+
+
+def _kotlin_literal_type(node: Node, src: str) -> str | None:
+ text = node_text(node, src)
+ if node.type == "identifier":
+ return "Boolean" if text in _KOTLIN_BOOLEANS else None
+ if node.type != "number_literal":
+ return _KOTLIN_LITERAL_TYPES.get(node.type)
+ return _kotlin_number_type(text.lower().replace("_", ""))
+
+
+def _kotlin_number_type(lowered: str) -> str | None:
+ """``Long``, ``Int``, ``Float`` or ``Double`` for a lowercased number.
+
+ None when unsigned, and for an unsuffixed integer past ``Int``'s range,
+ which Kotlin types as a ``Long`` only where no ``Int`` is expected.
+ """
+ if lowered.endswith(("u", "ul")):
+ return None
+ if lowered.endswith("l"):
+ return "Long"
+ base = {"0x": 16, "0b": 2}.get(lowered[:2], 10)
+ if base == 10 and (fraction := _kotlin_fraction_type(lowered)) is not None:
+ return fraction
+ try:
+ value = int(lowered[2:] if base != 10 else lowered, base)
+ except ValueError:
+ return None
+ return "Int" if value < 2**31 else None
+
+
+def _kotlin_fraction_type(lowered: str) -> str | None:
+ if lowered.endswith("f"):
+ return "Float"
+ return "Double" if "." in lowered or "e" in lowered else None
+
+
def _argument_literal_types(
arguments: list[Node], src: str, language: str = "java"
) -> tuple[str | None, ...] | None:
@@ -480,9 +545,11 @@ def _argument_literal_types(
None overall when no argument is a literal. C# reports a lambda's and a
construction's shape instead (``_csharp_argument_shape``).
"""
- literal_type = {"apex": _apex_literal_type, "csharp": _csharp_argument_shape}.get(
- language, _java_literal_type
- )
+ literal_type = {
+ "apex": _apex_literal_type,
+ "csharp": _csharp_argument_shape,
+ "kotlin": _kotlin_literal_type,
+ }.get(language, _java_literal_type)
types = tuple(literal_type(argument, src) for argument in arguments)
return types if any(types) else None
@@ -511,7 +578,10 @@ def _argument_names(arguments: list[Node], src: str) -> tuple[str | 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)
+ names = tuple(
+ node_text(a, src) if a.type == "identifier" and a.text not in _NOT_NAMES else None
+ for a in arguments
+ )
return names if any(names) else None
diff --git a/tests/unit/ingestion/parser/golden/kotlin.json b/tests/unit/ingestion/parser/golden/kotlin.json
index dadb70aed..b3dc41b9e 100644
--- a/tests/unit/ingestion/parser/golden/kotlin.json
+++ b/tests/unit/ingestion/parser/golden/kotlin.json
@@ -80,7 +80,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -96,7 +99,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -112,7 +118,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -128,7 +137,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -144,7 +156,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -160,7 +175,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -176,7 +194,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -192,7 +213,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -208,7 +232,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -224,7 +251,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -240,7 +270,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -256,7 +289,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -272,7 +308,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -288,7 +327,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -304,7 +346,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -320,7 +365,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -336,7 +384,10 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
+ "argument_types": [
+ "Int",
+ "Int"
+ ],
"argument_names": null
},
{
@@ -352,8 +403,14 @@
"bare_name_fallback": false,
"spawned": false,
"program_call": false,
- "argument_types": null,
- "argument_names": null
+ "argument_types": [
+ null,
+ "Int"
+ ],
+ "argument_names": [
+ "x",
+ null
+ ]
}
],
"heritage": [],
diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.py
index 671924838..5b68c270d 100644
--- a/tests/unit/ingestion/test_overload_identity.py
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -28,6 +28,7 @@ from repowise.core.ingestion.call_resolver import CallResolver
from repowise.core.ingestion.graph.builder import GraphBuilder
from repowise.core.ingestion.models import FileInfo, ParsedFile
from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.parser_helpers import _kotlin_number_type
from repowise.core.ingestion.return_types import signature_parameter_range, signature_parameters
from repowise.core.ingestion.symbol_identity import (
base_symbol_id,
@@ -803,6 +804,48 @@ class TestKotlinOverloads:
assert ("app/U.kt::screen", "app/U.kt::item") not in edges
assert ("app/U.kt::Remote::sync", "app/U.kt::Remote::topics") in edges
+ _BUF = (
+ "package app\n\nclass ByteString\n\nclass Buf {\n"
+ " fun write(b: ByteString): Buf = this\n fun write(b: ByteArray): Buf = this\n"
+ " fun put(a: Long, b: Int) { }\n fun put(a: Int, b: Long) { }\n"
+ " fun mark(s: String?) { }\n fun mark(f: Boolean) { }\n"
+ " fun each(b: ByteString, f: () -> Unit) { }\n fun each(b: ByteArray, f: () -> Unit) { }\n"
+ " fun fill(b: ByteString, vararg n: Int) { }\n fun fill(b: ByteArray, vararg n: Int) { }\n"
+ " fun see(s: String) { }\n fun see(a: Any) { }\n"
+ " fun scan(bytes: ByteString) { }\n fun scan(bytes: ByteArray) { }\n}\n\n"
+ "fun use(b: Buf, bytes: ByteArray, text: ByteString, n: Int, maybe: String?, nums: IntArray, any: Any) {\n"
+ )
+
+ @pytest.mark.parametrize(
+ ("call", "member"),
+ [
+ ("b.write(bytes)", "write#1(ByteArray)"),
+ ("b.write(text)", "write#1(ByteString)"),
+ ("b.put(1L, n)", "put#2(Long,Int)"),
+ ("b.put(n, 1L)", "put#2(Int,Long)"),
+ ('b.mark("x")', "mark#1(String?)"),
+ ("b.mark(true)", "mark#1(Boolean)"),
+ ("b.mark(maybe)", "mark#1(String?)"),
+ # Nothing decides, so the set's first member answers as before.
+ ("b.write(b = bytes)", "write#1(ByteString)"),
+ ("b.put(1, 2)", "put#2(Long,Int)"),
+ ("b.put(n, n)", "put#2(Long,Int)"),
+ # A named argument, a trailing lambda or a spread leaves positions unread.
+ ("b.scan(bytes = text)", "scan#1(ByteString)"),
+ ("b.each(bytes) { }", "each#2(ByteString,Function0)"),
+ ("b.fill(bytes, *nums)", "fill#2(ByteString,Int[])"),
+ # A smart cast may have narrowed an Any argument, so its declared type decides nothing.
+ ("b.see(any)", "see#1(String)"),
+ ],
+ )
+ def test_a_typed_argument_picks_the_overload_of_exactly_its_type(
+ self, tmp_path: Path, call: str, member: str
+ ) -> None:
+ """Kotlin converts no argument, so the member whose parameter is the argument's type is it."""
+ text = f"{self._BUF} {call}\n}}\n"
+ edges = _edges(tmp_path, {"app/B.kt": ("kotlin", text)})
+ assert edges == {("app/B.kt::use", f"app/B.kt::Buf::{member}")}
+
def test_a_trailing_comma_closes_no_parameter(self) -> None:
"""Compose style, ``modifier: Modifier = Modifier,`` before ``)``."""
signature = (
@@ -1641,3 +1684,16 @@ class TestJavaNamedArguments:
)
edges = _edges(tmp_path, {"app/Node.java": ("java", text)})
assert edges == {("app/Node.java::Node::use", "app/Node.java::Node::add#2")}
+
+
+ ("literal", "kotlin_type"),
+ [
+ ("1", "Int"), ("0xff", "Int"), ("1_000L", "Long"), ("0b1010L", "Long"), ("1.0", "Double"),
+ ("1e10", "Double"), ("1.0f", "Float"), ("3000000000", None), ("0xffffffff", None), ("1u", None),
+ ],
+)
+def test_a_kotlin_number_literal_types_only_what_no_expected_type_changes(
+ literal: str, kotlin_type: str | None
+) -> None:
+ assert _kotlin_number_type(literal.lower().replace("_", "")) == kotlin_type