ast-grep-config 0.43.0

Search and Rewrite code at large scale using precise AST pattern
Documentation
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
use crate::{RuleConfig, SerializableRule, SerializableRuleConfig, SerializableRuleCore, Severity};

use ast_grep_core::language::Language;
use ast_grep_core::matcher::{Matcher, MatcherExt};
use ast_grep_core::{AstGrep, Doc, Node, NodeMatch};

use std::collections::{HashMap, HashSet};

pub struct ScanResult<'t, 'r, D: Doc, L: Language> {
  pub diffs: Vec<(&'r RuleConfig<L>, NodeMatch<'t, D>)>,
  pub matches: Vec<(&'r RuleConfig<L>, Vec<NodeMatch<'t, D>>)>,
}

/// store the index to the rule and the matched node
/// it will be converted to ScanResult by resolving the rule
struct ScanResultInner<'t, D: Doc> {
  diffs: Vec<(usize, NodeMatch<'t, D>)>,
  matches: HashMap<usize, Vec<NodeMatch<'t, D>>>,
  unused_suppressions: Vec<NodeMatch<'t, D>>,
  suppress_all_nodes: Vec<NodeMatch<'t, D>>,
}

impl<'t, D: Doc> ScanResultInner<'t, D> {
  pub fn into_result<'r, L: Language>(
    self,
    combined: &CombinedScan<'r, L>,
    separate_fix: bool,
  ) -> ScanResult<'t, 'r, D, L> {
    let mut diffs: Vec<_> = self
      .diffs
      .into_iter()
      .map(|(idx, nm)| (combined.get_rule(idx), nm))
      .collect();
    let mut matches: Vec<_> = self
      .matches
      .into_iter()
      .map(|(idx, nms)| (combined.get_rule(idx), nms))
      .collect();
    if let Some(rule) = combined.unused_suppression_rule {
      if separate_fix {
        diffs.extend(self.unused_suppressions.into_iter().map(|nm| (rule, nm)));
        diffs.sort_unstable_by_key(|(_, nm)| nm.range().start);
      } else if !self.unused_suppressions.is_empty() {
        // do not push empty suppression to matches
        let mut supprs = self.unused_suppressions;
        supprs.sort_unstable_by_key(|nm| nm.range().start);
        matches.push((rule, supprs));
      }
    }
    if let Some(rule) = combined.no_suppress_all_rule {
      if !self.suppress_all_nodes.is_empty() {
        let mut supprs = self.suppress_all_nodes;
        supprs.sort_unstable_by_key(|nm| nm.range().start);
        matches.push((rule, supprs));
      }
    }
    ScanResult { diffs, matches }
  }
}

enum SuppressKind {
  /// suppress the whole file
  File,
  /// suppress specific line
  Line(usize),
}

fn get_suppression_kind(node: &Node<'_, impl Doc>) -> Option<SuppressKind> {
  if !node.kind().contains("comment") || !node.text().contains(IGNORE_TEXT) {
    return None;
  }
  let line = node.start_pos().line();
  let suppress_next_line = if let Some(prev) = node.prev() {
    prev.start_pos().line() != line
  } else {
    true
  };
  // if the first line is suppressed and the next line is empyt,
  // we suppress the whole file see gh #1541
  if line == 0
    && suppress_next_line
    && node
      .next()
      .map(|next| next.start_pos().line() >= 2)
      .unwrap_or(true)
  {
    return Some(SuppressKind::File);
  }
  let key = if suppress_next_line { line + 1 } else { line };
  Some(SuppressKind::Line(key))
}

struct Suppressions {
  file: Option<Suppression>,
  /// line number which may be suppressed
  lines: HashMap<usize, Suppression>,
}

