Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(graph): bind a bare Kotlin call to an extension only with its receiver in scope (#3681)
Swati Ahuja8d40605e9b70
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.pyindex 788f09f46..356843e71 100644--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py@@ -6,12 +6,16 @@ targets and crate roots that no import statement names.from __future__ import annotations+import refrom dataclasses import dataclass, replacefrom typing import Any-from .call_receiver_typing import _TYPE_KINDS-from .models import CallSite, ParsedFile+from .call_receiver_typing import _FUNCTION_KINDS, _TYPE_KINDS+from .lang_helpers.kotlin_lambdas import in_lambda+from .models import CallSite, ParsedFile, Symbolfrom .resolved_call import ResolvedCall+from .symbol_identity import outer_scope+from .type_names import bare_type_name, kotlin_extension_receiver@dataclass(frozen=True, slots=True)@@ -41,6 +45,14 @@ _NO_LANGUAGE_STRATEGIES = _LanguageCallStrategies()_TYPED_RECEIVER = ("_resolve_typed_receiver",)++def _gradle_script_receiver(path: str) -> str | None:+ """The ``this`` a Gradle Kotlin script's own code runs with."""+ if not path.endswith(".gradle.kts"):+ return None+ return "Settings" if path.rpartition("/")[2] == "settings.gradle.kts" else "Project"++_JVM_STRATEGIES = _LanguageCallStrategies(free=("_resolve_jvm_same_package",),member=("_resolve_jvm_receiver_same_package",),@@ -111,6 +123,9 @@ class LanguageStrategiesMixin:self._go_index: Any = Noneself._go_index_built = False+ # {Kotlin function id: the type it extends, or None}+ self._kotlin_receivers: dict[str, str | None] = {}+# JVM same-package resolution (lazy JvmWorkspaceIndex)self._jvm_index: Any = Noneself._jvm_index_built = False@@ -439,3 +454,98 @@ class LanguageStrategiesMixin:if sym_id is not None and sym_id != caller_id:return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")return None++ def _lacks_extension_receiver(self, file_path: str, call: CallSite, callee_id: str) -> bool:+ """Is *callee_id* a Kotlin extension this bare call has no receiver for?++ Written bare, ``digest(..)`` reaches ``fun AuthenticationConfig.digest``+ only where the implicit ``this`` is that type: in a member or an+ extension of it or of a subtype, or in a lambda, whose receiver+ (``routing { .. }``) a text scan cannot type and so never refuses.+ """+ receiver = self._extension_receiver(callee_id)+ if receiver is None:+ return False+ caller = self._symbols_by_id.get(call.caller_symbol_id or "")+ if receiver in self._receivers_in_scope(file_path, caller):+ return False+ return not self._call_in_lambda(file_path, call, caller)++ def _extension_receiver(self, callee_id: str) -> str | None:+ """The repo class a Kotlin extension needs as ``this``.++ None for an external receiver (``List<String>``, a library base the+ caller may extend) or an alias: no repo class says which callers+ have one, so nothing is refused.+ """+ callee = self._symbols_by_id.get(callee_id)+ if callee is None or callee.language != "kotlin" or callee.kind not in _FUNCTION_KINDS:+ return None+ receiver = self._kotlin_receiver(callee)+ return receiver if receiver in self._known_type_names else None++ def _receivers_in_scope(self, file_path: str, caller: Symbol | None) -> set[str]:+ """The bare type names ``this`` may be outside any lambda of *caller*."""+ if caller is not None:+ return self._implicit_receivers(caller)+ script = _gradle_script_receiver(file_path)+ return {script} if script else set()++ def _call_in_lambda(self, file_path: str, call: CallSite, caller: Symbol | None) -> bool:+ """Is *call* inside a lambda of *caller*? True when the text cannot tell."""+ lines = self._text_of(file_path).splitlines()+ start = caller.start_line if caller is not None else 1+ if not 1 <= start <= call.line <= len(lines):+ return True+ last = lines[call.line - 1]+ at = re.search(rf"(?<![\w.]){re.escape(call.target_name)}\b", last)+ source = "\n".join([*lines[start - 1 : call.line - 1], last[: at.start() if at else 0]])+ return in_lambda(source, caller is not None and caller.kind in _FUNCTION_KINDS)++ def _kotlin_receiver(self, symbol: Symbol) -> str | None:+ """The type a Kotlin function extends, read off its header (annotations included)."""+ if symbol.id not in self._kotlin_receivers:+ path = self._symbol_paths_by_id.get(symbol.id, "")+ lines = self._text_of(path).splitlines()[symbol.start_line - 1 : symbol.start_line + 7]+ self._kotlin_receivers[symbol.id] = kotlin_extension_receiver(+ " ".join(lines), symbol.name+ )+ return self._kotlin_receivers[symbol.id]++ def _implicit_receivers(self, caller: Symbol) -> set[str]:+ """The bare type names ``this`` may be inside *caller*."""+ extended = self._kotlin_receiver(caller) if caller.language == "kotlin" else None+ names = {extended} if extended else set()+ names.update(self._names_of_classes(self._receiver_classes(caller)))+ parsed = self._parsed_files.get(self._symbol_paths_by_id.get(caller.id, ""))+ names.update(+ bare_type_name(h.parent_name)+ for h in (parsed.heritage if parsed else ())+ if h.child_name in names+ )+ return names++ def _receiver_classes(self, caller: Symbol) -> list[str]:+ """The class whose code *caller* is, then each outer class an ``inner`` one sees."""+ if caller.kind in _TYPE_KINDS:+ class_id = caller.id+ elif caller.parent_name:+ class_id = self._caller_class_id(caller.id)+ else:+ return []+ found = []+ while (symbol := self._symbols_by_id.get(class_id)) is not None:+ found.append(class_id)+ if "inner" not in symbol.modifiers:+ break+ class_id = outer_scope(class_id)+ return found++ def _names_of_classes(self, class_ids: list[str]) -> set[str]:+ """The names of *class_ids* and of their repo ancestors."""+ return {+ symbol.name+ for class_id in class_ids+ for symbol in map(self._symbols_by_id.get, (class_id, *self._ancestors_of(class_id)))+ if symbol is not None+ }diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex b73adf7a1..92ec92165 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -1014,7 +1014,19 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):return None# --- Free function call: function() ---- return self._with_props(self._resolve_free_call(file_path, call, caller_id), call)+ return self._with_props(self._resolve_bare_call(file_path, call, caller_id), call)++ def _resolve_bare_call(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ ) -> ResolvedCall | None:+ """A receiver-less call, refused where it lands on an extension it has no receiver for."""+ hit = self._resolve_free_call(file_path, call, caller_id)+ if hit is None or call.receiver_call is not None:+ return hit+ return None if self._lacks_extension_receiver(file_path, call, hit.callee_id) else hitdef _with_props(self, res: ResolvedCall | None, call: CallSite) -> ResolvedCall | None:if res is not None and call.supplied_props is not None:diff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/kotlin_lambdas.py b/packages/core/src/repowise/core/ingestion/lang_helpers/kotlin_lambdas.pynew file mode 100644index 000000000..1dba6fcc1--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/kotlin_lambdas.py@@ -0,0 +1,79 @@+"""Is a Kotlin call site inside a lambda of its function?++A lambda may carry a receiver (`routing { get("/") }`, `LazyColumn { item() }`)+whose type a text scan cannot see, so code there may have any implicit+``this``. Code directly in a function body has only the function's own+receivers. A brace opens a lambda unless it is the function body or a+control-flow block.+"""++from __future__ import annotations++import re++_STRING = re.compile(r'"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])\'')+_LINE_COMMENT = re.compile(r"//[^\n]*")+_BLOCK_WORDS = re.compile(r"(?:\b(?:else|try|finally|do|init|when)|->)$")+_BLOCK_HEADS = frozenset({"if", "for", "while", "when", "catch"})+_HEAD_WORD = re.compile(r"(\w+)\s*$")+_PARENTHESIZED = re.compile(r"\([^()]*\)")+++def _paren_head(text: str, end: int) -> str | None:+ """The word before the `(` matching the `)` just before *end*."""+ depth = 0+ index = end+ while index > 0:+ index -= 1+ depth += (text[index] == ")") - (text[index] == "(")+ if depth == 0:+ break+ if depth:+ return None+ word = _HEAD_WORD.search(text, max(0, index - 40), index)+ return word.group(1) if word else None+++def _opens_block(text: str, end: int) -> bool:+ """Does a `{` at *end* open a control-flow block rather than a lambda?"""+ while end and text[end - 1].isspace():+ end -= 1+ if _BLOCK_WORDS.search(text, max(0, end - 16), end):+ return True+ return text[end - 1 : end] == ")" and _paren_head(text, end) in _BLOCK_HEADS+++def _is_block_body(header: str) -> bool:+ """Does the first brace after *header* open a block body, not an expression body's lambda?++ An expression body is the only `=` outside the header's parentheses.+ """+ while True:+ stripped = _PARENTHESIZED.sub("", header)+ if stripped == header:+ return "=" not in header+ header = stripped+++def in_lambda(source: str, has_body: bool) -> bool:+ """Is the end of *source*, a function's text up to a call, inside a lambda?++ *has_body* says the function's first brace is its block body, not a+ lambda of an expression body. Ceiling: a raw string holding a brace+ miscounts.+ """+ text = _LINE_COMMENT.sub("", _STRING.sub('""', source))+ stack: list[bool] = []+ body_seen = not has_body+ for match in re.finditer(r"[{}]", text):+ if match.group() == "}":+ if stack:+ stack.pop()+ continue+ if not body_seen:+ body_seen = True+ if _is_block_body(text[: match.start()]):+ stack.append(False)+ continue+ stack.append(not _opens_block(text, match.start()))+ return any(stack)diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.pyindex f21199efb..59695be06 100644--- a/packages/core/src/repowise/core/ingestion/type_names.py+++ b/packages/core/src/repowise/core/ingestion/type_names.py@@ -219,6 +219,27 @@ _CSHARP_EXTENSION_RECEIVER = re.compile()+def kotlin_extension_receiver(header: str, name: str) -> str | None:+ """The bare type Kotlin's ``fun Type.name(`` in *header* extends, or None.++ None too for a receiver that is the function's own type parameter+ (``fun <T> T.name()``): any implicit receiver fits it.+ """+ # Read at the header's first `fun` only: a same-named function below it is+ # another declaration.+ first = re.search(r"\bfun\s", header)+ match = first and re.compile(+ rf"fun\s+(?:<(?P<params>(?:[^<>]|<[^<>]*>)*)>\s*)?"+ rf"(?P<type>[^()=]+?)\.\s*`?{re.escape(name)}`?\s*[(<]"+ ).match(header, first.start())+ if not match:+ return None+ bare = bare_type_name(match.group("type").strip().rstrip("?"))+ params = (match.group("params") or "").split(",")+ declared = {p.split(":")[0].split()[-1] for p in params if p.strip()}+ return None if not bare or bare in declared else bare++def csharp_extension_receiver(signature: str) -> str | None:"""The bare type a C# extension method extends, or None if it is not one.diff --git a/tests/unit/ingestion/test_kotlin_extension_calls.py b/tests/unit/ingestion/test_kotlin_extension_calls.pynew file mode 100644index 000000000..20a80f3da--- /dev/null+++ b/tests/unit/ingestion/test_kotlin_extension_calls.py@@ -0,0 +1,152 @@+"""A bare Kotlin call reaches an extension only through an implicit receiver.++``fun AuthenticationConfig.digest(..)`` needs an ``AuthenticationConfig`` as+``this``: a bare ``digest(..)`` in a plain function body is something else (a+local function, a library call), while one inside a member or extension of+that type, or inside a lambda whose receiver a text scan cannot type, may be+the extension.+"""++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.lang_helpers.kotlin_lambdas import in_lambda+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import parse_file+from repowise.core.ingestion.type_names import kotlin_extension_receiver++SOURCE = """\+package app++fun Config.digest(name: String) = name++class Config {+ fun member() {+ digest("a")+ }+}++fun Config.sibling() {+ digest("b")+}++fun plain(bytes: ByteArray) {+ digest("c")+}++fun scoped() {+ configure {+ digest("d")+ }+}++typealias Cfg = Config++open class Base {+ inner class In {+ fun f() {+ based("e")+ }+ }+}++fun Base.based(name: String) = name+fun Cfg.viaAlias(name: String) = name+fun List<String>.firstTwo(name: String) = name++class UsesAlias : Base() {+ fun k() {+ viaAlias("f")+ }+}++class MyList : ArrayList<String>() {+ fun h() {+ firstTwo("g")+ }+}+"""+++def _callees(tmp_path: Path, caller: str) -> set[str]:+ 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,+ )+ parsed = {"App.kt": parse_file(info, SOURCE.encode("utf-8"))}+ resolver = CallResolver(parsed, {"App.kt": set()}, repo_path=str(tmp_path))+ return {+ rc.callee_id+ for rc in resolver.resolve_file("App.kt", parsed["App.kt"].calls)+ if rc.caller_id == f"App.kt::{caller}"+ }++[email protected]("caller", ["Config::member", "sibling", "scoped"])+def test_a_receiver_in_scope_keeps_the_extension(tmp_path: Path, caller: str) -> None:+ assert _callees(tmp_path, caller) == {"App.kt::digest"}+++def test_a_plain_body_has_no_receiver_for_it(tmp_path: Path) -> None:+ assert _callees(tmp_path, "plain") == set()+++ ("caller", "callee"),+ [+ ("In::f", "App.kt::based"), # an inner class sees its outer `this`+ ("UsesAlias::k", "App.kt::viaAlias"), # an alias receiver is not refused+ ("MyList::h", "App.kt::firstTwo"), # nor a library one+ ],+)+def test_an_untyped_or_outer_receiver_keeps_the_extension(+ tmp_path: Path, caller: str, callee: str+) -> None:+ assert _callees(tmp_path, caller) == {callee}+++class TestReceiverShape:+ @pytest.mark.parametrize(+ ("header", "name", "receiver"),+ [+ ("private operator fun Random.get(range: IntRange) = 1", "get", "Random"),+ ("fun <T : Any> Mono<T>.capture(x: Int)", "capture", "Mono"),+ ("fun String?.orBlank(): String", "orBlank", "String"),+ ("fun <T> T.also2(): T", "also2", None),+ ("@Composable fun Card(x: a.B) {}", "Card", None),+ ("fun foo()\nfun Bar.foo()", "foo", None),+ ],+ )+ def test_kotlin_extension_receiver(self, header: str, name: str, receiver) -> None:+ assert kotlin_extension_receiver(header, name) == receiver+++class TestLambdaScan:+ @pytest.mark.parametrize(+ ("source", "has_body", "inside"),+ [+ ("fun a() {\n routing {\n ", True, True),+ ("fun a() {\n if (x) {\n ", True, False),+ ('fun a() {\n val s = "{"\n ', True, False),+ ("fun a() = rule.collect(name) {\n ", True, True),+ ("fun a(x: Int = 1): Int {\n list.forEach { it }\n ", True, False),+ ("plugins {\n ", False, True),+ ],+ )+ def test_in_lambda(self, source: str, has_body: bool, inside: bool) -> None:+ assert in_lambda(source, has_body) is inside