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): type Kotlin constructor properties and Swift stored properties as receivers (#3609)

Swati Ahuja7f2a66284ae7
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 10b781c8b..6c32dae09 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -372,7 +372,9 @@ class ReceiverTypingMixin:
A local shadows a field, so the body answers first and its answer
stands — including when that answer is "declared twice, no usable
type". Only a name the body never mentions reaches class scope, and
- only a name neither binds reaches module scope.
+ only a name neither binds reaches module scope. A name the body binds
+ with no type it can read (`{ api -> api.m() }`) is still a local, so it
+ refuses the field too.
"""
body_types = self._declared_types_in(file_path, caller_id, language)
# A builtin type answers only when nothing else does, so a local
@@ -387,7 +389,9 @@ class ReceiverTypingMixin:
fields = self._field_types_in(file_path, language).get(class_id, {})
field = fields.get(receiver_name)
if receiver_name in fields and not (builtin_local and external_type_name(field)):
- return field, "field"
+ bound = self._bound_names_in(file_path, caller_id, language)
+ if builtin_local or receiver_name not in bound:
+ return field, "field"
if builtin_local:
return declared, "body"
# Third scope: a module-level def a framework decorator turned into an
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 81cef27ba..4c3bbeef7 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -482,6 +482,47 @@ def _python_target_bindings(cleaned: str) -> set[tuple[int, str]]:
BINDING_LANGUAGES = frozenset({"javascript", "python", "typescript"})
_BINDING_SCAN_AS = {"javascript": "typescript"}
+# Names a body binds whatever their type: an untyped local, a loop variable, a
+# lambda or closure parameter. The scan sees only some of them, so these never
+# prove a name unbound; they only refuse a field of the same name, which class
+# scope would otherwise answer for (`{ api -> api.m() }` is not the field).
+# `(named, listed)` shapes; a lambda's list stays on its opening line.
+_JAVA_LAMBDA = (
+ re.compile(r"(?<![\w.])var\s+(?P<name>[a-z_]\w*)"),
+ re.compile(r"(?<![\w.])(?P<name>[a-z_]\w*)\s*->"),
+), (re.compile(r"\((?P<lhs>[\w\s,]*)\)\s*->"),)
+_LOCAL_NAME_SHAPES: dict[str, tuple[tuple[re.Pattern[str], ...], ...]] = {
+ "csharp": (
+ (
+ re.compile(r"(?<![\w.])var\s+(?P<name>[a-z_]\w*)"),
+ re.compile(r"(?<![\w.])(?P<name>[a-z_]\w*)\s*=>"),
+ ),
+ (re.compile(r"\((?P<lhs>[\w\s,]*)\)\s*=>"),),
+ ),
+ "java": _JAVA_LAMBDA,
+ "kotlin": (
+ (
+ re.compile(r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)"),
+ re.compile(r"\bfor\s*\(\s*(?P<name>[a-z_]\w*)\s+in\b"),
+ ),
+ (re.compile(r"\{[ \t]*(?P<lhs>[\w \t,:?()]*?)->"),),
+ ),
+ "swift": (
+ # `guard let client else` and `if let client = self.client {` unwrap
+ # the field itself, so the name keeps the field's type.
+ (
+ re.compile(
+ r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\b"
+ r"(?!\s*(?:=\s*(?:self\.)?(?P=name)\s*)?(?:[,{]|else\b))"
+ ),
+ ),
+ (
+ re.compile(r"\{[ \t]*(?:\[[^\]\n]*\][ \t]*)?(?P<lhs>[\w \t,:?()]*?)[ \t]+in\b"),
+ re.compile(r"\bfor\s+(?:case\s+(?:let\s+)?)?(?P<lhs>\([^()\n]*\)|[a-z_]\w*)\s+in\b"),
+ ),
+ ),
+}
+
def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:
"""Every ``(line, name)`` *text* binds, in line order."""
@@ -494,12 +535,15 @@ def scan_binding_positions(text: str, language: str) -> tuple[tuple[int, int, st
Ceiling: a block comment earlier on the same line shifts the column, since
comments are blanked without keeping their width.
"""
- if language not in BINDING_LANGUAGES:
+ local = _LOCAL_NAME_SHAPES.get(language)
+ if language not in BINDING_LANGUAGES and local is None:
return ()
language = _BINDING_SCAN_AS.get(language, language)
cleaned = _without_comments(text, language)
starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
- if language == "typescript":
+ if local is not None:
+ found = _named_bindings(local[0], cleaned) | _listed_bindings(local[1], _PY_NAME, cleaned)
+ elif language == "typescript":
found = _named_bindings(_TS_BINDINGS, cleaned)
found |= _listed_bindings(_TS_TARGET_LISTS, _TS_IDENTIFIER, cleaned)
else:
@@ -668,9 +712,14 @@ class Declaration(NamedTuple):
_FIELD_CLOSERS = frozenset({";", "="})
# Where a class-scope annotation may end its line: Python's ``x: T`` and a
-# semicolon-free TypeScript ``x: T`` are fields too.
+# semicolon-free TypeScript ``x: T`` are fields too. Kotlin and Swift keep a
+# closer only on a `val`/`var`/`let` match, so no parameter reaches here: a
+# Kotlin constructor property (`class R @Inject constructor(private val api:
+# Api)`) closes on `,` or `)`, a Swift computed property on `{`.
_LANGUAGE_FIELD_CLOSERS: dict[str, frozenset[str]] = {
+ "kotlin": frozenset({"=", "\n", ",", ")"}),
"python": frozenset({"=", "\n"}),
+ "swift": frozenset({"=", "\n", "{"}),
"typescript": frozenset({";", "=", "\n"}),
}
diff --git a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
index 8365e7fb3..d819d4e09 100644
--- a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
@@ -65,10 +65,15 @@
; 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.
+; instead of a second pattern. ``this.field.method()`` captures the field, as
+; java.scm does, so a constructor property types it.
(call_expression
(navigation_expression
- [(identifier) (this_expression)] @call.receiver
+ [
+ (identifier) @call.receiver
+ (this_expression) @call.receiver
+ (navigation_expression (this_expression) (identifier) @call.receiver)
+ ]
(identifier) @call.target
)
(value_arguments) @call.arguments
diff --git a/packages/core/src/repowise/core/ingestion/queries/swift.scm b/packages/core/src/repowise/core/ingestion/queries/swift.scm
index 2092227a6..b86e1b240 100644
--- a/packages/core/src/repowise/core/ingestion/queries/swift.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/swift.scm
@@ -82,9 +82,16 @@
; Member call: obj.method(args) — and self-dispatch: self.method(args).
; Swift spells it ``self``, which the resolver treats identically to ``this``.
; See typescript.scm for why this is an alternation rather than a second pattern.
+; ``self.field.method()`` captures the field, as java.scm does.
(call_expression
(navigation_expression
- [(simple_identifier) (self_expression)] @call.receiver
+ [
+ (simple_identifier) @call.receiver
+ (self_expression) @call.receiver
+ (navigation_expression
+ (self_expression)
+ (navigation_suffix (simple_identifier) @call.receiver))
+ ]
(navigation_suffix
(simple_identifier) @call.target
)
diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.py
index d58f87f16..bac5159a3 100644
--- a/tests/unit/ingestion/test_call_resolver_strategies.py
+++ b/tests/unit/ingestion/test_call_resolver_strategies.py
@@ -420,6 +420,124 @@ class TestFieldTypedReceiver:
)
assert not [e for e in _edges(parsed, tmp_path) if e[3].startswith("receiver_field_")]
+ def test_a_kotlin_constructor_property_types_its_receiver(self, tmp_path: Path) -> None:
+ """Hilt's `@Inject constructor(private val api: Api)`, read bare and through `this`."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "app/Repo.kt": (
+ "kotlin",
+ "package app\n\nclass Repo @Inject constructor(\n"
+ " private val api: Api,\n val dao: Dao\n) {\n"
+ " fun load() {\n api.fetch()\n this.dao.read()\n }\n}\n",
+ ),
+ "app/Api.kt": (
+ "kotlin",
+ "package app\n\nclass Api {\n fun fetch() {}\n}\n"
+ "class Dao {\n fun read() {}\n}\n",
+ ),
+ },
+ )
+ edges = _edges(parsed, tmp_path)
+ for callee in ("app/Api.kt::Api::fetch", "app/Api.kt::Dao::read"):
+ assert ("app/Repo.kt::Repo::load", callee, 0.90, "receiver_field_same_package") in edges
+
+ def test_a_swift_stored_property_types_its_receiver(self, tmp_path: Path) -> None:
+ """An init-assigned `let`, read bare and through `self`."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "Repo.swift": (
+ "swift",
+ "final class Repo {\n private let api: Api\n var dao: Dao\n\n"
+ " init(api: Api, dao: Dao) {\n self.api = api\n"
+ " self.dao = dao\n }\n\n"
+ " func load() {\n api.fetch()\n self.dao.read()\n }\n}\n",
+ ),
+ "Api.swift": (
+ "swift",
+ "final class Api {\n func fetch() {}\n}\n"
+ "final class Dao {\n func read() {}\n}\n",
+ ),
+ },
+ )
+ edges = _edges(parsed, tmp_path)
+ for callee in ("Api.swift::Api::fetch", "Api.swift::Dao::read"):
+ assert ("Repo.swift::Repo::load", callee, 0.75, "receiver_field_global") in edges
+
+ @pytest.mark.parametrize(
+ ("rel", "lang", "source", "method"),
+ [
+ (
+ "Repo.kt",
+ "kotlin",
+ "class Repo(private val api: Api) {\n"
+ " fun a() { api.nothing() }\n"
+ " fun b(items: List<X>) { items.forEach { api -> api.nothing() } }\n"
+ " fun c() { val api = make()\n api.nothing() }\n}\n"
+ "class Api { fun nothing() {} }\n",
+ "nothing",
+ ),
+ (
+ "Repo.swift",
+ "swift",
+ "final class Repo {\n private let api: Api\n"
+ " func a() { api.nothing() }\n"
+ " func b(items: [X]) { items.forEach { api in api.nothing() } }\n"
+ " func c() { let api = make()\n api.nothing() }\n}\n"
+ "final class Api { func nothing() {} }\n",
+ "nothing",
+ ),
+ (
+ "Repo.java",
+ "java",
+ "class Repo {\n private final Api api = new Api();\n"
+ " void a() { api.nothing(); }\n"
+ " void b(List<X> items) { items.forEach(api -> api.nothing()); }\n"
+ " void c() { var api = make(); api.nothing(); }\n}\n"
+ "class Api { void nothing() {} }\n",
+ "nothing",
+ ),
+ (
+ "Repo.cs",
+ "csharp",
+ "class Repo {\n private readonly Api api;\n"
+ " void A() { api.Nothing(); }\n"
+ " void B(List<X> items) { items.ForEach(api => api.Nothing()); }\n"
+ " void C() { var api = Make(); api.Nothing(); }\n}\n"
+ "class Api { public void Nothing() {} }\n",
+ "Nothing",
+ ),
+ ],
+ )
+ def test_an_untyped_local_or_lambda_parameter_shadows_the_field(
+ self, tmp_path: Path, rel: str, lang: str, source: str, method: str
+ ) -> None:
+ """`{ api -> api.m() }` names the lambda's parameter, not the field.
+
+ Only the field origin is asserted: Java's same-file name tier still
+ binds `api.nothing()` by name alone, which is not this scope's doing.
+ """
+ edges = _edges(_parse_all(tmp_path, {rel: (lang, source)}), tmp_path)
+ callers = {
+ e[0].rsplit("::", 1)[-1]
+ for e in edges
+ if e[1] == f"{rel}::Api::{method}" and e[3].startswith("receiver_field_")
+ }
+ assert callers == {"a" if lang != "csharp" else "A"}
+
+ def test_a_swift_optional_binding_of_the_field_keeps_it(self, tmp_path: Path) -> None:
+ """`guard let client else` unwraps the field itself, not a new local."""
+ source = (
+ "final class Repo {\n var client: Api?\n"
+ " func a() { guard let client else { return }\n client.nothing() }\n"
+ " func b() { if let client = self.client { client.nothing() } }\n}\n"
+ "final class Api { func nothing() {} }\n"
+ )
+ edges = _edges(_parse_all(tmp_path, {"Repo.swift": ("swift", source)}), tmp_path)
+ callers = {e[0] for e in edges if e[3].startswith("receiver_field_")}
+ assert callers == {"Repo.swift::Repo::a", "Repo.swift::Repo::b"}
+
def test_a_nested_class_field_types_its_receiver(self, tmp_path: Path) -> None:
"""A nested class's id carries its outer class; its methods' ids do not."""
parsed = _parse_all(
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index 54b056621..75bfe630e 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -30,7 +30,7 @@ def fields(source: str, language: str, methods: list[tuple[int, int]]) -> dict[s
"""One class spanning the whole text, with *methods* as its bodies."""
lines = source.count("\n") + 1
return types_by_class(
- scan_declarations(source, language), {"f.cs::C": (1, lines)}, methods
+ scan_declarations(source, language), {"f.cs::C": (1, lines)}, methods, language
).get("f.cs::C", {})
@@ -407,6 +407,27 @@ class TestKotlinFieldScope:
source = "class C {\n fun run(timeout: Duration = d) { }\n}"
assert fields(source, "kotlin", []) == {}
+ def test_an_injected_constructor_property_is_a_field(self) -> None:
+ """The Hilt shape: each property closes on `,` or `)`, not `=`."""
+ source = (
+ "class Repo @Inject constructor(\n private val api: Api,\n"
+ " val dao: Dao\n) {\n fun f() { api.get() }\n}"
+ )
+ found = fields(source, "kotlin", [(5, 5)])
+ assert (found["api"], found["dao"]) == ("Api", "Dao")
+
+ def test_a_one_line_constructor_property_is_a_field(self) -> None:
+ source = "class Repo(private val api: Api) {\n fun f() { api.get() }\n}"
+ assert fields(source, "kotlin", [(2, 2)])["api"] == "Api"
+
+ def test_a_plain_constructor_parameter_is_not_a_field(self) -> None:
+ source = "class Repo(api: Api, other: Dao) {\n fun f() { }\n}"
+ assert fields(source, "kotlin", [(2, 2)]) == {}
+
+ def test_an_uninitialised_property_is_a_field(self) -> None:
+ source = "abstract class Repo {\n abstract val api: Api\n}"
+ assert fields(source, "kotlin", [])["api"] == "Api"
+
class TestSwiftShapes:
@@ -506,6 +527,18 @@ class TestSwiftRefusals:
)
assert fields(source, "swift", [(3, 5)])["logger"] == "Logger"
+ def test_an_init_assigned_stored_property_is_a_field(self) -> None:
+ """`let api: Api` has no initialiser; `init` assigns it, so it ends its line."""
+ source = (
+ "final class Repo {\n private let api: Api\n"
+ " init(api: Api) { self.api = api }\n func run() { api.get() }\n}"
+ )
+ assert fields(source, "swift", [(4, 4)]) == {"api": "Api"}
+
+ def test_a_computed_property_is_a_field(self) -> None:
+ source = "class C {\n var store: Store { Store.shared }\n}"
+ assert fields(source, "swift", [])["store"] == "Store"
+
class TestGoShapes:
"""Go writes ``name T``, which is the reverse of every other shape here.