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): give Kotlin overloads and same-named extensions their own ids (#3766)

Swati Ahujade7b773d86f2
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 93ea2d157..4b1798748 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -23,7 +23,7 @@ from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
from .resolvers.jvm_gradle import declaration_rank, source_set_dir
from .symbol_identity import outer_scope
-from .type_names import bare_type_name, kotlin_extension_receiver
+from .type_names import bare_type_name
@dataclass(frozen=True, slots=True)
@@ -152,8 +152,6 @@ class LanguageStrategiesMixin:
# Whether any symbol is a Kotlin Multiplatform ``expect``; None until asked.
self._has_expect: bool | None = None
- # {(Kotlin function id, line): the type it extends, or None}
- self._kotlin_receivers: dict[tuple[str, int], str | None] = {}
# {Dart class id: the named constructors its body declares}
self._dart_constructors: dict[str, frozenset[str]] = {}
@@ -667,16 +665,8 @@ class LanguageStrategiesMixin:
return in_lambda(source, caller is not None and caller.kind in _FUNCTION_KINDS)
def _kotlin_receiver(self, symbol: Symbol) -> str | None:
- """The type a Kotlin function extends, read off its header (annotations included).
-
- Kept per declaration: same-named functions of one file share an id.
- """
- key = (symbol.id, symbol.start_line)
- if key not in self._kotlin_receivers:
- path = self._symbol_paths_by_id.get(symbol.id, "")
- lines = self._lines_of(path)[symbol.start_line - 1 : symbol.start_line + 7]
- self._kotlin_receivers[key] = kotlin_extension_receiver(" ".join(lines), symbol.name)
- return self._kotlin_receivers[key]
+ """The type a Kotlin function extends, as the parser read it off its header."""
+ return symbol.extension_receiver
def _implicit_receivers(self, caller: Symbol) -> set[str]:
"""The bare type names ``this`` may be inside *caller*."""
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 b40616b77..f98aa7610 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -1518,10 +1518,8 @@ class ReceiverTypingMixin:
is called one argument short of its parameters.
"""
counts = {argument_count, signature_parameter_count(symbol.signature or "")}
- return any(
- len(self._overload_return_types.get((path, symbol.parent_name, symbol.name, n), ())) > 1
- for n in counts
- )
+ scope = (path, symbol.parent_name, symbol.extension_receiver, symbol.name)
+ return any(len(self._overload_return_types.get((*scope, n), ())) > 1 for n in counts)
def _python_call_returns(self, symbol: Symbol, path: str, awaited: bool) -> str | None:
"""``_returned_type_id`` for a Python function.
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index f2e2d015b..6006297ff 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -195,9 +195,11 @@ _BOUND_CHAIN_LANGUAGES = frozenset({"java", "csharp", "typescript", "go"})
def _overload_return_types(
parsed_files: dict[str, ParsedFile],
-) -> dict[tuple[str, str | None, str, int | None], set[str]]:
- """``{(path, parent, name, parameter count): normalised return types}``."""
- found: dict[tuple[str, str | None, str, int | None], set[str]] = defaultdict(set)
+) -> dict[tuple[str, str | None, str | None, str, int | None], set[str]]:
+ """``{(path, parent, extension receiver, name, parameter count): normalised return types}``."""
+ found: dict[tuple[str, str | None, str | None, str, int | None], set[str]] = defaultdict(
+ set
+ )
for path, parsed in parsed_files.items():
for symbol in parsed.symbols:
raw_return = declared_return_type(symbol.signature or "")
@@ -209,6 +211,7 @@ def _overload_return_types(
key = (
path,
symbol.parent_name,
+ symbol.extension_receiver,
symbol.name,
signature_parameter_count(symbol.signature or ""),
)
@@ -398,6 +401,18 @@ def _java_method_refusing(symbol: Symbol | None, argument_count: int | None) ->
return symbol.language == "java" and symbol.kind == "method" and not _takes(symbol, argument_count)
+def _kotlin_function_refusing(symbol: Symbol | None, argument_count: int | None) -> bool:
+ """Whether *symbol* is a Kotlin function whose parameters cannot take *argument_count*.
+
+ Never an ``override``: it inherits defaults its own list does not write.
+ """
+ if symbol is None or argument_count is None or symbol.language != "kotlin":
+ return False
+ if symbol.kind not in _FUNCTION_KINDS or "override" in symbol.modifiers:
+ return False
+ return 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)
@@ -874,13 +889,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""Record *parsed*'s overload sets; ``{member id: representative}``.
Only parameter-count members are narrowed: a build-variant member
- (``#cfg(...)``) is not chosen by its arguments.
+ (``#cfg(...)``) is not chosen by its arguments. Kotlin extensions of
+ different receivers are separate sets: the receiver chooses among them.
"""
- members: dict[str, list[Symbol]] = defaultdict(list)
+ members: dict[tuple[str, str | None], list[Symbol]] = defaultdict(list)
for sym in parsed.symbols:
base, payload = split_symbol_id(sym.id)
if payload is not None and payload[0].isdigit():
- members[base].append(sym)
+ members[(base, sym.extension_receiver)].append(sym)
representatives: dict[str, str] = {}
for overloads in members.values():
overloads.sort(key=lambda sym: sym.start_line)
@@ -1189,9 +1205,13 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
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.
+ only, where arity is binding. Kotlin binds arity too: a function that
+ cannot take the count (``item(key) { }`` against ``item(a, b, onClick)``)
+ names a library one, so the edge goes.
"""
callee = self._symbols_by_id.get(resolved.callee_id)
+ if _kotlin_function_refusing(callee, call.argument_count):
+ return None
if not _java_method_refusing(callee, call.argument_count):
return resolved
assert callee is not None
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index c22e1a224..e48d94103 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -22,7 +22,7 @@ from ..cohesion import (
withdraw_declaration_hint,
)
from ..languages.python_modules import dotted_module_for
-from ..models import Import, ParsedFile, combine_load_kinds
+from ..models import Import, ParsedFile, Symbol, combine_load_kinds
from ..resolvers import ResolverContext, resolve_import
from ..resolvers.go import read_go_module_path, read_go_modules
from ..symbol_identity import has_overload_identity
@@ -36,6 +36,23 @@ from ._stem import build_stem_map
log = structlog.get_logger(__name__)
+_CALLABLE_KINDS = frozenset({"function", "method"})
+
+
+def _first_definition_keeps_node(existing: dict[str, Any] | None, sym: Symbol) -> bool:
+ """Does the definition already holding *sym*'s id keep its node?
+
+ Where overloads get their own ids, two definitions still sharing one erase
+ to one signature: the first declared keeps the node, so its span does not
+ depend on how many follow it. A function sharing its id with a Kotlin
+ property takes the node: calls name it.
+ """
+ if existing is None or existing.get("is_declaration") is not False:
+ return False
+ if not has_overload_identity(sym.language):
+ return False
+ return not (sym.kind in _CALLABLE_KINDS and existing.get("kind") not in _CALLABLE_KINDS)
+
def _merge_load_kind(data: dict[str, Any], imp: Import) -> None:
"""Fold one more import into an edge's ``type_only`` / ``deferred`` marks,
@@ -289,14 +306,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
if existing is not None and existing.get("is_declaration") is False:
self._graph.add_edge(path, sym.id, edge_type="defines")
continue
- # Where overloads get their own ids, two definitions still sharing
- # one erase to one signature: the first declared keeps the node,
- # so its span does not depend on how many follow it.
- elif (
- existing is not None
- and existing.get("is_declaration") is False
- and has_overload_identity(sym.language)
- ):
+ elif _first_definition_keeps_node(existing, sym):
self._graph.add_edge(path, sym.id, edge_type="defines")
continue
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 50cb096af..089b75ec3 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -226,6 +226,12 @@ class Symbol:
# C# type declarations only: how many type parameters it declares, which is
# what tells ``IFoo<T>`` from a same-named ``IFoo``. None elsewhere.
type_parameter_count: int | None = None
+ # Kotlin functions only: the bare type an extension dispatches on (``Byte``
+ # for ``fun Byte.toHexString()``), None for a receiver that is its own type
+ # parameter; and the receiver as the id spells it, nullable mark and type
+ # parameter kept (``Byte?``, ``T``), which tells same-named extensions apart.
+ extension_receiver: str | None = None
+ written_receiver: str | None = None
# Keyword modifiers the declaration writes, lowercased (``override``,
# ``static``, ``abstract``...), for languages whose ``LanguageConfig``
# names its modifier nodes. Access keywords land here too; ``visibility``
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index cba0f0ccc..d9e25a4b9 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -113,6 +113,7 @@ from .parser_helpers import (
_has_callable_ancestor,
_head_type_identifier,
_is_async_node,
+ _kotlin_receiver_fields,
_objc_call_is_block_variable,
_objc_container_node,
_objc_container_parent,
@@ -1889,6 +1890,7 @@ class ASTParser:
type_parameter_count=(
_csharp_type_parameter_count(def_node) if language == "csharp" else None
),
+ **_kotlin_receiver_fields(def_node, params_nodes, language, name),
modifiers=_declared_modifiers(def_node, config.modifier_node_types, src),
)
return symbol, def_node
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index ec99b1eb0..7baf309cb 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -52,6 +52,7 @@ from .lang_helpers.type_heads import (
_rust_head_type_identifier,
_rust_shadowed_by_type_param,
)
+from .type_names import kotlin_extension_receiver
log = structlog.get_logger(__name__)
@@ -320,6 +321,21 @@ def _csharp_type_parameter_count(def_node: Node) -> int | None:
return 0
+def _kotlin_receiver_fields(def_node: Node, params: list[Node], language: str, name: str) -> dict:
+ """``Symbol`` fields for the receiver a Kotlin extension function declares; {} otherwise.
+
+ Read off the header alone, up to the parameter list: the body cannot hold
+ the receiver, and a long one is not worth scanning.
+ """
+ if language != "kotlin" or def_node.type != "function_declaration" or not params:
+ return {}
+ header = (def_node.text or b"")[: params[0].start_byte - def_node.start_byte]
+ receiver = kotlin_extension_receiver(header.decode("utf-8", errors="replace") + "(", name)
+ if receiver is None:
+ return {}
+ return {"written_receiver": receiver[0], "extension_receiver": receiver[1]}
+
+
def _count_arguments(arg_node: Node) -> int:
"""Count the number of arguments in an argument/argument_list node.
@@ -329,11 +345,25 @@ def _count_arguments(arg_node: Node) -> int:
substring test rather than a fixed set.
"""
skip_types = frozenset({"(", ")", ",", "[", "]"})
- return sum(
+ listed = sum(
1
for child in arg_node.children
if child.type not in skip_types and "comment" not in child.type
)
+ return listed + _kotlin_trailing_lambda(arg_node)
+
+
+def _kotlin_trailing_lambda(arg_node: Node) -> int:
+ """1 when a Kotlin call passes a trailing lambda, ``f(a) { .. }``, else 0.
+
+ The grammar hangs the lambda off an outer ``call_expression`` wrapping the
+ call, outside the argument list.
+ """
+ call = arg_node.parent
+ outer = call.parent if call is not None else None
+ if outer is None or outer.type != "call_expression" or outer.child(0) != call:
+ return 0
+ return int(any(child.type == "annotated_lambda" for child in outer.children))
# Java literal nodes and the type each one has, for the overload tie-break.
diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.py
index 0727f35fe..239173323 100644
--- a/packages/core/src/repowise/core/ingestion/return_types.py
+++ b/packages/core/src/repowise/core/ingestion/return_types.py
@@ -38,7 +38,8 @@ def signature_parameters(signature: str) -> list[str] | None:
"""The top-level parameter texts of a stored callable signature.
``[]`` for an empty list, None when the signature has no closed list. A
- C/C++ ``(void)`` list is empty, and ``operator()(int)`` lists ``int``.
+ C/C++ ``(void)`` list is empty, ``operator()(int)`` lists ``int``, and a
+ trailing comma (Kotlin, Swift, Dart, TypeScript) closes no parameter.
"""
operator = signature.find("operator()")
start = signature.find("(", 0 if operator < 0 else operator + len("operator()"))
@@ -50,7 +51,8 @@ def signature_parameters(signature: str) -> list[str] | None:
closers: list[str] = []
for char in signature[start + 1 :]:
if char == ")" and not closers:
- pieces.append("".join(current))
+ if not pieces or "".join(current).strip():
+ pieces.append("".join(current))
return pieces if content and [p.strip() for p in pieces] != ["void"] else []
if char in _PAIRS:
closers.append(_PAIRS[char])
@@ -75,9 +77,10 @@ def signature_parameter_count(signature: str) -> int | None:
def signature_parameter_range(signature: str, language: str) -> tuple[int, int | None] | None:
"""``(fewest, most)`` arguments a call may pass; ``most`` is None when open.
- Java ``T...``, C# ``params``, C ``...`` and a C++ parameter pack leave the
- top open, a C# or C++ default lowers the floor, and a C# extension method
- is also called on its receiver, one argument short of its declared list.
+ Java ``T...``, C# ``params``, C ``...``, Kotlin ``vararg`` and a C++
+ parameter pack leave the top open, a C#, C++ or Kotlin default lowers the
+ floor, and a C# extension method is also called on its receiver, one
+ argument short of its declared list.
"""
parameters = signature_parameters(signature)
if parameters is None:
@@ -88,7 +91,9 @@ def signature_parameter_range(signature: str, language: str) -> tuple[int, int |
return 0, 0
if language in ("java", "cpp") and "..." in texts[-1]:
fewest, most = fewest - 1, None
- if language in ("csharp", "cpp"):
+ if language == "kotlin" and any("vararg" in text.split() for text in texts):
+ fewest, most = fewest - 1, None
+ if language in ("csharp", "cpp", "kotlin"):
fewest -= sum(1 for text in texts if "=" in text)
if language == "csharp":
if texts[-1].startswith("params "):
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
index 5d373e8ea..d2110ecf5 100644
--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -10,7 +10,9 @@ gains a discriminator:
narrows to the member whose parameters admit its argument count. Members
that share a count also carry their erased parameter types,
``StringUtil.java::StringUtil::append#1(String)``, so an inserted overload
- never renames its siblings.
+ never renames its siblings. A Kotlin extension's receiver leads its types,
+ as it leads the JVM signature it compiles to: ``Byte.toHexString()`` is
+ ``Util.kt::toHexString#0(Byte)``, beside ``toHexString#0(Int)``.
- ``#<tag>(<predicate>)`` on the last segment: one build variant of a symbol
declared once per configuration, ``lib.rs::f#cfg(not(unix))``. A call may
mean any variant.
@@ -151,14 +153,115 @@ def erased_type(parameter: str) -> str:
return "_".join(re.split(r"\.|::", w)[-1] for w in words) + marks
+# A Kotlin annotation's name, ``@StringRes`` or ``@param:Json``; its arguments
+# are skipped by bracket depth, since they may nest parentheses.
+_KOTLIN_ANNOTATION = re.compile(r"@[\w.:]+\s*")
+_OPENERS, _CLOSERS = "(<[{", ")>]}"
+
+
+def _depth_zero_split(text: str, separator: str) -> list[str]:
+ """*text* split on *separator* outside brackets; the ``>`` of ``->`` closes none."""
+ pieces: list[str] = []
+ depth = start = i = 0
+ while i < len(text):
+ at_arrow = text.startswith("->", i)
+ if depth == 0 and text.startswith(separator, i):
+ pieces.append(text[start:i])
+ i = start = i + len(separator)
+ continue
+ if at_arrow:
+ i += 2
+ continue
+ if text[i] in _OPENERS:
+ depth += 1
+ elif text[i] in _CLOSERS:
+ depth = max(0, depth - 1)
+ i += 1
+ pieces.append(text[start:])
+ return pieces
+
+
+def _strip_kotlin_annotations(text: str) -> str:
+ """*text* without its annotations, nested parentheses in their arguments included."""
+ out: list[str] = []
+ i = 0
+ while (found := _KOTLIN_ANNOTATION.search(text, i)) is not None:
+ out.append(text[i : found.start()])
+ i = found.end()
+ if text.startswith("(", i):
+ arguments = _depth_zero_split(text[i + 1 :], ")")
+ i += len(arguments[0]) + 2
+ out.append(text[i:])
+ return " ".join(out)
+
+
+def _kotlin_function_arity(written: str) -> int | None:
+ """``N`` of the ``FunctionN`` a Kotlin function type compiles to; None for another type.
+
+ ``Int.() -> Unit`` counts its receiver, and ``((Int) -> Unit)?`` its inner type.
+ """
+ arrow = _depth_zero_split(written, "->")
+ if len(arrow) < 2:
+ inner = written.rstrip("?").strip()
+ if inner.startswith("(") and inner.endswith(")"):
+ return _kotlin_function_arity(inner[1:-1].strip())
+ return None
+ left = arrow[0].strip()
+ if not left.endswith(")"):
+ return None
+ opened = _opening_paren(left)
+ params = [p for p in _depth_zero_split(left[opened + 1 : -1], ",") if p.strip()]
+ receiver = left[:opened].rstrip().endswith(".")
+ return len(params) + (1 if receiver else 0)
+
+
+def _opening_paren(text: str) -> int:
+ """The index of the ``(`` matching the ``)`` that ends *text*."""
+ depth = 0
+ for index in range(len(text) - 1, -1, -1):
+ if text[index] == ")":
+ depth += 1
+ elif text[index] == "(":
+ depth -= 1
+ if depth == 0:
+ return index
+ return 0
+
+
+def kotlin_erased_type(parameter: str) -> str:
+ """``vararg xs: List<Int>`` -> ``List[]``, ``f: (Int) -> Unit`` -> ``Function1``.
+
+ A function type erases to the ``FunctionN`` class it compiles to, its
+ receiver counted, and a nullable mark stays, as ``erased_type`` keeps it.
+ """
+ head, *rest = _depth_zero_split(_strip_kotlin_annotations(parameter), ":")
+ written = _depth_zero_split(":".join(rest), "=")[0].strip()
+ arity = _kotlin_function_arity(written)
+ if arity is not None:
+ erased = f"Function{arity}"
+ else:
+ # ``->`` goes first: type-argument stripping reads its ``>`` as a closer.
+ written = strip_type_arguments(written.replace("->", " "))
+ words = _WORD.findall(written)
+ erased = words[-1].rpartition(".")[2] if words else ""
+ erased += "?" if written.endswith("?") else ""
+ return erased + ("[]" if "vararg" in head.split() else "")
+
+
def erased_parameter_types(symbol: Symbol) -> list[str]:
"""``["String", "int[]"]``: each parameter's erased type, as an id spells it."""
- return [erased_type(p) for p in signature_parameters(symbol.signature or "") or []]
+ erase = kotlin_erased_type if symbol.language == "kotlin" else erased_type
+ return [erase(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."""
- return "(" + ",".join(erased_parameter_types(symbol)) + ")"
+ """``(String,int[])``: the erased types that split a same-count overload.
+
+ A Kotlin extension's receiver comes first, which is what tells
+ ``Byte.toHexString()`` from ``Int.toHexString()``.
+ """
+ receiver = [symbol.written_receiver] if symbol.written_receiver else []
+ return "(" + ",".join(receiver + erased_parameter_types(symbol)) + ")"
# Which discriminator tells colliding members apart, per language. A build
@@ -167,6 +270,7 @@ _DISCRIMINATORS: dict[str, Callable[[Symbol], str | None]] = {
"java": _parameter_count,
"csharp": _parameter_count,
"cpp": _parameter_count,
+ "kotlin": _parameter_count,
}
# Languages where a type may share its name with a sibling of another arity.
@@ -301,6 +405,7 @@ __all__ = [
"disambiguate_colliding_ids",
"has_overload_identity",
"id_segment_name",
+ "kotlin_erased_type",
"outer_scope",
"overload_sets",
"pair_overloads",
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
index d9fdd0809..23f15b0cb 100644
--- a/packages/core/src/repowise/core/ingestion/type_names.py
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -247,10 +247,13 @@ _CSHARP_EXTENSION_RECEIVER = re.compile(
)
-def kotlin_extension_receiver(header: str, name: str) -> str | None:
- """The bare type Kotlin's ``fun Type.name(`` in *header* extends, or None.
+def kotlin_extension_receiver(header: str, name: str) -> tuple[str, str | None] | None:
+ """``(written, extended)`` for Kotlin's ``fun Type.name(`` in *header*, or None.
- None too for a receiver that is the function's own type parameter
+ *written* is the receiver as a symbol id spells it, nullable mark and type
+ parameter kept (``Int?``, ``T``), which tells ``Int.f()`` from
+ ``Int?.f()``. *extended* is the bare type the extension dispatches on,
+ None for a receiver that is the function's own type parameter
(``fun <T> T.name()``): any implicit receiver fits it.
"""
# Read at the header's first `fun` only: a same-named function below it is
@@ -262,10 +265,14 @@ def kotlin_extension_receiver(header: str, name: str) -> str | None:
).match(header, first.start())
if not match:
return None
- bare = bare_type_name(match.group("type").strip().rstrip("?"))
+ written = match.group("type").strip()
+ bare = bare_type_name(written.rstrip("?").strip())
+ if not bare:
+ return None
params = (match.group("params") or "").split(",")
declared = {p.split(":")[0].split()[-1] for p in params if p.strip()}
- return None if not bare or bare in declared else bare
+ nullable = "?" if written.endswith("?") else ""
+ return bare + nullable, None if bare in declared else bare
def csharp_extension_receiver(signature: str) -> str | None:
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index fc0ad5f22..38b6029d4 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -89,6 +89,10 @@ STORE_FORMAT_VERSION: int = 2
#: A Dart call chained on a call (``a.b().c()``) carries that inner call too,
#: and a Dart function's signature carries its declared return type.
#: A Kotlin function's signature carries its declared return type.
+#: Kotlin overloads and same-named extensions in one scope get their own ids
+#: the Java way, an extension's receiver leading its types
+#: (``toHexString#0(Byte)``, ``g#0(Int?)``), and a Kotlin trailing lambda counts as an
+#: argument.
PARSER_SCHEMA_VERSION: int = 8
#: state.json key holding the store format version that wrote the store.
diff --git a/tests/unit/ingestion/test_kotlin_extension_calls.py b/tests/unit/ingestion/test_kotlin_extension_calls.py
index e3b44f7c5..fea5dabfc 100644
--- a/tests/unit/ingestion/test_kotlin_extension_calls.py
+++ b/tests/unit/ingestion/test_kotlin_extension_calls.py
@@ -125,10 +125,10 @@ class TestReceiverShape:
@pytest.mark.parametrize(
("header", "name", "receiver"),
[
- ("private operator fun Random.get(range: IntRange) = 1", "get", "Random"),
- ("fun <T : Any> Mono<T>.capture(x: Int)", "capture", "Mono"),
- ("fun String?.orBlank(): String", "orBlank", "String"),
- ("fun <T> T.also2(): T", "also2", None),
+ ("private operator fun Random.get(range: IntRange) = 1", "get", ("Random", "Random")),
+ ("fun <T : Any> Mono<T>.capture(x: Int)", "capture", ("Mono", "Mono")),
+ ("fun String?.orBlank(): String", "orBlank", ("String?", "String")),
+ ("fun <T> T.also2(): T", "also2", ("T", None)),
("@Composable fun Card(x: a.B) {}", "Card", None),
("fun foo()\nfun Bar.foo()", "foo", None),
],
diff --git a/tests/unit/ingestion/test_overload_declarations.py b/tests/unit/ingestion/test_overload_declarations.py
index 61e589ddf..5e8401a06 100644
--- a/tests/unit/ingestion/test_overload_declarations.py
+++ b/tests/unit/ingestion/test_overload_declarations.py
@@ -88,7 +88,11 @@ class TestPythonOverloads:
parsed, _ = parsed_graph
types = _overload_return_types({"py_overload_init.py": parsed})
assert {"str", "bytes"} <= set().union(
- *(v for (_, parent, name, _), v in types.items() if (parent, name) == (None, "parse"))
+ *(
+ v
+ for (_, parent, _, name, _), v in types.items()
+ if (parent, name) == (None, "parse")
+ )
)
def test_stub_is_not_paired_with_a_same_named_definition_elsewhere(
diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.py
index e819287d7..c966f274b 100644
--- a/tests/unit/ingestion/test_overload_identity.py
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -28,11 +28,12 @@ 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.return_types import signature_parameter_range
+from repowise.core.ingestion.return_types import signature_parameter_range, signature_parameters
from repowise.core.ingestion.symbol_identity import (
base_symbol_id,
erased_type,
id_segment_name,
+ kotlin_erased_type,
overload_sets,
split_symbol_id,
symbol_id_arity,
@@ -612,7 +613,6 @@ class TestOtherLanguagesAreUntouched:
[
("m.py", "python", "def f(a):\n pass\n\ndef f(a, b):\n pass\n"),
("m.c", "c", "int f(int a) { return a; }\nint f(int a, int b) { return a; }\n"),
- ("m.kt", "kotlin", "class K {\n fun f(a: Int) {}\n fun f(a: Int, b: Int) {}\n}\n"),
],
)
def test_same_named_definitions_keep_one_plain_id(self, rel: str, language: str, text: str) -> None:
@@ -620,6 +620,177 @@ class TestOtherLanguagesAreUntouched:
assert all(base_symbol_id(i) == i for i in ids), ids
+class TestKotlinOverloads:
+ """Kotlin overloads and same-named extensions of one scope, ``Main.kt::main``."""
+
+ _MAIN = (
+ "package app\n"
+ "fun main(args: Array<String>) { }\n"
+ "fun Application.main() { main(JwkProvider()) }\n"
+ "fun Application.main(jwkProvider: JwkProvider) { }\n"
+ 'fun Byte.toHexString(): String = ""\n'
+ 'fun Int.toHexString(): String = ""\n'
+ "fun once() { }\n"
+ "class Application\nclass JwkProvider\n"
+ )
+
+ def test_each_member_gets_its_own_id_and_a_receiver_leads_its_types(self) -> None:
+ ids = _ids(_parse("app/Main.kt", "kotlin", self._MAIN))
+ assert ids[:6] == [
+ "app/Main.kt::main#1(Array)",
+ "app/Main.kt::main#0",
+ "app/Main.kt::main#1(Application,JwkProvider)",
+ "app/Main.kt::toHexString#0(Byte)",
+ "app/Main.kt::toHexString#0(Int)",
+ "app/Main.kt::once",
+ ]
+ assert untyped_symbol_id(ids[2]) == "app/Main.kt::main#1"
+
+ def test_a_nullable_or_generic_receiver_is_its_own_member(self) -> None:
+ """``Int?.g()`` beside ``Int.g()`` is legal: the JVM sees ``Integer`` and ``int``."""
+ text = "fun Int.g() { }\nfun Int?.g() { }\nfun <T> T.h() { }\nfun <T> T?.h() { }\n"
+ symbols = _parse("G.kt", "kotlin", text).symbols
+ assert [s.id for s in symbols] == [
+ "G.kt::g#0(Int)",
+ "G.kt::g#0(Int?)",
+ "G.kt::h#0(T)",
+ "G.kt::h#0(T?)",
+ ]
+ # The dispatch type stays bare, and a type parameter extends nothing in particular.
+ assert [s.extension_receiver for s in symbols] == ["Int", "Int", None, None]
+
+ def test_a_same_erasure_collision_keeps_the_first_declaration(self) -> None:
+ """``@JvmName`` lets two members erase alike; they stay one id, held by the first."""
+ text = 'fun f(xs: List<String>) { }\n@JvmName("fInts")\nfun f(xs: List<Int>) { }\n'
+ assert _ids(_parse("F.kt", "kotlin", text)) == ["F.kt::f", "F.kt::f"]
+ assert _graph({"F.kt": ("kotlin", text)}).nodes["F.kt::f"]["start_line"] == 1
+
+ def test_an_override_spelled_through_a_typealias_dispatches_from_its_interface(self) -> None:
+ text = (
+ "package app\n\ntypealias Name = String\n\n"
+ "interface Store {\n fun put(x: Int)\n fun put(x: String)\n}\n\n"
+ "class Mem : Store {\n"
+ " override fun put(x: Int) { }\n override fun put(x: Name) { }\n}\n"
+ )
+ graph = _graph({"app/Store.kt": ("kotlin", text)})
+ dispatched = {
+ (base, impl)
+ for base, impl, data in graph.edges(data=True)
+ if data.get("edge_type") == "dispatches_to"
+ }
+ assert (
+ "app/Store.kt::Store::put#1(String)",
+ "app/Store.kt::Mem::put#1(Name)",
+ ) in dispatched
+
+ def test_a_property_beside_a_same_named_function_keeps_one_id(self) -> None:
+ text = "class K {\n val x: Int = 1\n fun x() = 2\n}\n"
+ assert _ids(_parse("K.kt", "kotlin", text)) == ["K.kt::K", "K.kt::K::x", "K.kt::K::x"]
+ # The function holds the shared node, whichever is declared first.
+ for source in (text, "class K {\n fun x() = 2\n val x: Int = 1\n}\n"):
+ node = _graph({"K.kt": ("kotlin", source)}).nodes["K.kt::K::x"]
+ assert node["kind"] == "method"
+
+ @pytest.mark.parametrize(
+ ("parameter", "erased"),
+ [
+ ("args: Array<String>", "Array"),
+ ("sink: java.nio.ByteBuffer", "ByteBuffer"),
+ ("name: String? = null", "String?"),
+ ("vararg more: Int", "Int[]"),
+ ("@StringRes id: Int", "Int"),
+ ("block: (Int, String) -> Unit", "Function2"),
+ ("block: suspend Builder.() -> Unit = {}", "Function1"),
+ ("f: ((Int) -> Unit, String) -> X", "Function2"),
+ ("f: ((Int) -> Unit)?", "Function1"),
+ ("@Json(name = key(1, (2))) m: Map<String, (Int) -> Unit>", "Map"),
+ ('@param:Json("a") y: Int', "Int"),
+ ],
+ )
+ def test_a_parameter_erases_to_its_written_type(self, parameter: str, erased: str) -> None:
+ assert kotlin_erased_type(parameter) == erased
+
+ def test_calls_bind_by_receiver_then_by_argument_count(self, tmp_path: Path) -> None:
+ io = (
+ "package app\n\ninterface Source\n\ninterface Sink\n\n"
+ 'class BufferedSource {\n fun readUtf8(): String = ""\n}\n\n'
+ "class BufferedSink\n\n"
+ "fun Source.buffer(): BufferedSource = BufferedSource()\n\n"
+ "fun Sink.buffer(): BufferedSink = BufferedSink()\n"
+ )
+ use = (
+ "package app\n"
+ "fun read(s: Source) {\n val b = s.buffer()\n b.readUtf8()\n}\n"
+ "fun write(k: Sink) { k.buffer() }\n"
+ )
+ files = {
+ "app/Io.kt": ("kotlin", io),
+ "app/Use.kt": ("kotlin", use),
+ "app/Main.kt": ("kotlin", self._MAIN),
+ }
+ edges = _edges(tmp_path, files)
+ assert ("app/Use.kt::read", "app/Io.kt::buffer#0(Source)") in edges
+ assert ("app/Use.kt::write", "app/Io.kt::buffer#0(Sink)") in edges
+ # Each extension's own return type types the local it assigns.
+ assert ("app/Use.kt::read", "app/Io.kt::BufferedSource::readUtf8") in edges
+ assert ("app/Main.kt::main#0", "app/Main.kt::main#1(Application,JwkProvider)") in edges
+
+ def test_a_trailing_lambda_is_an_argument_and_a_default_lowers_the_floor(
+ self, tmp_path: Path
+ ) -> None:
+ text = (
+ "package app\nclass R {\n"
+ " fun exec(a: Int) { }\n"
+ " fun exec(a: Int, block: () -> Unit) { }\n"
+ " fun put(a: Int, b: Int, c: Int = 0) { }\n"
+ " fun put(a: Int) { }\n"
+ " fun go() {\n exec(1) { }\n put(1, 2)\n }\n}\n"
+ )
+ edges = _edges(tmp_path, {"app/R.kt": ("kotlin", text)})
+ assert edges == {
+ ("app/R.kt::R::go", "app/R.kt::R::exec#2"),
+ ("app/R.kt::R::go", "app/R.kt::R::put#3"),
+ }
+
+ def test_a_function_that_cannot_take_the_count_draws_no_edge(self, tmp_path: Path) -> None:
+ """``item(key) { }`` is a library call, not the repo's ``item(a, b, onClick)``.
+
+ An ``override`` is exempt: it inherits the defaults its interface writes.
+ """
+ text = (
+ "package app\n\n"
+ "fun item(selected: Boolean, label: String, onClick: () -> Unit) { }\n\n"
+ "interface Source {\n fun topics(ids: List<String>? = null): List<String>\n}\n\n"
+ "class Remote : Source {\n"
+ " override fun topics(ids: List<String>?): List<String> = emptyList()\n"
+ " fun sync() {\n topics()\n }\n}\n\n"
+ 'fun screen() {\n item("k") { }\n}\n'
+ )
+ edges = _edges(tmp_path, {"app/U.kt": ("kotlin", text)})
+ 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
+
+ def test_a_trailing_comma_closes_no_parameter(self) -> None:
+ """Compose style, ``modifier: Modifier = Modifier,`` before ``)``."""
+ signature = (
+ "function Screen(\n onClick: () -> Unit,\n modifier: Modifier = Modifier,\n)"
+ )
+ assert signature_parameter_range(signature, "kotlin") == (1, 2)
+
+
+ ("signature", "parameters"),
+ [
+ ("def f(a, b,)", ["a", "b"]),
+ ("fn f(a: i32, b: &str,)", ["a: i32", "b: &str"]),
+ ("function f(\n a: Int,\n b: Int,\n)", ["a: Int", "b: Int"]),
+ ],
+ ids=["python", "rust", "kotlin"],
+)
+def test_a_trailing_comma_is_not_a_parameter(signature: str, parameters: list[str]) -> None:
+ assert [p.strip() for p in signature_parameters(signature) or []] == parameters
+
+
def test_fixture_ids_carry_a_discriminator_only_on_collision() -> None:
"""Every fixture symbol declared once keeps its plain id, in every language.
@@ -636,7 +807,7 @@ def test_fixture_ids_carry_a_discriminator_only_on_collision() -> None:
checked += 1
if symbol.id == base and "`" not in symbol.id:
continue
- assert symbol.language in ("java", "csharp", "cpp"), symbol.id
+ assert symbol.language in ("java", "csharp", "cpp", "kotlin"), symbol.id
assert bases.count(base) > 1 or "`" in symbol.id, symbol.id
assert checked > 500