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(jvm): resolve Kotlin imports of top-level functions and properties (#3407)

Amane77259f9289a
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 464ee37d8..3eb23463f 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
@@ -44,6 +44,58 @@ _TOP_LEVEL_TYPE_RE = re.compile(
)
_JVM_EXTENSIONS = frozenset({".java", ".kt", ".scala"})
+# Kotlin top-level callables (``fun`` / ``val`` / ``var`` / ``const val``),
+# including extension forms. A Kotlin import can name one directly
+# (``import com.acme.util.shout``), and the declaring file rarely shares the
+# name (``StringUtils.kt``), so the type scan above never sees it.
+#
+# "Top level" is approximated by column 0: the match is anchored at the start
+# of the line with no leading indentation, which excludes members of a class
+# body and local declarations. It is a line scan, not a parse, so a column-0
+# declaration inside a raw string or an unindented class body is a (rare)
+# false positive.
+_KT_TOP_LEVEL_CALLABLE_RE = re.compile(
+ r"^(?P<mods>(?:(?:@\w+(?:\([^)\n]*\))?|public|internal|private|protected"
+ r"|inline|infix|operator|tailrec|suspend|external|expect|actual|const"
+ r"|lateinit|override|open|final|abstract)[ \t]+)*)"
+ r"(?P<kw>fun|val|var)[ \t]+(?P<rest>[^\n]*)",
+ re.MULTILINE,
+)
+_KT_GENERIC_RE = re.compile(r"<[^<>]*>")
+_KT_TRAILING_IDENT_RE = re.compile(r"(\w+)\s*$")
+_KT_KEYWORD_ONLY_RE = re.compile(r"^(?:interface)\b")
+
+
+def _kotlin_top_level_callables(text: str) -> tuple[str, ...]:
+ """Names of non-private top-level ``fun`` / ``val`` / ``var`` in Kotlin text.
+
+ Extension declarations yield the member name, not the receiver:
+ ``fun <T : Any> Mono<T>.captureMetrics(`` -> ``captureMetrics`` and
+ ``val String.shout: String`` -> ``shout``. ``private`` declarations are
+ file-local and cannot be imported, so they are skipped.
+ """
+ names: list[str] = []
+ for m in _KT_TOP_LEVEL_CALLABLE_RE.finditer(text):
+ if re.search(r"\bprivate\b", m.group("mods")):
+ continue
+ rest = m.group("rest")
+ if m.group("kw") == "fun" and _KT_KEYWORD_ONLY_RE.match(rest):
+ continue # ``fun interface Foo`` declares a type, not a function
+ # Drop generic argument lists (innermost first) so ``<T : Any>`` and
+ # ``Map<String, List<Int>>`` receivers cannot hide the name.
+ prev = None
+ while prev != rest:
+ prev = rest
+ rest = _KT_GENERIC_RE.sub("", rest)
+ if m.group("kw") == "fun":
+ head = rest.split("(", 1)[0]
+ else:
+ head = re.split(r":|=|\bby\b", rest, maxsplit=1)[0]
+ ident = _KT_TRAILING_IDENT_RE.search(head)
+ if ident:
+ names.append(ident.group(1))
+ return tuple(names)
+
# Chained Scala package clauses (``package org.example`` then ``package
# tools`` → org.example.tools) are scanned line-wise from the top of the
# file; ``package object foo`` is a definition, not a clause.
@@ -124,7 +176,7 @@ class JvmWorkspaceIndex:
"""Maps repo-relative file path → package FQN."""
fqn_to_files: dict[str, list[str]] = field(default_factory=dict)
- """Maps a fully-qualified class name → defining file(s)."""
+ """Maps a fully-qualified class (or Kotlin top-level function/property) name → defining file(s)."""
services: dict[str, tuple[str, ...]] = field(default_factory=dict)
"""META-INF/services/<Iface> → impl FQNs (for Phase 3/4 reachability)."""
@@ -227,9 +279,11 @@ class JvmWorkspaceIndex:
def _scan_jvm_text(abs_path: str, text: str) -> tuple[str, tuple[str, ...]]:
- """Return (package_fqn, top_level_type_names) from already-read text.
+ """Return (package_fqn, top_level_names) from already-read text.
- Cheap line scan — no AST.
+ ``top_level_names`` are the file's top-level type names and, for Kotlin
+ files, its non-private top-level ``fun`` / ``val`` / ``var`` names too —
+ both are importable by ``package.name``. Cheap line scan — no AST.
"""
if abs_path.endswith(".scala"):
package = _scala_package(text)
@@ -237,7 +291,18 @@ def _scan_jvm_text(abs_path: str, text: str) -> tuple[str, tuple[str, ...]]:
pkg_match = _PACKAGE_RE.search(text)
package = pkg_match.group(1) if pkg_match else ""
- return package, tuple(m.group(1) for m in _TOP_LEVEL_TYPE_RE.finditer(text))
+ names = [m.group(1) for m in _TOP_LEVEL_TYPE_RE.finditer(text)]
+ if abs_path.endswith((".kt", ".kts")):
+ # Types stay first and keep their duplicates (the same-package pass
+ # reads a repeated name as ambiguous); callables are appended once and
+ # only when not already recorded, so ``fun Foo()`` beside
+ # ``class Foo`` adds no second entry for the file.
+ seen = set(names)
+ for name in _kotlin_top_level_callables(text):
+ if name not in seen:
+ seen.add(name)
+ names.append(name)
+ return package, tuple(names)
@lru_cache(maxsize=16384)
diff --git a/tests/integration/test_jvm_dead_code.py b/tests/integration/test_jvm_dead_code.py
index 98ec14dc4..615f86b58 100644
--- a/tests/integration/test_jvm_dead_code.py
+++ b/tests/integration/test_jvm_dead_code.py
@@ -139,3 +139,51 @@ class TestJvmSampleNoFalsePositives:
# exported class shouldn't be flagged unused.
exports = _names(jvm_report, DeadCodeKind.UNUSED_EXPORT)
assert "UserService" not in exports
+
+
+def _analyze_repo(repo: Path):
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ graph = builder.build()
+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze({"min_confidence": 0.0})
+ return graph, report
+
+
+class TestKotlinTopLevelFunctionImports:
+ """Issue #3081: a Kotlin utility file imported by function name is live."""
+
+ def _write(self, repo: Path) -> None:
+ util = repo / "core/src/main/kotlin/com/acme/util/StringUtils.kt"
+ app = repo / "app/src/main/kotlin/com/acme/app/Main.kt"
+ util.parent.mkdir(parents=True)
+ app.parent.mkdir(parents=True)
+ util.write_text(
+ "package com.acme.util\n\n"
+ 'fun String.shout(): String = uppercase() + "!"\n\n'
+ "fun twice(s: String): String = s + s\n"
+ )
+ app.write_text(
+ "package com.acme.app\n\n"
+ "import com.acme.util.shout\nimport com.acme.util.twice\n\n"
+ 'fun main() {\n println(twice("hi".shout()))\n}\n'
+ )
+
+ def test_import_edge_targets_the_utility_file(self, tmp_path: Path) -> None:
+ self._write(tmp_path)
+ graph, _ = _analyze_repo(tmp_path)
+
+ util = "core/src/main/kotlin/com/acme/util/StringUtils.kt"
+ app = "app/src/main/kotlin/com/acme/app/Main.kt"
+ assert graph.has_edge(app, util)
+ assert not graph.has_node("external:com.acme.util.shout")
+ assert not graph.has_node("external:com.acme.util.twice")
+
+ def test_utility_file_is_not_unreachable(self, tmp_path: Path) -> None:
+ self._write(tmp_path)
+ _, report = _analyze_repo(tmp_path)
+
+ unreachable = _paths(report, DeadCodeKind.UNREACHABLE_FILE)
+ assert not any(p.endswith("StringUtils.kt") for p in unreachable)
diff --git a/tests/unit/ingestion/test_jvm_workspace.py b/tests/unit/ingestion/test_jvm_workspace.py
index c0670096e..600b92758 100644
--- a/tests/unit/ingestion/test_jvm_workspace.py
+++ b/tests/unit/ingestion/test_jvm_workspace.py
@@ -8,6 +8,7 @@ import networkx as nx
from repowise.core.ingestion.resolvers.context import ResolverContext
from repowise.core.ingestion.resolvers.jvm_workspace import (
+ _scan_jvm_text,
build_jvm_workspace_index,
)
@@ -204,3 +205,115 @@ class TestMemberFqnResolution:
# a package.
targets = resolve_kotlin_import_all("okio.ByteString.Companion.*", u, ctx)
assert targets == (b,)
+
+
+_STRING_UTILS_KT = """package com.acme.util
+
+fun String.shout(): String = uppercase() + "!"
+
+fun twice(s: String): String = s + s
+"""
+
+
+class TestKotlinTopLevelCallables:
+ def test_scan_records_plain_and_extension_functions(self) -> None:
+ package, names = _scan_jvm_text("StringUtils.kt", _STRING_UTILS_KT)
+ assert package == "com.acme.util"
+ assert "shout" in names
+ assert "twice" in names
+
+ def test_scan_records_generic_extension_function(self) -> None:
+ text = (
+ "package com.orbitalhq.connectors.metrics\n\n"
+ "fun <T : Any> Mono<T>.captureMetrics(tags: List<Tag>, "
+ "meterRegistry: MeterRegistry): Mono<T> = this\n"
+ )
+ _, names = _scan_jvm_text("MetricsUtils.kt", text)
+ assert "captureMetrics" in names
+ assert "Mono" not in names
+
+ def test_scan_records_nested_generic_receiver_and_properties(self) -> None:
+ text = (
+ "package p\n\n"
+ "fun Map<String, List<Int>>.flat(): List<Int> = emptyList()\n"
+ "val String.lastChar: Char get() = last()\n"
+ "const val LIMIT = 10\n"
+ "var counter: Int = 0\n"
+ "inline fun <reified T> parse(s: String): T = TODO()\n"
+ "internal fun helper() {}\n"
+ "@JvmName(\"other\") fun renamed() {}\n"
+ )
+ _, names = _scan_jvm_text("Misc.kt", text)
+ assert {"flat", "lastChar", "LIMIT", "counter", "parse", "helper", "renamed"} <= set(
+ names
+ )
+
+ def test_scan_skips_private_and_nested_declarations(self) -> None:
+ text = (
+ "package p\n\n"
+ "private fun hidden() {}\n"
+ "private val secret = 1\n"
+ "class Box {\n"
+ " fun member() {}\n"
+ " val field = 1\n"
+ "}\n"
+ "fun outer() {\n"
+ " fun local() {}\n"
+ "}\n"
+ )
+ _, names = _scan_jvm_text("Box.kt", text)
+ assert "outer" in names
+ assert "Box" in names
+ for absent in ("hidden", "secret", "member", "field", "local"):
+ assert absent not in names
+
+ def test_fun_interface_is_not_read_as_a_function(self) -> None:
+ text = "package p\n\nfun interface Handler : Base {\n fun handle()\n}\n"
+ _, names = _scan_jvm_text("Handler.kt", text)
+ assert "Base" not in names
+ assert "interface" not in names
+ assert "handle" not in names
+
+ def test_function_beside_same_named_type_is_not_duplicated(self) -> None:
+ text = "package p\n\nclass Foo\n\nfun Foo(x: Int): Foo = Foo()\n"
+ _, names = _scan_jvm_text("Foo.kt", text)
+ assert names.count("Foo") == 1
+
+ def test_java_files_are_unchanged(self) -> None:
+ text = "package p;\n\npublic class A {\n}\nfun notJava() {}\n"
+ _, names = _scan_jvm_text("A.java", text)
+ assert names == ("A",)
+
+ def test_files_for_fqn_resolves_top_level_function(self, tmp_path: Path) -> None:
+ rel = "core/src/main/kotlin/com/acme/util/StringUtils.kt"
+ full = tmp_path / rel
+ full.parent.mkdir(parents=True)
+ full.write_text(_STRING_UTILS_KT)
+
+ index = build_jvm_workspace_index(_ctx(tmp_path, [rel]))
+
+ assert index.files_for_fqn("com.acme.util.shout") == (rel,)
+ assert index.files_for_fqn("com.acme.util.twice") == (rel,)
+ assert "shout" in index.packages["com.acme.util"].exported_top_level
+
+ def test_overloads_across_files_fan_out(self, tmp_path: Path) -> None:
+ a = "src/com/acme/util/A.kt"
+ b = "src/com/acme/util/B.kt"
+ for rel, body in ((a, "fun render(x: Int) {}\n"), (b, "fun render(x: String) {}\n")):
+ full = tmp_path / rel
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(f"package com.acme.util\n\n{body}")
+
+ index = build_jvm_workspace_index(_ctx(tmp_path, [a, b]))
+
+ assert sorted(index.files_for_fqn("com.acme.util.render")) == [a, b]
+
+ def test_private_function_is_not_importable(self, tmp_path: Path) -> None:
+ rel = "src/com/acme/util/Hidden.kt"
+ full = tmp_path / rel
+ full.parent.mkdir(parents=True)
+ full.write_text("package com.acme.util\n\nprivate fun hidden() {}\n")
+
+ index = build_jvm_workspace_index(_ctx(tmp_path, [rel]))
+
+ assert index.files_for_fqn("com.acme.util.hidden") == ()
diff --git a/tests/unit/ingestion/test_kotlin_resolver.py b/tests/unit/ingestion/test_kotlin_resolver.py
index 938e8c7d8..70d54bfd4 100644
--- a/tests/unit/ingestion/test_kotlin_resolver.py
+++ b/tests/unit/ingestion/test_kotlin_resolver.py
@@ -7,7 +7,10 @@ from pathlib import Path
import networkx as nx
from repowise.core.ingestion.resolvers.context import ResolverContext
-from repowise.core.ingestion.resolvers.kotlin import resolve_kotlin_import
+from repowise.core.ingestion.resolvers.kotlin import (
+ resolve_kotlin_import,
+ resolve_kotlin_import_all,
+)
from repowise.core.ingestion.resolvers.kotlin_gradle import build_kotlin_index
@@ -149,3 +152,66 @@ class TestKotlinStdlibFiltering:
ctx = _ctx(tmp_path, ["src/CommentRoutes.kt"])
result = resolve_kotlin_import("com.acme.domain.commentRoutes", "Main.kt", ctx)
assert result == "src/CommentRoutes.kt"
+
+
+class TestTopLevelFunctionImports:
+ """``import pkg.fn`` must reach the file declaring ``fn``, whatever its name."""
+
+ def _util_repo(self, repo: Path) -> tuple[str, str]:
+ util = "core/src/main/kotlin/com/acme/util/StringUtils.kt"
+ app = "app/src/main/kotlin/com/acme/app/Main.kt"
+ for rel, body in (
+ (
+ util,
+ "package com.acme.util\n\n"
+ "fun String.shout(): String = uppercase() + \"!\"\n\n"
+ "fun twice(s: String): String = s + s\n",
+ ),
+ (
+ app,
+ "package com.acme.app\n\n"
+ "import com.acme.util.shout\nimport com.acme.util.twice\n\n"
+ "fun main() { println(twice(\"hi\".shout())) }\n",
+ ),
+ ):
+ full = repo / rel
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(body)
+ return util, app
+
+ def test_function_import_resolves_to_utility_file(self, tmp_path: Path) -> None:
+ util, app = self._util_repo(tmp_path)
+ ctx = _ctx(tmp_path, [util, app])
+
+ assert resolve_kotlin_import_all("com.acme.util.twice", app, ctx) == (util,)
+ assert resolve_kotlin_import_all("com.acme.util.shout", app, ctx) == (util,)
+
+ def test_function_import_is_not_an_external_node(self, tmp_path: Path) -> None:
+ util, app = self._util_repo(tmp_path)
+ ctx = _ctx(tmp_path, [util, app])
+
+ result = resolve_kotlin_import("com.acme.util.twice", app, ctx)
+
+ assert result == util
+ assert not str(result).startswith("external:")
+
+ def test_unknown_function_in_known_package_stays_external(self, tmp_path: Path) -> None:
+ util, app = self._util_repo(tmp_path)
+ ctx = _ctx(tmp_path, [util, app])
+
+ result = resolve_kotlin_import("com.acme.util.missing", app, ctx)
+
+ assert result == "external:com.acme.util.missing"
+
+ def test_private_function_import_does_not_resolve(self, tmp_path: Path) -> None:
+ # A file name unrelated to the function, so the stem fallback cannot
+ # be what resolves (or fails to resolve) it.
+ rel = "src/main/kotlin/com/acme/util/Internals.kt"
+ full = tmp_path / rel
+ full.parent.mkdir(parents=True)
+ full.write_text("package com.acme.util\n\nprivate fun hidden() {}\n")
+ ctx = _ctx(tmp_path, [rel])
+
+ assert resolve_kotlin_import("com.acme.util.hidden", "x.kt", ctx) == (
+ "external:com.acme.util.hidden"
+ )