-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathsuppression.rs
More file actions
708 lines (614 loc) · 20.4 KB
/
suppression.rs
File metadata and controls
708 lines (614 loc) · 20.4 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use ruff_db::{files::File, parsed::parsed_module, source::source_text};
use ruff_python_parser::TokenKind;
use ruff_python_trivia::Cursor;
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use smallvec::{smallvec, SmallVec};
use crate::lint::LintRegistry;
use crate::{lint::LintId, Db};
#[salsa::tracked(return_ref)]
pub(crate) fn suppressions(db: &dyn Db, file: File) -> Suppressions {
let parsed = parsed_module(db.upcast(), file);
let source = source_text(db.upcast(), file);
let mut builder = SuppressionsBuilder::new(&source, db.lint_registry());
let mut line_start = TextSize::default();
for token in parsed.tokens() {
if !token.kind().is_trivia() {
builder.set_seen_non_trivia_token();
}
match token.kind() {
TokenKind::Comment => {
let parser = SuppressionParser::new(&source, token.range());
for comment in parser {
builder.add_comment(comment, line_start);
}
}
TokenKind::Newline | TokenKind::NonLogicalNewline => {
line_start = token.end();
}
_ => {}
}
}
builder.finish()
}
/// The suppressions of a single file.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Suppressions {
/// Suppressions that apply to the entire file.
///
/// The suppressions are sorted by [`Suppression::comment_range`] and the [`Suppression::suppressed_range`]
/// spans the entire file.
///
/// For now, this is limited to `type: ignore` comments.
file: Vec<Suppression>,
/// Suppressions that apply to a specific line (or lines).
///
/// Comments with multiple codes create multiple [`Suppression`]s that all share the same [`Suppression::comment_range`].
///
/// The suppressions are sorted by [`Suppression::range`] (which implies [`Suppression::comment_range`]).
line: Vec<Suppression>,
}
impl Suppressions {
pub(crate) fn find_suppression(&self, range: TextRange, id: LintId) -> Option<&Suppression> {
self.file
.iter()
.chain(self.line_suppressions(range))
.find(|suppression| suppression.matches(id))
}
/// Returns the line-level suppressions that apply for `range`.
///
/// A suppression applies for the given range if it contains the range's
/// start or end offset. This means the suppression is on the same line
/// as the diagnostic's start or end.
fn line_suppressions(&self, range: TextRange) -> impl Iterator<Item = &Suppression> + '_ {
// First find the index of the suppression comment that ends right before the range
// starts. This allows us to skip suppressions that are not relevant for the range.
let end_offset = self
.line
.binary_search_by_key(&range.start(), |suppression| {
suppression.suppressed_range.end()
})
.unwrap_or_else(|index| index);
// From here, search the remaining suppression comments for one that
// contains the range's start or end offset. Stop the search
// as soon as the suppression's range and the range no longer overlap.
self.line[end_offset..]
.iter()
// Stop searching if the suppression starts after the range we're looking for.
.take_while(move |suppression| range.end() >= suppression.suppressed_range.start())
.filter(move |suppression| {
// Don't use intersect to avoid that suppressions on inner-expression
// ignore errors for outer expressions
suppression.suppressed_range.contains(range.start())
|| suppression.suppressed_range.contains(range.end())
})
}
}
/// A `type: ignore` or `knot: ignore` suppression.
///
/// Suppression comments that suppress multiple codes
/// create multiple suppressions: one for every code.
/// They all share the same `comment_range`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Suppression {
target: SuppressionTarget,
/// The range of this specific suppression.
/// This is the same as `comment_range` except for suppression comments that suppress multiple
/// codes. For those, the range is limited to the specific code.
range: TextRange,
/// The range of the suppression comment.
comment_range: TextRange,
/// The range for which this suppression applies.
/// Most of the time, this is the range of the comment's line.
/// However, there are few cases where the range gets expanded to
/// cover multiple lines:
/// * multiline strings: `expr + """multiline\nstring""" # type: ignore`
/// * line continuations: `expr \ + "test" # type: ignore`
suppressed_range: TextRange,
}
impl Suppression {
fn matches(&self, tested_id: LintId) -> bool {
match self.target {
SuppressionTarget::All => true,
SuppressionTarget::Lint(suppressed_id) => tested_id == suppressed_id,
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum SuppressionTarget {
/// Suppress all lints
All,
/// Suppress the lint with the given id
Lint(LintId),
}
struct SuppressionsBuilder<'a> {
lint_registry: &'a LintRegistry,
source: &'a str,
/// `type: ignore` comments at the top of the file before any non-trivia code apply to the entire file.
/// This boolean tracks if there has been any non trivia token.
seen_non_trivia_token: bool,
line: Vec<Suppression>,
file: Vec<Suppression>,
}
impl<'a> SuppressionsBuilder<'a> {
fn new(source: &'a str, lint_registry: &'a LintRegistry) -> Self {
Self {
source,
lint_registry,
seen_non_trivia_token: false,
line: Vec::new(),
file: Vec::new(),
}
}
fn set_seen_non_trivia_token(&mut self) {
self.seen_non_trivia_token = true;
}
fn finish(mut self) -> Suppressions {
self.line.shrink_to_fit();
self.file.shrink_to_fit();
Suppressions {
file: self.file,
line: self.line,
}
}
fn add_comment(&mut self, comment: SuppressionComment, line_start: TextSize) {
let (suppressions, suppressed_range) =
// `type: ignore` comments at the start of the file apply to the entire range.
// > A # type: ignore comment on a line by itself at the top of a file, before any docstrings,
// > imports, or other executable code, silences all errors in the file.
// > Blank lines and other comments, such as shebang lines and coding cookies,
// > may precede the # type: ignore comment.
// > https://typing.readthedocs.io/en/latest/spec/directives.html#type-ignore-comments
if comment.kind.is_type_ignore() && !self.seen_non_trivia_token {
(
&mut self.file,
TextRange::new(0.into(), self.source.text_len()),
)
} else {
(
&mut self.line,
TextRange::new(line_start, comment.range.end()),
)
};
match comment.codes {
// `type: ignore`
None => {
suppressions.push(Suppression {
target: SuppressionTarget::All,
comment_range: comment.range,
range: comment.range,
suppressed_range,
});
}
// `type: ignore[..]`
// The suppression applies to all lints if it is a `type: ignore`
// comment. `type: ignore` apply to all lints for better mypy compatibility.
Some(_) if comment.kind.is_type_ignore() => {
suppressions.push(Suppression {
target: SuppressionTarget::All,
comment_range: comment.range,
range: comment.range,
suppressed_range,
});
}
// `knot: ignore[a, b]`
Some(codes) => {
for code_range in &codes {
let code = &self.source[*code_range];
match self.lint_registry.get(code) {
Ok(lint) => {
let range = if codes.len() == 1 {
comment.range
} else {
*code_range
};
suppressions.push(Suppression {
target: SuppressionTarget::Lint(lint),
range,
comment_range: comment.range,
suppressed_range,
});
}
Err(error) => {
tracing::debug!("Invalid suppression: {error}");
// TODO(micha): Handle invalid lint codes
}
}
}
}
}
}
}
struct SuppressionParser<'src> {
cursor: Cursor<'src>,
range: TextRange,
}
impl<'src> SuppressionParser<'src> {
fn new(source: &'src str, range: TextRange) -> Self {
let cursor = Cursor::new(&source[range]);
Self { cursor, range }
}
fn parse_comment(&mut self) -> Option<SuppressionComment> {
let comment_start = self.offset();
self.cursor.start_token();
if !self.cursor.eat_char('#') {
return None;
}
self.eat_whitespace();
// type: ignore[code]
// ^^^^^^^^^^^^
let kind = self.eat_kind()?;
let has_trailing_whitespace = self.eat_whitespace();
// type: ignore[code1, code2]
// ^^^^^^
let codes = self.eat_codes();
if self.cursor.is_eof() || codes.is_some() || has_trailing_whitespace {
// Consume the comment until its end or until the next "sub-comment" starts.
self.cursor.eat_while(|c| c != '#');
Some(SuppressionComment {
kind,
codes,
range: TextRange::at(comment_start, self.cursor.token_len()),
})
} else {
None
}
}
fn eat_kind(&mut self) -> Option<SuppressionKind> {
let kind = if self.cursor.as_str().starts_with("type") {
SuppressionKind::TypeIgnore
} else if self.cursor.as_str().starts_with("knot") {
SuppressionKind::Knot
} else {
return None;
};
self.cursor.skip_bytes(kind.len_utf8());
self.eat_whitespace();
if !self.cursor.eat_char(':') {
return None;
}
self.eat_whitespace();
if !self.cursor.as_str().starts_with("ignore") {
return None;
}
self.cursor.skip_bytes("ignore".len());
Some(kind)
}
fn eat_codes(&mut self) -> Option<SmallVec<[TextRange; 2]>> {
if !self.cursor.eat_char('[') {
return None;
}
let mut codes: SmallVec<[TextRange; 2]> = smallvec![];
loop {
if self.cursor.is_eof() {
return None;
}
self.eat_whitespace();
// `knot: ignore[]` or `knot: ignore[a,]`
if self.cursor.eat_char(']') {
break Some(codes);
}
let code_start = self.offset();
if !self.eat_word() {
return None;
}
codes.push(TextRange::new(code_start, self.offset()));
self.eat_whitespace();
if !self.cursor.eat_char(',') {
self.eat_whitespace();
if self.cursor.eat_char(']') {
break Some(codes);
}
// `knot: ignore[a b]
return None;
}
}
}
fn eat_whitespace(&mut self) -> bool {
if self.cursor.eat_if(char::is_whitespace) {
self.cursor.eat_while(char::is_whitespace);
true
} else {
false
}
}
fn eat_word(&mut self) -> bool {
if self.cursor.eat_if(char::is_alphabetic) {
self.cursor
.eat_while(|c| c.is_alphanumeric() || matches!(c, '_' | '-'));
true
} else {
false
}
}
fn offset(&self) -> TextSize {
self.range.start() + self.range.len() - self.cursor.text_len()
}
}
impl Iterator for SuppressionParser<'_> {
type Item = SuppressionComment;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.cursor.is_eof() {
return None;
}
if let Some(suppression) = self.parse_comment() {
return Some(suppression);
}
self.cursor.eat_while(|c| c != '#');
}
}
}
/// A single parsed suppression comment.
#[derive(Clone, Debug, Eq, PartialEq)]
struct SuppressionComment {
/// The range of the suppression comment.
///
/// This can be a sub-range of the comment token if the comment token contains multiple `#` tokens:
/// ```py
/// # fmt: off # type: ignore
/// ^^^^^^^^^^^^^^
/// ```
range: TextRange,
kind: SuppressionKind,
/// The ranges of the codes in the optional `[...]`.
/// `None` for comments that don't specify any code.
///
/// ```py
/// # type: ignore[unresolved-reference, invalid-exception-caught]
/// ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
/// ```
codes: Option<SmallVec<[TextRange; 2]>>,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum SuppressionKind {
TypeIgnore,
Knot,
}
impl SuppressionKind {
const fn is_type_ignore(self) -> bool {
matches!(self, SuppressionKind::TypeIgnore)
}
fn len_utf8(self) -> usize {
match self {
SuppressionKind::TypeIgnore => "type".len(),
SuppressionKind::Knot => "knot".len(),
}
}
}
#[cfg(test)]
mod tests {
use crate::suppression::{SuppressionComment, SuppressionParser};
use insta::assert_debug_snapshot;
use ruff_text_size::{TextLen, TextRange};
use std::fmt;
use std::fmt::Formatter;
#[test]
fn type_ignore_no_codes() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore",
),
@r##"
[
SuppressionComment {
text: "# type: ignore",
kind: TypeIgnore,
codes: [],
},
]
"##
);
}
#[test]
fn type_ignore_explanation() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore I tried but couldn't figure out the proper type",
),
@r##"
[
SuppressionComment {
text: "# type: ignore I tried but couldn't figure out the proper type",
kind: TypeIgnore,
codes: [],
},
]
"##
);
}
#[test]
fn fmt_comment_before_type_ignore() {
assert_debug_snapshot!(
SuppressionComments::new(
"# fmt: off # type: ignore",
),
@r##"
[
SuppressionComment {
text: "# type: ignore",
kind: TypeIgnore,
codes: [],
},
]
"##
);
}
#[test]
fn type_ignore_before_fmt_off() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore # fmt: off",
),
@r##"
[
SuppressionComment {
text: "# type: ignore ",
kind: TypeIgnore,
codes: [],
},
]
"##
);
}
#[test]
fn multiple_type_ignore_comments() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore[a] # type: ignore[b]",
),
@r##"
[
SuppressionComment {
text: "# type: ignore[a] ",
kind: TypeIgnore,
codes: [
"a",
],
},
SuppressionComment {
text: "# type: ignore[b]",
kind: TypeIgnore,
codes: [
"b",
],
},
]
"##
);
}
#[test]
fn invalid_type_ignore_valid_type_ignore() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore[a # type: ignore[b]",
),
@r##"
[
SuppressionComment {
text: "# type: ignore[b]",
kind: TypeIgnore,
codes: [
"b",
],
},
]
"##
);
}
#[test]
fn valid_type_ignore_invalid_type_ignore() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore[a] # type: ignoreeee",
),
@r##"
[
SuppressionComment {
text: "# type: ignore[a] ",
kind: TypeIgnore,
codes: [
"a",
],
},
]
"##
);
}
#[test]
fn type_ignore_multiple_codes() {
assert_debug_snapshot!(
SuppressionComments::new(
"# type: ignore[invalid-exception-raised, invalid-exception-caught]",
),
@r##"
[
SuppressionComment {
text: "# type: ignore[invalid-exception-raised, invalid-exception-caught]",
kind: TypeIgnore,
codes: [
"invalid-exception-raised",
"invalid-exception-caught",
],
},
]
"##
);
}
#[test]
fn type_ignore_single_code() {
assert_debug_snapshot!(
SuppressionComments::new("# type: ignore[invalid-exception-raised]",),
@r##"
[
SuppressionComment {
text: "# type: ignore[invalid-exception-raised]",
kind: TypeIgnore,
codes: [
"invalid-exception-raised",
],
},
]
"##
);
}
struct SuppressionComments<'a> {
source: &'a str,
}
impl<'a> SuppressionComments<'a> {
fn new(source: &'a str) -> Self {
Self { source }
}
}
impl fmt::Debug for SuppressionComments<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut list = f.debug_list();
for comment in SuppressionParser::new(
self.source,
TextRange::new(0.into(), self.source.text_len()),
) {
list.entry(&comment.debug(self.source));
}
list.finish()
}
}
impl SuppressionComment {
fn debug<'a>(&'a self, source: &'a str) -> DebugSuppressionComment<'a> {
DebugSuppressionComment {
source,
comment: self,
}
}
}
struct DebugSuppressionComment<'a> {
source: &'a str,
comment: &'a SuppressionComment,
}
impl fmt::Debug for DebugSuppressionComment<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
struct DebugCodes<'a> {
source: &'a str,
codes: &'a [TextRange],
}
impl fmt::Debug for DebugCodes<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut f = f.debug_list();
for code in self.codes {
f.entry(&&self.source[*code]);
}
f.finish()
}
}
f.debug_struct("SuppressionComment")
.field("text", &&self.source[self.comment.range])
.field("kind", &self.comment.kind)
.field(
"codes",
&DebugCodes {
source: self.source,
codes: self.comment.codes.as_deref().unwrap_or_default(),
},
)
.finish()
}
}
}