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(dead-code): Compose previews and Dagger/Hilt modules are framework-loaded (#3661)

Swati Ahujaa583af5150cb
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 5921c6b5b..26d1340ab 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -78,6 +78,7 @@ from .file_reachability import (
from .go_name_uses import drop_go_package_uses
from .jvm_reachability import defines_main
from .kotlin_multiplatform import settle_platform_declarations
+from .meta_annotations import MetaAnnotations
from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
from .module_strings import drop_named_modules
from .name_occurrences import (
@@ -186,7 +187,9 @@ def _declared_deliberately_unused(decorators: Iterable[str]) -> bool:
return False
-def _is_framework_registered(decorators: list[str]) -> bool:
+def _is_framework_registered(
+ decorators: list[str], meta_annotations: frozenset[str] = frozenset()
+) -> bool:
"""Whether any decorator wires the symbol into a framework dispatcher.
Both dead-code passes ask this question, and both asked it with the same
@@ -208,9 +211,18 @@ def _is_framework_registered(decorators: list[str]) -> bool:
``@register``, ``@register_drainer``, ``@Field.register_lookup``. Held to
``register`` exactly or a ``register_`` stem so that a past participle
guarding a handler (``@registered_only``) is not read as one.
+
+ A qualified annotation (``@androidx.compose.ui.tooling.preview.Preview``)
+ is also matched by its type name, and *meta_annotations* names the repo's
+ own annotation classes that carry one of these (a Compose multipreview):
+ an unqualified use by its in-scope local name, a qualified use by its
+ fully qualified name.
"""
bases = _decorator_bases(decorators)
- if any(b.startswith(_FRAMEWORK_DECORATORS) for b in bases):
+ type_names = [n for n in (b.rsplit(".", 1)[-1] for b in bases) if n[:1].isupper()]
+ if any(b.startswith(_FRAMEWORK_DECORATORS) for b in (*bases, *type_names)):
+ return True
+ if not meta_annotations.isdisjoint(bases):
return True
if any(b.endswith(_FRAMEWORK_DECORATOR_SUFFIXES) for b in bases):
return True
@@ -940,6 +952,14 @@ class DeadCodeAnalyzer:
self._guard_cache: dict[str, list[tuple[str, str, str]]] = {}
# {base id: overload member ids}, built on first use.
self._overload_units: dict[str, list[str]] | None = None
+ # Repo annotation classes that register what they annotate, built on first use.
+ self._meta_annotations: MetaAnnotations | None = None
+
+ def _framework_meta_annotations(self, path: str) -> frozenset[str]:
+ """Names of repo annotation classes that register what they annotate in *path*."""
+ if self._meta_annotations is None:
+ self._meta_annotations = MetaAnnotations(self._source_map, _is_framework_registered)
+ return self._meta_annotations.visible_in(path)
def _reachability_rescues(self, whitelist: AbstractSet[str]) -> ReachabilityRescues:
"""Assemble the rescue state the shared predicate reads."""
@@ -1593,7 +1613,8 @@ class DeadCodeAnalyzer:
sym_name = sym.get("name", "")
decorators = sym.get("decorators", [])
- if _is_framework_registered(decorators):
+ meta = self._framework_meta_annotations(sym.get("file_path", ""))
+ if _is_framework_registered(decorators, meta):
return True
if _declared_deliberately_unused(decorators):
return True
@@ -2098,8 +2119,9 @@ class DeadCodeAnalyzer:
# private ``@PostConstruct``/``@EventListener``/``@Scheduled``
# method is invoked by the container, not by a source call.
decorators = node_data.get("decorators") or []
+ meta = self._framework_meta_annotations(node_data.get("file_path", ""))
return not (
- _is_framework_registered(decorators) or _declared_deliberately_unused(decorators)
+ _is_framework_registered(decorators, meta) or _declared_deliberately_unused(decorators)
)
def _detect_zombie_packages(self, whitelist: set[str]) -> list[DeadCodeFindingData]:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 1139640bd..52fd8d13f 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -885,6 +885,14 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = (
"Modified",
"PactTestFor",
"Pact",
+ # Dagger / Hilt: the generated component loads modules and calls their
+ # provider methods (prefix match covers ``BindsInstance``).
+ "Module",
+ "Provides",
+ "Binds",
+ # Compose previews, rendered by the IDE (prefix match covers
+ # ``PreviewLightDark``, ``PreviewScreenSizes`` and the other presets).
+ "Preview",
# ---- JVM: test method markers -----------------------------------
"Test",
"ParameterizedTest",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
index f4e275cdf..fc9456acc 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
@@ -33,6 +33,7 @@ from pathlib import PurePosixPath
from typing import Any
from ...entry_candidacy import is_reachability_root
+from ...ingestion.decorator_names import decorator_base
from .entry_shape import defines_main_function
# Class-level annotation names (without the leading ``@``) that mark the
@@ -79,6 +80,7 @@ _STEREOTYPE_ANNOTATIONS: frozenset[str] = frozenset({
"Endpoint",
"RestControllerEndpoint",
"RegisterForReflection",
+ "Module", # Dagger / Hilt
# JMH runs these by reflection; ``Benchmark`` sits on the methods.
"State",
"BenchmarkMode",
@@ -109,12 +111,8 @@ def build_jvm_package_files(graph: Any) -> dict[str, list[str]]:
def _annotation_base(decorator: str) -> str:
- """Strip ``@``, generic args, and arg list from a decorator string."""
- s = decorator.lstrip("@")
- for sep in ("(", "<"):
- pos = s.find(sep)
- if pos >= 0:
- s = s[:pos]
+ """Strip ``@``, generic args, arg list and trailing modifiers from a decorator string."""
+ s = decorator_base(decorator).partition("<")[0]
# Spring annotations may be FQN ('org.springframework.stereotype.Service');
# we match the bare type name.
if "." in s:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/meta_annotations.py b/packages/core/src/repowise/core/analysis/dead_code/meta_annotations.py
new file mode 100644
index 000000000..6d626bd3b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/meta_annotations.py
@@ -0,0 +1,142 @@
+"""Kotlin annotation classes that carry a framework-registering annotation.
+
+A Compose multipreview (``@Preview(...) @Preview(...) annotation class
+ThemePreviews``) or a Spring meta-annotation (``@Component annotation class
+UseCase``) makes every declaration it annotates framework-loaded. The Kotlin
+grammar parses an annotated ``annotation class`` as an expression, so the
+class never reaches the graph and its own annotations are read from source.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from collections.abc import Callable, Mapping
+from typing import NamedTuple
+
+# One annotation, arguments allowed one paren level deep (``@Preview(device =
+# spec(1))``), then the class header.
+_ANNOTATION = rb"@[\w.]+(?:\([^()]*(?:\([^()]*\)[^()]*)*\))?"
+_ANNOTATION_CLASS = re.compile(
+ rb"((?:" + _ANNOTATION + rb"\s*)+)"
+ rb"(?:(?:public|internal|private)\s+)?annotation\s+class\s+(\w+)"
+)
+_ANY_ANNOTATION_CLASS = re.compile(rb"\bannotation\s+class\s+(\w+)")
+_PACKAGE = re.compile(rb"^[ \t]*package[ \t]+([\w.]+)", re.MULTILINE)
+_IMPORT = re.compile(
+ rb"^[ \t]*import[ \t]+([\w.]+?)(\.\*)?(?:[ \t]+as[ \t]+(\w+))?[ \t]*;?\r?$", re.MULTILINE
+)
+
+Registers = Callable[[list[str], frozenset[str]], bool]
+
+
+class _Declared(NamedTuple):
+ package: str
+ name: str
+ path: str
+ blob: str
+
+
+class _Scope(NamedTuple):
+ package: str
+ named: dict[str, str] # imported fqn -> local name (alias or simple name)
+ stars: frozenset[str]
+
+
+class MetaAnnotations:
+ """Which repo annotation classes register what they annotate, per using file.
+
+ A class is matched by simple name only when no other repo annotation class
+ shares that name, or the using file is in its package or imports it (by
+ name, alias or star). A qualified use matches the class's fully qualified
+ name in any file, so every registering class's FQN is visible everywhere.
+ Registration is resolved to a fixpoint, so a multipreview built from
+ another multipreview counts too; each round adds a class or stops, which
+ bounds the loop by the number of annotation classes.
+
+ Ceiling: reads Kotlin sources only. Java ``@interface`` meta-annotations are
+ not resolved.
+ """
+
+ def __init__(self, source_map: Mapping[str, bytes], registers: Registers) -> None:
+ self._source_map = source_map
+ self._scopes: dict[str, _Scope] = {}
+ self._visible: dict[str, frozenset[str]] = {}
+ self._name_count: Counter[str] = Counter()
+ self._registering: set[_Declared] = set()
+ declared = [decl for path, source in source_map.items() for decl in self._scan(path, source)]
+ self._resolve(declared, registers)
+
+ def visible_in(self, path: str) -> frozenset[str]:
+ """Local and qualified names of the registering annotation classes *path* can mean."""
+ names = self._visible.get(path)
+ if names is None:
+ names = self._visible[path] = self._names_seen_by(path)
+ return names
+
+ def _scan(self, path: str, source: bytes) -> list[_Declared]:
+ """The annotated annotation classes *path* declares; counts every one's name."""
+ if not path.endswith(".kt") or b"annotation class" not in source:
+ return []
+ # Every annotation class counts toward a name's ambiguity, annotated or not.
+ self._name_count.update(name.decode("ascii") for name in _ANY_ANNOTATION_CLASS.findall(source))
+ package = self._scope(path).package
+ return [
+ _Declared(
+ package, match.group(2).decode("ascii"), path, match.group(1).decode("utf-8", "replace")
+ )
+ for match in _ANNOTATION_CLASS.finditer(source)
+ ]
+
+ def _resolve(self, declared: list[_Declared], registers: Registers) -> None:
+ while True:
+ found = {
+ d
+ for d in declared
+ if d not in self._registering and registers([d.blob], self._names_seen_by(d.path))
+ }
+ if not found:
+ return
+ self._registering |= found
+
+ def _names_seen_by(self, path: str) -> frozenset[str]:
+ if not self._registering:
+ return frozenset()
+ scope = self._scope(path)
+ names: set[str] = set()
+ for decl in self._registering:
+ fqn = f"{decl.package}.{decl.name}" if decl.package else decl.name
+ if decl.package:
+ names.add(fqn)
+ local = self._local_name(decl, fqn, scope)
+ if local:
+ names.add(local)
+ return frozenset(names)
+
+ def _local_name(self, decl: _Declared, fqn: str, scope: _Scope) -> str | None:
+ """The bare name a file in *scope* uses for *decl*, if it can mean it."""
+ if fqn in scope.named:
+ return scope.named[fqn]
+ in_scope = decl.package == scope.package or decl.package in scope.stars
+ return decl.name if in_scope or self._name_count[decl.name] == 1 else None
+
+ def _scope(self, path: str) -> _Scope:
+ scope = self._scopes.get(path)
+ if scope is None:
+ source = self._source_map.get(path, b"") if path.endswith(".kt") else b""
+ scope = self._scopes[path] = _parse_scope(source)
+ return scope
+
+
+def _parse_scope(source: bytes) -> _Scope:
+ package = _PACKAGE.search(source)
+ named: dict[str, str] = {}
+ stars: set[str] = set()
+ for match in _IMPORT.finditer(source):
+ fqn = match.group(1).decode("ascii", "replace")
+ if match.group(2):
+ stars.add(fqn)
+ continue
+ alias = match.group(3)
+ named[fqn] = alias.decode("ascii") if alias else fqn.rsplit(".", 1)[-1]
+ return _Scope(package.group(1).decode("ascii") if package else "", named, frozenset(stars))
diff --git a/tests/unit/dead_code/test_compose_hilt_roots.py b/tests/unit/dead_code/test_compose_hilt_roots.py
new file mode 100644
index 000000000..e2bbc6d24
--- /dev/null
+++ b/tests/unit/dead_code/test_compose_hilt_roots.py
@@ -0,0 +1,145 @@
+"""Compose previews and Dagger/Hilt modules are loaded by tooling, never imported.
+
+Shapes from nowinandroid: previews under ``@Preview``, a preset, a qualified
+``@Preview`` and the repo's own multipreview annotation (itself a misparse the
+graph never holds, so it is read from source), and a Hilt ``@Module`` object
+with ``@Provides``/``@Binds`` members. Every one was reported dead, the
+previews as deletion-ready exports.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.analyzer import _is_framework_registered
+from repowise.core.analysis.dead_code.meta_annotations import MetaAnnotations
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+_UI = "ui/src/main/kotlin/org/sample/ui"
+
+_FILES = {
+ f"{_UI}/ThemePreviews.kt": (
+ "package org.sample.ui\n\n"
+ "import androidx.compose.ui.tooling.preview.Preview\n\n"
+ '@Preview(name = "Light theme")\n'
+ '@Preview(name = "Dark theme", uiMode = mode(1))\n'
+ "annotation class ThemePreviews\n\n"
+ "@ThemePreviews\n"
+ "annotation class NestedPreviews\n\n"
+ "annotation class NotAPreview\n"
+ ),
+ f"{_UI}/Button.kt": (
+ "package org.sample.ui\n\n"
+ "@ThemePreviews\n@Composable\nfun ButtonThemePreview() {}\n\n"
+ "@NestedPreviews\n@Composable\nfun ButtonNestedPreview() {}\n\n"
+ "@Preview\n@Composable\nfun ButtonPlainPreview() {}\n\n"
+ "@PreviewLightDark\n@Composable\nfun ButtonPresetPreview() {}\n\n"
+ "@androidx.compose.ui.tooling.preview.Preview\n@Composable\n"
+ "fun ButtonQualifiedPreview() {}\n\n"
+ "@NotAPreview\n@Composable\nfun ButtonUnusedComposable() {}\n\n"
+ "class UnusedHelper {\n fun help() {}\n}\n"
+ ),
+ "app/src/main/kotlin/org/sample/app/di/JankStatsModule.kt": (
+ "package org.sample.app.di\n\n"
+ "@Module\n@InstallIn(ActivityComponent::class)\n"
+ "object JankStatsModule {\n"
+ " @Provides\n fun providesListener(): String = \"\"\n\n"
+ " @Binds\n fun bindsListener(x: Int): Int = x\n"
+ "}\n"
+ ),
+}
+
+
+def _report(root: Path):
+ source_map = {rel: text.encode() for rel, text in _FILES.items()}
+ for rel, source in source_map.items():
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(source)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=root)
+ for fi in FileTraverser(root).traverse():
+ builder.add_file(parser.parse_file(fi, source_map[fi.path]))
+ builder.set_source_map(source_map)
+ graph = builder.build()
+ builder.add_framework_edges([])
+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={}, source_map=source_map, repo_root=root)
+ return analyzer.analyze({"min_confidence": 0.0})
+
+
+def _of(report, kind: DeadCodeKind) -> set[str]:
+ return {f.symbol_name or Path(f.file_path).name for f in report.findings if f.kind is kind}
+
+
+def test_previews_are_never_flagged(tmp_path: Path):
+ unused = _of(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)
+ assert unused.isdisjoint(
+ {
+ "ButtonThemePreview",
+ "ButtonNestedPreview",
+ "ButtonPlainPreview",
+ "ButtonPresetPreview",
+ "ButtonQualifiedPreview",
+ }
+ )
+ # A repo annotation without a preview on it registers nothing.
+ assert {"ButtonUnusedComposable", "UnusedHelper"} <= unused
+
+
+def test_hilt_module_is_loaded_by_the_component(tmp_path: Path):
+ report = _report(tmp_path)
+ assert "JankStatsModule.kt" not in _of(report, DeadCodeKind.UNREACHABLE_FILE)
+ flagged = _of(report, DeadCodeKind.UNUSED_EXPORT) | _of(report, DeadCodeKind.UNUSED_INTERNAL)
+ assert flagged.isdisjoint({"JankStatsModule", "providesListener", "bindsListener"})
+
+
+# Two annotation classes named ``ThemeShots``: only ``org.sample.ui``'s is a
+# multipreview. A use counts only where that one is the class in scope.
+_UI_SHOTS = "package org.sample.ui\n\n@Preview\nannotation class ThemeShots\n"
+_UI_FQN = "org.sample.ui.ThemeShots"
+_OTHER_SHOTS = "package org.sample.other\n\nannotation class ThemeShots\n"
+_USERS = {
+ "app/SamePackage.kt": "package org.sample.ui\n",
+ "app/Imported.kt": "package org.sample.app\n\nimport org.sample.ui.ThemeShots\n",
+ "app/Star.kt": "package org.sample.app\n\nimport org.sample.ui.*\n",
+ "app/Aliased.kt": "package org.sample.app\n\nimport org.sample.ui.ThemeShots as UiShots\n",
+ "app/OtherImport.kt": "package org.sample.app\n\nimport org.sample.other.ThemeShots\n",
+ "app/OtherPackage.kt": "package org.sample.other\n",
+ "app/Unrelated.kt": "package org.sample.app\n",
+}
+
+
+def test_same_named_annotation_counts_only_where_it_is_in_scope():
+ sources = {
+ "ui/ThemeShots.kt": _UI_SHOTS.encode(),
+ "other/ThemeShots.kt": _OTHER_SHOTS.encode(),
+ **{path: text.encode() for path, text in _USERS.items()},
+ }
+ meta = MetaAnnotations(sources, _is_framework_registered)
+ assert meta.visible_in("app/SamePackage.kt") == {"ThemeShots", _UI_FQN}
+ assert meta.visible_in("app/Imported.kt") == {"ThemeShots", _UI_FQN}
+ assert meta.visible_in("app/Star.kt") == {"ThemeShots", _UI_FQN}
+ assert meta.visible_in("app/Aliased.kt") == {"UiShots", _UI_FQN}
+ for path in ("app/OtherImport.kt", "app/OtherPackage.kt", "app/Unrelated.kt"):
+ assert meta.visible_in(path) == {_UI_FQN}, path
+ # Unique repo-wide, the name counts wherever it is used.
+ unique = MetaAnnotations({"ui/ThemeShots.kt": _UI_SHOTS.encode()}, _is_framework_registered)
+ assert unique.visible_in("app/Unrelated.kt") == {"ThemeShots", _UI_FQN}
+
+
+def test_qualified_use_matches_by_fully_qualified_name():
+ sources = {
+ "ui/ThemeShots.kt": _UI_SHOTS.encode(),
+ "other/ThemeShots.kt": _OTHER_SHOTS.encode(),
+ "app/Unrelated.kt": _USERS["app/Unrelated.kt"].encode(),
+ "app/OtherPackage.kt": _USERS["app/OtherPackage.kt"].encode(),
+ }
+ meta = MetaAnnotations(sources, _is_framework_registered)
+ for path in ("app/Unrelated.kt", "app/OtherPackage.kt"):
+ visible = meta.visible_in(path)
+ # Out of scope by simple name, the preview one still counts qualified.
+ assert _is_framework_registered([f"@{_UI_FQN}"], visible), path
+ assert not _is_framework_registered(["@org.sample.other.ThemeShots"], visible), path
+ # In the other class's package, the bare name means the non-preview one.
+ assert not _is_framework_registered(["@ThemeShots"], meta.visible_in("app/OtherPackage.kt"))