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): let Kotlin, Swift and Dart parameters shadow a bare call (#3679)
Swati Ahuja46bc543a665d
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.pyindex c7b87d4cb..3af1b377a 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py@@ -14,6 +14,7 @@ from .decorator_names import is_property_accessor, is_property_getterfrom .lang_helpers.anonymous_classes import is_anonymous_memberfrom .languages.receiver_types import (BINDING_LANGUAGES,+ CALL_SHADOW_LANGUAGES,CALL_TYPED_LANGUAGES,EXTERNAL_TYPE_LANGUAGES,FRAMEWORK_DECORATOR_LANGUAGES,@@ -37,6 +38,7 @@ from .languages.receiver_types import (scan_binding_positions,scan_bindings,scan_call_assignments,+ scan_call_shadows,scan_declarations,scan_ranges,scan_scope_marks,@@ -596,9 +598,13 @@ class ReceiverTypingMixin:"""Is a bare call's name a parameter or local of the calling function?Then no module, import or repo-wide symbol of that name is the callee.+ In the languages added for that question alone, a member call on its+ bare fallback (`vm.onClick()`) is never the local."""language = self._language_of(file_path) or ""- return language in BINDING_LANGUAGES and self._binds_locally(+ if call.receiver_name and language not in BINDING_LANGUAGES:+ return False+ return language in CALL_SHADOW_LANGUAGES and self._binds_locally(file_path, caller_id, language, call.target_name, call.line)@@ -661,7 +667,7 @@ class ReceiverTypingMixin:return chainsparsed = self._parsed_files.get(file_path)text = self._text_of(file_path)- bindings = self._bindings_for(file_path, language)+ bindings = self._call_shadows_for(file_path, language)marks = scan_scope_marks(text, language)chains = {}open_functions: list[tuple[Symbol, _Scope]] = []@@ -1483,6 +1489,12 @@ class ReceiverTypingMixin:_store_capped(self._bound_names, key, names, _BODY_TYPE_CACHE_ENTRIES)return names+ def _call_shadows_for(self, file_path: str, language: str) -> tuple[tuple[int, str], ...]:+ """The bindings that hide a bare call of their name, read off one file."""+ if language in BINDING_LANGUAGES:+ return self._bindings_for(file_path, language)+ return scan_call_shadows(self._text_of(file_path), language)+def _bindings_for(self, file_path: str, language: str) -> tuple[tuple[int, str], ...]:"""Every name one file binds, scanned once however many bodies ask."""found = self._bindings.get(file_path)diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex 36d8c403a..a53257c78 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -593,6 +593,114 @@ def scan_binding_positions(text: str, language: str) -> tuple[tuple[int, int, streturn tuple(sorted(positions))+# Languages where a parameter or local hides a bare call of its name from every+# repo symbol of that name. Kotlin, Swift and Dart read their own shapes below.+CALL_SHADOW_LANGUAGES = BINDING_LANGUAGES | {"dart", "kotlin", "swift"}++# Kotlin resolves `f()` past a binding that cannot be invoked, so only a+# function-typed one hides `f`: `onClick: () -> Unit`, `r: Call.() -> T`,+# `val f = { .. }`. Ceiling: a class type with `operator fun invoke` is missed.+_KT_INVOKABLE = (+ re.compile(+ r"(?<![\w.@])(?P<name>[a-z_]\w*)\s*:\s*(?:@\w+(?:\([^()\n]*\))?\s+)*"+ r"(?:suspend\s+)?(?:[\w.]+(?:<[^\n]*?>)?\??\.)?\("+ ),+ re.compile(r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*=\s*\{"),+)+# 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]*)*>)?"+_SWIFT_HEADER = re.compile(rf"(?<![\w.])(?:func\s+[^\s(<]+|init[?!]?|subscript)\s*{_GENERIC}\s*\(")+_DART_HEADER = re.compile(rf"(?<![\w$.])(?P<fn>[A-Za-z_$][\w$]*)\s*{_GENERIC}\s*\(")+_DART_BODY = re.compile(r"\s*(?:async\*?|sync\*)?\s*(?:\{|=>)")+_DART_NOT_HEADERS = frozenset({"if", "for", "while", "switch", "catch", "super", "this", "assert"})+_GROUP_BRACKETS = str.maketrans("{}[]", " ")+_TRAILING_NAME = re.compile(r"(?P<name>[A-Za-z_$][\w$]*)\s*$")+++def _parameter_pieces(cleaned: str, open_paren: int) -> tuple[list[tuple[int, str]], int]:+ """``(offset, text)`` of each top-level parameter in the list at *open_paren*, and its end.++ A Dart `{..}` / `[..]` optional group at the top is read through, and an+ arrow (`->`, `=>`) closes nothing.+ """+ pieces: list[tuple[int, str]] = []+ depth, start, index = 0, open_paren + 1, open_paren + 1+ while index < len(cleaned):+ char = cleaned[index]+ if char in "(<" or (char in "{[" and depth):+ depth += 1+ elif char == ">" and cleaned[index - 1] in "-=":+ pass+ elif char in ")>" or (char in "}]" and depth):+ if not depth and char == ")":+ pieces.append((start, cleaned[start:index]))+ return pieces, index+ depth = max(depth - 1, 0)+ elif char == "," and not depth:+ pieces.append((start, cleaned[start:index]))+ start = index + 1+ index += 1+ return pieces, index+++def _swift_parameter(piece: str) -> str | None:+ """The name a Swift parameter binds in the body: the last word before its type."""+ words = piece.partition(":")[0].split()+ return words[-1] if words and words[-1] != "_" and words[-1].isidentifier() else None+++def _dart_parameter(piece: str) -> str | None:+ """The name a Dart parameter binds; a `this.x` / `super.x` one binds no new name."""+ # An optional group's brackets (`{required T name}`, `[T name]`) are not the name.+ head = re.split(r"[=:]", piece.translate(_GROUP_BRACKETS), maxsplit=1)[0].strip()+ if re.search(r"\b(?:this|super)\.", head):+ return None+ found = _TRAILING_NAME.search(head)+ return found.group("name") if found else None+++def _listed_parameters(+ cleaned: str, header: re.Pattern[str], name_of: Callable[[str], str | None], body: bool+) -> set[tuple[int, str]]:+ found: set[tuple[int, str]] = set()+ for match in header.finditer(cleaned):+ if body and match.group("fn") in _DART_NOT_HEADERS:+ continue+ pieces, end = _parameter_pieces(cleaned, match.end() - 1)+ if body and not _DART_BODY.match(cleaned, end + 1):+ continue+ for offset, piece in pieces:+ name = name_of(piece)+ if name is not None:+ found.add((offset + piece.find(name), name))+ return found+++def scan_call_shadows(text: str, language: str) -> tuple[tuple[int, str], ...]:+ """Every ``(line, name)`` binding in *text* that hides a bare call of that name.++ Everything ``scan_bindings`` reads, but for Kotlin only invokable bindings,+ and Swift and Dart add their declared parameters.+ """+ if language in BINDING_LANGUAGES:+ return scan_bindings(text, language)+ if language not in CALL_SHADOW_LANGUAGES:+ return ()+ cleaned = _without_comments(text, language)+ if language == "kotlin":+ found = _named_bindings(_KT_INVOKABLE, cleaned)+ elif language == "swift":+ found = _listed_parameters(cleaned, _SWIFT_HEADER, _swift_parameter, body=False)+ else:+ found = _listed_parameters(cleaned, _DART_HEADER, _dart_parameter, body=True)+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]+ lines = {(bisect_right(starts, offset), name) for offset, name in found}+ if language != "kotlin":+ lines.update(scan_bindings(text, language))+ return tuple(sorted(lines))++# What a scope binds beyond its positional bindings. A TypeScript/JavaScript# ``function`` declaration is hoisted, so it binds from the top of its scope# whatever its line. A Python ``global`` name is the module's in that scope,diff --git a/tests/unit/ingestion/test_shadowed_bare_calls.py b/tests/unit/ingestion/test_shadowed_bare_calls.pyindex 42fc1ad04..fd7164867 100644--- a/tests/unit/ingestion/test_shadowed_bare_calls.py+++ b/tests/unit/ingestion/test_shadowed_bare_calls.py@@ -4,7 +4,8 @@caller passes in, not the module's ``Class``: the parameter shadows everysame-named import and top-level declaration. The same holds for a local andfor a parameter of a function enclosing the caller, in TypeScript,-JavaScript and Python alike.+JavaScript and Python alike, and in Swift and Dart. Kotlin resolves a call+past a binding it cannot invoke, so only a function-typed one shadows there."""from __future__ import annotations@@ -15,7 +16,7 @@ from pathlib import Pathimport pytestfrom repowise.core.ingestion.call_resolver import CallResolver-from repowise.core.ingestion.languages.receiver_types import scan_bindings+from repowise.core.ingestion.languages.receiver_types import scan_bindings, scan_call_shadowsfrom repowise.core.ingestion.models import FileInfo, ParsedFilefrom repowise.core.ingestion.parser import parse_file@@ -239,6 +240,95 @@ class TestPython:assert "util.py::helper" not in parsed_callees+KT_UTIL = """package app++class TopicsViewModel {+ fun onTopicClick(id: String) {}+}+"""++KT_API = """package app++@Composable+fun TopicCard(+ name: String,+ onTopicClick: (String) -> Unit,+) {+ onTopicClick(name)+}++fun plain(onTopicClick: Int) {+ onTopicClick("x")+}++fun member(onTopicClick: (String) -> Unit, vm: TopicsViewModel) {+ vm.onTopicClick("x")+}+"""++SWIFT_UTIL = """func helper(_ x: Int) -> Int {+ return x + 1+}+"""++SWIFT_API = """func shadowed(with helper: (Int) -> Int) -> Int {+ return helper(1)+}++func plain(_ n: Int) -> Int {+ return helper(n)+}+"""++DART_UTIL = """int helper(int x) => x + 1;+"""++DART_API = """import 'util.dart';++int shadowed(int Function(int) helper) {+ return helper(1);+}++int plain(int n, {int Function(int)? other}) {+ return helper(n);+}+"""+++class TestKotlin:+ @pytest.fixture+ def files(self) -> dict[str, str]:+ return {"util.kt": KT_UTIL, "api.kt": KT_API}++ def test_a_function_typed_parameter_shadows(self, tmp_path: Path, files) -> None:+ assert _callees(tmp_path, files, "kotlin", "TopicCard") == set()++ def test_a_parameter_it_cannot_invoke_does_not(self, tmp_path: Path, files) -> None:+ # kotlinc resolves `onTopicClick("x")` past `onTopicClick: Int`.+ assert _callees(tmp_path, files, "kotlin", "plain") == {+ "util.kt::TopicsViewModel::onTopicClick"+ }++ def test_a_member_call_is_never_the_parameter(self, tmp_path: Path, files) -> None:+ assert "util.kt::TopicsViewModel::onTopicClick" in _callees(+ tmp_path, files, "kotlin", "member"+ )+++class TestSwiftAndDart:+ @pytest.mark.parametrize(+ ("language", "files"),+ [+ ("swift", {"util.swift": SWIFT_UTIL, "api.swift": SWIFT_API}),+ ("dart", {"util.dart": DART_UTIL, "api.dart": DART_API}),+ ],+ )+ def test_a_parameter_shadows(self, tmp_path: Path, language: str, files) -> None:+ util = next(rel for rel in files if rel.startswith("util"))+ assert _callees(tmp_path, files, language, "shadowed") == set()+ assert _callees(tmp_path, files, language, "plain") == {f"{util}::helper"}++class TestBindingScan:def test_typescript_parameter_types_and_defaults_are_not_bindings(self) -> None:names = {n for _, n in scan_bindings("function f(a: Foo<K, V>, b = make) {}", "typescript")}@@ -273,3 +363,30 @@ class TestBindingScan:def test_javascript_reads_with_the_typescript_shapes(self) -> None:names = {n for _, n in scan_bindings("const f = (x, y) => x;", "javascript")}assert {"f", "x", "y"} <= names++ def test_kotlin_shadows_only_with_invokable_bindings(self) -> None:+ text = (+ "fun f(a: (Int) -> Unit, b: Int, c: @Composable () -> Unit,\n"+ " d: suspend Call.() -> T, e: ((Int) -> Unit)? = null) {\n"+ " val g = { 1 }\n val h = 2\n}\n"+ )+ names = {n for _, n in scan_call_shadows(text, "kotlin")}+ assert names == {"a", "c", "d", "e", "g"}++ def test_swift_parameters_bind_their_inner_names(self) -> None:+ text = "func f(_ a: Int, with b: @escaping () -> Void) {}\ninit(c: Int) {}\nfoo(d: 1)\n"+ assert {n for _, n in scan_call_shadows(text, "swift")} == {"a", "b", "c"}++ def test_dart_parameters_bind_unless_they_initialize_a_field(self) -> None:+ text = (+ "void f(int a, {required void Function() b, this.c, int d = 3}) {}\n"+ "W({super.key, this.e});\ng(h);\n"+ )+ assert {n for _, n in scan_call_shadows(text, "dart")} == {"a", "b", "d"}++ def test_dart_names_closing_an_optional_group_bind(self) -> None:+ text = (+ "void f({required void Function() a}) {}\n"+ "void g({Function()? b}) {}\nvoid h([VoidCallback c]) {}\n"+ )+ assert {n for _, n in scan_call_shadows(text, "dart")} == {"a", "b", "c"}