diff --git a/crates/oxc/src/compiler.rs b/crates/oxc/src/compiler.rs index ab0b20eeb05a3..9a5af6bfc62a3 100644 --- a/crates/oxc/src/compiler.rs +++ b/crates/oxc/src/compiler.rs @@ -5,11 +5,10 @@ use oxc_ast::{ast::Program, Trivias}; use oxc_codegen::{CodeGenerator, CodegenOptions, CommentOptions}; use oxc_diagnostics::OxcDiagnostic; use oxc_mangler::{MangleOptions, Mangler}; -use oxc_parser::{ParseOptions, Parser, ParserReturn}; -use oxc_span::SourceType; - use oxc_minifier::{CompressOptions, Compressor}; +use oxc_parser::{ParseOptions, Parser, ParserReturn}; use oxc_semantic::{ScopeTree, SemanticBuilder, SemanticBuilderReturn, SymbolTable}; +use oxc_span::SourceType; use oxc_transformer::{TransformOptions, Transformer, TransformerReturn}; #[derive(Default)] diff --git a/crates/oxc_allocator/src/boxed.rs b/crates/oxc_allocator/src/boxed.rs index a334d5cc1d9ac..58a8d230dc243 100644 --- a/crates/oxc_allocator/src/boxed.rs +++ b/crates/oxc_allocator/src/boxed.rs @@ -124,9 +124,8 @@ impl<'a, T> Box<'a, T> { mod test { use std::hash::{DefaultHasher, Hash, Hasher}; - use crate::Allocator; - use super::Box; + use crate::Allocator; #[test] fn box_deref_mut() { diff --git a/crates/oxc_allocator/src/clone_in.rs b/crates/oxc_allocator/src/clone_in.rs index bca581f860136..79d1a6364ca59 100644 --- a/crates/oxc_allocator/src/clone_in.rs +++ b/crates/oxc_allocator/src/clone_in.rs @@ -30,6 +30,7 @@ where T: CloneIn<'alloc, Cloned = C>, { type Cloned = Option; + fn clone_in(&self, allocator: &'alloc Allocator) -> Self::Cloned { self.as_ref().map(|it| it.clone_in(allocator)) } @@ -40,6 +41,7 @@ where T: CloneIn<'new_alloc, Cloned = C>, { type Cloned = Box<'new_alloc, C>; + fn clone_in(&self, allocator: &'new_alloc Allocator) -> Self::Cloned { Box::new_in(self.as_ref().clone_in(allocator), allocator) } @@ -50,6 +52,7 @@ where T: CloneIn<'new_alloc, Cloned = C>, { type Cloned = Vec<'new_alloc, C>; + fn clone_in(&self, allocator: &'new_alloc Allocator) -> Self::Cloned { Vec::from_iter_in(self.iter().map(|it| it.clone_in(allocator)), allocator) } @@ -57,6 +60,7 @@ where impl<'alloc, T: Copy> CloneIn<'alloc> for Cell { type Cloned = Cell; + fn clone_in(&self, _: &'alloc Allocator) -> Self::Cloned { Cell::new(self.get()) } @@ -64,6 +68,7 @@ impl<'alloc, T: Copy> CloneIn<'alloc> for Cell { impl<'old_alloc, 'new_alloc> CloneIn<'new_alloc> for &'old_alloc str { type Cloned = &'new_alloc str; + fn clone_in(&self, allocator: &'new_alloc Allocator) -> Self::Cloned { allocator.alloc_str(self) } diff --git a/crates/oxc_allocator/src/vec.rs b/crates/oxc_allocator/src/vec.rs index a31e927c6e0ed..6220bbf23fd57 100644 --- a/crates/oxc_allocator/src/vec.rs +++ b/crates/oxc_allocator/src/vec.rs @@ -123,9 +123,8 @@ impl<'alloc, T: Hash> Hash for Vec<'alloc, T> { #[cfg(test)] mod test { - use crate::Allocator; - use super::Vec; + use crate::Allocator; #[test] fn vec_debug() { diff --git a/crates/oxc_ast/src/ast/js.rs b/crates/oxc_ast/src/ast/js.rs index 91be58de65ef7..15b58056816b7 100644 --- a/crates/oxc_ast/src/ast/js.rs +++ b/crates/oxc_ast/src/ast/js.rs @@ -18,15 +18,13 @@ use oxc_syntax::{ scope::ScopeId, symbol::SymbolId, }; - -use super::macros::inherit_variants; -use super::*; - #[cfg(feature = "serialize")] use serde::Serialize; #[cfg(feature = "serialize")] use tsify::Tsify; +use super::{macros::inherit_variants, *}; + /// Represents the root of a JavaScript abstract syntax tree (AST), containing metadata about the source, directives, top-level statements, and scope information. #[ast(visit)] #[scope( diff --git a/crates/oxc_ast/src/ast/mod.rs b/crates/oxc_ast/src/ast/mod.rs index a02fbf82d51de..3370e1c231408 100644 --- a/crates/oxc_ast/src/ast/mod.rs +++ b/crates/oxc_ast/src/ast/mod.rs @@ -182,9 +182,6 @@ pub(crate) mod macros; pub(crate) mod ts; use macros::inherit_variants; - -pub use self::{js::*, jsx::*, literal::*, ts::*}; - // Re-export AST types from other crates pub use oxc_span::{Atom, Language, LanguageVariant, ModuleKind, SourceType, Span}; pub use oxc_syntax::{ @@ -193,3 +190,5 @@ pub use oxc_syntax::{ AssignmentOperator, BinaryOperator, LogicalOperator, UnaryOperator, UpdateOperator, }, }; + +pub use self::{js::*, jsx::*, literal::*, ts::*}; diff --git a/crates/oxc_ast/src/ast_impl/js.rs b/crates/oxc_ast/src/ast_impl/js.rs index f9f198d35dc39..e487e9773fadd 100644 --- a/crates/oxc_ast/src/ast_impl/js.rs +++ b/crates/oxc_ast/src/ast_impl/js.rs @@ -1,5 +1,3 @@ -use crate::ast::*; - use std::{borrow::Cow, cell::Cell, fmt}; use oxc_allocator::{Box, FromIn, Vec}; @@ -8,6 +6,8 @@ use oxc_syntax::{ operator::UnaryOperator, reference::ReferenceId, scope::ScopeFlags, symbol::SymbolId, }; +use crate::ast::*; + #[cfg(feature = "serialize")] #[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)] const TS_APPEND_CONTENT: &'static str = r#" @@ -1079,6 +1079,7 @@ impl<'a> FormalParameters<'a> { pub fn is_empty(&self) -> bool { self.items.is_empty() } + pub fn has_parameter(&self) -> bool { !self.is_empty() || self.rest.is_some() } @@ -1427,6 +1428,7 @@ impl<'a> ImportDeclarationSpecifier<'a> { ImportDeclarationSpecifier::ImportDefaultSpecifier(specifier) => &specifier.local, } } + pub fn name(&self) -> Cow<'a, str> { Cow::Borrowed(self.local().name.as_str()) } diff --git a/crates/oxc_ast/src/ast_impl/jsx.rs b/crates/oxc_ast/src/ast_impl/jsx.rs index e62f6640fa514..d8b6503b1b814 100644 --- a/crates/oxc_ast/src/ast_impl/jsx.rs +++ b/crates/oxc_ast/src/ast_impl/jsx.rs @@ -1,9 +1,11 @@ //! [JSX](https://facebook.github.io/jsx) -use crate::ast::*; -use oxc_span::{Atom, Span}; use std::fmt; +use oxc_span::{Atom, Span}; + +use crate::ast::*; + // 1.2 JSX Elements impl<'a> JSXIdentifier<'a> { @@ -91,6 +93,7 @@ impl<'a> JSXAttributeName<'a> { Self::NamespacedName(_) => None, } } + pub fn get_identifier(&self) -> &JSXIdentifier<'a> { match self { Self::Identifier(ident) => ident.as_ref(), diff --git a/crates/oxc_ast/src/ast_impl/literal.rs b/crates/oxc_ast/src/ast_impl/literal.rs index 3d968a433d3a0..982fecdaed1d6 100644 --- a/crates/oxc_ast/src/ast_impl/literal.rs +++ b/crates/oxc_ast/src/ast_impl/literal.rs @@ -3,8 +3,6 @@ // Silence erroneous warnings from Rust Analyser for `#[derive(Tsify)]` #![allow(non_snake_case)] -use crate::ast::*; - use std::{ borrow::Cow, fmt, @@ -16,6 +14,8 @@ use oxc_regular_expression::ast::Pattern; use oxc_span::{cmp::ContentEq, hash::ContentHash, Atom, Span}; use oxc_syntax::number::NumberBase; +use crate::ast::*; + impl BooleanLiteral { pub fn new(span: Span, value: bool) -> Self { Self { span, value } @@ -187,6 +187,7 @@ impl ContentHash for RegExpFlags { impl<'alloc> CloneIn<'alloc> for RegExpFlags { type Cloned = Self; + fn clone_in(&self, _: &'alloc oxc_allocator::Allocator) -> Self::Cloned { *self } diff --git a/crates/oxc_ast/src/lib.rs b/crates/oxc_ast/src/lib.rs index e8cc9c1bd4e14..72469eef6623e 100644 --- a/crates/oxc_ast/src/lib.rs +++ b/crates/oxc_ast/src/lib.rs @@ -51,13 +51,10 @@ mod generated { } pub mod visit { - pub use crate::generated::visit::*; - pub use crate::generated::visit_mut::*; + pub use crate::generated::{visit::*, visit_mut::*}; } -pub use generated::ast_builder; -pub use generated::ast_kind; - +pub use generated::{ast_builder, ast_kind}; pub use num_bigint::BigUint; pub use crate::{ diff --git a/crates/oxc_codegen/src/annotation_comment.rs b/crates/oxc_codegen/src/annotation_comment.rs index 1525692f2abcb..257ffebce4dbf 100644 --- a/crates/oxc_codegen/src/annotation_comment.rs +++ b/crates/oxc_codegen/src/annotation_comment.rs @@ -34,6 +34,7 @@ impl AnnotationComment { pub fn span(&self) -> Span { self.comment.span } + pub fn kind(&self) -> CommentKind { self.comment.kind } diff --git a/crates/oxc_codegen/src/binary_expr_visitor.rs b/crates/oxc_codegen/src/binary_expr_visitor.rs index 1165ad8ca8481..8f48c8ed6f152 100644 --- a/crates/oxc_codegen/src/binary_expr_visitor.rs +++ b/crates/oxc_codegen/src/binary_expr_visitor.rs @@ -4,8 +4,10 @@ use std::ops::Not; use oxc_ast::ast::{BinaryExpression, Expression, LogicalExpression}; -use oxc_syntax::operator::{BinaryOperator, LogicalOperator}; -use oxc_syntax::precedence::{GetPrecedence, Precedence}; +use oxc_syntax::{ + operator::{BinaryOperator, LogicalOperator}, + precedence::{GetPrecedence, Precedence}, +}; use crate::{ gen::{Gen, GenExpr}, diff --git a/crates/oxc_codegen/src/lib.rs b/crates/oxc_codegen/src/lib.rs index 6f977574e3eb8..c2516e0a14d2c 100644 --- a/crates/oxc_codegen/src/lib.rs +++ b/crates/oxc_codegen/src/lib.rs @@ -25,6 +25,7 @@ use oxc_syntax::{ }; use rustc_hash::FxHashMap; +use self::annotation_comment::AnnotationComment; use crate::{ binary_expr_visitor::BinaryExpressionVisitor, operator::Operator, sourcemap_builder::SourcemapBuilder, @@ -34,8 +35,6 @@ pub use crate::{ gen::{Gen, GenExpr}, }; -use self::annotation_comment::AnnotationComment; - /// Code generator without whitespace removal. pub type CodeGenerator<'a> = Codegen<'a>; @@ -563,6 +562,7 @@ impl<'a> Codegen<'a> { ) -> impl DoubleEndedIterator + '_ { self.trivias.comments_range(start..end) } + /// In some scenario, we want to move the comment that should be codegened to another position. /// ```js /// /* @__NO_SIDE_EFFECTS__ */ export const a = function() { diff --git a/crates/oxc_codegen/src/sourcemap_builder.rs b/crates/oxc_codegen/src/sourcemap_builder.rs index f8142321ecf78..31ddb113d7588 100644 --- a/crates/oxc_codegen/src/sourcemap_builder.rs +++ b/crates/oxc_codegen/src/sourcemap_builder.rs @@ -1,7 +1,6 @@ use std::sync::Arc; use nonmax::NonMaxU32; - use oxc_index::{Idx, IndexVec}; use oxc_span::Span; use oxc_syntax::identifier::{LS, PS}; diff --git a/crates/oxc_codegen/tests/integration/esbuild.rs b/crates/oxc_codegen/tests/integration/esbuild.rs index 73ca1c5d5df58..0b52ce294304b 100644 --- a/crates/oxc_codegen/tests/integration/esbuild.rs +++ b/crates/oxc_codegen/tests/integration/esbuild.rs @@ -990,16 +990,26 @@ fn test_avoid_slash_script() { test("/*! \";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/script\"])));\n"); - test( "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/script\", \"\"])), a);\n"); - test( "String.raw`${a}\";\nvar _a;\nString.raw(_a || (_a = __template([\"\", \"<\\/script\"])), a);\n"); - test( "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/SCRIPT\"])));\n"); - test( "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/ScRiPt\"])));\n"); + test( + "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/script\"])));\n", + ); + test( + "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/script\", \"\"])), a);\n", + ); + test( + "String.raw`${a}\";\nvar _a;\nString.raw(_a || (_a = __template([\"\", \"<\\/script\"])), a);\n", + ); + test( + "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/SCRIPT\"])));\n", + ); + test( + "String.raw`\";\nvar _a;\nString.raw(_a || (_a = __template([\"<\\/ScRiPt\"])));\n", + ); // Negative cases test("x = ';", "d = x satisfies y;", "export @x declare abstract class C {}", - "div``" + "div``", ]; let snapshot = cases.into_iter().fold(String::new(), |mut w, case| { diff --git a/crates/oxc_diagnostics/src/lib.rs b/crates/oxc_diagnostics/src/lib.rs index 8f14a93bbd2be..1b837344b040a 100644 --- a/crates/oxc_diagnostics/src/lib.rs +++ b/crates/oxc_diagnostics/src/lib.rs @@ -108,6 +108,7 @@ impl Diagnostic for OxcDiagnostic { fn code<'a>(&'a self) -> Option> { self.code.is_some().then(|| Box::new(&self.code) as Box) } + fn url<'a>(&'a self) -> Option> { self.url.as_ref().map(Box::new).map(|c| c as Box) } diff --git a/crates/oxc_index/src/rayon_impl.rs b/crates/oxc_index/src/rayon_impl.rs index 36cc42e251346..fcd18c756674b 100644 --- a/crates/oxc_index/src/rayon_impl.rs +++ b/crates/oxc_index/src/rayon_impl.rs @@ -3,19 +3,21 @@ #![allow(clippy::manual_assert)] /// Disabled lint since we copy code from https://github.com/rayon-rs/rayon/blob/97c1133c2366a301a2d4ab35cf686bca7f74830f/src/vec.rs#L1-L284 use alloc::vec::Vec; -use core::iter; -use core::mem; -use core::ops::{Range, RangeBounds}; -use core::ptr; -use core::slice; -use rayon::iter::plumbing::{bridge, Consumer, Producer, ProducerCallback, UnindexedConsumer}; -use rayon::iter::{ - IndexedParallelIterator, IntoParallelIterator, ParallelDrainRange, ParallelIterator, +use core::{ + iter, mem, + ops::{Range, RangeBounds}, + ptr, slice, }; -use rayon::slice::{Iter, IterMut}; -use crate::Idx; -use crate::IndexVec; +use rayon::{ + iter::{ + plumbing::{bridge, Consumer, Producer, ProducerCallback, UnindexedConsumer}, + IndexedParallelIterator, IntoParallelIterator, ParallelDrainRange, ParallelIterator, + }, + slice::{Iter, IterMut}, +}; + +use crate::{Idx, IndexVec}; impl<'data, I: Idx, T: Sync + 'data> IntoParallelIterator for &'data IndexVec { type Item = &'data T; @@ -87,8 +89,8 @@ impl IndexedParallelIterator for IntoIter { } impl<'data, I: Idx, T: Send> ParallelDrainRange for &'data mut IndexVec { - type Iter = Drain<'data, T>; type Item = T; + type Iter = Drain<'data, T>; fn par_drain>(self, range: R) -> Self::Iter { Drain { orig_len: self.len(), range: simplify_range(range, self.len()), vec: &mut self.raw } @@ -202,8 +204,8 @@ impl DrainProducer<'_, T> { } impl<'data, T: 'data + Send> Producer for DrainProducer<'data, T> { - type Item = T; type IntoIter = SliceDrain<'data, T>; + type Item = T; fn into_iter(mut self) -> Self::IntoIter { // replace the slice so we don't drop it twice diff --git a/crates/oxc_isolated_declarations/tests/deno/mod.rs b/crates/oxc_isolated_declarations/tests/deno/mod.rs index fcfea244053eb..2f9f110837eeb 100644 --- a/crates/oxc_isolated_declarations/tests/deno/mod.rs +++ b/crates/oxc_isolated_declarations/tests/deno/mod.rs @@ -223,15 +223,15 @@ export function foo(a: any): number { ); transform_dts_test( - "export const foo = { str: \"bar\", bool: true, bool2: false, num: 42, nullish: null } as const;", - "export declare const foo: { + "export const foo = { str: \"bar\", bool: true, bool2: false, num: 42, nullish: null } as const;", + "export declare const foo: { readonly str: \"bar\"; readonly bool: true; readonly bool2: false; readonly num: 42; readonly nullish: null; };", - ); + ); transform_dts_test( "export const foo = { str: [1, 2] as const } as const;", diff --git a/crates/oxc_linter/src/ast_util.rs b/crates/oxc_linter/src/ast_util.rs index a501edc92862a..ea398211e5b92 100644 --- a/crates/oxc_linter/src/ast_util.rs +++ b/crates/oxc_linter/src/ast_util.rs @@ -1,7 +1,6 @@ use core::hash::Hasher; -use oxc_ast::ast::BindingIdentifier; -use oxc_ast::AstKind; +use oxc_ast::{ast::BindingIdentifier, AstKind}; use oxc_semantic::{AstNode, AstNodeId, SymbolId}; use oxc_span::{hash::ContentHash, GetSpan, Span}; use oxc_syntax::operator::{AssignmentOperator, BinaryOperator, LogicalOperator, UnaryOperator}; diff --git a/crates/oxc_linter/src/config/env.rs b/crates/oxc_linter/src/config/env.rs index ee1bd9e6c871a..02ca9aebe0df7 100644 --- a/crates/oxc_linter/src/config/env.rs +++ b/crates/oxc_linter/src/config/env.rs @@ -1,7 +1,8 @@ +use std::{borrow::Borrow, hash::Hash}; + use rustc_hash::FxHashMap; use schemars::JsonSchema; use serde::Deserialize; -use std::{borrow::Borrow, hash::Hash}; /// Predefine global variables. /// diff --git a/crates/oxc_linter/src/config/globals.rs b/crates/oxc_linter/src/config/globals.rs index 0b7440ab2e0ae..419703bb994bb 100644 --- a/crates/oxc_linter/src/config/globals.rs +++ b/crates/oxc_linter/src/config/globals.rs @@ -1,7 +1,8 @@ +use std::{borrow, fmt, hash}; + use rustc_hash::FxHashMap; use schemars::JsonSchema; use serde::{de::Visitor, Deserialize}; -use std::{borrow, fmt, hash}; /// Add or remove global variables. /// @@ -122,9 +123,10 @@ impl<'de> Visitor<'de> for GlobalValueVisitor { #[cfg(test)] mod test { - use super::*; use serde_json::json; + use super::*; + macro_rules! globals { ($($json:tt)+) => { OxlintGlobals::deserialize(&json!($($json)+)).unwrap() diff --git a/crates/oxc_linter/src/config/mod.rs b/crates/oxc_linter/src/config/mod.rs index 816fe04a87814..9e1b7d424cad7 100644 --- a/crates/oxc_linter/src/config/mod.rs +++ b/crates/oxc_linter/src/config/mod.rs @@ -195,9 +195,8 @@ mod test { use rustc_hash::FxHashSet; use serde::Deserialize; - use crate::rules::RULES; - use super::OxlintConfig; + use crate::rules::RULES; #[test] fn test_from_file() { diff --git a/crates/oxc_linter/src/config/settings/jsdoc.rs b/crates/oxc_linter/src/config/settings/jsdoc.rs index 8b1c47c10203d..50b0a0314771c 100644 --- a/crates/oxc_linter/src/config/settings/jsdoc.rs +++ b/crates/oxc_linter/src/config/settings/jsdoc.rs @@ -1,10 +1,11 @@ use std::borrow::Cow; -use crate::utils::default_true; use rustc_hash::FxHashMap; use schemars::JsonSchema; use serde::Deserialize; +use crate::utils::default_true; + // #[derive(Debug, Deserialize, JsonSchema)] pub struct JSDocPluginSettings { @@ -196,9 +197,10 @@ enum TagNamePreference { #[cfg(test)] mod test { - use serde::Deserialize; use std::borrow::Cow; + use serde::Deserialize; + use super::JSDocPluginSettings; #[test] diff --git a/crates/oxc_linter/src/config/settings/mod.rs b/crates/oxc_linter/src/config/settings/mod.rs index e3ff653e8119e..9d61c49c08852 100644 --- a/crates/oxc_linter/src/config/settings/mod.rs +++ b/crates/oxc_linter/src/config/settings/mod.rs @@ -35,9 +35,8 @@ mod test { use oxc_span::CompactStr; use serde::Deserialize; - use crate::config::settings::react::ComponentAttrs; - use super::OxlintSettings; + use crate::config::settings::react::ComponentAttrs; fn as_attrs, I: IntoIterator>( attrs: I, diff --git a/crates/oxc_linter/src/config/settings/react.rs b/crates/oxc_linter/src/config/settings/react.rs index 71fec9c9468ea..eeed7115f0c07 100644 --- a/crates/oxc_linter/src/config/settings/react.rs +++ b/crates/oxc_linter/src/config/settings/react.rs @@ -53,7 +53,7 @@ fn get_component_attrs_by_name<'c>( for item in components { match item { CustomComponent::NameOnly(comp_name) if comp_name == name => { - return Some(Cow::Owned(vec![])) + return Some(Cow::Owned(vec![])); } CustomComponent::ObjectWithOneAttr { name: comp_name, attribute } if comp_name == name => diff --git a/crates/oxc_linter/src/context.rs b/crates/oxc_linter/src/context.rs index 941066f0eb0fc..2acf631e493e0 100644 --- a/crates/oxc_linter/src/context.rs +++ b/crates/oxc_linter/src/context.rs @@ -62,6 +62,7 @@ pub struct LintContext<'a> { impl<'a> LintContext<'a> { const WEBSITE_BASE_URL: &'static str = "https://oxc.rs/docs/guide/usage/linter/rules"; + /// # Panics /// If `semantic.cfg()` is `None`. pub fn new(file_path: Box, semantic: Rc>) -> Self { diff --git a/crates/oxc_linter/src/fixer/fix.rs b/crates/oxc_linter/src/fixer/fix.rs index 9d42dd7b9b841..37d5f25ee46e4 100644 --- a/crates/oxc_linter/src/fixer/fix.rs +++ b/crates/oxc_linter/src/fixer/fix.rs @@ -261,6 +261,7 @@ impl GetSpan for RuleFix<'_> { impl<'a> Deref for RuleFix<'a> { type Target = CompositeFix<'a>; + fn deref(&self) -> &Self::Target { &self.fix } @@ -407,7 +408,10 @@ impl<'a> CompositeFix<'a> { Self::None => 0, Self::Single(_) => 1, Self::Multiple(fs) => { - debug_assert!(fs.len() > 1, "Single-element or empty composite fix vecs should have been turned into CompositeFix::None or CompositeFix::Single"); + debug_assert!( + fs.len() > 1, + "Single-element or empty composite fix vecs should have been turned into CompositeFix::None or CompositeFix::Single" + ); fs.len() } } @@ -427,6 +431,7 @@ impl<'a> CompositeFix<'a> { } } } + // TODO: do we want this? // pub fn extend(&mut self, fix: CompositeFix<'a>) { // match self { @@ -460,6 +465,7 @@ impl<'a> CompositeFix<'a> { CompositeFix::None => Fix::empty(), } } + /// Merges multiple fixes to one, returns an [`Fix::empty`] (which will not fix anything) if: /// /// 1. `fixes` is empty diff --git a/crates/oxc_linter/src/fixer/mod.rs b/crates/oxc_linter/src/fixer/mod.rs index 88e644ac796e4..5e572c845e911 100644 --- a/crates/oxc_linter/src/fixer/mod.rs +++ b/crates/oxc_linter/src/fixer/mod.rs @@ -2,14 +2,13 @@ mod fix; use std::borrow::Cow; +pub use fix::{CompositeFix, Fix, FixKind, RuleFix}; use oxc_codegen::{CodeGenerator, CodegenOptions}; use oxc_diagnostics::OxcDiagnostic; use oxc_span::{GetSpan, Span}; use crate::LintContext; -pub use fix::{CompositeFix, Fix, FixKind, RuleFix}; - /// Produces [`RuleFix`] instances. Inspired by ESLint's [`RuleFixer`]. /// /// [`RuleFixer`]: https://github.com/eslint/eslint/blob/main/lib/linter/rule-fixer.js diff --git a/crates/oxc_linter/src/frameworks.rs b/crates/oxc_linter/src/frameworks.rs index c0451940fae69..77d34ec98605e 100644 --- a/crates/oxc_linter/src/frameworks.rs +++ b/crates/oxc_linter/src/frameworks.rs @@ -1,6 +1,7 @@ +use std::{hash, path::Path}; + use bitflags::bitflags; use oxc_semantic::ModuleRecord; -use std::{hash, path::Path}; bitflags! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/oxc_linter/src/options/mod.rs b/crates/oxc_linter/src/options/mod.rs index 348949bb70838..5e42cda837e1d 100644 --- a/crates/oxc_linter/src/options/mod.rs +++ b/crates/oxc_linter/src/options/mod.rs @@ -3,7 +3,9 @@ mod plugins; use std::{convert::From, path::PathBuf}; +pub use allow_warn_deny::AllowWarnDeny; use oxc_diagnostics::Error; +pub use plugins::LintPluginOptions; use rustc_hash::FxHashSet; use crate::{ @@ -11,9 +13,6 @@ use crate::{ FrameworkFlags, RuleCategory, RuleEnum, RuleWithSeverity, }; -pub use allow_warn_deny::AllowWarnDeny; -pub use plugins::LintPluginOptions; - #[derive(Debug)] pub struct LintOptions { /// Allow / Deny rules in order. [("allow" / "deny", rule name)] diff --git a/crates/oxc_linter/src/rule.rs b/crates/oxc_linter/src/rule.rs index f30f6ab72e647..93885ab4e4f81 100644 --- a/crates/oxc_linter/src/rule.rs +++ b/crates/oxc_linter/src/rule.rs @@ -203,6 +203,7 @@ impl RuleFixMeta { } } } + pub fn emoji(self) -> Option<&'static str> { match self { Self::None => None, @@ -254,9 +255,10 @@ impl RuleWithSeverity { #[cfg(test)] mod test { - use crate::rules::RULES; use markdown::{to_html_with_options, Options}; + use crate::rules::RULES; + #[test] fn ensure_documentation() { assert!(!RULES.is_empty()); diff --git a/crates/oxc_linter/src/rules/eslint/func_names.rs b/crates/oxc_linter/src/rules/eslint/func_names.rs index 1e805c0123aad..4b3607a59c8b3 100644 --- a/crates/oxc_linter/src/rules/eslint/func_names.rs +++ b/crates/oxc_linter/src/rules/eslint/func_names.rs @@ -1,10 +1,12 @@ use std::borrow::Cow; -use oxc_ast::ast::{ - AssignmentTarget, AssignmentTargetProperty, BindingPatternKind, Expression, Function, - FunctionType, MethodDefinitionKind, PropertyKey, PropertyKind, +use oxc_ast::{ + ast::{ + AssignmentTarget, AssignmentTargetProperty, BindingPatternKind, Expression, Function, + FunctionType, MethodDefinitionKind, PropertyKey, PropertyKind, + }, + AstKind, }; -use oxc_ast::AstKind; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::AstNodeId; @@ -485,10 +487,10 @@ fn guess_function_name<'a>(ctx: &LintContext<'a>, parent_id: AstNodeId) -> Optio | AstKind::TSNonNullExpression(_) | AstKind::TSSatisfiesExpression(_) => continue, AstKind::AssignmentExpression(assign) => { - return assign.left.get_identifier().map(Cow::Borrowed) + return assign.left.get_identifier().map(Cow::Borrowed); } AstKind::VariableDeclarator(decl) => { - return decl.id.get_identifier().as_ref().map(Atom::as_str).map(Cow::Borrowed) + return decl.id.get_identifier().as_ref().map(Atom::as_str).map(Cow::Borrowed); } AstKind::ObjectProperty(prop) => { return prop.key.static_name().and_then(|name| { @@ -497,7 +499,7 @@ fn guess_function_name<'a>(ctx: &LintContext<'a>, parent_id: AstNodeId) -> Optio } else { None } - }) + }); } AstKind::PropertyDefinition(prop) => { return prop.key.static_name().and_then(|name| { @@ -506,7 +508,7 @@ fn guess_function_name<'a>(ctx: &LintContext<'a>, parent_id: AstNodeId) -> Optio } else { None } - }) + }); } _ => return None, } @@ -532,9 +534,10 @@ fn is_valid_identifier_name(name: &str) -> bool { #[test] fn test() { - use crate::tester::Tester; use serde_json::json; + use crate::tester::Tester; + let always = Some(json!(["always"])); let as_needed = Some(json!(["as-needed"])); let never = Some(json!(["never"])); @@ -679,8 +682,7 @@ fn test() { ("class C { foo = function bar() {} }", never.clone()), // { "ecmaVersion": 2022 } ]; - let fix = - vec![ + let fix = vec![ // lb ("const foo = function() {}", "const foo = function foo() {}", always.clone()), ( @@ -784,16 +786,18 @@ fn test() { "const foo = async function* foo(){}", always.clone(), ), - // we can't fix this case because adding a name would cause the - ("const setState = Component.prototype.setState; + // we can't fix this case because adding a name would cause the + ( + "const setState = Component.prototype.setState; Component.prototype.setState = function (update, callback) { return setState.call(this, update, callback); };", - "const setState = Component.prototype.setState; + "const setState = Component.prototype.setState; Component.prototype.setState = function (update, callback) { return setState.call(this, update, callback); };", - always.clone(),), + always.clone(), + ), ]; Tester::new(FuncNames::NAME, pass, fail).expect_fix(fix).test_and_snapshot(); diff --git a/crates/oxc_linter/src/rules/eslint/no_obj_calls.rs b/crates/oxc_linter/src/rules/eslint/no_obj_calls.rs index ce71ffa0ac37b..a3ea2f037d3cb 100644 --- a/crates/oxc_linter/src/rules/eslint/no_obj_calls.rs +++ b/crates/oxc_linter/src/rules/eslint/no_obj_calls.rs @@ -116,7 +116,7 @@ fn resolve_global_binding<'a, 'b: 'a>( } // handles "let a = globalThis.JSON; let b = a; a();" Some(parent_expr) if parent_expr.is_member_expression() => { - return global_this_member(parent_expr.to_member_expression()) + return global_this_member(parent_expr.to_member_expression()); } _ => None, } diff --git a/crates/oxc_linter/src/rules/eslint/no_undef.rs b/crates/oxc_linter/src/rules/eslint/no_undef.rs index 2383aa970e491..d36b103e09865 100644 --- a/crates/oxc_linter/src/rules/eslint/no_undef.rs +++ b/crates/oxc_linter/src/rules/eslint/no_undef.rs @@ -156,7 +156,7 @@ fn test() { "class C { static { a; let a; } }", "class C { static { function a() {} a; } }", "class C { static { a; function a() {} } }", - "String;Array;Boolean;" + "String;Array;Boolean;", ]; let fail = vec![ diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/allowed.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/allowed.rs index 6330ac5bbfaa6..e039530b21fb2 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/allowed.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/allowed.rs @@ -5,9 +5,8 @@ use oxc_ast::{ast::*, AstKind}; use oxc_semantic::{AstNode, AstNodeId, Semantic}; use oxc_span::GetSpan; -use crate::rules::eslint::no_unused_vars::binding_pattern::{BindingContext, HasAnyUsedBinding}; - use super::{options::ArgsOption, NoUnusedVars, Symbol}; +use crate::rules::eslint::no_unused_vars::binding_pattern::{BindingContext, HasAnyUsedBinding}; impl<'s, 'a> Symbol<'s, 'a> { /// Returns `true` if this function is use. @@ -87,7 +86,7 @@ impl<'s, 'a> Symbol<'s, 'a> { return b .body .first() - .is_some_and(|s| matches!(s, Statement::ReturnStatement(_))) + .is_some_and(|s| matches!(s, Statement::ReturnStatement(_))); } _ => return false, }, diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/binding_pattern.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/binding_pattern.rs index b1cf3cccfff7e..73b2e26d0e9a5 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/binding_pattern.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/binding_pattern.rs @@ -14,6 +14,7 @@ impl<'s, 'a> BindingContext<'s, 'a> { pub fn symbol(&self, symbol_id: SymbolId) -> Symbol<'s, 'a> { Symbol::new(self.semantic, symbol_id) } + #[inline] pub fn has_usages(&self, symbol_id: SymbolId) -> bool { self.symbol(symbol_id).has_usages(self.options) diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_symbol.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_symbol.rs index d067d65edc54d..b37af6435788f 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_symbol.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_symbol.rs @@ -1,9 +1,10 @@ -use super::Symbol; -use crate::fixer::{Fix, RuleFix, RuleFixer}; #[allow(clippy::wildcard_imports)] use oxc_ast::{ast::*, AstKind}; use oxc_span::{CompactStr, GetSpan, Span}; +use super::Symbol; +use crate::fixer::{Fix, RuleFix, RuleFixer}; + impl<'s, 'a> Symbol<'s, 'a> { /// Delete a single declarator from a [`VariableDeclaration`] list with more /// than one declarator. diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs index 058d4810d792d..dbe187f3c79b0 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs @@ -44,7 +44,9 @@ impl NoUnusedVars { AstKind::VariableDeclaration(decl) => (decl.span, &decl.declarations), _ => { #[cfg(debug_assertions)] - panic!("VariableDeclarator nodes should always be direct children of VariableDeclaration nodes"); + panic!( + "VariableDeclarator nodes should always be direct children of VariableDeclaration nodes" + ); #[cfg(not(debug_assertions))] return fixer.noop(); } diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/mod.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/mod.rs index 01c3a985e1d66..8e4901ddc8200 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/mod.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/mod.rs @@ -2,10 +2,10 @@ mod fix_imports; mod fix_symbol; mod fix_vars; -use super::{NoUnusedVars, Symbol}; - use fix_symbol::BindingInfo; +use super::{NoUnusedVars, Symbol}; + // source text will never be large enough for this usize to be truncated when // getting cast to a u32 #[allow(clippy::cast_possible_truncation)] diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/ignored.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/ignored.rs index 12623015bd5ba..e6c313af6b0dd 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/ignored.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/ignored.rs @@ -1,4 +1,3 @@ -use super::{NoUnusedVars, Symbol}; use oxc_ast::{ ast::{ ArrayAssignmentTarget, AssignmentTarget, AssignmentTargetMaybeDefault, @@ -9,6 +8,8 @@ use oxc_ast::{ }; use regex::Regex; +use super::{NoUnusedVars, Symbol}; + #[derive(Debug, Default, Clone, Copy)] pub(super) enum FoundStatus { /// The target identifier was not found @@ -342,10 +343,10 @@ impl NoUnusedVars { #[cfg(test)] mod test { - use crate::rule::Rule as _; + use oxc_span::Atom; use super::super::NoUnusedVars; - use oxc_span::Atom; + use crate::rule::Rule as _; #[test] fn test_ignored() { diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/mod.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/mod.rs index 13cc2f12525c2..e372623322665 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/mod.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/mod.rs @@ -11,15 +11,14 @@ mod usage; use std::ops::Deref; +use options::NoUnusedVarsOptions; use oxc_ast::AstKind; use oxc_macros::declare_oxc_lint; use oxc_semantic::{AstNode, ScopeFlags, SymbolFlags, SymbolId}; use oxc_span::GetSpan; +use symbol::Symbol; use crate::{context::LintContext, rule::Rule}; -use options::NoUnusedVarsOptions; - -use symbol::Symbol; #[derive(Debug, Default, Clone)] pub struct NoUnusedVars(Box); diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/options.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/options.rs index 7042cc48e0840..0c4ac93e358f4 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/options.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/options.rs @@ -257,10 +257,12 @@ impl ArgsOption { pub const fn is_after_used(&self) -> bool { matches!(self, Self::AfterUsed) } + #[inline] pub const fn is_all(&self) -> bool { matches!(self, Self::All) } + #[inline] pub const fn is_none(&self) -> bool { matches!(self, Self::None) @@ -281,6 +283,7 @@ impl CaughtErrors { pub const fn all() -> Self { Self(true) } + pub const fn none() -> Self { Self(false) } @@ -407,18 +410,14 @@ impl From for NoUnusedVarsOptions { let Some(config) = value.get(0) else { return Self::default() }; match config { Value::String(vars) => { - let vars: VarsOption = vars - .try_into() - .unwrap(); + let vars: VarsOption = vars.try_into().unwrap(); Self { vars, ..Default::default() } } Value::Object(config) => { let vars = config .get("vars") .map(|vars| { - let vars: VarsOption = vars - .try_into() - .unwrap(); + let vars: VarsOption = vars.try_into().unwrap(); vars }) .unwrap_or_default(); @@ -432,9 +431,7 @@ impl From for NoUnusedVarsOptions { let args: ArgsOption = config .get("args") .map(|args| { - let args: ArgsOption = args - .try_into() - .unwrap(); + let args: ArgsOption = args.try_into().unwrap(); args }) .unwrap_or_default(); @@ -445,9 +442,7 @@ impl From for NoUnusedVarsOptions { let caught_errors: CaughtErrors = config .get("caughtErrors") .map(|caught_errors| { - let caught_errors: CaughtErrors = caught_errors - .try_into() - .unwrap(); + let caught_errors: CaughtErrors = caught_errors.try_into().unwrap(); caught_errors }) .unwrap_or_default(); @@ -487,7 +482,7 @@ impl From for NoUnusedVarsOptions { caught_errors_ignore_pattern, destructured_array_ignore_pattern, ignore_class_with_static_init_block, - report_used_ignore_pattern + report_used_ignore_pattern, } } Value::Null => Self::default(), diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/symbol.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/symbol.rs index 3c55961d83064..12594f8692fa8 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/symbol.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/symbol.rs @@ -1,8 +1,10 @@ -use oxc_ast::ast::{ImportDeclarationSpecifier, VariableDeclarator}; use std::{cell::OnceCell, fmt}; use oxc_ast::{ - ast::{AssignmentTarget, BindingIdentifier, BindingPattern, IdentifierReference}, + ast::{ + AssignmentTarget, BindingIdentifier, BindingPattern, IdentifierReference, + ImportDeclarationSpecifier, VariableDeclarator, + }, AstKind, }; use oxc_semantic::{ diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/eslint.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/eslint.rs index 34c4856e68268..61302856e6dca 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/eslint.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/eslint.rs @@ -1,8 +1,7 @@ //! Test cases from vanilla eslint -use crate::{tester::Tester, RuleMeta as _}; - use super::NoUnusedVars; +use crate::{tester::Tester, RuleMeta as _}; /// These are tests from ESLint that are not passing. If you make a change that /// causes this test to fail, that's a good thing! @@ -30,127 +29,209 @@ fn fixme() { #[test] fn test() { let pass = vec![ - ("var foo = 5; + ( + "var foo = 5; label: while (true) { console.log(foo); break label; - }", None), -("var foo = 5; + }", + None, + ), + ( + "var foo = 5; while (true) { console.log(foo); break; - }", None), -("for (let prop in box) { + }", + None, + ), + ( + "for (let prop in box) { box[prop] = parseInt(box[prop]); - }", None), // { "ecmaVersion": 6 }, -("var box = {a: 2}; + }", + None, + ), // { "ecmaVersion": 6 }, + ( + "var box = {a: 2}; for (var prop in box) { box[prop] = parseInt(box[prop]); - }", None), -("f({ set foo(a) { return; } });", None), -("a; var a;", Some(serde_json::json!(["all"]))), -("var a=10; alert(a);", Some(serde_json::json!(["all"]))), -("var a=10; (function() { alert(a); })();", Some(serde_json::json!(["all"]))), -("var a=10; (function() { setTimeout(function() { alert(a); }, 0); })();", Some(serde_json::json!(["all"]))), -("var a=10; d[a] = 0;", Some(serde_json::json!(["all"]))), -("(function() { var a=10; return a; })();", Some(serde_json::json!(["all"]))), -("(function g() {})()", Some(serde_json::json!(["all"]))), -("function f(a) {alert(a);}; f();", Some(serde_json::json!(["all"]))), -("var c = 0; function f(a){ var b = a; return b; }; f(c);", Some(serde_json::json!(["all"]))), -("function a(x, y){ return y; }; a();", Some(serde_json::json!(["all"]))), -("var arr1 = [1, 2]; var arr2 = [3, 4]; for (var i in arr1) { arr1[i] = 5; } for (var i in arr2) { arr2[i] = 10; }", Some(serde_json::json!(["all"]))), -("var a=10;", Some(serde_json::json!(["local"]))), -(r#"var min = "min"; Math[min];"#, Some(serde_json::json!(["all"]))), -("Foo.bar = function(baz) { return baz; };", Some(serde_json::json!(["all"]))), -("myFunc(function foo() {}.bind(this))", None), -("myFunc(function foo(){}.toString())", None), -("function foo(first, second) { + }", + None, + ), + ("f({ set foo(a) { return; } });", None), + ("a; var a;", Some(serde_json::json!(["all"]))), + ("var a=10; alert(a);", Some(serde_json::json!(["all"]))), + ("var a=10; (function() { alert(a); })();", Some(serde_json::json!(["all"]))), + ( + "var a=10; (function() { setTimeout(function() { alert(a); }, 0); })();", + Some(serde_json::json!(["all"])), + ), + ("var a=10; d[a] = 0;", Some(serde_json::json!(["all"]))), + ("(function() { var a=10; return a; })();", Some(serde_json::json!(["all"]))), + ("(function g() {})()", Some(serde_json::json!(["all"]))), + ("function f(a) {alert(a);}; f();", Some(serde_json::json!(["all"]))), + ( + "var c = 0; function f(a){ var b = a; return b; }; f(c);", + Some(serde_json::json!(["all"])), + ), + ("function a(x, y){ return y; }; a();", Some(serde_json::json!(["all"]))), + ( + "var arr1 = [1, 2]; var arr2 = [3, 4]; for (var i in arr1) { arr1[i] = 5; } for (var i in arr2) { arr2[i] = 10; }", + Some(serde_json::json!(["all"])), + ), + ("var a=10;", Some(serde_json::json!(["local"]))), + (r#"var min = "min"; Math[min];"#, Some(serde_json::json!(["all"]))), + ("Foo.bar = function(baz) { return baz; };", Some(serde_json::json!(["all"]))), + ("myFunc(function foo() {}.bind(this))", None), + ("myFunc(function foo(){}.toString())", None), + ( + "function foo(first, second) { doStuff(function() { - console.log(second);});}; foo()", None), -("(function() { var doSomething = function doSomething() {}; doSomething() }())", None), -// ("/*global a */ a;", None), -("var a=10; (function() { alert(a); })();", Some(serde_json::json!([{ "vars": "all" }]))), -("function g(bar, baz) { return baz; }; g();", Some(serde_json::json!([{ "vars": "all" }]))), -("function g(bar, baz) { return baz; }; g();", Some(serde_json::json!([{ "vars": "all", "args": "after-used" }]))), -("function g(bar, baz) { return bar; }; g();", Some(serde_json::json!([{ "vars": "all", "args": "none" }]))), -("function g(bar, baz) { return 2; }; g();", Some(serde_json::json!([{ "vars": "all", "args": "none" }]))), -("function g(bar, baz) { return bar + baz; }; g();", Some(serde_json::json!([{ "vars": "local", "args": "all" }]))), -("var g = function(bar, baz) { return 2; }; g();", Some(serde_json::json!([{ "vars": "all", "args": "none" }]))), -("(function z() { z(); })();", None), -(" ", None), // { "globals": { "a": true } }, -(r#"var who = "Paul"; - module.exports = `Hello ${who}!`;"#, None), // { "ecmaVersion": 6 }, -("export var foo = 123;", None), // { "ecmaVersion": 6, "sourceType": "module" }, -("export function foo () {}", None), // { "ecmaVersion": 6, "sourceType": "module" }, -("let toUpper = (partial) => partial.toUpperCase; export {toUpper}", None), // { "ecmaVersion": 6, "sourceType": "module" }, -("export class foo {}", None), // { "ecmaVersion": 6, "sourceType": "module" }, -("class Foo{}; var x = new Foo(); x.foo()", None), // { "ecmaVersion": 6 }, -(r#"const foo = "hello!";function bar(foobar = foo) { foobar.replace(/!$/, " world!");} - bar();"#, None), // { "ecmaVersion": 6 }, -("function Foo(){}; var x = new Foo(); x.foo()", None), -("function foo() {var foo = 1; return foo}; foo();", None), -("function foo(foo) {return foo}; foo(1);", None), -("function foo() {function foo() {return 1;}; return foo()}; foo();", None), -("function foo() {var foo = 1; return foo}; foo();", None), // { "ecmaVersion": 6 }, -("function foo(foo) {return foo}; foo(1);", None), // { "ecmaVersion": 6 }, -("function foo() {function foo() {return 1;}; return foo()}; foo();", None), // { "ecmaVersion": 6 }, -("const x = 1; const [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, -("const x = 1; const {y = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, -("const x = 1; const {z: [y = x]} = {}; foo(y);", None), // { "ecmaVersion": 6 }, -("const x = []; const {z: [y] = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, -("const x = 1; let y; [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, -("const x = 1; let y; ({z: [y = x]} = {}); foo(y);", None), // { "ecmaVersion": 6 }, -("const x = []; let y; ({z: [y] = x} = {}); foo(y);", None), // { "ecmaVersion": 6 }, -("const x = 1; function foo(y = x) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, -("const x = 1; function foo({y = x} = {}) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, -("const x = 1; function foo(y = function(z = x) { bar(z); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, -("const x = 1; function foo(y = function() { bar(x); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, -("var x = 1; var [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, -("var x = 1; var {y = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, -("var x = 1; var {z: [y = x]} = {}; foo(y);", None), // { "ecmaVersion": 6 }, -("var x = []; var {z: [y] = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, -("var x = 1, y; [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, -("var x = 1, y; ({z: [y = x]} = {}); foo(y);", None), // { "ecmaVersion": 6 }, -("var x = [], y; ({z: [y] = x} = {}); foo(y);", None), // { "ecmaVersion": 6 }, -("var x = 1; function foo(y = x) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, -("var x = 1; function foo({y = x} = {}) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, -("var x = 1; function foo(y = function(z = x) { bar(z); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, -("var x = 1; function foo(y = function() { bar(x); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, -// ("/*exported toaster*/ var toaster = 'great'", None), -// ("/*exported toaster, poster*/ var toaster = 1; poster = 0;", None), -// ("/*exported x*/ var { x } = y", None), // { "ecmaVersion": 6 }, -// ("/*exported x, y*/ var { x, y } = z", None), // { "ecmaVersion": 6 }, -// ("/*eslint custom/use-every-a:1*/ var a;", None), -// ("/*eslint custom/use-every-a:1*/ !function(a) { return 1; }", None), -// ("/*eslint custom/use-every-a:1*/ !function() { var a; return 1 }", None), -("var _a;", Some(serde_json::json!([{ "vars": "all", "varsIgnorePattern": "^_" }]))), -("var a; function foo() { var _b; } foo();", Some(serde_json::json!([{ "vars": "local", "varsIgnorePattern": "^_" }]))), -("function foo(_a) { } foo();", Some(serde_json::json!([{ "args": "all", "argsIgnorePattern": "^_" }]))), -("function foo(a, _b) { return a; } foo();", Some(serde_json::json!([{ "args": "after-used", "argsIgnorePattern": "^_" }]))), -("var [ firstItemIgnored, secondItem ] = items; - console.log(secondItem);", Some(serde_json::json!([{ "vars": "all", "varsIgnorePattern": "[iI]gnored" }]))), // { "ecmaVersion": 6 }, -("const [ a, _b, c ] = items; - console.log(a+c);", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -("const [ [a, _b, c] ] = items; - console.log(a+c);", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -("const { x: [_a, foo] } = bar; - console.log(foo);", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -("function baz([_b, foo]) { foo; }; - baz()", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -("function baz({x: [_b, foo]}) {foo}; - baz()", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -("function baz([{x: [_b, foo]}]) {foo}; - baz()", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -(" + console.log(second);});}; foo()", + None, + ), + ("(function() { var doSomething = function doSomething() {}; doSomething() }())", None), + // ("/*global a */ a;", None), + ("var a=10; (function() { alert(a); })();", Some(serde_json::json!([{ "vars": "all" }]))), + ( + "function g(bar, baz) { return baz; }; g();", + Some(serde_json::json!([{ "vars": "all" }])), + ), + ( + "function g(bar, baz) { return baz; }; g();", + Some(serde_json::json!([{ "vars": "all", "args": "after-used" }])), + ), + ( + "function g(bar, baz) { return bar; }; g();", + Some(serde_json::json!([{ "vars": "all", "args": "none" }])), + ), + ( + "function g(bar, baz) { return 2; }; g();", + Some(serde_json::json!([{ "vars": "all", "args": "none" }])), + ), + ( + "function g(bar, baz) { return bar + baz; }; g();", + Some(serde_json::json!([{ "vars": "local", "args": "all" }])), + ), + ( + "var g = function(bar, baz) { return 2; }; g();", + Some(serde_json::json!([{ "vars": "all", "args": "none" }])), + ), + ("(function z() { z(); })();", None), + (" ", None), // { "globals": { "a": true } }, + ( + r#"var who = "Paul"; + module.exports = `Hello ${who}!`;"#, + None, + ), // { "ecmaVersion": 6 }, + ("export var foo = 123;", None), // { "ecmaVersion": 6, "sourceType": "module" }, + ("export function foo () {}", None), // { "ecmaVersion": 6, "sourceType": "module" }, + ("let toUpper = (partial) => partial.toUpperCase; export {toUpper}", None), // { "ecmaVersion": 6, "sourceType": "module" }, + ("export class foo {}", None), // { "ecmaVersion": 6, "sourceType": "module" }, + ("class Foo{}; var x = new Foo(); x.foo()", None), // { "ecmaVersion": 6 }, + ( + r#"const foo = "hello!";function bar(foobar = foo) { foobar.replace(/!$/, " world!");} + bar();"#, + None, + ), // { "ecmaVersion": 6 }, + ("function Foo(){}; var x = new Foo(); x.foo()", None), + ("function foo() {var foo = 1; return foo}; foo();", None), + ("function foo(foo) {return foo}; foo(1);", None), + ("function foo() {function foo() {return 1;}; return foo()}; foo();", None), + ("function foo() {var foo = 1; return foo}; foo();", None), // { "ecmaVersion": 6 }, + ("function foo(foo) {return foo}; foo(1);", None), // { "ecmaVersion": 6 }, + ("function foo() {function foo() {return 1;}; return foo()}; foo();", None), // { "ecmaVersion": 6 }, + ("const x = 1; const [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = 1; const {y = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = 1; const {z: [y = x]} = {}; foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = []; const {z: [y] = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = 1; let y; [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = 1; let y; ({z: [y = x]} = {}); foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = []; let y; ({z: [y] = x} = {}); foo(y);", None), // { "ecmaVersion": 6 }, + ("const x = 1; function foo(y = x) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, + ("const x = 1; function foo({y = x} = {}) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, + ("const x = 1; function foo(y = function(z = x) { bar(z); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, + ("const x = 1; function foo(y = function() { bar(x); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, + ("var x = 1; var [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = 1; var {y = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = 1; var {z: [y = x]} = {}; foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = []; var {z: [y] = x} = {}; foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = 1, y; [y = x] = []; foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = 1, y; ({z: [y = x]} = {}); foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = [], y; ({z: [y] = x} = {}); foo(y);", None), // { "ecmaVersion": 6 }, + ("var x = 1; function foo(y = x) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, + ("var x = 1; function foo({y = x} = {}) { bar(y); } foo();", None), // { "ecmaVersion": 6 }, + ("var x = 1; function foo(y = function(z = x) { bar(z); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, + ("var x = 1; function foo(y = function() { bar(x); }) { y(); } foo();", None), // { "ecmaVersion": 6 }, + // ("/*exported toaster*/ var toaster = 'great'", None), + // ("/*exported toaster, poster*/ var toaster = 1; poster = 0;", None), + // ("/*exported x*/ var { x } = y", None), // { "ecmaVersion": 6 }, + // ("/*exported x, y*/ var { x, y } = z", None), // { "ecmaVersion": 6 }, + // ("/*eslint custom/use-every-a:1*/ var a;", None), + // ("/*eslint custom/use-every-a:1*/ !function(a) { return 1; }", None), + // ("/*eslint custom/use-every-a:1*/ !function() { var a; return 1 }", None), + ("var _a;", Some(serde_json::json!([{ "vars": "all", "varsIgnorePattern": "^_" }]))), + ( + "var a; function foo() { var _b; } foo();", + Some(serde_json::json!([{ "vars": "local", "varsIgnorePattern": "^_" }])), + ), + ( + "function foo(_a) { } foo();", + Some(serde_json::json!([{ "args": "all", "argsIgnorePattern": "^_" }])), + ), + ( + "function foo(a, _b) { return a; } foo();", + Some(serde_json::json!([{ "args": "after-used", "argsIgnorePattern": "^_" }])), + ), + ( + "var [ firstItemIgnored, secondItem ] = items; + console.log(secondItem);", + Some(serde_json::json!([{ "vars": "all", "varsIgnorePattern": "[iI]gnored" }])), + ), // { "ecmaVersion": 6 }, + ( + "const [ a, _b, c ] = items; + console.log(a+c);", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + "const [ [a, _b, c] ] = items; + console.log(a+c);", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + "const { x: [_a, foo] } = bar; + console.log(foo);", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + "function baz([_b, foo]) { foo; }; + baz()", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + "function baz({x: [_b, foo]}) {foo}; + baz()", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + "function baz([{x: [_b, foo]}]) {foo}; + baz()", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + " let _a, b; foo.forEach(item => { [_a, b] = item; doSomething(b); }); - ", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 6 }, -(" + ", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 6 }, + ( + " // doesn't report _x let _x, y; _x = 1; @@ -162,8 +243,11 @@ fn test() { [_a, b] = foo; _a = 1; b; - ", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }]))), // { "ecmaVersion": 2018 }, -(" + ", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_" }])), + ), // { "ecmaVersion": 2018 }, + ( + " // doesn't report _x let _x, y; _x = 1; @@ -175,103 +259,188 @@ fn test() { _a = 1; ({_a, ...b } = foo); b; - ", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_", "ignoreRestSiblings": true }]))), // { "ecmaVersion": 2018 }, -("try {} catch ([firstError]) {}", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "Error$" }]))), // { "ecmaVersion": 2015 }, -("(function(obj) { var name; for ( name in obj ) return; })({});", None), -("(function(obj) { var name; for ( name in obj ) { return; } })({});", None), -("(function(obj) { for ( var name in obj ) { return true } })({})", None), -("(function(obj) { for ( var name in obj ) return true })({})", None), -("(function(obj) { let name; for ( name in obj ) return; })({});", None), // { "ecmaVersion": 6 }, -("(function(obj) { let name; for ( name in obj ) { return; } })({});", None), // { "ecmaVersion": 6 }, -("(function(obj) { for ( let name in obj ) { return true } })({})", None), // { "ecmaVersion": 6 }, -("(function(obj) { for ( let name in obj ) return true })({})", None), // { "ecmaVersion": 6 }, -("(function(obj) { for ( const name in obj ) { return true } })({})", None), // { "ecmaVersion": 6 }, -("(function(obj) { for ( const name in obj ) return true })({})", None), // { "ecmaVersion": 6 }, -("(function(iter) { let name; for ( name of iter ) return; })({});", None), // { "ecmaVersion": 6 }, -("(function(iter) { let name; for ( name of iter ) { return; } })({});", None), // { "ecmaVersion": 6 }, -("(function(iter) { for ( let name of iter ) { return true } })({})", None), // { "ecmaVersion": 6 }, -("(function(iter) { for ( let name of iter ) return true })({})", None), // { "ecmaVersion": 6 }, -("(function(iter) { for ( const name of iter ) { return true } })({})", None), // { "ecmaVersion": 6 }, -("(function(iter) { for ( const name of iter ) return true })({})", None), // { "ecmaVersion": 6 }, -("let x = 0; foo = (0, x++);", None), // { "ecmaVersion": 6 }, -("let x = 0; foo = (0, x += 1);", None), // { "ecmaVersion": 6 }, -("let x = 0; foo = (0, x = x + 1);", None), // { "ecmaVersion": 6 }, -("try{}catch(err){}", Some(serde_json::json!([{ "caughtErrors": "none" }]))), -("try{}catch(err){console.error(err);}", Some(serde_json::json!([{ "caughtErrors": "all" }]))), -("try{}catch(ignoreErr){}", Some(serde_json::json!([{ "caughtErrorsIgnorePattern": "^ignore" }]))), -("try{}catch(ignoreErr){}", Some(serde_json::json!([{ "caughtErrors": "all", "caughtErrorsIgnorePattern": "^ignore" }]))), -("try {} catch ({ message, stack }) {}", Some(serde_json::json!([{ "caughtErrorsIgnorePattern": "message|stack" }]))), // { "ecmaVersion": 2015 }, -("try {} catch ({ errors: [firstError] }) {}", Some(serde_json::json!([{ "caughtErrorsIgnorePattern": "Error$" }]))), // { "ecmaVersion": 2015 }, -("try{}catch(err){}", Some(serde_json::json!([{ "caughtErrors": "none", "vars": "all", "args": "all" }]))), -("const data = { type: 'coords', x: 1, y: 2 }; + ", + Some( + serde_json::json!([{ "destructuredArrayIgnorePattern": "^_", "ignoreRestSiblings": true }]), + ), + ), // { "ecmaVersion": 2018 }, + ( + "try {} catch ([firstError]) {}", + Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "Error$" }])), + ), // { "ecmaVersion": 2015 }, + ("(function(obj) { var name; for ( name in obj ) return; })({});", None), + ("(function(obj) { var name; for ( name in obj ) { return; } })({});", None), + ("(function(obj) { for ( var name in obj ) { return true } })({})", None), + ("(function(obj) { for ( var name in obj ) return true })({})", None), + ("(function(obj) { let name; for ( name in obj ) return; })({});", None), // { "ecmaVersion": 6 }, + ("(function(obj) { let name; for ( name in obj ) { return; } })({});", None), // { "ecmaVersion": 6 }, + ("(function(obj) { for ( let name in obj ) { return true } })({})", None), // { "ecmaVersion": 6 }, + ("(function(obj) { for ( let name in obj ) return true })({})", None), // { "ecmaVersion": 6 }, + ("(function(obj) { for ( const name in obj ) { return true } })({})", None), // { "ecmaVersion": 6 }, + ("(function(obj) { for ( const name in obj ) return true })({})", None), // { "ecmaVersion": 6 }, + ("(function(iter) { let name; for ( name of iter ) return; })({});", None), // { "ecmaVersion": 6 }, + ("(function(iter) { let name; for ( name of iter ) { return; } })({});", None), // { "ecmaVersion": 6 }, + ("(function(iter) { for ( let name of iter ) { return true } })({})", None), // { "ecmaVersion": 6 }, + ("(function(iter) { for ( let name of iter ) return true })({})", None), // { "ecmaVersion": 6 }, + ("(function(iter) { for ( const name of iter ) { return true } })({})", None), // { "ecmaVersion": 6 }, + ("(function(iter) { for ( const name of iter ) return true })({})", None), // { "ecmaVersion": 6 }, + ("let x = 0; foo = (0, x++);", None), // { "ecmaVersion": 6 }, + ("let x = 0; foo = (0, x += 1);", None), // { "ecmaVersion": 6 }, + ("let x = 0; foo = (0, x = x + 1);", None), // { "ecmaVersion": 6 }, + ("try{}catch(err){}", Some(serde_json::json!([{ "caughtErrors": "none" }]))), + ( + "try{}catch(err){console.error(err);}", + Some(serde_json::json!([{ "caughtErrors": "all" }])), + ), + ( + "try{}catch(ignoreErr){}", + Some(serde_json::json!([{ "caughtErrorsIgnorePattern": "^ignore" }])), + ), + ( + "try{}catch(ignoreErr){}", + Some( + serde_json::json!([{ "caughtErrors": "all", "caughtErrorsIgnorePattern": "^ignore" }]), + ), + ), + ( + "try {} catch ({ message, stack }) {}", + Some(serde_json::json!([{ "caughtErrorsIgnorePattern": "message|stack" }])), + ), // { "ecmaVersion": 2015 }, + ( + "try {} catch ({ errors: [firstError] }) {}", + Some(serde_json::json!([{ "caughtErrorsIgnorePattern": "Error$" }])), + ), // { "ecmaVersion": 2015 }, + ( + "try{}catch(err){}", + Some(serde_json::json!([{ "caughtErrors": "none", "vars": "all", "args": "all" }])), + ), + ( + "const data = { type: 'coords', x: 1, y: 2 }; const { type, ...coords } = data; - console.log(coords);", Some(serde_json::json!([{ "ignoreRestSiblings": true }]))), // { "ecmaVersion": 2018 }, -("try {} catch ({ foo, ...bar }) { console.log(bar); }", Some(serde_json::json!([{ "ignoreRestSiblings": true }]))), // { "ecmaVersion": 2018 }, -("var a = 0, b; b = a = a + 1; foo(b);", None), -("var a = 0, b; b = a += a + 1; foo(b);", None), -("var a = 0, b; b = a++; foo(b);", None), -("function foo(a) { var b = a = a + 1; bar(b) } foo();", None), -("function foo(a) { var b = a += a + 1; bar(b) } foo();", None), -("function foo(a) { var b = a++; bar(b) } foo();", None), -(r#"var unregisterFooWatcher; + console.log(coords);", + Some(serde_json::json!([{ "ignoreRestSiblings": true }])), + ), // { "ecmaVersion": 2018 }, + ( + "try {} catch ({ foo, ...bar }) { console.log(bar); }", + Some(serde_json::json!([{ "ignoreRestSiblings": true }])), + ), // { "ecmaVersion": 2018 }, + ("var a = 0, b; b = a = a + 1; foo(b);", None), + ("var a = 0, b; b = a += a + 1; foo(b);", None), + ("var a = 0, b; b = a++; foo(b);", None), + ("function foo(a) { var b = a = a + 1; bar(b) } foo();", None), + ("function foo(a) { var b = a += a + 1; bar(b) } foo();", None), + ("function foo(a) { var b = a++; bar(b) } foo();", None), + ( + r#"var unregisterFooWatcher; // ... unregisterFooWatcher = $scope.$watch( "foo", function() { // ...some code.. unregisterFooWatcher(); }); - "#, None), -("var ref; + "#, + None, + ), + ( + "var ref; ref = setInterval( function(){ clearInterval(ref); }, 10); - ", None), -("var _timer; + ", + None, + ), + ( + "var _timer; function f() { _timer = setTimeout(function () {}, _timer ? 100 : 0); } f(); - ", None), -("function foo(cb) { cb = function() { function something(a) { cb(1 + a); } register(something); }(); } foo();", None), -("function* foo(cb) { cb = yield function(a) { cb(1 + a); }; } foo();", None), // { "ecmaVersion": 6 }, -("function foo(cb) { cb = tag`hello${function(a) { cb(1 + a); }}`; } foo();", None), // { "ecmaVersion": 6 }, -("function foo(cb) { var b; cb = b = function(a) { cb(1 + a); }; b(); } foo();", None), -("function someFunction() { + ", + None, + ), + ( + "function foo(cb) { cb = function() { function something(a) { cb(1 + a); } register(something); }(); } foo();", + None, + ), + ("function* foo(cb) { cb = yield function(a) { cb(1 + a); }; } foo();", None), // { "ecmaVersion": 6 }, + ("function foo(cb) { cb = tag`hello${function(a) { cb(1 + a); }}`; } foo();", None), // { "ecmaVersion": 6 }, + ("function foo(cb) { var b; cb = b = function(a) { cb(1 + a); }; b(); } foo();", None), + ( + "function someFunction() { var a = 0, i; for (i = 0; i < 2; i++) { a = myFunction(a); } } someFunction(); - ", None), -("(function(a, b, {c, d}) { d })", Some(serde_json::json!([{ "argsIgnorePattern": "c" }]))), // { "ecmaVersion": 6 }, -("(function(a, b, {c, d}) { c })", Some(serde_json::json!([{ "argsIgnorePattern": "d" }]))), // { "ecmaVersion": 6 }, -("(function(a, b, c) { c })", Some(serde_json::json!([{ "argsIgnorePattern": "c" }]))), -("(function(a, b, {c, d}) { c })", Some(serde_json::json!([{ "argsIgnorePattern": "[cd]" }]))), // { "ecmaVersion": 6 }, -("(class { set foo(UNUSED) {} })", None), // { "ecmaVersion": 6 }, -("class Foo { set bar(UNUSED) {} } console.log(Foo)", None), // { "ecmaVersion": 6 }, -("(({a, ...rest}) => rest)", Some(serde_json::json!([{ "args": "all", "ignoreRestSiblings": true }]))), // { "ecmaVersion": 2018 }, -("let foo, rest; + ", + None, + ), + ("(function(a, b, {c, d}) { d })", Some(serde_json::json!([{ "argsIgnorePattern": "c" }]))), // { "ecmaVersion": 6 }, + ("(function(a, b, {c, d}) { c })", Some(serde_json::json!([{ "argsIgnorePattern": "d" }]))), // { "ecmaVersion": 6 }, + ("(function(a, b, c) { c })", Some(serde_json::json!([{ "argsIgnorePattern": "c" }]))), + ( + "(function(a, b, {c, d}) { c })", + Some(serde_json::json!([{ "argsIgnorePattern": "[cd]" }])), + ), // { "ecmaVersion": 6 }, + ("(class { set foo(UNUSED) {} })", None), // { "ecmaVersion": 6 }, + ("class Foo { set bar(UNUSED) {} } console.log(Foo)", None), // { "ecmaVersion": 6 }, + ( + "(({a, ...rest}) => rest)", + Some(serde_json::json!([{ "args": "all", "ignoreRestSiblings": true }])), + ), // { "ecmaVersion": 2018 }, + ( + "let foo, rest; ({ foo, ...rest } = something); - console.log(rest);", Some(serde_json::json!([{ "ignoreRestSiblings": true }]))), // { "ecmaVersion": 2020 }, -// ("/*eslint custom/use-every-a:1*/ !function(b, a) { return 1 }", None), -("var a = function () { a(); }; a();", None), -("var a = function(){ return function () { a(); } }; a();", None), -("const a = () => { a(); }; a();", None), // { "ecmaVersion": 2015 }, -("const a = () => () => { a(); }; a();", None), // { "ecmaVersion": 2015 }, -(r#"export * as ns from "source""#, None), // { "ecmaVersion": 2020, "sourceType": "module" }, -("import.meta", None), // { "ecmaVersion": 2020, "sourceType": "module" }, -// NOTE (@DonIsaac) ESLint thinks this counts as being used, I disagree -// ("var a; a ||= 1;", None), // { "ecmaVersion": 2021 }, -// ("var a; a &&= 1;", None), // { "ecmaVersion": 2021 }, -// ("var a; a ??= 1;", None), // { "ecmaVersion": 2021 }, -("class Foo { static {} }", Some(serde_json::json!([{ "ignoreClassWithStaticInitBlock": true }]))), // { "ecmaVersion": 2022 }, -("class Foo { static {} }", Some(serde_json::json!([{ "ignoreClassWithStaticInitBlock": true, "varsIgnorePattern": "^_" }]))), // { "ecmaVersion": 2022 }, -("class Foo { static {} }", Some(serde_json::json!([{ "ignoreClassWithStaticInitBlock": false, "varsIgnorePattern": "^Foo" }]))), // { "ecmaVersion": 2022 }, -("const a = 5; const _c = a + 5;", Some(serde_json::json!([{ "args": "all", "varsIgnorePattern": "^_", "reportUsedIgnorePattern": true }]))), // { "ecmaVersion": 6 }, -("(function foo(a, _b) { return a + 5 })(5)", Some(serde_json::json!([{ "args": "all", "argsIgnorePattern": "^_", "reportUsedIgnorePattern": true }]))), -("const [ a, _b, c ] = items; - console.log(a+c);", Some(serde_json::json!([{ "destructuredArrayIgnorePattern": "^_", "reportUsedIgnorePattern": true }]))), // { "ecmaVersion": 6 } + console.log(rest);", + Some(serde_json::json!([{ "ignoreRestSiblings": true }])), + ), // { "ecmaVersion": 2020 }, + // ("/*eslint custom/use-every-a:1*/ !function(b, a) { return 1 }", None), + ("var a = function () { a(); }; a();", None), + ("var a = function(){ return function () { a(); } }; a();", None), + ("const a = () => { a(); }; a();", None), // { "ecmaVersion": 2015 }, + ("const a = () => () => { a(); }; a();", None), // { "ecmaVersion": 2015 }, + (r#"export * as ns from "source""#, None), // { "ecmaVersion": 2020, "sourceType": "module" }, + ("import.meta", None), // { "ecmaVersion": 2020, "sourceType": "module" }, + // NOTE (@DonIsaac) ESLint thinks this counts as being used, I disagree + // ("var a; a ||= 1;", None), // { "ecmaVersion": 2021 }, + // ("var a; a &&= 1;", None), // { "ecmaVersion": 2021 }, + // ("var a; a ??= 1;", None), // { "ecmaVersion": 2021 }, + ( + "class Foo { static {} }", + Some(serde_json::json!([{ "ignoreClassWithStaticInitBlock": true }])), + ), // { "ecmaVersion": 2022 }, + ( + "class Foo { static {} }", + Some( + serde_json::json!([{ "ignoreClassWithStaticInitBlock": true, "varsIgnorePattern": "^_" }]), + ), + ), // { "ecmaVersion": 2022 }, + ( + "class Foo { static {} }", + Some( + serde_json::json!([{ "ignoreClassWithStaticInitBlock": false, "varsIgnorePattern": "^Foo" }]), + ), + ), // { "ecmaVersion": 2022 }, + ( + "const a = 5; const _c = a + 5;", + Some( + serde_json::json!([{ "args": "all", "varsIgnorePattern": "^_", "reportUsedIgnorePattern": true }]), + ), + ), // { "ecmaVersion": 6 }, + ( + "(function foo(a, _b) { return a + 5 })(5)", + Some( + serde_json::json!([{ "args": "all", "argsIgnorePattern": "^_", "reportUsedIgnorePattern": true }]), + ), + ), + ( + "const [ a, _b, c ] = items; + console.log(a+c);", + Some( + serde_json::json!([{ "destructuredArrayIgnorePattern": "^_", "reportUsedIgnorePattern": true }]), + ), + ), // { "ecmaVersion": 6 } ]; let fail = vec![ diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs index 1d3b476ee3361..063ad20941641 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs @@ -1,8 +1,9 @@ //! Test cases created by oxc maintainers +use serde_json::json; + use super::NoUnusedVars; use crate::{tester::Tester, FixKind, RuleMeta as _}; -use serde_json::json; #[test] fn test_vars_simple() { @@ -279,8 +280,8 @@ fn test_vars_destructure() { "caughtErrors": "none", "ignoreRestSiblings": true, "vars": "all" - }])) - ) + }])), + ), ]; let fail = vec![ ("const { a, ...rest } = obj", Some(json!( [{ "ignoreRestSiblings": true }] ))), @@ -476,7 +477,7 @@ fn test_functions() { }); ", "const foo = () => function bar() { }\nfoo()", - "module.exports.foo = () => function bar() { }" + "module.exports.foo = () => function bar() { }", ]; let fail = vec![ diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/usage.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/usage.rs index da47a11b86a66..898a26b34a95c 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/usage.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/usage.rs @@ -163,7 +163,7 @@ impl<'s, 'a> Symbol<'s, 'a> { return b .body .first() - .is_some_and(|s| matches!(s, Statement::ReturnStatement(_))) + .is_some_and(|s| matches!(s, Statement::ReturnStatement(_))); } _ => return false, }, @@ -603,7 +603,8 @@ impl<'s, 'a> Symbol<'s, 'a> { let decl_scope_id = self.scope_id(); let call_scope_id = self.get_ref_scope(reference); let Some(container_id) = self.declaration().kind().get_container_scope_id() else { - debug_assert!(false, + debug_assert!( + false, "Found a function call or or new expr reference on a node flagged as a function or class, but the symbol's declaration node has no scope id. It should always be a container." ); return false; @@ -667,7 +668,7 @@ impl<'s, 'a> Symbol<'s, 'a> { continue; } AstKind::VariableDeclarator(decl) if needs_variable_identifier => { - return decl.id.get_binding_identifier().and_then(|id| id.symbol_id.get()) + return decl.id.get_binding_identifier().and_then(|id| id.symbol_id.get()); } AstKind::AssignmentTarget(target) if needs_variable_identifier => { return match target { @@ -676,7 +677,7 @@ impl<'s, 'a> Symbol<'s, 'a> { .get() .and_then(|rid| self.symbols().get_reference(rid).symbol_id()), _ => None, - } + }; } AstKind::Program(_) => { return None; diff --git a/crates/oxc_linter/src/rules/import/no_dynamic_require.rs b/crates/oxc_linter/src/rules/import/no_dynamic_require.rs index 1ec1022741856..579af30e2b36f 100644 --- a/crates/oxc_linter/src/rules/import/no_dynamic_require.rs +++ b/crates/oxc_linter/src/rules/import/no_dynamic_require.rs @@ -89,9 +89,10 @@ fn is_static_value(expr: &Expression) -> bool { #[test] fn test() { - use crate::tester::Tester; use serde_json::json; + use crate::tester::Tester; + let pass = vec![ (r#"import _ from "lodash""#, None), (r#"require("foo")"#, None), diff --git a/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs b/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs index 5699f56b8ca68..e97ee6eaf39cf 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs @@ -136,9 +136,10 @@ fn can_fix<'a>(node: &AstNode<'a>, ctx: &LintContext<'a>) -> bool { #[test] fn test() { - use crate::tester::Tester; use std::path::PathBuf; + use crate::tester::Tester; + let pass = vec![ ("foo();", None, None, None), ("jest.mocked(foo).mockReturnValue(1);", None, None, None), diff --git a/crates/oxc_linter/src/rules/jest/prefer_to_have_length.rs b/crates/oxc_linter/src/rules/jest/prefer_to_have_length.rs index 02b96210be2b0..ab87b5d9a0b04 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_to_have_length.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_to_have_length.rs @@ -216,13 +216,15 @@ fn tests() { ("expect(files.length).toStrictEqual(1);", None), ("expect(files.length).not.toStrictEqual(1);", None), ( - "expect((meta.get('pages') as YArray).length).toBe((originalMeta.get('pages') as YArray).length);", - None + "expect((meta.get('pages') as YArray).length).toBe((originalMeta.get('pages') as YArray).length);", + None, ), ( "expect(assetTypeContainer.getElementsByTagName('time').length).toEqual( 0, - );", None) + );", + None, + ), ]; let fix = vec![ @@ -249,19 +251,19 @@ fn tests() { ("expect(files.length).toStrictEqual(1);", "expect(files).toHaveLength(1);", None), ("expect(files.length).not.toStrictEqual(1);", "expect(files).not.toHaveLength(1);", None), ( - "expect((meta.get('pages') as YArray).length).toBe((originalMeta.get('pages') as YArray).length);", - "expect((meta.get('pages') as YArray)).toHaveLength((originalMeta.get('pages') as YArray).length);", - None + "expect((meta.get('pages') as YArray).length).toBe((originalMeta.get('pages') as YArray).length);", + "expect((meta.get('pages') as YArray)).toHaveLength((originalMeta.get('pages') as YArray).length);", + None, ), ( "expect(assetTypeContainer.getElementsByTagName('time').length).toEqual( 0, - );", + );", "expect(assetTypeContainer.getElementsByTagName('time')).toHaveLength( 0, - );", - None - ) + );", + None, + ), ]; Tester::new(PreferToHaveLength::NAME, pass, fail) diff --git a/crates/oxc_linter/src/rules/oxc/no_accumulating_spread.rs b/crates/oxc_linter/src/rules/oxc/no_accumulating_spread.rs index 891918707bf4b..0e8525cace8dc 100644 --- a/crates/oxc_linter/src/rules/oxc/no_accumulating_spread.rs +++ b/crates/oxc_linter/src/rules/oxc/no_accumulating_spread.rs @@ -394,7 +394,7 @@ fn test() { "let foo = {}; for (const i in [1,2,3]) { foo[i] = i; }", "let foo = {}; for (let i of [1,2,3]) { foo[i] = i; }", "let foo = {}; for (const i of [1,2,3]) { foo[i] = i; }", - "let foo = {}; while (Object.keys(foo).length < 10) { foo[Object.keys(foo).length] = Object.keys(foo).length; }", + "let foo = {}; while (Object.keys(foo).length < 10) { foo[Object.keys(foo).length] = Object.keys(foo).length; }", ]; let fail = vec![ diff --git a/crates/oxc_linter/src/rules/oxc/no_async_endpoint_handlers.rs b/crates/oxc_linter/src/rules/oxc/no_async_endpoint_handlers.rs index d78cd0854c7ba..bb25775aa8386 100644 --- a/crates/oxc_linter/src/rules/oxc/no_async_endpoint_handlers.rs +++ b/crates/oxc_linter/src/rules/oxc/no_async_endpoint_handlers.rs @@ -1,15 +1,15 @@ use std::ops::Deref; +use oxc_ast::{ + ast::{Argument, ArrowFunctionExpression, Expression, Function}, + AstKind, +}; use oxc_diagnostics::{LabeledSpan, OxcDiagnostic}; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use serde_json::Value; use crate::{context::LintContext, rule::Rule, utils, AstNode}; -use oxc_ast::{ - ast::{Argument, ArrowFunctionExpression, Expression, Function}, - AstKind, -}; #[derive(Debug, Default, Clone)] pub struct NoAsyncEndpointHandlers(Box); @@ -296,9 +296,10 @@ impl NoAsyncEndpointHandlers { #[test] fn test() { - use crate::tester::Tester; use serde_json::json; + use crate::tester::Tester; + let pass = vec![ ("app.get('/', fooController)", None), ("app.get('/', (req, res) => {})", None), diff --git a/crates/oxc_linter/src/rules/react/jsx_curly_brace_presence.rs b/crates/oxc_linter/src/rules/react/jsx_curly_brace_presence.rs index 4712eff9aa48b..71fade98ad5df 100644 --- a/crates/oxc_linter/src/rules/react/jsx_curly_brace_presence.rs +++ b/crates/oxc_linter/src/rules/react/jsx_curly_brace_presence.rs @@ -36,6 +36,7 @@ enum Allowed { impl TryFrom<&str> for Allowed { type Error = (); + fn try_from(value: &str) -> Result { match value { "always" => Ok(Self::Always), @@ -50,6 +51,7 @@ impl Allowed { pub fn is_never(self) -> bool { matches!(self, Self::Never) } + #[inline] pub fn is_always(self) -> bool { matches!(self, Self::Always) @@ -327,6 +329,7 @@ impl Rule for JsxCurlyBracePresence { _ => default, } } + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { match node.kind() { AstKind::JSXElement(el) => { @@ -559,9 +562,10 @@ fn has_adjacent_jsx_expression_containers<'a>( #[test] fn test() { - use crate::tester::Tester; use serde_json::json; + use crate::tester::Tester; + let pass = vec![ ("foo", None), ("<>foo", None), diff --git a/crates/oxc_linter/src/rules/react/jsx_props_no_spread_multi.rs b/crates/oxc_linter/src/rules/react/jsx_props_no_spread_multi.rs index c3bc7f6729d75..0688956e72d75 100644 --- a/crates/oxc_linter/src/rules/react/jsx_props_no_spread_multi.rs +++ b/crates/oxc_linter/src/rules/react/jsx_props_no_spread_multi.rs @@ -1,11 +1,9 @@ -use rustc_hash::FxHashMap; - +use itertools::Itertools; use oxc_ast::{ast::JSXAttributeItem, AstKind}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{Atom, Span}; - -use itertools::Itertools; +use rustc_hash::FxHashMap; use crate::{ context::LintContext, diff --git a/crates/oxc_linter/src/rules/react_perf/jsx_no_jsx_as_prop.rs b/crates/oxc_linter/src/rules/react_perf/jsx_no_jsx_as_prop.rs index 5f68e2bb2007a..b06ff6fb4d322 100644 --- a/crates/oxc_linter/src/rules/react_perf/jsx_no_jsx_as_prop.rs +++ b/crates/oxc_linter/src/rules/react_perf/jsx_no_jsx_as_prop.rs @@ -1,9 +1,10 @@ -use crate::utils::ReactPerfRule; use oxc_ast::{ast::Expression, AstKind}; use oxc_macros::declare_oxc_lint; use oxc_semantic::SymbolId; use oxc_span::{GetSpan, Span}; +use crate::utils::ReactPerfRule; + #[derive(Debug, Default, Clone)] pub struct JsxNoJsxAsProp; diff --git a/crates/oxc_linter/src/rules/tree_shaking/no_side_effects_in_initialization/mod.rs b/crates/oxc_linter/src/rules/tree_shaking/no_side_effects_in_initialization/mod.rs index 4b1cfcb1ed990..f9a494ef3fe85 100644 --- a/crates/oxc_linter/src/rules/tree_shaking/no_side_effects_in_initialization/mod.rs +++ b/crates/oxc_linter/src/rules/tree_shaking/no_side_effects_in_initialization/mod.rs @@ -641,7 +641,7 @@ fn test() { { let x = () => {}; } let x = ext export {/* tree-shaking no-side-effects-when-called */ x} - ", + ", // ExpressionStatement "ext()", // ForInStatement diff --git a/crates/oxc_linter/src/rules/typescript/array_type.rs b/crates/oxc_linter/src/rules/typescript/array_type.rs index c05cb425e9c62..ab07e318f6bd5 100644 --- a/crates/oxc_linter/src/rules/typescript/array_type.rs +++ b/crates/oxc_linter/src/rules/typescript/array_type.rs @@ -37,7 +37,10 @@ fn generic(x0: &str, x1: &str, x2: &str, span3: Span) -> OxcDiagnostic { } fn generic_simple(x0: &str, x1: &str, x2: &str, span3: Span) -> OxcDiagnostic { - OxcDiagnostic::warn(format!("Array type using '{x0}{x2}[]' is forbidden for non-simple types. Use '{x1}<{x2}>' instead.")).with_label(span3) + OxcDiagnostic::warn(format!( + "Array type using '{x0}{x2}[]' is forbidden for non-simple types. Use '{x1}<{x2}>' instead." + )) + .with_label(span3) } fn array(x0: &str, x1: &str, x2: &str, span3: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/unicorn/consistent_function_scoping.rs b/crates/oxc_linter/src/rules/unicorn/consistent_function_scoping.rs index a250fe518e9ac..651ce2bca1e34 100644 --- a/crates/oxc_linter/src/rules/unicorn/consistent_function_scoping.rs +++ b/crates/oxc_linter/src/rules/unicorn/consistent_function_scoping.rs @@ -157,6 +157,7 @@ impl Rule for ConsistentFunctionScoping { Self(Box::new(configuration)) } + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { let (function_declaration_symbol_id, function_body, reporter_span) = match node.kind() { AstKind::Function(function) => { @@ -284,6 +285,7 @@ impl<'a> Visit<'a> for ReferencesFinder { self.in_function += 1; } } + fn leave_node(&mut self, kind: AstKind<'a>) { if let AstKind::Function(_) = kind { self.in_function -= 1; diff --git a/crates/oxc_linter/src/rules/unicorn/no_useless_spread/const_eval.rs b/crates/oxc_linter/src/rules/unicorn/no_useless_spread/const_eval.rs index 7e0ca4405f8e3..98ebbe2fb19c0 100644 --- a/crates/oxc_linter/src/rules/unicorn/no_useless_spread/const_eval.rs +++ b/crates/oxc_linter/src/rules/unicorn/no_useless_spread/const_eval.rs @@ -37,6 +37,7 @@ impl ValueHint { impl std::ops::BitAnd for ValueHint { type Output = Self; + fn bitand(self, rhs: Self) -> Self::Output { // NOTE: what about (NewArray, NewIterable), e.g. in // `foo ? new Set() : []` diff --git a/crates/oxc_linter/src/rules/unicorn/no_useless_spread/mod.rs b/crates/oxc_linter/src/rules/unicorn/no_useless_spread/mod.rs index cbe55097997f3..79a68fd40434f 100644 --- a/crates/oxc_linter/src/rules/unicorn/no_useless_spread/mod.rs +++ b/crates/oxc_linter/src/rules/unicorn/no_useless_spread/mod.rs @@ -1,5 +1,6 @@ mod const_eval; +use const_eval::{is_array_from, is_new_typed_array, ConstEval}; use oxc_ast::{ ast::{ ArrayExpression, ArrayExpressionElement, CallExpression, Expression, NewExpression, @@ -20,7 +21,6 @@ use crate::{ rule::Rule, AstNode, }; -use const_eval::{is_array_from, is_new_typed_array, ConstEval}; fn spread_in_list(span: Span, x1: &str) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Using a spread operator here creates a new {x1} unnecessarily.")) diff --git a/crates/oxc_linter/src/rules/unicorn/no_useless_undefined.rs b/crates/oxc_linter/src/rules/unicorn/no_useless_undefined.rs index d1ad71fe79021..84a32efcb0439 100644 --- a/crates/oxc_linter/src/rules/unicorn/no_useless_undefined.rs +++ b/crates/oxc_linter/src/rules/unicorn/no_useless_undefined.rs @@ -1,4 +1,3 @@ -use crate::{ast_util::is_method_call, context::LintContext, rule::Rule, AstNode}; use oxc_ast::{ ast::{Argument, CallExpression, Expression, VariableDeclarationKind}, AstKind, @@ -7,6 +6,8 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; +use crate::{ast_util::is_method_call, context::LintContext, rule::Rule, AstNode}; + fn warn() -> OxcDiagnostic { OxcDiagnostic::warn("Do not use useless `undefined`.") .with_help("Consider removing `undefined` or using `null` instead.") @@ -149,6 +150,7 @@ impl Rule for NoUselessUndefined { .unwrap_or(true); Self { check_arguments, check_arrow_function_body } } + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { match node.kind() { AstKind::IdentifierReference(undefined_literal) diff --git a/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs b/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs index 5b70f40961f83..1799d43866a74 100644 --- a/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs +++ b/crates/oxc_linter/src/rules/unicorn/prefer_string_replace_all.rs @@ -4,9 +4,7 @@ use oxc_ast::{ }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; -use oxc_span::{CompactStr, Span}; - -use oxc_span::GetSpan; +use oxc_span::{CompactStr, GetSpan, Span}; use crate::{ast_util::extract_regex_flags, context::LintContext, rule::Rule, AstNode}; diff --git a/crates/oxc_linter/src/table.rs b/crates/oxc_linter/src/table.rs index dc5a4ca3d1d6b..7fe893f733276 100644 --- a/crates/oxc_linter/src/table.rs +++ b/crates/oxc_linter/src/table.rs @@ -146,10 +146,12 @@ impl RuleTableSection { #[cfg(test)] mod test { - use super::*; - use markdown::{to_html_with_options, Options}; use std::sync::OnceLock; + use markdown::{to_html_with_options, Options}; + + use super::*; + static TABLE: OnceLock = OnceLock::new(); fn table() -> &'static RuleTable { diff --git a/crates/oxc_linter/src/utils/react_perf.rs b/crates/oxc_linter/src/utils/react_perf.rs index 56b32fdc9d701..4cf51fdd7653b 100644 --- a/crates/oxc_linter/src/utils/react_perf.rs +++ b/crates/oxc_linter/src/utils/react_perf.rs @@ -1,6 +1,5 @@ use std::fmt; -use crate::{rule::Rule, AstNode, LintContext}; use oxc_ast::{ ast::{ BindingIdentifier, BindingPattern, BindingPatternKind, Expression, JSXAttributeItem, @@ -12,6 +11,8 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_semantic::SymbolId; use oxc_span::Span; +use crate::{rule::Rule, AstNode, LintContext}; + fn react_perf_inline_diagnostic(message: &'static str, attr_span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(message) .with_help(r"simplify props or memoize props in the parent component (https://react.dev/reference/react/memo#my-component-rerenders-when-a-prop-is-an-object-or-array).") diff --git a/crates/oxc_linter/src/utils/vitest.rs b/crates/oxc_linter/src/utils/vitest.rs index 1936e9df9180a..17ff25c533e40 100644 --- a/crates/oxc_linter/src/utils/vitest.rs +++ b/crates/oxc_linter/src/utils/vitest.rs @@ -1,4 +1,3 @@ -use crate::LintContext; use oxc_ast::{ ast::{Argument, CallExpression, Expression}, AstKind, @@ -10,6 +9,7 @@ use super::{ is_equality_matcher, parse_jest_fn_call, ParsedExpectFnCall, ParsedJestFnCallNew, PossibleJestNode, }; +use crate::LintContext; mod valid_vitest_fn; pub use crate::utils::vitest::valid_vitest_fn::VALID_VITEST_FN_CALL_CHAINS; diff --git a/crates/oxc_macros/src/declare_oxc_lint.rs b/crates/oxc_macros/src/declare_oxc_lint.rs index fc75d6fb36602..8f80bcbe30cf4 100644 --- a/crates/oxc_macros/src/declare_oxc_lint.rs +++ b/crates/oxc_macros/src/declare_oxc_lint.rs @@ -126,22 +126,24 @@ fn parse_fix(s: &str) -> proc_macro2::TokenStream { "none" => { return quote! { RuleFixMeta::None }; } - "pending" => { return quote! { RuleFixMeta::FixPending }; } - "fix" => { - return quote! { RuleFixMeta::Fixable(FixKind::SafeFix) } - }, - "suggestion" => { - return quote! { RuleFixMeta::Fixable(FixKind::Suggestion) } - }, + "pending" => { + return quote! { RuleFixMeta::FixPending }; + } + "fix" => return quote! { RuleFixMeta::Fixable(FixKind::SafeFix) }, + "suggestion" => return quote! { RuleFixMeta::Fixable(FixKind::Suggestion) }, // "fix-dangerous" => quote! { RuleFixMeta::Fixable(FixKind::Fix.union(FixKind::Dangerous)) }, // "suggestion" => quote! { RuleFixMeta::Fixable(FixKind::Suggestion) }, // "suggestion-dangerous" => quote! { RuleFixMeta::Fixable(FixKind::Suggestion.union(FixKind::Dangerous)) }, - "conditional" => panic!("Invalid fix capabilities: missing a fix kind. Did you mean 'fix-conditional'?"), + "conditional" => { + panic!("Invalid fix capabilities: missing a fix kind. Did you mean 'fix-conditional'?") + } "None" => panic!("Invalid fix capabilities. Did you mean 'none'?"), "Pending" => panic!("Invalid fix capabilities. Did you mean 'pending'?"), "Fix" => panic!("Invalid fix capabilities. Did you mean 'fix'?"), "Suggestion" => panic!("Invalid fix capabilities. Did you mean 'suggestion'?"), - invalid if !invalid.contains(SEP) => panic!("invalid fix capabilities: {invalid}. Valid capabilities are none, pending, fix, suggestion, or [fix|suggestion]_[conditional?]_[dangerous?]."), + invalid if !invalid.contains(SEP) => panic!( + "invalid fix capabilities: {invalid}. Valid capabilities are none, pending, fix, suggestion, or [fix|suggestion]_[conditional?]_[dangerous?]." + ), _ => {} } diff --git a/crates/oxc_minifier/src/ast_passes/fold_constants.rs b/crates/oxc_minifier/src/ast_passes/fold_constants.rs index 74f925555a93e..2a009a4f07161 100644 --- a/crates/oxc_minifier/src/ast_passes/fold_constants.rs +++ b/crates/oxc_minifier/src/ast_passes/fold_constants.rs @@ -5,7 +5,6 @@ use std::cmp::Ordering; use num_bigint::BigInt; - use oxc_ast::{ast::*, AstBuilder, Visit}; use oxc_span::{GetSpan, Span, SPAN}; use oxc_syntax::{ diff --git a/crates/oxc_minifier/src/ast_passes/mod.rs b/crates/oxc_minifier/src/ast_passes/mod.rs index be21f5a4dce66..3447e36bc9dd9 100644 --- a/crates/oxc_minifier/src/ast_passes/mod.rs +++ b/crates/oxc_minifier/src/ast_passes/mod.rs @@ -6,13 +6,12 @@ mod substitute_alternate_syntax; pub use collapse::Collapse; pub use fold_constants::FoldConstants; -pub use remove_dead_code::RemoveDeadCode; -pub use remove_syntax::RemoveSyntax; -pub use substitute_alternate_syntax::SubstituteAlternateSyntax; - use oxc_ast::ast::Program; use oxc_semantic::{ScopeTree, SymbolTable}; use oxc_traverse::{walk_program, Traverse, TraverseCtx}; +pub use remove_dead_code::RemoveDeadCode; +pub use remove_syntax::RemoveSyntax; +pub use substitute_alternate_syntax::SubstituteAlternateSyntax; use crate::node_util::NodeUtil; diff --git a/crates/oxc_minifier/src/node_util/check_for_state_change.rs b/crates/oxc_minifier/src/node_util/check_for_state_change.rs index bce3ab93cf714..8f5f439a8e8cb 100644 --- a/crates/oxc_minifier/src/node_util/check_for_state_change.rs +++ b/crates/oxc_minifier/src/node_util/check_for_state_change.rs @@ -1,5 +1,4 @@ use oxc_ast::ast::*; - use oxc_syntax::operator::UnaryOperator; /// A "simple" operator is one whose children are expressions, has no direct side-effects. diff --git a/crates/oxc_minifier/src/node_util/mod.rs b/crates/oxc_minifier/src/node_util/mod.rs index 67c0e530ee8eb..38c3e74587faf 100644 --- a/crates/oxc_minifier/src/node_util/mod.rs +++ b/crates/oxc_minifier/src/node_util/mod.rs @@ -7,7 +7,6 @@ use std::borrow::Cow; use num_bigint::BigInt; use num_traits::{One, Zero}; - use oxc_ast::ast::*; use oxc_semantic::{ScopeTree, SymbolTable}; use oxc_syntax::operator::{AssignmentOperator, LogicalOperator, UnaryOperator}; diff --git a/crates/oxc_minifier/src/plugins/replace_global_defines.rs b/crates/oxc_minifier/src/plugins/replace_global_defines.rs index 2c17f55630abc..44681e6fa6f6e 100644 --- a/crates/oxc_minifier/src/plugins/replace_global_defines.rs +++ b/crates/oxc_minifier/src/plugins/replace_global_defines.rs @@ -1,5 +1,4 @@ -use std::cmp::Ordering; -use std::sync::Arc; +use std::{cmp::Ordering, sync::Arc}; use oxc_allocator::Allocator; use oxc_ast::{ast::*, visit::walk_mut, AstBuilder, VisitMut}; diff --git a/crates/oxc_parser/src/js/object.rs b/crates/oxc_parser/src/js/object.rs index ac4f3db719556..e69a98d9a430e 100644 --- a/crates/oxc_parser/src/js/object.rs +++ b/crates/oxc_parser/src/js/object.rs @@ -73,7 +73,9 @@ impl<'a> ParserImpl<'a> { self.error(diagnostics::modifier_cannot_be_used_here(&modifier)); } else { #[cfg(debug_assertions)] - panic!("Kind::is_modifier_kind() is true but the token could not be converted to a Modifier.") + panic!( + "Kind::is_modifier_kind() is true but the token could not be converted to a Modifier." + ) } // re-parse self.bump_any(); diff --git a/crates/oxc_parser/src/lexer/regex.rs b/crates/oxc_parser/src/lexer/regex.rs index 5e0a1adf6f13f..8d009124d9aea 100644 --- a/crates/oxc_parser/src/lexer/regex.rs +++ b/crates/oxc_parser/src/lexer/regex.rs @@ -1,8 +1,8 @@ +use oxc_diagnostics::Result; use oxc_syntax::identifier::is_line_terminator; use super::{Kind, Lexer, RegExpFlags, Token}; use crate::diagnostics; -use oxc_diagnostics::Result; impl<'a> Lexer<'a> { /// Re-tokenize the current `/` or `/=` and return `RegExp` diff --git a/crates/oxc_parser/src/modifiers.rs b/crates/oxc_parser/src/modifiers.rs index 338376fb6607c..8c9adffffed58 100644 --- a/crates/oxc_parser/src/modifiers.rs +++ b/crates/oxc_parser/src/modifiers.rs @@ -1,5 +1,4 @@ use bitflags::bitflags; - use oxc_allocator::Vec; use oxc_ast::ast::TSAccessibility; use oxc_diagnostics::{OxcDiagnostic, Result}; @@ -263,6 +262,7 @@ impl ModifierKind { } impl TryFrom for ModifierKind { type Error = (); + fn try_from(kind: Kind) -> std::result::Result { match kind { Kind::Abstract => Ok(Self::Abstract), diff --git a/crates/oxc_parser/src/ts/statement.rs b/crates/oxc_parser/src/ts/statement.rs index bf05d05a039be..9d7039e899134 100644 --- a/crates/oxc_parser/src/ts/statement.rs +++ b/crates/oxc_parser/src/ts/statement.rs @@ -98,6 +98,7 @@ impl<'a> ParserImpl<'a> { } } } + fn check_invalid_ts_enum_computed_property(&mut self, property: &Expression<'a>) { match property { Expression::StringLiteral(_) => {} diff --git a/crates/oxc_regular_expression/src/ast.rs b/crates/oxc_regular_expression/src/ast.rs index e398a4349d0e2..5db3e44200687 100644 --- a/crates/oxc_regular_expression/src/ast.rs +++ b/crates/oxc_regular_expression/src/ast.rs @@ -8,7 +8,6 @@ use oxc_allocator::{Box, CloneIn, Vec}; use oxc_ast_macros::ast; use oxc_span::{cmp::ContentEq, hash::ContentHash, Atom, Span}; - #[cfg(feature = "serialize")] use serde::Serialize; #[cfg(feature = "serialize")] diff --git a/crates/oxc_regular_expression/src/body_parser/mod.rs b/crates/oxc_regular_expression/src/body_parser/mod.rs index be0e18bd65dcf..077cea928c967 100644 --- a/crates/oxc_regular_expression/src/body_parser/mod.rs +++ b/crates/oxc_regular_expression/src/body_parser/mod.rs @@ -9,9 +9,10 @@ pub use parser::PatternParser; #[cfg(test)] mod test { - use crate::{ParserOptions, PatternParser}; use oxc_allocator::Allocator; + use crate::{ParserOptions, PatternParser}; + #[test] fn should_pass() { let allocator = Allocator::default(); diff --git a/crates/oxc_regular_expression/src/body_parser/parser.rs b/crates/oxc_regular_expression/src/body_parser/parser.rs index 4d180c1bada40..44c84a99f8dad 100644 --- a/crates/oxc_regular_expression/src/body_parser/parser.rs +++ b/crates/oxc_regular_expression/src/body_parser/parser.rs @@ -562,6 +562,7 @@ impl<'a> PatternParser<'a> { kind, }) } + // ``` // CharacterClassEscape[UnicodeMode] :: // [+UnicodeMode] p{ UnicodePropertyValueExpression } diff --git a/crates/oxc_regular_expression/src/lib.rs b/crates/oxc_regular_expression/src/lib.rs index d3720a7096727..9177cd4c4a5ed 100644 --- a/crates/oxc_regular_expression/src/lib.rs +++ b/crates/oxc_regular_expression/src/lib.rs @@ -15,7 +15,7 @@ mod generated { mod derive_content_hash; } -pub use crate::body_parser::PatternParser; -pub use crate::flag_parser::FlagsParser; -pub use crate::literal_parser::Parser; -pub use crate::options::ParserOptions; +pub use crate::{ + body_parser::PatternParser, flag_parser::FlagsParser, literal_parser::Parser, + options::ParserOptions, +}; diff --git a/crates/oxc_semantic/src/checker/typescript.rs b/crates/oxc_semantic/src/checker/typescript.rs index 51ac2d48ac175..43beef69ff074 100644 --- a/crates/oxc_semantic/src/checker/typescript.rs +++ b/crates/oxc_semantic/src/checker/typescript.rs @@ -258,7 +258,12 @@ fn abstract_element_cannot_have_initializer( span: Span, init_or_impl: &str, ) -> OxcDiagnostic { - ts_error(code, format!("{elem_name} '{prop_name}' cannot have an {init_or_impl} because it is marked abstract.")) + ts_error( + code, + format!( + "{elem_name} '{prop_name}' cannot have an {init_or_impl} because it is marked abstract." + ), + ) .with_label(span) } diff --git a/crates/oxc_semantic/src/counter.rs b/crates/oxc_semantic/src/counter.rs index cca87e48186b0..2a06e2bee6808 100644 --- a/crates/oxc_semantic/src/counter.rs +++ b/crates/oxc_semantic/src/counter.rs @@ -25,6 +25,7 @@ impl<'a> Visit<'a> for Counter { fn enter_node(&mut self, _: AstKind<'a>) { self.nodes_count += 1; } + #[inline] fn enter_scope(&mut self, _: ScopeFlags, _: &Cell>) { self.scopes_count += 1; diff --git a/crates/oxc_semantic/src/post_transform_checker.rs b/crates/oxc_semantic/src/post_transform_checker.rs index a568548699c6b..d87736a8666f0 100644 --- a/crates/oxc_semantic/src/post_transform_checker.rs +++ b/crates/oxc_semantic/src/post_transform_checker.rs @@ -92,8 +92,6 @@ use std::{ }; use indexmap::IndexMap; -use rustc_hash::FxHasher; - use oxc_allocator::{Allocator, CloneIn}; #[allow(clippy::wildcard_imports)] use oxc_ast::{ast::*, visit::walk, Visit}; @@ -104,6 +102,7 @@ use oxc_syntax::{ scope::{ScopeFlags, ScopeId}, symbol::SymbolId, }; +use rustc_hash::FxHasher; use crate::{ScopeTree, SemanticBuilder, SymbolTable}; diff --git a/crates/oxc_semantic/src/unresolved_stack.rs b/crates/oxc_semantic/src/unresolved_stack.rs index d9500ce92770b..4991241aeb2a3 100644 --- a/crates/oxc_semantic/src/unresolved_stack.rs +++ b/crates/oxc_semantic/src/unresolved_stack.rs @@ -1,8 +1,7 @@ use assert_unchecked::assert_unchecked; use oxc_span::Atom; -use rustc_hash::FxHashMap; - use oxc_syntax::reference::ReferenceId; +use rustc_hash::FxHashMap; /// The difference with Scope's `UnresolvedReferences` is that this type uses Atom as the key. its clone is very cheap! type TempUnresolvedReferences<'a> = FxHashMap, Vec>; @@ -21,16 +20,16 @@ pub(crate) struct UnresolvedReferencesStack<'a> { } impl<'a> UnresolvedReferencesStack<'a> { + // Initial scope depth. + // Start on 1 (`Program` scope depth). + // SAFETY: Must be >= 1 to ensure soundness of `current_and_parent_mut`. + const INITIAL_DEPTH: usize = 1; // Most programs will have at least 1 place where scope depth reaches 16, // so initialize `stack` with this length, to reduce reallocations as it grows. // This is just an estimate of a good initial size, but certainly better than // `Vec`'s default initial capacity of 4. // SAFETY: Must be >= 2 to ensure soundness of `current_and_parent_mut`. const INITIAL_SIZE: usize = 16; - // Initial scope depth. - // Start on 1 (`Program` scope depth). - // SAFETY: Must be >= 1 to ensure soundness of `current_and_parent_mut`. - const INITIAL_DEPTH: usize = 1; #[allow(clippy::assertions_on_constants)] const _SIZE_CHECK: () = assert!(Self::INITIAL_SIZE > Self::INITIAL_DEPTH); diff --git a/crates/oxc_semantic/tests/integration/modules.rs b/crates/oxc_semantic/tests/integration/modules.rs index 86d0e7f45181d..6f4cb4b00a261 100644 --- a/crates/oxc_semantic/tests/integration/modules.rs +++ b/crates/oxc_semantic/tests/integration/modules.rs @@ -231,7 +231,10 @@ fn test_export_in_invalid_scope() { .expect_errors(true); test.has_some_symbol("x").contains_flags(SymbolFlags::Export).test(); let SemanticBuilderReturn { semantic, errors } = test.build_with_errors(); - assert!(!errors.is_empty(), "expected an export within a function to produce a check error, but no errors were produced"); + assert!( + !errors.is_empty(), + "expected an export within a function to produce a check error, but no errors were produced" + ); assert!(semantic.module_record().exported_bindings.is_empty()); } diff --git a/crates/oxc_semantic/tests/integration/scopes.rs b/crates/oxc_semantic/tests/integration/scopes.rs index cd12d4fe9c03f..3573e958e095c 100644 --- a/crates/oxc_semantic/tests/integration/scopes.rs +++ b/crates/oxc_semantic/tests/integration/scopes.rs @@ -202,7 +202,11 @@ fn test_enums() { "Expected `enum A` to be created in the top-level scope." ); let enum_decl_scope_id = enum_decl.scope_id.get().expect("Enum declaration has no scope id"); - assert_ne!(enum_node.scope_id(), enum_decl_scope_id, "Enum declaration nodes should contain the scope ID they create, not the scope ID they're created in."); + assert_ne!( + enum_node.scope_id(), + enum_decl_scope_id, + "Enum declaration nodes should contain the scope ID they create, not the scope ID they're created in." + ); assert_eq!(enum_decl.members.len(), 3); } diff --git a/crates/oxc_span/src/atom.rs b/crates/oxc_span/src/atom.rs index 8a0541d9613cf..213dbd614f10e 100644 --- a/crates/oxc_span/src/atom.rs +++ b/crates/oxc_span/src/atom.rs @@ -5,11 +5,11 @@ use std::{ }; use compact_str::CompactString; +use oxc_allocator::{Allocator, CloneIn, FromIn}; #[cfg(feature = "serialize")] use serde::{Serialize, Serializer}; use crate::{cmp::ContentEq, hash::ContentHash, Span}; -use oxc_allocator::{Allocator, CloneIn, FromIn}; #[cfg(feature = "serialize")] #[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)] @@ -438,9 +438,10 @@ impl schemars::JsonSchema for CompactStr { #[cfg(test)] mod test { - use super::CompactStr; use compact_str::CompactString; + use super::CompactStr; + #[test] fn test_compactstr_eq() { let foo = CompactStr::new("foo"); diff --git a/crates/oxc_span/src/source_type/error.rs b/crates/oxc_span/src/source_type/error.rs index 72334364aaf2e..69aa693ce72d4 100644 --- a/crates/oxc_span/src/source_type/error.rs +++ b/crates/oxc_span/src/source_type/error.rs @@ -9,6 +9,7 @@ pub struct UnknownExtension(/* msg */ pub(crate) Cow<'static, str>); impl Deref for UnknownExtension { type Target = str; + fn deref(&self) -> &str { &self.0 } diff --git a/crates/oxc_span/src/source_type/mod.rs b/crates/oxc_span/src/source_type/mod.rs index 372d2093a6c77..6c0ceb42ea9aa 100644 --- a/crates/oxc_span/src/source_type/mod.rs +++ b/crates/oxc_span/src/source_type/mod.rs @@ -1,9 +1,10 @@ mod error; mod types; +use std::{hash::Hash, path::Path}; + pub use error::UnknownExtension; use oxc_allocator::{Allocator, CloneIn}; -use std::{hash::Hash, path::Path}; pub use types::*; use crate::{cmp::ContentEq, hash::ContentHash}; @@ -17,6 +18,7 @@ impl Default for SourceType { impl<'a> CloneIn<'a> for SourceType { type Cloned = Self; + #[inline] fn clone_in(&self, _: &'a Allocator) -> Self { *self diff --git a/crates/oxc_span/src/span/mod.rs b/crates/oxc_span/src/span/mod.rs index 1f332e914f117..fb928f2a51d9c 100644 --- a/crates/oxc_span/src/span/mod.rs +++ b/crates/oxc_span/src/span/mod.rs @@ -388,6 +388,7 @@ impl GetSpanMut for Span { impl<'a> CloneIn<'a> for Span { type Cloned = Self; + #[inline] fn clone_in(&self, _: &'a Allocator) -> Self { *self diff --git a/crates/oxc_span/src/span/types.rs b/crates/oxc_span/src/span/types.rs index ede19af712088..b470f04f75d34 100644 --- a/crates/oxc_span/src/span/types.rs +++ b/crates/oxc_span/src/span/types.rs @@ -1,11 +1,10 @@ // Silence erroneous warnings from Rust Analyser for `#[derive(Tsify)]` #![allow(non_snake_case)] +use oxc_ast_macros::ast; #[cfg(feature = "serialize")] use ::{serde::Serialize, tsify::Tsify}; -use oxc_ast_macros::ast; - /// Newtype for working with text ranges /// /// See the [`text-size`](https://docs.rs/text-size) crate for details. diff --git a/crates/oxc_syntax/src/identifier.rs b/crates/oxc_syntax/src/identifier.rs index 96b3342559112..ef5343f148beb 100644 --- a/crates/oxc_syntax/src/identifier.rs +++ b/crates/oxc_syntax/src/identifier.rs @@ -1,5 +1,4 @@ use assert_unchecked::assert_unchecked; - use unicode_id_start::{is_id_continue_unicode, is_id_start_unicode}; pub const EOF: char = '\0'; diff --git a/crates/oxc_syntax/src/node.rs b/crates/oxc_syntax/src/node.rs index d0d5288dedc4f..9efc14db981ae 100644 --- a/crates/oxc_syntax/src/node.rs +++ b/crates/oxc_syntax/src/node.rs @@ -1,11 +1,9 @@ use bitflags::bitflags; - use nonmax::NonMaxU32; +use oxc_index::Idx; #[cfg(feature = "serialize")] use serde::{Serialize, Serializer}; -use oxc_index::Idx; - #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct AstNodeId(NonMaxU32); diff --git a/crates/oxc_syntax/src/operator.rs b/crates/oxc_syntax/src/operator.rs index 0e9855f657965..8f1892432fc24 100644 --- a/crates/oxc_syntax/src/operator.rs +++ b/crates/oxc_syntax/src/operator.rs @@ -1,12 +1,11 @@ // Silence erroneous warnings from Rust Analyser for `#[derive(Tsify)]` #![allow(non_snake_case)] -#[cfg(feature = "serialize")] -use ::{serde::Serialize, tsify::Tsify}; - use oxc_allocator::CloneIn; use oxc_ast_macros::ast; use oxc_span::{cmp::ContentEq, hash::ContentHash}; +#[cfg(feature = "serialize")] +use ::{serde::Serialize, tsify::Tsify}; use crate::precedence::{GetPrecedence, Precedence}; diff --git a/crates/oxc_syntax/src/reference.rs b/crates/oxc_syntax/src/reference.rs index f2b0a4a6d2a79..bf4c267e55a63 100644 --- a/crates/oxc_syntax/src/reference.rs +++ b/crates/oxc_syntax/src/reference.rs @@ -1,11 +1,10 @@ use bitflags::bitflags; use nonmax::NonMaxU32; use oxc_allocator::CloneIn; +use oxc_index::Idx; #[cfg(feature = "serialize")] use serde::{Serialize, Serializer}; -use oxc_index::Idx; - #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct ReferenceId(NonMaxU32); @@ -165,6 +164,7 @@ impl ReferenceFlags { impl<'alloc> CloneIn<'alloc> for ReferenceFlags { type Cloned = Self; + fn clone_in(&self, _: &'alloc oxc_allocator::Allocator) -> Self::Cloned { *self } diff --git a/crates/oxc_syntax/src/scope.rs b/crates/oxc_syntax/src/scope.rs index 3bf3a7b223f43..d5ca05c436453 100644 --- a/crates/oxc_syntax/src/scope.rs +++ b/crates/oxc_syntax/src/scope.rs @@ -1,10 +1,9 @@ use bitflags::bitflags; use nonmax::NonMaxU32; +use oxc_index::Idx; #[cfg(feature = "serialize")] use serde::{Serialize, Serializer}; -use oxc_index::Idx; - #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct ScopeId(NonMaxU32); diff --git a/crates/oxc_syntax/src/symbol.rs b/crates/oxc_syntax/src/symbol.rs index 1ac6e953127ef..20a932c99811f 100644 --- a/crates/oxc_syntax/src/symbol.rs +++ b/crates/oxc_syntax/src/symbol.rs @@ -1,10 +1,9 @@ use bitflags::bitflags; use nonmax::NonMaxU32; +use oxc_index::Idx; #[cfg(feature = "serialize")] use serde::{Serialize, Serializer}; -use oxc_index::Idx; - #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct SymbolId(NonMaxU32); diff --git a/crates/oxc_transformer/src/env/targets/mod.rs b/crates/oxc_transformer/src/env/targets/mod.rs index 5f469a8fe9a46..345c50dce8097 100644 --- a/crates/oxc_transformer/src/env/targets/mod.rs +++ b/crates/oxc_transformer/src/env/targets/mod.rs @@ -10,9 +10,8 @@ use std::ops::{Deref, DerefMut}; use rustc_hash::FxHashMap; use serde::Deserialize; -use self::version::Version; - pub use self::query::Targets; +use self::version::Version; pub mod query; pub mod version; diff --git a/crates/oxc_transformer/src/es2015/options.rs b/crates/oxc_transformer/src/es2015/options.rs index d248163cc2b37..7864ca7f72024 100644 --- a/crates/oxc_transformer/src/es2015/options.rs +++ b/crates/oxc_transformer/src/es2015/options.rs @@ -1,8 +1,7 @@ use serde::Deserialize; -use crate::env::{can_enable_plugin, Versions}; - use super::ArrowFunctionsOptions; +use crate::env::{can_enable_plugin, Versions}; #[derive(Debug, Default, Clone, Deserialize)] #[serde(default, rename_all = "camelCase", deny_unknown_fields)] diff --git a/crates/oxc_transformer/src/es2016/mod.rs b/crates/oxc_transformer/src/es2016/mod.rs index 9ec05ea231ee8..857c4fa012623 100644 --- a/crates/oxc_transformer/src/es2016/mod.rs +++ b/crates/oxc_transformer/src/es2016/mod.rs @@ -1,12 +1,13 @@ mod exponentiation_operator; mod options; +use std::rc::Rc; + pub use exponentiation_operator::ExponentiationOperator; pub use options::ES2016Options; use oxc_allocator::Vec; use oxc_ast::ast::*; use oxc_traverse::{Traverse, TraverseCtx}; -use std::rc::Rc; use crate::context::Ctx; diff --git a/crates/oxc_transformer/src/es2018/mod.rs b/crates/oxc_transformer/src/es2018/mod.rs index a8e14f75ae913..c3c686ca819e0 100644 --- a/crates/oxc_transformer/src/es2018/mod.rs +++ b/crates/oxc_transformer/src/es2018/mod.rs @@ -1,11 +1,12 @@ mod object_rest_spread; mod options; +use std::rc::Rc; + pub use object_rest_spread::{ObjectRestSpread, ObjectRestSpreadOptions}; pub use options::ES2018Options; use oxc_ast::ast::*; use oxc_traverse::{Traverse, TraverseCtx}; -use std::rc::Rc; use crate::context::Ctx; diff --git a/crates/oxc_transformer/src/es2018/object_rest_spread/mod.rs b/crates/oxc_transformer/src/es2018/object_rest_spread/mod.rs index 21eac149cf448..985889b73e5f5 100644 --- a/crates/oxc_transformer/src/es2018/object_rest_spread/mod.rs +++ b/crates/oxc_transformer/src/es2018/object_rest_spread/mod.rs @@ -26,14 +26,15 @@ //! * Babel plugin implementation: //! * Object rest/spread TC39 proposal: -use crate::context::Ctx; +use std::rc::Rc; use object_rest::ObjectRest; use object_spread::ObjectSpread; use oxc_ast::ast::*; use oxc_traverse::{Traverse, TraverseCtx}; use serde::Deserialize; -use std::rc::Rc; + +use crate::context::Ctx; mod object_rest; mod object_spread; diff --git a/crates/oxc_transformer/src/es2018/object_rest_spread/object_rest.rs b/crates/oxc_transformer/src/es2018/object_rest_spread/object_rest.rs index aa31390ccfe30..8e943d1c3ea37 100644 --- a/crates/oxc_transformer/src/es2018/object_rest_spread/object_rest.rs +++ b/crates/oxc_transformer/src/es2018/object_rest_spread/object_rest.rs @@ -24,9 +24,8 @@ //! * Babel plugin implementation: //! * Object rest/spread TC39 proposal: -use crate::context::Ctx; - use super::ObjectRestSpreadOptions; +use crate::context::Ctx; pub struct ObjectRest<'a> { _ctx: Ctx<'a>, diff --git a/crates/oxc_transformer/src/es2018/object_rest_spread/object_spread.rs b/crates/oxc_transformer/src/es2018/object_rest_spread/object_spread.rs index 538b16c5e8b79..52aac1a905b36 100644 --- a/crates/oxc_transformer/src/es2018/object_rest_spread/object_spread.rs +++ b/crates/oxc_transformer/src/es2018/object_rest_spread/object_spread.rs @@ -26,14 +26,13 @@ //! * Babel plugin implementation: //! * Object rest/spread TC39 proposal: -use crate::context::Ctx; - use oxc_ast::ast::*; use oxc_semantic::{ReferenceFlags, SymbolId}; use oxc_span::SPAN; use oxc_traverse::{Traverse, TraverseCtx}; use super::ObjectRestSpreadOptions; +use crate::context::Ctx; pub struct ObjectSpread<'a> { _ctx: Ctx<'a>, diff --git a/crates/oxc_transformer/src/es2018/options.rs b/crates/oxc_transformer/src/es2018/options.rs index a5d9688bfbecf..1ac1831c114c1 100644 --- a/crates/oxc_transformer/src/es2018/options.rs +++ b/crates/oxc_transformer/src/es2018/options.rs @@ -1,8 +1,7 @@ -use crate::env::{can_enable_plugin, Versions}; - use serde::Deserialize; use super::ObjectRestSpreadOptions; +use crate::env::{can_enable_plugin, Versions}; #[derive(Debug, Default, Clone, Deserialize)] #[serde(default, rename_all = "camelCase", deny_unknown_fields)] diff --git a/crates/oxc_transformer/src/es2019/mod.rs b/crates/oxc_transformer/src/es2019/mod.rs index c8cbb52242d10..452e659a7a998 100644 --- a/crates/oxc_transformer/src/es2019/mod.rs +++ b/crates/oxc_transformer/src/es2019/mod.rs @@ -1,11 +1,12 @@ mod optional_catch_binding; mod options; +use std::rc::Rc; + pub use optional_catch_binding::OptionalCatchBinding; pub use options::ES2019Options; use oxc_ast::ast::*; use oxc_traverse::{Traverse, TraverseCtx}; -use std::rc::Rc; use crate::context::Ctx; diff --git a/crates/oxc_transformer/src/es2020/mod.rs b/crates/oxc_transformer/src/es2020/mod.rs index d541a4f8fa117..1f7e3a47e7c55 100644 --- a/crates/oxc_transformer/src/es2020/mod.rs +++ b/crates/oxc_transformer/src/es2020/mod.rs @@ -1,12 +1,13 @@ mod nullish_coalescing_operator; mod options; +use std::rc::Rc; + pub use nullish_coalescing_operator::NullishCoalescingOperator; pub use options::ES2020Options; use oxc_allocator::Vec; use oxc_ast::ast::*; use oxc_traverse::{Traverse, TraverseCtx}; -use std::rc::Rc; use crate::context::Ctx; diff --git a/crates/oxc_transformer/src/es2020/nullish_coalescing_operator.rs b/crates/oxc_transformer/src/es2020/nullish_coalescing_operator.rs index 5d1c54ab198df..51e3518ca5562 100644 --- a/crates/oxc_transformer/src/es2020/nullish_coalescing_operator.rs +++ b/crates/oxc_transformer/src/es2020/nullish_coalescing_operator.rs @@ -30,13 +30,12 @@ use std::cell::Cell; -use oxc_semantic::{ReferenceFlags, ScopeFlags, ScopeId, SymbolFlags}; -use oxc_traverse::{Ancestor, Traverse, TraverseCtx}; - use oxc_allocator::{CloneIn, Vec}; use oxc_ast::ast::*; +use oxc_semantic::{ReferenceFlags, ScopeFlags, ScopeId, SymbolFlags}; use oxc_span::SPAN; use oxc_syntax::operator::{AssignmentOperator, BinaryOperator, LogicalOperator}; +use oxc_traverse::{Ancestor, Traverse, TraverseCtx}; use crate::context::Ctx; diff --git a/crates/oxc_transformer/src/es2021/mod.rs b/crates/oxc_transformer/src/es2021/mod.rs index 392ff00949f2b..6a94877c296b0 100644 --- a/crates/oxc_transformer/src/es2021/mod.rs +++ b/crates/oxc_transformer/src/es2021/mod.rs @@ -1,12 +1,13 @@ mod logical_assignment_operators; mod options; +use std::rc::Rc; + pub use logical_assignment_operators::LogicalAssignmentOperators; pub use options::ES2021Options; use oxc_allocator::Vec; use oxc_ast::ast::*; use oxc_traverse::{Traverse, TraverseCtx}; -use std::rc::Rc; use crate::context::Ctx; diff --git a/crates/oxc_transformer/src/lib.rs b/crates/oxc_transformer/src/lib.rs index d6d20c76694d2..4d968ecc24d01 100644 --- a/crates/oxc_transformer/src/lib.rs +++ b/crates/oxc_transformer/src/lib.rs @@ -165,6 +165,7 @@ impl<'a> Traverse<'a> for Transformer<'a> { fn enter_class_body(&mut self, body: &mut ClassBody<'a>, ctx: &mut TraverseCtx<'a>) { self.x0_typescript.enter_class_body(body, ctx); } + fn enter_ts_module_declaration( &mut self, decl: &mut TSModuleDeclaration<'a>, @@ -296,7 +297,9 @@ impl<'a> Traverse<'a> for Transformer<'a> { if arrow.expression && arrow.body.statements.len() > 1 { let Statement::ExpressionStatement(statement) = arrow.body.statements.pop().unwrap() else { - unreachable!("The last statement in an ArrowFunctionExpression should always be an ExpressionStatement.") + unreachable!( + "The last statement in an ArrowFunctionExpression should always be an ExpressionStatement." + ) }; arrow .body diff --git a/crates/oxc_transformer/src/typescript/annotations.rs b/crates/oxc_transformer/src/typescript/annotations.rs index 7aaf1f09e2216..9d2d819f44b88 100644 --- a/crates/oxc_transformer/src/typescript/annotations.rs +++ b/crates/oxc_transformer/src/typescript/annotations.rs @@ -155,6 +155,7 @@ impl<'a> Traverse<'a> for TypeScriptAnnotations<'a> { program.body.push(self.ctx.ast.statement_module_declaration(export_decl)); } } + fn enter_arrow_function_expression( &mut self, expr: &mut ArrowFunctionExpression<'a>, diff --git a/crates/oxc_transformer/src/typescript/namespace.rs b/crates/oxc_transformer/src/typescript/namespace.rs index c2ee4a676b476..e8b7b4339adeb 100644 --- a/crates/oxc_transformer/src/typescript/namespace.rs +++ b/crates/oxc_transformer/src/typescript/namespace.rs @@ -11,12 +11,11 @@ use oxc_syntax::{ use oxc_traverse::{Traverse, TraverseCtx}; use rustc_hash::FxHashSet; -use crate::context::Ctx; - use super::{ diagnostics::{ambient_module_nested, namespace_exporting_non_const, namespace_not_supported}, TypeScriptOptions, }; +use crate::context::Ctx; pub struct TypeScriptNamespace<'a> { ctx: Ctx<'a>, diff --git a/crates/oxc_transformer/src/typescript/options.rs b/crates/oxc_transformer/src/typescript/options.rs index 656fa1dcb4eed..e21636d8bfe73 100644 --- a/crates/oxc_transformer/src/typescript/options.rs +++ b/crates/oxc_transformer/src/typescript/options.rs @@ -159,7 +159,9 @@ where match value { "rewrite" => Ok(Some(RewriteExtensionsMode::Rewrite)), "remove" => Ok(Some(RewriteExtensionsMode::Remove)), - _ => Err(E::custom(format!("Expected RewriteExtensionsMode is either \"rewrite\" or \"remove\" but found: {value}"))), + _ => Err(E::custom(format!( + "Expected RewriteExtensionsMode is either \"rewrite\" or \"remove\" but found: {value}" + ))), } } } diff --git a/crates/oxc_traverse/src/lib.rs b/crates/oxc_traverse/src/lib.rs index fb0eefe82a358..57dbf53aa2d1f 100644 --- a/crates/oxc_traverse/src/lib.rs +++ b/crates/oxc_traverse/src/lib.rs @@ -73,11 +73,8 @@ mod generated { pub mod traverse; pub(super) mod walk; } -pub use generated::ancestor; -pub use generated::ancestor::Ancestor; -use generated::scopes_collector; -pub use generated::traverse::Traverse; -use generated::walk; +pub use generated::{ancestor, ancestor::Ancestor, traverse::Traverse}; +use generated::{scopes_collector, walk}; mod compile_fail_tests; diff --git a/napi/parser/src/lib.rs b/napi/parser/src/lib.rs index a7348a4c7a6cc..4b439efa69758 100644 --- a/napi/parser/src/lib.rs +++ b/napi/parser/src/lib.rs @@ -139,8 +139,8 @@ pub struct ResolveTask { #[napi] impl Task for ResolveTask { - type Output = ParseResult; type JsValue = ParseResult; + type Output = ParseResult; fn compute(&mut self) -> napi::Result { Ok(parse_with_return(&self.source_text, &self.options)) diff --git a/napi/parser/src/module_lexer.rs b/napi/parser/src/module_lexer.rs index 2f51b3007fb5b..765a7e8403123 100644 --- a/napi/parser/src/module_lexer.rs +++ b/napi/parser/src/module_lexer.rs @@ -140,8 +140,8 @@ pub struct ResolveTask { #[napi] impl Task for ResolveTask { - type Output = ModuleLexer; type JsValue = ModuleLexer; + type Output = ModuleLexer; fn compute(&mut self) -> napi::Result { Ok(module_lexer(&self.source_text, &self.options)) diff --git a/napi/transform/src/context.rs b/napi/transform/src/context.rs index a8d2aee8cb389..6a9f8247668c0 100644 --- a/napi/transform/src/context.rs +++ b/napi/transform/src/context.rs @@ -1,12 +1,12 @@ -use oxc_allocator::Allocator; -use oxc_ast::{ast::Program, Trivias}; -use oxc_codegen::Codegen; use std::{ cell::{OnceCell, Ref, RefCell, RefMut}, path::Path, sync::Arc, }; +use oxc_allocator::Allocator; +use oxc_ast::{ast::Program, Trivias}; +use oxc_codegen::Codegen; use oxc_diagnostics::{Error, NamedSource, OxcDiagnostic}; use oxc_parser::{Parser, ParserReturn}; use oxc_span::SourceType; @@ -86,6 +86,7 @@ impl<'a> TransformContext<'a> { pub fn file_name(&self) -> &'a str { self.filename } + #[inline] pub fn file_path(&self) -> &'a Path { Path::new(self.filename) diff --git a/napi/transform/src/isolated_declaration.rs b/napi/transform/src/isolated_declaration.rs index 33b8be0164118..5015a935eeed6 100644 --- a/napi/transform/src/isolated_declaration.rs +++ b/napi/transform/src/isolated_declaration.rs @@ -1,5 +1,4 @@ use napi_derive::napi; - use oxc_allocator::Allocator; use oxc_codegen::CodegenReturn; use oxc_isolated_declarations::IsolatedDeclarations; diff --git a/napi/transform/src/options.rs b/napi/transform/src/options.rs index 37c2fb556163f..dfe8cce1f620a 100644 --- a/napi/transform/src/options.rs +++ b/napi/transform/src/options.rs @@ -2,7 +2,6 @@ use std::path::PathBuf; use napi::Either; use napi_derive::napi; - use oxc_transformer::{ ArrowFunctionsOptions, ES2015Options, ReactJsxRuntime, ReactOptions, RewriteExtensionsMode, TypeScriptOptions, diff --git a/napi/transform/src/transformer.rs b/napi/transform/src/transformer.rs index 63b82bae9dc54..88b26b6f69e25 100644 --- a/napi/transform/src/transformer.rs +++ b/napi/transform/src/transformer.rs @@ -1,12 +1,12 @@ use napi_derive::napi; - -use crate::{context::TransformContext, isolated_declaration, SourceMap, TransformOptions}; use oxc_allocator::Allocator; use oxc_codegen::CodegenReturn; use oxc_semantic::SemanticBuilder; use oxc_span::SourceType; use oxc_transformer::Transformer; +use crate::{context::TransformContext, isolated_declaration, SourceMap, TransformOptions}; + // NOTE: Use JSDoc syntax for all doc comments, not rustdoc. // NOTE: Types must be aligned with [@types/babel__core](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/babel__core/index.d.ts). diff --git a/tasks/ast_tools/src/derives/clone_in.rs b/tasks/ast_tools/src/derives/clone_in.rs index 502a844c99113..58108b7baf18a 100644 --- a/tasks/ast_tools/src/derives/clone_in.rs +++ b/tasks/ast_tools/src/derives/clone_in.rs @@ -3,14 +3,13 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::Ident; +use super::{define_derive, Derive, DeriveOutput}; use crate::{ codegen::LateCtx, markers::CloneInAttribute, schema::{EnumDef, GetIdent, StructDef, TypeDef}, }; -use super::{define_derive, Derive, DeriveOutput}; - define_derive! { pub struct DeriveCloneIn; } diff --git a/tasks/ast_tools/src/derives/content_eq.rs b/tasks/ast_tools/src/derives/content_eq.rs index 7ba98e13bda7c..29c1b59f43a22 100644 --- a/tasks/ast_tools/src/derives/content_eq.rs +++ b/tasks/ast_tools/src/derives/content_eq.rs @@ -2,14 +2,13 @@ use itertools::Itertools; use proc_macro2::TokenStream; use quote::quote; +use super::{define_derive, Derive, DeriveOutput}; use crate::{ codegen::LateCtx, schema::{EnumDef, GetGenerics, StructDef, ToType, TypeDef}, util::ToIdent, }; -use super::{define_derive, Derive, DeriveOutput}; - define_derive! { pub struct DeriveContentEq; } diff --git a/tasks/ast_tools/src/derives/content_hash.rs b/tasks/ast_tools/src/derives/content_hash.rs index 1cab2ac020727..9a129e8913fcb 100644 --- a/tasks/ast_tools/src/derives/content_hash.rs +++ b/tasks/ast_tools/src/derives/content_hash.rs @@ -2,14 +2,13 @@ use itertools::Itertools; use proc_macro2::TokenStream; use quote::quote; +use super::{define_derive, Derive, DeriveOutput}; use crate::{ codegen::LateCtx, schema::{EnumDef, GetGenerics, StructDef, ToType, TypeDef}, util::ToIdent, }; -use super::{define_derive, Derive, DeriveOutput}; - define_derive! { pub struct DeriveContentHash; } diff --git a/tasks/ast_tools/src/derives/get_span.rs b/tasks/ast_tools/src/derives/get_span.rs index 4d44c969acdd7..a26e20c21ef28 100644 --- a/tasks/ast_tools/src/derives/get_span.rs +++ b/tasks/ast_tools/src/derives/get_span.rs @@ -2,14 +2,13 @@ use proc_macro2::TokenStream; use quote::quote; use syn::Ident; +use super::{define_derive, Derive, DeriveOutput}; use crate::{ codegen::LateCtx, schema::{EnumDef, GetGenerics, StructDef, ToType, TypeDef}, util::{ToIdent, TypeWrapper}, }; -use super::{define_derive, Derive, DeriveOutput}; - define_derive! { pub struct DeriveGetSpan; } diff --git a/tasks/ast_tools/src/derives/mod.rs b/tasks/ast_tools/src/derives/mod.rs index cdcdb1ae6b337..555667a474e62 100644 --- a/tasks/ast_tools/src/derives/mod.rs +++ b/tasks/ast_tools/src/derives/mod.rs @@ -1,6 +1,7 @@ -use proc_macro2::TokenStream; use std::path::PathBuf; +use proc_macro2::TokenStream; + use crate::{codegen::LateCtx, schema::TypeDef}; mod clone_in; diff --git a/tasks/ast_tools/src/generators/assert_layouts.rs b/tasks/ast_tools/src/generators/assert_layouts.rs index f6cf2ffc01728..6e58c7a176f92 100644 --- a/tasks/ast_tools/src/generators/assert_layouts.rs +++ b/tasks/ast_tools/src/generators/assert_layouts.rs @@ -2,6 +2,7 @@ use proc_macro2::TokenStream; use quote::quote; use syn::Type; +use super::define_generator; use crate::{ codegen::{generated_header, LateCtx}, output, @@ -10,8 +11,6 @@ use crate::{ Generator, GeneratorOutput, }; -use super::define_generator; - define_generator! { pub struct AssertLayouts; } diff --git a/tasks/ast_tools/src/generators/ast_builder.rs b/tasks/ast_tools/src/generators/ast_builder.rs index 28366b1ec780c..4a4a51f9bdd42 100644 --- a/tasks/ast_tools/src/generators/ast_builder.rs +++ b/tasks/ast_tools/src/generators/ast_builder.rs @@ -1,5 +1,4 @@ -use std::stringify; -use std::{borrow::Cow, collections::HashMap}; +use std::{borrow::Cow, collections::HashMap, stringify}; use convert_case::{Case, Casing}; use itertools::Itertools; @@ -8,9 +7,9 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{parse_quote, Ident, Type}; -use crate::codegen::generated_header; +use super::define_generator; use crate::{ - codegen::LateCtx, + codegen::{generated_header, LateCtx}, output, schema::{ EnumDef, FieldDef, GetIdent, InheritDef, StructDef, ToType, TypeDef, TypeName, VariantDef, @@ -19,8 +18,6 @@ use crate::{ Generator, GeneratorOutput, }; -use super::define_generator; - define_generator! { pub struct AstBuilderGenerator; } diff --git a/tasks/ast_tools/src/generators/ast_kind.rs b/tasks/ast_tools/src/generators/ast_kind.rs index 874058e80f6af..d5afdfe0e9453 100644 --- a/tasks/ast_tools/src/generators/ast_kind.rs +++ b/tasks/ast_tools/src/generators/ast_kind.rs @@ -2,6 +2,7 @@ use itertools::Itertools; use quote::quote; use syn::{parse_quote, Arm, Ident, Type, Variant}; +use super::define_generator; use crate::{ codegen::{generated_header, LateCtx}, output, @@ -10,8 +11,6 @@ use crate::{ Generator, GeneratorOutput, }; -use super::define_generator; - define_generator! { pub struct AstKindGenerator; } diff --git a/tasks/ast_tools/src/generators/visit.rs b/tasks/ast_tools/src/generators/visit.rs index f57070bb41564..f017368dfd8b3 100644 --- a/tasks/ast_tools/src/generators/visit.rs +++ b/tasks/ast_tools/src/generators/visit.rs @@ -6,6 +6,7 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{parse_quote, Ident}; +use super::define_generator; use crate::{ codegen::{generated_header, LateCtx}, generators::ast_kind::BLACK_LIST as KIND_BLACK_LIST, @@ -16,8 +17,6 @@ use crate::{ Generator, GeneratorOutput, }; -use super::define_generator; - define_generator! { pub struct VisitGenerator; } diff --git a/tasks/ast_tools/src/markers.rs b/tasks/ast_tools/src/markers.rs index 5252df1ff63a2..692d808080c75 100644 --- a/tasks/ast_tools/src/markers.rs +++ b/tasks/ast_tools/src/markers.rs @@ -38,8 +38,9 @@ impl Parse for VisitArg { pub struct VisitArgs(Punctuated); impl IntoIterator for VisitArgs { - type Item = VisitArg; type IntoIter = syn::punctuated::IntoIter; + type Item = VisitArg; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } diff --git a/tasks/ast_tools/src/passes/calc_layout.rs b/tasks/ast_tools/src/passes/calc_layout.rs index 777e2d776d5f3..038c382d0a2e7 100644 --- a/tasks/ast_tools/src/passes/calc_layout.rs +++ b/tasks/ast_tools/src/passes/calc_layout.rs @@ -5,6 +5,7 @@ use lazy_static::lazy_static; use quote::ToTokens; use syn::Type; +use super::{define_pass, Pass}; use crate::{ codegen::EarlyCtx, layout::{KnownLayout, Layout}, @@ -13,8 +14,6 @@ use crate::{ Result, }; -use super::{define_pass, Pass}; - /// We use compiler to infer 64bit type layouts. #[cfg(not(target_pointer_width = "64"))] compile_error!("This module only supports 64bit architectures."); diff --git a/tasks/ast_tools/src/passes/linker.rs b/tasks/ast_tools/src/passes/linker.rs index d26bbbc40e82e..a74d1020acc27 100644 --- a/tasks/ast_tools/src/passes/linker.rs +++ b/tasks/ast_tools/src/passes/linker.rs @@ -2,9 +2,8 @@ use std::borrow::Cow; use syn::parse_quote; -use crate::{codegen::EarlyCtx, rust_ast::Inherit, util::NormalizeError}; - use super::{define_pass, AstType, Pass, Result}; +use crate::{codegen::EarlyCtx, rust_ast::Inherit, util::NormalizeError}; pub trait Unresolved { fn unresolved(&self) -> bool; @@ -68,7 +67,9 @@ impl Pass for Linker { }) } _ => { - panic!("invalid inheritance, you can only inherit from enums and in enums.") + panic!( + "invalid inheritance, you can only inherit from enums and in enums." + ) } }; ty.item.variants.extend(variants.clone()); @@ -79,7 +80,7 @@ impl Pass for Linker { } Inherit::Linked { .. } => Ok(Ok(it)), }) - .collect::>>>()?; + .collect::>>>()?; let unresolved = inherits.iter().any(std::result::Result::is_err); ty.meta.inherits = inherits.into_iter().map(|it| it.unwrap_or_else(|it| it)).collect(); diff --git a/tasks/ast_tools/src/rust_ast.rs b/tasks/ast_tools/src/rust_ast.rs index 64200dc674fd4..2ae98eb4c29ed 100644 --- a/tasks/ast_tools/src/rust_ast.rs +++ b/tasks/ast_tools/src/rust_ast.rs @@ -9,13 +9,12 @@ use syn::{ Variant, Visibility, }; +use super::{parse_file, Itertools, PathBuf, Rc, Read, RefCell, Result}; use crate::{ layout::Layout, util::{unexpanded_macro_err, NormalizeError}, }; -use super::{parse_file, Itertools, PathBuf, Rc, Read, RefCell, Result}; - pub type AstRef = Rc>; #[derive(Debug, Clone)] @@ -460,7 +459,12 @@ pub fn analyze(ast_ref: &AstRef) -> Result<()> { // AST without visit! ast_ref.borrow_mut().set_ast(true)?; } - Some(AstAttr::None) => return Err(format!("All `enums` and `structs` defined in the source of truth should be marked with an `#[ast]` attribute(missing `#[ast]` on '{:?}')", ast_ref.borrow().ident())), + Some(AstAttr::None) => { + return Err(format!( + "All `enums` and `structs` defined in the source of truth should be marked with an `#[ast]` attribute(missing `#[ast]` on '{:?}')", + ast_ref.borrow().ident() + )); + } None => { /* unrelated items like `use`, `type` and `macro` definitions */ } } diff --git a/tasks/ast_tools/src/schema/defs.rs b/tasks/ast_tools/src/schema/defs.rs index 218c23867b2cb..4625599165477 100644 --- a/tasks/ast_tools/src/schema/defs.rs +++ b/tasks/ast_tools/src/schema/defs.rs @@ -1,13 +1,12 @@ use serde::Serialize; +use super::{with_either, TypeName}; use crate::{ markers::{DeriveAttributes, ScopeAttribute, ScopeMarkers, VisitMarkers}, util::{ToIdent, TypeAnalysis, TypeWrapper}, TypeId, }; -use super::{with_either, TypeName}; - #[derive(Debug, Serialize)] #[serde(untagged)] pub enum TypeDef { diff --git a/tasks/ast_tools/src/schema/get_ident.rs b/tasks/ast_tools/src/schema/get_ident.rs index 4b5ae5965d7c2..35967dd99572b 100644 --- a/tasks/ast_tools/src/schema/get_ident.rs +++ b/tasks/ast_tools/src/schema/get_ident.rs @@ -1,9 +1,8 @@ -use crate::util::ToIdent; - use super::{ defs::{EnumDef, StructDef, TypeDef}, with_either, }; +use crate::util::ToIdent; pub trait GetIdent { fn ident(&self) -> syn::Ident; diff --git a/tasks/ast_tools/src/schema/mod.rs b/tasks/ast_tools/src/schema/mod.rs index 3c81d93c0609e..5121a6a2100be 100644 --- a/tasks/ast_tools/src/schema/mod.rs +++ b/tasks/ast_tools/src/schema/mod.rs @@ -94,8 +94,8 @@ impl Schema { } impl<'a> IntoIterator for &'a Schema { - type Item = &'a TypeDef; type IntoIter = std::slice::Iter<'a, TypeDef>; + type Item = &'a TypeDef; fn into_iter(self) -> Self::IntoIter { self.defs.iter() diff --git a/tasks/coverage/src/babel/mod.rs b/tasks/coverage/src/babel/mod.rs index e658034412bea..e8c7715473f83 100644 --- a/tasks/coverage/src/babel/mod.rs +++ b/tasks/coverage/src/babel/mod.rs @@ -1,7 +1,6 @@ use std::path::{Path, PathBuf}; -use oxc::span::SourceType; -use oxc::transformer::BabelOptions; +use oxc::{span::SourceType, transformer::BabelOptions}; use serde::{de::DeserializeOwned, Deserialize}; use serde_json::Value; diff --git a/tasks/coverage/src/driver.rs b/tasks/coverage/src/driver.rs index 59f8ec93fa3ef..bc2cc50f0ac25 100644 --- a/tasks/coverage/src/driver.rs +++ b/tasks/coverage/src/driver.rs @@ -1,19 +1,20 @@ use std::{collections::HashSet, ops::ControlFlow, path::PathBuf}; -use oxc::CompilerInterface; - #[allow(clippy::wildcard_imports)] use oxc::ast::{ast::*, Trivias}; -use oxc::codegen::CodegenOptions; -use oxc::diagnostics::OxcDiagnostic; -use oxc::minifier::CompressOptions; -use oxc::parser::{ParseOptions, ParserReturn}; -use oxc::semantic::{ - post_transform_checker::{check_semantic_after_transform, check_semantic_ids}, - SemanticBuilderReturn, +use oxc::{ + codegen::CodegenOptions, + diagnostics::OxcDiagnostic, + minifier::CompressOptions, + parser::{ParseOptions, ParserReturn}, + semantic::{ + post_transform_checker::{check_semantic_after_transform, check_semantic_ids}, + SemanticBuilderReturn, + }, + span::{SourceType, Span}, + transformer::{TransformOptions, TransformerReturn}, + CompilerInterface, }; -use oxc::span::{SourceType, Span}; -use oxc::transformer::{TransformOptions, TransformerReturn}; use crate::suite::TestResult; diff --git a/tasks/coverage/src/runtime/mod.rs b/tasks/coverage/src/runtime/mod.rs index 8a46ccbcc0598..8ccb4ee752e4c 100644 --- a/tasks/coverage/src/runtime/mod.rs +++ b/tasks/coverage/src/runtime/mod.rs @@ -5,10 +5,7 @@ use std::{ time::Duration, }; -use oxc::allocator::Allocator; -use oxc::codegen::CodeGenerator; -use oxc::parser::Parser; -use oxc::span::SourceType; +use oxc::{allocator::Allocator, codegen::CodeGenerator, parser::Parser, span::SourceType}; use oxc_tasks_common::{agent, project_root}; use phf::{phf_set, Set}; use serde_json::json; diff --git a/tasks/coverage/src/suite.rs b/tasks/coverage/src/suite.rs index cc6c7a1c718d6..5a4900dc8eb1e 100644 --- a/tasks/coverage/src/suite.rs +++ b/tasks/coverage/src/suite.rs @@ -10,8 +10,10 @@ use console::Style; use encoding_rs::UTF_16LE; use encoding_rs_io::DecodeReaderBytesBuilder; use futures::future::join_all; -use oxc::diagnostics::{GraphicalReportHandler, GraphicalTheme, NamedSource}; -use oxc::span::SourceType; +use oxc::{ + diagnostics::{GraphicalReportHandler, GraphicalTheme, NamedSource}, + span::SourceType, +}; use oxc_tasks_common::{normalize_path, Snapshot}; use rayon::prelude::*; use similar::{ChangeTag, TextDiff}; diff --git a/tasks/coverage/src/tools/prettier.rs b/tasks/coverage/src/tools/prettier.rs index 33b3edd9d7172..605c800626e3f 100644 --- a/tasks/coverage/src/tools/prettier.rs +++ b/tasks/coverage/src/tools/prettier.rs @@ -1,8 +1,10 @@ use std::path::{Path, PathBuf}; -use oxc::allocator::Allocator; -use oxc::parser::{ParseOptions, Parser, ParserReturn}; -use oxc::span::SourceType; +use oxc::{ + allocator::Allocator, + parser::{ParseOptions, Parser, ParserReturn}, + span::SourceType, +}; use oxc_prettier::{Prettier, PrettierOptions}; use crate::{ diff --git a/tasks/coverage/src/tools/semantic.rs b/tasks/coverage/src/tools/semantic.rs index c77ac361d8d3f..94cc04295f663 100644 --- a/tasks/coverage/src/tools/semantic.rs +++ b/tasks/coverage/src/tools/semantic.rs @@ -1,8 +1,10 @@ use std::path::{Path, PathBuf}; -use oxc::span::SourceType; -use oxc::transformer::{ - ES2015Options, ReactJsxRuntime, ReactOptions, TransformOptions, TypeScriptOptions, +use oxc::{ + span::SourceType, + transformer::{ + ES2015Options, ReactJsxRuntime, ReactOptions, TransformOptions, TypeScriptOptions, + }, }; use crate::{ diff --git a/tasks/coverage/src/tools/sourcemap.rs b/tasks/coverage/src/tools/sourcemap.rs index d9ceb073a60df..b26f6c2c278d0 100644 --- a/tasks/coverage/src/tools/sourcemap.rs +++ b/tasks/coverage/src/tools/sourcemap.rs @@ -4,11 +4,10 @@ use std::{ path::{Path, PathBuf}, }; -use oxc::allocator::Allocator; -use oxc::codegen::CodeGenerator; -use oxc::parser::Parser; -use oxc::sourcemap::SourcemapVisualizer; -use oxc::span::SourceType; +use oxc::{ + allocator::Allocator, codegen::CodeGenerator, parser::Parser, sourcemap::SourcemapVisualizer, + span::SourceType, +}; use oxc_tasks_common::TestFiles; use crate::{ diff --git a/tasks/coverage/src/tools/transformer.rs b/tasks/coverage/src/tools/transformer.rs index 369aa69cd0e0a..ea682444912a5 100644 --- a/tasks/coverage/src/tools/transformer.rs +++ b/tasks/coverage/src/tools/transformer.rs @@ -1,9 +1,11 @@ use std::path::{Path, PathBuf}; -use oxc::span::SourceType; -use oxc::transformer::{ - ArrowFunctionsOptions, ES2015Options, ReactJsxRuntime, ReactOptions, TransformOptions, - TypeScriptOptions, +use oxc::{ + span::SourceType, + transformer::{ + ArrowFunctionsOptions, ES2015Options, ReactJsxRuntime, ReactOptions, TransformOptions, + TypeScriptOptions, + }, }; use crate::{ diff --git a/tasks/coverage/src/typescript/meta.rs b/tasks/coverage/src/typescript/meta.rs index 735be18a7054d..8e8748eff59be 100644 --- a/tasks/coverage/src/typescript/meta.rs +++ b/tasks/coverage/src/typescript/meta.rs @@ -2,11 +2,13 @@ use std::{collections::HashMap, fs, path::Path, sync::Arc}; -use oxc::allocator::Allocator; -use oxc::codegen::CodeGenerator; -use oxc::diagnostics::{NamedSource, OxcDiagnostic}; -use oxc::parser::Parser; -use oxc::span::SourceType; +use oxc::{ + allocator::Allocator, + codegen::CodeGenerator, + diagnostics::{NamedSource, OxcDiagnostic}, + parser::Parser, + span::SourceType, +}; use regex::Regex; use crate::workspace_root; diff --git a/tasks/coverage/src/typescript/transpile_runner.rs b/tasks/coverage/src/typescript/transpile_runner.rs index 5e9a2c1646686..b399e3fa4ac12 100644 --- a/tasks/coverage/src/typescript/transpile_runner.rs +++ b/tasks/coverage/src/typescript/transpile_runner.rs @@ -2,12 +2,10 @@ use std::path::{Path, PathBuf}; -use oxc::allocator::Allocator; -use oxc::codegen::CodeGenerator; -use oxc::diagnostics::OxcDiagnostic; -use oxc::isolated_declarations::IsolatedDeclarations; -use oxc::parser::Parser; -use oxc::span::SourceType; +use oxc::{ + allocator::Allocator, codegen::CodeGenerator, diagnostics::OxcDiagnostic, + isolated_declarations::IsolatedDeclarations, parser::Parser, span::SourceType, +}; use super::{ meta::{Baseline, BaselineFile}, diff --git a/tasks/transform_conformance/src/test_case.rs b/tasks/transform_conformance/src/test_case.rs index 83fff14a93db4..7dad3472bd6ba 100644 --- a/tasks/transform_conformance/src/test_case.rs +++ b/tasks/transform_conformance/src/test_case.rs @@ -3,12 +3,14 @@ use std::{ path::{Path, PathBuf}, }; -use oxc::allocator::Allocator; -use oxc::codegen::CodeGenerator; -use oxc::diagnostics::{Error, NamedSource, OxcDiagnostic}; -use oxc::parser::Parser; -use oxc::span::{SourceType, VALID_EXTENSIONS}; -use oxc::transformer::{BabelOptions, TransformOptions}; +use oxc::{ + allocator::Allocator, + codegen::CodeGenerator, + diagnostics::{Error, NamedSource, OxcDiagnostic}, + parser::Parser, + span::{SourceType, VALID_EXTENSIONS}, + transformer::{BabelOptions, TransformOptions}, +}; use oxc_tasks_common::{normalize_path, print_diff_in_terminal, project_root}; use crate::{ diff --git a/tasks/website/src/linter/rules/doc_page.rs b/tasks/website/src/linter/rules/doc_page.rs index 193d8dd1b0129..a4c4a5f40bacc 100644 --- a/tasks/website/src/linter/rules/doc_page.rs +++ b/tasks/website/src/linter/rules/doc_page.rs @@ -1,12 +1,13 @@ //! Create documentation pages for each rule. Pages are printed as Markdown and //! get added to the website. -use oxc_linter::table::RuleTableRow; use std::{ fmt::{self, Write}, path::PathBuf, }; +use oxc_linter::table::RuleTableRow; + use super::HtmlWriter; pub fn render_rule_docs_page(rule: &RuleTableRow) -> Result { @@ -59,9 +60,10 @@ pub fn render_rule_docs_page(rule: &RuleTableRow) -> Result } fn rule_source(rule: &RuleTableRow) -> String { - use project_root::get_project_root; use std::sync::OnceLock; + use project_root::get_project_root; + const GITHUB_URL: &str = "https://github.com/oxc-project/oxc/blob/main"; const LINT_RULES_DIR: &str = "crates/oxc_linter/src/rules"; static ROOT: OnceLock = OnceLock::new(); diff --git a/tasks/website/src/linter/rules/test.rs b/tasks/website/src/linter/rules/test.rs index 672352b7a3403..e70e6e3990002 100644 --- a/tasks/website/src/linter/rules/test.rs +++ b/tasks/website/src/linter/rules/test.rs @@ -1,12 +1,12 @@ -use markdown::{to_html_with_options, Options}; -use oxc_diagnostics::NamedSource; -use scraper::{ElementRef, Html, Selector}; use std::sync::{Arc, OnceLock}; +use markdown::{to_html_with_options, Options}; use oxc_allocator::Allocator; +use oxc_diagnostics::NamedSource; use oxc_linter::table::RuleTable; use oxc_parser::Parser; use oxc_span::SourceType; +use scraper::{ElementRef, Html, Selector}; use super::{render_rule_docs_page, render_rules_table};