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 Kotlin multiplatform calls only to declarations their source set sees (#3831)
Aman3172bc0c24a2
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.pyindex 4b1798748..f1767310c 100644--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py@@ -21,7 +21,12 @@ from .lang_helpers.kotlin_lambdas import in_lambdafrom .languages.receiver_types import dart_named_constructorsfrom .models import CallSite, ParsedFile, Symbolfrom .resolved_call import ResolvedCall-from .resolvers.jvm_gradle import declaration_rank, source_set_dir+from .resolvers.jvm_gradle import (+ SourceSetGraph,+ build_source_set_graph,+ declaration_rank,+ source_set_dir,+)from .symbol_identity import outer_scopefrom .type_names import bare_type_name@@ -59,10 +64,8 @@ _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.+# Kotlin Multiplatform's common declaration._EXPECT = "expect"-_NO_RANK = 3def _gradle_script_receiver(path: str) -> str | None:@@ -152,6 +155,9 @@ class LanguageStrategiesMixin:# Whether any symbol is a Kotlin Multiplatform ``expect``; None until asked.self._has_expect: bool | None = None+ # Kotlin Multiplatform source-set dependencies; None until asked.+ self._source_set_graph: SourceSetGraph | None = None+# {Dart class id: the named constructors its body declares}self._dart_constructors: dict[str, frozenset[str]] = {}@@ -453,20 +459,34 @@ class LanguageStrategiesMixin:A Kotlin Multiplatform name has one declaration per source set; see``declaration_rank``. *found* is read lazily: the first declarationanswers when no rank can tell them apart, and one in the caller's own- source set ends the search.+ source set ends the search. A declaration in a source set the caller+ cannot see is skipped."""if source_set_dir(file_path) is None and not self._repo_declares_expect():return next(found, (None, None))[1]+ graph = self._get_source_set_graph()best: str | None = None- best_rank = _NO_RANK+ best_rank: int | None = Nonefor path, sym_id in found:- rank = declaration_rank(file_path, path, self._is_expect(sym_id))+ rank = declaration_rank(file_path, path, self._is_expect(sym_id), graph)+ if rank is None:+ continueif rank == 0:return sym_id- if rank < best_rank:+ if best_rank is None or rank < best_rank:best, best_rank = sym_id, rankreturn best+ def _get_source_set_graph(self) -> SourceSetGraph:+ """The repository's Kotlin Multiplatform source-set dependencies. Built once."""+ if self._source_set_graph is None:+ from pathlib import Path++ self._source_set_graph = build_source_set_graph(+ self._parsed_files, Path(self._repo_path) if self._repo_path else None+ )+ return self._source_set_graph+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]diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.pyindex 1f519465d..e5b76343b 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport osimport re+from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom functools import lru_cachefrom pathlib import Path@@ -195,21 +196,310 @@ def source_set_dir(path: str) -> str | None:return path[: match.end()] if match else None-def declaration_rank(importer: str, candidate: str, is_expect: bool) -> int:+# ---------------------------------------------------------------------------+# Kotlin Multiplatform source-set visibility+# ---------------------------------------------------------------------------++# ``dependsOn(commonMain)`` / ``jvmMain.dependsOn(zlibMain)`` in a build script.+_DEPENDS_ON_RE = re.compile(r"\bdependsOn\b")+_SET_CALL = r"""(?:getByName|named|maybeCreate|create)\s*\(\s*["'](\w+)["']\s*\)"""+_SET_INDEX = r"""sourceSets\s*\[\s*["'](\w+)["']\s*\]"""+# What follows ``dependsOn``: ``(commonMain)``, ``(sourceSets.commonMain)``,+# ``(getByName("commonMain"))``, ``(sourceSets["commonMain"])``, or Groovy's bare ``commonMain``.+_DEPENDS_ON_ARG_RE = re.compile(+ rf"\s*\(?\s*(?:sourceSets\s*\.\s*)?(?:{_SET_CALL}|{_SET_INDEX}|(\w+))"+)+# The receiver of ``x.dependsOn(..)``, read backwards from the dot.+_RECEIVER_RE = re.compile(rf"(?:{_SET_CALL}|{_SET_INDEX}|(\w+))\s*\.\s*$")+# The block a bare ``dependsOn(..)`` sits in, from the text before its ``{``.+_BLOCK_HEADERS = (+ re.compile(r"(?:val|var)\s+(\w+)\s+by\s+(?:getting|creating|registering)\s*$"),+ re.compile(rf"{_SET_CALL}\s*$"),+ re.compile(r"(?:getByName|named|maybeCreate|create|register)\s*\(\s*[\"'](\w+)[\"']\s*\)\s*$"),+ re.compile(_SET_INDEX + r"\s*$"),+ re.compile(r"(\w+)\s*$"),+)+# ``jvm("desktop")``: a custom-named target, whose source sets the default+# hierarchy template still hangs under the common ones.+_TARGET_RE = re.compile(r"""\b(?:jvm|js|wasmJs|wasmWasi)\s*\(\s*["'](\w+)["']""")+_MULTIPLATFORM_PLUGIN_RE = re.compile(+ r"""kotlin\s*\(\s*["']multiplatform["']\s*\)|kotlin[-.]?multiplatform|kotlinMultiplatform""",+ re.IGNORECASE,+)++# The default hierarchy template (Kotlin 1.9.20+): who each platform group sits under.+_COMMON = "common"+_TEMPLATE_GROUP_PARENT = {+ "jvm": _COMMON,+ "js": _COMMON,+ "wasmJs": _COMMON,+ "wasmWasi": _COMMON,+ "android": _COMMON,+ "androidUnit": _COMMON, # androidUnitTest, androidInstrumentedTest+ "androidInstrumented": _COMMON,+ "native": _COMMON,+ "apple": "native",+ "linux": "native",+ "mingw": "native",+ "androidNative": "native",+ "ios": "apple",+ "macos": "apple",+ "tvos": "apple",+ "watchos": "apple",+}+# ``iosArm64Main`` sits under ``iosMain``, ``linuxX64Main`` under ``linuxMain``, ...+_TEMPLATE_TARGET_RE = re.compile(r"^(ios|macos|tvos|watchos|linux|mingw|androidNative)[A-Z]\w*$")+++def _split_source_set_name(name: str) -> tuple[str, str] | None:+ """``("jvm", "Main")`` for ``jvmMain``; None when *name* ends in neither ``Main`` nor ``Test``."""+ for suffix in ("Main", "Test"):+ if name.endswith(suffix) and len(name) > len(suffix):+ return name[: -len(suffix)], suffix+ return None+++def _template_stem_parent(stem: str) -> str | None:+ if stem in _TEMPLATE_GROUP_PARENT:+ return _TEMPLATE_GROUP_PARENT[stem]+ match = _TEMPLATE_TARGET_RE.match(stem)+ return match.group(1) if match else None+++def _is_template_set(name: str) -> bool:+ """Is *name* a source set only a Kotlin Multiplatform module has?"""+ split = _split_source_set_name(name)+ if split is None:+ return False+ stem = split[0]+ # ``src/androidTest`` is an ordinary Android app's instrumented-test set.+ return not stem.startswith("android") and (+ stem == _COMMON or _template_stem_parent(stem) is not None+ )+++def _template_deps(name: str) -> tuple[str, ...]:+ """The source sets the default hierarchy template makes *name* depend on.++ ``linuxMain`` -> ``nativeMain`` -> ``commonMain``; a test set mirrors its+ main set's tree and also sees that main set (``jvmTest`` -> ``jvmMain``,+ ``commonTest`` -> ``commonMain``).+ """+ split = _split_source_set_name(name)+ if split is None:+ return ()+ stem, suffix = split+ deps: list[str] = []+ parent = _template_stem_parent(stem)+ if parent is not None:+ deps.append(parent + suffix)+ if suffix == "Test":+ main = "android" if stem in ("androidUnit", "androidInstrumented") else stem+ deps.append(main + "Main")+ return tuple(deps)+++def _plausible_source_set(name: str, known: set[str]) -> bool:+ return name in known or _split_source_set_name(name) is not None+++def _block_header(text: str, pos: int) -> str | None:+ """The statement before the ``{`` that encloses *pos*, or None at top level."""+ depth = 0+ for i in range(pos - 1, -1, -1):+ char = text[i]+ if char == "}":+ depth += 1+ elif char == "{":+ if depth == 0:+ return re.split(r"[\n;{}]", text[max(0, i - 200) : i])[-1]+ depth -= 1+ return None+++def _parse_source_set_edges(script: str, known: set[str]) -> dict[str, list[str]]:+ """``{source set: the sets it explicitly depends on}`` from a build script's text.++ Reads ``x.dependsOn(y)`` and a bare ``dependsOn(y)`` inside the block that+ configures ``x`` (``val x by getting { .. }``, ``getByName("x") { .. }``,+ ``x { .. }``), plus custom-named targets such as ``jvm("desktop")``. A+ task's ``dependsOn`` is not an edge: both ends have to look like source sets.+ """+ edges: dict[str, list[str]] = {}++ def add(source: str, target: str) -> None:+ if (+ source != target+ and _plausible_source_set(source, known)+ and _plausible_source_set(target, known)+ and target not in edges.setdefault(source, [])+ ):+ edges[source].append(target)++ for match in _DEPENDS_ON_RE.finditer(script):+ arg = _DEPENDS_ON_ARG_RE.match(script, match.end())+ if arg is None:+ continue+ target = arg.group(1) or arg.group(2) or arg.group(3)+ before = script[: match.start()].rstrip()+ if before.endswith("."):+ receiver = _RECEIVER_RE.search(before[-160:])+ if receiver is not None:+ add(receiver.group(1) or receiver.group(2) or receiver.group(3), target)+ continue+ header = _block_header(script, match.start())+ if header is None or re.search(r"\btasks\b", header):+ continue+ for pattern in _BLOCK_HEADERS:+ named = pattern.search(header)+ if named is not None:+ add(named.group(1), target)+ break++ for match in _TARGET_RE.finditer(script):+ add(match.group(1) + "Main", "commonMain")+ add(match.group(1) + "Test", "commonTest")+ return edges+++@dataclass(frozen=True)+class SourceSetModule:+ """One Kotlin Multiplatform module's source sets and what each one depends on."""++ root: str+ # Direct edges, default hierarchy template and build-script ``dependsOn`` merged.+ depends_on: dict[str, tuple[str, ...]] = field(default_factory=dict)+ _reach: dict[str, dict[str, int]] = field(default_factory=dict, repr=False, compare=False)++ def visible_from(self, name: str) -> dict[str, int]:+ """The source sets *name* sees, each with how many ``dependsOn`` steps away (itself 0)."""+ cached = self._reach.get(name)+ if cached is not None:+ return cached+ distance = {name: 0}+ queue = [name]+ for current in queue:+ for dep in self.depends_on.get(current) or _template_deps(current):+ if dep not in distance:+ distance[dep] = distance[current] + 1+ queue.append(dep)+ self._reach[name] = distance+ return distance+++@dataclass+class SourceSetGraph:+ """The source-set dependencies of every Kotlin Multiplatform module, by module directory."""++ modules: dict[str, SourceSetModule] = field(default_factory=dict)++ def scope(self, importer: str, candidate: str) -> tuple[SourceSetModule, str, str] | None:+ """``(module, importer's set, candidate's set)`` when both sit in one multiplatform module."""+ located = _locate_source_set(importer)+ other = _locate_source_set(candidate)+ if located is None or other is None or located[0] != other[0]:+ return None+ module = self.modules.get(located[0])+ return None if module is None else (module, located[1], other[1])+++def _locate_source_set(path: str) -> tuple[str, str] | None:+ """``("lib", "jvmMain")`` for ``lib/src/jvmMain/kotlin/x.kt``."""+ match = _SOURCE_SET_DIR_RE.search(path)+ if match is None:+ return None+ return path[: match.start()], match.group(0).strip("/").split("/")[1]+++def _read_build_script(module_dir: Path) -> str:+ """The comment-free text of *module_dir*'s ``build.gradle(.kts)``, or ``""``."""+ texts: list[str] = []+ for build_name in ("build.gradle.kts", "build.gradle"):+ try:+ text = (module_dir / build_name).read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ text = _GRADLE_BLOCK_COMMENT_RE.sub(lambda m: "\n" * m.group(0).count("\n"), text)+ texts.append(_GRADLE_LINE_COMMENT_RE.sub("", text))+ return "\n".join(texts)+++def build_source_set_graph(paths: Iterable[str], repo_path: Path | None) -> SourceSetGraph:+ """Each Kotlin Multiplatform module's source-set dependencies.++ Modules and their source sets come from the file *paths* (``lib/src/jvmMain/kotlin/..``),+ so a module no ``settings.gradle`` lists is still covered. A module is+ multiplatform when it has a ``commonMain``-style set or applies the+ multiplatform plugin; any other module (``src/main`` over ``src/test``) is+ left out, and its files rank by ``declaration_rank``'s plain rule.++ The edges are the default hierarchy template, plus ``dependsOn`` read from+ the module's build script. A script the reader cannot follow (a helper+ function that creates the sets) adds nothing, so it falls back to the+ template, never to a wider guess.+ """+ names_by_module: dict[str, set[str]] = {}+ for path in paths:+ located = _locate_source_set(path)+ if located is not None:+ names_by_module.setdefault(located[0], set()).add(located[1])++ graph = SourceSetGraph()+ for root, names in names_by_module.items():+ script = _read_build_script(repo_path / root) if repo_path is not None else ""+ if not (+ any(_is_template_set(name) for name in names)+ or _MULTIPLATFORM_PLUGIN_RE.search(script)+ ):+ continue+ explicit = _parse_source_set_edges(script, names)+ depends_on: dict[str, tuple[str, ...]] = {}+ for name in sorted(names | set(explicit) | {d for deps in explicit.values() for d in deps}):+ deps = list(_template_deps(name))+ deps.extend(dep for dep in explicit.get(name, ()) if dep not in deps)+ depends_on[name] = tuple(deps)+ graph.modules[root] = SourceSetModule(root=root, depends_on=depends_on)+ return graph+++def get_or_build_source_set_graph(ctx: ResolverContext) -> SourceSetGraph:+ """Return the cached :class:`SourceSetGraph`, building it on first access."""+ cached = getattr(ctx, "_source_set_graph", None)+ if cached is not None:+ return cached+ graph = build_source_set_graph(ctx.path_set, ctx.repo_path)+ ctx._source_set_graph = graph # type: ignore[attr-defined]+ return graph+++def declaration_rank(+ importer: str, candidate: str, is_expect: bool, graph: SourceSetGraph | None = None+) -> int | None:"""How directly *importer* sees *candidate*, one of a name's declarations; lowest wins.Kotlin Multiplatform declares a name once per source set: ``expect`` incommon 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.+ set's declaration (0), else the nearest set its own depends on: a source+ set's ``actual`` outranks the ``expect`` further up (``jvmTest`` -> ``jvmMain``+ -> ``commonMain``; ``linuxMain`` -> ``nativeMain``). With *graph*, a+ declaration in a set of the same module that the importer's set cannot see+ (``appleMain`` from ``linuxMain``) is no candidate: None. Ties keep their+ order. Without a graph entry for the module (a plain Gradle project, or a+ candidate in another module) only a declaration in the file's own source+ set (``src/main`` over ``src/test``) moves ahead; the ``expect`` is next (1),+ any other declaration last (2)."""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+ scope = graph.scope(importer, candidate) if graph is not None else None+ if scope is None:+ return 1 if is_expect else 2+ module, importer_set, candidate_set = scope+ steps = module.visible_from(importer_set).get(candidate_set)+ if steps is None:+ return None+ return 2 * max(steps, 1) - 1 + int(is_expect)def _is_test_source_set(name: str) -> bool:diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.pyindex 1d8bae2e9..8d9d84c51 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom pathlib import PurePosixPathfrom typing import TYPE_CHECKING-from .jvm_gradle import declaration_rank+from .jvm_gradle import declaration_rank, get_or_build_source_set_graphfrom .jvm_workspace import classify_jvm_import, get_or_build_jvm_indexfrom .kotlin_gradle import resolve_via_kotlin_index@@ -113,15 +113,18 @@ def _visible_first(The first file is the one the import binds (``declaration_rank``). A fileholds the ``expect`` declaration when it declares one of the imported- path's names ``expect``.+ path's names ``expect``. When several files declare the name, one in a+ source set the importer cannot see is dropped."""if len(files) < 2:return filesparsed = ctx.parsed_files or {}+ graph = get_or_build_source_set_graph(ctx)- def rank(path: str) -> int:+ def rank(path: str) -> int | None: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 declaration_rank(importer_path, path, expect, graph)- return tuple(sorted(files, key=rank))+ ranked = [(r, path) for path in files if (r := rank(path)) is not None]+ return tuple(path for _, path in sorted(ranked, key=lambda pair: pair[0]))diff --git a/tests/unit/ingestion/test_kotlin_multiplatform_calls.py b/tests/unit/ingestion/test_kotlin_multiplatform_calls.pyindex 6c59dff15..3b01ace6b 100644--- a/tests/unit/ingestion/test_kotlin_multiplatform_calls.py+++ b/tests/unit/ingestion/test_kotlin_multiplatform_calls.py@@ -66,6 +66,23 @@ MULTIPLATFORM = {_SRC.format("nativeMain") + "n/UseNative.kt": "package n\n\nfun useNative() = Plat()\n",}+# A test set sees its main set; a platform set sees the groups above it, not its siblings.+_V = "vis/src/{}/kotlin/"+_DECL = "package n\n\ninternal fun platformName(): String = \"x\"\n"+VISIBILITY = {+ _V.format("appleMain") + "n/Platform.kt": _DECL,+ _V.format("jvmMain") + "n/Platform.kt": _DECL,+ _V.format("nativeMain") + "n/Platform.kt": _DECL,+ _V.format("jvmTest") + "n/PlatformTest.kt": "package n\n\nfun jvmTestCaller() = platformName()\n",+ _V.format("linuxMain") + "n/UseLinux.kt": "package n\n\nfun linuxCaller() = platformName()\n",+ _V.format("commonMain") + "p/Foo.kt": "package p\n\nexpect class Foo()\n",+ _V.format("jvmMain") + "p/Foo.kt": "package p\n\nactual class Foo actual constructor()\n",+ _V.format("jvmMain") + "p/UseJvm.kt": "package p\n\nfun jvmMainCaller() = Foo()\n",+ _V.format("jvmTest") + "p/FooTest.kt": "package p\n\nfun jvmTestFooCaller() = Foo()\n",+ # Imported rather than reached through the package.+ _V.format("jvmTest") + "q/ImportTest.kt": "package q\n\nimport p.Foo\n\nfun jvmTestImports() = Foo()\n",+}+_APP = "app/src/{}/kotlin/m/"PLAIN_GRADLE = {_APP.format("main") + "Helper.kt": "package m\n\nclass Helper\n",@@ -97,6 +114,11 @@ def calls(tmp_path_factory: pytest.TempPathFactory) -> dict[str, set[str]]:return _calls(tmp_path_factory.mktemp("kmp"), MULTIPLATFORM)[email protected](scope="module")+def visibility_calls(tmp_path_factory: pytest.TempPathFactory) -> dict[str, set[str]]:+ return _calls(tmp_path_factory.mktemp("vis"), VISIBILITY)++@pytest.fixture(scope="module")def plain_calls(tmp_path_factory: pytest.TempPathFactory) -> dict[str, set[str]]:return _calls(tmp_path_factory.mktemp("plain"), PLAIN_GRADLE)@@ -136,11 +158,28 @@ def test_without_an_expect_a_platform_calls_its_own_actual(calls: dict[str, set[assert calls["useJvm"] == {_SRC.format("jvmMain") + "n/Plat.kt::Plat"}-def test_without_an_expect_or_own_actual_the_first_in_package_order_answers(+def test_without_an_expect_or_own_actual_a_set_that_sees_no_declaration_has_no_callee(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"}+ # ``nativeMain`` sees neither ``appleMain`` nor ``jvmMain``: no edge, not a guess.+ assert "useNative" not in calls+++def test_a_test_set_binds_the_declaration_its_main_set_sees(+ visibility_calls: dict[str, set[str]],+) -> None:+ jvm_main = _V.format("jvmMain")+ assert visibility_calls["jvmTestCaller"] == {jvm_main + "n/Platform.kt::platformName"}+ assert visibility_calls["jvmTestFooCaller"] == {jvm_main + "p/Foo.kt::Foo"}+ assert visibility_calls["jvmTestImports"] == {jvm_main + "p/Foo.kt::Foo"}+ assert visibility_calls["jvmMainCaller"] == {jvm_main + "p/Foo.kt::Foo"}+++def test_a_platform_group_binds_the_declaration_of_the_group_it_depends_on(+ visibility_calls: dict[str, set[str]],+) -> None:+ # ``linuxMain`` -> ``nativeMain``; its sibling ``appleMain`` is out of sight.+ assert visibility_calls["linuxCaller"] == {_V.format("nativeMain") + "n/Platform.kt::platformName"}@pytest.mark.parametrize(("caller", "source_set"), [("useMain", "main"), ("useTest", "test")])diff --git a/tests/unit/ingestion/test_kotlin_source_set_graph.py b/tests/unit/ingestion/test_kotlin_source_set_graph.pynew file mode 100644index 000000000..60304a34a--- /dev/null+++ b/tests/unit/ingestion/test_kotlin_source_set_graph.py@@ -0,0 +1,174 @@+"""The source-set dependencies a Kotlin Multiplatform call is ranked by."""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.ingestion.resolvers.jvm_gradle import (+ build_source_set_graph,+ declaration_rank,+)+++def _paths(module: str, *source_sets: str) -> list[str]:+ return [f"{module}/src/{name}/kotlin/p/F.kt" for name in source_sets]+++def _visible(graph, module: str, name: str) -> dict[str, int]: # type: ignore[no-untyped-def]+ return graph.modules[module].visible_from(name)+++def test_the_default_hierarchy_template_links_the_source_sets(tmp_path: Path) -> None:+ sets = ("commonMain", "nativeMain", "appleMain", "linuxMain", "jvmMain", "jvmTest")+ graph = build_source_set_graph(_paths("lib", *sets), tmp_path)++ assert _visible(graph, "lib", "linuxMain") == {"linuxMain": 0, "nativeMain": 1, "commonMain": 2}+ assert _visible(graph, "lib", "appleMain") == {"appleMain": 0, "nativeMain": 1, "commonMain": 2}+ assert set(_visible(graph, "lib", "jvmTest")) == {"jvmTest", "jvmMain", "commonTest", "commonMain"}+ assert "jvmMain" not in _visible(graph, "lib", "linuxMain")+ assert "appleMain" not in _visible(graph, "lib", "linuxMain")+++def test_target_specific_sets_sit_under_their_group(tmp_path: Path) -> None:+ graph = build_source_set_graph(_paths("lib", "commonMain", "iosArm64Main", "linuxX64Test"), tmp_path)++ assert list(_visible(graph, "lib", "iosArm64Main")) == [+ "iosArm64Main", "iosMain", "appleMain", "nativeMain", "commonMain",+ ] # fmt: skip+ assert {"linuxX64Main", "linuxMain", "nativeMain"} <= set(_visible(graph, "lib", "linuxX64Test"))+++def test_a_test_set_sees_its_main_set_and_common_test_sees_common_main(tmp_path: Path) -> None:+ graph = build_source_set_graph(_paths("lib", "commonMain", "commonTest"), tmp_path)++ assert _visible(graph, "lib", "commonTest") == {"commonTest": 0, "commonMain": 1}++[email protected]("script", ["build.gradle.kts", "build.gradle"])+def test_an_explicit_depends_on_adds_an_edge_the_template_does_not_have(+ tmp_path: Path, script: str+) -> None:+ (tmp_path / "lib").mkdir()+ (tmp_path / "lib" / script).write_text(+ "kotlin {\n sourceSets {\n"+ " val zlibMain by creating { dependsOn(commonMain) }\n"+ " val jvmMain by getting {\n dependsOn(zlibMain)\n }\n"+ " linuxMain.dependsOn(zlibMain)\n"+ " }\n}\n"+ )+ graph = build_source_set_graph(+ _paths("lib", "commonMain", "zlibMain", "jvmMain", "linuxMain"), tmp_path+ )++ assert _visible(graph, "lib", "jvmMain") == {"jvmMain": 0, "zlibMain": 1, "commonMain": 1}+ assert "zlibMain" in _visible(graph, "lib", "linuxMain")+ assert "zlibMain" not in _visible(graph, "lib", "commonMain")+++def test_depends_on_forms_in_the_build_script(tmp_path: Path) -> None:+ (tmp_path / "lib").mkdir()+ (tmp_path / "lib" / "build.gradle.kts").write_text(+ 'kotlin.sourceSets.getByName("aMain") { dependsOn(sourceSets["zMain"]) }\n'+ "sourceSets.bMain.dependsOn(sourceSets.getByName(\"zMain\"))\n"+ "// cMain.dependsOn(zMain)\n"+ "/* dMain.dependsOn(zMain) */\n"+ 'tasks.named("eMain") { dependsOn(zMain) }\n'+ 'compileKotlin.dependsOn(generateSources)\n'+ 'tasks.named("jvmTest") { dependsOn("prepare") }\n'+ )+ sets = ("commonMain", "aMain", "bMain", "cMain", "dMain", "eMain", "zMain")+ graph = build_source_set_graph(_paths("lib", *sets), tmp_path)++ assert "zMain" in _visible(graph, "lib", "aMain")+ assert "zMain" in _visible(graph, "lib", "bMain")+ for ignored in ("cMain", "dMain", "eMain"): # a comment, or a task's dependsOn+ assert "zMain" not in _visible(graph, "lib", ignored)+++def test_a_custom_named_target_sits_under_common(tmp_path: Path) -> None:+ (tmp_path / "app").mkdir()+ (tmp_path / "app" / "build.gradle.kts").write_text('kotlin { jvm("desktop") }\n')+ graph = build_source_set_graph(_paths("app", "commonMain", "desktopMain", "desktopTest"), tmp_path)++ assert _visible(graph, "app", "desktopTest") == {+ "desktopTest": 0, "desktopMain": 1, "commonTest": 1, "commonMain": 2,+ } # fmt: skip+++def test_a_script_the_reader_cannot_follow_falls_back_to_the_template(tmp_path: Path) -> None:+ (tmp_path / "lib").mkdir()+ (tmp_path / "lib" / "build.gradle.kts").write_text(+ 'createSourceSet("jvmMain", parent = commonMain)\n'+ )+ graph = build_source_set_graph(_paths("lib", "commonMain", "jvmMain", "linuxMain"), tmp_path)++ assert _visible(graph, "lib", "jvmMain") == {"jvmMain": 0, "commonMain": 1}+ assert "jvmMain" not in _visible(graph, "lib", "linuxMain")+++def test_a_plain_gradle_module_is_not_multiplatform(tmp_path: Path) -> None:+ paths = _paths("app", "main", "test", "integrationTest", "androidTest")+ graph = build_source_set_graph(paths, tmp_path)++ assert graph.modules == {}+++def test_the_multiplatform_plugin_marks_a_module(tmp_path: Path) -> None:+ (tmp_path / "lib").mkdir()+ (tmp_path / "lib" / "build.gradle.kts").write_text('plugins { kotlin("multiplatform") }\n')+ graph = build_source_set_graph(_paths("lib", "customMain"), tmp_path)++ assert "lib" in graph.modules+++class TestDeclarationRank:+ def _graph(self, tmp_path: Path): # type: ignore[no-untyped-def]+ sets = ("commonMain", "nativeMain", "appleMain", "linuxMain", "jvmMain", "jvmTest")+ return build_source_set_graph(_paths("lib", *sets) + _paths("app", "main", "test"), tmp_path)++ def _rank(self, graph, importer: str, candidate: str, expect: bool = False): # type: ignore[no-untyped-def]+ f = "lib/src/{}/kotlin/p/F.kt"+ return declaration_rank(f.format(importer), f.format(candidate), expect, graph)++ def test_own_set_then_nearest_actual_then_expect(self, tmp_path: Path) -> None:+ graph = self._graph(tmp_path)++ own = self._rank(graph, "linuxMain", "linuxMain")+ native_actual = self._rank(graph, "linuxMain", "nativeMain")+ common_expect = self._rank(graph, "linuxMain", "commonMain", expect=True)+ assert own == 0+ assert own < native_actual < common_expect++ def test_a_set_the_importer_cannot_see_is_not_a_candidate(self, tmp_path: Path) -> None:+ graph = self._graph(tmp_path)++ assert self._rank(graph, "linuxMain", "appleMain") is None+ assert self._rank(graph, "linuxMain", "jvmMain") is None+ assert self._rank(graph, "commonMain", "jvmMain") is None++ def test_a_test_set_ranks_its_main_actual_ahead_of_the_expect(self, tmp_path: Path) -> None:+ graph = self._graph(tmp_path)++ assert self._rank(graph, "jvmTest", "jvmMain") < self._rank(+ graph, "jvmTest", "commonMain", expect=True+ )++ def test_without_a_graph_the_rank_is_the_plain_one(self, tmp_path: Path) -> None:+ f = "lib/src/{}/kotlin/p/F.kt"++ assert declaration_rank(f.format("a"), f.format("a"), False) == 0+ assert declaration_rank(f.format("a"), f.format("b"), True) == 1+ assert declaration_rank(f.format("a"), f.format("b"), False) == 2++ def test_a_plain_gradle_module_and_other_modules_keep_the_plain_rank(+ self, tmp_path: Path+ ) -> None:+ graph = self._graph(tmp_path)+ app = "app/src/{}/kotlin/m/H.kt"+ lib = "lib/src/jvmMain/kotlin/p/F.kt"++ assert declaration_rank(app.format("test"), app.format("main"), False, graph) == 2+ assert declaration_rank(app.format("main"), lib, False, graph) == 2 # another module+ assert declaration_rank(lib, app.format("main"), True, graph) == 1