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(dead-code): treat a Kotlin expect and its platform actuals as one declaration (#2986)
Raghav Chamadiyab4ec385ea80b
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex d3c396585..fd4f0be15 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -62,6 +62,7 @@ from .file_reachability import (build_package_file_map,is_file_reachable,)+from .kotlin_multiplatform import settle_platform_declarationsfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReportfrom .module_strings import drop_named_modulesfrom .name_occurrences import (@@ -978,6 +979,9 @@ class DeadCodeAnalyzer:# out entirely, rather than being reported at a number it no longer# deserves.findings = self._clamp_for_unindexed_importers(findings)+ # Before the name search: an ``expect``'s own ``actual`` files write its+ # name, which that search would read as a use elsewhere.+ findings = settle_platform_declarations(findings, self._source_map)# Same position and for the same reason. This one asks the wider# version of the same question — not "could an unread file explain# this" but "did we look anywhere except the import graph".diff --git a/packages/core/src/repowise/core/analysis/dead_code/kotlin_multiplatform.py b/packages/core/src/repowise/core/analysis/dead_code/kotlin_multiplatform.pynew file mode 100644index 000000000..6cbeb4d92--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/kotlin_multiplatform.py@@ -0,0 +1,207 @@+"""Kotlin multiplatform ``expect`` / ``actual`` declarations in dead code.++A multiplatform API is one ``expect`` declaration in a common source set and+one ``actual`` per platform source set, all with the same name in the same+package. The compiler binds every use of the API to the ``expect`` and links+each ``actual`` to it, so the graph sees one name declared in several files of+one package. That is exactly the shape the same-package scan refuses to bind+(an ambiguous name gets no edge), and a call from a platform file may bind to+one ``actual`` and leave the others with no edge. Both read as "no importers".++A declaration pairs by package and name, read from the source.++* An ``actual`` whose ``expect`` is in the repository is the platform body of+ that ``expect``: it is never deleted on its own, and whether the API is used+ is the ``expect``'s question. So it is not reported, and neither is a file+ whose top-level ``actual`` pairs that way. An ``actual`` with no ``expect`` in+ view is left as it was.+* An ``expect`` stays reported, but is re-judged on a real use: its name written+ in code (comments and strings blanked) in a file that sees its package (the+ same package, or an import of the name or of the package), on a line that is+ not one of the API's own declarations. With such a use it falls below the+ review floor with the line that uses it; without one it stays at the review+ tier with a reason that says so.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from pathlib import PurePosixPath++from ...ingestion.languages.registry import REGISTRY+from .models import DeadCodeFindingData, DeadCodeKind+from .name_occurrences import occurrence_files, searchable_token+from .risk_factors import RISK_CAP_CONFIDENCE++#: Where an ``expect`` with a real use lands: below the review floor, so the+#: default report hides it while ``--min-confidence 0`` still lists it.+EXPECT_USED_CONFIDENCE = 0.3++# ``[annotations] [modifiers] expect|actual [modifiers] keyword [<T>] [Receiver.]Name``.+# Constructors are members of an ``actual class`` and never a finding of their own.+_PLATFORM_DECL_RE = re.compile(+ r"^(?P<indent>[ \t]*)(?:@[\w.]+(?:\([^)\n]*\))?\s+)*(?:[a-z]+[ \t]+)*?"+ r"(?P<modifier>expect|actual)[ \t]+(?:[a-z]+[ \t]+)*?"+ r"(?:fun|val|var|class|object|interface|typealias)[ \t]+"+ r"(?:<[^>\n]*>[ \t]*)?(?:[\w<>?, *]+\.)?(?P<name>[A-Za-z_]\w*)",+ re.MULTILINE,+)+_PACKAGE_RE = re.compile(r"^[ \t]*package[ \t]+([\w.]+)", re.MULTILINE)+_IMPORT_RE = re.compile(r"^[ \t]*import[ \t]+([\w.]*\w(?:\.\*)?)", re.MULTILINE)+# Comments and string literals, replaced by spaces so line numbers hold.+_NOISE_RE = re.compile(r'/\*.*?\*/|//[^\n]*|"""(?:.|\n)*?"""|"(?:\\.|[^"\\\n])*"', re.DOTALL)+++@dataclass(frozen=True)+class _PlatformDecl:+ path: str+ package: str+ line: int+ modifier: str+ top_level: bool+++def _is_kotlin(path: str) -> bool:+ return REGISTRY.from_extension(PurePosixPath(path).suffix) == "kotlin"+++def _blank_noise(text: str) -> str:+ return _NOISE_RE.sub(lambda m: re.sub(r"[^\n]", " ", m.group()), text)+++def _package(text: str) -> str:+ match = _PACKAGE_RE.search(text)+ return match.group(1) if match else ""+++def _platform_index(source_map: dict[str, bytes]) -> dict[tuple[str, str], list[_PlatformDecl]]:+ """``(package, name)`` -> its ``expect`` / ``actual`` declarations."""+ index: dict[tuple[str, str], list[_PlatformDecl]] = {}+ for path, blob in source_map.items():+ if not _is_kotlin(path) or (b"expect" not in blob and b"actual" not in blob):+ continue+ text = _blank_noise(blob.decode("utf-8", "replace"))+ package = _package(text)+ for match in _PLATFORM_DECL_RE.finditer(text):+ line = text.count("\n", 0, match.start("modifier")) + 1+ top_level = not match.group("indent")+ decl = _PlatformDecl(path, package, line, match.group("modifier"), top_level)+ index.setdefault((package, match.group("name")), []).append(decl)+ return index+++def _pairs_with_expect(decls: list[_PlatformDecl]) -> bool:+ return any(d.modifier == "expect" for d in decls)+++def _paired_actual_files(index: dict[tuple[str, str], list[_PlatformDecl]]) -> set[str]:+ """Files holding a top-level ``actual`` whose ``expect`` is in the index."""+ return {+ d.path+ for decls in index.values()+ if _pairs_with_expect(decls)+ for d in decls+ if d.modifier == "actual" and d.top_level+ }+++def _role(+ finding: DeadCodeFindingData,+ index: dict[tuple[str, str], list[_PlatformDecl]],+ packages: dict[str, str],+ paired_files: set[str],+) -> str | None:+ """``"actual"`` (paired, not reported), ``"expect"`` (re-judged) or None."""+ if finding.kind is DeadCodeKind.UNREACHABLE_FILE:+ return "actual" if finding.file_path in paired_files else None+ package = packages.get(finding.file_path)+ decls = index.get((package, finding.symbol_name), []) if package is not None else []+ own = next((d for d in decls if d.path == finding.file_path), None)+ if own is None or (own.modifier == "actual" and not _pairs_with_expect(decls)):+ return None+ return own.modifier+++def settle_platform_declarations(+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]+) -> list[DeadCodeFindingData]:+ """Drop paired ``actual`` findings and re-judge ``expect`` ones; see the module doc.++ Mutates the ``expect`` findings in place and returns the kept list. A file+ with no source is left as it was.+ """+ if not any(_is_kotlin(f.file_path) for f in findings):+ return findings+ index = _platform_index(source_map)+ packages = {d.path: d.package for decls in index.values() for d in decls}+ paired_files = _paired_actual_files(index)+ roles = {id(f): _role(f, index, packages, paired_files) for f in findings}+ expects = [f for f in findings if roles[id(f)] == "expect"]+ if expects:+ _judge_expects(expects, source_map, index, packages)+ return [f for f in findings if roles[id(f)] != "actual"]+++def _sees(text: str, package: str, name: str) -> bool:+ """Whether a file in its own package, or importing the name or the package, can use it."""+ if _package(text) == package:+ return True+ wanted = {f"{package}.{name}", f"{package}.*"}+ return any(imported in wanted for imported in _IMPORT_RE.findall(text))+++def _first_use(+ source_map: dict[str, bytes],+ candidates: set[str],+ key: tuple[str, str],+ declarations: set[tuple[str, int]],+) -> str | None:+ """``path:line`` of the first code use of *key* outside its own declarations."""+ package, name = key+ word = re.compile(rf"\b{re.escape(name)}\b")+ for path in sorted(candidates):+ if not _is_kotlin(path):+ continue+ text = _blank_noise(source_map[path].decode("utf-8", "replace"))+ if not _sees(text, package, name):+ continue+ for lineno, line in enumerate(text.split("\n"), start=1):+ if (path, lineno) not in declarations and word.search(line):+ return f"{path}:{lineno}"+ return None+++def _judge_expects(+ expects: list[DeadCodeFindingData],+ source_map: dict[str, bytes],+ index: dict[tuple[str, str], list[_PlatformDecl]],+ packages: dict[str, str],+) -> None:+ # A name the identifier scan cannot see is left to the shared name search,+ # which says it could not be searched for.+ tokens = {id(f): searchable_token(f.symbol_name or "") for f in expects}+ searchable = [f for f in expects if tokens[id(f)]]+ occurrences = occurrence_files(source_map, {tokens[id(f)] for f in searchable})+ for finding in searchable:+ name = finding.symbol_name+ key = (packages[finding.file_path], name)+ decls = index.get(key, [])+ declarations = {(d.path, d.line) for d in decls}+ used_at = _first_use(source_map, occurrences.get(tokens[id(finding)], set()), key, declarations)+ finding.safe_to_delete = False+ if used_at:+ finding.confidence = min(finding.confidence, EXPECT_USED_CONFIDENCE)+ finding.reason = f"Multiplatform expect '{name}' is not imported, but is used in its package"+ finding.evidence.append(+ f"'{name}' is used at {used_at}; the import graph does not bind "+ "uses of a name its platform actuals also declare"+ )+ continue+ finding.confidence = min(finding.confidence, RISK_CAP_CONFIDENCE)+ actuals = sum(1 for d in decls if d.modifier == "actual")+ finding.reason = (+ f"Multiplatform expect '{name}' has no use outside its {actuals} platform actual(s)"+ if actuals+ else f"Multiplatform expect '{name}' has no actual and no use in the repo"+ )diff --git a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.pyindex 5a0ff5d1e..b7cded96e 100644--- a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py+++ b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py@@ -162,7 +162,7 @@ def _uses_in_own_file(wanted: dict[bytes, list[DeadCodeFindingData]] = {}headers: dict[bytes, set[int]] = {}for finding in spanned:- token = _token(finding.symbol_name)+ token = searchable_token(finding.symbol_name)wanted.setdefault(token, []).append(finding)headers.setdefault(token, set()).add(finding.start_line)@@ -180,7 +180,7 @@ def _uses_in_own_file(return out-def _token(name: str) -> bytes:+def searchable_token(name: str) -> bytes:"""The searchable form of *name*, or empty when the scan cannot find it.The one rule is that the result must be something :data:`IDENTIFIER_RE`@@ -229,7 +229,7 @@ def _verdicts("""One verdict per candidate, from one repo-wide scan plus targeted reads."""# Built from the candidates alone, which is what keeps a whole-repo scan# affordable: the index only ever holds the names some finding asks about.- answerable = {_token(f.symbol_name) for f in candidates} - {b""}+ answerable = {searchable_token(f.symbol_name) for f in candidates} - {b""}occurrences = occurrence_files(source_map, answerable)out: dict[int, _Verdict] = {}@@ -240,7 +240,7 @@ def _verdicts(same_file_only: dict[str, list[DeadCodeFindingData]] = {}for finding in candidates:- token = _token(finding.symbol_name)+ token = searchable_token(finding.symbol_name)if not token:out[id(finding)] = _NOT_SEARCHABLEcontinue@@ -372,7 +372,7 @@ def drop_internals_used_in_own_file(if verdict is not None:if verdict.answer is _Answer.USED:continue- if verdict.answer is _Answer.SPAN_UNKNOWN or not _token(finding.symbol_name):+ if verdict.answer is _Answer.SPAN_UNKNOWN or not searchable_token(finding.symbol_name):finding.confidence = min(finding.confidence, UNVERIFIED_INTERNAL_CONFIDENCE)finding.evidence.append(f"'{finding.symbol_name}' could not be checked against the rest of "@@ -515,7 +515,7 @@ def _writers(source_map: dict[str, bytes], names: Mapping[int, frozenset[str]]) -> dict[bytes, set[str]]:"""For every searchable name in *names*, the files of *source_map* writing it."""- tokens = {_token(name) for group in names.values() for name in group} - {b""}+ tokens = {searchable_token(name) for group in names.values() for name in group} - {b""}return occurrence_files(source_map, tokens)@@ -543,7 +543,7 @@ def drop_reference_assembly_api(return [ffor f in findings- if not any(_token(name) in listed for name in names.get(id(f), ()))+ if not any(searchable_token(name) in listed for name in names.get(id(f), ()))]@@ -591,7 +591,7 @@ def _first_writer(((path, name)for name in names- for path in writers.get(_token(name), ())+ for path in writers.get(searchable_token(name), ())if path != file_path and not _is_own_type_sibling(path, file_path)),default=None,diff --git a/tests/unit/dead_code/test_kotlin_multiplatform.py b/tests/unit/dead_code/test_kotlin_multiplatform.pynew file mode 100644index 000000000..4eea3b27d--- /dev/null+++ b/tests/unit/dead_code/test_kotlin_multiplatform.py@@ -0,0 +1,145 @@+"""Kotlin multiplatform ``expect`` / ``actual`` declarations in dead code.++An ``actual`` is the platform body of an ``expect``: it is never reported, and+neither is a file declaring one at top level. An ``expect`` named by a file+other than its own and its actuals' falls below the review floor; named only+by those, it stays at the review tier. Other languages and plain Kotlin+declarations are untouched.+"""++from __future__ import annotations++from repowise.core.analysis.dead_code.kotlin_multiplatform import (+ EXPECT_USED_CONFIDENCE,+ settle_platform_declarations,+)+from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeKind+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE++_COMMON = "lib/common/src/io/x/Utils.kt"+_JVM = "lib/jvm/src/io/x/UtilsJvm.kt"+_NATIVE = "lib/posix/src/io/x/UtilsNative.kt"+_CALLER = "lib/common/src/io/x/Caller.kt"++_EXPECT_SRC = """package io.x++public expect fun Throwable.unwrapCause(): Throwable++public fun plainHelper(): Int = 1+"""+_JVM_SRC = """package io.x++/** Doc. */+@Suppress("UNUSED")+public actual fun Throwable.unwrapCause(): Throwable = cause ?: this+"""+_NATIVE_SRC = """package io.x++public actual fun Throwable.unwrapCause(): Throwable = this+"""+++def _finding(+ path: str, name: str | None, line: int | None, confidence: float = 0.4+) -> DeadCodeFindingData:+ return DeadCodeFindingData(+ kind=DeadCodeKind.UNUSED_EXPORT if name else DeadCodeKind.UNREACHABLE_FILE,+ file_path=path,+ symbol_name=name,+ symbol_kind="function" if name else None,+ confidence=confidence,+ reason="Public symbol has no importers",+ last_commit_at=None,+ commit_count_90d=0,+ lines=1,+ evidence=[],+ safe_to_delete=False,+ primary_owner=None,+ age_days=None,+ start_line=line,+ end_line=line,+ )+++def _settle(findings, source):+ return settle_platform_declarations(findings, {p: s.encode() for p, s in source.items()})+++def _source(**extra: str) -> dict[str, str]:+ return {_COMMON: _EXPECT_SRC, _JVM: _JVM_SRC, _NATIVE: _NATIVE_SRC, **extra}+++def test_actual_declarations_are_not_reported():+ findings = [_finding(_JVM, "unwrapCause", 4), _finding(_NATIVE, "unwrapCause", 3)]+ assert _settle(findings, _source()) == []+++def test_a_file_declaring_a_top_level_actual_is_not_unreachable():+ assert _settle([_finding(_NATIVE, None, None)], _source()) == []+++def test_an_expect_used_elsewhere_drops_below_the_floor():+ expect = _finding(_COMMON, "unwrapCause", 3, confidence=1.0)+ kept = _settle([expect], _source(**{_CALLER: "package io.x\nval c = e.unwrapCause()\n"}))+ assert kept == [expect]+ assert expect.confidence == EXPECT_USED_CONFIDENCE < RISK_CAP_CONFIDENCE+ assert _CALLER in expect.evidence[-1]+++def test_an_unused_pair_is_reported_once_as_its_expect():+ expect = _finding(_COMMON, "unwrapCause", 3, confidence=1.0)+ actuals = [_finding(_JVM, "unwrapCause", 4), _finding(_NATIVE, "unwrapCause", 3)]+ assert _settle([expect, *actuals], _source()) == [expect]+ assert expect.confidence == RISK_CAP_CONFIDENCE+ assert "no use outside its 2 platform actual(s)" in expect.reason+++def test_an_expect_with_no_actual_and_no_use_stays_at_the_review_tier():+ expect = _finding(_COMMON, "unwrapCause", 3, confidence=1.0)+ assert _settle([expect], {_COMMON: _EXPECT_SRC}) == [expect]+ assert expect.confidence == RISK_CAP_CONFIDENCE+ assert "no actual and no use" in expect.reason+++def test_an_actual_with_no_expect_in_view_is_left_alone():+ actual = _finding(_JVM, "unwrapCause", 4)+ unreachable = _finding(_JVM, None, None)+ assert _settle([actual, unreachable], {_JVM: _JVM_SRC}) == [actual, unreachable]+++def test_the_same_name_in_another_package_a_comment_or_a_string_is_no_use():+ other = 'package io.other\nfun unwrapCause() = 1\nval s = "unwrapCause"\n'+ comment = 'package io.x\n// we unwrapCause here later\nval t = "unwrapCause"\n'+ expect = _finding(_COMMON, "unwrapCause", 3, confidence=1.0)+ _settle([expect], _source(**{"lib/other/Other.kt": other, _CALLER: comment}))+ assert expect.confidence == RISK_CAP_CONFIDENCE+++def test_an_import_of_the_name_or_the_package_is_a_use():+ for imported in ("io.x.unwrapCause", "io.x.*"):+ user = f"package io.app\nimport {imported}\nval c = e.unwrapCause()\n"+ expect = _finding(_COMMON, "unwrapCause", 3, confidence=1.0)+ _settle([expect], _source(**{"app/User.kt": user}))+ assert expect.confidence == EXPECT_USED_CONFIDENCE, imported+++def test_plain_kotlin_and_other_languages_are_untouched():+ plain = _finding(_COMMON, "plainHelper", 5)+ java = _finding("src/Main.java", "actual", 1)+ unreachable = _finding(_CALLER, None, None)+ source = _source(**{"src/Main.java": "public actual fun x() {}\n", _CALLER: "package io.x\n"})+ kept = _settle([plain, java, unreachable], source)+ assert kept == [plain, java, unreachable]+ assert plain.reason == "Public symbol has no importers"+++def test_the_word_actual_in_a_string_or_member_is_not_a_modifier():+ source = {+ _CALLER: (+ 'package io.x\n@Deprecated("use the actual one")\npublic fun legacy() = 1\n'+ "class Box {\n actual fun inner() = 2\n}\n"+ )+ }+ legacy = _finding(_CALLER, "legacy", 2)+ unreachable = _finding(_CALLER, None, None)+ assert _settle([legacy, unreachable], source) == [legacy, unreachable]