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 build-named, JMH and bare-name-used JVM classes as used (#2917)
Raghav Chamadiya57c0c0c9e1c6
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.mdindex b805aeb89..774b7ccfd 100644--- a/docs/layers/DEAD_CODE.md+++ b/docs/layers/DEAD_CODE.md@@ -194,6 +194,7 @@ these, so they are never flagged rather than flagged and down-weighted.| Shell scripts | `*.sh`, `*.bash`, `*.zsh`. Invoked by name from CI configs and Makefiles; static reachability is meaningless || Programs | Any file whose first line is a shebang, and any Python file with a top-level `if __name__ == "__main__":` block. Nothing imports an entry point || Files a runner names | A file a CI workflow (`.github/workflows/`, `.gitlab-ci.yml`, `.circleci/`, `.buildkite/`), build file (above), task file (`Dockerfile`, `tox.ini`), manifest (`pyproject.toml`, `package.json`, `setup.cfg`) or shell script names by path. A doc that names a file only caps it at `0.40` |+| Build-named JVM classes | A class whose fully-qualified name a `build.gradle(.kts)` quotes: `esplugin { classname '...' }`, `implementationClass`, `mainClass` || Framework routes | Next.js `page.tsx` / `layout.tsx` / `route.ts` / `middleware.ts`, SvelteKit `+page.svelte`, Nuxt `pages/*.vue`, Remix entry files, ASP.NET minimal-API `Apis/` / `Endpoints/`, Blazor and Razor code-behind || Test files | `*_test.go`, `*.test.ts`, `*.spec.ts`, `*_test.cc`, `*Test.java`, `**/tests/*.rs`, `src/test/java/`, MSTest and xUnit project layouts, `__tests__/`, `__mocks__/` || Generated code | protoc `*.pb.go` / `*.pb.cs` / `*.pb.cc`, Qt MOC/UIC/RCC, Bison/Flex, SWIG, Cython, stringer, MapStruct `*MapperImpl.java`, Dagger, AutoValue, Roslyn `*.g.cs`, Dart `*.g.dart` / `*.freezed.dart`, `**/generated/**` |@@ -206,7 +207,12 @@ Symbols decorated by a framework are treated as live too: pytest fixtures, Flaskand FastAPI routes, Django `admin.register` and signal receivers, Celery tasks,Click and Typer commands, and the JVM stereotype and routing annotations(`@Component`, `@Service`, `@RestController`, `@Entity`, `@KafkaListener`,-`@GetMapping`, `@Test`, JAX-RS `@Path` / `@GET`). Decorator *suffixes* are matched+`@GetMapping`, `@Test`, JAX-RS `@Path` / `@GET`), and JMH `@State`,+`@BenchmarkMode` and `@Benchmark`. Every annotation of a Java or Kotlin+declaration counts, not only the first. A Java, Kotlin or Scala export whose+name is written in another code file, or further down its own file, is+dropped: those languages use a type from its own package by its bare name,+with no import. Decorator *suffixes* are matchedtoo, so `@my_local_group.command` and `@api.get` register even when the receiverhas a project-local name.diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex ccfef3e39..4e3a2fe89 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -77,6 +77,7 @@ from .name_occurrences import (clamp_path_mentions,clamp_unverified_absence,demote_used_in_own_file,+ drop_bare_name_uses,drop_internals_used_in_own_file,drop_reference_assembly_api,)@@ -220,7 +221,7 @@ def _is_framework_registered(decorators: list[str]) -> bool:``register`` exactly or a ``register_`` stem so that a past participleguarding a handler (``@registered_only``) is not read as one."""- bases = [_decorator_base(d) for d in decorators]+ bases = _decorator_bases(decorators)if any(b.startswith(_FRAMEWORK_DECORATORS) for b in bases):return Trueif any(b.endswith(_FRAMEWORK_DECORATOR_SUFFIXES) for b in bases):@@ -233,6 +234,23 @@ def _is_framework_registered(decorators: list[str]) -> bool:)+def _decorator_bases(decorators: Iterable[str]) -> list[str]:+ """The base name of every annotation in *decorators*.++ A Java or Kotlin modifiers blob carries all of a declaration's annotations+ (``@Fork(1) @State(Scope.Thread) public``), so each blob is split on+ ``@`` once its quoted arguments are blanked, the way+ :func:`_is_symbol_deprecated` reads it. Reading only the blob's first+ annotation missed every one after it.+ """+ return [+ _decorator_base(token)+ for blob in decorators+ for token in _QUOTED_STR_RE.sub('""', str(blob)).split("@")+ if token.strip()+ ]++def _is_receiver_registration(base: str) -> bool:"""Whether a dotted decorator hands the symbol to a receiver object.@@ -1014,6 +1032,7 @@ class DeadCodeAnalyzer:# 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".+ findings = drop_bare_name_uses(findings, self._source_map)findings = clamp_unverified_absence(findings, self._source_map)findings = drop_internals_used_in_own_file(findings, self._source_map)findings = clamp_path_mentions(findings, self._source_map)diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex ba49dcba3..d47f322a4 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -837,6 +837,10 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("Dependent","Factory","Bean",+ # JMH: the harness instantiates @State classes and runs @Benchmark+ # methods (and every @BenchmarkMode class) by reflection.+ "Benchmark",+ "State",# ---- JVM: lifecycle / event / scheduling / messaging callbacks --"PostConstruct","PreDestroy",@@ -1048,6 +1052,9 @@ _NAMESPACE_IMPORT_LANGUAGES: frozenset[str] = frozenset({"csharp"})# ``typedef struct _X {...} X`` tag used only through ``X``, a function called# through a ``#define`` alias or a ``##``-pasted name, an icall table entry._PREPROCESSED_LANGUAGES: frozenset[str] = frozenset({"c", "cpp", "objectivec"})+# Languages that use a type from its own package by its bare name, with no+# import, so a symbol's name written in another code file is taken as a use.+_BARE_NAME_USE_LANGUAGES: frozenset[str] = frozenset({"java", "kotlin", "scala"})# Annotations whose *argument* is the signal (``@SuppressWarnings("unused")``),# matched against the raw decorator text rather than its base name.diff --git a/packages/core/src/repowise/core/analysis/dead_code/jvm_name_scope.py b/packages/core/src/repowise/core/analysis/dead_code/jvm_name_scope.pynew file mode 100644index 000000000..f3ef3efef--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/jvm_name_scope.py@@ -0,0 +1,130 @@+"""Whether a JVM file's bare type name can refer to a given class.++Java, Kotlin and Scala use a type from their own package by its bare name, so+a class's name written in another file is usually a use the import graph+cannot see. It is not one when the name means a different type there: a+nested record of the same name, or a generated protobuf message imported from+another package. Reading those as uses hides a class nothing references.++A bare name in file W can refer to class ``C`` of package ``P`` when W does not+declare or explicitly import another ``C`` (either shadows it), and one of:++* W is in package ``P``;+* W writes ``P.C`` (a single-type import, a static import, a qualified use)+ or imports ``P.*``;+* no other file declares or imports a type named ``C``, so the name has+ nothing else to mean. A Kotlin ``expect``/``actual`` pair is one type.++Text-level, like the rest of the name scan. A declaration keyword followed by+the name in a comment reads as a second declaration, which only keeps a+finding reported.+"""++from __future__ import annotations++import re+from functools import lru_cache++from ...ingestion.languages.jvm_same_package import _IMPORT_LINE_RE+from ...ingestion.resolvers.jvm_workspace import _PACKAGE_RE++#: Keywords that declare a type. ``message`` is a protobuf declaration, whose+#: generated class shares the message's name.+_TYPE_KEYWORDS = r"(?:class|interface|enum|record|object|trait|typealias|message)"++#: A Kotlin ``expect`` or ``actual`` declaration is the same multiplatform type+#: in another source set, not another type.+_MULTIPLATFORM_RE = re.compile(r"\b(?:expect|actual)\b")+++class JvmNameScope:+ """Answers :meth:`can_refer` over one source map.++ Every per-file fact (text, package, imports, whether it means another type+ of a name) and the per-name "declared anywhere else" answer are computed+ once, so judging every writer of a name stays linear in the writers.+ """++ def __init__(self, source_map: dict[str, bytes]) -> None:+ self._source_map = source_map+ self._texts: dict[str, str] = {}+ self._packages: dict[str, str] = {}+ self._imports: dict[str, list[str]] = {}+ self._others: dict[tuple[str, str, str], bool] = {}+ self._declared_elsewhere: dict[tuple[str, str], bool] = {}++ def can_refer(self, name: str, declaring: str, writers: set[str], writer: str) -> bool:+ """Whether *name* written in *writer* can mean the class *declaring* declares.++ *writers* is every file writing *name*, used to tell whether the name+ is declared anywhere else.+ """+ package = self._package(declaring)+ fqn = f"{package}.{name}" if package else name+ if self._means_other(writer, name, fqn):+ return False+ if self._package(writer) == package or _names_fqn(self._text(writer), fqn, package):+ return True+ key = (name, declaring)+ elsewhere = self._declared_elsewhere.get(key)+ if elsewhere is None:+ elsewhere = any(+ self._means_other(path, name, fqn) for path in writers if path != declaring+ )+ self._declared_elsewhere[key] = elsewhere+ return not elsewhere++ def _means_other(self, path: str, name: str, fqn: str) -> bool:+ """Whether *path* declares its own *name* or imports one other than *fqn*."""+ key = (path, name, fqn)+ answer = self._others.get(key)+ if answer is None:+ answer = _declares(self._text(path), name) or any(+ imported.rsplit(".", 1)[-1] == name and imported != fqn+ for imported in self._imported(path)+ )+ self._others[key] = answer+ return answer++ def _package(self, path: str) -> str:+ package = self._packages.get(path)+ if package is None:+ match = _PACKAGE_RE.search(self._text(path))+ package = self._packages[path] = match.group(1) if match else ""+ return package++ def _imported(self, path: str) -> list[str]:+ imported = self._imports.get(path)+ if imported is None:+ imported = self._imports[path] = _IMPORT_LINE_RE.findall(self._text(path))+ return imported++ def _text(self, path: str) -> str:+ text = self._texts.get(path)+ if text is None:+ text = self._source_map.get(path, b"").decode("utf-8", "replace")+ self._texts[path] = text+ return text+++def _names_fqn(text: str, fqn: str, package: str) -> bool:+ """Whether *text* writes *fqn* or imports every type of *package*."""+ if not package:+ return False # a class in the default package cannot be imported+ pattern = rf"(?<![\w.]){re.escape(fqn)}\b|^\s*import\s+{re.escape(package)}\.[*_]"+ return re.search(pattern, text, re.MULTILINE) is not None+++def _declares(text: str, name: str) -> bool:+ """Whether *text* declares a type *name* that is not a multiplatform half."""+ for match in _declaration_re(name).finditer(text):+ start = text.rfind("\n", 0, match.start()) + 1+ end = text.find("\n", match.end())+ if not _MULTIPLATFORM_RE.search(text, start, end if end >= 0 else len(text)):+ return True+ return False+++@lru_cache(maxsize=1024)+def _declaration_re(name: str) -> re.Pattern[str]:+ return re.compile(rf"\b{_TYPE_KEYWORDS}\s+{re.escape(name)}\b")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.pyindex 30f2f826c..6969c777a 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@@ -76,6 +76,10 @@ _STEREOTYPE_ANNOTATIONS: frozenset[str] = frozenset({"Endpoint","RestControllerEndpoint","RegisterForReflection",+ # JMH runs these by reflection; ``Benchmark`` sits on the methods.+ "State",+ "BenchmarkMode",+ "Benchmark",})@@ -127,10 +131,15 @@ def _file_defines_entry_class(graph: Any, file_node: str) -> bool:if edge.get("edge_type") != "defines":continue# Stereotype annotation on a class / record / object.+ # One modifiers blob holds every annotation of the declaration.decorators = succ_data.get("decorators") or []- for dec in decorators:- if _annotation_base(dec) in _STEREOTYPE_ANNOTATIONS:- return True+ if any(+ _annotation_base(token) in _STEREOTYPE_ANNOTATIONS+ for dec in decorators+ for token in dec.split("@")+ if token.strip()+ ):+ return True# ``main`` method — JAR / Kotlin file entry point.if (succ_data.get("kind") in ("method", "function")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 263da6f25..6ff8d3471 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@@ -50,9 +50,18 @@ import refrom collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom enum import Enum--from .constants import _TOOL_CONFIG_LOAD_KEYS, is_runner_file, is_tool_config+from pathlib import PurePosixPath++from ...ingestion.languages.registry import REGISTRY+from .constants import (+ _BARE_NAME_USE_LANGUAGES,+ _NON_CODE_LANGUAGES,+ _TOOL_CONFIG_LOAD_KEYS,+ is_runner_file,+ is_tool_config,+)from .entry_shape import export_shape+from .jvm_name_scope import JvmNameScopefrom .models import DeadCodeFindingData, DeadCodeKindfrom .risk_factors import RISK_CAP_CONFIDENCE@@ -96,6 +105,8 @@ class _Answer(Enum):class _Verdict:answer: _Answerused_at: str | None = None+ # ``used_at`` is a code file, not documentation or config.+ in_code: bool = False_NOT_SEARCHABLE = _Verdict(_Answer.NOT_SEARCHABLE)@@ -178,7 +189,7 @@ def _uses_in_own_file(continueif lineno in headers[token]:continue # a sibling declaration of the same name- out[id(finding)] = _Verdict(_Answer.USED, f"{path}:{lineno}")+ out[id(finding)] = _Verdict(_Answer.USED, f"{path}:{lineno}", in_code=True)return out@@ -253,10 +264,41 @@ def _is_own_type_sibling(occurrence: str, declaring: str) -> bool:return stem == base+def _used_in(paths: list[str]) -> _Verdict:+ """A use in *paths*, preferring a code file to a doc or config."""+ in_code = [path for path in paths if _language(path) not in _NON_CODE_LANGUAGES]+ return _Verdict(_Answer.USED, (in_code or paths)[0], in_code=bool(in_code))+++def _uses_elsewhere(+ finding: DeadCodeFindingData, files: set[str], scope: JvmNameScope | None+) -> list[str]:+ """The files other than *finding*'s own whose mention of its name is a use.++ With *scope*, only the first such file is returned, code files first: one+ is all :func:`_used_in` needs, and a common name has hundreds of writers.+ """+ declaring = finding.file_path+ others = sorted(f for f in files - {declaring} if not _is_own_type_sibling(f, declaring))+ if scope is None:+ return others+ others.sort(key=lambda path: _language(path) in _NON_CODE_LANGUAGES)+ first = next(+ (f for f in others if scope.can_refer(finding.symbol_name, declaring, files, f)), None+ )+ return [first] if first is not None else []++def _verdicts(- source_map: dict[str, bytes], candidates: list[DeadCodeFindingData]+ source_map: dict[str, bytes],+ candidates: list[DeadCodeFindingData],+ scope: JvmNameScope | None = None,) -> dict[int, _Verdict]:- """One verdict per candidate, from one repo-wide scan plus targeted reads."""+ """One verdict per candidate, from one repo-wide scan plus targeted reads.++ With *scope*, another file's mention counts only when its bare name can+ refer to the candidate's own class.+ """# 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 = {searchable_token(f.symbol_name) for f in candidates} - {b""}@@ -275,13 +317,9 @@ def _verdicts(out[id(finding)] = _NOT_SEARCHABLEcontinuefiles = occurrences.get(token, set())- elsewhere = sorted(- f- for f in files - {finding.file_path}- if not _is_own_type_sibling(f, finding.file_path)- )+ elsewhere = _uses_elsewhere(finding, files, scope)if elsewhere:- out[id(finding)] = _Verdict(_Answer.USED, elsewhere[0])+ out[id(finding)] = _used_in(elsewhere)elif finding.file_path in files:same_file_only.setdefault(finding.file_path, []).append(finding)else:@@ -359,6 +397,41 @@ def clamp_unverified_absence(return findings+def _language(path: str) -> str | None:+ return REGISTRY.from_extension(PurePosixPath(path).suffix)+++def drop_bare_name_uses(+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]+) -> list[DeadCodeFindingData]:+ """Drop unused exports whose name another code file, or their own, writes.++ For a language that uses a type from its own package by its bare name (a+ Java class, a nested type used further down its own file), the name+ written in code outside the declaration is the use the import graph+ cannot see, so the finding is wrong rather than doubtful. A mention only+ in documentation or config is left to :func:`clamp_unverified_absence`.+ A mention whose name means another type there (a same-named nested type,+ a generated message class) is not a use; see :mod:`.jvm_name_scope`.+ Returns a new list.+ """+ candidates = [f for f in findings if _uses_bare_names(f)]+ if not candidates or not source_map:+ return findings+ verdicts = _verdicts(source_map, candidates, JvmNameScope(source_map))+ used = {key for key, verdict in verdicts.items() if verdict.in_code}+ return [f for f in findings if id(f) not in used]+++def _uses_bare_names(finding: DeadCodeFindingData) -> bool:+ """An unused export in a language that uses a type by its bare name."""+ return (+ finding.kind is DeadCodeKind.UNUSED_EXPORT+ and bool(finding.symbol_name)+ and _language(finding.file_path) in _BARE_NAME_USE_LANGUAGES+ )++def drop_internals_used_in_own_file(findings: list[DeadCodeFindingData], source_map: dict[str, bytes]) -> list[DeadCodeFindingData]:diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex 6023b9c24..da4f81bc3 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -86,6 +86,11 @@ def _warmup_jvm(ctx: ResolverContext) -> None:entry_fqns.update(impls)for fqns in index.autoconfig_imports.values():entry_fqns.update(fqns)+ # Classes a Gradle build script names (plugin ``classname``,+ # ``implementationClass``, ``mainClass``) and loads by reflection.+ from .resolvers.jvm_gradle import build_script_class_names++ entry_fqns.update(build_script_class_names(ctx))for fqn in entry_fqns:for path in index.files_for_fqn(fqn):diff --git a/packages/core/src/repowise/core/ingestion/queries/java.scm b/packages/core/src/repowise/core/ingestion/queries/java.scmindex 239ba231d..d0af4cc58 100644--- a/packages/core/src/repowise/core/ingestion/queries/java.scm+++ b/packages/core/src/repowise/core/ingestion/queries/java.scm@@ -7,35 +7,27 @@; Symbols; ---------------------------------------------------------------------------+; One pattern per declaration, modifiers optional: with a second pattern+; that captured them, the bare one matched first and a class's annotations+; (``@Component``, ``@State``) never reached its symbol.(class_declaration- name: (identifier) @symbol.name-) @symbol.def--(class_declaration- (modifiers) @symbol.modifiers- name: (identifier) @symbol.name-) @symbol.def--(interface_declaration+ (modifiers)? @symbol.modifiersname: (identifier) @symbol.name) @symbol.def(interface_declaration- (modifiers) @symbol.modifiers+ (modifiers)? @symbol.modifiersname: (identifier) @symbol.name) @symbol.def(enum_declaration+ (modifiers)? @symbol.modifiersname: (identifier) @symbol.name) @symbol.def; Java 16+ records: record Point(double x, double y) {}(record_declaration- name: (identifier) @symbol.name-) @symbol.def--(record_declaration- (modifiers) @symbol.modifiers+ (modifiers)? @symbol.modifiersname: (identifier) @symbol.name) @symbol.defdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.pyindex 4539c3043..81b9b0c48 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py@@ -52,6 +52,9 @@ _PLUGIN_ID_GROOVY_RE = re.compile(r"id\s+['\"]([^'\"]+)['\"]")_APPLY_PLUGIN_RE = re.compile(r"apply\s+plugin:\s*['\"]([^'\"]+)['\"]")_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)_ROOT_PROJECT_NAME_RE = re.compile(r'rootProject\s*\.\s*name\s*=\s*"([^"]+)"')+# A quoted fully-qualified class name: lowercase package segments, then a+# capitalised type (``'org.elasticsearch.system.indices.SystemIndicesQA'``).+_QUOTED_FQN_RE = re.compile(r"""['"]((?:[a-z_]\w*\.)+[A-Z]\w*)['"]""")_DEFAULT_MAIN_SRC_ROOTS = ("src/main/java", "src/main/kotlin")_DEFAULT_TEST_SRC_ROOTS = ("src/test/java", "src/test/kotlin")@@ -398,6 +401,31 @@ def build_jvm_gradle_index(return index+def build_script_class_names(ctx: ResolverContext) -> set[str]:+ """Fully-qualified class names quoted in any Gradle build script.++ A build names a class it loads by reflection: a plugin's+ ``esplugin { classname '...' }``, ``gradlePlugin`` ``implementationClass``,+ an application ``mainClass``. Every build script in the tree is read,+ since a settings file that adds projects by walking directories names+ none of them. A name only counts once it resolves to a class in the repo.+ """+ names: set[str] = set()+ if ctx.repo_path is None:+ return names+ for script in glob_via(+ getattr(ctx, "walk_snapshot", None),+ ctx.repo_path,+ ("build.gradle", "build.gradle.kts"),+ prune_nested_git=ctx.prune_nested_git,+ ):+ try:+ names.update(_QUOTED_FQN_RE.findall(script.read_text(encoding="utf-8", errors="ignore")))+ except OSError:+ continue+ return names++def get_or_build_jvm_gradle_index(ctx: ResolverContext) -> JvmGradleIndex:"""Return the cached JvmGradleIndex, building it on first access."""cached = getattr(ctx, "_jvm_gradle_index", None)diff --git a/tests/unit/dead_code/test_jvm_build_roots.py b/tests/unit/dead_code/test_jvm_build_roots.pynew file mode 100644index 000000000..b6b2b121e--- /dev/null+++ b/tests/unit/dead_code/test_jvm_build_roots.py@@ -0,0 +1,234 @@+"""JVM classes a build or a harness loads, and types used by bare name.++Shapes from elasticsearch, every one reported dead: a plugin class named only+in ``esplugin { classname '...' }``, a JMH benchmark whose ``@State`` sits+behind another class annotation, and a type used from its own package or+further down its own file with no import.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_FILES = {+ "settings.gradle": "rootProject.name = 'sample'\n",+ "build.gradle": "apply plugin: 'java'\n",+ "gradle/plugins/src/main/kotlin/java-library.sample.gradle.kts": "plugins { java }\n",+ "qa/system-indices/build.gradle": (+ "esplugin {\n"+ " name = 'system-indices-qa'\n"+ " classname = 'org.sample.indices.SystemIndicesQA'\n"+ "}\n"+ ),+ "qa/system-indices/src/main/java/org/sample/indices/SystemIndicesQA.java": (+ "package org.sample.indices;\n\npublic class SystemIndicesQA {\n}\n"+ ),+ "benchmarks/src/main/java/org/sample/bench/SortBench.java": (+ "package org.sample.bench;\n\n"+ "@Fork(1)\n@State(Scope.Thread)\npublic class SortBench {\n"+ " @Benchmark\n public void sort() {}\n}\n"+ ),+ # A production plugin module (``qa/`` trees are test code) whose build+ # names one class; its sibling no build script quotes stays a control,+ # as does a class whose only annotation is not a JMH root.+ "plugins/analysis/build.gradle": (+ "esplugin {\n classname = 'org.sample.analysis.AnalysisPlugin'\n}\n"+ ),+ "plugins/analysis/src/main/java/org/sample/analysis/AnalysisPlugin.java": (+ "package org.sample.analysis;\n\npublic class AnalysisPlugin {\n}\n"+ ),+ "plugins/analysis/src/main/java/org/sample/analysis/Unlisted.java": (+ "package org.sample.analysis;\n\npublic class Unlisted {\n}\n"+ ),+ "benchmarks/src/main/java/org/sample/bench/ForkOnly.java": (+ "package org.sample.bench;\n\n@Fork(1)\npublic class ForkOnly {\n}\n"+ ),+ "server/src/main/java/org/sample/core/FilterType.java": (+ "package org.sample.core;\n\npublic enum FilterType { A, B }\n"+ ),+ "server/src/main/java/org/sample/core/FilterRef.java": (+ "package org.sample.core;\n\npublic class FilterRef {\n"+ " public enum Mode { FAST, SLOW }\n\n"+ " FilterType type;\n Mode mode;\n"+ " public static void main(String[] args) {}\n}\n"+ ),+ "server/src/main/java/org/sample/core/Orphan.java": (+ "package org.sample.core;\n\npublic class Orphan {\n}\n"+ ),+ # Signal-Server: an unused top-level record whose name is also a nested+ # record in another package and a protobuf message.+ "app/src/main/java/org/sample/entities/SetKeyRequest.java": (+ "package org.sample.entities;\n\npublic record SetKeyRequest(String key) {\n}\n"+ ),+ "app/src/main/java/org/sample/entities/Shared.java": (+ "package org.sample.entities;\n\npublic class Shared {\n}\n"+ ),+ "app/src/main/java/org/sample/entities/SharedUser.java": (+ "package org.sample.entities;\n\npublic class SharedUser {\n"+ " Shared shared;\n public static void main(String[] args) {}\n}\n"+ ),+ "app/src/main/java/org/sample/controllers/ArchiveController.java": (+ "package org.sample.controllers;\n\npublic class ArchiveController {\n"+ " public record SetKeyRequest(String key) {}\n"+ " public static class Shared {}\n"+ " void set(SetKeyRequest request, Shared shared) {}\n"+ " public static void main(String[] args) {}\n}\n"+ ),+ "app/src/main/java/org/sample/grpc/BackupsService.java": (+ "package org.sample.grpc;\n\nimport org.sample.backup.SetKeyRequest;\n\n"+ "public class BackupsService {\n void set(SetKeyRequest request) {}\n"+ " public static void main(String[] args) {}\n}\n"+ ),+ "app/src/main/proto/backups.proto": (+ 'syntax = "proto3";\n\npackage org.sample.backup;\n\n'+ "message SetKeyRequest {\n string key = 1;\n}\n"+ ),+}+++def _report(root: Path):+ for rel, text in _FILES.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ parser = ASTParser()+ builder = GraphBuilder(repo_path=root)+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(root).traverse():+ source = Path(fi.abs_path).read_bytes()+ source_map[fi.path] = source+ builder.add_file(parser.parse_file(fi, source))+ builder.set_source_map(source_map)+ graph = builder.build()+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={}, source_map=source_map)+ return analyzer.analyze({"min_confidence": 0.0, "detect_zombie_packages": False})+++def _named(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_build_named_plugin_class_is_not_reported(tmp_path: Path):+ report = _report(tmp_path)+ assert "SystemIndicesQA" not in _named(report, DeadCodeKind.UNUSED_EXPORT)+ assert "SystemIndicesQA.java" not in _named(report, DeadCodeKind.UNREACHABLE_FILE)+++def test_jmh_class_with_state_after_another_annotation_is_not_reported(tmp_path: Path):+ report = _report(tmp_path)+ assert "SortBench" not in _named(report, DeadCodeKind.UNUSED_EXPORT)+ assert "SortBench.java" not in _named(report, DeadCodeKind.UNREACHABLE_FILE)+++def test_type_used_by_bare_name_is_not_reported(tmp_path: Path):+ exports = _named(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)+ assert "FilterType" not in exports # from its package+ assert "Mode" not in exports # further down its own file+++def test_gradle_kotlin_script_is_not_reported(tmp_path: Path):+ unreachable = _named(_report(tmp_path), DeadCodeKind.UNREACHABLE_FILE)+ assert "java-library.sample.gradle.kts" not in unreachable+++def test_class_nothing_names_is_still_reported(tmp_path: Path):+ assert "Orphan" in _named(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)+++def test_unquoted_class_and_non_jmh_annotation_are_still_reported(tmp_path: Path):+ exports = _named(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)+ assert "AnalysisPlugin" not in exports+ assert "Unlisted" in exports+ assert "ForkOnly" in exports+++def test_name_meaning_another_type_elsewhere_is_not_a_use(tmp_path: Path):+ # A same-named nested record in another package and a generated message+ # class imported from another package both mean other types.+ assert "SetKeyRequest" in _named(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)+++def test_same_package_use_counts_despite_a_same_named_type_elsewhere(tmp_path: Path):+ assert "Shared" not in _named(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)+++def test_class_annotations_reach_the_symbol():+ from repowise.core.ingestion.models import FileInfo++ source = b"package a;\n\n@Fork(1)\n@State(Scope.Thread)\npublic class C {\n}\n"+ info = FileInfo(+ path="C.java", abs_path="C.java", language="java", size_bytes=len(source),+ git_hash="", last_modified=None, is_test=False, is_config=False, is_api_contract=False,+ is_entry_point=False,+ )+ [cls] = [s for s in ASTParser().parse_file(info, source).symbols if s.name == "C"]+ assert "@State(Scope.Thread)" in cls.decorators[0]+++def test_kotlin_expect_declaration_is_the_same_type():+ from repowise.core.analysis.dead_code.jvm_name_scope import JvmNameScope++ common = "common/src/org/sample/mp/Engine.kt"+ actual = "jvm/src/org/sample/mp/BridgeJvm.kt"+ source_map = {+ common: (+ b"package org.sample.mp\n\ninternal expect class Bridge(x: Int)\n\n"+ b"class Engine {\n private val bridge = Bridge(1)\n}\n"+ ),+ actual: b"package org.sample.mp\n\ninternal actual class Bridge actual constructor(x: Int)\n",+ }+ assert JvmNameScope(source_map).can_refer("Bridge", actual, set(source_map), common)+++_DECLARING = "a/src/org/sample/a/Foo.java"+_OTHER = "b/src/org/sample/b/Foo.java"+++def _scope_refers(writer_text: bytes) -> bool:+ from repowise.core.analysis.dead_code.jvm_name_scope import JvmNameScope++ writer = "c/src/org/sample/c/User.java"+ source_map = {+ _DECLARING: b"package org.sample.a;\n\npublic class Foo {}\n",+ _OTHER: b"package org.sample.b;\n\npublic class Foo {}\n",+ writer: writer_text,+ }+ return JvmNameScope(source_map).can_refer("Foo", _DECLARING, set(source_map), writer)+++def test_fqn_or_package_import_lets_a_name_refer_to_the_class():+ assert _scope_refers(b"package org.sample.c;\n\nimport org.sample.a.Foo;\n\nclass User { Foo f; }\n")+ assert _scope_refers(b"package org.sample.c;\n\nimport org.sample.a.*;\n\nclass User { Foo f; }\n")+ assert not _scope_refers(b"package org.sample.c;\n\nimport org.sample.b.*;\n\nclass User { Foo f; }\n")+++def test_kotlin_typealias_shadows_the_name():+ assert not _scope_refers(+ b"package org.sample.c\n\nimport org.sample.a.*\n\ntypealias Foo = String\nval f: Foo = \"\"\n"+ )+++def test_each_writer_is_read_once(monkeypatch):+ from repowise.core.analysis.dead_code import jvm_name_scope++ calls = 0+ declares = jvm_name_scope._declares++ def counting(text: str, name: str) -> bool:+ nonlocal calls+ calls += 1+ return declares(text, name)++ monkeypatch.setattr(jvm_name_scope, "_declares", counting)+ source_map = {_OTHER: b"package org.sample.b;\n\npublic class Foo {}\n"}+ source_map.update(+ {f"x/X{i}.java": f"package org.sample.x{i};\n\nclass X{i} {{ Foo f; }}\n".encode() for i in range(300)}+ )+ source_map[_DECLARING] = b"package org.sample.a;\n\npublic class Foo {}\n"+ scope = jvm_name_scope.JvmNameScope(source_map)+ writers = set(source_map)+ assert not any(scope.can_refer("Foo", _DECLARING, writers, w) for w in writers - {_DECLARING})+ assert calls <= len(writers)