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(ingestion): type a Kotlin local assigned from a call with a trailing lambda (#3785)

Yunus Ozen70dd489793ed
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 de5d3f25c..c9619a18e 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -217,6 +217,12 @@ _KT_ANNOTATED = re.compile(
_KT_CONSTRUCTED = re.compile(
r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)"
)
+# `val x = Foo { ... }`: a constructor whose only argument is a trailing lambda.
+# The match ends at the `{`; `scan_declarations` keeps it only when the lambda
+# ends the statement, so `Foo { }.build()` is not a `Foo`.
+_KT_CONSTRUCTED_LAMBDA = re.compile(
+ r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)[ \t]*(?=\{)"
+)
# Swift annotates after the name: `let x: Foo`, `var x: Foo` and every parameter
# spelling are `name: Type`. Anchored on the colon, not the opening bracket,
@@ -332,7 +338,7 @@ _JAVA_PATTERN_VARIABLE = re.compile(
# IMPLICIT_FIELD_LANGUAGES: a field is read through its receiver (``c.parent``),
# so it types a chain hop and never a bare name.
_GO_FAMILY = (_GO_PARAM, _GO_SHORT_DECL, _GO_VAR_DECL, _GO_FIELD, _GO_EMBEDDED_FIELD)
-_KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED)
+_KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED, _KT_CONSTRUCTED_LAMBDA)
_SWIFT_FAMILY = (_SWIFT_ANNOTATED, _SWIFT_CONSTRUCTED)
_DART_FAMILY = (_DART_TYPED, _DART_CONSTRUCTED)
_PY_FAMILY = (_PY_ANNOTATED, _PY_CONSTRUCTED, _PY_SELF_ANNOTATED, _PY_SELF_CONSTRUCTED)
@@ -1004,6 +1010,10 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
inside = _inside_parentheses(cleaned) if language in _PARAMETERS_AT_CLASS_SCOPE else None
for pattern in patterns:
for match in pattern.finditer(cleaned):
+ if pattern is _KT_CONSTRUCTED_LAMBDA and not _ends_statement(
+ cleaned, _lambda_end(cleaned, match.end()), language
+ ):
+ continue
raw = match.group("type")
if raw not in resolved:
resolved[raw] = _usable_type_name(raw, language)
@@ -1139,9 +1149,48 @@ def _call_end(text: str, index: int) -> int:
return -1
+def _lambda_end(text: str, index: int) -> int:
+ """Index just past the ``}`` closing the ``{`` at *index*, or -1."""
+ depth = 0
+ while index < len(text):
+ char = text[index]
+ if char in _QUOTES:
+ index += 1
+ while index < len(text) and text[index] != char:
+ index += 2 if char != "`" and text[index] == "\\" else 1
+ elif char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if depth == 0:
+ return index + 1
+ index += 1
+ return -1
+
+
+def _after_trailing_lambda(text: str, end: int) -> int:
+ """*end*, or past a Kotlin trailing lambda that starts on the same line.
+
+ ``f(a) { .. }`` is still the call ``f``: the lambda is its last argument.
+ """
+ brace = end
+ while brace < len(text) and text[brace] in " \t":
+ brace += 1
+ if brace < len(text) and text[brace] == "{":
+ return _lambda_end(text, brace)
+ return end
+
+
def _call_ends_statement(cleaned: str, opened: int, language: str, start: int = 0) -> bool:
"""Does the call whose ``(`` ends just before *opened* end its statement?"""
end = _call_end(cleaned, opened)
+ if end >= 0 and language == "kotlin":
+ end = _after_trailing_lambda(cleaned, end)
+ return _ends_statement(cleaned, end, language, start)
+
+
+def _ends_statement(cleaned: str, end: int, language: str, start: int = 0) -> bool:
+ """Does the expression ending at *end* end its statement (-1: it never ends)?"""
if end < 0:
return False
rest = cleaned[end:].lstrip(" \t\n" if language == "dart" else " \t")
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index a0a780fe8..769b6717d 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -744,6 +744,35 @@ class TestGoFields:
assert declared_types(body, "go") == {}
+class TestKotlinTrailingLambda:
+ """A trailing lambda is the call's last argument, not more expression (#3761)."""
+
+ def test_a_call_with_a_trailing_lambda_is_a_call_assignment(self) -> None:
+ body = 'fun f() {\n val n = build(1) { x -> println(")}") }\n n.go()\n}'
+ assert scan_call_assignments(body, "kotlin") == (CallAssignment(2, "n", None, "build"),)
+
+ def test_a_lambda_across_lines_still_ends_the_statement(self) -> None:
+ body = 'fun f() {\n val n = build("a") {\n println("x")\n }\n n.go()\n}'
+ assert [a.name for a in scan_call_assignments(body, "kotlin")] == ["n"]
+
+ def test_a_chain_after_the_lambda_is_not_the_call(self) -> None:
+ for rest in ("{ }.bar()", "{ } ?: y", "{ }\n .bar()"):
+ body = f"fun f() {{\n val n = build(1) {rest}\n}}"
+ assert scan_call_assignments(body, "kotlin") == (), rest
+
+ def test_a_constructor_with_only_a_trailing_lambda(self) -> None:
+ body = 'fun f() {\n val c = Client {\n println("}")\n }\n c.get()\n}'
+ assert declared_types(body, "kotlin")["c"] == "Client"
+
+ def test_a_constructor_lambda_followed_by_a_chain_is_not_a_construction(self) -> None:
+ body = "fun f() {\n val c = Client { }.build()\n}"
+ assert "c" not in declared_types(body, "kotlin")
+
+ def test_a_lowercase_lambda_only_call_is_not_a_construction(self) -> None:
+ body = "fun f() {\n val x = remember { Foo() }\n}"
+ assert "x" not in declared_types(body, "kotlin")
+
+
class TestGoCallAssignments:
"""``x := f(..)``: the call the resolver reads a return type from."""
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index 1412645a6..ceffdd8af 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -921,6 +921,7 @@ _KOTLIN_LOCALS = (
"class Repo {\n fun load() {}\n}\n"
"class Other {\n fun load() {}\n}\n"
"fun makeRepo(): Repo = Repo()\n"
+ "fun build(name: String, block: () -> Unit): Repo = Repo()\n"
"fun mk(a: Int): Repo = Repo()\nfun mk(a: String): Other = Other()\n"
"fun <T> gen(): T = TODO()\n"
"object Factory {\n fun other(): Other = Other()\n}\n"
@@ -960,6 +961,8 @@ def _last_line_callees(tmp_path: Path, language: str, body: str) -> set[str]:
[
("kotlin", "val r = makeRepo()\nr.load()", "a.kt::Repo::load"),
("kotlin", "val r = Factory.other()\nr.load()", "a.kt::Other::load"),
+ ("kotlin", 'val r = build("a") { }\nr.load()', "a.kt::Repo::load"),
+ ("kotlin", 'val r = build("a") {\n println("x")\n}\nr.load()', "a.kt::Repo::load"),
("swift", "let r = try makeRepo()\nr.load()", "a.swift::Repo::load"),
("swift", "let r = await Factory.other()\nr.load()", "a.swift::Other::load"),
("swift", "let r = try? makeRepo()\nr?.load()", "a.swift::Repo::load"),
@@ -985,6 +988,8 @@ def test_kotlin_and_swift_local_takes_the_type_its_call_returns(
("swift", "var r = try makeRepo()\n .other()"),
("kotlin", "val r = makeRepo()\n ?: Other()"),
("kotlin", "val r = makeRepo()\n as Other"),
+ ("kotlin", 'val r = build("a") { }.let { Other() }'),
+ ("kotlin", 'val r = build("a") { } ?: Other()'),
("swift", "let r = try makeRepo()\n as! Other"),
("swift", "let r = makeRepo() { Other() }"),
("swift", "if case let .some(r) = findRepo() {"),