code-prune 1.7.0__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0 - 2026-12-04
4
+
5
+ ### Added
6
+
7
+ - `suppression_annotations.json`: JSON configuration of the annotations that
8
+ exempt declarations from `unused-symbol`. Each annotation lists one or more
9
+ languages and optional parameter rules (`values`, optional `name`, and a
10
+ `match` of `exists`, `in-array`, `in-array-only` or `in-all-arrays`). It is
11
+ bootstrapped into `CODE_PRUNE_CONFIG_DIR` so it can be customised.
12
+ - Gosu `$name` string interpolation (double-quoted strings) now counts as a
13
+ usage, so symbols referenced only that way are no longer reported as unused.
14
+
15
+ ### Changed
16
+
17
+ - **Breaking:** the `@SuppressWarnings` (Java/Gosu) and `@Export` (Gosu) rules
18
+ moved from hard-coded tables (`SUPPRESS_WARNINGS_NAME`,
19
+ `SUPPRESS_WARNINGS_VALUES`, `EXPORT_ANNOTATION_NAMES` in
20
+ `code_prune.language_tables`) into the default JSON file, which preserves the
21
+ previous behaviour.
22
+
3
23
  ## 1.7.0 - 2026-11-29
4
24
 
5
25
  ### Changed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-prune
3
- Version: 1.7.0
3
+ Version: 2.0.0
4
4
  Summary: Find unreachable, unused, and obsolete code before it becomes technical debt.
5
5
  License: MIT License
6
6
 
@@ -56,7 +56,7 @@ Description-Content-Type: text/markdown
56
56
 
57
57
  # code-prune
58
58
 
