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): honour Kotlin @Suppress("unused") and keep annotations the grammar splits off (#3873)

Wade339aa70bcfd7
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 43821ca63..b08a535aa 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -185,13 +185,20 @@ def _declared_deliberately_unused(decorators: Iterable[str]) -> bool:
continue
base = _decorator_base(token)
if any(
- base == name and argument in token
- for name, argument in _DELIBERATELY_UNUSED_ANNOTATIONS
+ base == name and _carries_argument(token, argument, whole)
+ for name, argument, whole in _DELIBERATELY_UNUSED_ANNOTATIONS
):
return True
return False
+def _carries_argument(token: str, argument: str, whole: bool) -> bool:
+ """*argument* in the annotation *token*: a substring, or one whole quoted argument."""
+ if not whole:
+ return argument in token
+ return argument in (q[1:-1].lower() for q in _QUOTED_STR_RE.findall(token))
+
+
def _is_framework_registered(
decorators: list[str], meta_annotations: frozenset[str] = frozenset()
) -> bool:
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 446f52a70..bd86080e1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -1089,9 +1089,13 @@ _PREPROCESSED_LANGUAGES: frozenset[str] = frozenset({"c", "cpp", "objectivec"})
_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.
-_DELIBERATELY_UNUSED_ANNOTATIONS: tuple[tuple[str, str], ...] = (
- ("SuppressWarnings", "unused"),
+# matched against the raw decorator text rather than its base name. The third
+# field asks for a whole quoted argument, case-insensitive: Kotlin writes both
+# ``unused`` and ``UNUSED``, and ``UNUSED_PARAMETER`` / ``UNUSED_VARIABLE``
+# silence a warning inside the body, not one about the declaration.
+_DELIBERATELY_UNUSED_ANNOTATIONS: tuple[tuple[str, str, bool], ...] = (
+ ("SuppressWarnings", "unused", False),
+ ("Suppress", "unused", True),
)
# Inner class names a framework reads off the class that declares them, so no
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index d3fd09821..78557e337 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -889,9 +889,39 @@ def _attribute_decorators(def_node: Node, language: str, src: str) -> list[str]:
# (NOT a preceding sibling at translation_unit level).
if language in ("cpp", "c"):
return _leading_child_attributes(def_node, "attribute_declaration", "[[", "]]", src)
+ if language == "kotlin":
+ return _kotlin_detached_annotation(def_node, src)
return []
+def _kotlin_detached_annotation(def_node: Node, src: str) -> list[str]:
+ """Kotlin: annotations the grammar split off a top-level declaration.
+
+ When the last annotation on its own line before a bare ``fun`` or
+ ``object`` takes one argument (``@Suppress("unused")``), the argument list
+ reads as a parenthesized expression: the annotations become an
+ ``annotated_expression`` chain beside a declaration with no modifiers.
+ """
+ if def_node.parent is None or def_node.parent.type != "source_file":
+ return []
+ sib = def_node.prev_sibling
+ while sib is not None and sib.type in ("line_comment", "block_comment"):
+ sib = sib.prev_sibling
+ return [_node_text(sib, src).strip()] if _is_split_annotation_chain(sib) else []
+
+
+def _is_split_annotation_chain(node: Node | None) -> bool:
+ """Nested ``annotated_expression`` nodes of annotations, the last one's argument at the tail."""
+ while node is not None and node.type == "annotated_expression":
+ kinds = [c.type for c in node.named_children]
+ if len(kinds) != 2 or kinds[0] != "annotation":
+ return False
+ if kinds[1] == "parenthesized_expression":
+ return True
+ node = node.named_children[1]
+ return False
+
+
def _declared_modifiers(def_node: Node, node_types: frozenset[str], src: str) -> tuple[str, ...]:
"""Lowercased keyword modifiers written in *def_node*'s modifier children.
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index 1d0a209c1..c03e3116e 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -97,6 +97,8 @@ STORE_FORMAT_VERSION: int = 2
#: ``s.forEachSegment { }``) is a call site, with one argument.
#: A Kotlin ``typealias`` signature carries its target (``typealias Repo =
#: DefaultRepository``), so a call through the alias reaches the repo class.
+#: A top-level Kotlin declaration keeps the annotations the grammar splits off
+#: it when the last one takes one argument (``@Suppress("unused")``).
PARSER_SCHEMA_VERSION: int = 8
#: state.json key holding the store format version that wrote the store.
diff --git a/tests/unit/dead_code/test_framework_registration_rescues.py b/tests/unit/dead_code/test_framework_registration_rescues.py
index 0a393052a..50a0dd12e 100644
--- a/tests/unit/dead_code/test_framework_registration_rescues.py
+++ b/tests/unit/dead_code/test_framework_registration_rescues.py
@@ -8,9 +8,14 @@ writes an extension method's name and never its holder class's.
from __future__ import annotations
+from pathlib import Path
+
import networkx as nx
+import pytest
from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.analyzer import _declared_deliberately_unused
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
from tests.unit.dead_code._helpers import _build_graph
@@ -118,6 +123,65 @@ def test_a_bare_suppresswarnings_still_flags():
assert "activate" in _unused_export_names(graph)
+ "decorator",
+ ['@Suppress("unused")', '@Suppress("UNUSED")', '@Suppress("unused", "DEPRECATION")'],
+)
+def test_kotlin_suppress_unused_is_read_as_an_author_statement(decorator: str):
+ """Kotlin's spelling of ``@SuppressWarnings("unused")``, in either case."""
+ assert _declared_deliberately_unused([decorator])
+
+
+ "decorator",
+ [
+ '@Suppress("UNUSED_PARAMETER")',
+ '@Suppress("UNUSED_VARIABLE")',
+ '@Suppress("unused_expression")',
+ '@Suppress("DEPRECATION")',
+ "@Suppress",
+ ],
+)
+def test_kotlin_suppress_of_another_warning_is_not_deliberate(decorator: str):
+ """``UNUSED_PARAMETER`` silences a warning inside the body, not about the symbol."""
+ assert not _declared_deliberately_unused([decorator])
+
+
+_KOTLIN_SUPPRESS_FILES = {
+ "src/main/kotlin/app/AppInfo.kt": (
+ 'package app\n\n@Suppress("UNUSED")\nobject AppInfo { fun getVersionCode(): Int = 1 }\n'
+ ),
+ "src/main/kotlin/app/Extensions.kt": (
+ "package app\n\n"
+ '@Suppress("unused")\n'
+ "fun String.selectText(): String = trim()\n\n"
+ "fun String.reallyUnused(): String = this\n"
+ ),
+ "src/main/kotlin/app/Main.kt": 'package app\n\nfun main() { println("hi") }\n',
+}
+
+
+def test_kotlin_suppress_unused_rescues_only_the_annotated_declarations(tmp_path: Path):
+ """``selectText`` is the grammar's shape that detaches a lone annotation."""
+ source_map = {rel: text.encode() for rel, text in _KOTLIN_SUPPRESS_FILES.items()}
+ for rel, source in source_map.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(source)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=tmp_path)
+ for fi in FileTraverser(tmp_path).traverse():
+ builder.add_file(parser.parse_file(fi, source_map[fi.path]))
+ builder.set_source_map(source_map)
+ graph = builder.build()
+ report = DeadCodeAnalyzer(
+ graph, git_meta_map={}, source_map=source_map, repo_root=tmp_path
+ ).analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ unused = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "reallyUnused" in unused
+ assert unused.isdisjoint({"AppInfo", "selectText"})
+
+
def _holder_graph(language: str, wire_call: bool) -> nx.DiGraph:
graph = _build_graph(
nodes={
diff --git a/tests/unit/ingestion/test_kotlin_extractors.py b/tests/unit/ingestion/test_kotlin_extractors.py
index badbcbfb1..7823629d9 100644
--- a/tests/unit/ingestion/test_kotlin_extractors.py
+++ b/tests/unit/ingestion/test_kotlin_extractors.py
@@ -132,3 +132,46 @@ class TestKotlinAliasImports:
src = b"package x\nimport com.example.Foo as\nclass App\n"
imp = parser.parse_file(_file(), src).imports[0]
assert [(b.local_name, b.exported_name) for b in imp.bindings] == [("Foo", "Foo")]
+
+
+class TestKotlinDetachedAnnotation:
+ """A lone one-argument annotation the grammar reads as an expression.
+
+ At top level, ``@Suppress("unused")`` on its own line before a bare ``fun``
+ or ``object`` parses as an ``annotated_expression`` (the argument list read
+ as a parenthesized expression) beside a declaration with no modifiers.
+ """
+
+ @staticmethod
+ def _decorators(parser: ASTParser, src: bytes) -> dict[str, list[str]]:
+ return {s.name: s.decorators for s in parser.parse_file(_file(), src).symbols}
+
+ def test_function_keeps_its_annotation(self, parser: ASTParser) -> None:
+ src = b'package x\n\n@Suppress("unused")\nfun a(): Int = 1\n\nfun z() {}\n'
+ decorators = self._decorators(parser, src)
+ assert decorators["a"] == ['@Suppress("unused")']
+ assert decorators["z"] == []
+
+ def test_extension_function_keeps_its_annotation(self, parser: ASTParser) -> None:
+ src = b'package x\n\n@Deprecated("old")\nfun String.a(): String = this\n\nfun z() {}\n'
+ assert self._decorators(parser, src)["a"] == ['@Deprecated("old")']
+
+ def test_object_keeps_its_annotation(self, parser: ASTParser) -> None:
+ src = b'package x\n\n@Suppress("UNUSED")\nobject A\n\nfun z() {}\n'
+ assert self._decorators(parser, src)["A"] == ['@Suppress("UNUSED")']
+
+ def test_annotation_stack_ending_in_one_argument(self, parser: ASTParser) -> None:
+ src = b'package x\n\n@JvmStatic\n@Suppress("unused")\nfun a(x: Int) {}\n\nfun z() {}\n'
+ assert self._decorators(parser, src)["a"] == ['@JvmStatic\n@Suppress("unused")']
+
+ def test_comment_between_annotation_and_declaration(self, parser: ASTParser) -> None:
+ src = b'package x\n\n@JvmName("b")\n// kept for Java callers\nfun a() {}\n\nfun z() {}\n'
+ assert self._decorators(parser, src)["a"] == ['@JvmName("b")']
+
+ def test_annotation_inside_modifiers_is_not_doubled(self, parser: ASTParser) -> None:
+ src = b'package x\n\n@Suppress("unused", "X")\nfun a() {}\n\nfun z() {}\n'
+ assert self._decorators(parser, src)["a"] == ['@Suppress("unused", "X")']
+
+ def test_file_annotation_is_not_taken(self, parser: ASTParser) -> None:
+ src = b'@file:Suppress("unused")\npackage x\n\nfun a() {}\n\nfun z() {}\n'
+ assert self._decorators(parser, src)["a"] == []