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): a module with a program main is run, not a zombie or unused export (#3645)
Swati Ahuja3fcaf556942d
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 8cb81e362..83e758eef 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -61,7 +61,12 @@ from .dynamic_markers import (find_dynamic_import_files,read_source_text,)-from .entry_shape import clamp_entry_shaped, drop_program_entries, is_program+from .entry_shape import (+ clamp_entry_shaped,+ defines_main_function,+ drop_program_entries,+ is_program,+)from .file_reachability import (CSHARP_SUFFIX,PackageFileMap,@@ -70,6 +75,7 @@ from .file_reachability import (is_file_reachable,)from .go_name_uses import drop_go_package_uses+from .jvm_reachability import defines_mainfrom .kotlin_multiplatform import settle_platform_declarationsfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReportfrom .module_strings import drop_named_modules@@ -1435,7 +1441,8 @@ class DeadCodeAnalyzer:# Roots include framework-instantiated files the runtime constructs.# Not ``is_file_reachable``: its barrel rescue is scoped to files, and an# unused symbol defined in a barrel should still be flagged.- if is_reachability_root(node_data):+ # A JVM ``main`` launches its file the same way.+ if is_reachability_root(node_data) or defines_main(self.graph, str(node)):return Noneif node_data.get("is_test", False):return None@@ -2166,10 +2173,21 @@ class DeadCodeAnalyzer:if not self._has_package_manifest(pkg, files):return False# Tests are run, never imported, and so is a package that ships a- # program (a CLI started by its shebang). One program file is enough,- # even a stray script: this errs toward not calling a package dead.+ # program: a CLI started by its shebang, a JVM ``main``, or a root+ # with a top-level ``main`` (Dart ``lib/main.dart``). A root alone is+ # not enough: a Rust ``lib.rs`` is a root and the library's surface.+ # One program file is enough, even a stray script: this errs toward+ # not calling a package dead.files = [f for f in files if not self.graph.nodes.get(f, {}).get("is_test")]- if any(is_program(f, self._source_map.get(f, b"")) for f in files):+ if any(+ is_program(f, self._source_map.get(f, b""))+ or defines_main(self.graph, f)+ or (+ is_reachability_root(self.graph.nodes[f])+ and defines_main_function(self.graph, f)+ )+ for f in files+ ):return False# A real package contains at least one source file something could# import. Config and data (YAML, JSON, MD, TOML) is metadata, and adiff --git a/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py b/packages/core/src/repowise/core/analysis/dead_code/entry_shape.pyindex 2fe7eb2fe..0d9fbad01 100644--- a/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py+++ b/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py@@ -29,6 +29,7 @@ import refrom collections import defaultdictfrom collections.abc import Mappingfrom pathlib import PurePosixPath+from typing import Anyfrom ...ingestion.extractors.visibility import _TS_BLOCK_COMMENT, _TS_CJS_EXPORTS_REfrom ...ingestion.languages.registry import REGISTRY@@ -136,6 +137,24 @@ def is_program(path: str, blob: bytes) -> bool:return _program_reason(path, blob) is not None+def defines_main_function(graph: Any, file_node: str) -> bool:+ """Whether *file_node* defines a top-level function named ``main``.++ A program's start in Kotlin, Dart, Go, Rust and C. On its own it is weak+ (a Python helper may be named ``main``), so callers pair it with a root+ stamp or a language rule.+ """+ return any(+ sym.get("node_type") == "symbol"+ and sym.get("kind") == "function"+ and sym.get("name") == "main"+ and not sym.get("parent_name")+ and graph.get_edge_data(file_node, succ, {}).get("edge_type") == "defines"+ for succ in graph.successors(file_node)+ for sym in (graph.nodes.get(succ, {}),)+ )++def drop_program_entries(findings: list[DeadCodeFindingData], source_map: dict[str, bytes]) -> list[DeadCodeFindingData]: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 6969c777a..d39343acc 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@@ -27,10 +27,13 @@ reaching this hook.from __future__ import annotations+import re+from collections.abc import Iteratorfrom pathlib import PurePosixPathfrom typing import Anyfrom ...entry_candidacy import is_reachability_root+from .entry_shape import defines_main_function# Class-level annotation names (without the leading ``@``) that mark the# bearing class as runtime-instantiated. Kept compact; full Spring@@ -119,34 +122,70 @@ def _annotation_base(decorator: str) -> str:return s-def _file_defines_entry_class(graph: Any, file_node: str) -> bool:- """True if *file_node* defines a class with a stereotype annotation- or a ``main`` method.- """+# The shape follows the JVM launcher rules: one ``String[]`` parameter+# (``String[] a``, ``String... a``, ``String a[]``, annotations allowed) or,+# since Java 25 (JEP 512), no parameters. The graph keeps no ``static`` keyword+# for Java, so the parameter shape is what tells the entry point from an+# ordinary method that happens to be named ``main``.+_JAVA_ANNOTATION = r"@[\w.]+(?:\([^)]*\))?"+_JAVA_MAIN_PARAMS = re.compile(+ rf"^main\(\s*(?:(?:(?:{_JAVA_ANNOTATION}|final)\s+)*(?:java\.lang\.)?String"+ rf"(?:\s*(?:{_JAVA_ANNOTATION}\s*)?(?:\[\s*\]|\.\.\.)\s*\w+|\s+\w+\s*\[\s*\])\s*)?\)"+)+++def _defined_symbols(graph: Any, file_node: str) -> Iterator[dict[str, Any]]:+ """The attribute dicts of the symbols *file_node* defines."""for succ in graph.successors(file_node):succ_data = graph.nodes.get(succ, {})if succ_data.get("node_type") != "symbol":continue- edge = graph.get_edge_data(file_node, succ, {})- 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 []- 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")- and succ_data.get("name") == "main"- ):- return True- return False+ if graph.get_edge_data(file_node, succ, {}).get("edge_type") == "defines":+ yield succ_data+++def _is_main_method(is_java: bool, sym: dict[str, Any]) -> bool:+ # The symbol name, not the id: an overloaded Java id reads ``main#1(String[])``.+ if sym.get("name") != "main" or sym.get("kind") != "method":+ return False+ if is_java:+ return bool(_JAVA_MAIN_PARAMS.match(sym.get("signature") or ""))+ # Kotlin: a ``@JvmStatic`` main in an object. A class member ``fun main()``+ # is an ordinary method.+ return "JvmStatic" in _annotation_names(sym)+++def _annotation_names(sym: dict[str, Any]) -> set[str]:+ # One modifiers blob holds every annotation of the declaration.+ return {+ _annotation_base(token)+ for dec in sym.get("decorators") or []+ for token in dec.split("@")+ if token.strip()+ }+++def defines_main(graph: Any, file_node: str) -> bool:+ """True if *file_node* is a Java or Kotlin file declaring a program ``main``."""+ if not file_node.endswith((".java", ".kt")):+ return False+ is_java = file_node.endswith(".java")+ # Kotlin's top-level ``fun main`` is a function, not a method.+ if not is_java and defines_main_function(graph, file_node):+ return True+ return any(_is_main_method(is_java, sym) for sym in _defined_symbols(graph, file_node))+++def _file_defines_entry_class(graph: Any, file_node: str) -> bool:+ """True if *file_node* defines a class with a stereotype annotation+ or a ``main`` method.+ """+ if any(+ not _STEREOTYPE_ANNOTATIONS.isdisjoint(_annotation_names(sym))+ for sym in _defined_symbols(graph, file_node)+ ):+ return True+ return defines_main(graph, file_node)def is_jvm_file_reachable(diff --git a/tests/unit/analysis/test_jvm_reachability.py b/tests/unit/analysis/test_jvm_reachability.pyindex 65b6dea63..bf3e41e3d 100644--- a/tests/unit/analysis/test_jvm_reachability.py+++ b/tests/unit/analysis/test_jvm_reachability.py@@ -152,6 +152,7 @@ class TestJvmFileReachable:symbols=[{"name": "main","kind": "method",+ "signature": "main(String[] args) -> void","visibility": "public","language": "java",}],diff --git a/tests/unit/dead_code/test_program_main.py b/tests/unit/dead_code/test_program_main.pynew file mode 100644index 000000000..31811e07b--- /dev/null+++ b/tests/unit/dead_code/test_program_main.py@@ -0,0 +1,130 @@+"""A module that declares a program ``main`` is run, never imported.++A Gradle or Maven module whose Kotlin ``fun main`` or Java launcher ``main``+starts the application, or a Flutter package with ``lib/main.dart``, has no+importer by design, so it is not a zombie package, and the class holding a+JVM ``main`` is not an unused export.+"""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.analysis.dead_code.jvm_reachability import defines_main+from repowise.core.ingestion.graph.builder import GraphBuilder+from repowise.core.ingestion.parser import ASTParser+from repowise.core.ingestion.traverser import FileTraverser++_FILES = {+ "settings.gradle.kts": 'include("server", "tool", "worker", "shared")\n',+ # Kotlin application module.+ "server/build.gradle.kts": "plugins { application }\n",+ "server/src/main/kotlin/demo/Launcher.kt": (+ "package demo\n\nfun main(args: Array<String>) {\n println(args.size)\n}\n"+ ),+ # Java application module: the launcher class has no importer.+ "tool/pom.xml": "<project/>\n",+ "tool/src/main/java/demo/tool/Tool.java": (+ "package demo.tool;\n\npublic class Tool {\n"+ " public static void main(String[] args) {}\n}\n"+ ),+ # Java 25 launches an instance ``void main()``.+ "applet/pom.xml": "<project/>\n",+ "applet/src/main/java/demo/applet/Hello.java": (+ "package demo.applet;\n\npublic class Hello {\n void main() {}\n}\n"+ ),+ # A ``main(int)`` is an ordinary method.+ "worker/pom.xml": "<project/>\n",+ "worker/src/main/java/demo/worker/Worker.java": (+ "package demo.worker;\n\npublic class Worker {\n public void main(int n) {}\n}\n"+ ),+ # A library module nobody imports.+ "shared/build.gradle.kts": "plugins { `java-library` }\n",+ "shared/src/main/kotlin/demo/shared/Strings.kt": (+ "package demo.shared\n\nfun shout(s: String): String = s.uppercase()\n"+ ),+ # Flutter app.+ "mobile/pubspec.yaml": "name: mobile\n",+ "mobile/lib/main.dart": "void main() {}\n",+ # A Rust library: ``lib.rs`` is a root, but not a program.+ "old-rs/Cargo.toml": '[package]\nname = "old"\n',+ "old-rs/src/lib.rs": "pub fn h() {}\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)+ analyzer = DeadCodeAnalyzer(+ builder.build(), 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 f.file_path for f in report.findings if f.kind is kind}+++def test_program_modules_are_not_zombies_and_libraries_still_are(tmp_path: Path):+ zombies = _of(_report(tmp_path), DeadCodeKind.ZOMBIE_PACKAGE)+ assert zombies.isdisjoint({"server", "tool", "applet", "mobile"})+ assert {"shared", "worker", "old-rs"} <= zombies+++def test_java_main_class_is_not_an_unused_export(tmp_path: Path):+ exports = _of(_report(tmp_path), DeadCodeKind.UNUSED_EXPORT)+ assert "Tool" not in exports+ assert "Worker" in exports+++def _graph(path: str, *symbols: dict) -> nx.DiGraph:+ g = nx.DiGraph()+ g.add_node(path, node_type="file")+ for i, sym in enumerate(symbols):+ g.add_node(f"{path}::{i}", node_type="symbol", **sym)+ g.add_edge(path, f"{path}::{i}", edge_type="defines")+ return g+++def test_defines_main_reads_the_name_and_the_launcher_shape():+ def java(sig: str) -> bool:+ sym = {"kind": "method", "name": "main", "parent_name": "A", "signature": sig}+ return defines_main(_graph("A.java", sym), "A.java")++ assert java("main(String[] args) -> void")+ assert java("main(String... args) -> void")+ assert java("main(String args[]) -> void")+ assert java("main(final java.lang.String[] argv) -> void")+ assert java("main(@Nullable String[] args) -> void")+ assert java("main(final @Foo(x = 1) String[] a) -> void")+ assert java("main(String @Foo [] a) -> void")+ assert java("main() -> void")+ assert not java("main(String s) -> void")+ assert not java("main(int x) -> void")+ # The id of an overloaded Java method carries a discriminator, the name does not.+ assert not defines_main(+ _graph("B.java", {"kind": "method", "name": "main#1(String[])", "signature": "x"}),+ "B.java",+ )++ def kotlin(**sym) -> bool:+ return defines_main(_graph("K.kt", {"name": "main", **sym}), "K.kt")++ assert kotlin(kind="function", signature="function main()")+ assert kotlin(kind="method", parent_name="Obj", decorators=["@JvmStatic"])+ assert not kotlin(kind="method", parent_name="K", decorators=[])+ # Only JVM files.+ assert not defines_main(_graph("m.py", {"kind": "function", "name": "main"}), "m.py")