-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsuppressions.py
More file actions
270 lines (234 loc) · 7.75 KB
/
suppressions.py
File metadata and controls
270 lines (234 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2026 Den Rozhnovskiy
from __future__ import annotations
import io
import re
import tokenize
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final, Literal
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
DEAD_CODE_RULE_ID: Final[str] = "dead-code"
SUPPORTED_RULE_IDS: Final[frozenset[str]] = frozenset(
{
DEAD_CODE_RULE_ID,
"clone-cohort-drift",
"clone-guard-exit-divergence",
}
)
DirectiveBindingKind = Literal["inline", "leading"]
DeclarationKind = Literal["function", "method", "class"]
SuppressionSource = Literal["inline_codeclone"]
INLINE_CODECLONE_SUPPRESSION_SOURCE: Final[SuppressionSource] = "inline_codeclone"
SuppressionTargetKey = tuple[str, str, int, int, DeclarationKind]
_SUPPRESSION_DIRECTIVE_PATTERN: Final[re.Pattern[str]] = re.compile(
r"^\s*#\s*codeclone\s*:\s*ignore\s*\[(?P<rules>[^\]]+)\]\s*$"
)
_RULE_ID_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9][a-z0-9-]*$")
__all__ = [
"DEAD_CODE_RULE_ID",
"INLINE_CODECLONE_SUPPRESSION_SOURCE",
"SUPPORTED_RULE_IDS",
"DeclarationKind",
"DeclarationTarget",
"DirectiveBindingKind",
"SuppressionBinding",
"SuppressionDirective",
"SuppressionTargetKey",
"bind_suppressions_to_declarations",
"build_suppression_index",
"extract_suppression_directives",
"suppression_target_key",
]
@dataclass(frozen=True, slots=True)
class SuppressionDirective:
line: int
binding: DirectiveBindingKind
rules: tuple[str, ...]
@dataclass(frozen=True, slots=True)
class DeclarationTarget:
filepath: str
qualname: str
start_line: int
end_line: int
kind: DeclarationKind
declaration_end_line: int | None = None
@dataclass(frozen=True, slots=True)
class SuppressionBinding:
filepath: str
qualname: str
start_line: int
end_line: int
kind: DeclarationKind
rules: tuple[str, ...]
source: SuppressionSource = "inline_codeclone"
def _merge_rules(
base: tuple[str, ...],
incoming: Sequence[str],
) -> tuple[str, ...]:
if not incoming:
return base
seen = set(base)
merged = list(base)
for rule_id in incoming:
if rule_id in seen:
continue
seen.add(rule_id)
merged.append(rule_id)
return tuple(merged)
def _parse_rule_ids(
raw: str,
*,
supported_rules: frozenset[str],
) -> tuple[str, ...]:
parsed: tuple[str, ...] = ()
for token in raw.split(","):
rule_id = token.strip()
if (
rule_id
and _RULE_ID_PATTERN.fullmatch(rule_id) is not None
and rule_id in supported_rules
):
parsed = _merge_rules(parsed, (rule_id,))
return parsed
def _parse_comment_rules(
comment: str,
*,
supported_rules: frozenset[str],
) -> tuple[str, ...]:
match = _SUPPRESSION_DIRECTIVE_PATTERN.fullmatch(comment)
if match is None:
return ()
return _parse_rule_ids(match.group("rules"), supported_rules=supported_rules)
def extract_suppression_directives(
source: str,
*,
supported_rules: frozenset[str] = SUPPORTED_RULE_IDS,
) -> tuple[SuppressionDirective, ...]:
# Fast-path: skip tokenization when no directive marker exists.
# Every valid directive contains the literal "codeclone:" — if absent,
# no comment can match _SUPPRESSION_DIRECTIVE_PATTERN.
if "codeclone:" not in source:
return ()
lines = source.splitlines()
directives: list[SuppressionDirective] = []
try:
tokens = tokenize.generate_tokens(io.StringIO(source).readline)
for token in tokens:
if token.type == tokenize.COMMENT:
parsed_rules = _parse_comment_rules(
token.string,
supported_rules=supported_rules,
)
if parsed_rules:
line_no = token.start[0]
col_no = token.start[1]
line_text = lines[line_no - 1] if 0 < line_no <= len(lines) else ""
binding: DirectiveBindingKind = (
"inline" if line_text[:col_no].strip() else "leading"
)
directives.append(
SuppressionDirective(
line=line_no,
binding=binding,
rules=parsed_rules,
)
)
except tokenize.TokenError:
return ()
return tuple(
sorted(
directives,
key=lambda item: (item.line, item.binding, item.rules),
)
)
def _declaration_inline_lines(target: DeclarationTarget) -> tuple[int, ...]:
end_line = target.declaration_end_line or target.start_line
if end_line <= 0 or end_line == target.start_line:
return (target.start_line,)
return (target.start_line, end_line)
def _bound_inline_rules(
*,
target: DeclarationTarget,
inline_rules_by_line: Mapping[int, tuple[str, ...]],
) -> tuple[str, ...]:
rules: tuple[str, ...] = ()
for line_no in _declaration_inline_lines(target):
rules = _merge_rules(rules, inline_rules_by_line.get(line_no, ()))
return rules
def bind_suppressions_to_declarations(
*,
directives: Sequence[SuppressionDirective],
declarations: Sequence[DeclarationTarget],
) -> tuple[SuppressionBinding, ...]:
leading_rules_by_line: dict[int, tuple[str, ...]] = {}
inline_rules_by_line: dict[int, tuple[str, ...]] = {}
for directive in directives:
target_map = (
inline_rules_by_line
if directive.binding == "inline"
else leading_rules_by_line
)
existing = target_map.get(directive.line, ())
target_map[directive.line] = _merge_rules(existing, directive.rules)
bindings: list[SuppressionBinding] = []
for target in declarations:
bound_rules = _merge_rules(
leading_rules_by_line.get(target.start_line - 1, ()),
_bound_inline_rules(
target=target,
inline_rules_by_line=inline_rules_by_line,
),
)
if not bound_rules:
continue
bindings.append(
SuppressionBinding(
filepath=target.filepath,
qualname=target.qualname,
start_line=target.start_line,
end_line=target.end_line,
kind=target.kind,
rules=bound_rules,
)
)
return tuple(
sorted(
bindings,
key=lambda item: (
item.filepath,
item.start_line,
item.end_line,
item.qualname,
item.kind,
item.rules,
),
)
)
def suppression_target_key(
*,
filepath: str,
qualname: str,
start_line: int,
end_line: int,
kind: DeclarationKind,
) -> SuppressionTargetKey:
return (filepath, qualname, start_line, end_line, kind)
def build_suppression_index(
bindings: Sequence[SuppressionBinding],
) -> Mapping[SuppressionTargetKey, tuple[str, ...]]:
index: dict[SuppressionTargetKey, tuple[str, ...]] = {}
for binding in bindings:
key = suppression_target_key(
filepath=binding.filepath,
qualname=binding.qualname,
start_line=binding.start_line,
end_line=binding.end_line,
kind=binding.kind,
)
existing = index.get(key, ())
index[key] = _merge_rules(existing, binding.rules)
return index