impl Suppressions {
  fn collect_all<D: Doc>(root: &AstGrep<D>) -> (Self, HashMap<usize, Node<'_, D>>) {
    let mut suppressions = Self {
      file: None,
      lines: HashMap::new(),
    };
    let mut suppression_nodes = HashMap::new();
    for node in root.root().dfs() {
      let is_all_suppressed = suppressions.collect(&node, &mut suppression_nodes);
      if is_all_suppressed {
        break;
      }
    }
    (suppressions, suppression_nodes)
  }
  /// collect all suppression nodes from the root node
  /// returns if the whole file need to be suppressed, including unused sup
  /// see #1541
  fn collect<'r, D: Doc>(
    &mut self,
    node: &Node<'r, D>,
    suppression_nodes: &mut HashMap<usize, Node<'r, D>>,
  ) -> bool {
    let Some(sup) = get_suppression_kind(node) else {
      return false;
    };
    let suppressed = Suppression {
      suppressed: parse_suppression_set(&node.text()),
      node_id: node.node_id(),
    };
    suppression_nodes.insert(node.node_id(), node.clone());
    match sup {
      SuppressKind::File => {
        let is_all_suppressed = suppressed.suppressed.is_none();
        self.file = Some(suppressed);
        is_all_suppressed
      }
      SuppressKind::Line(key) => {
        self.lines.insert(
          key,
          Suppression {
            suppressed: parse_suppression_set(&node.text()),
            node_id: node.node_id(),
          },
        );
        false
      }
    }
  }

  fn suppress_all_node_ids(&self) -> impl Iterator<Item = usize> + '_ {
    self
      .file
      .iter()
      .chain(self.lines.values())
      .filter(|s| s.suppressed.is_none())
      .map(|s| s.node_id)
  }

  fn file_suppression(&self) -> MaySuppressed<'_> {
    if let Some(sup) = &self.file {
      MaySuppressed::Yes(sup)
    } else {
      MaySuppressed::No
    }
  }

  fn line_suppression<D: Doc>(&self, node: &Node<'_, D>) -> MaySuppressed<'_> {
    let line = node.start_pos().line();
    if let Some(sup) = self.lines.get(&line) {
      MaySuppressed::Yes(sup)
    } else {
      MaySuppressed::No
    }
  }
}

struct Suppression {
  /// None = suppress all
  suppressed: Option<HashSet<String>>,
  node_id: usize,
}

enum MaySuppressed<'a> {
  Yes(&'a Suppression),
  No,
}

impl MaySuppressed<'_> {
  fn suppressed_id(&self, rule_id: &str) -> Option<usize> {
    let suppression = match self {
      MaySuppressed::No => return None,
      MaySuppressed::Yes(s) => s,
    };
    if let Some(set) = &suppression.suppressed {
      if set.contains(rule_id) {
        Some(suppression.node_id)
      } else {
        None
      }
    } else {
      Some(suppression.node_id)
    }
  }
}

const IGNORE_TEXT: &str = "ast-grep-ignore";
pub const UNUSED_SUPPRESSION_ID: &str = "unused-suppression";
pub const NO_SUPPRESS_ALL_ID: &str = "no-suppress-all";

/// A struct to group all rules according to their potential kinds.
/// This can greatly reduce traversal times and skip unmatchable rules.
/// Rules are referenced by their index in the rules vector.
pub struct CombinedScan<'r, L: Language> {
  rules: Vec<&'r RuleConfig<L>>,
  /// a vec of vec, mapping from kind to a list of rule index
  kind_rule_mapping: Vec<Vec<usize>>,
  /// a rule for unused_suppressions
  unused_suppression_rule: Option<&'r RuleConfig<L>>,
  /// a rule for banning suppress-all comments
  no_suppress_all_rule: Option<&'r RuleConfig<L>>,
}

impl<'r, L: Language> CombinedScan<'r, L> {
  pub fn new(mut rules: Vec<&'r RuleConfig<L>>) -> Self {
    // process fixable rule first, the order by id
    // note, mapping.push will invert order so we sort fixable order in reverse
    rules.sort_unstable_by_key(|r| (r.fix.is_some(), &r.id));
    let mut mapping = Vec::new();
    for (idx, rule) in rules.iter().enumerate() {
      let Some(kinds) = rule.matcher.potential_kinds() else {
        eprintln!("rule `{}` must have kind", &rule.id);
        continue;
      };
      for kind in &kinds {
        // NOTE: common languages usually have about several hundred kinds
        // from 200+ ~ 500+, it is okay to waste about 500 * 24 Byte vec size = 12kB
        // see https://github.com/Wilfred/difftastic/tree/master/vendored_parsers
        while mapping.len() <= kind {
          mapping.push(vec![]);
        }
        mapping[kind].push(idx);
      }
    }
    Self {
      rules,
      kind_rule_mapping: mapping,
      unused_suppression_rule: None,
      no_suppress_all_rule: None,
    }
  }

  pub fn set_no_suppress_all_rule(&mut self, rule: &'r RuleConfig<L>) {
    if matches!(rule.severity, Severity::Off) {
      return;
    }
    self.no_suppress_all_rule = Some(rule);
  }

  pub fn set_unused_suppression_rule(&mut self, rule: &'r RuleConfig<L>) {
    if matches!(rule.severity, Severity::Off) {
      return;
    }
    self.unused_suppression_rule = Some(rule);
  }

