Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(graph): type a Kotlin call chained on another call (#3756) (#3845)
Aman2a499a2a1a20
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.pyindex f1767310c..10894ec0c 100644--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py@@ -44,7 +44,9 @@ class _LanguageCallStrategies:Strategies are named rather than bound so a probe can substitute one.``member_bare_fallback`` lets a member or chained call nothing claimed fall- back to the bare-name tiers. ``inherited_typed_receiver`` lets a typed+ back to the bare-name tiers; ``chain_bare_fallback`` withholds that from a+ call chained on another call (``a.b().c()``) alone, which is resolved by+ its inner call's return type or not at all. ``inherited_typed_receiver`` lets a typedreceiver whose type lacks the method answer with the one ancestor thatdeclares it."""@@ -54,6 +56,7 @@ class _LanguageCallStrategies:member: tuple[str, ...] = ()member_fallback: tuple[str, ...] = ()member_bare_fallback: bool = True+ chain_bare_fallback: bool = Trueinherited_typed_receiver: bool = False@@ -113,7 +116,11 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {member_bare_fallback=False,inherited_typed_receiver=True,),- "kotlin": replace(_JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER),+ # A chained call keeps no bare-name fallback: ``.send()`` on a result the+ # return type does not type is not the repo's ``send``.+ "kotlin": replace(+ _JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER, chain_bare_fallback=False+ ),"csharp": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),"python": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),# Swift and Dart register the fallback: neither has a package tier of itsdiff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 0d8aa599c..2c32e5a15 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -204,12 +204,12 @@ _EXTENSION_KINDS = frozenset({"impl"})# Languages admitted to the full return-type chain lane; each is admitted# explicitly, once measured.PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset(- {"cpp", "csharp", "dart", "go", "java", "python"}+ {"cpp", "csharp", "dart", "go", "java", "kotlin", "python"})# Chain languages that type the inner call by the identity of the type it# returns (``_returned_type_id``); the rest read its type name.-_RETURNED_TYPE_ID_LANGUAGES = frozenset({"dart", "go", "python"})+_RETURNED_TYPE_ID_LANGUAGES = frozenset({"dart", "go", "kotlin", "python"})# Chain lanes that need a file or import/re-export identity for the head type:# a repository-global simple type name is not a language binding.@@ -833,14 +833,15 @@ class CallResolver(if handled:return resolved- bare_fallback = self._strategies_for(file_path).member_bare_fallback+ strategies = self._strategies_for(file_path)+ bare_fallback = strategies.member_bare_fallback# --- Method call with receiver: receiver.method() ---if call.receiver_name:handled, hit = self._resolve_member_call(file_path, call, caller_id)if not handled and call.bare_name_fallback and bare_fallback:hit = self._resolve_free_call(file_path, call, caller_id)return self._with_props(hit, call)- if receiver_call is not None and not bare_fallback:+ if receiver_call is not None and not (bare_fallback and strategies.chain_bare_fallback):return None# --- Free function call: function() ---@@ -1020,10 +1021,18 @@ class CallResolver(if hit is not None:tier = hit.origin.removeprefix("receiver_typed_")return True, self._return_typed_call(caller_id, hit.callee_id, tier, call.line)- if language in ("python", "dart"):+ if language == "kotlin" and type_id is not None:+ # A Kotlin extension function can add the method to the type the+ # inner call returns; a member of the type still wins over it.+ _, extension = self._extension_call(+ file_path, call, caller_id, self._symbols_by_id[type_id].name+ )+ if extension is not None:+ return True, extension+ if language in ("python", "dart", "kotlin"):# A type name read in the caller's file is not evidence, and an- # inherited method is not a refusal: the bare name keeps the site- # where the language allows one.+ # inherited method or an extension is not a refusal: the bare name+ # keeps the site where the language allows one.return False, Nonetype_name = (tabled@@ -1229,11 +1238,11 @@ class CallResolver(A receiver records one hop, but the parser keeps every link of a chainas its own site on the chain's first line, so the hop below is read- off the site *inner* names. C#, Dart, Go and Java read it, so a builder chain+ off the site *inner* names. C#, Dart, Go, Java and Kotlin read it, so a builder chaintypes each link from the one before; elsewhere an inner call is stilltyped as if nothing were chained under it."""- if language not in ("csharp", "dart", "go", "java"):+ if language not in ("csharp", "dart", "go", "java", "kotlin"):return Nonesites = self._chained_sites.get(file_path)if sites is None:diff --git a/packages/core/src/repowise/core/ingestion/parser/calls.py b/packages/core/src/repowise/core/ingestion/parser/calls.pyindex d52086c9d..7102d9158 100644--- a/packages/core/src/repowise/core/ingestion/parser/calls.py+++ b/packages/core/src/repowise/core/ingestion/parser/calls.py@@ -34,6 +34,12 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:if node.type == "identifier":return _dart_call_receiver(node, src)+ if (+ node.type == "call_expression"+ and node.child_by_field_name("function") is None+ and node.child_by_field_name("arguments") is None+ ):+ return _kotlin_call_receiver(node, src)arguments = node.child_by_field_name("arguments")argument_count = _count_arguments(arguments) if arguments is not None else None@@ -59,6 +65,42 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:return CallReceiver(target_name, receiver_name, argument_count)+def _kotlin_call_receiver(call: Node, src: str) -> CallReceiver | None:+ """Describe a Kotlin call captured as another call's receiver."""+ named = call.named_children+ callee = named[0] if named else None+ arguments = next(+ (child for child in named if child.type == "value_arguments"), None+ )+ if callee is None or arguments is None:+ return None+ count = _count_arguments(arguments)++ if callee.type == "identifier":+ return CallReceiver(_node_text(callee, src).strip(), None, count)+ if callee.type != "navigation_expression" or len(callee.named_children) != 2:+ return None++ receiver, target = callee.named_children+ if target.type != "identifier":+ return None++ if receiver.type == "call_expression":+ receiver_name = None+ elif receiver.type in ("identifier", "this_expression") or (+ receiver.type == "navigation_expression"+ and [child.type for child in receiver.named_children]+ == ["this_expression", "identifier"]+ ):+ receiver_name = _receiver_text("kotlin", receiver, src)+ else:+ return None++ if receiver.type != "call_expression" and receiver_name is None:+ return None+ return CallReceiver(_node_text(target, src).strip(), receiver_name, count)++def _function_target(function: Node) -> tuple[Node | None, Node | None]:"""``(target, receiver)`` named by an inner call's ``function`` field."""if function.type in ("identifier", "property_identifier", "field_identifier"):@@ -309,6 +351,14 @@ def _call_from_match(arg_nodes = capture_dict.get("call.arguments", [])receiver_call_nodes = capture_dict.get("call.receiver_call", [])+ receiver_call = (+ _call_receiver_from_node(receiver_call_nodes[0], src)+ if receiver_call_nodes+ else None+ )+ if receiver_call_nodes and receiver_call is None and language == "kotlin":+ # Avoid resolving an unsupported chained call by its bare name.+ return Nonescope_nodes = capture_dict.get("call.scope", [])line = site_node.start_point[0] + 1arguments = _overload_arguments(language, arg_nodes)@@ -318,9 +368,7 @@ def _call_from_match(caller_symbol_id=_find_enclosing_symbol(line, symbol_ranges),line=line,argument_count=_count_arguments(arg_nodes[0]) if arg_nodes else None,- receiver_call=(- _call_receiver_from_node(receiver_call_nodes[0], src) if receiver_call_nodes else None- ),+ receiver_call=receiver_call,argument_types=_argument_literal_types(arguments, src),argument_names=_argument_names(arguments, src),scope_name=_node_text(scope_nodes[0], src).strip() if scope_nodes else None,diff --git a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm b/packages/core/src/repowise/core/ingestion/queries/kotlin.scmindex 64a776cdb..79bd639a6 100644--- a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm+++ b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm@@ -86,6 +86,19 @@] @call.arguments) @call.site+; Call chained on another call: a.b().c(args), a?.b()?.c(args), B.Builder().c().+; The inner call is captured whole as ``@call.receiver_call``; the grammar+; names no fields on either node, so ``parser._kotlin_call_receiver`` reads its+; target, receiver and arguments by position. The ``.`` or ``?.`` between the+; two is an unnamed token, so one pattern serves both.+(call_expression+ (navigation_expression+ (call_expression) @call.receiver_call+ (identifier) @call.target+ )+ (value_arguments) @call.arguments+) @call.site+; ---------------------------------------------------------------------------; Callable references — a function named without being called; ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.pyindex cd6d15340..9a1328795 100644--- a/packages/core/src/repowise/core/upgrade/version.py+++ b/packages/core/src/repowise/core/upgrade/version.py@@ -89,6 +89,8 @@ 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.+#: A Kotlin call chained on a call (``a.b().c()``) is a call site and carries+#: that inner call.#: 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 andiff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.pyindex ceffdd8af..5b393f329 100644--- a/tests/unit/ingestion/test_return_type_chain_resolution.py+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py@@ -216,7 +216,7 @@ def test_unbound_global_return_type_preserves_legacy_fallback(def test_only_audited_lanes_are_enabled_by_default() -> None:assert (- frozenset({"cpp", "csharp", "dart", "go", "java", "python"})+ frozenset({"cpp", "csharp", "dart", "go", "java", "kotlin", "python"})== PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES)@@ -1022,3 +1022,128 @@ def test_kotlin_return_type_an_external_import_names_is_not_the_repo_class(assert ("Use.kt::Socket::source" in callees) == (not imported)+++_KOTLIN_CHAINS = (+ "class Request {\n fun send(): Int = 0\n}\n"+ "class Other {\n fun send(): Int = 0\n}\n"+ "class Client {\n"+ " fun request(): Request = Request()\n"+ " fun mk(a: Int): Request = Request()\n"+ " fun mk(a: String): Other = Other()\n"+ " fun <T> gen(): T = TODO()\n"+ "}\n"+ "class Response {\n"+ " class Builder {\n"+ " fun setHeaders(h: String): Builder = this\n"+ " fun makeUnsafe(): Builder = this\n"+ " fun build(): Response = Response()\n"+ " }\n"+ "}\n"+ "fun Request.extra(): Int = 0\n"+ "class Use {\n fun go(client: Client) {\n{body}\n }\n}\n"+)+++def _kotlin_chain_callees(tmp_path: Path, body: str) -> set[str]:+ """Callees of every call in *body*, held in ``Use.go``."""+ text = _KOTLIN_CHAINS.replace("{body}", body)+ parsed = _parse(tmp_path, "a.kt", "kotlin", text)+ resolver = CallResolver(parsed, {"a.kt": set()})+ return {+ rc.callee_id+ for rc in resolver.resolve_file("a.kt", parsed["a.kt"].calls)+ if rc.caller_id.endswith("::go")+ }+++ ("body", "expected"),+ [+ ("client.request().send()", {"a.kt::Client::request", "a.kt::Request::send"}),+ ("client.request()?.send()", {"a.kt::Client::request", "a.kt::Request::send"}),+ (+ "Response.Builder()\n .setHeaders(\"a\")\n .makeUnsafe()\n .build()",+ {+ "a.kt::Response::Builder",+ "a.kt::Builder::setHeaders",+ "a.kt::Builder::makeUnsafe",+ "a.kt::Builder::build",+ },+ ),+ ("Response.Builder().build()", {"a.kt::Response::Builder", "a.kt::Builder::build"}),+ ],+)+def test_kotlin_call_chained_on_a_call_takes_the_type_the_inner_call_returns(+ tmp_path: Path, body: str, expected: set[str]+) -> None:+ assert _kotlin_chain_callees(tmp_path, body) == expected+++def test_kotlin_chained_call_reaches_an_extension_on_the_returned_type(tmp_path: Path) -> None:+ callees = _kotlin_chain_callees(tmp_path, "client.request().extra()")++ assert any(callee.endswith("::extra") for callee in callees)+++ "body",+ [+ "client.mk(1).send()", # overloads of one arity that return different types+ "client.gen().send()", # a type parameter is no class+ "client.request().let { it }.send()", # a scope function is external+ "client.request().apply { }.send()",+ "remote.fetch().send()", # the head is not declared in the repo+ "remote.fetch()?.send()",+ ],+)+def test_kotlin_chained_call_without_a_typed_inner_call_binds_nothing(+ tmp_path: Path, body: str+) -> None:+ callees = _kotlin_chain_callees(tmp_path, body)++ assert not {callee for callee in callees if callee.endswith("::send")}+++ ("body", "inner"),+ [+ ("client.request().send()", ("request", "client", 0)),+ ("client.request()?.send()", ("request", "client", 0)),+ ("client.mk(1).send()", ("mk", "client", 1)),+ ("Response.Builder().build()", ("Builder", "Response", 0)),+ ("this.request().send()", ("request", "this", 0)),+ ("make().send()", ("make", None, 0)),+ ],+)+def test_kotlin_outer_call_of_a_chain_is_a_site_carrying_its_inner_call(+ tmp_path: Path, body: str, inner: tuple[str, str | None, int]+) -> None:+ text = _KOTLIN_CHAINS.replace("{body}", body)+ parsed = _parse(tmp_path, "a.kt", "kotlin", text)+ outer = next(c for c in parsed["a.kt"].calls if c.receiver_call and c.target_name != "extra")++ assert (+ outer.receiver_name,+ outer.receiver_call.target_name,+ outer.receiver_call.receiver_name,+ outer.receiver_call.argument_count,+ ) == (None, *inner)+++ "body",+ [+ "a.b.request().send()", # a dotted path is not a receiver the resolver can type+ "client.request()!!.send()",+ "client.request().let { it }.send()",+ "client.request() { }.send()",+ ],+)+def test_kotlin_chain_whose_inner_call_cannot_be_described_is_not_a_site(+ tmp_path: Path, body: str+) -> None:+ text = _KOTLIN_CHAINS.replace("{body}", body)+ parsed = _parse(tmp_path, "a.kt", "kotlin", text)++ assert not [c for c in parsed["a.kt"].calls if c.target_name == "send"]