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): never offer a Kotlin or Swift property as a bare call's callee (#3680)

Swati Ahuja80e8e60bdc67
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 4a26abd85..6eb52b4cb 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -49,6 +49,7 @@ from .language_data import (
get_external_receiver_types,
get_external_return_types,
)
+from .languages.receiver_types import holds_function
from .models import (
CallReceiver,
CallSite,
@@ -139,6 +140,16 @@ _MAX_ANCESTOR_EXPAND_DEPTH = 3
# ``property`` is the only kind that means "data member" and nothing else; every
# other language spells its fields ``variable``, indistinguishable by kind.
_NON_CALLABLE_KINDS = frozenset({"property"})
+# Languages whose ``variable`` is always a property (`val`/`var`/`let`): a data
+# member. Calling one invokes the value it holds, which is not this symbol.
+_PROPERTY_VARIABLE_LANGUAGES = frozenset({"kotlin", "swift"})
+
+
+def _is_data_member(sym: Symbol) -> bool:
+ if sym.kind in _NON_CALLABLE_KINDS:
+ return True
+ return sym.kind == "variable" and sym.language in _PROPERTY_VARIABLE_LANGUAGES
+
# A Rust ``impl`` or Swift ``extension`` block is named for the type it adds
# members to and declares nothing itself, so no bare name means it: ``Text(..)``
@@ -458,6 +469,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Held as an id set rather than a full id->kind map: it is the only
# kind question asked of it and the set is small.
self._non_callable_ids: set[str] = set()
+ self._callable_ids: set[str] = set()
+ # The lines of the file being indexed, for its property declarations.
+ self._indexed_lines: tuple[str, list[str]] = ("", [])
# C/C++ symbols with internal linkage; see ``_reachable_by_name``.
self._tu_local_ids: set[str] = set()
self._property_accessor_ids: set[str] = set()
@@ -704,8 +718,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
def _index_globally(self, path: str, sym: Symbol, index_id: str) -> None:
if _has_internal_linkage(path, sym):
self._tu_local_ids.add(index_id)
- if sym.kind in _NON_CALLABLE_KINDS:
- self._non_callable_ids.add(index_id)
+ self._record_callability(path, sym, index_id)
# A getter and its setter are two declarations under one id, which reads
# as an overload set and is not one: the name is an attribute.
if is_property_accessor(sym.decorators):
@@ -715,6 +728,27 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if not (bodiless_method or sym.kind in _EXTENSION_KINDS or is_anonymous_member(sym)):
self._global_symbols[sym.name].append(index_id)
+ def _record_callability(self, path: str, sym: Symbol, index_id: str) -> None:
+ """Mark *index_id* a data member's, unless anything callable shares it.
+
+ A Kotlin `val isDark` and `fun isDark()` in one file are one id.
+ """
+ if _is_data_member(sym) and not self._holds_function(path, sym):
+ if index_id not in self._callable_ids:
+ self._non_callable_ids.add(index_id)
+ else:
+ self._callable_ids.add(index_id)
+ self._non_callable_ids.discard(index_id)
+
+ def _holds_function(self, path: str, sym: Symbol) -> bool:
+ """Is property *sym* declared with a function value (`val f: () -> Unit`)?"""
+ if sym.kind != "variable" or sym.language not in _PROPERTY_VARIABLE_LANGUAGES:
+ return False
+ if self._indexed_lines[0] != path:
+ self._indexed_lines = (path, self._text_of(path).splitlines())
+ lines = self._indexed_lines[1][sym.start_line - 1 : max(sym.end_line, sym.start_line)]
+ return holds_function("\n".join(lines), sym.name, sym.language)
+
def _index_overload_sets(self, parsed: ParsedFile) -> dict[str, str]:
"""Record *parsed*'s overload sets; ``{member id: representative}``.
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 f90f0d962..871be4183 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -26,6 +26,7 @@ from bisect import bisect_left, bisect_right
from collections.abc import Callable, Iterable, Mapping
from typing import NamedTuple
+from ..framework_routes import scan_code
from ..language_data import get_builtin_types
from ..type_names import (
bare_type_name,
@@ -607,6 +608,26 @@ _KT_INVOKABLE = (
),
re.compile(r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*=\s*\{"),
)
+_SWIFT_INVOKABLE = re.compile(
+ r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\s*(?::\s*(?:@\w+\s+)*\(|=\s*\{)"
+)
+
+
+def holds_function(declaration: str, name: str, language: str) -> bool:
+ """Does Kotlin or Swift *declaration* give property *name* a function value?
+
+ Read with comments and string literals blanked, so text inside them never
+ looks like a function type.
+ """
+ code = [" "] * len(declaration)
+ quotes = "\"'" if language == "kotlin" else '"'
+ for index, char, _ in scan_code(declaration, quotes=quotes, text_blocks=True):
+ code[index] = char
+ masked = "".join(code)
+ shapes = _KT_INVOKABLE if language == "kotlin" else (_SWIFT_INVOKABLE,)
+ return any(match.group("name") == name for shape in shapes for match in shape.finditer(masked))
+
+
# Where a declared parameter list opens. Dart's header is told from a call by
# the body that follows its list (`_DART_BODY`).
_GENERIC = r"(?:<[^<>\n]*(?:<[^<>\n]*>[^<>\n]*)*>)?"
diff --git a/tests/unit/ingestion/test_bare_name_index_kinds.py b/tests/unit/ingestion/test_bare_name_index_kinds.py
index 2a84df800..18348d668 100644
--- a/tests/unit/ingestion/test_bare_name_index_kinds.py
+++ b/tests/unit/ingestion/test_bare_name_index_kinds.py
@@ -173,6 +173,74 @@ class TestThePredicateStaysNarrow:
assert [e for e in _edges(parsed, tmp_path) if e[1] == "util.ts::doThing"]
+class TestKotlinAndSwiftPropertiesAreNotCallable:
+ """A Kotlin or Swift ``variable`` is a property: ``url("...")`` in a Ktor
+ DSL block is not the repo's ``private var url``."""
+
+ def test_a_kotlin_property_does_not_answer_a_bare_name(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "Builder.kt": (
+ "kotlin",
+ "class Builder {\n private var url: String = \"\"\n}\n",
+ ),
+ "Client.kt": ("kotlin", "fun main() {\n url(\"https://x\")\n}\n"),
+ },
+ )
+ assert _kinds(parsed, "url") == {"variable"}
+ assert not [e for e in _edges(parsed, tmp_path) if e[1].endswith("::url")]
+
+ def test_a_swift_property_does_not_answer_a_bare_name(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "model.swift": ("swift", "struct Model {\n var title: String = \"\"\n}\n"),
+ "view.swift": ("swift", "func render() {\n title(\"x\")\n}\n"),
+ },
+ )
+ assert _kinds(parsed, "title") == {"variable"}
+ assert not [e for e in _edges(parsed, tmp_path) if e[1].endswith("::title")]
+
+ def test_a_function_shares_its_id_with_a_property(self, tmp_path: Path) -> None:
+ """``val isDark`` and ``fun isDark()`` in one file are one id, still callable."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "Theme.kt": (
+ "kotlin",
+ "package a\n\nval isDark: Boolean = false\nfun isDark(): Boolean = true\n",
+ ),
+ "Use.kt": ("kotlin", "package b\n\nfun use() {\n isDark()\n}\n"),
+ },
+ )
+ assert [e for e in _edges(parsed, tmp_path) if e[1] == "Theme.kt::isDark"]
+
+ def test_a_property_holding_a_function_stays_callable(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "Handlers.kt": ("kotlin", "package a\n\nval handler: () -> Unit = {}\n"),
+ "Use.kt": ("kotlin", "package b\n\nfun use() {\n handler()\n}\n"),
+ },
+ )
+ assert [e for e in _edges(parsed, tmp_path) if e[1] == "Handlers.kt::handler"]
+
+ def test_function_text_in_a_string_or_comment_is_no_function(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "Labels.kt": (
+ "kotlin",
+ 'package a\n\nval label: String = "x"\n// val label: () -> Unit\n'
+ 'val title = "val title = { }"\n',
+ ),
+ "Use.kt": ("kotlin", "package b\n\nfun use() {\n label()\n title()\n}\n"),
+ },
+ )
+ assert not [e for e in _edges(parsed, tmp_path) if e[1].startswith("Labels.kt::")]
+
+
def _edges_with_imports(
parsed: dict[str, ParsedFile],
tmp_path: Path,