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): resolve Kotlin extension calls on a typed receiver (#3707)

Swati Ahujad331e2b8a717
diff --git a/docs/layers/GRAPH.md b/docs/layers/GRAPH.md
index c1ee6a5aa..9e8526d69 100644
--- a/docs/layers/GRAPH.md
+++ b/docs/layers/GRAPH.md
@@ -258,7 +258,7 @@ own:
| Locals and parameters, including Go's method receiver | `var repo = new UserRepo()`, `func (s *Server) handle()` | 4 |
| Fields of the enclosing class | `this.cache.evict(...)` | 4 |
| Framework-retyped symbols | `@shared_task def add` makes `add` a `Task`, so `add.s()` is `Task::s` | 4 |
-| C# extension methods, via the type their `this` parameter names | `items.Paged(10)` | 3 |
+| C# extension methods and Kotlin extension functions, via the type they extend or one of its ancestors | `items.Paged(10)`, `helper.logScreenView(name)` | 3 |
| Dotted receivers typed hop by hop through declared fields | `this.a.b.m()` | 2 |
| The declared return type of an inner call | `repo.find(id).save()` | 4 |
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 8b5746058..8b6cdb9b5 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -142,8 +142,8 @@ class LanguageStrategiesMixin:
self._go_index: Any = None
self._go_index_built = False
- # {Kotlin function id: the type it extends, or None}
- self._kotlin_receivers: dict[str, str | None] = {}
+ # {(Kotlin function id, line): the type it extends, or None}
+ self._kotlin_receivers: dict[tuple[str, int], str | None] = {}
# {Dart class id: the named constructors its body declares}
self._dart_constructors: dict[str, frozenset[str]] = {}
@@ -616,14 +616,16 @@ class LanguageStrategiesMixin:
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:
+ """The type a Kotlin function extends, read off its header (annotations included).
+
+ Kept per declaration: same-named functions of one file share an id.
+ """
+ key = (symbol.id, symbol.start_line)
+ if key 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]
+ lines = self._lines_of(path)[symbol.start_line - 1 : symbol.start_line + 7]
+ self._kotlin_receivers[key] = kotlin_extension_receiver(" ".join(lines), symbol.name)
+ return self._kotlin_receivers[key]
def _implicit_receivers(self, caller: Symbol) -> set[str]:
"""The bare type names ``this`` may be inside *caller*."""
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 b83cc4c47..0cd862382 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -62,6 +62,39 @@ from .type_names import (
# from a local.
_TYPE_KINDS = frozenset({"class", "struct", "interface", "enum", "trait", "impl"})
_FUNCTION_KINDS = frozenset({"function", "method"})
+# Languages whose extensions the extension index holds, keyed on the type extended.
+_EXTENSION_LANGUAGES = frozenset({"csharp", "kotlin"})
+# Members an extension of the same name can never beat: those of Kotlin's
+# ``Any``, which every type has, and the common ones of the builtin types a
+# library declares, which the repo's index cannot see. Not exhaustive.
+_ANY_MEMBERS = frozenset({"equals", "hashCode", "toString"})
+_LIBRARY_MEMBERS = frozenset(
+ {
+ "get",
+ "set",
+ "contains",
+ "containsAll",
+ "containsKey",
+ "containsValue",
+ "size",
+ "isEmpty",
+ "iterator",
+ "indexOf",
+ "lastIndexOf",
+ "subList",
+ "add",
+ "addAll",
+ "remove",
+ "removeAll",
+ "retainAll",
+ "clear",
+ "put",
+ "putAll",
+ "length",
+ "subSequence",
+ "compareTo",
+ }
+)
_SOURCE_CACHE_FILES = 4
@@ -224,25 +257,75 @@ class ReceiverTypingMixin:
"""The extension method a ``(type, method)`` pair names, and its scope.
Same three scopes as ``_receiver_pair_match``, over the extension index.
+ Kotlin has no global one: see ``_kotlin_extension_scope``.
"""
site = self._extension_methods.get(key)
if site is None:
return None
type_name, method_name = key
- # An import bound the name outside the repo, so a local holder of the
- # same simple name is not what the call site named.
- if type_name in self._externally_bound_names(file_path):
+ if not self._writes_one_type(file_path, site[0], type_name):
return None
- if self._inherits_the_method(type_name, method_name):
+ if self._reaches_a_member(type_name, method_name):
return None
own = self._file_extension_methods.get(file_path, {})
if key in own:
return own[key], "same_file"
+ if self._language_of(file_path) == "kotlin":
+ return self._kotlin_extension_scope(file_path, site, method_name)
merged = self._merged_extension_methods_for(file_path)
if key in merged:
return merged[key], "import"
return site[1], "global"
+ def _kotlin_extension_scope(
+ self, file_path: str, site: tuple[str, str], name: str
+ ) -> tuple[str, str] | None:
+ """The Kotlin extension at *site*, scoped ``import`` when *file_path* sees it.
+
+ Kotlin brings a top-level function into scope only from the caller's
+ own package (an implicit import) or by an import naming it or its
+ package's ``*``, so a repo-wide name match is no evidence. ``private``
+ stays in its file and ``internal`` in its build.
+ """
+ path, sym_id = site
+ if self._symbols_by_id[sym_id].visibility == "private":
+ return None
+ if not self._in_reach_of_build(file_path, path):
+ return None
+ index = self._get_jvm_index()
+ package = index.package_for_file(path) if index is not None else None
+ if package is None:
+ seen = posixpath.dirname(path) == posixpath.dirname(file_path)
+ else:
+ parsed = self._parsed_files.get(file_path)
+ wanted = {f"{package}.{name}", f"{package}.*"}
+ seen = index.package_for_file(file_path) == package or any(
+ imp.module_path in wanted for imp in (parsed.imports if parsed else ())
+ )
+ return (sym_id, "import") if seen else None
+
+ def _writes_one_type(self, file_path: str, other_path: str, name: str) -> bool:
+ """Do the two files mean one type by *name*?
+
+ Both a repo or builtin one, or both the same library import.
+ """
+ written = self._external_import(file_path, name)
+ other = self._external_import(other_path, name)
+ return written == other
+
+ def _external_import(self, file_path: str, name: str) -> str | None:
+ """The path *file_path* imports *name* from outside the repo, else None.
+
+ Read off the names the file writes, so an alias (``import a.B as C``)
+ binds ``C`` and leaves ``B`` free.
+ """
+ parsed = self._parsed_files.get(file_path)
+ for imp in parsed.imports if parsed else ():
+ outside = not imp.resolved_file or imp.resolved_file.startswith("external:")
+ if outside and name in imp.local_names:
+ return imp.module_path
+ return None
+
def _typed_receiver_language(self, file_path: str, call: CallSite) -> str | None:
"""The language receiver typing may run in here, or None to decline.
@@ -263,7 +346,8 @@ class ReceiverTypingMixin:
return None
# Refuse before reading the file: nothing resolves unless some class
- # declares a method of this name, which a free function does not prove.
+ # declares a method of this name or an extension carries it, which a
+ # free function does not prove.
if call.target_name not in self._method_names():
return None
return language
@@ -588,9 +672,10 @@ class ReceiverTypingMixin:
return None
builtin = external_type_name(type_name)
if builtin is not None:
- # Typed only when a repo class shadows the builtin's name.
+ # A builtin's own members are not the repo's: only an extension on
+ # it is, unless a repo class shadows the builtin's name.
if builtin not in self._known_type_names:
- return None
+ return self._typed_extension_call(file_path, call, caller_id, builtin, language)
type_name = builtin
if "::" in type_name:
# A symbol id, recorded by ``_add_call_typed_locals``.
@@ -600,8 +685,8 @@ class ReceiverTypingMixin:
found = self._typed_receiver_target(typing_file, call, caller_id, type_name)
if found is None:
- # Last, because C# prefers an instance method to an extension.
- return self._typed_extension_call(file_path, call, caller_id, type_name, language)
+ # Last, because C# and Kotlin prefer a member to an extension.
+ return self._extension_call(file_path, call, caller_id, type_name)[1]
sym_id, tier = found
if scope == "framework":
return self._framework_typed_call(caller_id, sym_id, tier, call.line)
@@ -1077,6 +1162,39 @@ class ReceiverTypingMixin:
return None
return type_name
+ def _extension_call(
+ self, file_path: str, call: CallSite, caller_id: str, type_name: str
+ ) -> tuple[bool, ResolvedCall | None]:
+ """The extension a *type_name* receiver reaches, as ``(answered, edge)``.
+
+ One on the type itself, else one on an ancestor, which serves every
+ type deriving from it. Ancestors on two branches answering is
+ ambiguous: answered, with no edge.
+ """
+ language = self._language_of(file_path) or ""
+ if language not in _EXTENSION_LANGUAGES:
+ return False, None
+ own = self._typed_extension_call(file_path, call, caller_id, type_name, language)
+ if own is not None:
+ return True, own
+ hits = {}
+ for name in self._ancestor_names(type_name, language):
+ hit = self._typed_extension_call(file_path, call, caller_id, name, language)
+ if hit is not None:
+ hits[hit.callee_id] = hit
+ if not hits:
+ return False, None
+ return True, next(iter(hits.values())) if len(hits) == 1 else None
+
+ def _ancestor_names(self, type_name: str, language: str) -> list[str]:
+ """The names of the repo ancestors of the one *language* type *type_name* names."""
+ type_id = self._unique_type_id(type_name, language)
+ return [
+ symbol.name
+ for ancestor in (self._ancestors_of(type_id) if type_id is not None else ())
+ if (symbol := self._symbols_by_id.get(ancestor)) is not None
+ ]
+
def _typed_extension_call(
self,
file_path: str,
@@ -1085,12 +1203,12 @@ class ReceiverTypingMixin:
type_name: str,
language: str,
) -> ResolvedCall | None:
- if language != "csharp":
+ if language not in _EXTENSION_LANGUAGES:
return None
# Extensions are indexed by the type they name, written without arity.
key = (id_segment_name(type_name), call.target_name)
extension = self._extension_target(file_path, key)
- if extension is None:
+ if extension is None or self._symbols_by_id[extension[0]].language != language:
return None
return self._extension_typed_call(caller_id, *extension, call.line)
@@ -1152,26 +1270,32 @@ class ReceiverTypingMixin:
return ResolvedCall(caller_id, sym_id, 0.88, line, "receiver_framework_import")
return ResolvedCall(caller_id, sym_id, 0.75, line, "receiver_framework_global")
- def _inherits_the_method(self, type_name: str, method_name: str) -> bool:
- """Could a class of this name reach *method_name* through an ancestor?
+ def _reaches_a_member(self, type_name: str, method_name: str) -> bool:
+ """Could a class of this name reach a member *method_name*, its own or inherited?
- C# dispatches to an inherited instance method in preference to an
- extension, and every tier above asks only for the literal
- ``(type, method)`` pair, so none of them sees one. Asked of every class
- sharing the simple name: which is meant is not settled here.
+ C# and Kotlin dispatch to a member in preference to an extension, and
+ every tier above asks only for the literal ``(type, method)`` pair, so
+ none of them sees an inherited one, nor one it refused as ambiguous.
+ Asked of every class sharing the simple name: which is meant is not
+ settled here. A member the repo cannot see, of ``Any`` or of a library
+ type, is read off a short list instead.
"""
+ if method_name in _ANY_MEMBERS:
+ return True
+ if type_name not in self._known_type_names and method_name in _LIBRARY_MEMBERS:
+ return True
for sym_id in self._global_symbols.get(type_name, ()):
symbol = self._symbols_by_id.get(sym_id)
if symbol is None or symbol.kind not in _TYPE_KINDS:
continue
- if any(self._declares(a, method_name) for a in self._ancestors_of(sym_id)):
+ if any(self._declares(a, method_name) for a in (sym_id, *self._ancestors_of(sym_id))):
return True
return False
def _extension_typed_call(
self, caller_id: str, sym_id: str, tier: str, line: int
) -> ResolvedCall:
- """Stamp an edge onto a C# extension method.
+ """Stamp an edge onto a C# extension method or a Kotlin extension function.
One family whatever scope typed the receiver, unlike the three-way
typed/field/framework split above: what an audit needs to separate is
@@ -1184,9 +1308,11 @@ class ReceiverTypingMixin:
return ResolvedCall(caller_id, sym_id, 0.75, line, "receiver_extension_global")
def _method_names(self) -> frozenset[str]:
- """Every name declared as a method of some class, built once."""
+ """Every name a typed receiver can reach: a class's method or an extension, built once."""
if self._method_name_set is None:
- self._method_name_set = frozenset(method for _, method in self._global_methods)
+ self._method_name_set = frozenset(
+ method for _, method in (*self._global_methods, *self._extension_methods)
+ )
return self._method_name_set
def _receiver_type_is_external(self, file_path: str, call: CallSite, caller_id: str) -> bool:
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 6da3172b3..b4b0a88d3 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -36,6 +36,7 @@ import structlog
from .call_language_strategies import _LANGUAGE_CALL_STRATEGIES as _LANGUAGE_CALL_STRATEGIES
from .call_language_strategies import LanguageStrategiesMixin
from .call_receiver_typing import (
+ _FUNCTION_KINDS,
_SOURCE_CACHE_FILES,
_TYPE_KINDS,
ReceiverTypingMixin,
@@ -494,8 +495,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# every file's method dict with one short-list lookup.
self._global_methods: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
- # C# extension methods, keyed on the type they extend rather than on
- # their holder class: {(type, method): (file_path, symbol_id)} and the
+ # C# extension methods and Kotlin extension functions, keyed on the
+ # type they extend rather than on their holder: {(type, method):
+ # (file_path, symbol_id)} and the
# per-file view of the same. Held apart from the method index on
# purpose — merging them would leak C# keys into the C++ and JVM tiers
# that read ``_global_methods``, and would let an extension answer a
@@ -543,7 +545,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# 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.
+ # The lines of the file whose declarations are being read; see ``_lines_of``.
self._indexed_lines: tuple[str, list[str]] = ("", [])
# C/C++ symbols with internal linkage; see ``_reachable_by_name``.
self._tu_local_ids: set[str] = set()
@@ -771,9 +773,13 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
file_methods[key] = index_id
self._global_methods[key].append((path, index_id))
- extended = self._csharp_extended_type(sym)
- if extended is not None:
- extensions[(extended, sym.name)].add((path, index_id))
+ extended = (
+ self._csharp_extended_type(sym)
+ if sym.parent_name
+ else self._kotlin_extended_type(sym)
+ )
+ if extended is not None:
+ extensions[(extended, sym.name)].add((path, index_id))
self._index_globally(path, sym, index_id)
@@ -790,6 +796,21 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return None
return extended if extended in self._csharp_type_names else None
+ def _kotlin_extended_type(self, sym: Symbol) -> str | None:
+ """The type a top-level Kotlin extension function extends, a library one included.
+
+ Unlike C#, a library receiver is kept: Kotlin types a ``ByteArray`` or
+ ``List`` receiver too, and only an extension can be the repo's callee.
+ A member extension is left out, since only its holder's scope sees it.
+
+ Ceiling: the key is the bare type, so ``List<String>.f`` and
+ ``List<Int>.f`` collide (and refuse as ambiguous), and ``Foo?`` keys as
+ ``Foo``. Keying on type arguments would need the receiver's too.
+ """
+ if sym.language != "kotlin" or sym.kind not in _FUNCTION_KINDS:
+ return None
+ return self._kotlin_receiver(sym)
+
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)
@@ -819,10 +840,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""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
+ lines = self._lines_of(path)[sym.start_line - 1 : max(sym.end_line, sym.start_line)]
+ return holds_function("\n".join(lines), sym.name, sym.language)
+
+ def _lines_of(self, path: str) -> list[str]:
+ """*path*'s lines, split once while its symbols are read one by one."""
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)
+ return self._indexed_lines[1]
def _index_overload_sets(self, parsed: ParsedFile) -> dict[str, str]:
"""Record *parsed*'s overload sets; ``{member id: representative}``.
@@ -1457,7 +1482,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
unless an extension the index leaves out carries the name: one on a
type parameter (``this TBuilder b``) or an external type may be it.
"""
- type_id = self._csharp_type_id(type_name)
+ type_id = self._unique_type_id(type_name, "csharp")
if type_id is not None:
inherited = self._ancestor_method(type_id, call.target_name, caller_id)
if inherited is not None:
@@ -1465,21 +1490,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
tier = "same_file" if same_file else "import"
return True, self._return_typed_call(caller_id, inherited, tier, call.line)
- own = self._typed_extension_call(file_path, call, caller_id, type_name, "csharp")
- if own is not None:
- return True, own
- ancestor_names = [
- symbol.name
- for ancestor in (self._ancestors_of(type_id) if type_id is not None else ())
- if (symbol := self._symbols_by_id.get(ancestor)) is not None
- ]
- hits = {}
- for name in ancestor_names:
- hit = self._typed_extension_call(file_path, call, caller_id, name, "csharp")
- if hit is not None:
- hits[hit.callee_id] = hit
- if hits:
- return True, next(iter(hits.values())) if len(hits) == 1 else None
+ answered, hit = self._extension_call(file_path, call, caller_id, type_name)
+ if answered:
+ return True, hit
# Proven only for a type whose members were all asked: one whose every
# base is a repository type, or a builtin. A name the repository does
# not declare may be a type parameter (``TBuilder``), whose members are
@@ -1499,15 +1512,15 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return False
return True
- def _csharp_type_id(self, type_name: str) -> str | None:
- """The one C# type *type_name* (``IFoo`1`` or ``IFoo``) names repo-wide, or None."""
+ def _unique_type_id(self, type_name: str, language: str) -> str | None:
+ """The one *language* type *type_name* (``IFoo`1`` or ``IFoo``) names repo-wide, or None."""
bare, _, arity = type_name.partition("`")
+ shape = (language, int(arity or 0))
candidates = [
symbol
for sym_id in self._global_symbols.get(bare, ())
if (symbol := self._symbols_by_id[sym_id]).kind in _TYPE_KINDS
- and symbol.language == "csharp"
- and (symbol.type_parameter_count or 0) == int(arity or 0)
+ and (symbol.language, symbol.type_parameter_count or 0) == shape
]
return candidates[0].id if len(candidates) == 1 else None
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 4a66885cf..06f521708 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -370,6 +370,9 @@ IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "dart", "java", "kotlin", "swift
# Only where nothing in the repo can add a method to a builtin type: C#
# extension methods, Kotlin and Swift extensions and Rust trait impls all can.
EXTERNAL_TYPE_LANGUAGES = frozenset({"java"})
+# Those, and Kotlin, whose scan keeps the marked declaration without refusing:
+# a call on it may still reach a repo extension of the builtin.
+_MARKED_BUILTIN_LANGUAGES = EXTERNAL_TYPE_LANGUAGES | {"kotlin"}
_EXTERNAL_TYPE = "external:"
# A decorator that changes what the symbol it wraps *is*: `@shared_task` leaves
@@ -1004,7 +1007,7 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
raw = match.group("type")
if raw not in resolved:
resolved[raw] = _usable_type_name(raw, language)
- if resolved[raw][0] is None and language in EXTERNAL_TYPE_LANGUAGES:
+ if resolved[raw][0] is None and language in _MARKED_BUILTIN_LANGUAGES:
resolved[raw] = (_builtin_type_name(raw, language), False)
type_name, unwrapped = resolved[raw]
if type_name is None:
diff --git a/tests/unit/ingestion/test_csharp_extension_methods.py b/tests/unit/ingestion/test_csharp_extension_methods.py
index bf805b508..82e1bb03e 100644
--- a/tests/unit/ingestion/test_csharp_extension_methods.py
+++ b/tests/unit/ingestion/test_csharp_extension_methods.py
@@ -138,6 +138,23 @@ class TestTiers:
found = _resolve(tmp_path, files, "src/Consumer.cs")
assert found["Net"] == ("receiver_extension_global", 0.75)
+ def test_an_extension_on_a_base_serves_a_derived_receiver(self, tmp_path: Path) -> None:
+ files = {
+ "src/Base.cs": "namespace Acme;\npublic class BaseOrder { }\n",
+ "src/Order.cs": "namespace Acme;\npublic class Order : BaseOrder { }\n",
+ "src/Ext.cs": (
+ "namespace Acme;\npublic static class Ext {\n"
+ " public static int Net(this BaseOrder o) { return 1; }\n}\n"
+ ),
+ "src/Consumer.cs": (
+ "namespace Acme;\npublic class Consumer {\n"
+ " public void Run() { Order o = new Order(); var z = o.Net(); }\n}\n"
+ ),
+ }
+ heritage = {"src/Order.cs::Order": {"src/Base.cs::BaseOrder"}}
+ found = _resolve(tmp_path, files, "src/Consumer.cs", heritage=heritage)
+ assert found["Net"] == ("receiver_extension_global", 0.75)
+
def test_an_instance_method_outranks_an_extension(self, tmp_path: Path) -> None:
"""C# dispatches to the instance method, so the extension must not answer."""
files = {
diff --git a/tests/unit/ingestion/test_kotlin_extension_calls.py b/tests/unit/ingestion/test_kotlin_extension_calls.py
index 20a80f3da..e3b44f7c5 100644
--- a/tests/unit/ingestion/test_kotlin_extension_calls.py
+++ b/tests/unit/ingestion/test_kotlin_extension_calls.py
@@ -9,6 +9,7 @@ the extension.
from __future__ import annotations
+import re
from datetime import datetime
from pathlib import Path
@@ -150,3 +151,242 @@ class TestLambdaScan:
)
def test_in_lambda(self, source: str, has_body: bool, inside: bool) -> None:
assert in_lambda(source, has_body) is inside
+
+
+TYPED = """\
+package app
+
+interface Helper {
+ fun log(name: String)
+}
+
+open class Base
+class Derived : Base()
+
+class Owner {
+ fun own() = 1
+}
+
+fun Helper.logScreen(name: String) = log(name)
+fun Base.describe() = "base"
+fun ByteArray.toText(): String = ""
+fun List<String>.firstTwo() = take(2)
+fun Owner.own() = 2
+fun <T> T.also2(): T = this
+
+class Uses(private val helper: Helper) {
+ fun typed(derived: Derived, bytes: ByteArray, names: List<String>, maybe: Derived?) {
+ helper.logScreen("x")
+ derived.describe()
+ bytes.toText()
+ names.firstTwo()
+ maybe?.describe()
+ }
+
+ fun refused(owner: Owner, derived: Derived) {
+ owner.own()
+ derived.also2()
+ }
+}
+"""
+
+
+def _typed_callees(tmp_path: Path, caller: str) -> set[str]:
+ path = tmp_path / "Typed.kt"
+ path.write_text(TYPED, encoding="utf-8")
+ info = FileInfo(
+ path="Typed.kt",
+ abs_path=str(path),
+ language="kotlin",
+ size_bytes=len(TYPED),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = {"Typed.kt": parse_file(info, TYPED.encode("utf-8"))}
+ heritage = {"Typed.kt::Derived": {"Typed.kt::Base"}}
+ resolver = CallResolver(
+ parsed, {"Typed.kt": set()}, repo_path=str(tmp_path), heritage_parents=heritage
+ )
+ return {
+ rc.callee_id
+ for rc in resolver.resolve_file("Typed.kt", parsed["Typed.kt"].calls)
+ if rc.caller_id == f"Typed.kt::Uses::{caller}"
+ }
+
+
+def test_a_typed_receiver_reaches_the_extension_on_its_type_or_ancestor(tmp_path: Path) -> None:
+ assert _typed_callees(tmp_path, "typed") == {
+ "Typed.kt::logScreen",
+ "Typed.kt::describe", # declared on Derived's base
+ "Typed.kt::toText", # a library receiver
+ "Typed.kt::firstTwo",
+ }
+
+
+def test_a_member_wins_and_a_generic_receiver_is_not_indexed(tmp_path: Path) -> None:
+ assert _typed_callees(tmp_path, "refused") == {"Typed.kt::Owner::own"}
+
+
+def _resolve_files(tmp_path: Path, files: dict[str, str], caller_file: str) -> set[str]:
+ parsed = {}
+ for rel, text in files.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ if not rel.endswith(".kt"):
+ continue # a build file, read off the disk
+ info = FileInfo(
+ path=rel,
+ abs_path=str(path),
+ language="kotlin",
+ 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[rel] = parse_file(info, text.encode("utf-8"))
+ # What the builder's import pass would record: `a.Foo` is the repo file
+ # whose package `a` declares `Foo`; any other import stays outside.
+ packages = {rel: re.match(r"package (\S+)", files[rel]) for rel in parsed}
+ declaring = {
+ f"{package[1]}.{symbol.name}": rel
+ for rel, package in packages.items()
+ if package
+ for symbol in parsed[rel].symbols
+ }
+ for result in parsed.values():
+ for imp in result.imports:
+ imp.resolved_file = declaring.get(imp.module_path)
+ resolver = CallResolver(parsed, {rel: set() for rel in parsed}, repo_path=str(tmp_path))
+ return {rc.callee_id for rc in resolver.resolve_file(caller_file, parsed[caller_file].calls)}
+
+
+_EXT = "src/a/Ext.kt"
+_FOO = "package a\n\nclass Foo\n"
+
+
+ ("ext", "caller", "callee"),
+ [
+ # The caller's own package sees the extension with no import.
+ ("package a\n\nfun Foo.ext() = 1\n", "package a\n\nfun use(foo: Foo) {\n foo.ext()\n}\n", _EXT + "::ext"),
+ # An import naming it, or its package's `*`, brings it in.
+ ("package a\n\nfun Foo.ext() = 1\n", "package b\n\nimport a.Foo\nimport a.ext\n\nfun use(foo: Foo) {\n foo.ext()\n}\n", _EXT + "::ext"),
+ ("package a\n\nfun Foo.ext() = 1\n", "package b\n\nimport a.*\n\nfun use(foo: Foo) {\n foo.ext()\n}\n", _EXT + "::ext"),
+ # Another package that does not import it does not see it.
+ ("package a\n\nfun Foo.ext() = 1\n", "package b\n\nimport a.Foo\n\nfun use(foo: Foo) {\n foo.ext()\n}\n", None),
+ # `private` stays in its own file, even within the package.
+ ("package a\n\nprivate fun Foo.ext() = 1\n", "package a\n\nfun use(foo: Foo) {\n foo.ext()\n}\n", None),
+ ],
+) # fmt: skip
+def test_an_extension_binds_only_where_kotlin_sees_it(
+ tmp_path: Path, ext: str, caller: str, callee: str | None
+) -> None:
+ files = {"src/a/Foo.kt": _FOO, _EXT: ext, "src/b/Use.kt": caller}
+ if caller.startswith("package a"):
+ files = {"src/a/Foo.kt": _FOO, _EXT: ext, "src/a/Use.kt": caller}
+ found = _resolve_files(tmp_path, files, next(f for f in files if f.endswith("Use.kt")))
+ assert found == ({callee} if callee else set())
+
+
+def test_a_same_named_type_in_another_package_is_not_extended(tmp_path: Path) -> None:
+ files = {
+ "src/a/Foo.kt": _FOO,
+ _EXT: "package a\n\nfun Foo.ext() = 1\n",
+ "src/b/Foo.kt": "package b\n\nclass Foo\n",
+ "src/b/Use.kt": "package b\n\nfun use(foo: Foo) {\n foo.ext()\n}\n",
+ }
+ assert _resolve_files(tmp_path, files, "src/b/Use.kt") == set()
+
+
+def test_a_member_the_repo_cannot_see_wins(tmp_path: Path) -> None:
+ """`Any` members and a builtin's own members beat any extension of their name."""
+ source = (
+ "package a\n\nclass Foo\n\n"
+ "fun Foo.toString(x: Int) = 1\n"
+ "fun List<String>.get(x: Long) = 1\n"
+ "fun String.trimFoo() = 1\n\n"
+ "fun use(foo: Foo, names: List<String>, name: String) {\n"
+ " foo.toString(1)\n names.get(1L)\n name.trimFoo()\n}\n"
+ )
+ found = _resolve_files(tmp_path, {"src/a/Use.kt": source}, "src/a/Use.kt")
+ assert found == {"src/a/Use.kt::trimFoo"}
+
+
+def test_a_builtin_typed_local_binds_no_class_method(tmp_path: Path) -> None:
+ """`name: String` is typed now, and a repo class's same-named method is not it."""
+ source = (
+ "package a\n\nclass Text {\n fun shout() = 1\n}\n\n"
+ "fun use(name: String) {\n name.shout()\n}\n"
+ )
+ assert _resolve_files(tmp_path, {"src/a/Use.kt": source}, "src/a/Use.kt") == set()
+
+
+_USE = "fun use(foo: Foo) {\n foo.ext()\n}\n"
+
+
+def test_an_extension_in_another_build_is_not_seen(tmp_path: Path) -> None:
+ """Same package name, but two Gradle builds side by side."""
+ files = {
+ "one/settings.gradle.kts": "",
+ "two/settings.gradle.kts": "",
+ "one/src/a/Foo.kt": _FOO,
+ "one/src/a/Ext.kt": "package a\n\nfun Foo.ext() = 1\n",
+ "two/src/a/Use.kt": "package a\n\n" + _USE,
+ }
+ assert _resolve_files(tmp_path, files, "two/src/a/Use.kt") == set()
+
+
+ ("caller", "callee"),
+ [("src/Use.kt", "src/Ext.kt::ext"), ("other/Use.kt", None)],
+)
+def test_with_no_package_only_the_extensions_directory_sees_it(
+ tmp_path: Path, caller: str, callee: str | None
+) -> None:
+ """No package to compare, so the directory stands in for it (conservative)."""
+ files = {
+ "src/Foo.kt": "class Foo\n",
+ "src/Ext.kt": "fun Foo.ext() = 1\n",
+ caller: _USE,
+ }
+ assert _resolve_files(tmp_path, files, caller) == ({callee} if callee else set())
+
+
+ ("extension_import", "callee"),
+ [
+ ("import lib.one.Request", "src/a/Ext.kt::ext"),
+ ("import lib.two.Request", None), # another library's `Request`
+ ("", None), # the package's own `Request`, not the caller's library one
+ ],
+)
+def test_a_library_receiver_must_be_the_same_import(
+ tmp_path: Path, extension_import: str, callee: str | None
+) -> None:
+ files = {
+ "src/a/Ext.kt": f"package a\n\n{extension_import}\n\nfun Request.ext() = 1\n",
+ "src/a/Use.kt": (
+ "package a\n\nimport lib.one.Request\n\n"
+ "fun use(request: Request) {\n request.ext()\n}\n"
+ ),
+ }
+ found = _resolve_files(tmp_path, files, "src/a/Use.kt")
+ assert found == ({callee} if callee else set())
+
+
+def test_an_aliased_library_import_leaves_the_name_to_the_repo(tmp_path: Path) -> None:
+ """`import lib.Request as LibRequest` binds `LibRequest`; `Request` is still `a.Request`."""
+ files = {
+ "src/a/Request.kt": "package a\n\nclass Request\n",
+ "src/a/Ext.kt": "package a\n\nimport lib.Request as LibRequest\n\nfun Request.ext() = 1\n",
+ "src/a/Use.kt": "package a\n\nfun use(request: Request) {\n request.ext()\n}\n",
+ }
+ assert _resolve_files(tmp_path, files, "src/a/Use.kt") == {"src/a/Ext.kt::ext"}
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index eb47e0430..c599c3653 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -289,11 +289,11 @@ class TestKotlinShapes:
class TestKotlinRefusals:
- def test_a_builtin_generic_is_refused(self) -> None:
- """``List<Header>`` bares to ``List``, which the language spec refuses
- — and must, because the value is a List and not a Header."""
+ def test_a_builtin_generic_is_marked_external(self) -> None:
+ """``List<Header>`` bares to ``List``, marked a builtin: the value is a
+ List and not a Header, so only a repo extension on ``List`` answers."""
body = "fun run() {\n val items: List<Header> = call.headers\n}"
- assert "items" not in declared_types(body, "kotlin")
+ assert external_type_name(declared_types(body, "kotlin")["items"]) == "List"
def test_a_named_argument_is_not_a_declaration(self) -> None:
"""Kotlin spells a named argument with ``=``, which is why the
@@ -314,8 +314,12 @@ class TestKotlinRefusals:
body = 'class C {\n @get:JvmName("x")\n fun f() { }\n}'
assert declared_types(body, "kotlin") == {}
- def test_a_builtin_type_is_refused(self) -> None:
- assert declared_types("fun run(name: String, n: Int) { }", "kotlin") == {}
+ def test_a_builtin_type_is_marked_external(self) -> None:
+ types = declared_types("fun run(name: String, n: Int) { }", "kotlin")
+ assert {name: external_type_name(t) for name, t in types.items()} == {
+ "name": "String",
+ "n": "Int",
+ }
def test_a_declaration_in_a_line_comment_is_ignored(self) -> None:
body = "fun run() { // a val node: Node once lived here\n }"