59
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [![Version](https://img.shields.io/badge/Version-1.7.0-green.svg)](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [![Python](https://img.shields.io/badge/Python-3.14%2B-blue)](https://www.python.org/) [![PyPI](https://img.shields.io/badge/PyPI-code--prune-orange)](https://pypi.org/project/code-prune/)
59
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [![Version](https://img.shields.io/badge/Version-2.0.0-green.svg)](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [![Python](https://img.shields.io/badge/Python-3.14%2B-blue)](https://www.python.org/) [![PyPI](https://img.shields.io/badge/PyPI-code--prune-orange)](https://pypi.org/project/code-prune/)
60
60
 
61
61
 
62
62
  A CLI tool that scans a codebase for unreachable, unused, and obsolete code,
@@ -145,7 +145,8 @@ HTML summary line shows only the total number of findings.
145
145
 
146
146
  Logging is bootstrapped via `env-dir-bootstrap`. Set the `CODE_PRUNE_CONFIG_DIR`
147
147
  environment variable to override the default configuration directory used to
148
- resolve `logging.ini`, `config.ini`, `.codepruneignore`, and `symbol_ignore`.
148
+ resolve `logging.ini`, `config.ini`, `.codepruneignore`, `symbol_ignore`, and
149
+ `suppression_annotations.json`.
149
150
 
150
151
  ### Ignoring files and directories
151
152
 
@@ -171,10 +172,48 @@ intentionally-unreferenced symbols.
171
172
 
172
173
  Overriding members are also never reported as unused symbols: Java `@Override`,
173
174
  Gosu `override` / `@Override`, TypeScript `override`, and Python `@override` /
174
- `@typing.override`. In Java and Gosu, declarations annotated with
175
- `@SuppressWarnings("unused")` or `@SuppressWarnings("all")` (including a class
176
- annotated that way, which covers all of its members) are skipped as well, as are
177
- Gosu declarations annotated with `@Export` (on a class, this covers its members).
175
+ `@typing.override`.
176
+
177
+ Gosu `$name` and `${expr}` string interpolation in double-quoted strings counts
178
+ as a usage of `name` (single-quoted Gosu strings are not interpolated).
179
+
180
+ ### Suppression annotations
181
+
182
+ `suppression_annotations.json` configures the annotations that exempt a
183
+ declaration from "unused" findings. An annotation on a class also exempts all
184
+ of its members. The default file contains:
185
+
186
+ ```json
187
+ {
188
+ "annotations": [
189
+ {
190
+ "name": "SuppressWarnings",
191
+ "languages": ["Java", "Gosu"],
192
+ "parameters": [{"values": ["unused", "all"], "match": "in-array"}]
193
+ },
194
+ {"name": "Export", "languages": ["Gosu"]}
195
+ ]
196
+ }
197
+ ```
198
+
199
+ - `name` is the simple annotation name (`@a.b.Name` matches `Name`).
200
+ - `languages` lists every language the annotation applies to (`Java`, `Gosu`).
201
+ - `parameters` is optional. Without it, the annotation suppresses by being
202
+ present; with it, at least one parameter rule must match. A rule has
203
+ `values` (case-insensitive strings, any one is enough unless noted),
204
+ an optional `name` (only inspect the argument with that name; a positional
205
+ argument is named `value`; omit to inspect every argument) and a `match`
206
+ qualifier (default `exists`):
207
+
208
+ | `match` | Satisfied when |
209
+ |-----------------|------------------------------------------------------------------------------|
210
+ | `exists` | a value appears anywhere in an argument (plain, array or nested literal). |
211
+ | `in-array` | a value is a plain argument or an element of an array argument. |
212
+ | `in-array-only` | a value is an element of an array argument (a plain argument does not count).|
213
+ | `in-all-arrays` | **all** values are present once the elements of every array argument are combined. |
214
+
215
+ Edit the copy in the configuration directory (`CODE_PRUNE_CONFIG_DIR`) to
216
+ change the behaviour; an invalid file stops the scan with an explanatory error.
178
217
 
179
218
  ## Development
180
219
 
@@ -1,6 +1,6 @@
1
1
  # code-prune
2
2
 
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [![Version](https://img.shields.io/badge/Version-1.7.0-green.svg)](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [![Python](https://img.shields.io/badge/Python-3.14%2B-blue)](https://www.python.org/) [![PyPI](https://img.shields.io/badge/PyPI-code--prune-orange)](https://pypi.org/project/code-prune/)
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [![Version](https://img.shields.io/badge/Version-2.0.0-green.svg)](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [![Python](https://img.shields.io/badge/Python-3.14%2B-blue)](https://www.python.org/) [![PyPI](https://img.shields.io/badge/PyPI-code--prune-orange)](https://pypi.org/project/code-prune/)
4
4
 
5
5
 
6
6
  A CLI tool that scans a codebase for unreachable, unused, and obsolete code,
@@ -89,7 +89,8 @@ HTML summary line shows only the total number of findings.
89
89
 
90
90
  Logging is bootstrapped via `env-dir-bootstrap`. Set the `CODE_PRUNE_CONFIG_DIR`
91
91
  environment variable to override the default configuration directory used to
92
- resolve `logging.ini`, `config.ini`, `.codepruneignore`, and `symbol_ignore`.
92
+ resolve `logging.ini`, `config.ini`, `.codepruneignore`, `symbol_ignore`, and
93
+ `suppression_annotations.json`.
93
94
 
94
95
  ### Ignoring files and directories
95
96
 
@@ -115,10 +116,48 @@ intentionally-unreferenced symbols.
115
116
 
116
117
  Overriding members are also never reported as unused symbols: Java `@Override`,
117
118
  Gosu `override` / `@Override`, TypeScript `override`, and Python `@override` /
118
- `@typing.override`. In Java and Gosu, declarations annotated with
119
- `@SuppressWarnings("unused")` or `@SuppressWarnings("all")` (including a class
120
- annotated that way, which covers all of its members) are skipped as well, as are
121
- Gosu declarations annotated with `@Export` (on a class, this covers its members).
119
+ `@typing.override`.
120
+
121
+ Gosu `$name` and `${expr}` string interpolation in double-quoted strings counts
122
+ as a usage of `name` (single-quoted Gosu strings are not interpolated).
123
+
124
+ ### Suppression annotations
125
+
126
+ `suppression_annotations.json` configures the annotations that exempt a
127
+ declaration from "unused" findings. An annotation on a class also exempts all
128
+ of its members. The default file contains:
129
+
130
+ ```json
131
+ {
132
+ "annotations": [
133
+ {
134
+ "name": "SuppressWarnings",
135
+ "languages": ["Java", "Gosu"],
136
+ "parameters": [{"values": ["unused", "all"], "match": "in-array"}]
137
+ },
138
+ {"name": "Export", "languages": ["Gosu"]}
139
+ ]
140
+ }
141
+ ```
142
+
143
+ - `name` is the simple annotation name (`@a.b.Name` matches `Name`).
144
+ - `languages` lists every language the annotation applies to (`Java`, `Gosu`).
145
+ - `parameters` is optional. Without it, the annotation suppresses by being
146
+ present; with it, at least one parameter rule must match. A rule has
147
+ `values` (case-insensitive strings, any one is enough unless noted),
148
+ an optional `name` (only inspect the argument with that name; a positional
149
+ argument is named `value`; omit to inspect every argument) and a `match`
150
+ qualifier (default `exists`):
151
+
152
+ | `match` | Satisfied when |
153
+ |-----------------|------------------------------------------------------------------------------|
154
+ | `exists` | a value appears anywhere in an argument (plain, array or nested literal). |
155
+ | `in-array` | a value is a plain argument or an element of an array argument. |
156
+ | `in-array-only` | a value is an element of an array argument (a plain argument does not count).|
157
+ | `in-all-arrays` | **all** values are present once the elements of every array argument are combined. |
158
+
159
+ Edit the copy in the configuration directory (`CODE_PRUNE_CONFIG_DIR`) to
160
+ change the behaviour; an invalid file stops the scan with an explanatory error.
122
161
 
123
162
  ## Development
124
163
 
@@ -10,11 +10,17 @@ Since: 1.0.0
10
10
  from env_dir_bootstrap import EnvDirBootstrap
11
11
 
12
12
  __app_name__ = "code-prune"
13
- __version__ = "1.7.0"
13
+ __version__ = "2.0.0"
14
14
 
15
15
  _bootstrapper = EnvDirBootstrap(
16
16
  env_var="CODE_PRUNE_CONFIG_DIR",
17
- resources=["logging.ini", "config.ini", ".codepruneignore", "symbol_ignore"],
17
+ resources=[
18
+ "logging.ini",
19
+ "config.ini",
20
+ ".codepruneignore",
21
+ "symbol_ignore",
22
+ "suppression_annotations.json",
23
+ ],
18
24
  package="code_prune",
19
25
  )
20
26
 
@@ -23,3 +29,4 @@ _bootstrapper.setup()
23
29
  CONF_DIR = str(_bootstrapper.get_dir())
24
30
  PATH_IGNORE_PATH = _bootstrapper.resolve(".codepruneignore")
25
31
  SYMBOL_IGNORE_PATH = _bootstrapper.resolve("symbol_ignore")
32
+ SUPPRESSION_ANNOTATIONS_PATH = _bootstrapper.resolve("suppression_annotations.json")
@@ -0,0 +1,284 @@
1
+ """JSON-configurable annotations that exempt declarations from ``unused-symbol``.
2
+
3
+ Each configured annotation lists the languages it applies to and, optionally,
4
+ parameter rules qualifying which arguments make it suppress. See the README for
5
+ the file format.
6
+
7
+ Author: Ron Webb
8
+ Since: 2.0.0
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from collections.abc import Collection, Mapping, Sequence
15
+ from dataclasses import dataclass
16
+ from functools import lru_cache
17
+ from pathlib import Path
18
+
19
+ from . import SUPPRESSION_ANNOTATIONS_PATH
20
+ from .language_tables import ANNOTATION_NODE_TYPES
21
+
22
+ MATCH_EXISTS = "exists"
23
+ MATCH_IN_ARRAY = "in-array"
24
+ MATCH_IN_ARRAY_ONLY = "in-array-only"
25
+ MATCH_IN_ALL_ARRAYS = "in-all-arrays"
26
+ MATCH_MODES = frozenset(
27
+ {MATCH_EXISTS, MATCH_IN_ARRAY, MATCH_IN_ARRAY_ONLY, MATCH_IN_ALL_ARRAYS}
28
+ )
29
+
30
+ #: Name assumed for a positional (unnamed) annotation argument.
31
+ DEFAULT_ARGUMENT_NAME = "value"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class AnnotationArgument:
36
+ """The string values of one argument of an annotation usage.
37
+
38
+ ``plain`` holds the value of a scalar string argument, ``array`` the
39
+ elements of an array argument and ``all_values`` every string literal found
40
+ anywhere inside the argument. Values are lower-cased.
41
+
42
+ Author: Ron Webb
43
+ Since: 2.0.0
44
+ """
45
+
46
+ name: str = DEFAULT_ARGUMENT_NAME
47
+ plain: frozenset[str] = frozenset()
48
+ array: frozenset[str] = frozenset()
49
+ all_values: frozenset[str] = frozenset()
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ParameterRule:
54
+ """A qualifier on the arguments of a configured annotation.
55
+
56
+ *name* restricts the rule to the argument of that name (``None`` means any
57
+ argument). *match* is one of :data:`MATCH_MODES`:
58
+
59
+ - ``exists``: any of *values* appears anywhere in an argument.
60
+ - ``in-array``: any of *values* is a plain argument or an array element.
61
+ - ``in-array-only``: any of *values* is an array element.
62
+ - ``in-all-arrays``: *all* of *values* are present once the elements of
63
+ every array argument are combined.
64
+
65
+ Author: Ron Webb
66
+ Since: 2.0.0
67
+ """
68
+
69
+ values: frozenset[str]
70
+ match: str = MATCH_EXISTS
71
+ name: str | None = None
72
+
73
+ def matches(self, arguments: Sequence[AnnotationArgument]) -> bool:
74
+ """Return whether *arguments* satisfy this rule.
75
+
76
+ Author: Ron Webb
77
+ Since: 2.0.0
78
+ """
79
+ candidates = [
80
+ argument
81
+ for argument in arguments
82
+ if self.name is None or argument.name == self.name
83
+ ]
84
+ if self.match == MATCH_IN_ALL_ARRAYS:
85
+ pooled = frozenset().union(*(argument.array for argument in candidates))
86
+ return self.values <= pooled
87
+ return any(self._argument_matches(argument) for argument in candidates)
88
+
89
+ def _argument_matches(self, argument: AnnotationArgument) -> bool:
90
+ """Return whether a single *argument* satisfies a per-argument mode.
91
+
92
+ Author: Ron Webb
93
+ Since: 2.0.0
94
+ """
95
+ if self.match == MATCH_EXISTS:
96
+ return bool(self.values & argument.all_values)
97
+ if self.match == MATCH_IN_ARRAY:
98
+ return bool(self.values & (argument.plain | argument.array))
99
+ return bool(self.values & argument.array)
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class AnnotationRule:
104
+ """A configured suppression annotation.
105
+
106
+ Without *parameters* the annotation suppresses by being present; otherwise
107
+ at least one parameter rule must match.
108
+
109
+ Author: Ron Webb
110
+ Since: 2.0.0
111
+ """
112
+
113
+ name: str
114
+ languages: frozenset[str]
115
+ parameters: tuple[ParameterRule, ...] = ()
116
+
117
+ def matches(self, arguments: Sequence[AnnotationArgument]) -> bool:
118
+ """Return whether the annotation usage with *arguments* suppresses.
119
+
120
+ Author: Ron Webb
121
+ Since: 2.0.0
122
+ """
123
+ if not self.parameters:
124
+ return True
125
+ return any(rule.matches(arguments) for rule in self.parameters)
126
+
127
+
128
+ class AnnotationRuleSet:
129
+ """Configured annotation rules indexed by language and annotation name.
130
+
131
+ Author: Ron Webb
132
+ Since: 2.0.0
133
+ """
134
+
135
+ def __init__(self, rules: Collection[AnnotationRule] = ()) -> None:
136
+ """Index *rules* by language and annotation name.
137
+
138
+ Author: Ron Webb
139
+ Since: 2.0.0
140
+ """
141
+ self._index: dict[str, dict[str, list[AnnotationRule]]] = {}
142
+ for rule in rules:
143
+ for language in rule.languages:
144
+ self._index.setdefault(language, {}).setdefault(rule.name, []).append(
145
+ rule
146
+ )
147
+
148
+ def supports(self, language: str) -> bool:
149
+ """Return whether any annotation is configured for *language*.
150
+
151
+ Author: Ron Webb
152
+ Since: 2.0.0
153
+ """
154
+ return language in self._index
155
+
156
+ def is_suppressing(
157
+ self, language: str, name: str, arguments: Sequence[AnnotationArgument]
158
+ ) -> bool:
159
+ """Return whether annotation *name* with *arguments* suppresses.
160
+
161
+ Author: Ron Webb
162
+ Since: 2.0.0
163
+ """
164
+ rules = self._index.get(language, {}).get(name, [])
165
+ return any(rule.matches(arguments) for rule in rules)
166
+
167
+
168
+ def _string_list(raw: object, where: str) -> list[str]:
169
+ """Return *raw* as a non-empty list of strings or raise ``ValueError``.
170
+
171
+ Author: Ron Webb
172
+ Since: 2.0.0
173
+ """
174
+ if (
175
+ not isinstance(raw, list)
176
+ or not raw
177
+ or not all(isinstance(item, str) and item for item in raw)
178
+ ):
179
+ raise ValueError(f"{where} must be a non-empty list of non-empty strings.")
180
+ return raw
181
+
182
+
183
+ def _parse_parameter(raw: object, where: str) -> ParameterRule:
184
+ """Build a :class:`ParameterRule` from its JSON object.
185
+
186
+ Author: Ron Webb
187
+ Since: 2.0.0
188
+ """
189
+ if not isinstance(raw, Mapping):
190
+ raise ValueError(f"{where} must be an object.")
191
+ match = raw.get("match", MATCH_EXISTS)
192
+ if match not in MATCH_MODES:
193
+ raise ValueError(
194
+ f"{where}: 'match' must be one of {sorted(MATCH_MODES)}, got {match!r}."
195
+ )
196
+ name = raw.get("name")
197
+ if name is not None and (not isinstance(name, str) or not name):
198
+ raise ValueError(f"{where}: 'name' must be a non-empty string.")
199
+ values = _string_list(raw.get("values"), f"{where}: 'values'")
200
+ return ParameterRule(
201
+ values=frozenset(value.lower() for value in values), match=match, name=name
202
+ )
203
+
204
+
205
+ def _parse_annotation(
206
+ raw: object, index: int, supported_languages: Collection[str]
207
+ ) -> AnnotationRule:
208
+ """Build an :class:`AnnotationRule` from its JSON object.
209
+
210
+ Author: Ron Webb
211
+ Since: 2.0.0
212
+ """
213
+ where = f"annotations[{index}]"
214
+ if not isinstance(raw, Mapping):
215
+ raise ValueError(f"{where} must be an object.")
216
+ name = raw.get("name")
217
+ if not isinstance(name, str) or not name:
218
+ raise ValueError(f"{where}: 'name' must be a non-empty string.")
219
+ languages = _string_list(raw.get("languages"), f"{where}: 'languages'")
220
+ unsupported = sorted(set(languages) - set(supported_languages))
221
+ if unsupported:
222
+ raise ValueError(
223
+ f"{where}: unsupported language(s) {unsupported}; "
224
+ f"supported: {sorted(supported_languages)}."
225
+ )
226
+ parameters = raw.get("parameters", [])
227
+ if not isinstance(parameters, list):
228
+ raise ValueError(f"{where}: 'parameters' must be a list.")
229
+ return AnnotationRule(
230
+ name=name,
231
+ languages=frozenset(languages),
232
+ parameters=tuple(
233
+ _parse_parameter(parameter, f"{where}.parameters[{position}]")
234
+ for position, parameter in enumerate(parameters)
235
+ ),
236
+ )
237
+
238
+
239
+ def parse_annotation_rules(
240
+ data: object, supported_languages: Collection[str] = tuple(ANNOTATION_NODE_TYPES)
241
+ ) -> AnnotationRuleSet:
242
+ """Build an :class:`AnnotationRuleSet` from decoded JSON *data*.
243
+
244
+ Raises ``ValueError`` when *data* does not follow the documented format.
245
+
246
+ Author: Ron Webb
247
+ Since: 2.0.0
248
+ """
249
+ if not isinstance(data, Mapping) or not isinstance(data.get("annotations"), list):
250
+ raise ValueError("Top level must be an object with an 'annotations' list.")
251
+ return AnnotationRuleSet(
252
+ [
253
+ _parse_annotation(raw, index, supported_languages)
254
+ for index, raw in enumerate(data["annotations"])
255
+ ]
256
+ )
257
+
258
+
259
+ def load_annotation_rules(path: Path) -> AnnotationRuleSet:
260
+ """Read and validate the suppression annotation JSON file at *path*.
261
+
262
+ Author: Ron Webb
263
+ Since: 2.0.0
264
+ """
265
+ try:
266
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
267
+ except json.JSONDecodeError as error:
268
+ raise ValueError(f"Invalid JSON in {path}: {error}") from error
269
+ try:
270
+ return parse_annotation_rules(data)
271
+ except ValueError as error:
272
+ raise ValueError(
273
+ f"Invalid suppression annotations in {path}: {error}"
274
+ ) from error
275
+
276
+
277
+ @lru_cache(maxsize=1)
278
+ def default_annotation_rules() -> AnnotationRuleSet:
279
+ """Return the rules from the configured ``suppression_annotations.json``.
280
+
281
+ Author: Ron Webb
282
+ Since: 2.0.0
283
+ """
284
+ return load_annotation_rules(Path(SUPPRESSION_ANNOTATIONS_PATH))
@@ -0,0 +1,45 @@
1
+ """Usages hidden inside Gosu string interpolation.
2
+
3
+ Gosu parses ``"${expr}"`` into real identifier nodes, but a simple ``"$name"``
4
+ stays plain string text. Those names are real usages, so they are extracted here
5
+ and counted when deciding whether a symbol is unused. Single-quoted Gosu strings
6
+ are not interpolated and are therefore ignored.
7
+
8
+ Author: Ron Webb
9
+ Since: 2.0.0
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from collections.abc import Iterable
16
+
17
+ from tree_sitter import Node # type: ignore[import-untyped]
18
+
19
+ from .language_tables import INTERPOLATED_TEXT_NODE_TYPES
20
+
21
+ _SIMPLE_INTERPOLATION = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)")
22
+
23
+
24
+ def interpolated_names(
25
+ nodes: Iterable[Node], source_bytes: bytes, language: str
26
+ ) -> list[str]:
27
+ """Return the names referenced as ``$name`` within string text of *nodes*.
28
+
29
+ Escaped dollars (``\\$name``) are separate escape-sequence nodes in the
30
+ grammar, so they never reach the text checked here.
31
+
32
+ Author: Ron Webb
33
+ Since: 2.0.0
34
+ """
35
+ text_types = INTERPOLATED_TEXT_NODE_TYPES.get(language)
36
+ if not text_types:
37
+ return []
38
+ names: list[str] = []
39
+ for node in nodes:
40
+ if node.type in text_types:
41
+ text = source_bytes[node.start_byte : node.end_byte].decode(
42
+ "utf-8", errors="replace"
43
+ )
44
+ names.extend(_SIMPLE_INTERPOLATION.findall(text))
45
+ return names
@@ -145,7 +145,7 @@ DECORATOR_NODE_TYPES: dict[str, frozenset[str]] = {
145
145
  "Gosu": frozenset({"annotation"}),
146
146
  }
147
147
 
148
- #: Languages whose declarations may carry ``@SuppressWarnings`` annotations.
148
+ #: Languages whose declarations carry ``modifiers`` annotations (``@Override``).
149
149
  SUPPRESSIBLE_LANGUAGES = frozenset({"Java", "Gosu"})
150
150
 
151
151
  #: Annotation node types found inside a ``modifiers`` node, per language.
@@ -154,24 +154,38 @@ ANNOTATION_NODE_TYPES: dict[str, frozenset[str]] = {
154
154
  "Gosu": frozenset({"annotation"}),
155
155
  }
156
156
 
157
- #: Name of the annotation that suppresses warnings.
158
- SUPPRESS_WARNINGS_NAME = "SuppressWarnings"
157
+ #: Node types holding an annotation's argument list, per language.
158
+ ANNOTATION_ARGUMENT_LIST_TYPES: dict[str, frozenset[str]] = {
159
+ "Java": frozenset({"annotation_argument_list"}),
160
+ "Gosu": frozenset({"annotation_arguments"}),
161
+ }
162
+
163
+ #: Node types of a ``name = value`` annotation argument, per language.
164
+ ANNOTATION_NAMED_ARGUMENT_TYPES: dict[str, frozenset[str]] = {
165
+ "Java": frozenset({"element_value_pair"}),
166
+ "Gosu": frozenset({"named_argument"}),
167
+ }
159
168
 
160
- #: ``@SuppressWarnings`` values (lower-case) that suppress unused-symbol findings.
161
- SUPPRESS_WARNINGS_VALUES = frozenset({"unused", "all"})
169
+ #: Node types of an array-valued annotation argument, per language.
170
+ ANNOTATION_ARRAY_TYPES: dict[str, frozenset[str]] = {
171
+ "Java": frozenset({"element_value_array_initializer"}),
172
+ "Gosu": frozenset({"initializer_expression"}),
173
+ }
162
174
 
163
175
  #: Annotation names marking a method as an override.
164
176
  OVERRIDE_ANNOTATION_NAMES = frozenset({"Override"})
165
177
 
166
- #: Annotation names marking a declaration as exported (used externally), per language.
167
- EXPORT_ANNOTATION_NAMES: dict[str, frozenset[str]] = {"Gosu": frozenset({"Export"})}
168
-
169
178
  #: Modifier node types marking a declaration as an override, per language.
170
179
  OVERRIDE_MODIFIER_TYPES: dict[str, frozenset[str]] = {
171
180
  "TypeScript": frozenset({"override_modifier"}),
172
181
  "Gosu": frozenset({"override"}),
173
182
  }
174
183
 
184
+ #: String-text node types that may contain ``$name`` interpolation, per language.
185
+ INTERPOLATED_TEXT_NODE_TYPES: dict[str, frozenset[str]] = {
186
+ "Gosu": frozenset({"string_content"}),
187
+ }
188
+
175
189
  #: Identifier-like node types counted as a "usage" of a name.
176
190
  USAGE_NODE_TYPES: dict[str, frozenset[str]] = {
177
191
  "Python": frozenset({"identifier"}),
@@ -20,6 +20,7 @@ from pathlib import Path
20
20
 
21
21
  from tree_sitter import Node, Tree # type: ignore[import-untyped]
22
22
 
23
+ from .interpolation import interpolated_names
23
24
  from .language_tables import (
24
25
  BLOCK_NODE_TYPES,
25
26
  CLASS_NODE_TYPES,
@@ -643,15 +644,21 @@ def _collect_usage_names(
643
644
  ) -> list[str]:
644
645
  """Return every usage-identifier name in *tree*, skipping binding sites.
645
646
 
647
+ Gosu ``$name`` string interpolations are counted as usages too.
648
+
646
649
  Author: Ron Webb
647
650
  Since: 1.0.0
648
651
  """
649
652
  usage_types = USAGE_NODE_TYPES.get(language, frozenset())
650
- return [
653
+ names = [
651
654
  _decode(source_bytes, node)
652
655
  for node in _iter_nodes(tree.root_node)
653
656
  if node.type in usage_types and node.start_byte not in excluded_positions
654
657
  ]
658
+ names.extend(
659
+ interpolated_names(_iter_nodes(tree.root_node), source_bytes, language)
660
+ )
661
+ return names
655
662
 
656
663
 
657
664
  def detect_unused_bindings(
@@ -1,10 +1,11 @@
1
1
  """Detection of declarations exempt from ``unused-symbol`` findings.
2
2
 
3
3
  A declaration is exempt when it overrides an inherited member (it is invoked
4
- through its base type, so it never has a textual usage) or, for Java and Gosu,
5
- when it (or an enclosing class) carries ``@SuppressWarnings`` with ``"unused"``
6
- or ``"all"``, or when a Gosu declaration is annotated ``@Export``. Both
7
- annotations on a class also exempt every member of that class.
4
+ through its base type, so it never has a textual usage) or when it (or an
5
+ enclosing class) carries an annotation configured in
6
+ ``suppression_annotations.json`` (by default ``@SuppressWarnings("unused"|"all")``
7
+ for Java/Gosu and ``@Export`` for Gosu). Such an annotation on a class also
8
+ exempts every member of that class.
8
9
 
9
10
  Author: Ron Webb
10
11
  Since: 1.5.0
@@ -14,13 +15,19 @@ from __future__ import annotations
14
15
 
15
16
  from tree_sitter import Node # type: ignore[import-untyped]
16
17
 
18
+ from .annotation_config import (
19
+ DEFAULT_ARGUMENT_NAME,
20
+ AnnotationArgument,
21
+ AnnotationRuleSet,
22
+ default_annotation_rules,
23
+ )
17
24
  from .language_tables import (
25
+ ANNOTATION_ARGUMENT_LIST_TYPES,
26
+ ANNOTATION_ARRAY_TYPES,
27
+ ANNOTATION_NAMED_ARGUMENT_TYPES,
18
28
  ANNOTATION_NODE_TYPES,
19
- EXPORT_ANNOTATION_NAMES,
20
29
  OVERRIDE_ANNOTATION_NAMES,
21
30
  OVERRIDE_MODIFIER_TYPES,
22
- SUPPRESS_WARNINGS_NAME,
23
- SUPPRESS_WARNINGS_VALUES,
24
31
  SUPPRESSIBLE_LANGUAGES,
25
32
  )
26
33
 
@@ -96,47 +103,101 @@ def _annotation_name(annotation: Node, source_bytes: bytes) -> str:
96
103
  return ""
97
104
 
98
105
 
99
- def _string_arguments(annotation: Node, source_bytes: bytes) -> set[str]:
100
- """Return the lower-cased string literal values passed to *annotation*.
106
+ def _string_values(node: Node, source_bytes: bytes) -> frozenset[str]:
107
+ """Return the lower-cased string literal values found inside *node*.
101
108
 
102
109
  Author: Ron Webb
103
110
  Since: 1.5.0
104
111
  """
105
112
  values: set[str] = set()
106
- pending = list(annotation.children)
113
+ pending = [node]
107
114
  while pending:
108
- node = pending.pop()
109
- if node.type == _STRING_NODE_TYPE:
110
- values.add(_decode(source_bytes, node).strip("\"'").lower())
115
+ current = pending.pop()
116
+ if current.type == _STRING_NODE_TYPE:
117
+ values.add(_decode(source_bytes, current).strip("\"'").lower())
111
118
  else:
112
- pending.extend(node.children)
113
- return values
119
+ pending.extend(current.children)
120
+ return frozenset(values)
121
+
114
122
 
123
+ def _build_argument(
124
+ child: Node, source_bytes: bytes, language: str
125
+ ) -> AnnotationArgument:
126
+ """Return the :class:`AnnotationArgument` for the argument node *child*.
115
127
 
116
- def _is_suppressed_here(node: Node, source_bytes: bytes, language: str) -> bool:
117
- """Return whether *node* itself carries a matching ``@SuppressWarnings``.
128
+ A ``name = value`` argument carries its name; a positional one is named
129
+ ``value``.
118
130
 
119
131
  Author: Ron Webb
120
- Since: 1.5.0
132
+ Since: 2.0.0
133
+ """
134
+ name = DEFAULT_ARGUMENT_NAME
135
+ value_node = child
136
+ if child.type in ANNOTATION_NAMED_ARGUMENT_TYPES.get(language, frozenset()):
137
+ name_node = next(
138
+ (item for item in child.named_children if item.type == "identifier"), None
139
+ )
140
+ if name_node is not None and child.named_children:
141
+ name = _decode(source_bytes, name_node)
142
+ value_node = child.named_children[-1]
143
+ is_array = value_node.type in ANNOTATION_ARRAY_TYPES.get(language, frozenset())
144
+ values = _string_values(value_node, source_bytes)
145
+ return AnnotationArgument(
146
+ name=name,
147
+ plain=values if value_node.type == _STRING_NODE_TYPE else frozenset(),
148
+ array=values if is_array else frozenset(),
149
+ all_values=values,
150
+ )
151
+
152
+
153
+ def _annotation_arguments(
154
+ annotation: Node, source_bytes: bytes, language: str
155
+ ) -> list[AnnotationArgument]:
156
+ """Return the arguments passed to *annotation*.
157
+
158
+ Author: Ron Webb
159
+ Since: 2.0.0
160
+ """
161
+ list_types = ANNOTATION_ARGUMENT_LIST_TYPES.get(language, frozenset())
162
+ return [
163
+ _build_argument(child, source_bytes, language)
164
+ for argument_list in annotation.named_children
165
+ if argument_list.type in list_types
166
+ for child in argument_list.named_children
167
+ ]
168
+
169
+
170
+ def _is_annotation_exempt_here(
171
+ node: Node, source_bytes: bytes, language: str, rules: AnnotationRuleSet
172
+ ) -> bool:
173
+ """Return whether *node* itself carries a configured suppressing annotation.
174
+
175
+ Author: Ron Webb
176
+ Since: 2.0.0
121
177
  """
122
178
  return any(
123
- _annotation_name(annotation, source_bytes) == SUPPRESS_WARNINGS_NAME
124
- and _string_arguments(annotation, source_bytes) & SUPPRESS_WARNINGS_VALUES
179
+ rules.is_suppressing(
180
+ language,
181
+ _annotation_name(annotation, source_bytes),
182
+ _annotation_arguments(annotation, source_bytes, language),
183
+ )
125
184
  for annotation in _annotations(node, language)
126
185
  )
127
186
 
128
187
 
129
- def _is_suppressed(node: Node, source_bytes: bytes, language: str) -> bool:
130
- """Return whether *node* or any enclosing declaration suppresses ``unused``.
188
+ def _is_annotation_exempt(
189
+ node: Node, source_bytes: bytes, language: str, rules: AnnotationRuleSet
190
+ ) -> bool:
191
+ """Return whether *node* or any enclosing declaration is exempted by *rules*.
131
192
 
132
193
  Author: Ron Webb
133
- Since: 1.5.0
194
+ Since: 2.0.0
134
195
  """
135
- if language not in SUPPRESSIBLE_LANGUAGES:
196
+ if not rules.supports(language):
136
197
  return False
137
198
  current: Node | None = node
138
199
  while current is not None:
139
- if _is_suppressed_here(current, source_bytes, language):
200
+ if _is_annotation_exempt_here(current, source_bytes, language, rules):
140
201
  return True
141
202
  current = current.parent
142
203
  return False
@@ -183,43 +244,25 @@ def _is_override(node: Node, source_bytes: bytes, language: str) -> bool:
183
244
  )
184
245
 
185
246
 
186
- def _is_exported_here(node: Node, source_bytes: bytes, language: str) -> bool:
187
- """Return whether *node* itself carries an ``@Export``-style annotation.
188
-
189
- Author: Ron Webb
190
- Since: 1.6.0
191
- """
192
- export_names = EXPORT_ANNOTATION_NAMES.get(language, frozenset())
193
- return any(
194
- _annotation_name(annotation, source_bytes) in export_names
195
- for annotation in _annotations(node, language)
196
- )
197
-
198
-
199
- def _is_exported(node: Node, source_bytes: bytes, language: str) -> bool:
200
- """Return whether *node* or any enclosing declaration is ``@Export``-ed.
201
-
202
- Author: Ron Webb
203
- Since: 1.7.0
204
- """
205
- if language not in EXPORT_ANNOTATION_NAMES:
206
- return False
207
- current: Node | None = node
208
- while current is not None:
209
- if _is_exported_here(current, source_bytes, language):
210
- return True
211
- current = current.parent
212
- return False
213
-
214
-
215
- def is_exempt_symbol(node: Node, source_bytes: bytes, language: str) -> bool:
247
+ def is_exempt_symbol(
248
+ node: Node,
249
+ source_bytes: bytes,
250
+ language: str,
251
+ rules: AnnotationRuleSet | None = None,
252
+ ) -> bool:
216
253
  """Return whether the declaration *node* must not be an unused-symbol finding.
217
254
 
255
+ *rules* are the configured suppression annotations (defaulting to the
256
+ ``suppression_annotations.json`` file).
257
+
218
258
  Author: Ron Webb
219
259
  Since: 1.5.0
220
260
  """
221
- return (
222
- _is_override(node, source_bytes, language)
223
- or _is_exported(node, source_bytes, language)
224
- or _is_suppressed(node, source_bytes, language)
261
+ if _is_override(node, source_bytes, language):
262
+ return True
263
+ return _is_annotation_exempt(
264
+ node,
265
+ source_bytes,
266
+ language,
267
+ rules if rules is not None else default_annotation_rules(),
225
268
  )
@@ -0,0 +1,18 @@
1
+ {
2
+ "annotations": [
3
+ {
4
+ "name": "SuppressWarnings",
5
+ "languages": ["Java", "Gosu"],
6
+ "parameters": [
7
+ {
8
+ "values": ["unused", "all"],
9
+ "match": "in-array"
10
+ }
11
+ ]
12
+ },
13
+ {
14
+ "name": "Export",
15
+ "languages": ["Gosu"]
16
+ }
17
+ ]
18
+ }
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "code-prune"
3
- version = "1.7.0"
3
+ version = "2.0.0"
4
4
  description = "Find unreachable, unused, and obsolete code before it becomes technical debt."
5
5
  authors = [
6
6
  {name = "Ron Webb"}
@@ -59,6 +59,7 @@ include = [
59
59
  "code_prune/config.ini",
60
60
  "code_prune/.codepruneignore",
61
61
  "code_prune/symbol_ignore",
62
+ "code_prune/suppression_annotations.json",
62
63
  "CHANGELOG.md"
63
64
  ]
64
65
 
File without changes
File without changes