-
-
Notifications
You must be signed in to change notification settings - Fork 902
Expand file tree
/
Copy pathmod.rs
More file actions
609 lines (546 loc) · 22.5 KB
/
mod.rs
File metadata and controls
609 lines (546 loc) · 22.5 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
#![expect(rustdoc::private_intra_doc_links)] // useful for intellisense
use std::{ffi::OsStr, ops::Deref, path::Path, rc::Rc};
use javascript_globals::GLOBALS;
use oxc_ast::ast::IdentifierReference;
use oxc_cfg::ControlFlowGraph;
use oxc_diagnostics::{OxcDiagnostic, Severity};
use oxc_semantic::Semantic;
use oxc_span::Span;
#[cfg(debug_assertions)]
use crate::rule::RuleFixMeta;
use crate::{
AllowWarnDeny, FrameworkFlags, ModuleRecord, OxlintEnv, OxlintGlobals, OxlintSettings,
WEBSITE_BASE_RULES_URL,
config::GlobalValue,
disable_directives::DisableDirectives,
fixer::{Fix, FixKind, Message, PossibleFixes, RuleFix, RuleFixer},
frameworks::FrameworkOptions,
};
mod host;
pub use host::{ContextHost, ContextSubHost};
/// Contains all of the state and context specific to this lint rule.
///
/// Includes information like the rule name, plugin name, and severity of the rule.
/// It also has a reference to the shared linting data [`ContextHost`], which is the same for all rules.
#[derive(Clone)]
#[must_use]
pub struct LintContext<'a> {
/// Shared context independent of the rule being linted.
parent: Rc<ContextHost<'a>>,
/// Name of the plugin this rule belongs to. Example: `eslint`, `unicorn`, `react`
current_plugin_name: &'static str,
/// Prefixed version of the plugin name. Examples:
/// - `eslint-plugin-react`, for `react` plugin,
/// - `typescript-eslint`, for `typescript` plugin,
/// - `eslint-plugin-import`, for `import` plugin.
current_plugin_prefix: &'static str,
/// Kebab-cased name of the current rule being linted. Example: `no-unused-vars`, `no-undef`.
current_rule_name: &'static str,
/// Capabilities of the current rule to fix issues. Indicates whether:
/// - Rule cannot be auto-fixed [`RuleFixMeta::None`]
/// - Rule needs an auto-fix to be written still [`RuleFixMeta::FixPending`]
/// - Rule can be fixed in some cases [`RuleFixMeta::Conditional`]
/// - Rule is fully auto-fixable [`RuleFixMeta::Fixable`]
#[cfg(debug_assertions)]
current_rule_fix_capabilities: RuleFixMeta,
/// Current rule severity. Allows for user severity overrides, e.g.
/// ```json
/// // .oxlintrc.json
/// {
/// "rules": {
/// "no-debugger": "error"
/// }
/// }
/// ```
severity: Severity,
}
impl<'a> Deref for LintContext<'a> {
type Target = Semantic<'a>;
#[inline]
fn deref(&self) -> &Self::Target {
self.parent.semantic()
}
}
impl<'a> LintContext<'a> {
/// Set the plugin name for the current rule.
pub fn with_plugin_name(mut self, plugin: &'static str) -> Self {
self.current_plugin_name = plugin;
self.current_plugin_prefix = plugin_name_to_prefix(plugin);
self
}
/// Set the current rule name. Name should be kebab-cased like: `no-unused-vars` or `no-undef`.
pub fn with_rule_name(mut self, name: &'static str) -> Self {
self.current_rule_name = name;
self
}
/// Set the current rule fix capabilities. See [`RuleFixMeta`] for more information.
#[cfg(debug_assertions)]
pub fn with_rule_fix_capabilities(mut self, capabilities: RuleFixMeta) -> Self {
self.current_rule_fix_capabilities = capabilities;
self
}
/// Update the severity of diagnostics reported by the rule this context is
/// associated with.
#[inline]
pub fn with_severity(mut self, severity: AllowWarnDeny) -> Self {
self.severity = Severity::from(severity);
self
}
/// Get information such as the control flow graph, bound symbols, AST, etc.
/// for the file being linted.
///
/// Refer to [`Semantic`]'s documentation for more information.
#[inline]
pub fn semantic(&self) -> &Semantic<'a> {
self.parent.semantic()
}
#[inline]
pub fn module_record(&self) -> &ModuleRecord {
self.parent.module_record()
}
/// Get the control flow graph for the current program.
#[inline]
pub fn cfg(&self) -> &ControlFlowGraph {
// SAFETY: `LintContext::new` is the only way to construct a `LintContext` and we always
// assert the existence of control flow so it should always be `Some`.
unsafe { self.parent.semantic().cfg().unwrap_unchecked() }
}
/// List of all disable directives in the file being linted.
#[inline]
pub fn disable_directives(&self) -> &DisableDirectives {
self.parent.disable_directives()
}
/// Get a snippet of source text covered by the given [`Span`]. For details,
/// see [`Span::source_text`].
pub fn source_range(&self, span: Span) -> &'a str {
span.source_text(self.parent.semantic().source_text())
}
/// Finds the next occurrence of the given token in the source code,
/// starting from the specified position, skipping over comments.
#[expect(clippy::cast_possible_truncation)]
pub fn find_next_token_from(&self, start: u32, token: &str) -> Option<u32> {
let source =
self.source_range(Span::new(start, self.parent.semantic().source_text().len() as u32));
source
.match_indices(token)
.find(|(a, _)| !self.is_inside_comment(start + *a as u32))
.map(|(a, _)| a as u32)
}
/// Finds the previous occurrence of the given token in the source code,
/// starting from the specified position, skipping over comments.
#[expect(clippy::cast_possible_truncation)]
pub fn find_prev_token_from(&self, start: u32, token: &str) -> Option<u32> {
let source = self.source_range(Span::from(0..start));
source
.rmatch_indices(token)
.find(|(a, _)| !self.is_inside_comment(*a as u32))
.map(|(a, _)| a as u32)
}
/// Finds the next occurrence of the given token within a bounded span,
/// starting from the specified position, skipping over comments.
///
/// Returns the offset from `start` if the token is found before `end`,
/// otherwise returns `None`.
#[expect(clippy::cast_possible_truncation)]
pub fn find_next_token_within(&self, start: u32, end: u32, token: &str) -> Option<u32> {
let source = self.source_range(Span::new(start, end));
source
.match_indices(token)
.find(|(a, _)| !self.is_inside_comment(start + *a as u32))
.map(|(a, _)| a as u32)
}
/// Finds the previous occurrence of the given token within a bounded span,
/// starting from the specified position, skipping over comments.
///
/// Returns the offset from `start` if the token is found before `end`,
/// otherwise returns `None`.
#[expect(clippy::cast_possible_truncation)]
pub fn find_prev_token_within(&self, start: u32, end: u32, token: &str) -> Option<u32> {
let source = self.source_range(Span::new(start, end));
source
.rmatch_indices(token)
.find(|(a, _)| !self.is_inside_comment(start + *a as u32))
.map(|(a, _)| a as u32)
}
/// Path to the file currently being linted.
#[inline]
pub fn file_path(&self) -> &Path {
&self.parent.file_path
}
/// Extension of the file currently being linted, without the leading dot.
#[inline]
pub fn file_extension(&self) -> Option<&OsStr> {
self.parent.file_extension()
}
/// Plugin settings
#[inline]
pub fn settings(&self) -> &OxlintSettings {
&self.parent.config.settings
}
/// Sets of global variables that have been enabled or disabled.
#[inline]
pub fn globals(&self) -> &OxlintGlobals {
&self.parent.config.globals
}
/// Checks if the provided identifier is a reference to a global variable.
pub fn is_reference_to_global_variable(&self, ident: &IdentifierReference) -> bool {
let name = ident.name.as_str();
self.scoping().root_unresolved_references().contains_key(name)
&& !self.globals().get(name).is_some_and(|value| *value == GlobalValue::Off)
}
/// Checks if the provided identifier is a reference to a global variable.
pub fn get_global_variable_value(&self, name: &str) -> Option<GlobalValue> {
if !self.scoping().root_unresolved_references().contains_key(name) {
return None;
}
if let Some(value) = self.globals().get(name) {
return Some(*value);
}
self.get_env_global_entry(name)
}
/// Runtime environments turned on/off by the user.
///
/// Examples of environments are `builtin`, `browser`, `node`, etc.
#[inline]
pub fn env(&self) -> &OxlintEnv {
&self.parent.config.env
}
fn get_env_global_entry(&self, var: &str) -> Option<GlobalValue> {
// builtin is always readonly
if GLOBALS["builtin"].contains_key(var) {
return Some(GlobalValue::Readonly);
}
for env in self.env().iter() {
if let Some(env) = GLOBALS.get(env)
&& let Some(value) = env.get(var)
{
return Some(GlobalValue::from(*value));
}
}
None
}
/// Checks if a given variable named is defined as a global variable in the current environment.
///
/// Example:
/// - `is_global_defined("Date")` returns `true` because it is a global builtin in all environments.
/// - `is_global_defined("HTMLElement")` returns `true` only if the `browser` environment is enabled.
/// - `is_global_defined("globalThis")` returns `true` only if the `es2020` environment or higher is enabled.
/// - `is_global_defined("myGlobalVar")` returns `true` only if it is defined in the `globals` section as a non "off" value.
pub fn is_global_defined(&self, var: &str) -> bool {
if !self.scoping().root_unresolved_references().contains_key(var) {
return false;
}
if self.globals().is_enabled(var) {
return true;
}
self.env_contains_var(var)
}
pub fn is_ecma_script_global(&self, var: &str) -> bool {
if !self.scoping().root_unresolved_references().contains_key(var) {
return false;
}
GLOBALS["es2026"].contains_key(var) || GLOBALS["builtin"].contains_key(var)
}
fn env_contains_var(&self, var: &str) -> bool {
if GLOBALS["builtin"].contains_key(var) {
return true;
}
for env in self.env().iter() {
if let Some(env) = GLOBALS.get(env)
&& env.contains_key(var)
{
return true;
}
}
false
}
/* Diagnostics */
/// Add a diagnostic message to the list of diagnostics. Outputs a diagnostic with the current rule
/// name, severity, and a link to the rule's documentation URL.
fn add_diagnostic(&self, mut message: Message) {
if self.parent.disable_directives().contains(self.current_rule_name, message.span) {
return;
}
message.error = message
.error
.with_error_code(self.current_plugin_prefix, self.current_rule_name)
.with_url(format!(
"{}/{}/{}.html",
WEBSITE_BASE_RULES_URL, self.current_plugin_name, self.current_rule_name
));
if message.error.severity != self.severity {
message.error = message.error.with_severity(self.severity);
}
self.parent.push_diagnostic(message);
}
/// Report a lint rule violation.
///
/// Use [`LintContext::diagnostic_with_fix`] to provide an automatic fix.
#[inline]
pub fn diagnostic(&self, diagnostic: OxcDiagnostic) {
self.add_diagnostic(
Message::new(diagnostic, PossibleFixes::None)
.with_section_offset(self.parent.current_sub_host().source_text_offset),
);
}
/// Report a lint rule violation and provide an automatic fix.
///
/// The second argument is a [closure] that takes a [`RuleFixer`] and
/// returns something that can turn into a `CompositeFix`.
///
/// Fixes created this way should not create parse errors or change the
/// semantics of the linted code. If your fix may change the code's
/// semantics, use [`LintContext::diagnostic_with_suggestion`] instead. If
/// your fix has the potential to create parse errors, use
/// [`LintContext::diagnostic_with_dangerous_fix`].
///
/// [closure]: <https://doc.rust-lang.org/book/ch13-01-closures.html>
#[inline]
pub fn diagnostic_with_fix<C, F>(&self, diagnostic: OxcDiagnostic, fix: F)
where
C: Into<RuleFix>,
F: FnOnce(RuleFixer<'_, 'a>) -> C,
{
self.diagnostic_with_fix_of_kind(diagnostic, FixKind::SafeFix, fix);
}
/// Report a lint rule violation and provide a suggestion for fixing it.
///
/// The second argument is a [closure] that takes a [`RuleFixer`] and
/// returns something that can turn into a `CompositeFix`.
///
/// Fixes created this way should not create parse errors, but have the
/// potential to change the code's semantics. If your fix is completely safe
/// and definitely does not change semantics, use [`LintContext::diagnostic_with_fix`].
/// If your fix has the potential to create parse errors, use
/// [`LintContext::diagnostic_with_dangerous_fix`].
///
/// [closure]: <https://doc.rust-lang.org/book/ch13-01-closures.html>
#[inline]
pub fn diagnostic_with_suggestion<C, F>(&self, diagnostic: OxcDiagnostic, fix: F)
where
C: Into<RuleFix>,
F: FnOnce(RuleFixer<'_, 'a>) -> C,
{
self.diagnostic_with_fix_of_kind(diagnostic, FixKind::Suggestion, fix);
}
/// Report a lint rule violation and provide a suggestion for fixing it.
///
/// The second argument is a [closure] that takes a [`RuleFixer`] and
/// returns something that can turn into a `CompositeFix`.
///
/// Fixes created this way should not create parse errors, but have the
/// potential to change the code's semantics. If your fix is completely safe
/// and definitely does not change semantics, use [`LintContext::diagnostic_with_fix`].
/// If your fix has the potential to create parse errors, use
/// [`LintContext::diagnostic_with_dangerous_fix`].
///
/// [closure]: <https://doc.rust-lang.org/book/ch13-01-closures.html>
#[inline]
pub fn diagnostic_with_dangerous_suggestion<C, F>(&self, diagnostic: OxcDiagnostic, fix: F)
where
C: Into<RuleFix>,
F: FnOnce(RuleFixer<'_, 'a>) -> C,
{
self.diagnostic_with_fix_of_kind(diagnostic, FixKind::DangerousSuggestion, fix);
}
/// Report a lint rule violation and provide a potentially dangerous
/// automatic fix for it.
///
/// The second argument is a [closure] that takes a [`RuleFixer`] and
/// returns something that can turn into a `CompositeFix`.
///
/// Dangerous fixes should be avoided and are not applied by default with
/// `--fix`. Use this method if:
/// - Your fix is experimental and you want to test it out in the wild
/// before marking it as safe.
/// - Your fix is extremely aggressive and risky, but you want to provide
/// it as an option to users.
///
/// When possible, prefer [`LintContext::diagnostic_with_fix`]. If the only
/// risk your fix poses is minor(ish) changes to code semantics, use
/// [`LintContext::diagnostic_with_suggestion`] instead.
///
/// [closure]: <https://doc.rust-lang.org/book/ch13-01-closures.html>
///
#[inline]
pub fn diagnostic_with_dangerous_fix<C, F>(&self, diagnostic: OxcDiagnostic, fix: F)
where
C: Into<RuleFix>,
F: FnOnce(RuleFixer<'_, 'a>) -> C,
{
self.diagnostic_with_fix_of_kind(diagnostic, FixKind::DangerousFix, fix);
}
/// Report a lint rule violation and provide an automatic fix of a specific kind.
///
/// The second argument is a [closure] that takes a [`RuleFixer`] and
/// returns something that can turn into a [`RuleFix`].
///
/// [closure]: <https://doc.rust-lang.org/book/ch13-01-closures.html>
pub fn diagnostic_with_fix_of_kind<C, F>(
&self,
diagnostic: OxcDiagnostic,
fix_kind: FixKind,
fix: F,
) where
C: Into<RuleFix>,
F: FnOnce(RuleFixer<'_, 'a>) -> C,
{
let (diagnostic, fix) = self.create_fix(fix_kind, fix, diagnostic);
if let Some(fix) = fix {
self.add_diagnostic(
Message::new(diagnostic, PossibleFixes::Single(fix))
.with_section_offset(self.parent.current_sub_host().source_text_offset),
);
} else {
self.diagnostic(diagnostic);
}
}
/// Report a lint rule violation and provide an automatic fix of a specific kind.
/// This method is used when the rule can provide multiple fixes for the same diagnostic.
pub fn diagnostics_with_multiple_fixes<C, F1, F2>(
&self,
diagnostic: OxcDiagnostic,
fix_one: (FixKind, F1),
fix_two: (FixKind, F2),
) where
C: Into<RuleFix>,
F1: FnOnce(RuleFixer<'_, 'a>) -> C,
F2: FnOnce(RuleFixer<'_, 'a>) -> C,
{
let fixes_result: Vec<Fix> = vec![
self.create_fix(fix_one.0, fix_one.1, diagnostic.clone()).1,
self.create_fix(fix_two.0, fix_two.1, diagnostic.clone()).1,
]
.into_iter()
.flatten()
.collect();
if fixes_result.is_empty() {
self.diagnostic(diagnostic);
} else {
self.add_diagnostic(
Message::new(diagnostic, PossibleFixes::Multiple(fixes_result))
.with_section_offset(self.parent.current_sub_host().source_text_offset),
);
}
}
/// Report a lint rule violation and provide multiple suggestions for fixing it.
///
/// The second argument is an iterator of [`RuleFix`] values representing
/// the available suggestions.
///
/// Use this when a rule violation can be fixed in multiple ways and the user
/// should choose which fix to apply.
pub fn diagnostic_with_suggestions<I>(&self, diagnostic: OxcDiagnostic, suggestions: I)
where
I: IntoIterator<Item = RuleFix>,
{
let fixes_result: Vec<Fix> = suggestions
.into_iter()
.filter_map(|rule_fix| {
#[cfg(debug_assertions)]
debug_assert!(
self.current_rule_fix_capabilities.supports_fix(rule_fix.kind()),
"Rule `{}` does not support this fix kind. Did you forget to update fix capabilities in declare_oxc_lint?.\n\tSupported fix kinds: {:?}\n\tAttempted fix kind: {:?}",
self.current_rule_name,
FixKind::from(self.current_rule_fix_capabilities),
rule_fix.kind()
);
if self.parent.fix.can_apply(rule_fix.kind()) && !rule_fix.is_empty() {
Some(rule_fix.into_fix(self.source_text()))
} else {
None
}
})
.collect();
if fixes_result.is_empty() {
self.diagnostic(diagnostic);
} else {
self.add_diagnostic(
Message::new(diagnostic, PossibleFixes::Multiple(fixes_result))
.with_section_offset(self.parent.current_sub_host().source_text_offset),
);
}
}
fn create_fix<C, F>(
&self,
fix_kind: FixKind,
fix: F,
diagnostic: OxcDiagnostic,
) -> (OxcDiagnostic, Option<Fix>)
where
C: Into<RuleFix>,
F: FnOnce(RuleFixer<'_, 'a>) -> C,
{
let fixer = RuleFixer::new(fix_kind, self);
let rule_fix: RuleFix = fix(fixer).into();
#[cfg(debug_assertions)]
debug_assert!(
self.current_rule_fix_capabilities.supports_fix(fix_kind),
"Rule `{}` does not support safe fixes. Did you forget to update fix capabilities in declare_oxc_lint?.\n\tSupported fix kinds: {:?}\n\tAttempted fix kind: {:?}",
self.current_rule_name,
FixKind::from(self.current_rule_fix_capabilities),
rule_fix.kind()
);
let diagnostic = match (rule_fix.message(), &diagnostic.help) {
(Some(message), None) => diagnostic.with_help(message.to_owned()),
_ => diagnostic,
};
if self.parent.fix.can_apply(rule_fix.kind()) && !rule_fix.is_empty() {
let fix = rule_fix.into_fix(self.source_text());
#[cfg(debug_assertions)]
{
if fix.span.size() > 1 {
debug_assert!(
fix.message.as_ref().is_some_and(|msg| !msg.is_empty()),
"Rule `{}/{}` fix should have a message for a complex fix. Did you forget to add a message?\n Source text: {:?}\n Fixed text: {:?}\nhelp: You can add a message to a fix with `RuleFix.with_message()`",
self.current_plugin_name,
self.current_rule_name,
self.source_range(fix.span),
fix.content
);
}
}
(diagnostic, Some(fix))
} else {
(diagnostic, None)
}
}
/// Framework flags, indicating front-end frameworks that might be in use.
pub fn frameworks(&self) -> FrameworkFlags {
self.parent.frameworks
}
/// Returns the framework options for the current script block.
/// For Vue files, this can be `FrameworkOptions::VueSetup` if we're in a `<script setup>` block.
pub fn frameworks_options(&self) -> FrameworkOptions {
self.parent.frameworks_options()
}
pub fn other_file_hosts(&self) -> Vec<&ContextSubHost<'a>> {
self.parent.other_file_hosts()
}
}
/// Gets the prefixed plugin name, given the short plugin name.
///
/// Example:
///
/// ```text
/// assert_eq!(plugin_name_to_prefix("react"), "eslint-plugin-react");
/// ```
#[inline]
fn plugin_name_to_prefix(plugin_name: &'static str) -> &'static str {
match plugin_name {
"import" => "eslint-plugin-import",
"jest" => "eslint-plugin-jest",
"jsdoc" => "eslint-plugin-jsdoc",
"jsx_a11y" => "eslint-plugin-jsx-a11y",
"nextjs" => "eslint-plugin-next",
"promise" => "eslint-plugin-promise",
"react_perf" => "eslint-plugin-react-perf",
"react" => "eslint-plugin-react",
"typescript" => "typescript-eslint",
"unicorn" => "eslint-plugin-unicorn",
"vitest" => "eslint-plugin-vitest",
"node" => "eslint-plugin-node",
"vue" => "eslint-plugin-vue",
_ => plugin_name,
}
}