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): read Kotlin calls under a unary operator or on a string literal (#4840)

Swati Ahuja0ccbbba26d2e
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
index 418450256..bf094b6a2 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
@@ -20,6 +20,7 @@ from ..languages.receiver_types import (
IMPLICIT_FIELD_LANGUAGES,
RANGE_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
+ STRING_LITERAL_TYPE,
CallAssignment,
DartCallback,
Declaration,
@@ -41,7 +42,7 @@ from ..languages.receiver_types import (
types_in_span,
unwrapped_names_in_span,
)
-from ..models import CallSite, NamedBinding, ParsedFile, Symbol
+from ..models import STRING_LITERAL_RECEIVER, CallSite, NamedBinding, ParsedFile, Symbol
from ..resolved_call import ResolvedCall
from ..return_types import declared_return_type, signature_parameter_count
from ..symbol_identity import id_segment_name
@@ -335,7 +336,8 @@ class ReceiverTypingMixin(
# tried it, so only a C# one is read further: C# spells its properties
# and many fields that way. An underscore one cannot be anything but a name.
head = receiver_name[:1]
- if not (head.islower() or head == "_" or language == "csharp"):
+ literal = receiver_name == STRING_LITERAL_RECEIVER
+ if not (head.islower() or head == "_" or literal or language == "csharp"):
return None
# Refuse before reading the file: nothing resolves unless some class
@@ -551,6 +553,8 @@ class ReceiverTypingMixin(
neither types nor binds is asked of the function around it, whose
locals it captures and whose class fields it sees.
"""
+ if receiver_name == STRING_LITERAL_RECEIVER:
+ return STRING_LITERAL_TYPE, "body", file_path
if line is not None and language == "dart":
bound, closure_type = self._callback_parameter(
file_path, caller_id, language, receiver_name, line
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 7374e5bbc..f33042518 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -402,6 +402,8 @@ EXTERNAL_TYPE_LANGUAGES = frozenset({"java"})
# a builtin-typed local still reads as a variable and types overload arguments.
_MARKED_BUILTIN_LANGUAGES = EXTERNAL_TYPE_LANGUAGES | {"kotlin", "apex"}
_EXTERNAL_TYPE = "external:"
+#: A Kotlin string literal receiver, typed as a declared ``String`` would be.
+STRING_LITERAL_TYPE = _EXTERNAL_TYPE + "String"
# A decorator that changes what the symbol it wraps *is*: `@shared_task` leaves
# no function behind, so `add.s(...)` is a method call on `Task`. A table, since
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 9abf0b6ff..d8d2d4f6f 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -350,6 +350,10 @@ class CallReceiver:
#: site may produce.
CallSiteEdgeType = Literal["calls", "references"]
+#: The ``receiver_name`` of a Kotlin call on a string literal (``"/".encodeUtf8()``):
+#: no name can be spelled this way, and receiver typing reads it as ``String``.
+STRING_LITERAL_RECEIVER = '""'
+
@dataclass
class CallSite:
diff --git a/packages/core/src/repowise/core/ingestion/parser/calls.py b/packages/core/src/repowise/core/ingestion/parser/calls.py
index d2a701bbc..1a35ac338 100644
--- a/packages/core/src/repowise/core/ingestion/parser/calls.py
+++ b/packages/core/src/repowise/core/ingestion/parser/calls.py
@@ -9,7 +9,7 @@ from tree_sitter import Node
from ..extractors import node_text
from ..language_configs import LanguageConfig
-from ..models import CallReceiver, CallSite, FileInfo, Symbol
+from ..models import STRING_LITERAL_RECEIVER, CallReceiver, CallSite, FileInfo, Symbol
from ..parser_helpers import (
_argument_literal_types,
_argument_names,
@@ -28,6 +28,8 @@ _node_text = node_text
# letter, so ``X.CONST`` is not one. Same shape as the java.scm member-type pattern.
_JAVA_MEMBER_TYPE_PATH = re.compile(r"[A-Z][A-Za-z0-9_]*(?:\.[A-Z][A-Za-z0-9_]*[a-z][A-Za-z0-9_]*)+")
+_KOTLIN_STRING_LITERALS = ("string_literal", "multiline_string_literal")
+
def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
"""Describe an inner call captured as another call's receiver.
@@ -91,6 +93,7 @@ def _kotlin_call_receiver(call: Node, src: str) -> CallReceiver | None:
return None
count = _count_arguments(arguments)
+ callee = _kotlin_operand(callee)
if callee.type == "identifier":
return CallReceiver(_node_text(callee, src).strip(), None, count)
if callee.type != "navigation_expression" or len(callee.named_children) != 2:
@@ -100,9 +103,10 @@ def _kotlin_call_receiver(call: Node, src: str) -> CallReceiver | None:
if target.type != "identifier":
return None
+ receiver = _kotlin_operand(receiver)
if receiver.type == "call_expression":
receiver_name = None
- elif receiver.type in ("identifier", "this_expression") or (
+ elif receiver.type in ("identifier", "this_expression", *_KOTLIN_STRING_LITERALS) or (
receiver.type == "navigation_expression"
and [child.type for child in receiver.named_children]
== ["this_expression", "identifier"]
@@ -116,6 +120,18 @@ def _kotlin_call_receiver(call: Node, src: str) -> CallReceiver | None:
return CallReceiver(_node_text(target, src).strip(), receiver_name, count)
+def _kotlin_operand(node: Node) -> Node:
+ """The name under a Kotlin prefix or postfix operator, else *node* itself.
+
+ tree-sitter-kotlin binds the operator before the call, so ``!a.f()`` and
+ ``a!!.f()`` put ``!a`` / ``a!!`` where the receiver goes.
+ """
+ named = node.named_children
+ if node.type == "unary_expression" and len(named) == 1 and named[0].type == "identifier":
+ return named[0]
+ return node
+
+
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"):
@@ -235,6 +251,8 @@ def _receiver_text(language: str, node: Node, src: str) -> str | None:
if language == "java" and node.type != "super" and getattr(sibling, "type", None) == "super":
# ``S.super.m()``: ``S`` qualifies the ``super`` its own pattern captures.
return None
+ if language == "kotlin" and node.type in _KOTLIN_STRING_LITERALS:
+ return STRING_LITERAL_RECEIVER
text = _node_text(node, src).strip()
if (language, node.type) not in _PATH_RECEIVERS:
return text
diff --git a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
index 79bd639a6..4b20b54a0 100644
--- a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
@@ -59,8 +59,14 @@
; Simple call: foo(args), or foo { ... } whose only argument is a trailing
; lambda: the grammar gives that form no ``value_arguments`` at all.
+; tree-sitter-kotlin binds a prefix or postfix operator before the call, so
+; ``!f(x)`` arrives as ``(!f)(x)`` and ``a!!.f()`` / ``!a.f()`` as ``(!a).f()``;
+; the operand is still the name called or the receiver.
(call_expression
- (identifier) @call.target
+ [
+ (identifier) @call.target
+ (unary_expression (identifier) @call.target)
+ ]
[
(value_arguments)
(annotated_lambda)
@@ -70,13 +76,17 @@
; Member call: obj.method(args) — and self-dispatch: this.method(args).
; See typescript.scm for why ``this`` rides an alternation in the receiver slot
; instead of a second pattern. ``this.field.method()`` captures the field, as
-; java.scm does, so a constructor property types it.
+; java.scm does, so a constructor property types it. A string literal
+; receiver (``"/".encodeUtf8()``) is typed ``String`` by the parser.
(call_expression
(navigation_expression
[
(identifier) @call.receiver
+ (unary_expression (identifier) @call.receiver)
(this_expression) @call.receiver
(navigation_expression (this_expression) (identifier) @call.receiver)
+ (string_literal) @call.receiver
+ (multiline_string_literal) @call.receiver
]
(identifier) @call.target
)
diff --git a/tests/unit/ingestion/test_kotlin_operator_call_sites.py b/tests/unit/ingestion/test_kotlin_operator_call_sites.py
new file mode 100644
index 000000000..9cafd1a46
--- /dev/null
+++ b/tests/unit/ingestion/test_kotlin_operator_call_sites.py
@@ -0,0 +1,104 @@
+"""Kotlin calls under a prefix or postfix operator, or on a string literal, are call sites.
+
+tree-sitter-kotlin binds ``!`` / ``-`` / ``!!`` before the call, so ``!g(1)``
+arrives as ``(!g)(1)`` and ``!b.h(2)`` / ``a!!.h(3)`` as ``(!b).h(2)``; the
+operand is still the callee or the receiver. A string literal receiver is a
+``String``, so only an extension on ``String`` answers it.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.models import STRING_LITERAL_RECEIVER, FileInfo
+from repowise.core.ingestion.parser import parse_file
+
+SOURCE = '''\
+package app
+
+class Account {
+ fun valid(x: Int): Boolean = true
+ fun again(): Account = this
+}
+
+class Text {
+ fun shout(): Int = 1
+}
+
+fun allowed(x: Int): Boolean = true
+fun String.slash(): Account = Account()
+
+fun unary(maybe: Account?, account: Account) {
+ if (!allowed(1)) return
+ if (!account.valid(2)) return
+ maybe!!.valid(3)
+ !account.again().valid(4)
+}
+
+fun literal() {
+ "/".slash()
+ """raw""".slash()
+ "a$x".slash().valid(5)
+ "s".shout()
+}
+'''
+
+
+def _parse(tmp_path: Path):
+ path = tmp_path / "App.kt"
+ path.write_text(SOURCE, encoding="utf-8")
+ info = FileInfo(
+ path="App.kt",
+ abs_path=str(path),
+ language="kotlin",
+ size_bytes=len(SOURCE),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return parse_file(info, SOURCE.encode("utf-8"))
+
+
+def _edges(tmp_path: Path, caller: str) -> set[tuple[str, str]]:
+ parsed = _parse(tmp_path)
+ resolver = CallResolver({"App.kt": parsed}, {"App.kt": set()}, repo_path=str(tmp_path))
+ return {
+ (rc.callee_id, rc.origin)
+ for rc in resolver.resolve_file("App.kt", parsed.calls)
+ if rc.caller_id == f"App.kt::{caller}"
+ }
+
+
+def test_operator_wrapped_calls_are_sites(tmp_path: Path) -> None:
+ sites = {(c.line, c.receiver_name, c.target_name) for c in _parse(tmp_path).calls}
+ assert {
+ (16, None, "allowed"),
+ (17, "account", "valid"),
+ (18, "maybe", "valid"),
+ (19, "account", "again"),
+ (19, None, "valid"),
+ } <= sites
+
+
+def test_operator_wrapped_calls_resolve(tmp_path: Path) -> None:
+ assert {callee for callee, _ in _edges(tmp_path, "unary")} == {
+ "App.kt::allowed",
+ "App.kt::Account::valid",
+ "App.kt::Account::again",
+ }
+
+
+def test_a_string_literal_receiver_is_a_string(tmp_path: Path) -> None:
+ sites = {(c.line, c.receiver_name, c.target_name) for c in _parse(tmp_path).calls}
+ assert (23, STRING_LITERAL_RECEIVER, "slash") in sites
+ assert (24, STRING_LITERAL_RECEIVER, "slash") in sites
+ # Only the extension on String answers; a repo class's same-named method does not.
+ assert _edges(tmp_path, "literal") == {
+ ("App.kt::slash", "receiver_extension_same_file"),
+ ("App.kt::Account::valid", "return_type_same_file"),
+ }