  pub fn scan<'a, D>(&self, root: &'a AstGrep<D>, separate_fix: bool) -> ScanResult<'a, '_, D, L>
  where
    D: Doc<Lang = L>,
  {
    let mut result = ScanResultInner {
      diffs: vec![],
      matches: HashMap::new(),
      unused_suppressions: vec![],
      suppress_all_nodes: vec![],
    };
    let (suppressions, mut suppression_nodes) = Suppressions::collect_all(root);
    if self.no_suppress_all_rule.is_some() {
      let nodes = suppressions
        .suppress_all_node_ids()
        .filter_map(|id| suppression_nodes.get(&id));
      result
        .suppress_all_nodes
        .extend(nodes.cloned().map(NodeMatch::from));
    }
    let file_sup = suppressions.file_suppression();
    if let MaySuppressed::Yes(s) = file_sup {
      if s.suppressed.is_none() {
        return result.into_result(self, separate_fix);
      }
    }
    for node in root.root().dfs() {
      let kind = node.kind_id() as usize;
      let Some(rule_idx) = self.kind_rule_mapping.get(kind) else {
        continue;
      };
      let line_sup = suppressions.line_suppression(&node);
      for &idx in rule_idx {
        let rule = &self.rules[idx];
        let Some(ret) = rule.matcher.match_node(node.clone()) else {
          continue;
        };
        if let Some(id) = file_sup.suppressed_id(&rule.id) {
          suppression_nodes.remove(&id);
          continue;
        }
        if let Some(id) = line_sup.suppressed_id(&rule.id) {
          suppression_nodes.remove(&id);
          continue;
        }
        if rule.fix.is_none() || !separate_fix {
          let matches = result.matches.entry(idx).or_default();
          matches.push(ret);
        } else {
          result.diffs.push((idx, ret));
        }
      }
    }
    result.unused_suppressions = suppression_nodes
      .into_values()
      .map(NodeMatch::from)
      .collect();
    result.into_result(self, separate_fix)
  }

  pub fn get_rule(&self, idx: usize) -> &'r RuleConfig<L> {
    self.rules[idx]
  }

  pub fn no_suppress_all_config(severity: Severity, lang: L) -> RuleConfig<L> {
    let config = SerializableRuleConfig {
      id: NO_SUPPRESS_ALL_ID.into(),
      severity,
      message: "ast-grep-ignore must specify rule IDs.".into(),
      note: Some("Use 'ast-grep-ignore: rule-id' to suppress specific rules.".into()),
      ..Self::builtin_config(lang)
    };
    RuleConfig::try_from(config, &Default::default()).unwrap()
  }

  pub fn unused_config(severity: Severity, lang: L) -> RuleConfig<L> {
    let mut config = SerializableRuleConfig {
      id: UNUSED_SUPPRESSION_ID.into(),
      severity,
      message: "Unused 'ast-grep-ignore' directive.".into(),
      ..Self::builtin_config(lang)
    };
    config.core.fix = crate::from_str(r#"''"#).unwrap();
    RuleConfig::try_from(config, &Default::default()).unwrap()
  }

  fn builtin_config(lang: L) -> SerializableRuleConfig<L> {
    let rule: SerializableRule = crate::from_str(r#"{"any": []}"#).unwrap();
    SerializableRuleConfig {
      core: SerializableRuleCore {
        rule,
        constraints: None,
        fix: None,
        transform: None,
        utils: None,
      },
      language: lang,
      id: String::new(),
      severity: Severity::default(),
      message: String::new(),
      note: None,
      files: None,
      ignores: None,
      rewriters: None,
      url: None,
      metadata: None,
      labels: None,
    }
  }
}

// trim text after whitepaces, this is useful for comment like `/* ast-grep-ignore: test */`
// we assume no rule-id contains whitespace, so trailing comment can be stripped
// see https://github.com/ast-grep/ast-grep/issues/2644
fn trim_comment_trailing(text: &str) -> Option<&str> {
  text
    .trim_start() // trim leading whitespace
    .split(' ') // finding the first whitespace
    .next() // keep only the part before the first whitespace
}

fn parse_suppression_set(text: &str) -> Option<HashSet<String>> {
  let (_, after) = text.trim().split_once(IGNORE_TEXT)?;
  let after = after.trim();
  if after.is_empty() {
    return None;
  }
  let (_, rules) = after.split_once(':')?;
  let set = rules
    .split(',')
    .flat_map(trim_comment_trailing)
    .map(ToString::to_string)
    .collect();
  Some(set)
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::from_str;
  use crate::test::TypeScript;
  use crate::SerializableRuleConfig;
  use ast_grep_core::tree_sitter::{LanguageExt, StrDoc};

  fn create_rule() -> RuleConfig<TypeScript> {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {pattern: 'console.log($A)'}
language: Tsx",
    )
    .expect("parse");
    RuleConfig::try_from(rule, &Default::default()).expect("work")
  }

  fn test_scan<F>(source: &str, test_fn: F)
  where
    F: Fn(
      Vec<(
        &'_ RuleConfig<TypeScript>,
        Vec<NodeMatch<'_, StrDoc<TypeScript>>>,
      )>,
    ),
  {
    let root = TypeScript::Tsx.ast_grep(source);
    let rule = create_rule();
    let rules = vec![&rule];
    let scan = CombinedScan::new(rules);
    let scanned = scan.scan(&root, false);
    test_fn(scanned.matches);
  }

  #[test]
  fn test_ignore_node() {
    let source = r#"
    // ast-grep-ignore
    console.log('ignored all')
    console.log('no ignore')
    // ast-grep-ignore: test
    console.log('ignore one')
    // ast-grep-ignore: not-test
    console.log('ignore another')
    // ast-grep-ignore: not-test, test
    console.log('multiple ignore')
    "#;
    test_scan(source, |scanned| {
      let matches = &scanned[0];
      assert_eq!(matches.1.len(), 2);
      assert_eq!(matches.1[0].text(), "console.log('no ignore')");
      assert_eq!(matches.1[1].text(), "console.log('ignore another')");
    });
  }

  #[test]
  fn test_ignore_node_same_line() {
    let source = r#"
    console.log('ignored all') // ast-grep-ignore
    console.log('no ignore')
    console.log('ignore one') // ast-grep-ignore: test
    console.log('ignore another') // ast-grep-ignore: not-test
    console.log('multiple ignore') // ast-grep-ignore: not-test, test
    "#;
    test_scan(source, |scanned| {
      let matches = &scanned[0];
      assert_eq!(matches.1.len(), 2);
      assert_eq!(matches.1[0].text(), "console.log('no ignore')");
      assert_eq!(matches.1[1].text(), "console.log('ignore another')");
    });
  }

  #[test]
  fn test_ignore_node_block_comment() {
    let source = r#"
    /* ast-grep-ignore: test */
    console.log('ignore one')
    /* ast-grep-ignore: not-test */
    console.log('ignore another')
    /* ast-grep-ignore: not-test, test */
    console.log('multiple ignore')
    console.log('no ignore')
    "#;
    test_scan(source, |scanned| {
      let matches = &scanned[0];
      assert_eq!(matches.1.len(), 2);
      assert_eq!(matches.1[0].text(), "console.log('ignore another')");
      assert_eq!(matches.1[1].text(), "console.log('no ignore')");
    });
  }

  #[test]
  fn test_parse_suppression_set_trims_block_comment_trailing() {
    let set = parse_suppression_set("/* ast-grep-ignore: test */").expect("should parse");
    assert!(set.contains("test"));
    assert!(!set.contains("test */"));

    let set = parse_suppression_set("/* ast-grep-ignore: not-test, test */").expect("should parse");
    assert!(set.contains("not-test"));
    assert!(set.contains("test"));
    assert!(!set.contains("test */"));
  }

  fn test_scan_unused<F>(source: &str, test_fn: F)
  where
    F: Fn(
      Vec<(
        &'_ RuleConfig<TypeScript>,
        Vec<NodeMatch<'_, StrDoc<TypeScript>>>,
      )>,
    ),
  {
    let root = TypeScript::Tsx.ast_grep(source);
    let rule = create_rule();
    let rules = vec![&rule];
    let mut scan = CombinedScan::new(rules);
    let mut unused = create_rule();
    unused.id = UNUSED_SUPPRESSION_ID.to_string();
    scan.set_unused_suppression_rule(&unused);
    let scanned = scan.scan(&root, false);
    test_fn(scanned.matches);
  }

  #[test]
  fn test_non_used_suppression() {
    let source = r#"
    console.log('no ignore')
    console.debug('not used') // ast-grep-ignore: test
    console.log('multiple ignore') // ast-grep-ignore: test
    "#;
    test_scan_unused(source, |scanned| {
      assert_eq!(scanned.len(), 2);
      let unused = &scanned[1];
      assert_eq!(unused.1.len(), 1);
      assert_eq!(unused.1[0].text(), "// ast-grep-ignore: test");
    });
  }

  #[test]
  fn test_file_suppression() {
    let source = r#"// ast-grep-ignore: test

    console.log('ignored')
    console.debug('report') // ast-grep-ignore: test
    console.log('report') // ast-grep-ignore: test
    "#;
    test_scan_unused(source, |scanned| {
      assert_eq!(scanned.len(), 1);
      let unused = &scanned[0];
      assert_eq!(unused.1.len(), 2);
    });
    let source = r#"// ast-grep-ignore: test
    console.debug('above is not file sup')
    console.log('not ignored')
    "#;
    test_scan_unused(source, |scanned| {
      assert_eq!(scanned.len(), 2);
      assert_eq!(scanned[0].0.id, "test");
      assert_eq!(scanned[1].0.id, UNUSED_SUPPRESSION_ID);
    });
  }

  fn test_scan_no_suppress_all<F>(source: &str, test_fn: F)
  where
    F: Fn(
      Vec<(
        &'_ RuleConfig<TypeScript>,
        Vec<NodeMatch<'_, StrDoc<TypeScript>>>,
      )>,
    ),
  {
    let root = TypeScript::Tsx.ast_grep(source);
    let rule = create_rule();
    let rules = vec![&rule];
    let mut scan = CombinedScan::new(rules);
    let no_suppress_all = CombinedScan::no_suppress_all_config(Severity::Warning, TypeScript::Tsx);
    scan.set_no_suppress_all_rule(&no_suppress_all);
    let scanned = scan.scan(&root, false);
    test_fn(scanned.matches);
  }

  #[test]
  fn test_no_suppress_all_bare() {
    // bare `ast-grep-ignore` (intentional suppress-all) should fire
    let source = r#"
    // ast-grep-ignore
    console.log('ignored all')
    console.log('no ignore')
    "#;
    test_scan_no_suppress_all(source, |scanned| {
      let no_sup_all: Vec<_> = scanned
        .iter()
        .filter(|(r, _)| r.id == NO_SUPPRESS_ALL_ID)
        .collect();
      assert_eq!(no_sup_all.len(), 1);
      assert_eq!(no_sup_all[0].1.len(), 1);
      assert_eq!(no_sup_all[0].1[0].text(), "// ast-grep-ignore");
    });
  }

  #[test]
  fn test_no_suppress_all_missing_colon() {
    // `ast-grep-ignore rule-id` (missing colon) is also suppress-all
    let source = r#"
    // ast-grep-ignore test
    console.log('ignored all')
    "#;
    test_scan_no_suppress_all(source, |scanned| {
      let no_sup_all: Vec<_> = scanned
        .iter()
        .filter(|(r, _)| r.id == NO_SUPPRESS_ALL_ID)
        .collect();
      assert_eq!(no_sup_all.len(), 1);
      assert_eq!(no_sup_all[0].1.len(), 1);
    });
  }

  #[test]
  fn test_no_suppress_all_with_colon_does_not_fire() {
    // `ast-grep-ignore: rule-id` (specific suppression) should NOT fire
    let source = r#"
    // ast-grep-ignore: test
    console.log('ignored specific')
    console.log('no ignore')
    "#;
    test_scan_no_suppress_all(source, |scanned| {
      let no_sup_all: Vec<_> = scanned
        .iter()
        .filter(|(r, _)| r.id == NO_SUPPRESS_ALL_ID)
        .collect();
      assert_eq!(no_sup_all.len(), 0);
    });
  }

  #[test]
  fn test_no_suppress_all_same_line() {
    let source = r#"
    console.log('ignored') // ast-grep-ignore
    console.log('no ignore')
    "#;
    test_scan_no_suppress_all(source, |scanned| {
      let no_sup_all: Vec<_> = scanned
        .iter()
        .filter(|(r, _)| r.id == NO_SUPPRESS_ALL_ID)
        .collect();
      assert_eq!(no_sup_all.len(), 1);
      assert_eq!(no_sup_all[0].1.len(), 1);
    });
  }

  #[test]
  fn test_no_suppress_all_file_level() {
    // file-level suppress-all should also fire
    let source = r#"// ast-grep-ignore

    console.log('ignored')
    "#;
    test_scan_no_suppress_all(source, |scanned| {
      let no_sup_all: Vec<_> = scanned
        .iter()
        .filter(|(r, _)| r.id == NO_SUPPRESS_ALL_ID)
        .collect();
      assert_eq!(no_sup_all.len(), 1);
    });
  }

  #[test]
  fn test_file_suppression_all() {
    let source = r#"// ast-grep-ignore

    console.log('ignored')
    console.debug('report') // ast-grep-ignore: test
    console.log('report') // ast-grep-ignore
    "#;
    test_scan_unused(source, |scanned| {
      assert_eq!(scanned.len(), 0);
    });
    let source = r#"// ast-grep-ignore

    console.debug('no hit')
    "#;
    test_scan_unused(source, |scanned| {
      assert_eq!(scanned.len(), 0);
    });
  }
}