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 or Swift property initialised with a constructor (#3789)

Yunus Ozenc9a4f7f6cf2d
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 6316d6fc8..738f13782 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -215,7 +215,8 @@ _KT_ANNOTATED = re.compile(
# a `Builder`); `_PY_CONSTRUCTED` does not refuse one yet. Ceiling: `[^()]*`
# cannot cross a nested call, so `Foo(bar(1)).baz()` is still typed.
_KT_CONSTRUCTED = re.compile(
- r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)"
+ r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*(?P<closer>=)\s*(?P<type>[A-Z]\w*)\s*"
+ r"\((?![^()]*\)\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
@@ -244,7 +245,8 @@ _SWIFT_ANNOTATED = re.compile(
# `_KT_CONSTRUCTED` gives: `let x = Foo.bar()` is a call on a class, and
# `let x = Builder().build()` makes `x` whatever `build()` returns.
_SWIFT_CONSTRUCTED = re.compile(
- r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)"
+ r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\s*(?P<closer>=)\s*(?P<type>[A-Z]\w*)\s*"
+ r"\((?![^()]*\)\s*\.)"
)
# Dart writes the C family's `Type name`, plus a nullable `Api? api` and a named
@@ -992,6 +994,60 @@ def _inside_parentheses(cleaned: str) -> Callable[[int], bool]:
return inside
+# Kotlin and Swift run code at class scope that is not a function: an ``init``
+# block, a lambda or closure a property holds. A declaration there is a local
+# of that block, so only one directly in a type's body may be a field.
+_TYPE_BODY_SCOPED_LANGUAGES = frozenset({"kotlin", "swift"})
+_BRACE = re.compile(r"[{};]")
+# A function, accessor or initialiser declared after a bodiless type.
+_CODE_HEADER = re.compile(r"\b(?:fun|func|init|get|set)\b")
+_TYPE_HEADER = re.compile(r"\b(?:class|object|interface|struct|enum|extension|protocol|actor)\b")
+
+
+def _opens_type_body(header: str) -> bool:
+ """Does a ``{`` after *header* open a type's body?
+
+ The last type keyword decides, unless an expression leads into it:
+ ``val f = object : T {`` is an anonymous object, not a declared type.
+ """
+ keywords = list(_TYPE_HEADER.finditer(header))
+ if not keywords:
+ return False
+ before = header[: keywords[-1].start()].rstrip()
+ after = header[keywords[-1].end() :]
+ return not before.endswith(("=", "(", ",", "return")) and not _CODE_HEADER.search(after)
+
+
+def _in_type_body(cleaned: str) -> Callable[[int], bool]:
+ """Is the innermost ``{`` open at an offset of *cleaned* a type's body (or none)?
+
+ None counts: a primary constructor's ``val`` parameters sit before any brace.
+
+ A brace opens a type body when the text since the last ``{``, ``}`` or
+ ``;`` declares a type (see ``_opens_type_body``), so ``val f = {`` and
+ ``init {`` are not one. Strings are not skipped.
+ """
+ offsets: list[int] = []
+ innermost: list[bool] = []
+ stack: list[bool] = []
+ segment_start = 0
+ for match in _BRACE.finditer(cleaned):
+ char = match.group()
+ if char == "{":
+ stack.append(_opens_type_body(cleaned[segment_start : match.start()]))
+ elif char == "}" and stack:
+ stack.pop()
+ segment_start = match.end()
+ offsets.append(match.start())
+ innermost.append(stack[-1] if stack else True)
+
+ def inside(offset: int) -> bool:
+ index = bisect_left(offsets, offset) - 1
+ return index < 0 or innermost[index]
+
+ return inside
+
+
def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
"""Every declaration *text* makes, in line order."""
patterns = _LANGUAGE_PATTERNS.get(language)
@@ -1008,6 +1064,7 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
resolved: dict[str, tuple[str | None, bool]] = {}
found: list[Declaration] = []
inside = _inside_parentheses(cleaned) if language in _PARAMETERS_AT_CLASS_SCOPE else None
+ in_type_body = _in_type_body(cleaned) if language in _TYPE_BODY_SCOPED_LANGUAGES else None
for pattern in patterns:
for match in pattern.finditer(cleaned):
if pattern is _KT_CONSTRUCTED_LAMBDA and not _ends_statement(
@@ -1030,6 +1087,8 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
closer = ""
if inside is not None and inside(match.start()):
closer = ""
+ if in_type_body is not None and not in_type_body(match.start()):
+ closer = ""
found.append(
Declaration(
bisect_right(starts, match.start()),
diff --git a/tests/unit/ingestion/test_constructed_property_types.py b/tests/unit/ingestion/test_constructed_property_types.py
new file mode 100644
index 000000000..6599d4aef
--- /dev/null
+++ b/tests/unit/ingestion/test_constructed_property_types.py
@@ -0,0 +1,110 @@
+"""A Kotlin or Swift property initialised with a constructor types its calls (#3752).
+
+``private val store = Store()`` / ``let store = Store()`` at class scope is a
+field of type ``Store``, as the spelled-out ``val store: Store = Store()`` is.
+A declaration in code that runs at class scope without being a method, an
+``init`` block or a lambda / closure a property holds, is a local of that block
+and never a field.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import parse_file
+
+_KOTLIN = (
+ "class Store {\n fun current() {}\n}\n"
+ "class Builder {\n fun build(): Other = Other()\n}\n"
+ "class Other {\n fun current() {}\n}\n"
+ "class Use {\n{decl}\n fun go() {\n store.current()\n }\n}\n"
+)
+_SWIFT = (
+ "class Store {\n func current() {}\n}\n"
+ "class Builder {\n func build() -> Other { return Other() }\n}\n"
+ "class Other {\n func current() {}\n}\n"
+ "class Use {\n{decl}\n func go() {\n store.current()\n }\n}\n"
+)
+_SOURCES = {"kotlin": ("a.kt", _KOTLIN), "swift": ("a.swift", _SWIFT)}
+
+
+def _callees(tmp_path: Path, language: str, text: str) -> set[str]:
+ """The ``current`` methods the file's calls reach."""
+ path = _SOURCES[language][0]
+ (tmp_path / path).write_text(text, encoding="utf-8")
+ info = FileInfo(
+ path=path,
+ abs_path=str(tmp_path / path),
+ language=language,
+ size_bytes=len(text),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = {path: parse_file(info, text.encode("utf-8"))}
+ resolver = CallResolver(parsed, {path: set()}, repo_path=str(tmp_path))
+ return {
+ rc.callee_id
+ for rc in resolver.resolve_file(path, parsed[path].calls)
+ if rc.callee_id.endswith("::current")
+ }
+
+
+def _current_callees(tmp_path: Path, language: str, decl: str) -> set[str]:
+ return _callees(tmp_path, language, _SOURCES[language][1].replace("{decl}", decl))
+
+
+ ("language", "decl"),
+ [
+ ("kotlin", " private val store = Store()"),
+ ("kotlin", " var store = Store()"),
+ ("swift", " let store = Store()"),
+ ("swift", " var store = Store()"),
+ ],
+)
+def test_a_constructed_property_types_its_calls(tmp_path: Path, language: str, decl: str) -> None:
+ path = _SOURCES[language][0]
+ assert _current_callees(tmp_path, language, decl) == {f"{path}::Store::current"}
+
+
+ ("language", "decl"),
+ [
+ # A chain is not a construction, at class scope as in a body.
+ ("kotlin", " private val store = Builder().build()"),
+ ("swift", " let store = Builder().build()"),
+ # A local of a block that runs at class scope is no field.
+ ("kotlin", " val handler = { val store = Store() }"),
+ ("kotlin", " val handler = {\n val store = Store()\n }"),
+ ("kotlin", " init {\n val store = Store()\n }"),
+ (
+ "swift",
+ " lazy var h: Int = {\n let store = Store()\n return 1\n }()",
+ ),
+ ],
+)
+def test_no_field_without_a_class_scope_construction(
+ tmp_path: Path, language: str, decl: str
+) -> None:
+ assert _current_callees(tmp_path, language, decl) == set()
+
+
+def test_a_primary_constructor_property_is_still_a_field(tmp_path: Path) -> None:
+ text = _KOTLIN.replace("class Use {\n{decl}\n", "class Use(private val store: Store) {\n")
+ assert _callees(tmp_path, "kotlin", text) == {"a.kt::Store::current"}
+
+
+def test_a_local_still_shadows_the_property(tmp_path: Path) -> None:
+ text = _KOTLIN.replace("{decl}", " private val store = Store()").replace(
+ " store.current()", " val store = Other()\n store.current()"
+ )
+ assert _callees(tmp_path, "kotlin", text) == {"a.kt::Other::current"}