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): bind Kotlin operator invoke calls and multiplatform declarations by source set (#3733)

Swati Ahujaf17c901359f9
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 8b6cdb9b5..93ea2d157 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -7,6 +7,7 @@ targets and crate roots that no import statement names.
from __future__ import annotations
import re
+from collections.abc import Iterator
from dataclasses import dataclass, replace
from typing import Any
@@ -20,6 +21,7 @@ from .lang_helpers.kotlin_lambdas import in_lambda
from .languages.receiver_types import dart_named_constructors
from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
+from .resolvers.jvm_gradle import declaration_rank, source_set_dir
from .symbol_identity import outer_scope
from .type_names import bare_type_name, kotlin_extension_receiver
@@ -57,6 +59,11 @@ _BUILD_ROOT_LANGUAGES = frozenset({"dart", "java", "kotlin", "scala", "swift"})
_TYPED_RECEIVER = ("_resolve_typed_receiver",)
+# Kotlin Multiplatform's common declaration, and a rank worse than any
+# ``declaration_rank`` returns.
+_EXPECT = "expect"
+_NO_RANK = 3
+
def _gradle_script_receiver(path: str) -> str | None:
"""The ``this`` a Gradle Kotlin script's own code runs with."""
@@ -142,6 +149,9 @@ class LanguageStrategiesMixin:
self._go_index: Any = None
self._go_index_built = False
+ # Whether any symbol is a Kotlin Multiplatform ``expect``; None until asked.
+ self._has_expect: bool | None = 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}
@@ -424,19 +434,56 @@ class LanguageStrategiesMixin:
index = self._get_jvm_index()
if index is None:
return None
- found: str | None = None
- for sibling in self._same_package_siblings(index, file_path):
- sym_id = self._package_symbol(sibling, call.target_name, caller_id)
- if sym_id is not None:
- if not unique_only:
- return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")
- if found is not None:
- # Two siblings declare it and nothing here can tell them apart.
- return None
- found = sym_id
- if found is None:
+ found = (
+ (sibling, sym_id)
+ for sibling in self._same_package_siblings(index, file_path)
+ if (sym_id := self._package_symbol(sibling, call.target_name, caller_id)) is not None
+ )
+ if unique_only:
+ # Two siblings declare it and, for Java, nothing here can tell them apart.
+ first, second = next(found, None), next(found, None)
+ sym_id = first[1] if first is not None and second is None else None
+ else:
+ sym_id = self._most_visible(file_path, found)
+ if sym_id is None:
return None
- return ResolvedCall(caller_id, found, 0.90, call.line, "same_package")
+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")
+
+ def _most_visible(self, file_path: str, found: Iterator[tuple[str, str]]) -> str | None:
+ """The first of *found*'s ``(file, symbol id)`` declarations *file_path* sees most directly.
+
+ A Kotlin Multiplatform name has one declaration per source set; see
+ ``declaration_rank``. *found* is read lazily: the first declaration
+ answers when no rank can tell them apart, and one in the caller's own
+ source set ends the search.
+ """
+ if source_set_dir(file_path) is None and not self._repo_declares_expect():
+ return next(found, (None, None))[1]
+ best: str | None = None
+ best_rank = _NO_RANK
+ for path, sym_id in found:
+ rank = declaration_rank(file_path, path, self._is_expect(sym_id))
+ if rank == 0:
+ return sym_id
+ if rank < best_rank:
+ best, best_rank = sym_id, rank
+ return best
+
+ def _is_expect(self, sym_id: str) -> bool:
+ """Is *sym_id* an ``expect`` declaration, or a member of an ``expect`` type?"""
+ symbol = self._symbols_by_id[sym_id]
+ if _EXPECT in symbol.modifiers:
+ return True
+ if symbol.parent_name is None:
+ return False
+ owner = self._symbols_by_id.get(self._caller_class_id(sym_id))
+ return owner is not None and _EXPECT in owner.modifiers
+
+ def _repo_declares_expect(self) -> bool:
+ """Does any repository symbol carry ``expect``? Asked once."""
+ if self._has_expect is None:
+ self._has_expect = any(_EXPECT in s.modifiers for s in self._symbols_by_id.values())
+ return self._has_expect
def _package_symbol(self, sibling: str, name: str, caller_id: str) -> str | None:
"""What *name* means in *sibling* to a bare call from another package file.
@@ -473,11 +520,15 @@ class LanguageStrategiesMixin:
index = self._get_jvm_index()
if index is None:
return None
- for sibling in self._same_package_siblings(index, file_path):
- sym_id = self._file_methods.get(sibling, {}).get(key)
- if sym_id is not None:
- return ResolvedCall(caller_id, sym_id, 0.90, call.line, "receiver_same_package")
- return None
+ found = (
+ (sibling, sym_id)
+ for sibling in self._same_package_siblings(index, file_path)
+ if (sym_id := self._file_methods.get(sibling, {}).get(key)) is not None
+ )
+ sym_id = self._most_visible(file_path, found)
+ if sym_id is None:
+ return None
+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "receiver_same_package")
def _resolve_go_package_call(
self,
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index b4b0a88d3..04edc8408 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -62,6 +62,7 @@ from .models import (
)
from .resolved_call import ResolvedCall
from .resolvers.cpp import _SOURCE_TU_EXTS
+from .resolvers.jvm_workspace import classify_jvm_import
from .return_types import (
declared_return_type,
normalize_return_type,
@@ -147,6 +148,23 @@ _NON_CALLABLE_KINDS = frozenset({"property"})
_PROPERTY_VARIABLE_LANGUAGES = frozenset({"kotlin", "swift"})
+# Kotlin's call operator: ``f(x)`` on a value is ``f.invoke(x)`` when its type
+# declares an ``operator fun invoke``.
+_INVOKE_OPERATOR = "invoke"
+_OPERATOR_MODIFIER = "operator"
+
+
+def _imports_a_library(imp: Import) -> bool:
+ """Does *imp* name a JVM library namespace the repository does not hold?"""
+ if classify_jvm_import(imp.module_path, kotlin=True) is None:
+ return False
+ return not imp.resolved_file or imp.resolved_file.startswith(_EXTERNAL_PREFIX)
+
+
+def _is_kotlin_alias(sym: Symbol | None) -> bool:
+ return sym is not None and sym.kind == "type_alias" and sym.language == "kotlin"
+
+
def _is_data_member(sym: Symbol) -> bool:
if sym.kind in _NON_CALLABLE_KINDS:
return True
@@ -545,6 +563,8 @@ 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()
+ # {Kotlin file: names it imports from a library namespace}
+ self._library_names: dict[str, frozenset[str]] = {}
# 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``.
@@ -1375,12 +1395,113 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
call: CallSite,
caller_id: str,
) -> ResolvedCall | None:
- """A receiver-less call, refused where it lands on an extension it has no receiver for."""
+ """A receiver-less call, refused where it lands on an extension it has no receiver for.
+
+ Also refused on a Kotlin ``typealias``: ``IOException(..)`` through
+ ``actual typealias IOException = java.io.IOException`` constructs the
+ aliased type, which the alias is not. Ceiling: an alias of a repo class
+ draws no edge to that class.
+ """
+ invoked = self._operator_invoke_call(file_path, call, caller_id)
+ if invoked is not None:
+ return invoked
hit = self._resolve_free_call(file_path, call, caller_id)
+ if hit is not None and _is_kotlin_alias(self._symbols_by_id.get(hit.callee_id)):
+ return None
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 hit
+ def _operator_invoke_call(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """``useCase(args)`` on a Kotlin value whose type declares ``operator fun invoke``.
+
+ The name is typed as the receiver of ``useCase.invoke(args)``: a local,
+ a parameter, a property of the caller's class or of its file. A local or
+ parameter outranks every function of the name. A property does not
+ outrank a function its own scope declares (Kotlin prefers the function
+ at one level), so a member or top-level ``fun`` of the name leaves the
+ call to the function tiers. The operator may be inherited. A name no
+ declaration types, or a type with no such operator, falls through to
+ the function tiers too.
+ """
+ if not self._may_invoke(file_path, call):
+ return None
+ typed = self._invoked_value_type(file_path, call, caller_id)
+ if typed is None:
+ return None
+ type_name, scope, typing_file = typed
+ as_member = replace(call, receiver_name=call.target_name, target_name=_INVOKE_OPERATOR)
+ if "::" in type_name:
+ hit = self._call_typed_receiver(file_path, as_member, caller_id, type_name)
+ return hit if hit is not None and self._is_operator_invoke(hit.callee_id) else None
+ found = self._invoke_target(typing_file, as_member, caller_id, type_name)
+ if found is None:
+ return None
+ typed_call = self._field_typed_call if scope == "field" else self._body_typed_call
+ return typed_call(caller_id, found[0], found[1], call.line)
+
+ def _may_invoke(self, file_path: str, call: CallSite) -> bool:
+ """Is *call* a bare Kotlin call in a repo that declares some ``invoke`` method?"""
+ return (
+ call.receiver_call is None
+ and self._language_of(file_path) == "kotlin"
+ and _INVOKE_OPERATOR in self._method_names()
+ )
+
+ def _invoke_target(
+ self, typing_file: str, as_member: CallSite, caller_id: str, type_name: str
+ ) -> tuple[str, str] | None:
+ """``(operator invoke id, tier)`` *type_name* declares or inherits, if any."""
+ found = self._typed_receiver_target(
+ typing_file, as_member, caller_id, type_name
+ ) or self._inherited_typed_target(
+ typing_file, as_member, caller_id, id_segment_name(type_name)
+ )
+ return found if found is not None and self._is_operator_invoke(found[0]) else None
+
+ def _invoked_value_type(
+ self, file_path: str, call: CallSite, caller_id: str
+ ) -> tuple[str, str, str] | None:
+ """``(type, scope, typing file)`` of the value a bare Kotlin call names, if it may invoke.
+
+ None for an untyped or builtin-typed name, and for a property (not a
+ local or parameter) whose scope also declares a function of the name.
+ """
+ name = call.target_name
+ type_name, scope, typing_file = self._receiver_type_and_scope(
+ file_path, caller_id, "kotlin", name
+ )
+ if type_name is None:
+ type_name, scope = self._module_types_in(file_path, "kotlin").get(name), "module"
+ if type_name is None or external_type_name(type_name) is not None:
+ return None
+ if scope != "body" and self._function_in_scope(file_path, call, caller_id):
+ return None
+ return type_name, scope, typing_file
+
+ def _is_operator_invoke(self, sym_id: str) -> bool:
+ symbol = self._symbols_by_id.get(sym_id)
+ return (
+ symbol is not None
+ and symbol.name == _INVOKE_OPERATOR
+ and _OPERATOR_MODIFIER in symbol.modifiers
+ )
+
+ def _function_in_scope(self, file_path: str, call: CallSite, caller_id: str) -> bool:
+ """Does the caller's class, or its file at top level, declare a function *call* names?
+
+ A Kotlin ``val`` and ``fun`` of one name share an id; the id is callable
+ when the function is there.
+ """
+ own = self._enclosing_class_method(file_path, call, caller_id)
+ top = self._file_top_level.get(file_path, {}).get(call.target_name)
+ return any(sym_id in self._callable_ids for sym_id in (own, top) if sym_id is not None)
+
def _with_props(self, res: ResolvedCall | None, call: CallSite) -> ResolvedCall | None:
if res is not None and call.supplied_props is not None:
return replace(res, supplied_props=call.supplied_props)
@@ -1800,7 +1921,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
and self._language_of(file_path) == "python"
):
return None
- if not declared:
+ # A Kotlin import from a library namespace the repo does not hold
+ # (``import java.io.IOException``) binds the name just as surely.
+ if not declared or target_name in self._library_imported_names(file_path):
return None
return (
self._named_import_call(file_path, call, caller_id, binding)
@@ -1907,6 +2030,28 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return None
return ResolvedCall(caller_id, sym_id, 0.85, call.line, "import_merged")
+ def _library_imported_names(self, file_path: str) -> frozenset[str]:
+ """The names a Kotlin file binds by importing a JVM library namespace.
+
+ A namespace ``classify_jvm_import`` knows (the JDK, the Kotlin stdlib,
+ ``kotlinx``, ``androidx``) counts unless the import resolved into the
+ repo, which may be that library. An aliased import binds the alias only.
+ """
+ names = self._library_names.get(file_path)
+ if names is not None:
+ return names
+ parsed = self._parsed_files.get(file_path)
+ kotlin = parsed is not None and parsed.file_info.language == "kotlin"
+ imports = parsed.imports if kotlin else ()
+ names = frozenset(
+ name
+ for imp in imports
+ if _imports_a_library(imp)
+ for name in imp.local_names or [imp.module_path.rsplit(".", 1)[-1]]
+ ) - {"*"}
+ self._library_names[file_path] = names
+ return names
+
def _repo_wide_free_call(
self,
file_path: str,
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py
index 9e5db10e7..9526cb528 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py
@@ -184,6 +184,33 @@ def _module_dir(repo_path: Path, module_name: str, overrides: dict[str, str]) ->
# Source-set discovery
# ---------------------------------------------------------------------------
+# ``<module>/src/<set>/kotlin/``: the source-set directory a JVM file sits in.
+_SOURCE_SET_DIR_RE = re.compile(r"(?:^|/)src/[^/]+/(?=(?:java|kotlin)/)")
+
+
+def source_set_dir(path: str) -> str | None:
+ """The source-set directory *path* sits in (``okio/src/jvmMain/``), or None."""
+ match = _SOURCE_SET_DIR_RE.search(path)
+ return path[: match.end()] if match else None
+
+
+def declaration_rank(importer: str, candidate: str, is_expect: bool) -> int:
+ """How directly *importer* sees *candidate*, one of a name's declarations; lowest wins.
+
+ Kotlin Multiplatform declares a name once per source set: ``expect`` in
+ common code and ``actual`` in each platform's. A file binds its own source
+ set's declaration (0), else the ``expect`` its set depends on (1); any
+ other declaration (2) is a guess, since source-set dependencies are not
+ read: an intermediate set's ``actual`` may be visible, another platform's
+ is not. Ties keep their order. Outside multiplatform only a declaration in
+ the file's own source set (``src/main`` over ``src/test``) moves ahead.
+ """
+ own = source_set_dir(importer)
+ if own is not None and source_set_dir(candidate) == own:
+ return 0
+ return 1 if is_expect else 2
+
+
def _is_test_source_set(name: str) -> bool:
lower = name.lower()
return any(marker in lower for marker in _TEST_SOURCESET_MARKERS)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
index e44041e6e..75da41cdc 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
@@ -35,11 +35,13 @@ _PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)
# before their single-keyword prefixes in the alternation, otherwise the
# bare ``enum`` / ``annotation`` branch matches first and captures the
# literal word "class" as the type name. ``trait`` and the ``case`` /
-# ``implicit`` modifiers cover Scala's type declarations.
+# ``implicit`` modifiers cover Scala's type declarations, ``expect`` and
+# ``actual`` Kotlin Multiplatform's, whose ``actual`` is often a ``typealias``.
_TOP_LEVEL_TYPE_RE = re.compile(
r"^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+"
- r"|sealed\s+|open\s+|data\s+|value\s+|inline\s+|case\s+|implicit\s+)*"
- r"(?:annotation\s+class|enum\s+class|class|interface|trait|enum|object|record|annotation)\s+(\w+)",
+ r"|sealed\s+|open\s+|data\s+|value\s+|inline\s+|case\s+|implicit\s+|expect\s+|actual\s+)*"
+ r"(?:annotation\s+class|enum\s+class|class|interface|trait|enum|object|record|annotation"
+ r"|typealias)\s+(\w+)",
re.MULTILINE,
)
_JVM_EXTENSIONS = frozenset({".java", ".kt", ".scala"})
@@ -113,7 +115,7 @@ _KOTLIN_STDLIB_PREFIXES = ("kotlin.",)
# ``Filter.java``. Unlike stdlib these only apply AFTER exact workspace
# lookup fails — a repo can legitimately contain these namespaces (the
# library's own source tree).
-_JAVA_EXTERNAL_PREFIXES = ("jakarta.",)
+_JAVA_EXTERNAL_PREFIXES = ("jakarta.", "android.", "androidx.")
_KOTLIN_EXTERNAL_PREFIXES = ("kotlinx.",)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
index 1a3e3bd51..1d8bae2e9 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
@@ -10,6 +10,7 @@ from __future__ import annotations
from pathlib import PurePosixPath
from typing import TYPE_CHECKING
+from .jvm_gradle import declaration_rank
from .jvm_workspace import classify_jvm_import, get_or_build_jvm_index
from .kotlin_gradle import resolve_via_kotlin_index
@@ -62,16 +63,12 @@ def resolve_kotlin_import_all(
return files
return (ctx.add_external_node(module_path),) if module_path else ()
- # Try JVM workspace index first (handles cross-language Java ↔ Kotlin)
- files = jvm_index.files_for_fqn(module_path)
+ # Try JVM workspace index first (handles cross-language Java ↔ Kotlin).
+ # Member imports (``import okio.ByteString.Companion.encodeUtf8``) name a
+ # function/constant inside a type, so the declaring type resolves them.
+ files = jvm_index.files_for_fqn(module_path) or jvm_index.files_for_member_fqn(module_path)
if files:
- return files
-
- # Member imports: ``import okio.ByteString.Companion.encodeUtf8``
- # names a function/constant inside a type — resolve the declaring type.
- files = jvm_index.files_for_member_fqn(module_path)
- if files:
- return files
+ return _visible_first(files, set(parts[1:]), importer_path, ctx)
# Gradle-aware resolution (settings.gradle subprojects)
gradle_match = resolve_via_kotlin_index(module_path, ctx)
@@ -107,3 +104,24 @@ def resolve_kotlin_import_all(
return (p,)
return (ctx.add_external_node(module_path),)
+
+
+def _visible_first(
+ files: tuple[str, ...], names: set[str], importer_path: str, ctx: ResolverContext
+) -> tuple[str, ...]:
+ """*files* with the declaration *importer_path* sees most directly first.
+
+ The first file is the one the import binds (``declaration_rank``). A file
+ holds the ``expect`` declaration when it declares one of the imported
+ path's names ``expect``.
+ """
+ if len(files) < 2:
+ return files
+ parsed = ctx.parsed_files or {}
+
+ def rank(path: str) -> int:
+ symbols = parsed[path].symbols if path in parsed else ()
+ expect = any("expect" in s.modifiers and s.name in names for s in symbols)
+ return declaration_rank(importer_path, path, expect)
+
+ return tuple(sorted(files, key=rank))
diff --git a/tests/unit/ingestion/test_kotlin_multiplatform_calls.py b/tests/unit/ingestion/test_kotlin_multiplatform_calls.py
new file mode 100644
index 000000000..6c59dff15
--- /dev/null
+++ b/tests/unit/ingestion/test_kotlin_multiplatform_calls.py
@@ -0,0 +1,150 @@
+"""A Kotlin call binds the declaration its source set sees.
+
+``Foo`` is declared ``expect`` in ``commonMain`` and ``actual`` in each
+platform's source set. Common code calls the ``expect``; a platform file calls
+its own ``actual``; another platform's ``actual`` is never the callee, whether
+the name is reached through the package or through an import. An ``actual
+typealias`` names a type outside the repo, so a call through it has no callee,
+as does a name imported from a library namespace. A plain Gradle project ranks
+the same way: ``src/main`` code calls its own declaration, ``src/test`` its own.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+_SRC = "lib/src/{}/kotlin/"
+_EXPECT = "package p\n\nexpect class Foo() {\n fun size(): Int\n}\n"
+_ACTUAL = (
+ "package p\n\nactual class Foo actual constructor() {\n actual fun size(): Int = 0\n}\n"
+)
+_PLATFORM = "package n\n\nactual class Plat\n"
+
+MULTIPLATFORM = {
+ # Sorted first, so a first-found answer lands on another platform.
+ _SRC.format("appleMain") + "p/Foo.kt": _ACTUAL,
+ _SRC.format("commonMain") + "p/Foo.kt": _EXPECT,
+ _SRC.format("jvmMain") + "p/Foo.kt": _ACTUAL,
+ _SRC.format("commonMain") + "p/Common.kt": "package p\n\nfun common() = Foo()\n",
+ _SRC.format("jvmMain") + "p/Jvm.kt": "package p\n\nfun jvm() = Foo()\n",
+ _SRC.format("commonMain") + "q/Other.kt": "package q\n\nimport p.Foo\n\nfun other() = Foo()\n",
+ _SRC.format("jvmMain") + "q/OtherJvm.kt": (
+ "package q\n\nimport p.Foo\n\nfun otherJvm() = Foo()\n"
+ ),
+ _SRC.format("commonMain") + "p/Errors.kt": (
+ "package p\n\nexpect open class IOException(message: String?)\n\nexpect class Missing\n"
+ ),
+ _SRC.format("jvmMain") + "p/JvmErrors.kt": (
+ "package p\n\nactual typealias IOException = java.io.IOException\n"
+ ),
+ _SRC.format("commonMain") + "p/Fail.kt": 'package p\n\nfun fail() = IOException("x")\n',
+ _SRC.format("jvmMain") + "p/FailJvm.kt": 'package p\n\nfun failJvm() = IOException("x")\n',
+ _SRC.format("jvmMain") + "q/FailOther.kt": (
+ 'package q\n\nimport p.IOException\n\nfun failOther() = IOException("x")\n'
+ ),
+ _SRC.format("jvmMain") + "q/Io.kt": (
+ 'package q\n\nimport java.io.IOException\nimport p.Missing\n\nfun io() = IOException("x")\n'
+ ),
+ # Library imports: a repo package declaring the same simple names.
+ _SRC.format("jvmMain") + "r/Things.kt": (
+ "package r\n\nclass File\n\nclass Job\n\nclass Marker\n"
+ ),
+ _SRC.format("jvmMain") + "s/Coroutines.kt": (
+ "package s\n\nimport kotlinx.coroutines.Job\nimport r.Marker\n\nfun coroutines() = Job()\n"
+ ),
+ _SRC.format("jvmMain") + "s/Aliased.kt": (
+ "package s\n\nimport java.io.File as JFile\nimport r.Marker\n\nfun aliased() = File()\n"
+ ),
+ # Several actuals and no expect.
+ _SRC.format("appleMain") + "n/Plat.kt": _PLATFORM,
+ _SRC.format("jvmMain") + "n/Plat.kt": _PLATFORM,
+ _SRC.format("jvmMain") + "n/UseJvm.kt": "package n\n\nfun useJvm() = Plat()\n",
+ _SRC.format("nativeMain") + "n/UseNative.kt": "package n\n\nfun useNative() = Plat()\n",
+}
+
+_APP = "app/src/{}/kotlin/m/"
+PLAIN_GRADLE = {
+ _APP.format("main") + "Helper.kt": "package m\n\nclass Helper\n",
+ _APP.format("test") + "Helper.kt": "package m\n\nclass Helper\n",
+ _APP.format("main") + "UseMain.kt": "package m\n\nfun useMain() = Helper()\n",
+ _APP.format("test") + "UseTest.kt": "package m\n\nfun useTest() = Helper()\n",
+}
+
+
+def _calls(repo: Path, files: dict[str, str]) -> dict[str, set[str]]:
+ for rel, text in files.items():
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in FileTraverser(repo).traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ graph = builder.build()
+ out: dict[str, set[str]] = {}
+ for caller, callee, data in graph.edges(data=True):
+ if data.get("edge_type") == "calls":
+ out.setdefault(caller.rsplit("::", 1)[-1], set()).add(callee)
+ return out
+
+
[email protected](scope="module")
+def calls(tmp_path_factory: pytest.TempPathFactory) -> dict[str, set[str]]:
+ return _calls(tmp_path_factory.mktemp("kmp"), MULTIPLATFORM)
+
+
[email protected](scope="module")
+def plain_calls(tmp_path_factory: pytest.TempPathFactory) -> dict[str, set[str]]:
+ return _calls(tmp_path_factory.mktemp("plain"), PLAIN_GRADLE)
+
+
+ ("caller", "source_set"),
+ [
+ ("common", "commonMain"), # package sibling, common code
+ ("jvm", "jvmMain"), # package sibling, platform code
+ ("other", "commonMain"), # imported, common code
+ ("otherJvm", "jvmMain"), # imported, platform code
+ ],
+)
+def test_a_call_binds_the_declaration_its_source_set_sees(
+ calls: dict[str, set[str]], caller: str, source_set: str
+) -> None:
+ assert calls[caller] == {_SRC.format(source_set) + "p/Foo.kt::Foo"}
+
+
+def test_common_code_calls_the_expect_type(calls: dict[str, set[str]]) -> None:
+ assert calls["fail"] == {_SRC.format("commonMain") + "p/Errors.kt::IOException"}
+
+
[email protected]("caller", ["failJvm", "failOther", "io", "coroutines"])
+def test_a_call_through_an_alias_or_library_import_has_no_callee(
+ calls: dict[str, set[str]], caller: str
+) -> None:
+ assert caller not in calls
+
+
+def test_an_aliased_library_import_binds_only_its_alias(calls: dict[str, set[str]]) -> None:
+ assert calls["aliased"] == {_SRC.format("jvmMain") + "r/Things.kt::File"}
+
+
+def test_without_an_expect_a_platform_calls_its_own_actual(calls: dict[str, set[str]]) -> None:
+ assert calls["useJvm"] == {_SRC.format("jvmMain") + "n/Plat.kt::Plat"}
+
+
+def test_without_an_expect_or_own_actual_the_first_in_package_order_answers(
+ calls: dict[str, set[str]],
+) -> None:
+ # Source-set dependencies are not read, so this is a guess, kept stable.
+ assert calls["useNative"] == {_SRC.format("appleMain") + "n/Plat.kt::Plat"}
+
+
[email protected](("caller", "source_set"), [("useMain", "main"), ("useTest", "test")])
+def test_a_plain_gradle_source_set_calls_its_own_declaration(
+ plain_calls: dict[str, set[str]], caller: str, source_set: str
+) -> None:
+ assert plain_calls[caller] == {_APP.format(source_set) + "Helper.kt::Helper"}
diff --git a/tests/unit/ingestion/test_kotlin_operator_invoke.py b/tests/unit/ingestion/test_kotlin_operator_invoke.py
new file mode 100644
index 000000000..a1beb57ed
--- /dev/null
+++ b/tests/unit/ingestion/test_kotlin_operator_invoke.py
@@ -0,0 +1,152 @@
+"""A Kotlin call on a value reaches its type's ``operator fun invoke``.
+
+``getTopics()`` where ``getTopics`` is a property, a parameter or a local of a
+type declaring ``operator fun invoke`` calls that ``invoke``. A function-typed
+value, a type without the operator and a plain function keep their own
+answers.
+"""
+
+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.models import FileInfo
+from repowise.core.ingestion.parser import parse_file
+
+SOURCE = """\
+package app
+
+class GetTopicsUseCase {
+ operator fun invoke(sortBy: Int = 0): List<String> = emptyList()
+}
+
+class Plain {
+ fun invoke(): Int = 0
+}
+
+fun helper(): Int = 1
+
+open class BaseUseCase {
+ operator fun invoke(): Int = 0
+}
+
+class ChildUseCase : BaseUseCase()
+
+class Parser {
+ operator fun invoke(x: Int): Int = x
+}
+
+class Reader(val parse: Parser) {
+ fun parse(x: Int): Int = x
+
+ fun f() = parse(1)
+
+ fun g(parse: Parser) = parse(2)
+}
+
+val topLogger: GetTopicsUseCase = GetTopicsUseCase()
+
+fun useTop() = topLogger()
+
+class TopicsViewModel(
+ private val getTopics: GetTopicsUseCase,
+ private val plain: Plain,
+ private val child: ChildUseCase,
+) {
+ lateinit var logger: GetTopicsUseCase
+
+ fun load() {
+ getTopics(1)
+ }
+
+ fun log() {
+ logger()
+ }
+
+ fun plainValue() {
+ plain()
+ }
+
+ fun withCallback(onDone: () -> Unit) {
+ onDone()
+ }
+
+ fun local() {
+ val useCase: GetTopicsUseCase = GetTopicsUseCase()
+ useCase()
+ }
+
+ fun function() {
+ helper()
+ }
+
+ fun inherited() {
+ child()
+ }
+}
+"""
+
+
+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"))}
+ # The graph builder resolves ``ChildUseCase : BaseUseCase()`` before calls.
+ heritage = {"App.kt::ChildUseCase": {"App.kt::BaseUseCase"}}
+ resolver = CallResolver(
+ parsed, {"App.kt": set()}, repo_path=str(tmp_path), heritage_parents=heritage
+ )
+ return {
+ rc.callee_id
+ for rc in resolver.resolve_file("App.kt", parsed["App.kt"].calls)
+ if rc.caller_id == f"App.kt::{caller.replace('.', '::')}"
+ }
+
+
[email protected]("caller", ["TopicsViewModel.load", "TopicsViewModel.log", "useTop"])
+def test_a_typed_value_call_reaches_its_operator_invoke(tmp_path: Path, caller: str) -> None:
+ assert _callees(tmp_path, caller) == {"App.kt::GetTopicsUseCase::invoke"}
+
+
+def test_a_typed_local_call_reaches_its_operator_invoke(tmp_path: Path) -> None:
+ assert "App.kt::GetTopicsUseCase::invoke" in _callees(tmp_path, "TopicsViewModel.local")
+
+
+def test_an_invoke_without_the_operator_is_not_called(tmp_path: Path) -> None:
+ assert "App.kt::Plain::invoke" not in _callees(tmp_path, "TopicsViewModel.plainValue")
+
+
+def test_a_function_typed_value_has_no_repo_callee(tmp_path: Path) -> None:
+ assert _callees(tmp_path, "TopicsViewModel.withCallback") == set()
+
+
+def test_a_plain_function_call_is_unchanged(tmp_path: Path) -> None:
+ assert _callees(tmp_path, "TopicsViewModel.function") == {"App.kt::helper"}
+
+
+def test_an_inherited_operator_invoke_is_reached(tmp_path: Path) -> None:
+ assert _callees(tmp_path, "TopicsViewModel.inherited") == {"App.kt::BaseUseCase::invoke"}
+
+
+def test_a_member_function_outranks_a_property_of_its_name(tmp_path: Path) -> None:
+ assert _callees(tmp_path, "Reader.f") == {"App.kt::Reader::parse"}
+
+
+def test_a_parameter_outranks_a_member_function_of_its_name(tmp_path: Path) -> None:
+ assert _callees(tmp_path, "Reader.g") == {"App.kt::Parser::invoke"}