forked from facebook/pyrefly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathignore.rs
More file actions
925 lines (850 loc) · 31.9 KB
/
Copy pathignore.rs
File metadata and controls
925 lines (850 loc) · 31.9 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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Given a file, record which ignore statements are in it.
//!
//! Given `# type: ignore` we should ignore errors on that line.
//! Originally specified in <https://peps.python.org/pep-0484/>.
//!
//! You can also use the name of the linter, e.g. `# pyright: ignore`,
//! `# pyrefly: ignore`.
//!
//! You can specify a specific error code, e.g. `# type: ignore[invalid-type]`.
//! Note that Pyright will only honor such codes after `# pyright: ignore[code]`.
//!
//! You can also use `# mypy: ignore-errors`, `# pyrefly: ignore-errors`
//! or `# type: ignore` at the beginning of a file to suppress all errors.
//! `# pyrefly: ignore-errors[invalid-type]` suppresses only the listed error
//! codes across the file rather than all errors.
//!
//! For Pyre compatibility we also allow `# pyre-ignore` and `# pyre-fixme`
//! as equivalents to `pyre: ignore`, and `# pyre-ignore-all-errors` as
//! an equivalent to `type: ignore` on its own line.
//!
//! We are permissive with whitespace, allowing `#type:ignore[code]` and
//! `# type: ignore [ code ]`, but do not allow a space before the colon.
use clap::ValueEnum;
use dupe::Dupe;
use enum_iterator::Sequence;
use pyrefly_util::lined_buffer::LineNumber;
use serde::Deserialize;
use serde::Serialize;
use starlark_map::small_map::SmallMap;
use starlark_map::small_set::SmallSet;
use starlark_map::smallset;
/// Finds the byte offset of the first '#' character that starts a comment, tracking
/// whether we're inside a multi-line triple-quoted string.
///
/// All interesting characters (`#`, `'`, `"`, `\`) are ASCII, so we operate
/// on bytes directly — UTF-8 guarantees these never appear inside multi-byte
/// sequences.
///
/// `in_triple_quote` should be `Some('"')` or `Some('\'')` if the line begins
/// inside an open triple-quoted string from a previous line, or `None` otherwise.
///
/// Returns `(comment_start, new_triple_quote_state)`.
pub fn find_comment_start(
line: &str,
in_triple_quote: Option<char>,
) -> (Option<usize>, Option<char>) {
// Fast path: when not inside a triple-quoted string, scan for the first
// byte that requires string-aware parsing (#, ', ", \). If the first such
// byte is '#', it is the comment start — no further analysis is needed.
// This avoids the per-byte state machine for the common case of plain code
// lines like `x = foo(bar) # comment`.
if in_triple_quote.is_none() {
let bytes = line.as_bytes();
match bytes
.iter()
.position(|&b| b == b'#' || b == b'\'' || b == b'"' || b == b'\\')
{
None => return (None, None),
Some(pos) if bytes[pos] == b'#' => return (Some(pos), None),
_ => {} // quote or backslash found — need full parser
}
}
find_comment_start_slow(line, in_triple_quote)
}
/// Full string-aware comment finder. Handles triple-quoted strings, single-quoted
/// strings, and escape sequences.
fn find_comment_start_slow(
line: &str,
in_triple_quote: Option<char>,
) -> (Option<usize>, Option<char>) {
let mut bytes = line.bytes().enumerate().peekable();
let mut triple_quote: Option<u8> = in_triple_quote.map(|c| c as u8);
let mut single_quote: Option<u8> = None;
while let Some((idx, b)) = bytes.next() {
if let Some(q) = triple_quote {
// Inside triple-quoted string.
if b == b'\\' {
bytes.next(); // Skip escaped character.
} else if b == q
&& bytes.next_if(|&(_, next)| next == q).is_some()
&& bytes.next_if(|&(_, next)| next == q).is_some()
{
triple_quote = None;
}
continue;
}
if let Some(q) = single_quote {
// Inside regular string.
if b == b'\\' {
bytes.next(); // Skip escaped character.
} else if b == q {
single_quote = None;
}
continue;
}
// Normal code.
match b {
b'"' | b'\'' => {
if bytes.next_if(|&(_, next)| next == b).is_some() {
if bytes.next_if(|&(_, next)| next == b).is_some() {
triple_quote = Some(b);
}
// else: empty string ("" or ''), both quotes already consumed.
} else {
single_quote = Some(b);
}
}
b'#' => return (Some(idx), None),
_ => {}
}
}
(None, triple_quote.map(|b| b as char))
}
/// Finds the byte offset of the first '#' character that starts a comment.
/// Returns None if no comment is found or if all '#' are inside strings.
/// Handles escape sequences, single/double quotes, and triple-quoted strings.
///
/// This is string-aware parsing that avoids treating '#' inside strings as comments.
/// For example: `x = "hello # world" # real comment` correctly identifies the second '#'.
pub fn find_comment_start_in_line(line: &str) -> Option<usize> {
find_comment_start(line, None).0
}
/// The name of the tool that is being suppressed.
/// Note that the variant names and docstrings are displayed in `pyrefly check --help`.
#[derive(PartialEq, Debug, Clone, Hash, Eq, Dupe, Copy, Sequence)]
#[derive(Deserialize, Serialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum Tool {
/// Enables `# type: ignore`
Type,
/// Enables `# pyrefly: ignore` and `# pyrefly: ignore-errors`
Pyrefly,
/// Enables `# pyright: ignore`
Pyright,
/// Enables `# mypy: ignore-errors`
Mypy,
/// Enables `# ty: ignore`
Ty,
/// Enables `# pyre: ignore`, `# pyre-ignore`, `# pyre-fixme`, and `# pyre-ignore-all-errors`
Pyre,
/// Enables `# zuban: ignore`
Zuban,
}
impl Tool {
/// The maximum length of any tool.
const MAX_LEN: usize = 7;
fn from_comment(x: &str) -> Option<Self> {
match x {
"type" => Some(Tool::Type),
"pyrefly" => Some(Tool::Pyrefly),
"pyre" => Some(Tool::Pyre),
"pyright" => Some(Tool::Pyright),
"mypy" => Some(Tool::Mypy),
"ty" => Some(Tool::Ty),
"zuban" => Some(Tool::Zuban),
_ => None,
}
}
pub fn default_enabled() -> SmallSet<Self> {
smallset! { Self::Type, Self::Pyrefly }
}
pub fn all() -> SmallSet<Self> {
enum_iterator::all::<Self>().collect()
}
}
/// A simple lexer that deals with the rules around whitespace.
/// As it consumes the string, it will move forward.
struct Lexer<'a>(&'a str);
impl<'a> Lexer<'a> {
/// The string starts with the given string, return `true` if so.
fn starts_with(&mut self, x: &str) -> bool {
match self.0.strip_prefix(x) {
Some(x) => {
self.0 = x;
true
}
None => false,
}
}
/// The string starts with `tool:`, return the tool if it does.
fn starts_with_tool(&mut self) -> Option<Tool> {
let p = self
.0
.as_bytes()
.iter()
.take(Tool::MAX_LEN + 1)
.position(|&c| c == b':')?;
let tool = Tool::from_comment(&self.0[..p])?;
self.0 = &self.0[p + 1..];
Some(tool)
}
/// Trim whitespace from the start of the string.
/// Return `true` if the string was changed.
fn trim_start(&mut self) -> bool {
let before = self.0;
self.0 = self.0.trim_start();
self.0.len() != before.len()
}
/// Return `true` if the string is empty or only whitespace.
fn blank(&mut self) -> bool {
self.0.trim_start().is_empty()
}
/// Return `true` if the string is at the start of a word boundary.
/// That means the next char is not something that continues an identifier.
fn word_boundary(&mut self) -> bool {
self.0
.chars()
.next()
.is_none_or(|c| !c.is_alphanumeric() && c != '-' && c != '_')
}
/// Finish and return the rest of the string.
fn rest(self) -> &'a str {
self.0
}
}
#[derive(PartialEq, Debug, Clone, Hash, Eq)]
pub struct Suppression {
tool: Tool,
/// The permissible error kinds, use empty Vec to mean any are allowed
kind: Vec<String>,
/// The line number where the suppression comment is located.
/// This may differ from the line the suppression applies to
/// (e.g., when the comment is on the line above).
comment_line: LineNumber,
/// Byte offset within `comment_line` of the `#` that starts the comment.
comment_offset: usize,
}
impl Suppression {
/// A blanket suppression for `tool` that matches every error code.
fn blanket(tool: Tool, comment_line: LineNumber, comment_offset: usize) -> Self {
Self {
tool,
kind: Vec::new(),
comment_line,
comment_offset,
}
}
/// Returns the line number where the suppression comment is located.
pub fn comment_line(&self) -> LineNumber {
self.comment_line
}
/// Returns the byte offset of the comment's `#` within `comment_line`.
pub fn comment_offset(&self) -> usize {
self.comment_offset
}
/// Returns the error codes that this suppression applies to.
/// An empty slice means the suppression applies to all error codes.
pub fn error_codes(&self) -> &[String] {
&self.kind
}
/// Returns the tool that this suppression is for.
pub fn tool(&self) -> Tool {
self.tool
}
}
/// Record the position of lines affected by `# type: ignore[valid-type]` suppressions.
/// For now we don't record the content of the ignore, but we could.
#[derive(Debug, Clone, Default)]
pub struct Ignore {
/// The line number here represents the line that the suppression applies to,
/// not the line of the suppression comment.
ignores: SmallMap<LineNumber, Vec<Suppression>>,
}
impl Ignore {
pub fn new(code: &str) -> Self {
Self {
ignores: Self::parse_ignores(code),
}
}
fn parse_ignores(code: &str) -> SmallMap<LineNumber, Vec<Suppression>> {
let mut ignores: SmallMap<LineNumber, Vec<Suppression>> = SmallMap::new();
// If we see a comment on a non-code line, apply it to the next non-comment line.
let mut pending = Vec::new();
let mut line = LineNumber::default();
let mut in_triple_quote = None;
for (idx, line_str) in code.lines().enumerate() {
let (comment_start, new_state) = find_comment_start(line_str, in_triple_quote);
in_triple_quote = new_state;
let is_comment_only_line = comment_start
.is_some_and(|comment_start| line_str[..comment_start].trim_start().is_empty());
line = LineNumber::from_zero_indexed(idx as u32);
if !pending.is_empty() && (line_str.is_empty() || !is_comment_only_line) {
ignores.entry(line).or_default().append(&mut pending);
}
let Some(comment_start) = comment_start else {
continue;
};
// We know `#` is at `comment_start`, so the first split is an empty string
for x in line_str[comment_start..].split('#').skip(1) {
if let Some(supp) = Self::parse_ignore_comment(x, line, comment_start) {
if is_comment_only_line {
pending.push(supp);
} else {
ignores.entry(line).or_default().push(supp);
}
}
}
}
if !pending.is_empty() {
ignores
.entry(line.increment())
.or_default()
.append(&mut pending);
}
ignores
}
/// Given the content of a comment, parse it as a suppression.
/// `comment_line` and `comment_offset` locate the `#` starting the comment.
fn parse_ignore_comment(
l: &str,
comment_line: LineNumber,
comment_offset: usize,
) -> Option<Suppression> {
let mut lex = Lexer(l);
lex.trim_start();
let mut tool = None;
if let Some(t) = lex.starts_with_tool() {
lex.trim_start();
if lex.starts_with("ignore") {
tool = Some(t);
}
} else if lex.starts_with("pyre-ignore") || lex.starts_with("pyre-fixme") {
tool = Some(Tool::Pyre);
}
let tool = tool?;
// We have seen `type: ignore` or `pyre-ignore`. Now look for `[code]` or the end.
let gap = lex.trim_start();
if lex.starts_with("[") {
let rest = lex.rest();
let inside = rest.split_once(']').map_or(rest, |x| x.0);
return Some(Suppression {
tool,
kind: parse_error_codes(inside),
comment_line,
comment_offset,
});
} else if gap || lex.word_boundary() {
return Some(Suppression::blanket(tool, comment_line, comment_offset));
}
None
}
pub fn is_ignored(
&self,
start_line: LineNumber,
kind: &str,
enabled_ignores: &SmallSet<Tool>,
) -> bool {
if let Some(suppressions) = self.ignores.get(&start_line)
&& suppressions.iter().any(|supp| {
enabled_ignores.contains(&supp.tool)
&& match supp.tool {
// We only check the subkind if they do `# pyrefly: ignore`
Tool::Pyrefly => {
supp.kind.is_empty() || supp.kind.iter().any(|x| x == kind)
}
_ => true,
}
})
{
return true;
}
false
}
/// Similar to `is_ignored`, but it only returns true if the error is ignored
/// by a suppression that targets a specific line.
pub fn is_ignored_by_suppression_line(
&self,
suppression_line: LineNumber,
start_line: LineNumber,
end_line: LineNumber,
kind: &str,
enabled_ignores: &SmallSet<Tool>,
) -> bool {
// If the error does not overlap the range, skip the more expensive check
if start_line > suppression_line || end_line < suppression_line {
return false;
}
let Some(suppressions) = self.ignores.get(&suppression_line) else {
return false;
};
if suppressions.iter().any(|supp| {
enabled_ignores.contains(&supp.tool)
&& match supp.tool {
// We only check the subkind if they do `# pyrefly: ignore`
Tool::Pyrefly => supp.kind.is_empty() || supp.kind.iter().any(|x| x == kind),
_ => true,
}
}) {
return true;
}
false
}
// gets either just pyrefly ignores or pyrefly and type: ignore comments
pub fn get_pyrefly_ignores(&self, all: bool) -> SmallSet<LineNumber> {
let ignore_iter = self.ignores.iter();
let filtered_ignores: Box<dyn Iterator<Item = (&LineNumber, &Vec<Suppression>)>> = if all {
Box::new(ignore_iter.filter(|ignore| {
ignore
.1
.iter()
.any(|s| s.tool == Tool::Pyrefly || s.tool == Tool::Type)
}))
} else {
Box::new(ignore_iter.filter(|ignore| ignore.1.iter().any(|s| s.tool == Tool::Pyrefly)))
};
filtered_ignores.map(|(line, _)| *line).collect()
}
/// Returns an iterator over all suppressions in the file.
/// Each item is a (line_number, suppressions) pair where line_number is where the suppression applies.
pub fn iter(&self) -> impl Iterator<Item = (&LineNumber, &Vec<Suppression>)> {
self.ignores.iter()
}
/// Gets the suppressions for a specific line.
pub fn get(&self, line: &LineNumber) -> Option<&Vec<Suppression>> {
self.ignores.get(line)
}
/// Returns true if there are no suppressions.
pub fn is_empty(&self) -> bool {
self.ignores.is_empty()
}
}
/// Returns true if `line` falls inside one of the sorted multiline string ranges.
fn is_in_multiline_string(
multiline_string_ranges: &[(LineNumber, LineNumber)],
line: LineNumber,
) -> bool {
let idx = multiline_string_ranges.partition_point(|(start, _)| *start <= line);
idx > 0 && {
let (start, end) = multiline_string_ranges[idx - 1];
line >= start && line <= end
}
}
/// Parse top-level `ignore-errors` / `ignore-all-errors` / `type: ignore` directives.
///
/// Scans the beginning of the file for comment-only lines (including blank lines
/// and lines inside multiline strings like docstrings). Returns the file-level
/// suppressions found; Pyrefly entries may carry specific error codes
/// (`# pyrefly: ignore-errors[code]`), while other tools are blanket-only.
///
/// After a docstring, only `ignore-errors` directives are recognized — bare
/// `# type: ignore` is not, since it could plausibly be meant as a per-line
/// suppression for code that follows.
pub fn parse_ignore_all(
code: &str,
multiline_string_ranges: &[(LineNumber, LineNumber)],
) -> Vec<Suppression> {
let mut res = Vec::new();
let mut prev_ignore = None;
let mut seen_docstring = false;
for (idx, raw_line) in code.lines().enumerate() {
let line = LineNumber::from_zero_indexed(idx as u32);
let trimmed = raw_line.trim();
// Lines inside a multiline string (e.g. a module docstring) are not
// code — skip them but record that we've passed through a docstring.
if is_in_multiline_string(multiline_string_ranges, line) {
seen_docstring = true;
continue;
}
// Lines that open/close a triple-quoted string are also part of the
// preamble — skip them.
if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
seen_docstring = true;
continue;
}
// Stop at the first non-empty, non-comment line (i.e. actual code).
// A pending `# type: ignore` followed directly by code is a per-line
// suppression, not an ignore-all directive, so we discard it.
if !trimmed.is_empty() && !trimmed.starts_with('#') {
break;
}
if let Some((tool, prev_line, prev_offset)) = prev_ignore {
// The previous `# type: ignore` was followed by another comment or
// blank line, so it is a whole-file suppression.
res.push(Suppression::blanket(tool, prev_line, prev_offset));
prev_ignore = None;
}
let mut lex = Lexer(trimmed);
if !lex.starts_with("#") {
continue;
}
// `trimmed` starts with `#`, so its offset is the line's leading whitespace.
let comment_offset = raw_line.len() - raw_line.trim_start().len();
lex.trim_start();
if lex.starts_with("pyre-ignore-all-errors") {
res.push(Suppression::blanket(Tool::Pyre, line, comment_offset));
} else if let Some(tool) = lex.starts_with_tool() {
lex.trim_start();
if lex.starts_with("ignore-errors") {
lex.trim_start();
// Parse an optional `[code, ...]` list, sharing `parse_error_codes`
// with the line-level parser. A file-level directive must close its
// bracket and have nothing after it, so malformed lines are rejected.
let kind = if lex.starts_with("[") {
lex.0.split_once(']').and_then(|(inside, after)| {
// Drop empty entries so `[]`/trailing commas act as a blanket
// ignore rather than a directive that matches nothing.
Lexer(after).blank().then(|| {
parse_error_codes(inside)
.into_iter()
.filter(|code| !code.is_empty())
.collect()
})
})
} else if lex.blank() {
Some(Vec::new())
} else {
None
};
// Only Pyrefly honors specific codes; other tools are blanket-only.
if let Some(kind) = kind
&& (tool == Tool::Pyrefly || kind.is_empty())
{
res.push(Suppression {
tool,
kind,
comment_line: line,
comment_offset,
});
}
} else if !seen_docstring && lex.starts_with("ignore") && lex.blank() {
// After a docstring, bare `# type: ignore` is not recognized
// as an ignore-all directive.
prev_ignore = Some((tool, line, comment_offset));
}
}
}
res
}
/// Split the comma-separated error codes inside a `[...]` suppression into trimmed names.
fn parse_error_codes(inside: &str) -> Vec<String> {
inside.split(',').map(|x| x.trim().to_owned()).collect()
}
#[cfg(test)]
mod tests {
use pyrefly_util::prelude::SliceExt;
use super::*;
#[test]
fn test_parse_ignores() {
fn f(x: &str, expect: &[(Tool, u32)]) {
assert_eq!(
&Ignore::parse_ignores(x)
.into_iter()
.flat_map(|(line, xs)| xs.map(|x| (x.tool, line.get())))
.collect::<Vec<_>>(),
expect,
"{x:?}"
);
}
f("stuff # type: ignore # and then stuff", &[(Tool::Type, 1)]);
f("more # stuff # type: ignore", &[(Tool::Type, 1)]);
f(" pyrefly: ignore", &[]);
f("normal line", &[]);
f(
"code # pyright: ignore\n# pyre-fixme\nmore code",
&[(Tool::Pyright, 1), (Tool::Pyre, 3)],
);
f(
"# type: ignore\n# pyright: ignore\n# bad\n\ncode",
&[(Tool::Type, 4), (Tool::Pyright, 4)],
);
// Ignore `# pyrefly: ignore` inside a string but not before/after
f("x = 1 + '# pyrefly: ignore'", &[]);
f("x = '' # pyrefly: ignore", &[(Tool::Pyrefly, 1)]);
f("x = '''# pyrefly: ignore'''", &[]);
f(
r#"
x = """
x = 1 # pyrefly: ignore
"""
"#,
&[],
);
f(
r#"
import textwrap
textwrap.dedent("""\
x = 1 # pyrefly: ignore
""")
"#,
&[],
);
f(
r#"
x = """ # pyrefly: ignore
"""
"#,
&[],
);
f(
r#"
x = """
# pyrefly: ignore"""
"#,
&[],
);
f(
r#"
x = """
""" # pyrefly: ignore
"#,
&[(Tool::Pyrefly, 3)],
);
f("x = '''''' # pyrefly: ignore", &[(Tool::Pyrefly, 1)]);
}
#[test]
fn test_suppression_comment_offset() {
fn f(x: &str, expect: &[(u32, usize)]) {
assert_eq!(
&Ignore::parse_ignores(x)
.into_iter()
.flat_map(|(_, xs)| xs.map(|x| (x.comment_line.get(), x.comment_offset)))
.collect::<Vec<_>>(),
expect,
"{x:?}"
);
}
f("x = 1 # type: ignore", &[(1, 7)]);
// Not the `#` inside the string literal
f(r##"x: str = "#hash" # type: ignore"##, &[(1, 18)]);
// Line starts inside a triple-quoted string that closes mid-line
f("x = \"\"\"\n#fake\"\"\" # type: ignore", &[(2, 9)]);
// A comment above code keeps its own line and offset
f(" # type: ignore\nx = 1", &[(1, 2)]);
}
#[test]
fn test_parse_ignore_comment() {
fn f(x: &str, tool: Option<Tool>, kind: &[&str]) {
let dummy_line = LineNumber::default();
assert_eq!(
Ignore::parse_ignore_comment(x, dummy_line, 0),
tool.map(|tool| Suppression {
tool,
kind: kind.map(|x| (*x).to_owned()),
comment_line: dummy_line,
comment_offset: 0,
}),
"{x:?}"
);
}
f("ignore: pyrefly", None, &[]);
f("pyrefly: ignore", Some(Tool::Pyrefly), &[]);
f(
"pyrefly: ignore[bad-return]",
Some(Tool::Pyrefly),
&["bad-return"],
);
f("pyrefly: ignore[]", Some(Tool::Pyrefly), &[""]);
f("pyrefly: ignore[bad-]", Some(Tool::Pyrefly), &["bad-"]);
// Check spacing
f(" type: ignore ", Some(Tool::Type), &[]);
f("type:ignore", Some(Tool::Type), &[]);
f("type :ignore", None, &[]);
// Check extras
// Mypy rejects that, Pyright accepts it
f("type: ignore because it is wrong", Some(Tool::Type), &[]);
f("type: ignore_none", None, &[]);
f("type: ignore1", None, &[]);
f("type: ignore?", Some(Tool::Type), &[]);
f("pyright: ignore", Some(Tool::Pyright), &[]);
f(
"pyright: ignore[something]",
Some(Tool::Pyright),
&["something"],
);
f("pyre-ignore", Some(Tool::Pyre), &[]);
f("pyre-ignore[7]", Some(Tool::Pyre), &["7"]);
f("pyre-fixme[7]", Some(Tool::Pyre), &["7"]);
f(
"pyre-fixme[61]: `x` may not be initialized here.",
Some(Tool::Pyre),
&["61"],
);
f("pyre-fixme: core type error", Some(Tool::Pyre), &[]);
f("zuban: ignore", Some(Tool::Zuban), &[]);
f(
"zuban: ignore[something]",
Some(Tool::Zuban),
&["something"],
);
// For a malformed comment, at least do something with it (works well incrementally)
f("type: ignore[hello", Some(Tool::Type), &["hello"]);
}
#[test]
fn test_find_comment_start_in_line() {
// Test basic comment finding
assert_eq!(find_comment_start_in_line("x = 1 # comment"), Some(7));
assert_eq!(find_comment_start_in_line("no comment here"), None);
// Test string-aware parsing
assert_eq!(
find_comment_start_in_line(r#"x = "hello # world" # real"#),
Some(21)
);
assert_eq!(
find_comment_start_in_line(r#"x = 'hello # world' # real"#),
Some(21)
);
// Test escaped quotes
assert_eq!(
find_comment_start_in_line(r#"x = "she said \"hi\" # not" # real"#),
Some(28)
);
// Test multiple hashes
assert_eq!(find_comment_start_in_line("# first # second"), Some(0));
}
#[test]
fn test_parse_ignore_all() {
fn f(x: &str, ignores: &[(Tool, u32, &[&str])]) {
assert_eq!(
parse_ignore_all(x, &[]),
ignores
.iter()
.map(|x| Suppression {
tool: x.0,
kind: x.2.iter().map(|x| (*x).to_owned()).collect(),
comment_line: LineNumber::new(x.1).unwrap(),
comment_offset: 0,
})
.collect::<Vec<_>>(),
"{x:?}"
);
}
f(
"# pyrefly: ignore-errors\nx = 5",
&[(Tool::Pyrefly, 1, &[])],
);
f(
"# pyrefly: ignore-errors[bad-assignment]\nx = 5",
&[(Tool::Pyrefly, 1, &["bad-assignment"])],
);
f(
"# pyrefly: ignore-errors [ bad-assignment, bad-return ]\nx = 5",
&[(Tool::Pyrefly, 1, &["bad-assignment", "bad-return"])],
);
// Empty brackets and trailing commas drop empty entries, acting as a blanket ignore.
f(
"# pyrefly: ignore-errors[]\nx = 5",
&[(Tool::Pyrefly, 1, &[])],
);
f(
"# pyrefly: ignore-errors[bad-assignment,]\nx = 5",
&[(Tool::Pyrefly, 1, &["bad-assignment"])],
);
// A missing closing bracket is malformed and rejected, not silently accepted.
f("# pyrefly: ignore-errors[bad-assignment\nx = 5", &[]);
f(
"# comment\n# pyrefly: ignore-errors\nx = 5",
&[(Tool::Pyrefly, 2, &[])],
);
f(
"#comment\n # indent\n# pyrefly: ignore-errors\nx = 5",
&[(Tool::Pyrefly, 3, &[])],
);
f("x = 5\n# pyrefly: ignore-errors", &[]);
// Directives are only recognized in the preamble; once real code (including an
// import) appears the scan stops, so a later typed directive is inert — whether
// it trails code, trails an import, or is sandwiched between code lines.
f("x = 5\n# pyrefly: ignore-errors[bad-assignment]", &[]);
f(
"import os\n# pyrefly: ignore-errors[bad-assignment]\nx = 5",
&[],
);
f(
"x = 5\n# pyrefly: ignore-errors[bad-assignment]\ny = 6",
&[],
);
f("# type: ignore\n\nx = 5", &[(Tool::Type, 1, &[])]);
f(
"# comment\n# type: ignore\n# comment\nx = 5",
&[(Tool::Type, 2, &[])],
);
f("# type: ignore\nx = 5", &[]);
f("# pyre-ignore-all-errors\nx = 5", &[(Tool::Pyre, 1, &[])]);
f(
"# mypy: ignore-errors\n#pyrefly:ignore-errors",
&[(Tool::Mypy, 1, &[]), (Tool::Pyrefly, 2, &[])],
);
f("# mypy: ignore-errors[bad-assignment]\nx = 5", &[]);
// Anything else on the line (other than space) makes it invalid
f("# pyrefly: ignore-errors because I want to\nx = 5", &[]);
f("# pyrefly: ignore-errors # because I want to\nx = 5", &[]);
f(
"# pyrefly: ignore-errors[bad-assignment] # because I want to\nx = 5",
&[],
);
f(
"# pyrefly: ignore-errors \nx = 5",
&[(Tool::Pyrefly, 1, &[])],
);
}
#[test]
fn test_parse_ignore_all_with_docstring() {
fn f(x: &str, ranges: &[(LineNumber, LineNumber)], ignores: &[(Tool, u32, &[&str])]) {
assert_eq!(
parse_ignore_all(x, ranges),
ignores
.iter()
.map(|x| Suppression {
tool: x.0,
kind: x.2.iter().map(|x| (*x).to_owned()).collect(),
comment_line: LineNumber::new(x.1).unwrap(),
comment_offset: 0,
})
.collect::<Vec<_>>(),
"{x:?}"
);
}
// ignore-errors after a docstring should work
f(
"\"\"\"\nmodule docstring\n\"\"\"\n# pyrefly: ignore-errors\nx = 5",
&[(
LineNumber::from_zero_indexed(0),
LineNumber::from_zero_indexed(2),
)],
&[(Tool::Pyrefly, 4, &[])],
);
// typed ignore-errors[code] after a docstring should also work
f(
"\"\"\"\nmodule docstring\n\"\"\"\n# pyrefly: ignore-errors[bad-assignment]\nx = 5",
&[(
LineNumber::from_zero_indexed(0),
LineNumber::from_zero_indexed(2),
)],
&[(Tool::Pyrefly, 4, &["bad-assignment"])],
);
// bare `# type: ignore` after docstring should NOT be recognized
f(
"\"\"\"\nmodule docstring\n\"\"\"\n# type: ignore\n\nx = 5",
&[(
LineNumber::from_zero_indexed(0),
LineNumber::from_zero_indexed(2),
)],
&[],
);
// ignore-errors before a docstring should still work
f(
"# pyrefly: ignore-errors\n\"\"\"\nmodule docstring\n\"\"\"\nx = 5",
&[(
LineNumber::from_zero_indexed(1),
LineNumber::from_zero_indexed(3),
)],
&[(Tool::Pyrefly, 1, &[])],
);
}
}