-
-
Notifications
You must be signed in to change notification settings - Fork 512
/
Copy pathlib.rs
945 lines (841 loc) · 36.2 KB
/
lib.rs
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
#![deny(rustdoc::broken_intra_doc_links)]
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::{BTreeMap, BinaryHeap};
use std::fmt::{Debug, Display, Formatter};
use std::ops;
use tracing::trace;
mod categories;
pub mod context;
mod diagnostics;
mod matcher;
pub mod options;
mod query;
mod registry;
mod rule;
mod services;
mod signals;
mod suppression_action;
mod syntax;
mod visitor;
// Re-exported for use in the `declare_group` macro
pub use biome_diagnostics::category_concat;
pub use crate::categories::{
ActionCategory, RefactorKind, RuleCategories, RuleCategoriesBuilder, RuleCategory,
SourceActionKind, SUPPRESSION_ACTION_CATEGORY,
};
pub use crate::diagnostics::{AnalyzerDiagnostic, RuleError, SuppressionDiagnostic};
pub use crate::matcher::{InspectMatcher, MatchQueryParams, QueryMatcher, RuleKey, SignalEntry};
pub use crate::options::{AnalyzerConfiguration, AnalyzerOptions, AnalyzerRules};
pub use crate::query::{AddVisitor, QueryKey, QueryMatch, Queryable};
pub use crate::registry::{
LanguageRoot, MetadataRegistry, Phase, Phases, RegistryRuleMetadata, RegistryVisitor,
RuleRegistry, RuleRegistryBuilder, RuleSuppressions,
};
pub use crate::rule::{
CategoryLanguage, FixKind, GroupCategory, GroupLanguage, Rule, RuleAction, RuleDiagnostic,
RuleGroup, RuleMeta, RuleMetadata, RuleSource, RuleSourceKind, SuppressAction,
};
pub use crate::services::{FromServices, MissingServicesDiagnostic, ServiceBag};
pub use crate::signals::{
AnalyzerAction, AnalyzerSignal, AnalyzerTransformation, DiagnosticSignal,
};
pub use crate::syntax::{Ast, SyntaxVisitor};
pub use crate::visitor::{NodeVisitor, Visitor, VisitorContext, VisitorFinishContext};
pub use suppression_action::{ApplySuppression, SuppressionAction};
use biome_console::markup;
use biome_diagnostics::{
category, Applicability, Diagnostic, DiagnosticExt, DiagnosticTags, Severity,
};
use biome_rowan::{
AstNode, BatchMutation, Direction, Language, SyntaxElement, SyntaxToken, TextLen, TextRange,
TextSize, TokenAtOffset, TriviaPiece, TriviaPieceKind, WalkEvent,
};
/// The analyzer is the main entry point into the `biome_analyze` infrastructure.
/// Its role is to run a collection of [Visitor]s over a syntax tree, with each
/// visitor implementing various analysis over this syntax tree to generate
/// auxiliary data structures as well as emit "query match" events to be
/// processed by lint rules and in turn emit "analyzer signals" in the form of
/// diagnostics, code actions or both
pub struct Analyzer<'analyzer, L: Language, Matcher, Break, Diag> {
/// List of visitors being run by this instance of the analyzer for each phase
phases: BTreeMap<Phases, Vec<Box<dyn Visitor<Language = L> + 'analyzer>>>,
/// Holds the metadata for all the rules statically known to the analyzer
metadata: &'analyzer MetadataRegistry,
/// Executor for the query matches emitted by the visitors
query_matcher: Matcher,
/// Language-specific suppression comment parsing function
parse_suppression_comment: SuppressionParser<Diag>,
/// Language-specific suppression comment emitter
suppression_action: Box<dyn SuppressionAction<Language = L>>,
/// Handles analyzer signals emitted by individual rules
emit_signal: SignalHandler<'analyzer, L, Break>,
}
pub struct AnalyzerContext<'a, L: Language> {
pub root: LanguageRoot<L>,
pub services: ServiceBag,
pub range: Option<TextRange>,
pub options: &'a AnalyzerOptions,
}
impl<'analyzer, L, Matcher, Break, Diag> Analyzer<'analyzer, L, Matcher, Break, Diag>
where
L: Language,
Matcher: QueryMatcher<L>,
Diag: Diagnostic + Clone + Send + Sync + 'static,
{
/// Construct a new instance of the analyzer with the given rule registry
/// and suppression comment parser
pub fn new(
metadata: &'analyzer MetadataRegistry,
query_matcher: Matcher,
parse_suppression_comment: SuppressionParser<Diag>,
suppression_action: Box<dyn SuppressionAction<Language = L>>,
emit_signal: SignalHandler<'analyzer, L, Break>,
) -> Self {
Self {
phases: BTreeMap::new(),
metadata,
query_matcher,
parse_suppression_comment,
suppression_action,
emit_signal,
}
}
/// Registers a [Visitor] to be executed as part of a given `phase` of the analyzer run
pub fn add_visitor(
&mut self,
phase: Phases,
visitor: Box<dyn Visitor<Language = L> + 'analyzer>,
) {
self.phases.entry(phase).or_default().push(visitor);
}
pub fn run(self, mut ctx: AnalyzerContext<L>) -> Option<Break> {
let Self {
phases,
metadata,
mut query_matcher,
parse_suppression_comment,
mut emit_signal,
suppression_action,
} = self;
let mut line_index = 0;
let mut line_suppressions = Vec::new();
for (index, (phase, mut visitors)) in phases.into_iter().enumerate() {
let runner = PhaseRunner {
phase,
visitors: &mut visitors,
metadata,
query_matcher: &mut query_matcher,
signal_queue: BinaryHeap::new(),
parse_suppression_comment,
line_index: &mut line_index,
line_suppressions: &mut line_suppressions,
emit_signal: &mut emit_signal,
root: &ctx.root,
services: &ctx.services,
range: ctx.range,
suppression_action: suppression_action.as_ref(),
options: ctx.options,
};
// The first phase being run will inspect the tokens and parse the
// suppression comments, then subsequent phases only needs to read
// this data again since it's already cached in `line_suppressions`
let result = if index == 0 {
runner.run_first_phase()
} else {
runner.run_remaining_phases()
};
if let ControlFlow::Break(br) = result {
return Some(br);
}
// Finish all the active visitors, this is executed outside of the
// phase runner as it needs mutable access to the service bag (the
// runner borrows the services for the entire phase)
for visitor in visitors {
visitor.finish(VisitorFinishContext {
root: &ctx.root,
services: &mut ctx.services,
});
}
}
for suppression in line_suppressions {
if suppression.did_suppress_signal {
continue;
}
let signal = DiagnosticSignal::new(|| {
SuppressionDiagnostic::new(
category!("suppressions/unused"),
suppression.comment_span,
"Suppression comment has no effect. Remove the suppression or make sure you are suppressing the correct rule.",
)
});
if let ControlFlow::Break(br) = (emit_signal)(&signal) {
return Some(br);
}
}
None
}
}
/// Holds all the state required to run a single analysis phase to completion
struct PhaseRunner<'analyzer, 'phase, L: Language, Matcher, Break, Diag> {
/// Identifier of the phase this runner is executing
phase: Phases,
/// List of visitors being run by this instance of the analyzer for each phase
visitors: &'phase mut [Box<dyn Visitor<Language = L> + 'analyzer>],
/// Holds the metadata for all the rules statically known to the analyzer
metadata: &'analyzer MetadataRegistry,
/// Executor for the query matches emitted by the visitors
query_matcher: &'phase mut Matcher,
/// Queue for pending analyzer signals
signal_queue: BinaryHeap<SignalEntry<'phase, L>>,
/// Language-specific suppression comment parsing function
parse_suppression_comment: SuppressionParser<Diag>,
/// Language-specific suppression comment emitter
suppression_action: &'phase dyn SuppressionAction<Language = L>,
/// Line index at the current position of the traversal
line_index: &'phase mut usize,
/// Track active suppression comments per-line, ordered by line index
line_suppressions: &'phase mut Vec<LineSuppression>,
/// Handles analyzer signals emitted by individual rules
emit_signal: &'phase mut SignalHandler<'analyzer, L, Break>,
/// Root node of the file being analyzed
root: &'phase L::Root,
/// Service bag handle for this phase
services: &'phase ServiceBag,
/// Optional text range to restrict the analysis to
range: Option<TextRange>,
/// Analyzer options
options: &'phase AnalyzerOptions,
}
/// Single entry for a suppression comment in the `line_suppressions` buffer
#[derive(Debug)]
struct LineSuppression {
/// Line index this comment is suppressing lint rules for
line_index: usize,
/// Range of source text covered by the suppression comment
comment_span: TextRange,
/// Range of source text this comment is suppressing lint rules for
text_range: TextRange,
/// Set to true if this comment has set the `suppress_all` flag to true
/// (must be restored to false on expiration)
suppress_all: bool,
/// List of all the rules this comment has started suppressing (must be
/// removed from the suppressed set on expiration)
suppressed_rules: Vec<RuleFilter<'static>>,
/// List of all the rule instances this comment has started suppressing.
suppressed_instances: Vec<(RuleFilter<'static>, String)>,
/// Set to `true` when a signal matching this suppression was emitted and
/// suppressed
did_suppress_signal: bool,
}
impl<'a, 'phase, L, Matcher, Break, Diag> PhaseRunner<'a, 'phase, L, Matcher, Break, Diag>
where
L: Language,
Matcher: QueryMatcher<L>,
Diag: Diagnostic + Clone + Send + Sync + 'static,
{
/// Runs phase 0 over nodes and tokens to process line breaks and
/// suppression comments
fn run_first_phase(mut self) -> ControlFlow<Break> {
trace!("Running first analyzer phase");
let iter = self.root.syntax().preorder_with_tokens(Direction::Next);
for event in iter {
let node_event = match event {
WalkEvent::Enter(SyntaxElement::Node(node)) => WalkEvent::Enter(node),
WalkEvent::Leave(SyntaxElement::Node(node)) => WalkEvent::Leave(node),
// If this is a token enter event, process its text content
WalkEvent::Enter(SyntaxElement::Token(token)) => {
self.handle_token(token)?;
continue;
}
WalkEvent::Leave(SyntaxElement::Token(_)) => {
continue;
}
};
// If this is a node event pass it to the visitors for this phase
for visitor in self.visitors.iter_mut() {
let ctx = VisitorContext {
phase: self.phase,
root: self.root,
services: self.services,
range: self.range,
query_matcher: self.query_matcher,
signal_queue: &mut self.signal_queue,
suppression_action: self.suppression_action,
options: self.options,
};
visitor.visit(&node_event, ctx);
}
}
// Flush all remaining pending events
self.flush_matches(None)
}
/// Runs phases 1..N over nodes, since suppression comments were already
/// processed and cached in `run_initial_phase`
fn run_remaining_phases(mut self) -> ControlFlow<Break> {
for event in self.root.syntax().preorder() {
// Run all the active visitors for the phase on the event
for visitor in self.visitors.iter_mut() {
let ctx = VisitorContext {
phase: self.phase,
root: self.root,
services: self.services,
range: self.range,
query_matcher: self.query_matcher,
signal_queue: &mut self.signal_queue,
suppression_action: self.suppression_action,
options: self.options,
};
visitor.visit(&event, ctx);
}
// Flush all pending query signals
self.flush_matches(None)?;
}
ControlFlow::Continue(())
}
/// Process the text for a single token, parsing suppression comments and
/// handling line breaks, then flush all pending query signals in the queue
/// whose position is less then the end of the token within the file
fn handle_token(&mut self, token: SyntaxToken<L>) -> ControlFlow<Break> {
// Process the content of the token for comments and newline
for (index, piece) in token.leading_trivia().pieces().enumerate() {
if matches!(
piece.kind(),
TriviaPieceKind::Newline
| TriviaPieceKind::MultiLineComment
| TriviaPieceKind::Skipped
) {
self.bump_line_index(piece.text(), piece.text_range());
}
if let Some(comment) = piece.as_comments() {
self.handle_comment(&token, true, index, comment.text(), piece.text_range())?;
}
}
self.bump_line_index(token.text_trimmed(), token.text_trimmed_range());
for (index, piece) in token.trailing_trivia().pieces().enumerate() {
if matches!(
piece.kind(),
TriviaPieceKind::Newline
| TriviaPieceKind::MultiLineComment
| TriviaPieceKind::Skipped
) {
self.bump_line_index(piece.text(), piece.text_range());
}
if let Some(comment) = piece.as_comments() {
self.handle_comment(&token, false, index, comment.text(), piece.text_range())?;
}
}
// Flush signals from the queue until the end of the current token is reached
let cutoff = token.text_range().end();
self.flush_matches(Some(cutoff))
}
/// Flush all pending query signals in the queue. If `cutoff` is specified,
/// signals that start after this position in the file will be skipped
fn flush_matches(&mut self, cutoff: Option<TextSize>) -> ControlFlow<Break> {
while let Some(entry) = self.signal_queue.peek() {
let start = entry.text_range.start();
if let Some(cutoff) = cutoff {
if start >= cutoff {
break;
}
}
// Search for an active suppression comment covering the range of
// this signal: first try to load the last line suppression and see
// if it matches the current line index, otherwise perform a binary
// search over all the previously seen suppressions to find one
// with a matching range
let suppression = self.line_suppressions.last_mut().filter(|suppression| {
suppression.line_index == *self.line_index
&& suppression.text_range.start() <= start
});
let suppression = match suppression {
Some(suppression) => Some(suppression),
None => {
let index = self.line_suppressions.binary_search_by(|suppression| {
if suppression.text_range.end() < entry.text_range.start() {
Ordering::Less
} else if entry.text_range.end() < suppression.text_range.start() {
Ordering::Greater
} else {
Ordering::Equal
}
});
index.ok().map(|index| &mut self.line_suppressions[index])
}
};
let suppression = suppression.filter(|suppression| {
if suppression.suppress_all {
return true;
}
if suppression
.suppressed_rules
.iter()
.any(|filter| *filter == entry.rule)
{
return true;
}
if entry.instances.is_empty() {
return false;
}
entry.instances.iter().all(|value| {
suppression
.suppressed_instances
.iter()
.any(|(filter, v)| *filter == entry.rule && v == value.as_ref())
})
});
// If the signal is being suppressed mark the line suppression as
// hit, otherwise emit the signal
if let Some(suppression) = suppression {
suppression.did_suppress_signal = true;
} else if range_match(self.range, entry.text_range) {
(self.emit_signal)(&*entry.signal)?;
}
// Remove signal from the queue.
self.signal_queue.pop();
}
ControlFlow::Continue(())
}
/// Parse the text content of a comment trivia piece for suppression
/// comments, and create line suppression entries accordingly
fn handle_comment(
&mut self,
token: &SyntaxToken<L>,
is_leading: bool,
index: usize,
text: &str,
range: TextRange,
) -> ControlFlow<Break> {
let mut suppress_all = false;
let mut suppressed_rules = Vec::new();
let mut suppressed_instances = Vec::new();
let mut has_legacy = false;
for result in (self.parse_suppression_comment)(text) {
let kind = match result {
Ok(kind) => kind,
Err(diag) => {
// Emit the suppression parser diagnostic
let signal = DiagnosticSignal::new(move || {
let location = diag.location();
let span = location.span.map_or(range, |span| span + range.start());
diag.clone().with_file_span(span)
});
(self.emit_signal)(&signal)?;
continue;
}
};
if matches!(kind, SuppressionKind::Deprecated) {
let signal = DiagnosticSignal::new(move || {
SuppressionDiagnostic::new(
category!("suppressions/deprecatedSuppressionComment"),
range,
"// rome-ignore is deprecated, use // biome-ignore instead",
)
.with_tags(DiagnosticTags::DEPRECATED_CODE)
.with_severity(Severity::Information)
})
.with_action(move || create_suppression_comment_action(token));
(self.emit_signal)(&signal)?;
}
let (rule, instance) = match kind {
SuppressionKind::Everything => (None, None),
SuppressionKind::Rule(rule) => (Some(rule), None),
SuppressionKind::RuleInstance(rule, instance) => (Some(rule), Some(instance)),
SuppressionKind::MaybeLegacy(rule) => (Some(rule), None),
SuppressionKind::Deprecated => (None, None),
};
if let Some(rule) = rule {
let group_rule = rule.split_once('/');
let key = match group_rule {
None => self.metadata.find_group(rule).map(RuleFilter::from),
Some((group, rule)) => {
self.metadata.find_rule(group, rule).map(RuleFilter::from)
}
};
match (key, instance) {
(Some(key), Some(value)) => suppressed_instances.push((key, value.to_owned())),
(Some(key), None) => {
suppressed_rules.push(key);
has_legacy |= matches!(kind, SuppressionKind::MaybeLegacy(_));
}
_ if range_match(self.range, range) => {
// Emit a warning for the unknown rule
let signal = DiagnosticSignal::new(move || match group_rule {
Some((group, rule)) => SuppressionDiagnostic::new(
category!("suppressions/unknownRule"),
range,
format_args!(
"Unknown lint rule {group}/{rule} in suppression comment"
),
),
None => SuppressionDiagnostic::new(
category!("suppressions/unknownGroup"),
range,
format_args!(
"Unknown lint rule group {rule} in suppression comment"
),
),
});
(self.emit_signal)(&signal)?;
}
_ => {}
}
} else {
suppressed_rules.clear();
suppress_all = true;
// If this if a "suppress all lints" comment, no need to
// parse anything else
break;
}
}
// Emit a warning for legacy suppression syntax
if has_legacy && range_match(self.range, range) {
let signal = DiagnosticSignal::new(move || {
SuppressionDiagnostic::new(
category!("suppressions/deprecatedSuppressionComment"),
range,
"Suppression is using a deprecated syntax",
)
.with_tags(DiagnosticTags::DEPRECATED_CODE)
});
let signal = signal
.with_action(|| update_suppression(self.root, token, is_leading, index, text));
(self.emit_signal)(&signal)?;
}
if !suppress_all && suppressed_rules.is_empty() && suppressed_instances.is_empty() {
return ControlFlow::Continue(());
}
// Suppression comments apply to the next line
let line_index = *self.line_index + 1;
// If the last suppression was on the same or previous line, extend its
// range and set of suppressed rules with the content for the new suppression
if let Some(last_suppression) = self.line_suppressions.last_mut() {
if last_suppression.line_index == line_index
|| last_suppression.line_index + 1 == line_index
{
last_suppression.line_index = line_index;
last_suppression.text_range = last_suppression.text_range.cover(range);
last_suppression.suppress_all |= suppress_all;
if !last_suppression.suppress_all {
last_suppression.suppressed_rules.extend(suppressed_rules);
last_suppression
.suppressed_instances
.extend(suppressed_instances);
} else {
last_suppression.suppressed_rules.clear();
last_suppression.suppressed_instances.clear();
}
return ControlFlow::Continue(());
}
}
let entry = LineSuppression {
line_index,
comment_span: range,
text_range: range,
suppress_all,
suppressed_rules,
suppressed_instances,
did_suppress_signal: false,
};
self.line_suppressions.push(entry);
ControlFlow::Continue(())
}
/// Check a piece of source text (token or trivia) for line breaks and
/// increment the line index accordingly, extending the range of the
/// current suppression as required
fn bump_line_index(&mut self, text: &str, range: TextRange) {
let mut did_match = false;
for (index, _) in text.match_indices('\n') {
if let Some(last_suppression) = self.line_suppressions.last_mut() {
if last_suppression.line_index == *self.line_index {
let index = TextSize::try_from(index).expect(
"integer overflow while converting a suppression line to `TextSize`",
);
let range = TextRange::at(range.start(), index);
last_suppression.text_range = last_suppression.text_range.cover(range);
did_match = true;
}
}
*self.line_index += 1;
}
if !did_match {
if let Some(last_suppression) = self.line_suppressions.last_mut() {
if last_suppression.line_index == *self.line_index {
last_suppression.text_range = last_suppression.text_range.cover(range);
}
}
}
}
}
fn create_suppression_comment_action<L: Language>(
token: &SyntaxToken<L>,
) -> Option<AnalyzerAction<L>> {
let first_node = token.parent()?;
let mut new_leading_trivia = vec![];
let mut token_text = String::new();
let mut new_trailing_trivia = vec![];
let mut mutation = BatchMutation::new(first_node);
for piece in token.leading_trivia().pieces() {
if !piece.is_comments() {
new_leading_trivia.push(TriviaPiece::new(piece.kind(), piece.text_len()));
token_text.push_str(piece.text());
}
if piece.text().contains("rome-ignore") {
let new_text = piece.text().replace("rome-ignore", "biome-ignore");
new_leading_trivia.push(TriviaPiece::new(piece.kind(), new_text.text_len()));
token_text.push_str(&new_text);
}
}
token_text.push_str(token.text_trimmed());
for piece in token.trailing_trivia().pieces() {
new_trailing_trivia.push(TriviaPiece::new(piece.kind(), piece.text_len()));
token_text.push_str(piece.text());
}
let new_token = SyntaxToken::new_detached(
token.kind(),
&token_text,
new_leading_trivia,
new_trailing_trivia,
);
mutation.replace_token_discard_trivia(token.clone(), new_token);
Some(AnalyzerAction {
mutation,
applicability: Applicability::MaybeIncorrect,
category: ActionCategory::QuickFix(Cow::Borrowed("")),
message: markup! {
"Use // biome-ignore instead"
}
.to_owned(),
rule_name: None,
})
}
fn range_match(filter: Option<TextRange>, range: TextRange) -> bool {
filter.map_or(true, |filter| filter.intersect(range).is_some())
}
/// Signature for a suppression comment parser function
///
/// This function receives the text content of a comment and returns a list of
/// lint suppressions as an optional lint rule (if the lint rule is `None` the
/// comment is interpreted as suppressing all lints)
///
/// # Examples
///
/// - `// biome-ignore format` -> `vec![]`
/// - `// biome-ignore lint` -> `vec![Everything]`
/// - `// biome-ignore lint/style/useWhile` -> `vec![Rule("style/useWhile")]`
/// - `// biome-ignore lint/style/useWhile(foo)` -> `vec![RuleWithValue("style/useWhile", "foo")]`
/// - `// biome-ignore lint/style/useWhile lint/nursery/noUnreachable` -> `vec![Rule("style/useWhile"), Rule("nursery/noUnreachable")]`
/// - `// biome-ignore lint(style/useWhile)` -> `vec![MaybeLegacy("style/useWhile")]`
/// - `// biome-ignore lint(style/useWhile) lint(nursery/noUnreachable)` -> `vec![MaybeLegacy("style/useWhile"), MaybeLegacy("nursery/noUnreachable")]`
type SuppressionParser<D> = fn(&str) -> Vec<Result<SuppressionKind, D>>;
/// This enum is used to categorize what is disabled by a suppression comment and with what syntax
pub enum SuppressionKind<'a> {
/// A suppression disabling all lints eg. `// biome-ignore lint`
Everything,
/// A suppression disabling a specific rule eg. `// biome-ignore lint/style/useWhile`
Rule(&'a str),
/// A suppression to be evaluated by a specific rule eg. `// biome-ignore lint/correctness/useExhaustiveDependencies(foo)`
RuleInstance(&'a str, &'a str),
/// A suppression using the legacy syntax to disable a specific rule eg. `// biome-ignore lint(style/useWhile)`
MaybeLegacy(&'a str),
/// `rome-ignore` is legacy
Deprecated,
}
fn update_suppression<L: Language>(
root: &L::Root,
token: &SyntaxToken<L>,
is_leading: bool,
index: usize,
text: &str,
) -> Option<AnalyzerAction<L>> {
let old_token = token.clone();
let new_token = token.clone().detach();
let old_trivia = if is_leading {
old_token.leading_trivia()
} else {
old_token.trailing_trivia()
};
let old_trivia: Vec<_> = old_trivia.pieces().collect();
let mut text = text.to_string();
while let Some(range_start) = text.find("lint(") {
let range_end = range_start + text[range_start..].find(')')?;
text.replace_range(range_end..range_end + 1, "");
text.replace_range(range_start + 4..range_start + 5, "/");
}
let new_trivia = old_trivia.iter().enumerate().map(|(piece_index, piece)| {
if piece_index == index {
(piece.kind(), text.as_str())
} else {
(piece.kind(), piece.text())
}
});
let new_token = if is_leading {
new_token.with_leading_trivia(new_trivia)
} else {
new_token.with_trailing_trivia(new_trivia)
};
let mut mutation = BatchMutation::new(root.syntax().clone());
mutation.replace_token_discard_trivia(old_token, new_token);
Some(AnalyzerAction {
rule_name: None,
category: ActionCategory::QuickFix(Cow::Borrowed("")),
applicability: Applicability::Always,
message: markup! {
"Rewrite suppression to use the newer syntax"
}
.to_owned(),
mutation,
})
}
/// Payload received by the function responsible to mark a suppression comment
pub struct SuppressionCommentEmitterPayload<'a, L: Language> {
/// The possible offset found in the [TextRange] of the emitted diagnostic
pub token_offset: TokenAtOffset<SyntaxToken<L>>,
/// A [BatchMutation] where the consumer can apply the suppression comment
pub mutation: &'a mut BatchMutation<L>,
/// A string equals to "rome-ignore: lint(<RULE_GROUP>/<RULE_NAME>)"
pub suppression_text: &'a str,
/// The original range of the diagnostic where the rule was triggered
pub diagnostic_text_range: &'a TextRange,
/// Explanation for the suppression to be used with `--suppress` and `--reason`
pub suppression_reason: &'a str,
}
type SignalHandler<'a, L, Break> = &'a mut dyn FnMut(&dyn AnalyzerSignal<L>) -> ControlFlow<Break>;
/// Allow filtering a single rule or group of rules by their names
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum RuleFilter<'a> {
Group(&'a str),
Rule(&'a str, &'a str),
}
impl<'a> RuleFilter<'a> {
// Returns the group name of this filter.
pub fn group(self) -> &'a str {
match self {
RuleFilter::Group(group) => group,
RuleFilter::Rule(group, _) => group,
}
}
/// Return `true` if the group `G` matches this filter
pub fn match_group<G: RuleGroup>(self) -> bool {
match self {
RuleFilter::Group(group) => group == G::NAME,
RuleFilter::Rule(group, _) => group == G::NAME,
}
}
/// Return `true` if the rule `R` matches this filter
pub fn match_rule<R>(self) -> bool
where
R: Rule,
{
match self {
RuleFilter::Group(group) => group == <R::Group as RuleGroup>::NAME,
RuleFilter::Rule(group, rule) => {
group == <R::Group as RuleGroup>::NAME && rule == R::METADATA.name
}
}
}
}
impl<'a> Debug for RuleFilter<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(self, f)
}
}
impl<'a> Display for RuleFilter<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
RuleFilter::Group(group) => {
write!(f, "{group}")
}
RuleFilter::Rule(group, rule) => {
write!(f, "{group}/{rule}")
}
}
}
}
impl<'a> biome_console::fmt::Display for RuleFilter<'a> {
fn fmt(&self, fmt: &mut biome_console::fmt::Formatter) -> std::io::Result<()> {
match self {
RuleFilter::Group(group) => {
write!(fmt, "{group}")
}
RuleFilter::Rule(group, rule) => {
write!(fmt, "{group}/{rule}")
}
}
}
}
/// Allows filtering the list of rules that will be executed in a run of the analyzer,
/// and at what source code range signals (diagnostics or actions) may be raised
#[derive(Debug, Default, Clone, Copy)]
pub struct AnalysisFilter<'a> {
/// Only allow rules with these categories to emit signals
pub categories: RuleCategories,
/// Only allow rules matching these names to emit signals
/// If `enabled_rules` is set to `None`, then all rules are enabled.
pub enabled_rules: Option<&'a [RuleFilter<'a>]>,
/// Do not allow rules matching these names to emit signals
pub disabled_rules: &'a [RuleFilter<'a>],
/// Only emit signals matching this text range
pub range: Option<TextRange>,
}
impl<'analysis> AnalysisFilter<'analysis> {
/// It creates a new filter with the set of [enabled rules](RuleFilter) passed as argument
pub fn from_enabled_rules(enabled_rules: &'analysis [RuleFilter<'analysis>]) -> Self {
Self {
enabled_rules: Some(enabled_rules),
..AnalysisFilter::default()
}
}
/// Return `true` if the category `C` matches this filter
pub fn match_category<C: GroupCategory>(&self) -> bool {
self.categories.contains(C::CATEGORY)
}
/// Return `true` if the group `G` matches this filter
pub fn match_group<G: RuleGroup>(&self) -> bool {
self.match_category::<G::Category>()
&& self.enabled_rules.map_or(true, |enabled_rules| {
enabled_rules.iter().any(|filter| filter.match_group::<G>())
})
&& !self
.disabled_rules
.iter()
.any(|filter| matches!(filter, RuleFilter::Group(_)) && filter.match_group::<G>())
}
/// Return `true` if the rule `R` matches this filter
pub fn match_rule<R: Rule>(&self) -> bool {
self.match_category::<<R::Group as RuleGroup>::Category>()
&& self.enabled_rules.map_or(true, |enabled_rules| {
enabled_rules.iter().any(|filter| filter.match_rule::<R>())
})
&& !self
.disabled_rules
.iter()
.any(|filter| filter.match_rule::<R>())
}
}
/// Utility type to be used as a default value for the `B` generic type on
/// `analyze` when the provided callback never breaks
///
/// This should eventually get replaced with the `!` type when it gets stabilized
pub enum Never {}
/// Type alias of [ops::ControlFlow] with the `B` generic type defaulting to [Never]
///
/// By default, the analysis loop never breaks, so it behaves mostly like
/// `let b = loop {};` and has a "break type" of `!` (the `!` type isn't stable
/// yet, so I'm using an empty enum instead, but they're identical for this
/// purpose)
///
/// In practice, it's not really a `loop` but a `for` because it's iterating on
/// all nodes in the syntax tree, so when it reaches the end of the iterator
/// the loop will exit but without producing a value of type `B`: for this
/// reason the `analyze` function returns an `Option<B>` that's set to
/// `Some(B)` if the callback did break, and `None` if the analysis reached the
/// end of the file.
///
/// Most consumers of the analyzer will want to analyze the entire file at once
/// and never break, so using [Never] as the type of `B` in this case lets the
/// compiler know the `ControlFlow::Break` branch will never be taken and can
/// be optimized out, as well as completely remove the `return Some` case
/// (`Option<Never>` has a size of 0 and can be elided, while `Option<()>` has
/// a size of 1 as it still need to store a discriminant)
pub type ControlFlow<B = Never> = ops::ControlFlow<B>;