diff --git a/.cargo/config.toml b/.cargo/config.toml index 07509d8a5dc17d..e54202a807a1c0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -11,9 +11,6 @@ rule = "run -p rulegen" # Build oxlint in release mode oxlint = "build --release --bin oxlint --features allocator" -[resolver] -incompatible-rust-versions = "fallback" - # Fix napi breaking in test environment # To be able to run unit tests on macOS, support compilation to 'x86_64-apple-darwin'. [target.'cfg(target_vendor = "apple")'] diff --git a/.rustfmt.toml b/.rustfmt.toml index 6862d534ce1c6d..3337f3683dccdd 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,3 +1,4 @@ +style_edition = "2024" # Make Rust more readable given most people have wide screens nowadays. # This is also the setting used by [rustc](https://github.com/rust-lang/rust/blob/master/rustfmt.toml) use_small_heuristics = "Max" @@ -9,7 +10,6 @@ reorder_modules = true # All unstable features that we wish for # unstable_features = true -# style_edition = "2024" # Provide a cleaner impl order # reorder_impl_items = true # Provide a cleaner import sort order diff --git a/Cargo.lock b/Cargo.lock index 08cc0f08dd8a5f..95edd7ddc46c56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -216,9 +216,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.14" +version = "1.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c3d1b2e905a3a7b00a6141adb0e4c0bb941d11caf55349d863942a1cc44e3c9" +checksum = "c736e259eea577f443d5c86c304f9f4ae0295c43f3ba05c21f1d66b5f06001af" dependencies = [ "shlex", ] @@ -1268,9 +1268,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.25" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04cbf5b083de1c7e0222a7a51dbfdba1cbe1c6ab0b15e29fff3f6c077fd9cd9f" +checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" [[package]] name = "lsp-types" @@ -1311,9 +1311,9 @@ dependencies = [ [[package]] name = "miniz_oxide" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3b1c9bd4fe1f0f8b387f6eb9eb3b4a1aa26185e5750efb9140301703f62cd1b" +checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5" dependencies = [ "adler2", ] @@ -2521,9 +2521,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" +checksum = "82b568323e98e49e2a0899dcee453dd679fae22d69adf9b11dd508d1549b7e2f" dependencies = [ "bitflags 2.8.0", ] @@ -2559,9 +2559,9 @@ checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "ring" -version = "0.17.9" +version = "0.17.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e75ec5e92c4d8aede845126adc388046234541629e76029599ed35a003c7ed24" +checksum = "d34b5020fcdea098ef7d95e9f89ec15952123a4a039badd09fabebe9e963e839" dependencies = [ "cc", "cfg-if", @@ -2783,9 +2783,9 @@ checksum = "a3f0bf26fd526d2a95683cd0f87bf103b8539e2ca1ef48ce002d67aad59aa0b4" [[package]] name = "serde" -version = "1.0.217" +version = "1.0.218" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" +checksum = "e8dfc9d19bdbf6d17e22319da49161d5d0108e4188e8b680aef6299eed22df60" dependencies = [ "serde_derive", ] @@ -2803,9 +2803,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.217" +version = "1.0.218" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" +checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" dependencies = [ "proc-macro2", "quote", @@ -2836,9 +2836,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.138" +version = "1.0.139" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d434192e7da787e94a6ea7e9670b26a036d0ca41e0b7efb2676dd32bae872949" +checksum = "44f86c3acccc9c65b153fe1b85a3be07fe5515274ec9f0653b4a0875731c72a6" dependencies = [ "indexmap", "itoa", @@ -3042,9 +3042,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.17.0" +version = "3.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a40f762a77d2afa88c2d919489e390a12bdd261ed568e60cfa7e48d4e20f0d33" +checksum = "22e5a0acb1f3f55f65cc4a866c361b2fb2a0ff6366785ae6fbb5f85df07ba230" dependencies = [ "cfg-if", "fastrand", @@ -3343,9 +3343,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" [[package]] name = "ucd-trie" @@ -3367,9 +3367,9 @@ checksum = "2f322b60f6b9736017344fa0635d64be2f458fbc04eef65f6be22976dd1ffd5b" [[package]] name = "unicode-ident" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" +checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" [[package]] name = "unicode-linebreak" @@ -3403,9 +3403,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.0.5" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2916852be768844b6e9cbe107358b5bc40a696bd6dc8e036c9f80c731242c9c" +checksum = "ca2e2dbdf4e95780e5d41804fab88b928a24585721018409eb429b1d29356bde" dependencies = [ "base64", "cookie_store", @@ -3465,9 +3465,9 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "uuid" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced87ca4be083373936a67f8de945faa23b6b42384bd5b64434850802c6dccd0" +checksum = "93d59ca99a559661b96bf898d8fce28ed87935fd2bea9f05983c1464dd6c71b1" dependencies = [ "getrandom 0.3.1", ] diff --git a/Cargo.toml b/Cargo.toml index dd5ec0c40fba01..38202ffc2e5874 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,12 +6,14 @@ exclude = ["tasks/lint_rules", "tasks/e2e"] [workspace.package] authors = ["Boshen ", "Oxc contributors"] categories = ["compilers", "development-tools", "web-programming"] -edition = "2021" +# MSRV Policy N-2 (12 weeks) starting from v1.87.0 +# Balance between the core contributors enjoying the latest version of rustc, while waiting for dependents to catch up. +edition = "2024" homepage = "https://oxc.rs" keywords = ["JavaScript", "TypeScript", "linter", "minifier", "parser"] license = "MIT" repository = "https://github.com/oxc-project/oxc" -rust-version = "1.82.0" # Support last 4 minor versions. (NOTE: bump to `edition = "2024"` when 1.85.0. +rust-version = "1.85.0" description = "A collection of JavaScript tools written in Rust." # @@ -20,6 +22,9 @@ absolute_paths_not_starting_with_crate = "warn" non_ascii_idents = "warn" unit-bindings = "warn" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage)', 'cfg(coverage_nightly)'] } +tail_expr_drop_order = "allow" # FIXME +unsafe_op_in_unsafe_fn = "allow" # FIXME +unused_unsafe = "allow" [workspace.lints.clippy] all = { level = "warn", priority = -1 } @@ -45,7 +50,7 @@ rc_buffer = "warn" rc_mutex = "warn" rest_pat_in_fully_bound_structs = "warn" unnecessary_safety_comment = "warn" -undocumented_unsafe_blocks = "warn" +undocumented_unsafe_blocks = "allow" # FIXME infinite_loop = "warn" map_with_unused_argument_over_ranges = "warn" unused_result_ok = "warn" diff --git a/apps/oxlint/src/command/ignore.rs b/apps/oxlint/src/command/ignore.rs index fb0da2905c6d59..ab5269eefa1a1f 100644 --- a/apps/oxlint/src/command/ignore.rs +++ b/apps/oxlint/src/command/ignore.rs @@ -1,6 +1,6 @@ use std::ffi::OsString; -use bpaf::{doc::Style, Bpaf}; +use bpaf::{Bpaf, doc::Style}; pub const NO_IGNORE_HELP: &[(&str, Style)] = &[ ("Disables excluding of files from .eslintignore files, ", Style::Text), diff --git a/apps/oxlint/src/command/lint.rs b/apps/oxlint/src/command/lint.rs index ba145aa2860f58..48bf4dae26a7ce 100644 --- a/apps/oxlint/src/command/lint.rs +++ b/apps/oxlint/src/command/lint.rs @@ -6,8 +6,9 @@ use oxc_linter::{AllowWarnDeny, FixKind, LintPlugins}; use crate::output_formatter::OutputFormat; use super::{ - ignore::{ignore_options, IgnoreOptions}, - misc_options, validate_paths, MiscOptions, PATHS_ERROR_MESSAGE, VERSION, + MiscOptions, PATHS_ERROR_MESSAGE, VERSION, + ignore::{IgnoreOptions, ignore_options}, + misc_options, validate_paths, }; #[derive(Debug, Clone, Bpaf)] @@ -392,7 +393,7 @@ mod plugins { #[cfg(test)] mod warning_options { - use super::{lint_command, WarningOptions}; + use super::{WarningOptions, lint_command}; fn get_warning_options(arg: &str) -> WarningOptions { let args = arg.split(' ').map(std::string::ToString::to_string).collect::>(); @@ -425,7 +426,7 @@ mod lint_options { use oxc_linter::AllowWarnDeny; - use super::{lint_command, LintCommand, OutputFormat}; + use super::{LintCommand, OutputFormat, lint_command}; fn get_lint_options(arg: &str) -> LintCommand { let args = arg.split(' ').map(std::string::ToString::to_string).collect::>(); diff --git a/apps/oxlint/src/command/mod.rs b/apps/oxlint/src/command/mod.rs index ff4066c91171a4..8ae2c4d6b597c8 100644 --- a/apps/oxlint/src/command/mod.rs +++ b/apps/oxlint/src/command/mod.rs @@ -7,7 +7,7 @@ use bpaf::Bpaf; pub use self::{ ignore::IgnoreOptions, - lint::{lint_command, LintCommand, OutputOptions, WarningOptions}, + lint::{LintCommand, OutputOptions, WarningOptions, lint_command}, }; const VERSION: &str = match option_env!("OXC_VERSION") { @@ -45,7 +45,7 @@ const PATHS_ERROR_MESSAGE: &str = "PATH must not contain \"..\""; #[cfg(test)] mod misc_options { - use super::{lint::lint_command, MiscOptions}; + use super::{MiscOptions, lint::lint_command}; fn get_misc_options(arg: &str) -> MiscOptions { let args = arg.split(' ').map(std::string::ToString::to_string).collect::>(); diff --git a/apps/oxlint/src/lint.rs b/apps/oxlint/src/lint.rs index ea0523c57ee5e4..1da9ed23d921cd 100644 --- a/apps/oxlint/src/lint.rs +++ b/apps/oxlint/src/lint.rs @@ -9,8 +9,8 @@ use cow_utils::CowUtils; use ignore::{gitignore::Gitignore, overrides::OverrideBuilder}; use oxc_diagnostics::{DiagnosticService, GraphicalReportHandler}; use oxc_linter::{ - loader::LINT_PARTIAL_LOADER_EXT, AllowWarnDeny, ConfigStoreBuilder, InvalidFilterKind, - LintFilter, LintOptions, LintService, LintServiceOptions, Linter, Oxlintrc, + AllowWarnDeny, ConfigStoreBuilder, InvalidFilterKind, LintFilter, LintOptions, LintService, + LintServiceOptions, Linter, Oxlintrc, loader::LINT_PARTIAL_LOADER_EXT, }; use oxc_span::VALID_EXTENSIONS; use serde_json::Value; @@ -340,13 +340,17 @@ impl LintRunner { )); } Err(InvalidFilterKind::PluginMissing(filter)) => { - return Err((CliRunResult::InvalidOptionSeverityWithoutPluginName, format!( + return Err(( + CliRunResult::InvalidOptionSeverityWithoutPluginName, + format!( "Failed to {severity} filter {filter}: Plugin name is missing. Expected /\n" ), )); } Err(InvalidFilterKind::RuleMissing(filter)) => { - return Err((CliRunResult::InvalidOptionSeverityWithoutRuleName, format!( + return Err(( + CliRunResult::InvalidOptionSeverityWithoutRuleName, + format!( "Failed to {severity} filter {filter}: Rule name is missing. Expected /\n" ), )); diff --git a/apps/oxlint/src/output_formatter/checkstyle.rs b/apps/oxlint/src/output_formatter/checkstyle.rs index 5f529f39288933..031f8ec3bdcece 100644 --- a/apps/oxlint/src/output_formatter/checkstyle.rs +++ b/apps/oxlint/src/output_formatter/checkstyle.rs @@ -3,11 +3,11 @@ use std::borrow::Cow; use rustc_hash::FxHashMap; use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult, Info}, Error, Severity, + reporter::{DiagnosticReporter, DiagnosticResult, Info}, }; -use crate::output_formatter::{xml_utils::xml_escape, InternalFormatter}; +use crate::output_formatter::{InternalFormatter, xml_utils::xml_escape}; #[derive(Debug, Default)] pub struct CheckStyleOutputFormatter; @@ -69,8 +69,8 @@ fn format_checkstyle(diagnostics: &[Error]) -> String { #[cfg(test)] mod test { use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult}, NamedSource, OxcDiagnostic, + reporter::{DiagnosticReporter, DiagnosticResult}, }; use oxc_span::Span; @@ -93,6 +93,9 @@ mod test { let second_result = reporter.finish(&DiagnosticResult::default()); assert!(second_result.is_some()); - assert_eq!(second_result.unwrap(), "\n"); + assert_eq!( + second_result.unwrap(), + "\n" + ); } } diff --git a/apps/oxlint/src/output_formatter/default.rs b/apps/oxlint/src/output_formatter/default.rs index 38d9944048f9ab..a1beeadc42dcdc 100644 --- a/apps/oxlint/src/output_formatter/default.rs +++ b/apps/oxlint/src/output_formatter/default.rs @@ -2,8 +2,8 @@ use std::time::Duration; use crate::output_formatter::InternalFormatter; use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult}, Error, GraphicalReportHandler, + reporter::{DiagnosticReporter, DiagnosticResult}, }; use oxc_linter::table::RuleTable; @@ -51,11 +51,7 @@ impl InternalFormatter for DefaultOutputFormatter { impl DefaultOutputFormatter { fn get_execution_time(duration: &Duration) -> String { let ms = duration.as_millis(); - if ms < 1000 { - format!("{ms}ms") - } else { - format!("{:.1}s", duration.as_secs_f64()) - } + if ms < 1000 { format!("{ms}ms") } else { format!("{:.1}s", duration.as_secs_f64()) } } } @@ -115,8 +111,8 @@ fn get_diagnostic_result_output(result: &DiagnosticResult) -> String { #[cfg(test)] mod test_implementation { use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult, Info}, Error, GraphicalReportHandler, GraphicalTheme, + reporter::{DiagnosticReporter, DiagnosticResult, Info}, }; use crate::output_formatter::default::get_diagnostic_result_output; @@ -155,8 +151,8 @@ mod test { use std::time::Duration; use crate::output_formatter::{ - default::{DefaultOutputFormatter, GraphicalReporter}, InternalFormatter, LintCommandInfo, + default::{DefaultOutputFormatter, GraphicalReporter}, }; use oxc_diagnostics::reporter::{DiagnosticReporter, DiagnosticResult}; diff --git a/apps/oxlint/src/output_formatter/github.rs b/apps/oxlint/src/output_formatter/github.rs index 3242d06cba8bd2..aa5438faaed4df 100644 --- a/apps/oxlint/src/output_formatter/github.rs +++ b/apps/oxlint/src/output_formatter/github.rs @@ -1,8 +1,8 @@ use std::borrow::Cow; use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult, Info}, Error, Severity, + reporter::{DiagnosticReporter, DiagnosticResult, Info}, }; use crate::output_formatter::InternalFormatter; @@ -41,10 +41,7 @@ fn format_github(diagnostic: &Error) -> String { let message = escape_data(&message); format!( "::{severity} file={filename},line={},endLine={},col={},endColumn={},title={title}::{message}\n", - start.line, - end.line, - start.column, - end.column + start.line, end.line, start.column, end.column ) } @@ -85,8 +82,8 @@ fn escape_property(value: &str) -> String { #[cfg(test)] mod test { use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult}, NamedSource, OxcDiagnostic, + reporter::{DiagnosticReporter, DiagnosticResult}, }; use oxc_span::Span; @@ -111,6 +108,9 @@ mod test { let result = reporter.render_error(error); assert!(result.is_some()); - assert_eq!(result.unwrap(), "::warning file=file%3A//test.ts,line=1,endLine=1,col=1,endColumn=9,title=oxlint::error message\n"); + assert_eq!( + result.unwrap(), + "::warning file=file%3A//test.ts,line=1,endLine=1,col=1,endColumn=9,title=oxlint::error message\n" + ); } } diff --git a/apps/oxlint/src/output_formatter/json.rs b/apps/oxlint/src/output_formatter/json.rs index 89c89fbdc3b471..5af7e039c940d1 100644 --- a/apps/oxlint/src/output_formatter/json.rs +++ b/apps/oxlint/src/output_formatter/json.rs @@ -1,8 +1,8 @@ use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult}, Error, + reporter::{DiagnosticReporter, DiagnosticResult}, }; -use oxc_linter::{rules::RULES, RuleCategory}; +use oxc_linter::{RuleCategory, rules::RULES}; use miette::JSONReportHandler; @@ -77,8 +77,8 @@ fn format_json(diagnostics: &mut Vec) -> String { #[cfg(test)] mod test { use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult}, NamedSource, OxcDiagnostic, + reporter::{DiagnosticReporter, DiagnosticResult}, }; use oxc_span::Span; diff --git a/apps/oxlint/src/output_formatter/junit.rs b/apps/oxlint/src/output_formatter/junit.rs index 956964f70cfe51..89f800497a63a3 100644 --- a/apps/oxlint/src/output_formatter/junit.rs +++ b/apps/oxlint/src/output_formatter/junit.rs @@ -1,10 +1,10 @@ use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult, Info}, Error, Severity, + reporter::{DiagnosticReporter, DiagnosticResult, Info}, }; use rustc_hash::FxHashMap; -use super::{xml_utils::xml_escape, InternalFormatter}; +use super::{InternalFormatter, xml_utils::xml_escape}; #[derive(Default)] pub struct JUnitOutputFormatter; @@ -76,9 +76,22 @@ fn format_junit(diagnostics: &[Error]) -> String { format!("\n \n{status}\n "); test_cases = format!("{test_cases}{test_case}"); } - test_suite = format!(" {}\n ", filename, diagnostics.len(), error, warning, test_cases); + test_suite = format!( + " {}\n ", + filename, + diagnostics.len(), + error, + warning, + test_cases + ); } - let test_suites = format!("\n{}\n\n", total_errors + total_warnings, total_warnings, total_errors, test_suite); + let test_suites = format!( + "\n{}\n\n", + total_errors + total_warnings, + total_warnings, + total_errors, + test_suite + ); format!("\n{test_suites}") } @@ -86,7 +99,7 @@ fn format_junit(diagnostics: &[Error]) -> String { #[cfg(test)] mod test { use super::*; - use oxc_diagnostics::{reporter::DiagnosticResult, NamedSource, OxcDiagnostic}; + use oxc_diagnostics::{NamedSource, OxcDiagnostic, reporter::DiagnosticResult}; use oxc_span::Span; #[test] diff --git a/apps/oxlint/src/output_formatter/stylish.rs b/apps/oxlint/src/output_formatter/stylish.rs index a0b127afdc4e4f..e2799de9c4cd7d 100644 --- a/apps/oxlint/src/output_formatter/stylish.rs +++ b/apps/oxlint/src/output_formatter/stylish.rs @@ -1,6 +1,6 @@ use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult, Info}, Error, Severity, + reporter::{DiagnosticReporter, DiagnosticResult, Info}, }; use rustc_hash::FxHashMap; @@ -110,7 +110,7 @@ fn format_stylish(diagnostics: &[Error]) -> String { #[cfg(test)] mod test { use super::*; - use oxc_diagnostics::{reporter::DiagnosticResult, NamedSource, OxcDiagnostic}; + use oxc_diagnostics::{NamedSource, OxcDiagnostic, reporter::DiagnosticResult}; use oxc_span::Span; #[test] diff --git a/apps/oxlint/src/output_formatter/unix.rs b/apps/oxlint/src/output_formatter/unix.rs index 0078e819e3a121..c083970287bd54 100644 --- a/apps/oxlint/src/output_formatter/unix.rs +++ b/apps/oxlint/src/output_formatter/unix.rs @@ -1,8 +1,8 @@ use std::borrow::Cow; use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult, Info}, Error, Severity, + reporter::{DiagnosticReporter, DiagnosticResult, Info}, }; use crate::output_formatter::InternalFormatter; @@ -54,8 +54,8 @@ fn format_unix(diagnostic: &Error) -> String { #[cfg(test)] mod test { use oxc_diagnostics::{ - reporter::{DiagnosticReporter, DiagnosticResult}, NamedSource, OxcDiagnostic, + reporter::{DiagnosticReporter, DiagnosticResult}, }; use oxc_span::Span; diff --git a/apps/oxlint/src/tester.rs b/apps/oxlint/src/tester.rs index 8d48377c05de31..b2a05499173336 100644 --- a/apps/oxlint/src/tester.rs +++ b/apps/oxlint/src/tester.rs @@ -1,5 +1,5 @@ #[cfg(test)] -use crate::cli::{lint_command, LintRunner}; +use crate::cli::{LintRunner, lint_command}; #[cfg(test)] use crate::runner::Runner; #[cfg(test)] diff --git a/apps/oxlint/src/walk.rs b/apps/oxlint/src/walk.rs index ad30c7a46195a8..0f38557d1e5dc8 100644 --- a/apps/oxlint/src/walk.rs +++ b/apps/oxlint/src/walk.rs @@ -3,7 +3,7 @@ use std::{ sync::mpsc, }; -use ignore::{overrides::Override, DirEntry}; +use ignore::{DirEntry, overrides::Override}; use oxc_span::VALID_EXTENSIONS; use crate::cli::IgnoreOptions; diff --git a/crates/oxc/examples/compiler.rs b/crates/oxc/examples/compiler.rs index f856b76bb71286..fe2596ac1c00d1 100644 --- a/crates/oxc/examples/compiler.rs +++ b/crates/oxc/examples/compiler.rs @@ -2,7 +2,7 @@ use std::{env, io, path::Path}; -use oxc::{span::SourceType, Compiler}; +use oxc::{Compiler, span::SourceType}; // Instruction: // 1. create a `test.js` diff --git a/crates/oxc_allocator/src/allocator_api2.rs b/crates/oxc_allocator/src/allocator_api2.rs index 71d41448b8da2d..b41af94b1b0da6 100644 --- a/crates/oxc_allocator/src/allocator_api2.rs +++ b/crates/oxc_allocator/src/allocator_api2.rs @@ -15,7 +15,9 @@ unsafe impl Allocator for &crate::Allocator { #[inline(always)] unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - self.bump().deallocate(ptr, layout); + unsafe { + self.bump().deallocate(ptr, layout); + } } #[inline(always)] @@ -25,7 +27,7 @@ unsafe impl Allocator for &crate::Allocator { old_layout: Layout, new_layout: Layout, ) -> Result, AllocError> { - self.bump().shrink(ptr, old_layout, new_layout) + unsafe { self.bump().shrink(ptr, old_layout, new_layout) } } #[inline(always)] @@ -35,7 +37,7 @@ unsafe impl Allocator for &crate::Allocator { old_layout: Layout, new_layout: Layout, ) -> Result, AllocError> { - self.bump().grow(ptr, old_layout, new_layout) + unsafe { self.bump().grow(ptr, old_layout, new_layout) } } #[inline(always)] @@ -45,6 +47,6 @@ unsafe impl Allocator for &crate::Allocator { old_layout: Layout, new_layout: Layout, ) -> Result, AllocError> { - self.bump().grow_zeroed(ptr, old_layout, new_layout) + unsafe { self.bump().grow_zeroed(ptr, old_layout, new_layout) } } } diff --git a/crates/oxc_allocator/src/hash_map.rs b/crates/oxc_allocator/src/hash_map.rs index 04810094044676..0ead3447116ec2 100644 --- a/crates/oxc_allocator/src/hash_map.rs +++ b/crates/oxc_allocator/src/hash_map.rs @@ -18,11 +18,11 @@ use rustc_hash::FxBuildHasher; // Re-export additional types from `hashbrown` pub use hashbrown::{ + Equivalent, TryReserveError, hash_map::{ Drain, Entry, EntryRef, ExtractIf, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, OccupiedError, Values, ValuesMut, }, - Equivalent, TryReserveError, }; use crate::Allocator; diff --git a/crates/oxc_allocator/src/string.rs b/crates/oxc_allocator/src/string.rs index b769e26482bf99..a9ed03b3926368 100644 --- a/crates/oxc_allocator/src/string.rs +++ b/crates/oxc_allocator/src/string.rs @@ -13,8 +13,8 @@ use std::{ }; use bumpalo::collections::String as BumpaloString; -use simdutf8::basic::from_utf8; pub use simdutf8::basic::Utf8Error; +use simdutf8::basic::from_utf8; use crate::{Allocator, Vec}; @@ -103,16 +103,17 @@ impl<'alloc> String<'alloc> { /// Caller must ensure this `Vec` comprises a valid UTF-8 string. // // `#[inline(always)]` because this is a no-op at runtime - #[expect(clippy::unnecessary_safety_comment)] #[inline(always)] pub unsafe fn from_utf8_unchecked(bytes: Vec<'alloc, u8>) -> String<'alloc> { - // Cannot use `bumpalo::String::from_utf8_unchecked` because it takes a `bumpalo::collections::Vec`, - // and our inner `Vec` type is `allocator_api2::vec::Vec`. - // SAFETY: Conversion is safe because both types store data in arena in same way. - // Lifetime of returned `String` is same as lifetime of original `Vec`. - let inner = ManuallyDrop::into_inner(bytes.0); - let (ptr, len, capacity, bump) = inner.into_raw_parts_with_alloc(); - Self(ManuallyDrop::new(BumpaloString::from_raw_parts_in(ptr, len, capacity, bump))) + unsafe { + // Cannot use `bumpalo::String::from_utf8_unchecked` because it takes a `bumpalo::collections::Vec`, + // and our inner `Vec` type is `allocator_api2::vec::Vec`. + // SAFETY: Conversion is safe because both types store data in arena in same way. + // Lifetime of returned `String` is same as lifetime of original `Vec`. + let inner = ManuallyDrop::into_inner(bytes.0); + let (ptr, len, capacity, bump) = inner.into_raw_parts_with_alloc(); + Self(ManuallyDrop::new(BumpaloString::from_raw_parts_in(ptr, len, capacity, bump))) + } } /// Creates a new [`String`] from a length, capacity, and pointer. @@ -149,7 +150,6 @@ impl<'alloc> String<'alloc> { /// assert_eq!(s, "hello"); /// } /// ``` - #[expect(clippy::unnecessary_safety_comment)] #[inline(always)] pub unsafe fn from_raw_parts_in( buf: *mut u8, @@ -157,9 +157,11 @@ impl<'alloc> String<'alloc> { capacity: usize, allocator: &'alloc Allocator, ) -> String<'alloc> { - // SAFETY: Safety conditions of this method are the same as `BumpaloString`'s method - let inner = BumpaloString::from_raw_parts_in(buf, length, capacity, allocator.bump()); - Self(ManuallyDrop::new(inner)) + unsafe { + // SAFETY: Safety conditions of this method are the same as `BumpaloString`'s method + let inner = BumpaloString::from_raw_parts_in(buf, length, capacity, allocator.bump()); + Self(ManuallyDrop::new(inner)) + } } /// Convert this `String<'alloc>` into an `&'alloc str`. This is analogous to diff --git a/crates/oxc_ast/src/ast_builder_impl.rs b/crates/oxc_ast/src/ast_builder_impl.rs index 6173e6a46b1098..8bb2be5afc3983 100644 --- a/crates/oxc_ast/src/ast_builder_impl.rs +++ b/crates/oxc_ast/src/ast_builder_impl.rs @@ -3,10 +3,10 @@ use std::{borrow::Cow, mem}; use oxc_allocator::{Allocator, Box, FromIn, Vec}; -use oxc_span::{Atom, Span, SPAN}; +use oxc_span::{Atom, SPAN, Span}; use oxc_syntax::{number::NumberBase, operator::UnaryOperator, scope::ScopeId}; -use crate::{ast::*, AstBuilder}; +use crate::{AstBuilder, ast::*}; /// Type that can be used in any AST builder method call which requires an `IntoIn<'a, Anything<'a>>`. /// Pass `NONE` instead of `None::>`. diff --git a/crates/oxc_ast/src/ast_impl/js.rs b/crates/oxc_ast/src/ast_impl/js.rs index 5ecd777cc1427f..a1d5ad4d7588ac 100644 --- a/crates/oxc_ast/src/ast_impl/js.rs +++ b/crates/oxc_ast/src/ast_impl/js.rs @@ -352,11 +352,7 @@ impl<'a> Expression<'a> { /// /// See [`CallExpression::is_require_call`] for details of the exact patterns that match. pub fn is_require_call(&self) -> bool { - if let Self::CallExpression(call_expr) = self { - call_expr.is_require_call() - } else { - false - } + if let Self::CallExpression(call_expr) = self { call_expr.is_require_call() } else { false } } /// Returns `true` if this is an [assignment expression](AssignmentExpression). diff --git a/crates/oxc_ast/src/ast_impl/literal.rs b/crates/oxc_ast/src/ast_impl/literal.rs index ae429fcfa19bf9..dcb5c43401d033 100644 --- a/crates/oxc_ast/src/ast_impl/literal.rs +++ b/crates/oxc_ast/src/ast_impl/literal.rs @@ -11,11 +11,7 @@ use crate::ast::*; impl BooleanLiteral { /// `"true"` or `"false"` depending on this boolean's value. pub fn as_str(&self) -> &'static str { - if self.value { - "true" - } else { - "false" - } + if self.value { "true" } else { "false" } } } @@ -54,11 +50,7 @@ impl NumericLiteral<'_> { let int32bit = pos_int % 2f64.powi(32); // step5 - if int32bit >= 2f64.powi(31) { - (int32bit - 2f64.powi(32)) as i32 - } else { - int32bit as i32 - } + if int32bit >= 2f64.powi(31) { (int32bit - 2f64.powi(32)) as i32 } else { int32bit as i32 } } /// Return raw source code for `NumericLiteral`. @@ -182,11 +174,7 @@ impl<'a> RegExpPattern<'a> { /// Flatten this regular expression into a compiled [`Pattern`], returning /// [`None`] if the pattern is invalid or not parsed. pub fn as_pattern(&self) -> Option<&Pattern<'a>> { - if let Self::Pattern(it) = self { - Some(it.as_ref()) - } else { - None - } + if let Self::Pattern(it) = self { Some(it.as_ref()) } else { None } } } diff --git a/crates/oxc_ast/src/ast_kind_impl.rs b/crates/oxc_ast/src/ast_kind_impl.rs index cabe68e46343e1..750f6d78684067 100644 --- a/crates/oxc_ast/src/ast_kind_impl.rs +++ b/crates/oxc_ast/src/ast_kind_impl.rs @@ -2,7 +2,7 @@ use oxc_span::Atom; use oxc_syntax::scope::ScopeId; -use super::{ast::*, AstKind}; +use super::{AstKind, ast::*}; impl<'a> AstKind<'a> { #[rustfmt::skip] diff --git a/crates/oxc_ast/src/generated/ast_kind.rs b/crates/oxc_ast/src/generated/ast_kind.rs index cf9713773c2081..de7b583177be99 100644 --- a/crates/oxc_ast/src/generated/ast_kind.rs +++ b/crates/oxc_ast/src/generated/ast_kind.rs @@ -552,1490 +552,830 @@ impl GetSpan for AstKind<'_> { impl<'a> AstKind<'a> { #[inline] pub fn as_program(self) -> Option<&'a Program<'a>> { - if let Self::Program(v) = self { - Some(v) - } else { - None - } + if let Self::Program(v) = self { Some(v) } else { None } } #[inline] pub fn as_identifier_name(self) -> Option<&'a IdentifierName<'a>> { - if let Self::IdentifierName(v) = self { - Some(v) - } else { - None - } + if let Self::IdentifierName(v) = self { Some(v) } else { None } } #[inline] pub fn as_identifier_reference(self) -> Option<&'a IdentifierReference<'a>> { - if let Self::IdentifierReference(v) = self { - Some(v) - } else { - None - } + if let Self::IdentifierReference(v) = self { Some(v) } else { None } } #[inline] pub fn as_binding_identifier(self) -> Option<&'a BindingIdentifier<'a>> { - if let Self::BindingIdentifier(v) = self { - Some(v) - } else { - None - } + if let Self::BindingIdentifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_label_identifier(self) -> Option<&'a LabelIdentifier<'a>> { - if let Self::LabelIdentifier(v) = self { - Some(v) - } else { - None - } + if let Self::LabelIdentifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_this_expression(self) -> Option<&'a ThisExpression> { - if let Self::ThisExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ThisExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_array_expression(self) -> Option<&'a ArrayExpression<'a>> { - if let Self::ArrayExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ArrayExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_array_expression_element(self) -> Option<&'a ArrayExpressionElement<'a>> { - if let Self::ArrayExpressionElement(v) = self { - Some(v) - } else { - None - } + if let Self::ArrayExpressionElement(v) = self { Some(v) } else { None } } #[inline] pub fn as_elision(self) -> Option<&'a Elision> { - if let Self::Elision(v) = self { - Some(v) - } else { - None - } + if let Self::Elision(v) = self { Some(v) } else { None } } #[inline] pub fn as_object_expression(self) -> Option<&'a ObjectExpression<'a>> { - if let Self::ObjectExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ObjectExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_object_property(self) -> Option<&'a ObjectProperty<'a>> { - if let Self::ObjectProperty(v) = self { - Some(v) - } else { - None - } + if let Self::ObjectProperty(v) = self { Some(v) } else { None } } #[inline] pub fn as_property_key(self) -> Option<&'a PropertyKey<'a>> { - if let Self::PropertyKey(v) = self { - Some(v) - } else { - None - } + if let Self::PropertyKey(v) = self { Some(v) } else { None } } #[inline] pub fn as_template_literal(self) -> Option<&'a TemplateLiteral<'a>> { - if let Self::TemplateLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::TemplateLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_tagged_template_expression(self) -> Option<&'a TaggedTemplateExpression<'a>> { - if let Self::TaggedTemplateExpression(v) = self { - Some(v) - } else { - None - } + if let Self::TaggedTemplateExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_member_expression(self) -> Option<&'a MemberExpression<'a>> { - if let Self::MemberExpression(v) = self { - Some(v) - } else { - None - } + if let Self::MemberExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_call_expression(self) -> Option<&'a CallExpression<'a>> { - if let Self::CallExpression(v) = self { - Some(v) - } else { - None - } + if let Self::CallExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_new_expression(self) -> Option<&'a NewExpression<'a>> { - if let Self::NewExpression(v) = self { - Some(v) - } else { - None - } + if let Self::NewExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_meta_property(self) -> Option<&'a MetaProperty<'a>> { - if let Self::MetaProperty(v) = self { - Some(v) - } else { - None - } + if let Self::MetaProperty(v) = self { Some(v) } else { None } } #[inline] pub fn as_spread_element(self) -> Option<&'a SpreadElement<'a>> { - if let Self::SpreadElement(v) = self { - Some(v) - } else { - None - } + if let Self::SpreadElement(v) = self { Some(v) } else { None } } #[inline] pub fn as_argument(self) -> Option<&'a Argument<'a>> { - if let Self::Argument(v) = self { - Some(v) - } else { - None - } + if let Self::Argument(v) = self { Some(v) } else { None } } #[inline] pub fn as_update_expression(self) -> Option<&'a UpdateExpression<'a>> { - if let Self::UpdateExpression(v) = self { - Some(v) - } else { - None - } + if let Self::UpdateExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_unary_expression(self) -> Option<&'a UnaryExpression<'a>> { - if let Self::UnaryExpression(v) = self { - Some(v) - } else { - None - } + if let Self::UnaryExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_binary_expression(self) -> Option<&'a BinaryExpression<'a>> { - if let Self::BinaryExpression(v) = self { - Some(v) - } else { - None - } + if let Self::BinaryExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_private_in_expression(self) -> Option<&'a PrivateInExpression<'a>> { - if let Self::PrivateInExpression(v) = self { - Some(v) - } else { - None - } + if let Self::PrivateInExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_logical_expression(self) -> Option<&'a LogicalExpression<'a>> { - if let Self::LogicalExpression(v) = self { - Some(v) - } else { - None - } + if let Self::LogicalExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_conditional_expression(self) -> Option<&'a ConditionalExpression<'a>> { - if let Self::ConditionalExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ConditionalExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_assignment_expression(self) -> Option<&'a AssignmentExpression<'a>> { - if let Self::AssignmentExpression(v) = self { - Some(v) - } else { - None - } + if let Self::AssignmentExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_assignment_target(self) -> Option<&'a AssignmentTarget<'a>> { - if let Self::AssignmentTarget(v) = self { - Some(v) - } else { - None - } + if let Self::AssignmentTarget(v) = self { Some(v) } else { None } } #[inline] pub fn as_simple_assignment_target(self) -> Option<&'a SimpleAssignmentTarget<'a>> { - if let Self::SimpleAssignmentTarget(v) = self { - Some(v) - } else { - None - } + if let Self::SimpleAssignmentTarget(v) = self { Some(v) } else { None } } #[inline] pub fn as_assignment_target_pattern(self) -> Option<&'a AssignmentTargetPattern<'a>> { - if let Self::AssignmentTargetPattern(v) = self { - Some(v) - } else { - None - } + if let Self::AssignmentTargetPattern(v) = self { Some(v) } else { None } } #[inline] pub fn as_array_assignment_target(self) -> Option<&'a ArrayAssignmentTarget<'a>> { - if let Self::ArrayAssignmentTarget(v) = self { - Some(v) - } else { - None - } + if let Self::ArrayAssignmentTarget(v) = self { Some(v) } else { None } } #[inline] pub fn as_object_assignment_target(self) -> Option<&'a ObjectAssignmentTarget<'a>> { - if let Self::ObjectAssignmentTarget(v) = self { - Some(v) - } else { - None - } + if let Self::ObjectAssignmentTarget(v) = self { Some(v) } else { None } } #[inline] pub fn as_assignment_target_with_default(self) -> Option<&'a AssignmentTargetWithDefault<'a>> { - if let Self::AssignmentTargetWithDefault(v) = self { - Some(v) - } else { - None - } + if let Self::AssignmentTargetWithDefault(v) = self { Some(v) } else { None } } #[inline] pub fn as_sequence_expression(self) -> Option<&'a SequenceExpression<'a>> { - if let Self::SequenceExpression(v) = self { - Some(v) - } else { - None - } + if let Self::SequenceExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_super(self) -> Option<&'a Super> { - if let Self::Super(v) = self { - Some(v) - } else { - None - } + if let Self::Super(v) = self { Some(v) } else { None } } #[inline] pub fn as_await_expression(self) -> Option<&'a AwaitExpression<'a>> { - if let Self::AwaitExpression(v) = self { - Some(v) - } else { - None - } + if let Self::AwaitExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_chain_expression(self) -> Option<&'a ChainExpression<'a>> { - if let Self::ChainExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ChainExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_parenthesized_expression(self) -> Option<&'a ParenthesizedExpression<'a>> { - if let Self::ParenthesizedExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ParenthesizedExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_directive(self) -> Option<&'a Directive<'a>> { - if let Self::Directive(v) = self { - Some(v) - } else { - None - } + if let Self::Directive(v) = self { Some(v) } else { None } } #[inline] pub fn as_hashbang(self) -> Option<&'a Hashbang<'a>> { - if let Self::Hashbang(v) = self { - Some(v) - } else { - None - } + if let Self::Hashbang(v) = self { Some(v) } else { None } } #[inline] pub fn as_block_statement(self) -> Option<&'a BlockStatement<'a>> { - if let Self::BlockStatement(v) = self { - Some(v) - } else { - None - } + if let Self::BlockStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_variable_declaration(self) -> Option<&'a VariableDeclaration<'a>> { - if let Self::VariableDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::VariableDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_variable_declarator(self) -> Option<&'a VariableDeclarator<'a>> { - if let Self::VariableDeclarator(v) = self { - Some(v) - } else { - None - } + if let Self::VariableDeclarator(v) = self { Some(v) } else { None } } #[inline] pub fn as_empty_statement(self) -> Option<&'a EmptyStatement> { - if let Self::EmptyStatement(v) = self { - Some(v) - } else { - None - } + if let Self::EmptyStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_expression_statement(self) -> Option<&'a ExpressionStatement<'a>> { - if let Self::ExpressionStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ExpressionStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_if_statement(self) -> Option<&'a IfStatement<'a>> { - if let Self::IfStatement(v) = self { - Some(v) - } else { - None - } + if let Self::IfStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_do_while_statement(self) -> Option<&'a DoWhileStatement<'a>> { - if let Self::DoWhileStatement(v) = self { - Some(v) - } else { - None - } + if let Self::DoWhileStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_while_statement(self) -> Option<&'a WhileStatement<'a>> { - if let Self::WhileStatement(v) = self { - Some(v) - } else { - None - } + if let Self::WhileStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_for_statement(self) -> Option<&'a ForStatement<'a>> { - if let Self::ForStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ForStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_for_statement_init(self) -> Option<&'a ForStatementInit<'a>> { - if let Self::ForStatementInit(v) = self { - Some(v) - } else { - None - } + if let Self::ForStatementInit(v) = self { Some(v) } else { None } } #[inline] pub fn as_for_in_statement(self) -> Option<&'a ForInStatement<'a>> { - if let Self::ForInStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ForInStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_for_of_statement(self) -> Option<&'a ForOfStatement<'a>> { - if let Self::ForOfStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ForOfStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_continue_statement(self) -> Option<&'a ContinueStatement<'a>> { - if let Self::ContinueStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ContinueStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_break_statement(self) -> Option<&'a BreakStatement<'a>> { - if let Self::BreakStatement(v) = self { - Some(v) - } else { - None - } + if let Self::BreakStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_return_statement(self) -> Option<&'a ReturnStatement<'a>> { - if let Self::ReturnStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ReturnStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_with_statement(self) -> Option<&'a WithStatement<'a>> { - if let Self::WithStatement(v) = self { - Some(v) - } else { - None - } + if let Self::WithStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_switch_statement(self) -> Option<&'a SwitchStatement<'a>> { - if let Self::SwitchStatement(v) = self { - Some(v) - } else { - None - } + if let Self::SwitchStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_switch_case(self) -> Option<&'a SwitchCase<'a>> { - if let Self::SwitchCase(v) = self { - Some(v) - } else { - None - } + if let Self::SwitchCase(v) = self { Some(v) } else { None } } #[inline] pub fn as_labeled_statement(self) -> Option<&'a LabeledStatement<'a>> { - if let Self::LabeledStatement(v) = self { - Some(v) - } else { - None - } + if let Self::LabeledStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_throw_statement(self) -> Option<&'a ThrowStatement<'a>> { - if let Self::ThrowStatement(v) = self { - Some(v) - } else { - None - } + if let Self::ThrowStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_try_statement(self) -> Option<&'a TryStatement<'a>> { - if let Self::TryStatement(v) = self { - Some(v) - } else { - None - } + if let Self::TryStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_catch_clause(self) -> Option<&'a CatchClause<'a>> { - if let Self::CatchClause(v) = self { - Some(v) - } else { - None - } + if let Self::CatchClause(v) = self { Some(v) } else { None } } #[inline] pub fn as_catch_parameter(self) -> Option<&'a CatchParameter<'a>> { - if let Self::CatchParameter(v) = self { - Some(v) - } else { - None - } + if let Self::CatchParameter(v) = self { Some(v) } else { None } } #[inline] pub fn as_debugger_statement(self) -> Option<&'a DebuggerStatement> { - if let Self::DebuggerStatement(v) = self { - Some(v) - } else { - None - } + if let Self::DebuggerStatement(v) = self { Some(v) } else { None } } #[inline] pub fn as_assignment_pattern(self) -> Option<&'a AssignmentPattern<'a>> { - if let Self::AssignmentPattern(v) = self { - Some(v) - } else { - None - } + if let Self::AssignmentPattern(v) = self { Some(v) } else { None } } #[inline] pub fn as_object_pattern(self) -> Option<&'a ObjectPattern<'a>> { - if let Self::ObjectPattern(v) = self { - Some(v) - } else { - None - } + if let Self::ObjectPattern(v) = self { Some(v) } else { None } } #[inline] pub fn as_array_pattern(self) -> Option<&'a ArrayPattern<'a>> { - if let Self::ArrayPattern(v) = self { - Some(v) - } else { - None - } + if let Self::ArrayPattern(v) = self { Some(v) } else { None } } #[inline] pub fn as_binding_rest_element(self) -> Option<&'a BindingRestElement<'a>> { - if let Self::BindingRestElement(v) = self { - Some(v) - } else { - None - } + if let Self::BindingRestElement(v) = self { Some(v) } else { None } } #[inline] pub fn as_function(self) -> Option<&'a Function<'a>> { - if let Self::Function(v) = self { - Some(v) - } else { - None - } + if let Self::Function(v) = self { Some(v) } else { None } } #[inline] pub fn as_formal_parameters(self) -> Option<&'a FormalParameters<'a>> { - if let Self::FormalParameters(v) = self { - Some(v) - } else { - None - } + if let Self::FormalParameters(v) = self { Some(v) } else { None } } #[inline] pub fn as_formal_parameter(self) -> Option<&'a FormalParameter<'a>> { - if let Self::FormalParameter(v) = self { - Some(v) - } else { - None - } + if let Self::FormalParameter(v) = self { Some(v) } else { None } } #[inline] pub fn as_function_body(self) -> Option<&'a FunctionBody<'a>> { - if let Self::FunctionBody(v) = self { - Some(v) - } else { - None - } + if let Self::FunctionBody(v) = self { Some(v) } else { None } } #[inline] pub fn as_arrow_function_expression(self) -> Option<&'a ArrowFunctionExpression<'a>> { - if let Self::ArrowFunctionExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ArrowFunctionExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_yield_expression(self) -> Option<&'a YieldExpression<'a>> { - if let Self::YieldExpression(v) = self { - Some(v) - } else { - None - } + if let Self::YieldExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_class(self) -> Option<&'a Class<'a>> { - if let Self::Class(v) = self { - Some(v) - } else { - None - } + if let Self::Class(v) = self { Some(v) } else { None } } #[inline] pub fn as_class_body(self) -> Option<&'a ClassBody<'a>> { - if let Self::ClassBody(v) = self { - Some(v) - } else { - None - } + if let Self::ClassBody(v) = self { Some(v) } else { None } } #[inline] pub fn as_method_definition(self) -> Option<&'a MethodDefinition<'a>> { - if let Self::MethodDefinition(v) = self { - Some(v) - } else { - None - } + if let Self::MethodDefinition(v) = self { Some(v) } else { None } } #[inline] pub fn as_property_definition(self) -> Option<&'a PropertyDefinition<'a>> { - if let Self::PropertyDefinition(v) = self { - Some(v) - } else { - None - } + if let Self::PropertyDefinition(v) = self { Some(v) } else { None } } #[inline] pub fn as_private_identifier(self) -> Option<&'a PrivateIdentifier<'a>> { - if let Self::PrivateIdentifier(v) = self { - Some(v) - } else { - None - } + if let Self::PrivateIdentifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_static_block(self) -> Option<&'a StaticBlock<'a>> { - if let Self::StaticBlock(v) = self { - Some(v) - } else { - None - } + if let Self::StaticBlock(v) = self { Some(v) } else { None } } #[inline] pub fn as_module_declaration(self) -> Option<&'a ModuleDeclaration<'a>> { - if let Self::ModuleDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::ModuleDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_import_expression(self) -> Option<&'a ImportExpression<'a>> { - if let Self::ImportExpression(v) = self { - Some(v) - } else { - None - } + if let Self::ImportExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_import_declaration(self) -> Option<&'a ImportDeclaration<'a>> { - if let Self::ImportDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::ImportDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_import_specifier(self) -> Option<&'a ImportSpecifier<'a>> { - if let Self::ImportSpecifier(v) = self { - Some(v) - } else { - None - } + if let Self::ImportSpecifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_import_default_specifier(self) -> Option<&'a ImportDefaultSpecifier<'a>> { - if let Self::ImportDefaultSpecifier(v) = self { - Some(v) - } else { - None - } + if let Self::ImportDefaultSpecifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_import_namespace_specifier(self) -> Option<&'a ImportNamespaceSpecifier<'a>> { - if let Self::ImportNamespaceSpecifier(v) = self { - Some(v) - } else { - None - } + if let Self::ImportNamespaceSpecifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_export_named_declaration(self) -> Option<&'a ExportNamedDeclaration<'a>> { - if let Self::ExportNamedDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::ExportNamedDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_export_default_declaration(self) -> Option<&'a ExportDefaultDeclaration<'a>> { - if let Self::ExportDefaultDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::ExportDefaultDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_export_all_declaration(self) -> Option<&'a ExportAllDeclaration<'a>> { - if let Self::ExportAllDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::ExportAllDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_export_specifier(self) -> Option<&'a ExportSpecifier<'a>> { - if let Self::ExportSpecifier(v) = self { - Some(v) - } else { - None - } + if let Self::ExportSpecifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_boolean_literal(self) -> Option<&'a BooleanLiteral> { - if let Self::BooleanLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::BooleanLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_null_literal(self) -> Option<&'a NullLiteral> { - if let Self::NullLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::NullLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_numeric_literal(self) -> Option<&'a NumericLiteral<'a>> { - if let Self::NumericLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::NumericLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_string_literal(self) -> Option<&'a StringLiteral<'a>> { - if let Self::StringLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::StringLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_big_int_literal(self) -> Option<&'a BigIntLiteral<'a>> { - if let Self::BigIntLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::BigIntLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_reg_exp_literal(self) -> Option<&'a RegExpLiteral<'a>> { - if let Self::RegExpLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::RegExpLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_element(self) -> Option<&'a JSXElement<'a>> { - if let Self::JSXElement(v) = self { - Some(v) - } else { - None - } + if let Self::JSXElement(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_opening_element(self) -> Option<&'a JSXOpeningElement<'a>> { - if let Self::JSXOpeningElement(v) = self { - Some(v) - } else { - None - } + if let Self::JSXOpeningElement(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_closing_element(self) -> Option<&'a JSXClosingElement<'a>> { - if let Self::JSXClosingElement(v) = self { - Some(v) - } else { - None - } + if let Self::JSXClosingElement(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_fragment(self) -> Option<&'a JSXFragment<'a>> { - if let Self::JSXFragment(v) = self { - Some(v) - } else { - None - } + if let Self::JSXFragment(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_element_name(self) -> Option<&'a JSXElementName<'a>> { - if let Self::JSXElementName(v) = self { - Some(v) - } else { - None - } + if let Self::JSXElementName(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_namespaced_name(self) -> Option<&'a JSXNamespacedName<'a>> { - if let Self::JSXNamespacedName(v) = self { - Some(v) - } else { - None - } + if let Self::JSXNamespacedName(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_member_expression(self) -> Option<&'a JSXMemberExpression<'a>> { - if let Self::JSXMemberExpression(v) = self { - Some(v) - } else { - None - } + if let Self::JSXMemberExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_member_expression_object(self) -> Option<&'a JSXMemberExpressionObject<'a>> { - if let Self::JSXMemberExpressionObject(v) = self { - Some(v) - } else { - None - } + if let Self::JSXMemberExpressionObject(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_expression_container(self) -> Option<&'a JSXExpressionContainer<'a>> { - if let Self::JSXExpressionContainer(v) = self { - Some(v) - } else { - None - } + if let Self::JSXExpressionContainer(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_attribute_item(self) -> Option<&'a JSXAttributeItem<'a>> { - if let Self::JSXAttributeItem(v) = self { - Some(v) - } else { - None - } + if let Self::JSXAttributeItem(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_spread_attribute(self) -> Option<&'a JSXSpreadAttribute<'a>> { - if let Self::JSXSpreadAttribute(v) = self { - Some(v) - } else { - None - } + if let Self::JSXSpreadAttribute(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_identifier(self) -> Option<&'a JSXIdentifier<'a>> { - if let Self::JSXIdentifier(v) = self { - Some(v) - } else { - None - } + if let Self::JSXIdentifier(v) = self { Some(v) } else { None } } #[inline] pub fn as_jsx_text(self) -> Option<&'a JSXText<'a>> { - if let Self::JSXText(v) = self { - Some(v) - } else { - None - } + if let Self::JSXText(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_this_parameter(self) -> Option<&'a TSThisParameter<'a>> { - if let Self::TSThisParameter(v) = self { - Some(v) - } else { - None - } + if let Self::TSThisParameter(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_enum_declaration(self) -> Option<&'a TSEnumDeclaration<'a>> { - if let Self::TSEnumDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSEnumDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_enum_member(self) -> Option<&'a TSEnumMember<'a>> { - if let Self::TSEnumMember(v) = self { - Some(v) - } else { - None - } + if let Self::TSEnumMember(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_annotation(self) -> Option<&'a TSTypeAnnotation<'a>> { - if let Self::TSTypeAnnotation(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeAnnotation(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_literal_type(self) -> Option<&'a TSLiteralType<'a>> { - if let Self::TSLiteralType(v) = self { - Some(v) - } else { - None - } + if let Self::TSLiteralType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_conditional_type(self) -> Option<&'a TSConditionalType<'a>> { - if let Self::TSConditionalType(v) = self { - Some(v) - } else { - None - } + if let Self::TSConditionalType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_union_type(self) -> Option<&'a TSUnionType<'a>> { - if let Self::TSUnionType(v) = self { - Some(v) - } else { - None - } + if let Self::TSUnionType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_intersection_type(self) -> Option<&'a TSIntersectionType<'a>> { - if let Self::TSIntersectionType(v) = self { - Some(v) - } else { - None - } + if let Self::TSIntersectionType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_parenthesized_type(self) -> Option<&'a TSParenthesizedType<'a>> { - if let Self::TSParenthesizedType(v) = self { - Some(v) - } else { - None - } + if let Self::TSParenthesizedType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_indexed_access_type(self) -> Option<&'a TSIndexedAccessType<'a>> { - if let Self::TSIndexedAccessType(v) = self { - Some(v) - } else { - None - } + if let Self::TSIndexedAccessType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_named_tuple_member(self) -> Option<&'a TSNamedTupleMember<'a>> { - if let Self::TSNamedTupleMember(v) = self { - Some(v) - } else { - None - } + if let Self::TSNamedTupleMember(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_any_keyword(self) -> Option<&'a TSAnyKeyword> { - if let Self::TSAnyKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSAnyKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_string_keyword(self) -> Option<&'a TSStringKeyword> { - if let Self::TSStringKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSStringKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_boolean_keyword(self) -> Option<&'a TSBooleanKeyword> { - if let Self::TSBooleanKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSBooleanKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_number_keyword(self) -> Option<&'a TSNumberKeyword> { - if let Self::TSNumberKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSNumberKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_never_keyword(self) -> Option<&'a TSNeverKeyword> { - if let Self::TSNeverKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSNeverKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_intrinsic_keyword(self) -> Option<&'a TSIntrinsicKeyword> { - if let Self::TSIntrinsicKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSIntrinsicKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_unknown_keyword(self) -> Option<&'a TSUnknownKeyword> { - if let Self::TSUnknownKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSUnknownKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_null_keyword(self) -> Option<&'a TSNullKeyword> { - if let Self::TSNullKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSNullKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_undefined_keyword(self) -> Option<&'a TSUndefinedKeyword> { - if let Self::TSUndefinedKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSUndefinedKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_void_keyword(self) -> Option<&'a TSVoidKeyword> { - if let Self::TSVoidKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSVoidKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_symbol_keyword(self) -> Option<&'a TSSymbolKeyword> { - if let Self::TSSymbolKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSSymbolKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_this_type(self) -> Option<&'a TSThisType> { - if let Self::TSThisType(v) = self { - Some(v) - } else { - None - } + if let Self::TSThisType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_object_keyword(self) -> Option<&'a TSObjectKeyword> { - if let Self::TSObjectKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSObjectKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_big_int_keyword(self) -> Option<&'a TSBigIntKeyword> { - if let Self::TSBigIntKeyword(v) = self { - Some(v) - } else { - None - } + if let Self::TSBigIntKeyword(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_reference(self) -> Option<&'a TSTypeReference<'a>> { - if let Self::TSTypeReference(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeReference(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_name(self) -> Option<&'a TSTypeName<'a>> { - if let Self::TSTypeName(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeName(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_qualified_name(self) -> Option<&'a TSQualifiedName<'a>> { - if let Self::TSQualifiedName(v) = self { - Some(v) - } else { - None - } + if let Self::TSQualifiedName(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_parameter_instantiation( self, ) -> Option<&'a TSTypeParameterInstantiation<'a>> { - if let Self::TSTypeParameterInstantiation(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeParameterInstantiation(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_parameter(self) -> Option<&'a TSTypeParameter<'a>> { - if let Self::TSTypeParameter(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeParameter(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_parameter_declaration(self) -> Option<&'a TSTypeParameterDeclaration<'a>> { - if let Self::TSTypeParameterDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeParameterDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_alias_declaration(self) -> Option<&'a TSTypeAliasDeclaration<'a>> { - if let Self::TSTypeAliasDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeAliasDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_class_implements(self) -> Option<&'a TSClassImplements<'a>> { - if let Self::TSClassImplements(v) = self { - Some(v) - } else { - None - } + if let Self::TSClassImplements(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_interface_declaration(self) -> Option<&'a TSInterfaceDeclaration<'a>> { - if let Self::TSInterfaceDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSInterfaceDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_property_signature(self) -> Option<&'a TSPropertySignature<'a>> { - if let Self::TSPropertySignature(v) = self { - Some(v) - } else { - None - } + if let Self::TSPropertySignature(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_method_signature(self) -> Option<&'a TSMethodSignature<'a>> { - if let Self::TSMethodSignature(v) = self { - Some(v) - } else { - None - } + if let Self::TSMethodSignature(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_construct_signature_declaration( self, ) -> Option<&'a TSConstructSignatureDeclaration<'a>> { - if let Self::TSConstructSignatureDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSConstructSignatureDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_interface_heritage(self) -> Option<&'a TSInterfaceHeritage<'a>> { - if let Self::TSInterfaceHeritage(v) = self { - Some(v) - } else { - None - } + if let Self::TSInterfaceHeritage(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_module_declaration(self) -> Option<&'a TSModuleDeclaration<'a>> { - if let Self::TSModuleDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSModuleDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_module_block(self) -> Option<&'a TSModuleBlock<'a>> { - if let Self::TSModuleBlock(v) = self { - Some(v) - } else { - None - } + if let Self::TSModuleBlock(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_literal(self) -> Option<&'a TSTypeLiteral<'a>> { - if let Self::TSTypeLiteral(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeLiteral(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_infer_type(self) -> Option<&'a TSInferType<'a>> { - if let Self::TSInferType(v) = self { - Some(v) - } else { - None - } + if let Self::TSInferType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_query(self) -> Option<&'a TSTypeQuery<'a>> { - if let Self::TSTypeQuery(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeQuery(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_import_type(self) -> Option<&'a TSImportType<'a>> { - if let Self::TSImportType(v) = self { - Some(v) - } else { - None - } + if let Self::TSImportType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_mapped_type(self) -> Option<&'a TSMappedType<'a>> { - if let Self::TSMappedType(v) = self { - Some(v) - } else { - None - } + if let Self::TSMappedType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_template_literal_type(self) -> Option<&'a TSTemplateLiteralType<'a>> { - if let Self::TSTemplateLiteralType(v) = self { - Some(v) - } else { - None - } + if let Self::TSTemplateLiteralType(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_as_expression(self) -> Option<&'a TSAsExpression<'a>> { - if let Self::TSAsExpression(v) = self { - Some(v) - } else { - None - } + if let Self::TSAsExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_satisfies_expression(self) -> Option<&'a TSSatisfiesExpression<'a>> { - if let Self::TSSatisfiesExpression(v) = self { - Some(v) - } else { - None - } + if let Self::TSSatisfiesExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_type_assertion(self) -> Option<&'a TSTypeAssertion<'a>> { - if let Self::TSTypeAssertion(v) = self { - Some(v) - } else { - None - } + if let Self::TSTypeAssertion(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_import_equals_declaration(self) -> Option<&'a TSImportEqualsDeclaration<'a>> { - if let Self::TSImportEqualsDeclaration(v) = self { - Some(v) - } else { - None - } + if let Self::TSImportEqualsDeclaration(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_module_reference(self) -> Option<&'a TSModuleReference<'a>> { - if let Self::TSModuleReference(v) = self { - Some(v) - } else { - None - } + if let Self::TSModuleReference(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_external_module_reference(self) -> Option<&'a TSExternalModuleReference<'a>> { - if let Self::TSExternalModuleReference(v) = self { - Some(v) - } else { - None - } + if let Self::TSExternalModuleReference(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_non_null_expression(self) -> Option<&'a TSNonNullExpression<'a>> { - if let Self::TSNonNullExpression(v) = self { - Some(v) - } else { - None - } + if let Self::TSNonNullExpression(v) = self { Some(v) } else { None } } #[inline] pub fn as_decorator(self) -> Option<&'a Decorator<'a>> { - if let Self::Decorator(v) = self { - Some(v) - } else { - None - } + if let Self::Decorator(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_export_assignment(self) -> Option<&'a TSExportAssignment<'a>> { - if let Self::TSExportAssignment(v) = self { - Some(v) - } else { - None - } + if let Self::TSExportAssignment(v) = self { Some(v) } else { None } } #[inline] pub fn as_ts_instantiation_expression(self) -> Option<&'a TSInstantiationExpression<'a>> { - if let Self::TSInstantiationExpression(v) = self { - Some(v) - } else { - None - } + if let Self::TSInstantiationExpression(v) = self { Some(v) } else { None } } } diff --git a/crates/oxc_ast/src/generated/derive_estree.rs b/crates/oxc_ast/src/generated/derive_estree.rs index a9ff43af1389bc..33139dfe50a664 100644 --- a/crates/oxc_ast/src/generated/derive_estree.rs +++ b/crates/oxc_ast/src/generated/derive_estree.rs @@ -4,8 +4,8 @@ #![allow(unused_imports, clippy::match_same_arms, clippy::semicolon_if_nothing_returned)] use oxc_estree::{ - ser::{AppendTo, AppendToConcat}, ESTree, FlatStructSerializer, Serializer, StructSerializer, + ser::{AppendTo, AppendToConcat}, }; use crate::ast::js::*; diff --git a/crates/oxc_ast/src/lib.rs b/crates/oxc_ast/src/lib.rs index dfe565b8e7deff..b512bb7a239c32 100644 --- a/crates/oxc_ast/src/lib.rs +++ b/crates/oxc_ast/src/lib.rs @@ -83,7 +83,7 @@ pub use crate::{ ast_builder::AstBuilder, ast_builder_impl::NONE, ast_kind::{AstKind, AstType}, - trivia::{comments_range, has_comments_between, CommentsRange}, + trivia::{CommentsRange, comments_range, has_comments_between}, visit::{Visit, VisitMut}, }; diff --git a/crates/oxc_ast/src/precedence.rs b/crates/oxc_ast/src/precedence.rs index b7e059e8f33674..0705bac3c572e3 100644 --- a/crates/oxc_ast/src/precedence.rs +++ b/crates/oxc_ast/src/precedence.rs @@ -2,11 +2,11 @@ use oxc_syntax::precedence::{GetPrecedence, Precedence}; use crate::ast::{ - match_member_expression, AssignmentExpression, AwaitExpression, BinaryExpression, - CallExpression, ChainExpression, ComputedMemberExpression, ConditionalExpression, Expression, - ImportExpression, LogicalExpression, MemberExpression, NewExpression, PrivateFieldExpression, - SequenceExpression, StaticMemberExpression, TSTypeAssertion, UnaryExpression, UpdateExpression, - YieldExpression, + AssignmentExpression, AwaitExpression, BinaryExpression, CallExpression, ChainExpression, + ComputedMemberExpression, ConditionalExpression, Expression, ImportExpression, + LogicalExpression, MemberExpression, NewExpression, PrivateFieldExpression, SequenceExpression, + StaticMemberExpression, TSTypeAssertion, UnaryExpression, UpdateExpression, YieldExpression, + match_member_expression, }; impl GetPrecedence for Expression<'_> { @@ -79,11 +79,7 @@ impl GetPrecedence for AwaitExpression<'_> { impl GetPrecedence for UpdateExpression<'_> { fn precedence(&self) -> Precedence { - if self.prefix { - Precedence::Prefix - } else { - Precedence::Postfix - } + if self.prefix { Precedence::Prefix } else { Precedence::Postfix } } } diff --git a/crates/oxc_ast/src/utf8_to_utf16.rs b/crates/oxc_ast/src/utf8_to_utf16.rs index 01af9047082cd8..0b449f8f85607d 100644 --- a/crates/oxc_ast/src/utf8_to_utf16.rs +++ b/crates/oxc_ast/src/utf8_to_utf16.rs @@ -120,8 +120,8 @@ mod test { use oxc_span::{GetSpan, SourceType, Span}; use crate::{ - ast::{Expression, Statement}, AstBuilder, Comment, CommentKind, + ast::{Expression, Statement}, }; use super::Utf8ToUtf16; @@ -207,7 +207,7 @@ mod test { #[test] fn char_lengths() { macro_rules! assert_utf8_bytes_eq { - ($c:expr, $bytes:expr) => {{ + ($c:expr_2021, $bytes:expr_2021) => {{ let mut buffer = [0; 4]; let bytes = $c.encode_utf8(&mut buffer).as_bytes(); assert!($bytes == bytes); diff --git a/crates/oxc_ast_macros/src/ast.rs b/crates/oxc_ast_macros/src/ast.rs index 3e76e510901c6f..7cc0a8857a4bc1 100644 --- a/crates/oxc_ast_macros/src/ast.rs +++ b/crates/oxc_ast_macros/src/ast.rs @@ -1,6 +1,6 @@ use proc_macro2::TokenStream; use quote::quote; -use syn::{punctuated::Punctuated, token::Comma, Attribute, Fields, Ident, Item, ItemEnum}; +use syn::{Attribute, Fields, Ident, Item, ItemEnum, punctuated::Punctuated, token::Comma}; use crate::generated::get_trait_crate_and_generics; @@ -63,7 +63,7 @@ fn assert_generated_derives(attrs: &[Attribute]) -> TokenStream { } #[inline] -fn parse_attr(attr: &Attribute) -> impl Iterator { +fn parse_attr(attr: &Attribute) -> impl Iterator + use<> { attr.parse_args_with(Punctuated::::parse_terminated) .expect("`#[generate_derive]` only accepts traits as single segment paths. Found an invalid argument.") .into_iter() diff --git a/crates/oxc_ast_macros/src/lib.rs b/crates/oxc_ast_macros/src/lib.rs index b1a813a1674f59..7eb63752eac37e 100644 --- a/crates/oxc_ast_macros/src/lib.rs +++ b/crates/oxc_ast_macros/src/lib.rs @@ -1,6 +1,6 @@ use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, Item}; +use syn::{Item, parse_macro_input}; mod ast; mod generated; diff --git a/crates/oxc_cfg/src/lib.rs b/crates/oxc_cfg/src/lib.rs index 8f39d55709b84d..a74fe431eb1f1d 100644 --- a/crates/oxc_cfg/src/lib.rs +++ b/crates/oxc_cfg/src/lib.rs @@ -9,8 +9,8 @@ use itertools::Itertools; use nonmax::NonMaxU32; use oxc_index::{Idx, IndexVec}; use petgraph::{ - visit::{Control, DfsEvent, EdgeRef}, Direction, + visit::{Control, DfsEvent, EdgeRef}, }; pub mod graph { diff --git a/crates/oxc_cfg/src/visit.rs b/crates/oxc_cfg/src/visit.rs index 883269f5285ec5..8febb35acae585 100644 --- a/crates/oxc_cfg/src/visit.rs +++ b/crates/oxc_cfg/src/visit.rs @@ -1,8 +1,8 @@ use std::hash::Hash; use petgraph::{ - visit::{ControlFlow, DfsEvent, EdgeRef, IntoNeighbors, Time, VisitMap, Visitable}, Direction, Graph, + visit::{ControlFlow, DfsEvent, EdgeRef, IntoNeighbors, Time, VisitMap, Visitable}, }; use rustc_hash::FxHashSet; @@ -66,10 +66,10 @@ where /// Return if the expression is a break value, execute the provided statement /// if it is a prune value. macro_rules! try_control { - ($e:expr, $p:stmt) => { + ($e:expr_2021, $p:stmt) => { try_control!($e, $p, ()); }; - ($e:expr, $p:stmt, $q:stmt) => { + ($e:expr_2021, $p:stmt, $q:stmt) => { match $e { x => { #[allow(clippy::redundant_else, clippy::allow_attributes)] diff --git a/crates/oxc_codegen/examples/sourcemap.rs b/crates/oxc_codegen/examples/sourcemap.rs index 7ec667225f508e..802a21d9357b54 100644 --- a/crates/oxc_codegen/examples/sourcemap.rs +++ b/crates/oxc_codegen/examples/sourcemap.rs @@ -1,7 +1,7 @@ #![expect(clippy::print_stdout)] use std::{env, path::Path}; -use base64::{prelude::BASE64_STANDARD, Engine}; +use base64::{Engine, prelude::BASE64_STANDARD}; use oxc_allocator::Allocator; use oxc_codegen::{CodeGenerator, CodegenOptions, CodegenReturn}; use oxc_parser::Parser; diff --git a/crates/oxc_codegen/src/binary_expr_visitor.rs b/crates/oxc_codegen/src/binary_expr_visitor.rs index 26770069002f42..3813939f7e1b9d 100644 --- a/crates/oxc_codegen/src/binary_expr_visitor.rs +++ b/crates/oxc_codegen/src/binary_expr_visitor.rs @@ -9,7 +9,7 @@ use oxc_syntax::{ precedence::{GetPrecedence, Precedence}, }; -use crate::{gen::GenExpr, Codegen, Context, Operator}; +use crate::{Codegen, Context, Operator, r#gen::GenExpr}; #[derive(Clone, Copy)] pub enum Binaryish<'a> { @@ -67,7 +67,7 @@ fn print_binary_operator(op: BinaryOperator, p: &mut Codegen) { } impl BinaryishOperator { - fn gen(self, p: &mut Codegen) { + fn r#gen(self, p: &mut Codegen) { match self { Self::Binary(op) => print_binary_operator(op, p), Self::Logical(op) => p.print_str(op.as_str()), @@ -220,7 +220,7 @@ impl<'a> BinaryExpressionVisitor<'a> { pub fn visit_right_and_finish(&self, p: &mut Codegen) { p.print_soft_space(); - self.operator.gen(p); + self.operator.r#gen(p); p.print_soft_space(); self.e.right().gen_expr(p, self.right_precedence, self.ctx); if self.wrap { diff --git a/crates/oxc_codegen/src/code_buffer.rs b/crates/oxc_codegen/src/code_buffer.rs index a3e91ef13c2f0b..2f7fbe2887829a 100644 --- a/crates/oxc_codegen/src/code_buffer.rs +++ b/crates/oxc_codegen/src/code_buffer.rs @@ -161,11 +161,7 @@ impl CodeBuffer { #[must_use = "Peeking is pointless if the peeked char isn't used"] pub fn peek_nth_byte_back(&self, n: usize) -> Option { let len = self.len(); - if n < len { - Some(self.buf[len - 1 - n]) - } else { - None - } + if n < len { Some(self.buf[len - 1 - n]) } else { None } } /// Peek the last byte from the end of the buffer. diff --git a/crates/oxc_codegen/src/context.rs b/crates/oxc_codegen/src/context.rs index 10a310f6f8bd07..f8c3a17e392839 100644 --- a/crates/oxc_codegen/src/context.rs +++ b/crates/oxc_codegen/src/context.rs @@ -43,10 +43,6 @@ impl Context { #[inline] fn and(self, flag: Self, set: bool) -> Self { - if set { - self | flag - } else { - self - flag - } + if set { self | flag } else { self - flag } } } diff --git a/crates/oxc_codegen/src/gen.rs b/crates/oxc_codegen/src/gen.rs index f5c82000fac53e..5f2b6557744731 100644 --- a/crates/oxc_codegen/src/gen.rs +++ b/crates/oxc_codegen/src/gen.rs @@ -9,19 +9,19 @@ use oxc_syntax::{ }; use crate::{ - binary_expr_visitor::{BinaryExpressionVisitor, Binaryish, BinaryishOperator}, Codegen, Context, Operator, + binary_expr_visitor::{BinaryExpressionVisitor, Binaryish, BinaryishOperator}, }; /// Generate source code for an AST node. pub trait Gen: GetSpan { /// Generate code for an AST node. - fn gen(&self, p: &mut Codegen, ctx: Context); + fn r#gen(&self, p: &mut Codegen, ctx: Context); /// Generate code for an AST node. Alias for `gen`. #[inline] fn print(&self, p: &mut Codegen, ctx: Context) { - self.gen(p, ctx); + self.r#gen(p, ctx); } } @@ -38,7 +38,7 @@ pub trait GenExpr: GetSpan { } impl Gen for Program<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.is_jsx = self.source_type.is_jsx(); if let Some(hashbang) = &self.hashbang { @@ -57,7 +57,7 @@ impl Gen for Program<'_> { } impl Gen for Hashbang<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_str("#!"); p.print_str(self.value.as_str()); p.print_hard_newline(); @@ -65,7 +65,7 @@ impl Gen for Hashbang<'_> { } impl Gen for Directive<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); // A Use Strict Directive may not contain an EscapeSequence or LineContinuation. @@ -100,7 +100,7 @@ impl Gen for Directive<'_> { } impl Gen for Statement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::BlockStatement(stmt) => { p.print_statement_comments(stmt.span.start); @@ -251,7 +251,7 @@ impl Gen for Statement<'_> { } impl Gen for ExpressionStatement<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.start_of_stmt = p.code_len(); @@ -265,7 +265,7 @@ impl Gen for ExpressionStatement<'_> { } impl Gen for IfStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); print_if(self, p, ctx); @@ -352,7 +352,7 @@ fn wrap_to_avoid_ambiguous_else(stmt: &Statement) -> bool { } impl Gen for BlockStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_indent(); p.print_block_statement(self, ctx); p.print_soft_newline(); @@ -360,7 +360,7 @@ impl Gen for BlockStatement<'_> { } impl Gen for ForStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -392,7 +392,7 @@ impl Gen for ForStatement<'_> { } impl Gen for ForInStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -411,7 +411,7 @@ impl Gen for ForInStatement<'_> { } impl Gen for ForOfStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -433,7 +433,7 @@ impl Gen for ForOfStatement<'_> { } impl Gen for ForStatementInit<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::VariableDeclaration(var) => var.print(p, ctx), _ => self.to_expression().print_expr(p, Precedence::Lowest, ctx), @@ -442,7 +442,7 @@ impl Gen for ForStatementInit<'_> { } impl Gen for ForStatementLeft<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { ForStatementLeft::VariableDeclaration(var) => var.print(p, ctx), ForStatementLeft::AssignmentTargetIdentifier(identifier) => { @@ -457,7 +457,7 @@ impl Gen for ForStatementLeft<'_> { } impl Gen for WhileStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -471,7 +471,7 @@ impl Gen for WhileStatement<'_> { } impl Gen for DoWhileStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -502,7 +502,7 @@ impl Gen for DoWhileStatement<'_> { } impl Gen for EmptyStatement { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_semicolon(); @@ -511,7 +511,7 @@ impl Gen for EmptyStatement { } impl Gen for ContinueStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -525,7 +525,7 @@ impl Gen for ContinueStatement<'_> { } impl Gen for BreakStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -539,7 +539,7 @@ impl Gen for BreakStatement<'_> { } impl Gen for SwitchStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -560,7 +560,7 @@ impl Gen for SwitchStatement<'_> { } impl Gen for SwitchCase<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_semicolon_if_needed(); p.print_indent(); p.add_source_mapping(self.span); @@ -590,7 +590,7 @@ impl Gen for SwitchCase<'_> { } impl Gen for ReturnStatement<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -604,7 +604,7 @@ impl Gen for ReturnStatement<'_> { } impl Gen for LabeledStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if !p.options.minify && (p.indent > 0 || p.print_next_indent_as_space) { p.add_source_mapping(self.span); p.print_indent(); @@ -617,7 +617,7 @@ impl Gen for LabeledStatement<'_> { } impl Gen for TryStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -647,7 +647,7 @@ impl Gen for TryStatement<'_> { } impl Gen for ThrowStatement<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -659,7 +659,7 @@ impl Gen for ThrowStatement<'_> { } impl Gen for WithStatement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -672,7 +672,7 @@ impl Gen for WithStatement<'_> { } impl Gen for DebuggerStatement { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -682,7 +682,7 @@ impl Gen for DebuggerStatement { } impl Gen for VariableDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_space_before_identifier(); if self.declare { @@ -713,7 +713,7 @@ impl Gen for VariableDeclaration<'_> { } impl Gen for VariableDeclarator<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.id.kind.print(p, ctx); if self.definite { p.print_ascii_byte(b'!'); @@ -737,7 +737,7 @@ impl Gen for VariableDeclarator<'_> { } impl Gen for Function<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let n = p.code_len(); let wrap = self.is_expression() && (p.start_of_stmt == n || p.start_of_default_export == n); p.print_annotation_comments(self.span.start); @@ -787,7 +787,7 @@ impl Gen for Function<'_> { } impl Gen for FunctionBody<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let span_end = self.span.end; let comments_at_end = if p.print_comments && span_end > 0 { p.get_statement_comments(span_end - 1) @@ -817,7 +817,7 @@ impl Gen for FunctionBody<'_> { } impl Gen for FormalParameter<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { for decorator in &self.decorators { decorator.print(p, ctx); p.print_soft_space(); @@ -837,7 +837,7 @@ impl Gen for FormalParameter<'_> { } impl Gen for FormalParameters<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_list(&self.items, ctx); if let Some(rest) = &self.rest { if !self.items.is_empty() { @@ -850,7 +850,7 @@ impl Gen for FormalParameters<'_> { } impl Gen for ImportDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_space_before_identifier(); @@ -963,7 +963,7 @@ impl Gen for ImportDeclaration<'_> { } impl Gen for WithClause<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); self.attributes_keyword.print(p, ctx); p.print_soft_space(); @@ -980,7 +980,7 @@ impl Gen for WithClause<'_> { } impl Gen for ImportAttribute<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { match &self.key { ImportAttributeKey::Identifier(identifier) => { p.print_str(identifier.name.as_str()); @@ -996,7 +996,7 @@ impl Gen for ImportAttribute<'_> { } impl Gen for ExportNamedDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); @@ -1065,7 +1065,7 @@ impl Gen for ExportNamedDeclaration<'_> { } impl Gen for TSExportAssignment<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_indent(); p.print_str("export = "); self.expression.print_expr(p, Precedence::Lowest, ctx); @@ -1074,7 +1074,7 @@ impl Gen for TSExportAssignment<'_> { } impl Gen for TSNamespaceExportDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_indent(); p.print_str("export as namespace "); self.id.print(p, ctx); @@ -1094,7 +1094,7 @@ fn get_module_export_name<'a>( } impl Gen for ExportSpecifier<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.export_kind.is_type() { p.print_str("type "); } @@ -1109,7 +1109,7 @@ impl Gen for ExportSpecifier<'_> { } impl Gen for ModuleExportName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::IdentifierName(ident) => ident.print(p, ctx), Self::IdentifierReference(ident) => ident.print(p, ctx), @@ -1119,7 +1119,7 @@ impl Gen for ModuleExportName<'_> { } impl Gen for ExportAllDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_str("export"); @@ -1151,7 +1151,7 @@ impl Gen for ExportAllDeclaration<'_> { } impl Gen for ExportDefaultDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_indent(); p.print_str("export default "); @@ -1159,7 +1159,7 @@ impl Gen for ExportDefaultDeclaration<'_> { } } impl Gen for ExportDefaultDeclarationKind<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::FunctionDeclaration(fun) => { fun.print(p, ctx); @@ -1235,7 +1235,7 @@ impl GenExpr for ParenthesizedExpression<'_> { } impl Gen for IdentifierReference<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { let name = p.get_identifier_reference_name(self); p.print_space_before_identifier(); p.add_source_mapping_for_name(self.span, name); @@ -1244,7 +1244,7 @@ impl Gen for IdentifierReference<'_> { } impl Gen for IdentifierName<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_space_before_identifier(); p.add_source_mapping(self.span); p.print_str(self.name.as_str()); @@ -1252,7 +1252,7 @@ impl Gen for IdentifierName<'_> { } impl Gen for BindingIdentifier<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { let name = p.get_binding_identifier_name(self); p.print_space_before_identifier(); p.add_source_mapping_for_name(self.span, name); @@ -1261,7 +1261,7 @@ impl Gen for BindingIdentifier<'_> { } impl Gen for LabelIdentifier<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_space_before_identifier(); p.add_source_mapping_for_name(self.span, &self.name); p.print_str(self.name.as_str()); @@ -1269,7 +1269,7 @@ impl Gen for LabelIdentifier<'_> { } impl Gen for BooleanLiteral { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_space_before_identifier(); p.print_str(self.as_str()); @@ -1277,7 +1277,7 @@ impl Gen for BooleanLiteral { } impl Gen for NullLiteral { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_space_before_identifier(); p.add_source_mapping(self.span); p.print_str("null"); @@ -1342,7 +1342,7 @@ impl GenExpr for BigIntLiteral<'_> { } impl Gen for RegExpLiteral<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); let last = p.last_byte(); let pattern_text = self.regex.pattern.source_text(p.source_text); @@ -1361,13 +1361,13 @@ impl Gen for RegExpLiteral<'_> { } impl Gen for StringLiteral<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_string_literal(self, true); } } impl Gen for ThisExpression { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_space_before_identifier(); p.add_source_mapping(self.span); p.print_str("this"); @@ -1474,7 +1474,7 @@ impl GenExpr for CallExpression<'_> { } impl Gen for Argument<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::SpreadElement(elem) => elem.print(p, ctx), _ => self.to_expression().print_expr(p, Precedence::Comma, Context::empty()), @@ -1483,7 +1483,7 @@ impl Gen for Argument<'_> { } impl Gen for ArrayExpressionElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::SpreadElement(elem) => elem.print(p, ctx), Self::Elision(_span) => {} @@ -1493,7 +1493,7 @@ impl Gen for ArrayExpressionElement<'_> { } impl Gen for SpreadElement<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_ellipsis(); self.argument.print_expr(p, Precedence::Comma, Context::empty()); @@ -1501,7 +1501,7 @@ impl Gen for SpreadElement<'_> { } impl Gen for ArrayExpression<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let is_multi_line = self.elements.len() > 2; p.add_source_mapping(self.span); p.print_ascii_byte(b'['); @@ -1571,7 +1571,7 @@ impl GenExpr for ObjectExpression<'_> { } impl Gen for ObjectPropertyKind<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::ObjectProperty(prop) => prop.print(p, ctx), Self::SpreadProperty(elem) => elem.print(p, ctx), @@ -1580,7 +1580,7 @@ impl Gen for ObjectPropertyKind<'_> { } impl Gen for ObjectProperty<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if let Expression::FunctionExpression(func) = &self.value { p.add_source_mapping(self.span); let is_accessor = match &self.kind { @@ -1669,7 +1669,7 @@ impl Gen for ObjectProperty<'_> { } impl Gen for PropertyKey<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::StaticIdentifier(ident) => ident.print(p, ctx), Self::PrivateIdentifier(ident) => ident.print(p, ctx), @@ -1886,7 +1886,7 @@ impl GenExpr for AssignmentExpression<'_> { } impl Gen for AssignmentTarget<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { match_simple_assignment_target!(Self) => { self.to_simple_assignment_target().print_expr( @@ -1919,7 +1919,7 @@ impl GenExpr for SimpleAssignmentTarget<'_> { } impl Gen for AssignmentTargetPattern<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::ArrayAssignmentTarget(target) => target.print(p, ctx), Self::ObjectAssignmentTarget(target) => target.print(p, ctx), @@ -1928,7 +1928,7 @@ impl Gen for AssignmentTargetPattern<'_> { } impl Gen for ArrayAssignmentTarget<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_ascii_byte(b'['); for (index, item) in self.elements.iter().enumerate() { @@ -1956,7 +1956,7 @@ impl Gen for ArrayAssignmentTarget<'_> { } impl Gen for ObjectAssignmentTarget<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_ascii_byte(b'{'); p.print_list(&self.properties, ctx); @@ -1973,7 +1973,7 @@ impl Gen for ObjectAssignmentTarget<'_> { } impl Gen for AssignmentTargetMaybeDefault<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { match_assignment_target!(Self) => self.to_assignment_target().print(p, ctx), Self::AssignmentTargetWithDefault(target) => target.print(p, ctx), @@ -1982,7 +1982,7 @@ impl Gen for AssignmentTargetMaybeDefault<'_> { } impl Gen for AssignmentTargetWithDefault<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.binding.print(p, ctx); p.print_soft_space(); p.print_equal(); @@ -1992,7 +1992,7 @@ impl Gen for AssignmentTargetWithDefault<'_> { } impl Gen for AssignmentTargetProperty<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::AssignmentTargetPropertyIdentifier(ident) => ident.print(p, ctx), Self::AssignmentTargetPropertyProperty(prop) => prop.print(p, ctx), @@ -2001,7 +2001,7 @@ impl Gen for AssignmentTargetProperty<'_> { } impl Gen for AssignmentTargetPropertyIdentifier<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let ident_name = p.get_identifier_reference_name(&self.binding); if ident_name == self.binding.name.as_str() { self.binding.print(p, ctx); @@ -2022,7 +2022,7 @@ impl Gen for AssignmentTargetPropertyIdentifier<'_> { } impl Gen for AssignmentTargetPropertyProperty<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let omit_key = if p.options.minify { let key_name = match &self.name { PropertyKey::StaticIdentifier(ident) => Some(&ident.name), @@ -2063,7 +2063,7 @@ impl Gen for AssignmentTargetPropertyProperty<'_> { } impl Gen for AssignmentTargetRest<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_ellipsis(); self.target.print(p, ctx); } @@ -2133,7 +2133,7 @@ impl GenExpr for ImportExpression<'_> { } impl Gen for TemplateLiteral<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_ascii_byte(b'`'); let mut expressions = self.expressions.iter(); @@ -2153,7 +2153,7 @@ impl Gen for TemplateLiteral<'_> { } impl Gen for TaggedTemplateExpression<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); self.tag.print_expr(p, Precedence::Postfix, Context::empty()); if let Some(type_parameters) = &self.type_parameters { @@ -2164,7 +2164,7 @@ impl Gen for TaggedTemplateExpression<'_> { } impl Gen for Super { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_space_before_identifier(); p.add_source_mapping(self.span); p.print_str("super"); @@ -2295,7 +2295,7 @@ impl GenExpr for TSTypeAssertion<'_> { } impl Gen for MetaProperty<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_space_before_identifier(); p.add_source_mapping(self.span); self.meta.print(p, ctx); @@ -2305,7 +2305,7 @@ impl Gen for MetaProperty<'_> { } impl Gen for Class<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); let n = p.code_len(); let wrap = self.is_expression() && (p.start_of_stmt == n || p.start_of_default_export == n); @@ -2349,7 +2349,7 @@ impl Gen for Class<'_> { } impl Gen for ClassBody<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_curly_braces(self.span, self.body.is_empty(), |p| { for item in &self.body { p.print_semicolon_if_needed(); @@ -2362,7 +2362,7 @@ impl Gen for ClassBody<'_> { } impl Gen for ClassElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::StaticBlock(elem) => { elem.print(p, ctx); @@ -2389,14 +2389,14 @@ impl Gen for ClassElement<'_> { } impl Gen for JSXIdentifier<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping_for_name(self.span, &self.name); p.print_str(self.name.as_str()); } } impl Gen for JSXMemberExpressionObject<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::IdentifierReference(ident) => ident.print(p, ctx), Self::MemberExpression(member_expr) => member_expr.print(p, ctx), @@ -2406,7 +2406,7 @@ impl Gen for JSXMemberExpressionObject<'_> { } impl Gen for JSXMemberExpression<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.object.print(p, ctx); p.print_ascii_byte(b'.'); self.property.print(p, ctx); @@ -2414,7 +2414,7 @@ impl Gen for JSXMemberExpression<'_> { } impl Gen for JSXElementName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::Identifier(identifier) => identifier.print(p, ctx), Self::IdentifierReference(identifier) => identifier.print(p, ctx), @@ -2426,7 +2426,7 @@ impl Gen for JSXElementName<'_> { } impl Gen for JSXNamespacedName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.namespace.print(p, ctx); p.print_colon(); self.property.print(p, ctx); @@ -2434,7 +2434,7 @@ impl Gen for JSXNamespacedName<'_> { } impl Gen for JSXAttributeName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::Identifier(ident) => ident.print(p, ctx), Self::NamespacedName(namespaced_name) => namespaced_name.print(p, ctx), @@ -2443,7 +2443,7 @@ impl Gen for JSXAttributeName<'_> { } impl Gen for JSXAttribute<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.name.print(p, ctx); if let Some(value) = &self.value { p.print_equal(); @@ -2453,11 +2453,11 @@ impl Gen for JSXAttribute<'_> { } impl Gen for JSXEmptyExpression { - fn gen(&self, _: &mut Codegen, _ctx: Context) {} + fn r#gen(&self, _: &mut Codegen, _ctx: Context) {} } impl Gen for JSXExpression<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::EmptyExpression(expr) => expr.print(p, ctx), _ => p.print_expression(self.to_expression()), @@ -2466,7 +2466,7 @@ impl Gen for JSXExpression<'_> { } impl Gen for JSXExpressionContainer<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_ascii_byte(b'{'); self.expression.print(p, ctx); p.print_ascii_byte(b'}'); @@ -2474,7 +2474,7 @@ impl Gen for JSXExpressionContainer<'_> { } impl Gen for JSXAttributeValue<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::Fragment(fragment) => fragment.print(p, ctx), Self::Element(el) => el.print(p, ctx), @@ -2490,7 +2490,7 @@ impl Gen for JSXAttributeValue<'_> { } impl Gen for JSXSpreadAttribute<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_str("{..."); self.argument.print_expr(p, Precedence::Comma, Context::empty()); p.print_ascii_byte(b'}'); @@ -2498,7 +2498,7 @@ impl Gen for JSXSpreadAttribute<'_> { } impl Gen for JSXAttributeItem<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::Attribute(attr) => attr.print(p, ctx), Self::SpreadAttribute(spread_attr) => spread_attr.print(p, ctx), @@ -2507,7 +2507,7 @@ impl Gen for JSXAttributeItem<'_> { } impl Gen for JSXOpeningElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_ascii_byte(b'<'); self.name.print(p, ctx); @@ -2531,7 +2531,7 @@ impl Gen for JSXOpeningElement<'_> { } impl Gen for JSXClosingElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_str(" { } impl Gen for JSXElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.opening_element.print(p, ctx); for child in &self.children { child.print(p, ctx); @@ -2552,35 +2552,35 @@ impl Gen for JSXElement<'_> { } impl Gen for JSXOpeningFragment { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_str("<>"); } } impl Gen for JSXClosingFragment { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_str(""); } } impl Gen for JSXText<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping(self.span); p.print_str(self.value.as_str()); } } impl Gen for JSXSpreadChild<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.print_str("..."); p.print_expression(&self.expression); } } impl Gen for JSXChild<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::Fragment(fragment) => fragment.print(p, ctx), Self::Element(el) => el.print(p, ctx), @@ -2592,7 +2592,7 @@ impl Gen for JSXChild<'_> { } impl Gen for JSXFragment<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.opening_fragment.print(p, ctx); for child in &self.children { child.print(p, ctx); @@ -2602,7 +2602,7 @@ impl Gen for JSXFragment<'_> { } impl Gen for StaticBlock<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_str("static"); p.print_soft_space(); @@ -2617,7 +2617,7 @@ impl Gen for StaticBlock<'_> { } impl Gen for MethodDefinition<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); for decorator in &self.decorators { decorator.print(p, ctx); @@ -2702,7 +2702,7 @@ impl Gen for MethodDefinition<'_> { } impl Gen for PropertyDefinition<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); for decorator in &self.decorators { decorator.print(p, ctx); @@ -2759,7 +2759,7 @@ impl Gen for PropertyDefinition<'_> { } impl Gen for AccessorProperty<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); for decorator in &self.decorators { decorator.print(p, ctx); @@ -2809,7 +2809,7 @@ impl Gen for AccessorProperty<'_> { } impl Gen for PrivateIdentifier<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { p.add_source_mapping_for_name(self.span, &self.name); p.print_ascii_byte(b'#'); p.print_str(self.name.as_str()); @@ -2817,7 +2817,7 @@ impl Gen for PrivateIdentifier<'_> { } impl Gen for BindingPattern<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.kind.print(p, ctx); if self.optional { p.print_str("?"); @@ -2831,7 +2831,7 @@ impl Gen for BindingPattern<'_> { } impl Gen for BindingPatternKind<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { BindingPatternKind::BindingIdentifier(ident) => ident.print(p, ctx), BindingPatternKind::ObjectPattern(pattern) => pattern.print(p, ctx), @@ -2842,7 +2842,7 @@ impl Gen for BindingPatternKind<'_> { } impl Gen for ObjectPattern<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_ascii_byte(b'{'); if !self.is_empty() { @@ -2864,7 +2864,7 @@ impl Gen for ObjectPattern<'_> { } impl Gen for BindingProperty<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); if self.computed { p.print_ascii_byte(b'['); @@ -2906,7 +2906,7 @@ impl Gen for BindingProperty<'_> { } impl Gen for BindingRestElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_ellipsis(); self.argument.print(p, ctx); @@ -2914,7 +2914,7 @@ impl Gen for BindingRestElement<'_> { } impl Gen for ArrayPattern<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.add_source_mapping(self.span); p.print_ascii_byte(b'['); for (index, item) in self.elements.iter().enumerate() { @@ -2939,7 +2939,7 @@ impl Gen for ArrayPattern<'_> { } impl Gen for AssignmentPattern<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.left.print(p, ctx); p.print_soft_space(); p.print_equal(); @@ -2949,7 +2949,7 @@ impl Gen for AssignmentPattern<'_> { } impl Gen for Decorator<'_> { - fn gen(&self, p: &mut Codegen, _ctx: Context) { + fn r#gen(&self, p: &mut Codegen, _ctx: Context) { fn need_wrap(expr: &Expression) -> bool { match expr { // "@foo" @@ -2976,7 +2976,7 @@ impl Gen for Decorator<'_> { } impl Gen for TSClassImplements<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.expression.print(p, ctx); if let Some(type_parameters) = self.type_parameters.as_ref() { type_parameters.print(p, ctx); @@ -2985,7 +2985,7 @@ impl Gen for TSClassImplements<'_> { } impl Gen for TSTypeParameterDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let is_multi_line = self.params.len() >= 2; p.print_ascii_byte(b'<'); if is_multi_line { @@ -3017,13 +3017,13 @@ impl Gen for TSTypeParameterDeclaration<'_> { } impl Gen for TSTypeAnnotation<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.type_annotation.print(p, ctx); } } impl Gen for TSType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let ctx = ctx.with_typescript(); match self { Self::TSFunctionType(ty) => ty.print(p, ctx), @@ -3068,14 +3068,14 @@ impl Gen for TSType<'_> { } impl Gen for TSArrayType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.element_type.print(p, ctx); p.print_str("[]"); } } impl Gen for TSTupleType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("["); p.print_list(&self.element_types, ctx); p.print_str("]"); @@ -3083,7 +3083,7 @@ impl Gen for TSTupleType<'_> { } impl Gen for TSUnionType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.types.len() == 1 { self.types[0].print(p, ctx); return; @@ -3100,7 +3100,7 @@ impl Gen for TSUnionType<'_> { } impl Gen for TSParenthesizedType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_ascii_byte(b'('); self.type_annotation.print(p, ctx); p.print_ascii_byte(b')'); @@ -3108,7 +3108,7 @@ impl Gen for TSParenthesizedType<'_> { } impl Gen for TSIntersectionType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.types.len() == 1 { self.types[0].print(p, ctx); return; @@ -3125,7 +3125,7 @@ impl Gen for TSIntersectionType<'_> { } impl Gen for TSConditionalType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.check_type.print(p, ctx); p.print_str(" extends "); self.extends_type.print(p, ctx); @@ -3137,14 +3137,14 @@ impl Gen for TSConditionalType<'_> { } impl Gen for TSInferType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("infer "); self.type_parameter.print(p, ctx); } } impl Gen for TSIndexedAccessType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.object_type.print(p, ctx); p.print_str("["); self.index_type.print(p, ctx); @@ -3153,7 +3153,7 @@ impl Gen for TSIndexedAccessType<'_> { } impl Gen for TSMappedType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("{"); p.print_soft_space(); match self.readonly { @@ -3207,7 +3207,7 @@ impl Gen for TSMappedType<'_> { } impl Gen for TSQualifiedName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.left.print(p, ctx); p.print_str("."); self.right.print(p, ctx); @@ -3215,7 +3215,7 @@ impl Gen for TSQualifiedName<'_> { } impl Gen for TSTypeOperator<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self.operator { TSTypeOperatorOperator::Keyof => { p.print_str("keyof "); @@ -3232,7 +3232,7 @@ impl Gen for TSTypeOperator<'_> { } impl Gen for TSTypePredicate<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.asserts { p.print_str("asserts "); } @@ -3252,7 +3252,7 @@ impl Gen for TSTypePredicate<'_> { } impl Gen for TSTypeReference<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.type_name.print(p, ctx); if let Some(type_parameters) = &self.type_parameters { type_parameters.print(p, ctx); @@ -3261,7 +3261,7 @@ impl Gen for TSTypeReference<'_> { } impl Gen for JSDocNullableType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.postfix { self.type_annotation.print(p, ctx); p.print_str("?"); @@ -3273,7 +3273,7 @@ impl Gen for JSDocNullableType<'_> { } impl Gen for JSDocNonNullableType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.postfix { self.type_annotation.print(p, ctx); p.print_str("!"); @@ -3285,7 +3285,7 @@ impl Gen for JSDocNonNullableType<'_> { } impl Gen for TSTemplateLiteralType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("`"); for (index, item) in self.quasis.iter().enumerate() { if index != 0 { @@ -3302,7 +3302,7 @@ impl Gen for TSTemplateLiteralType<'_> { } impl Gen for TSTypeLiteral<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_curly_braces(self.span, self.members.is_empty(), |p| { for item in &self.members { p.print_leading_comments(item.span().start); @@ -3318,7 +3318,7 @@ impl Gen for TSTypeLiteral<'_> { } impl Gen for TSTypeName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::IdentifierReference(ident) => { ident.print(p, ctx); @@ -3333,7 +3333,7 @@ impl Gen for TSTypeName<'_> { } impl Gen for TSLiteral<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::BooleanLiteral(decl) => decl.print(p, ctx), Self::NumericLiteral(decl) => decl.print_expr(p, Precedence::Lowest, ctx), @@ -3346,7 +3346,7 @@ impl Gen for TSLiteral<'_> { } impl Gen for TSTypeParameter<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.r#const { p.print_str("const "); } @@ -3363,7 +3363,7 @@ impl Gen for TSTypeParameter<'_> { } impl Gen for TSFunctionType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if let Some(type_parameters) = &self.type_parameters { type_parameters.print(p, ctx); } @@ -3385,7 +3385,7 @@ impl Gen for TSFunctionType<'_> { } impl Gen for TSThisParameter<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("this"); if let Some(type_annotation) = &self.type_annotation { p.print_str(": "); @@ -3395,7 +3395,7 @@ impl Gen for TSThisParameter<'_> { } impl Gen for TSSignature<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::TSIndexSignature(signature) => signature.print(p, ctx), Self::TSPropertySignature(signature) => signature.r#gen(p, ctx), @@ -3486,7 +3486,7 @@ impl Gen for TSSignature<'_> { } impl Gen for TSPropertySignature<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.readonly { p.print_str("readonly "); } @@ -3522,7 +3522,7 @@ impl Gen for TSPropertySignature<'_> { } impl Gen for TSTypeQuery<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("typeof "); self.expr_name.print(p, ctx); if let Some(type_params) = &self.type_parameters { @@ -3532,7 +3532,7 @@ impl Gen for TSTypeQuery<'_> { } impl Gen for TSTypeQueryExprName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { match_ts_type_name!(Self) => self.to_ts_type_name().print(p, ctx), Self::TSImportType(decl) => decl.print(p, ctx), @@ -3541,7 +3541,7 @@ impl Gen for TSTypeQueryExprName<'_> { } impl Gen for TSImportType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.is_type_of { p.print_str("typeof "); } @@ -3563,7 +3563,7 @@ impl Gen for TSImportType<'_> { } impl Gen for TSImportAttributes<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_ascii_byte(b'{'); p.print_soft_space(); self.attributes_keyword.print(p, ctx); @@ -3580,7 +3580,7 @@ impl Gen for TSImportAttributes<'_> { } impl Gen for TSImportAttribute<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.name.print(p, ctx); p.print_str(": "); self.value.print_expr(p, Precedence::Member, ctx); @@ -3588,7 +3588,7 @@ impl Gen for TSImportAttribute<'_> { } impl Gen for TSImportAttributeName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { TSImportAttributeName::Identifier(ident) => ident.print(p, ctx), TSImportAttributeName::StringLiteral(literal) => { @@ -3599,7 +3599,7 @@ impl Gen for TSImportAttributeName<'_> { } impl Gen for TSTypeParameterInstantiation<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("<"); p.print_list(&self.params, ctx); p.print_str(">"); @@ -3607,7 +3607,7 @@ impl Gen for TSTypeParameterInstantiation<'_> { } impl Gen for TSIndexSignature<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.readonly { p.print_str("readonly "); } @@ -3629,7 +3629,7 @@ impl Gen for TSIndexSignature<'_> { } impl Gen for TSTupleElement<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { match_ts_type!(TSTupleElement) => self.to_ts_type().print(p, ctx), TSTupleElement::TSOptionalType(ts_type) => { @@ -3645,7 +3645,7 @@ impl Gen for TSTupleElement<'_> { } impl Gen for TSNamedTupleMember<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.label.print(p, ctx); if self.optional { p.print_str("?"); @@ -3657,7 +3657,7 @@ impl Gen for TSNamedTupleMember<'_> { } impl Gen for TSModuleDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.declare { p.print_str("declare "); } @@ -3694,7 +3694,7 @@ impl Gen for TSModuleDeclaration<'_> { } impl Gen for TSModuleDeclarationName<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::Identifier(ident) => ident.print(p, ctx), Self::StringLiteral(s) => p.print_string_literal(s, false), @@ -3703,7 +3703,7 @@ impl Gen for TSModuleDeclarationName<'_> { } impl Gen for TSModuleBlock<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { let is_empty = self.directives.is_empty() && self.body.is_empty(); p.print_curly_braces(self.span, is_empty, |p| { for directive in &self.directives { @@ -3719,7 +3719,7 @@ impl Gen for TSModuleBlock<'_> { } impl Gen for TSTypeAliasDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.declare { p.print_str("declare "); } @@ -3737,7 +3737,7 @@ impl Gen for TSTypeAliasDeclaration<'_> { } impl Gen for TSInterfaceDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("interface"); p.print_hard_space(); self.id.print(p, ctx); @@ -3764,7 +3764,7 @@ impl Gen for TSInterfaceDeclaration<'_> { } impl Gen for TSInterfaceHeritage<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { self.expression.print_expr(p, Precedence::Call, ctx); if let Some(type_parameters) = &self.type_parameters { type_parameters.print(p, ctx); @@ -3773,7 +3773,7 @@ impl Gen for TSInterfaceHeritage<'_> { } impl Gen for TSEnumDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_indent(); if self.declare { p.print_str("declare "); @@ -3798,7 +3798,7 @@ impl Gen for TSEnumDeclaration<'_> { } impl Gen for TSEnumMember<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match &self.id { TSEnumMemberName::Identifier(decl) => decl.print(p, ctx), TSEnumMemberName::String(decl) => p.print_string_literal(decl, false), @@ -3813,7 +3813,7 @@ impl Gen for TSEnumMember<'_> { } impl Gen for TSConstructorType<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { if self.r#abstract { p.print_str("abstract "); } @@ -3832,7 +3832,7 @@ impl Gen for TSConstructorType<'_> { } impl Gen for TSImportEqualsDeclaration<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { p.print_str("import "); self.id.print(p, ctx); p.print_str(" = "); @@ -3841,7 +3841,7 @@ impl Gen for TSImportEqualsDeclaration<'_> { } impl Gen for TSModuleReference<'_> { - fn gen(&self, p: &mut Codegen, ctx: Context) { + fn r#gen(&self, p: &mut Codegen, ctx: Context) { match self { Self::ExternalModuleReference(decl) => { p.print_str("require("); diff --git a/crates/oxc_codegen/src/lib.rs b/crates/oxc_codegen/src/lib.rs index 6f4ed6802c002e..2c3a0d1c978495 100644 --- a/crates/oxc_codegen/src/lib.rs +++ b/crates/oxc_codegen/src/lib.rs @@ -8,7 +8,7 @@ mod binary_expr_visitor; mod code_buffer; mod comment; mod context; -mod gen; +mod r#gen; mod operator; mod options; mod sourcemap_builder; @@ -21,9 +21,9 @@ use oxc_ast::ast::{ }; use oxc_data_structures::stack::Stack; use oxc_semantic::SymbolTable; -use oxc_span::{GetSpan, Span, SPAN}; +use oxc_span::{GetSpan, SPAN, Span}; use oxc_syntax::{ - identifier::{is_identifier_part, is_identifier_part_ascii, LS, PS}, + identifier::{LS, PS, is_identifier_part, is_identifier_part_ascii}, operator::{BinaryOperator, UnaryOperator, UpdateOperator}, precedence::Precedence, }; @@ -34,7 +34,7 @@ use crate::{ }; pub use crate::{ context::Context, - gen::{Gen, GenExpr}, + r#gen::{Gen, GenExpr}, options::{CodegenOptions, LegalComment}, }; diff --git a/crates/oxc_data_structures/src/stack/common.rs b/crates/oxc_data_structures/src/stack/common.rs index e4e4ee4470e977..92b554a5552c41 100644 --- a/crates/oxc_data_structures/src/stack/common.rs +++ b/crates/oxc_data_structures/src/stack/common.rs @@ -1,5 +1,3 @@ -#![expect(clippy::unnecessary_safety_comment)] - use std::{ alloc::{self, Layout}, mem::{align_of, size_of}, @@ -34,12 +32,14 @@ pub trait StackCommon: StackCapacity { /// * `capacity_bytes` must not exceed `Self::MAX_CAPACITY_BYTES`. #[inline] unsafe fn allocate(capacity_bytes: usize) -> (NonNull, NonNull) { - // SAFETY: Caller guarantees `capacity_bytes` satisfies requirements - let layout = Self::layout_for(capacity_bytes); - let (start, end) = allocate(layout); + unsafe { + // SAFETY: Caller guarantees `capacity_bytes` satisfies requirements + let layout = Self::layout_for(capacity_bytes); + let (start, end) = allocate(layout); - // SAFETY: `layout_for` produces a layout with `T`'s alignment, so pointers are aligned for `T` - (start.cast::(), end.cast::()) + // SAFETY: `layout_for` produces a layout with `T`'s alignment, so pointers are aligned for `T` + (start.cast::(), end.cast::()) + } } /// Grow allocation. @@ -55,28 +55,30 @@ pub trait StackCommon: StackCapacity { /// Stack must have already allocated. i.e. `start` is not a dangling pointer. #[inline] unsafe fn grow(&mut self) { - // Grow allocation. - // SAFETY: Caller guarantees stack has allocated. - // `start` and `end` are boundaries of that allocation (`alloc` and `grow` ensure that). - // So `old_start_ptr` and `old_layout` accurately describe the current allocation. - // `grow` creates new allocation with byte size double what it currently is, or caps it - // at `MAX_CAPACITY_BYTES`. - // Old capacity in bytes was a multiple of `size_of::()`, so double that must be too. - // `MAX_CAPACITY_BYTES` is also a multiple of `size_of::()`. - // So new capacity in bytes must be a multiple of `size_of::()`. - // `MAX_CAPACITY_BYTES <= isize::MAX`. - let old_start_ptr = self.start().cast::(); - let old_layout = Self::layout_for(self.capacity_bytes()); - let (start, end, current) = grow(old_start_ptr, old_layout, Self::MAX_CAPACITY_BYTES); + unsafe { + // Grow allocation. + // SAFETY: Caller guarantees stack has allocated. + // `start` and `end` are boundaries of that allocation (`alloc` and `grow` ensure that). + // So `old_start_ptr` and `old_layout` accurately describe the current allocation. + // `grow` creates new allocation with byte size double what it currently is, or caps it + // at `MAX_CAPACITY_BYTES`. + // Old capacity in bytes was a multiple of `size_of::()`, so double that must be too. + // `MAX_CAPACITY_BYTES` is also a multiple of `size_of::()`. + // So new capacity in bytes must be a multiple of `size_of::()`. + // `MAX_CAPACITY_BYTES <= isize::MAX`. + let old_start_ptr = self.start().cast::(); + let old_layout = Self::layout_for(self.capacity_bytes()); + let (start, end, current) = grow(old_start_ptr, old_layout, Self::MAX_CAPACITY_BYTES); - // Update pointers. - // SAFETY: `start`, `end`, and `current` are all `NonNull` - just casting them. - // All pointers returned from `grow` are aligned for `T`. - // Old capacity and new capacity in bytes are both multiples of `size_of::()`, - // so distances `end - start` and `current - start` are both multiples of `size_of::()`. - self.set_start(start.cast::()); - self.set_end(end.cast::()); - self.set_cursor(current.cast::()); + // Update pointers. + // SAFETY: `start`, `end`, and `current` are all `NonNull` - just casting them. + // All pointers returned from `grow` are aligned for `T`. + // Old capacity and new capacity in bytes are both multiples of `size_of::()`, + // so distances `end - start` and `current - start` are both multiples of `size_of::()`. + self.set_start(start.cast::()); + self.set_end(end.cast::()); + self.set_cursor(current.cast::()); + } } /// Deallocate stack memory. @@ -88,11 +90,13 @@ pub trait StackCommon: StackCapacity { /// Stack must have already allocated. i.e. `start` is not a dangling pointer. #[inline] unsafe fn deallocate(&self) { - // SAFETY: Caller guarantees stack is allocated. - // `start` and `end` are boundaries of that allocation (`allocate` and `grow` ensure that). - // So `start` and `layout` accurately describe the current allocation. - let layout = Self::layout_for(self.capacity_bytes()); - alloc::dealloc(self.start().as_ptr().cast::(), layout); + unsafe { + // SAFETY: Caller guarantees stack is allocated. + // `start` and `end` are boundaries of that allocation (`allocate` and `grow` ensure that). + // So `start` and `layout` accurately describe the current allocation. + let layout = Self::layout_for(self.capacity_bytes()); + alloc::dealloc(self.start().as_ptr().cast::(), layout); + } } /// Drop contents of stack. @@ -105,9 +109,11 @@ pub trait StackCommon: StackCapacity { /// * Stack must contain `self.len()` initialized entries, starting at `self.start()`. #[inline] unsafe fn drop_contents(&self) { - // Drop contents. Next line copied from `std`'s `Vec`. - // SAFETY: Caller guarantees stack contains `len` initialized entries, starting at `start`. - ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.start().as_ptr(), self.len())); + unsafe { + // Drop contents. Next line copied from `std`'s `Vec`. + // SAFETY: Caller guarantees stack contains `len` initialized entries, starting at `start`. + ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.start().as_ptr(), self.len())); + } } /// Get layout for allocation of `capacity_bytes` bytes. @@ -118,19 +124,21 @@ pub trait StackCommon: StackCapacity { /// * `capacity_bytes` must not exceed `Self::MAX_CAPACITY_BYTES`. #[inline] unsafe fn layout_for(capacity_bytes: usize) -> Layout { - // `capacity_bytes` must not be 0 because cannot make 0-size allocations. - debug_assert!(capacity_bytes > 0); - // `capacity_bytes` must be a multiple of `size_of::()` so that `cursor == end` - // checks in `push` methods accurately detects when full to capacity - debug_assert!(capacity_bytes % size_of::() == 0); - // `capacity_bytes` must not exceed `Self::MAX_CAPACITY_BYTES` to prevent creating an allocation - // of illegal size - debug_assert!(capacity_bytes <= Self::MAX_CAPACITY_BYTES); + unsafe { + // `capacity_bytes` must not be 0 because cannot make 0-size allocations. + debug_assert!(capacity_bytes > 0); + // `capacity_bytes` must be a multiple of `size_of::()` so that `cursor == end` + // checks in `push` methods accurately detects when full to capacity + debug_assert!(capacity_bytes % size_of::() == 0); + // `capacity_bytes` must not exceed `Self::MAX_CAPACITY_BYTES` to prevent creating an allocation + // of illegal size + debug_assert!(capacity_bytes <= Self::MAX_CAPACITY_BYTES); - // SAFETY: `align_of::()` trivially satisfies alignment requirements. - // Caller guarantees `capacity_bytes <= MAX_CAPACITY_BYTES`. - // `MAX_CAPACITY_BYTES` takes into account the rounding-up by alignment requirement. - Layout::from_size_align_unchecked(capacity_bytes, align_of::()) + // SAFETY: `align_of::()` trivially satisfies alignment requirements. + // Caller guarantees `capacity_bytes <= MAX_CAPACITY_BYTES`. + // `MAX_CAPACITY_BYTES` takes into account the rounding-up by alignment requirement. + Layout::from_size_align_unchecked(capacity_bytes, align_of::()) + } } /// Get offset of `cursor` in number of `T`s. @@ -215,18 +223,20 @@ pub trait StackCommon: StackCapacity { /// `layout` must have non-zero size. #[inline] unsafe fn allocate(layout: Layout) -> (/* start */ NonNull, /* end */ NonNull) { - // SAFETY: Caller guarantees `layout` has non-zero-size - let ptr = alloc::alloc(layout); - if ptr.is_null() { - alloc::handle_alloc_error(layout); - } + unsafe { + // SAFETY: Caller guarantees `layout` has non-zero-size + let ptr = alloc::alloc(layout); + if ptr.is_null() { + alloc::handle_alloc_error(layout); + } - // SAFETY: We checked `ptr` is non-null - let start = NonNull::new_unchecked(ptr); - // SAFETY: We allocated `layout.size()` bytes, so `end` is end of allocation - let end = start.add(layout.size()); + // SAFETY: We checked `ptr` is non-null + let start = NonNull::new_unchecked(ptr); + // SAFETY: We allocated `layout.size()` bytes, so `end` is end of allocation + let end = start.add(layout.size()); - (start, end) + (start, end) + } } /// Grow existing allocation. @@ -242,54 +252,59 @@ unsafe fn grow( old_layout: Layout, max_capacity_bytes: usize, ) -> (/* start */ NonNull, /* end */ NonNull, /* current */ NonNull) { - // Get new capacity - // Capacity in bytes cannot be larger than `isize::MAX`, so `* 2` cannot overflow - let old_capacity_bytes = old_layout.size(); - let mut new_capacity_bytes = old_capacity_bytes * 2; - if new_capacity_bytes > max_capacity_bytes { - assert!(old_capacity_bytes < max_capacity_bytes, "Cannot grow beyond `Self::MAX_CAPACITY`"); - new_capacity_bytes = max_capacity_bytes; - } - debug_assert!(new_capacity_bytes > old_capacity_bytes); + unsafe { + // Get new capacity + // Capacity in bytes cannot be larger than `isize::MAX`, so `* 2` cannot overflow + let old_capacity_bytes = old_layout.size(); + let mut new_capacity_bytes = old_capacity_bytes * 2; + if new_capacity_bytes > max_capacity_bytes { + assert!( + old_capacity_bytes < max_capacity_bytes, + "Cannot grow beyond `Self::MAX_CAPACITY`" + ); + new_capacity_bytes = max_capacity_bytes; + } + debug_assert!(new_capacity_bytes > old_capacity_bytes); - // Reallocate. - // SAFETY: Caller guarantees `old_start` and `old_layout` describe an existing allocation. - // Caller guarantees that `max_capacity_bytes <= isize::MAX`. - // `new_capacity_bytes` is capped above at `max_capacity_bytes`, so is a legal allocation size. + // Reallocate. + // SAFETY: Caller guarantees `old_start` and `old_layout` describe an existing allocation. + // Caller guarantees that `max_capacity_bytes <= isize::MAX`. + // `new_capacity_bytes` is capped above at `max_capacity_bytes`, so is a legal allocation size. - // `start` and `end` are boundaries of that allocation (`alloc` and `grow` ensure that). - // So `start` and `old_layout` accurately describe the current allocation. - // `old_capacity_bytes` was a multiple of `size_of::()`, so double that must be too. - // `MAX_CAPACITY_BYTES` is also a multiple of `size_of::()`. - // So `new_capacity_bytes` must be a multiple of `size_of::()`. - // `new_capacity_bytes` is `<= MAX_CAPACITY_BYTES`, so is a legal allocation size. - // `layout_for` produces a layout with `T`'s alignment, so `new_ptr` is aligned for `T`. - let new_start = unsafe { - let old_ptr = old_start.as_ptr(); - let new_ptr = alloc::realloc(old_ptr, old_layout, new_capacity_bytes); - if new_ptr.is_null() { - let new_layout = - Layout::from_size_align_unchecked(old_capacity_bytes, old_layout.align()); - alloc::handle_alloc_error(new_layout); - } - NonNull::new_unchecked(new_ptr) - }; + // `start` and `end` are boundaries of that allocation (`alloc` and `grow` ensure that). + // So `start` and `old_layout` accurately describe the current allocation. + // `old_capacity_bytes` was a multiple of `size_of::()`, so double that must be too. + // `MAX_CAPACITY_BYTES` is also a multiple of `size_of::()`. + // So `new_capacity_bytes` must be a multiple of `size_of::()`. + // `new_capacity_bytes` is `<= MAX_CAPACITY_BYTES`, so is a legal allocation size. + // `layout_for` produces a layout with `T`'s alignment, so `new_ptr` is aligned for `T`. + let new_start = unsafe { + let old_ptr = old_start.as_ptr(); + let new_ptr = alloc::realloc(old_ptr, old_layout, new_capacity_bytes); + if new_ptr.is_null() { + let new_layout = + Layout::from_size_align_unchecked(old_capacity_bytes, old_layout.align()); + alloc::handle_alloc_error(new_layout); + } + NonNull::new_unchecked(new_ptr) + }; - // Update pointers. - // - // Stack was full to capacity, so new last index after push is the old capacity. - // i.e. `new_cursor - new_start == old_end - old_start`. - // Note: All pointers need to be updated even if allocation grew in place. - // From docs for `GlobalAlloc::realloc`: - // "Any access to the old `ptr` is Undefined Behavior, even if the allocation remained in-place." - // - // `end` changes whatever happens, so always need to be updated. - // `cursor` needs to be derived from `start` to make `offset_from` valid, so also needs updating. - // - // SAFETY: We checked that `new_ptr` is non-null. - // `old_capacity_bytes < new_capacity_bytes` (ensured above), so `new_cursor` must be in bounds. - let new_end = new_start.add(new_capacity_bytes); - let new_cursor = new_start.add(old_capacity_bytes); + // Update pointers. + // + // Stack was full to capacity, so new last index after push is the old capacity. + // i.e. `new_cursor - new_start == old_end - old_start`. + // Note: All pointers need to be updated even if allocation grew in place. + // From docs for `GlobalAlloc::realloc`: + // "Any access to the old `ptr` is Undefined Behavior, even if the allocation remained in-place." + // + // `end` changes whatever happens, so always need to be updated. + // `cursor` needs to be derived from `start` to make `offset_from` valid, so also needs updating. + // + // SAFETY: We checked that `new_ptr` is non-null. + // `old_capacity_bytes < new_capacity_bytes` (ensured above), so `new_cursor` must be in bounds. + let new_end = new_start.add(new_capacity_bytes); + let new_cursor = new_start.add(old_capacity_bytes); - (new_start, new_end, new_cursor) + (new_start, new_end, new_cursor) + } } diff --git a/crates/oxc_data_structures/src/stack/non_empty.rs b/crates/oxc_data_structures/src/stack/non_empty.rs index ad2acdce31b311..1b2af47f078635 100644 --- a/crates/oxc_data_structures/src/stack/non_empty.rs +++ b/crates/oxc_data_structures/src/stack/non_empty.rs @@ -1,5 +1,3 @@ -#![expect(clippy::unnecessary_safety_comment)] - use std::{ mem::size_of, ops::{Deref, DerefMut}, @@ -180,13 +178,15 @@ impl NonEmptyStack { /// * `capacity` must not exceed [`Self::MAX_CAPACITY`]. #[inline] pub unsafe fn with_capacity_unchecked(capacity: usize, initial_value: T) -> Self { - debug_assert!(capacity > 0); - debug_assert!(capacity <= Self::MAX_CAPACITY); - // Cannot overflow if `capacity <= MAX_CAPACITY` - let capacity_bytes = capacity * size_of::(); - // SAFETY: Safety invariants which caller must satisfy guarantee that `capacity_bytes` - // satisfies requirements - Self::new_with_capacity_bytes_unchecked(capacity_bytes, initial_value) + unsafe { + debug_assert!(capacity > 0); + debug_assert!(capacity <= Self::MAX_CAPACITY); + // Cannot overflow if `capacity <= MAX_CAPACITY` + let capacity_bytes = capacity * size_of::(); + // SAFETY: Safety invariants which caller must satisfy guarantee that `capacity_bytes` + // satisfies requirements + Self::new_with_capacity_bytes_unchecked(capacity_bytes, initial_value) + } } /// Create new [`NonEmptyStack`] with provided capacity in bytes, and initial value `initial_value`, @@ -201,19 +201,21 @@ impl NonEmptyStack { /// * `capacity_bytes` must not exceed [`Self::MAX_CAPACITY_BYTES`]. #[inline] unsafe fn new_with_capacity_bytes_unchecked(capacity_bytes: usize, initial_value: T) -> Self { - // ZSTs are not supported for simplicity - assert!(size_of::() > 0, "Zero sized types are not supported"); + unsafe { + // ZSTs are not supported for simplicity + assert!(size_of::() > 0, "Zero sized types are not supported"); - // SAFETY: Caller guarantees `capacity_bytes` satisfies requirements - let (start, end) = Self::allocate(capacity_bytes); + // SAFETY: Caller guarantees `capacity_bytes` satisfies requirements + let (start, end) = Self::allocate(capacity_bytes); - // Write initial value to start of allocation. - // SAFETY: Allocation was created with alignment of `T`, and with capacity for at least 1 entry, - // so `start` is valid for writing a `T`. - start.as_ptr().write(initial_value); + // Write initial value to start of allocation. + // SAFETY: Allocation was created with alignment of `T`, and with capacity for at least 1 entry, + // so `start` is valid for writing a `T`. + start.as_ptr().write(initial_value); - // `cursor` is positioned at start i.e. pointing at initial value - Self { cursor: start, start, end } + // `cursor` is positioned at start i.e. pointing at initial value + Self { cursor: start, start, end } + } } /// Get reference to first value on stack. @@ -287,14 +289,16 @@ impl NonEmptyStack { #[cold] #[inline(never)] unsafe fn push_slow(&mut self, value: T) { - // Grow allocation. - // SAFETY: Stack is always allocated. - self.grow(); - - // Write value. - // SAFETY: We just allocated additional capacity, so `self.cursor` is in bounds. - // `self.cursor` is aligned for `T`. - unsafe { self.cursor.as_ptr().write(value) } + unsafe { + // Grow allocation. + // SAFETY: Stack is always allocated. + self.grow(); + + // Write value. + // SAFETY: We just allocated additional capacity, so `self.cursor` is in bounds. + // `self.cursor` is aligned for `T`. + unsafe { self.cursor.as_ptr().write(value) } + } } /// Pop value from stack. @@ -331,15 +335,17 @@ impl NonEmptyStack { /// * Stack must have at least 2 entries, so that after pop, it still has at least 1. #[inline] pub unsafe fn pop_unchecked(&mut self) -> T { - debug_assert!(self.cursor > self.start); - debug_assert!(self.cursor < self.end); - // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, - // and points to a valid initialized `T` - let value = self.cursor.read(); - // SAFETY: Caller guarantees there's at least 2 entries on stack, so subtracting 1 - // cannot be out of bounds - self.cursor = self.cursor.sub(1); - value + unsafe { + debug_assert!(self.cursor > self.start); + debug_assert!(self.cursor < self.end); + // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, + // and points to a valid initialized `T` + let value = self.cursor.read(); + // SAFETY: Caller guarantees there's at least 2 entries on stack, so subtracting 1 + // cannot be out of bounds + self.cursor = self.cursor.sub(1); + value + } } /// Get number of values on stack. @@ -417,7 +423,7 @@ mod tests { use super::*; macro_rules! assert_len_cap_last { - ($stack:ident, $len:expr, $capacity:expr, $last:expr) => { + ($stack:ident, $len:expr_2021, $capacity:expr_2021, $last:expr_2021) => { assert_eq!($stack.len(), $len); assert_eq!($stack.capacity(), $capacity); assert_eq!($stack.last(), $last); diff --git a/crates/oxc_data_structures/src/stack/sparse.rs b/crates/oxc_data_structures/src/stack/sparse.rs index 4bb07dc6f76da0..8b2011875b73ed 100644 --- a/crates/oxc_data_structures/src/stack/sparse.rs +++ b/crates/oxc_data_structures/src/stack/sparse.rs @@ -95,11 +95,12 @@ impl SparseStack { /// Push an entry to the stack. #[inline] pub fn push(&mut self, value: Option) { - let has_value = if let Some(value) = value { - self.values.push(value); - true - } else { - false + let has_value = match value { + Some(value) => { + self.values.push(value); + true + } + _ => false, }; self.has_values.push(has_value); } diff --git a/crates/oxc_data_structures/src/stack/standard.rs b/crates/oxc_data_structures/src/stack/standard.rs index 115e59eeb5d746..2d0d16745a231c 100644 --- a/crates/oxc_data_structures/src/stack/standard.rs +++ b/crates/oxc_data_structures/src/stack/standard.rs @@ -1,5 +1,3 @@ -#![expect(clippy::unnecessary_safety_comment)] - use std::{ mem::size_of, ops::{Deref, DerefMut}, @@ -154,13 +152,15 @@ impl Stack { /// * `capacity` must not exceed [`Self::MAX_CAPACITY`]. #[inline] pub unsafe fn with_capacity_unchecked(capacity: usize) -> Self { - debug_assert!(capacity > 0); - debug_assert!(capacity <= Self::MAX_CAPACITY); - // Cannot overflow if `capacity <= MAX_CAPACITY` - let capacity_bytes = capacity * size_of::(); - // SAFETY: Safety invariants which caller must satisfy guarantee that `capacity_bytes` - // satisfies requirements - Self::new_with_capacity_bytes_unchecked(capacity_bytes) + unsafe { + debug_assert!(capacity > 0); + debug_assert!(capacity <= Self::MAX_CAPACITY); + // Cannot overflow if `capacity <= MAX_CAPACITY` + let capacity_bytes = capacity * size_of::(); + // SAFETY: Safety invariants which caller must satisfy guarantee that `capacity_bytes` + // satisfies requirements + Self::new_with_capacity_bytes_unchecked(capacity_bytes) + } } /// Create new `Stack` with provided capacity in bytes, without checks. @@ -174,14 +174,16 @@ impl Stack { /// * `capacity_bytes` must not exceed [`Self::MAX_CAPACITY_BYTES`]. #[inline] unsafe fn new_with_capacity_bytes_unchecked(capacity_bytes: usize) -> Self { - // ZSTs are not supported for simplicity - assert!(size_of::() > 0, "Zero sized types are not supported"); + unsafe { + // ZSTs are not supported for simplicity + assert!(size_of::() > 0, "Zero sized types are not supported"); - // SAFETY: Caller guarantees `capacity_bytes` satisfies requirements - let (start, end) = Self::allocate(capacity_bytes); + // SAFETY: Caller guarantees `capacity_bytes` satisfies requirements + let (start, end) = Self::allocate(capacity_bytes); - // `cursor` is positioned at start - Self { cursor: start, start, end } + // `cursor` is positioned at start + Self { cursor: start, start, end } + } } // Note: There is no need to implement `first` and `first_mut` methods. @@ -209,13 +211,15 @@ impl Stack { /// * Stack must not be empty. #[inline] pub unsafe fn last_unchecked(&self) -> &T { - debug_assert!(self.end > self.start); - debug_assert!(self.cursor > self.start); - debug_assert!(self.cursor <= self.end); - // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, - // and `self.current.sub(1)` points to a valid initialized `T`, if stack is not empty. - // Caller guarantees stack is not empty. - self.cursor.sub(1).as_ref() + unsafe { + debug_assert!(self.end > self.start); + debug_assert!(self.cursor > self.start); + debug_assert!(self.cursor <= self.end); + // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, + // and `self.current.sub(1)` points to a valid initialized `T`, if stack is not empty. + // Caller guarantees stack is not empty. + self.cursor.sub(1).as_ref() + } } /// Get mutable reference to last value on stack. @@ -237,13 +241,15 @@ impl Stack { /// * Stack must not be empty. #[inline] pub unsafe fn last_unchecked_mut(&mut self) -> &mut T { - debug_assert!(self.end > self.start); - debug_assert!(self.cursor > self.start); - debug_assert!(self.cursor <= self.end); - // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, - // and `self.current.sub(1)` points to a valid initialized `T`, if stack is not empty. - // Caller guarantees stack is not empty. - self.cursor.sub(1).as_mut() + unsafe { + debug_assert!(self.end > self.start); + debug_assert!(self.cursor > self.start); + debug_assert!(self.cursor <= self.end); + // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, + // and `self.current.sub(1)` points to a valid initialized `T`, if stack is not empty. + // Caller guarantees stack is not empty. + self.cursor.sub(1).as_mut() + } } /// Push value to stack. @@ -279,26 +285,28 @@ impl Stack { #[cold] #[inline(never)] unsafe fn push_slow(&mut self, value: T) { - #[expect(clippy::if_not_else)] - if self.end != self.start { - // Stack was already allocated. Grow capacity. - // SAFETY: Checked above that is already allocated. - self.grow(); - } else { - // Stack was not allocated yet. - // SAFETY: `DEFAULT_CAPACITY_BYTES` satisfies requirements. - let (start, end) = Self::allocate(Self::DEFAULT_CAPACITY_BYTES); - self.start = start; - self.cursor = start; - self.end = end; - } + unsafe { + #[expect(clippy::if_not_else)] + if self.end != self.start { + // Stack was already allocated. Grow capacity. + // SAFETY: Checked above that is already allocated. + self.grow(); + } else { + // Stack was not allocated yet. + // SAFETY: `DEFAULT_CAPACITY_BYTES` satisfies requirements. + let (start, end) = Self::allocate(Self::DEFAULT_CAPACITY_BYTES); + self.start = start; + self.cursor = start; + self.end = end; + } - // Write value + increment cursor. - // SAFETY: We just allocated additional capacity, so `self.cursor` is in bounds. - // `self.cursor` is aligned for `T`. - unsafe { self.cursor.as_ptr().write(value) } - // SAFETY: Cursor is not at end, so advancing by a `T` cannot be out of bounds - self.cursor = unsafe { self.cursor.add(1) }; + // Write value + increment cursor. + // SAFETY: We just allocated additional capacity, so `self.cursor` is in bounds. + // `self.cursor` is aligned for `T`. + unsafe { self.cursor.as_ptr().write(value) } + // SAFETY: Cursor is not at end, so advancing by a `T` cannot be out of bounds + self.cursor = unsafe { self.cursor.add(1) }; + } } /// Pop value from stack. @@ -320,15 +328,17 @@ impl Stack { /// * Stack must not be empty. #[inline] pub unsafe fn pop_unchecked(&mut self) -> T { - debug_assert!(self.end > self.start); - debug_assert!(self.cursor > self.start); - debug_assert!(self.cursor <= self.end); - // SAFETY: Caller guarantees stack is not empty, so subtracting 1 cannot be out of bounds - self.cursor = self.cursor.sub(1); - // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, - // and points to a valid initialized `T`, if stack is not empty. - // Caller guarantees stack was not empty. - self.cursor.read() + unsafe { + debug_assert!(self.end > self.start); + debug_assert!(self.cursor > self.start); + debug_assert!(self.cursor <= self.end); + // SAFETY: Caller guarantees stack is not empty, so subtracting 1 cannot be out of bounds + self.cursor = self.cursor.sub(1); + // SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`, + // and points to a valid initialized `T`, if stack is not empty. + // Caller guarantees stack was not empty. + self.cursor.read() + } } /// Get number of entries on stack. @@ -402,7 +412,7 @@ mod tests { use super::*; macro_rules! assert_len_cap_last { - ($stack:ident, $len:expr, $capacity:expr, $last:expr) => { + ($stack:ident, $len:expr_2021, $capacity:expr_2021, $last:expr_2021) => { assert_eq!($stack.len(), $len); assert_eq!($stack.capacity(), $capacity); assert_eq!($stack.last(), $last); diff --git a/crates/oxc_diagnostics/src/service.rs b/crates/oxc_diagnostics/src/service.rs index 4f32c22de30b55..a89f596a27dd03 100644 --- a/crates/oxc_diagnostics/src/service.rs +++ b/crates/oxc_diagnostics/src/service.rs @@ -1,14 +1,14 @@ use std::{ io::{ErrorKind, Write}, path::{Path, PathBuf}, - sync::{mpsc, Arc}, + sync::{Arc, mpsc}, }; use cow_utils::CowUtils; use crate::{ - reporter::{DiagnosticReporter, DiagnosticResult}, Error, NamedSource, OxcDiagnostic, Severity, + reporter::{DiagnosticReporter, DiagnosticResult}, }; pub type DiagnosticTuple = (PathBuf, Vec); diff --git a/crates/oxc_ecmascript/src/array_join.rs b/crates/oxc_ecmascript/src/array_join.rs index d1e9675b7eedeb..266467b25ea981 100644 --- a/crates/oxc_ecmascript/src/array_join.rs +++ b/crates/oxc_ecmascript/src/array_join.rs @@ -1,6 +1,6 @@ use oxc_ast::ast::*; -use crate::{is_global_reference::IsGlobalReference, ToJsString}; +use crate::{ToJsString, is_global_reference::IsGlobalReference}; pub trait ArrayJoin<'a> { /// `Array.prototype.join ( separator )` diff --git a/crates/oxc_ecmascript/src/constant_evaluation/mod.rs b/crates/oxc_ecmascript/src/constant_evaluation/mod.rs index 0a650b580197f4..80f0eb9c4b828e 100644 --- a/crates/oxc_ecmascript/src/constant_evaluation/mod.rs +++ b/crates/oxc_ecmascript/src/constant_evaluation/mod.rs @@ -4,11 +4,11 @@ use num_bigint::BigInt; use num_traits::{FromPrimitive, ToPrimitive, Zero}; use equality_comparison::{abstract_equality_comparison, strict_equality_comparison}; -use oxc_ast::{ast::*, AstBuilder}; +use oxc_ast::{AstBuilder, ast::*}; use crate::{ - is_global_reference::IsGlobalReference, side_effects::MayHaveSideEffects, - to_numeric::ToNumeric, ToBigInt, ToBoolean, ToInt32, ToJsString, ToNumber, + ToBigInt, ToBoolean, ToInt32, ToJsString, ToNumber, is_global_reference::IsGlobalReference, + side_effects::MayHaveSideEffects, to_numeric::ToNumeric, }; mod equality_comparison; diff --git a/crates/oxc_ecmascript/src/constant_evaluation/value.rs b/crates/oxc_ecmascript/src/constant_evaluation/value.rs index 9cca9549294066..449ec8013e7e07 100644 --- a/crates/oxc_ecmascript/src/constant_evaluation/value.rs +++ b/crates/oxc_ecmascript/src/constant_evaluation/value.rs @@ -4,7 +4,7 @@ use std::borrow::Cow; use num_bigint::BigInt; use num_traits::Zero; -use crate::{is_global_reference::IsGlobalReference, ToBoolean, ToJsString, ToNumber}; +use crate::{ToBoolean, ToJsString, ToNumber, is_global_reference::IsGlobalReference}; #[derive(Debug, PartialEq)] pub enum ConstantValue<'a> { diff --git a/crates/oxc_ecmascript/src/constant_evaluation/value_type.rs b/crates/oxc_ecmascript/src/constant_evaluation/value_type.rs index c77de9fceb9647..39d19d7883f236 100644 --- a/crates/oxc_ecmascript/src/constant_evaluation/value_type.rs +++ b/crates/oxc_ecmascript/src/constant_evaluation/value_type.rs @@ -196,11 +196,7 @@ impl DetermineValueType for AssignmentExpression<'_> { AssignmentOperator::Assign => self.right.value_type(is_global_reference), AssignmentOperator::Addition => { let right = self.right.value_type(is_global_reference); - if right.is_string() { - ValueType::String - } else { - ValueType::Undetermined - } + if right.is_string() { ValueType::String } else { ValueType::Undetermined } } AssignmentOperator::Subtraction | AssignmentOperator::Multiplication diff --git a/crates/oxc_ecmascript/src/string_char_code_at.rs b/crates/oxc_ecmascript/src/string_char_code_at.rs index 2a7d59f13d6478..5f0b6407dad724 100644 --- a/crates/oxc_ecmascript/src/string_char_code_at.rs +++ b/crates/oxc_ecmascript/src/string_char_code_at.rs @@ -1,4 +1,4 @@ -use crate::{string_char_at::StringCharAtResult, StringCharAt}; +use crate::{StringCharAt, string_char_at::StringCharAtResult}; pub trait StringCharCodeAt { /// `String.prototype.charCodeAt ( pos )` diff --git a/crates/oxc_ecmascript/src/to_big_int.rs b/crates/oxc_ecmascript/src/to_big_int.rs index 1809a1a603525f..78dba040a42052 100644 --- a/crates/oxc_ecmascript/src/to_big_int.rs +++ b/crates/oxc_ecmascript/src/to_big_int.rs @@ -4,7 +4,7 @@ use num_traits::{One, Zero}; use oxc_ast::ast::{BigIntLiteral, Expression}; use oxc_syntax::operator::UnaryOperator; -use crate::{is_global_reference::IsGlobalReference, StringToBigInt, ToBoolean, ToJsString}; +use crate::{StringToBigInt, ToBoolean, ToJsString, is_global_reference::IsGlobalReference}; /// `ToBigInt` /// @@ -33,21 +33,19 @@ impl<'a> ToBigInt<'a> for Expression<'a> { Some(BigInt::zero()) } } - Expression::UnaryExpression(unary_expr) => { - match unary_expr.operator { - UnaryOperator::LogicalNot => self - .to_boolean(is_global_reference) - .map(|boolean| if boolean { BigInt::one() } else { BigInt::zero() }), - UnaryOperator::UnaryNegation => { - unary_expr.argument.to_big_int(is_global_reference).map(std::ops::Neg::neg) - } - UnaryOperator::BitwiseNot => { - unary_expr.argument.to_big_int(is_global_reference).map(std::ops::Not::not) - } - UnaryOperator::UnaryPlus => unary_expr.argument.to_big_int(is_global_reference), - _ => None, + Expression::UnaryExpression(unary_expr) => match unary_expr.operator { + UnaryOperator::LogicalNot => self + .to_boolean(is_global_reference) + .map(|boolean| if boolean { BigInt::one() } else { BigInt::zero() }), + UnaryOperator::UnaryNegation => { + unary_expr.argument.to_big_int(is_global_reference).map(std::ops::Neg::neg) } - } + UnaryOperator::BitwiseNot => { + unary_expr.argument.to_big_int(is_global_reference).map(std::ops::Not::not) + } + UnaryOperator::UnaryPlus => unary_expr.argument.to_big_int(is_global_reference), + _ => None, + }, Expression::StringLiteral(string_literal) => { string_literal.value.as_str().string_to_big_int() } diff --git a/crates/oxc_ecmascript/src/to_boolean.rs b/crates/oxc_ecmascript/src/to_boolean.rs index 45e5f8ba2215af..a9024ed3c2eba0 100644 --- a/crates/oxc_ecmascript/src/to_boolean.rs +++ b/crates/oxc_ecmascript/src/to_boolean.rs @@ -36,13 +36,9 @@ impl<'a> ToBoolean<'a> for Expression<'a> { | Expression::ObjectExpression(_) => Some(true), Expression::NullLiteral(_) => Some(false), Expression::BooleanLiteral(boolean_literal) => Some(boolean_literal.value), - Expression::NumericLiteral(lit) => Some({ - if lit.value.is_nan() { - false - } else { - lit.value != 0.0 - } - }), + Expression::NumericLiteral(lit) => { + Some(if lit.value.is_nan() { false } else { lit.value != 0.0 }) + } Expression::BigIntLiteral(big_int_literal) => Some(!big_int_literal.is_zero()), Expression::StringLiteral(string_literal) => Some(!string_literal.value.is_empty()), Expression::TemplateLiteral(template_literal) => { diff --git a/crates/oxc_ecmascript/src/to_int_32.rs b/crates/oxc_ecmascript/src/to_int_32.rs index 0a55b6c9a438ca..f5948505204ea4 100644 --- a/crates/oxc_ecmascript/src/to_int_32.rs +++ b/crates/oxc_ecmascript/src/to_int_32.rs @@ -39,19 +39,11 @@ impl ToInt32 for f64 { let d64 = number.to_bits(); let significand = d64 & SIGNIFICAND_MASK; - if is_denormal(number) { - significand - } else { - significand + HIDDEN_BIT - } + if is_denormal(number) { significand } else { significand + HIDDEN_BIT } } fn sign(number: f64) -> i64 { - if (number.to_bits() & SIGN_MASK) == 0 { - 1 - } else { - -1 - } + if (number.to_bits() & SIGN_MASK) == 0 { 1 } else { -1 } } let number = *self; diff --git a/crates/oxc_ecmascript/src/to_number.rs b/crates/oxc_ecmascript/src/to_number.rs index 003fe18c1ca326..8c528c4f8cbd0d 100644 --- a/crates/oxc_ecmascript/src/to_number.rs +++ b/crates/oxc_ecmascript/src/to_number.rs @@ -71,11 +71,7 @@ impl<'a> ToNumber<'a> for Expression<'a> { // If the array has at least 2 elements, `ToPrimitive` returns a string containing // `,` which is not included in `StringNumericLiteral` // So `ToNumber` returns `NaN` - if non_spread_element_count >= 2 { - Some(f64::NAN) - } else { - None - } + if non_spread_element_count >= 2 { Some(f64::NAN) } else { None } } _ => None, } diff --git a/crates/oxc_ecmascript/src/to_string.rs b/crates/oxc_ecmascript/src/to_string.rs index 39ec42dba8ddfc..85d9d65a9fbe75 100644 --- a/crates/oxc_ecmascript/src/to_string.rs +++ b/crates/oxc_ecmascript/src/to_string.rs @@ -5,11 +5,11 @@ use oxc_ast::ast::*; use oxc_syntax::operator::UnaryOperator; use crate::{ + ToBoolean, array_join::ArrayJoin, constant_evaluation::{DetermineValueType, ValueType}, is_global_reference::IsGlobalReference, to_primitive::maybe_object_with_to_primitive_related_properties_overridden, - ToBoolean, }; /// `ToString` diff --git a/crates/oxc_isolated_declarations/src/class.rs b/crates/oxc_isolated_declarations/src/class.rs index 17d4792d1e0986..5cc3d39110bcc3 100644 --- a/crates/oxc_isolated_declarations/src/class.rs +++ b/crates/oxc_isolated_declarations/src/class.rs @@ -1,16 +1,16 @@ use std::borrow::Cow; use oxc_allocator::{Box, CloneIn}; -use oxc_ast::{ast::*, NONE}; +use oxc_ast::{NONE, ast::*}; use oxc_span::{GetSpan, SPAN}; use rustc_hash::FxHashMap; use crate::{ + IsolatedDeclarations, diagnostics::{ accessor_must_have_explicit_return_type, computed_property_name, extends_clause_expression, method_must_have_explicit_return_type, property_must_have_explicit_type, }, - IsolatedDeclarations, }; impl<'a> IsolatedDeclarations<'a> { diff --git a/crates/oxc_isolated_declarations/src/declaration.rs b/crates/oxc_isolated_declarations/src/declaration.rs index 37b25cd315dacd..cb364b40daa174 100644 --- a/crates/oxc_isolated_declarations/src/declaration.rs +++ b/crates/oxc_isolated_declarations/src/declaration.rs @@ -1,18 +1,18 @@ use std::cell::Cell; use oxc_allocator::{Box, CloneIn, Vec}; -use oxc_ast::{ast::*, visit::walk_mut::walk_ts_signatures, Visit, VisitMut}; +use oxc_ast::{Visit, VisitMut, ast::*, visit::walk_mut::walk_ts_signatures}; use oxc_ecmascript::BoundNames; use oxc_span::{GetSpan, SPAN}; use oxc_syntax::scope::ScopeFlags; use crate::{ + IsolatedDeclarations, diagnostics::{ accessor_must_have_explicit_return_type, binding_element_export, inferred_type_of_expression, signature_computed_property_name, variable_must_have_explicit_type, }, - IsolatedDeclarations, }; impl<'a> IsolatedDeclarations<'a> { diff --git a/crates/oxc_isolated_declarations/src/enum.rs b/crates/oxc_isolated_declarations/src/enum.rs index e8b6605317d54c..eaa852959536b0 100644 --- a/crates/oxc_isolated_declarations/src/enum.rs +++ b/crates/oxc_isolated_declarations/src/enum.rs @@ -9,7 +9,7 @@ use oxc_syntax::{ operator::{BinaryOperator, UnaryOperator}, }; -use crate::{diagnostics::enum_member_initializers, IsolatedDeclarations}; +use crate::{IsolatedDeclarations, diagnostics::enum_member_initializers}; #[derive(Debug, Clone)] enum ConstantValue { diff --git a/crates/oxc_isolated_declarations/src/formal_parameter_binding_pattern.rs b/crates/oxc_isolated_declarations/src/formal_parameter_binding_pattern.rs index faeb91a27a6dbb..74185b3cdb680d 100644 --- a/crates/oxc_isolated_declarations/src/formal_parameter_binding_pattern.rs +++ b/crates/oxc_isolated_declarations/src/formal_parameter_binding_pattern.rs @@ -1,6 +1,6 @@ use oxc_allocator::CloneIn; use oxc_ast::{ - ast::BindingPatternKind, visit::walk_mut::walk_binding_pattern_kind, AstBuilder, VisitMut, + AstBuilder, VisitMut, ast::BindingPatternKind, visit::walk_mut::walk_binding_pattern_kind, }; pub struct FormalParameterBindingPattern<'a> { diff --git a/crates/oxc_isolated_declarations/src/function.rs b/crates/oxc_isolated_declarations/src/function.rs index 03a9268b7f49c8..3814f9d5aee44d 100644 --- a/crates/oxc_isolated_declarations/src/function.rs +++ b/crates/oxc_isolated_declarations/src/function.rs @@ -1,14 +1,14 @@ use oxc_allocator::{Box, CloneIn}; -use oxc_ast::{ast::*, NONE}; -use oxc_span::{Span, SPAN}; +use oxc_ast::{NONE, ast::*}; +use oxc_span::{SPAN, Span}; use crate::{ + IsolatedDeclarations, diagnostics::{ function_must_have_explicit_return_type, implicitly_adding_undefined_to_type, parameter_must_have_explicit_type, }, formal_parameter_binding_pattern::FormalParameterBindingPattern, - IsolatedDeclarations, }; impl<'a> IsolatedDeclarations<'a> { diff --git a/crates/oxc_isolated_declarations/src/inferrer.rs b/crates/oxc_isolated_declarations/src/inferrer.rs index 1081578cdbbaac..6e6c1efb8581bc 100644 --- a/crates/oxc_isolated_declarations/src/inferrer.rs +++ b/crates/oxc_isolated_declarations/src/inferrer.rs @@ -6,9 +6,9 @@ use oxc_ast::ast::{ use oxc_span::SPAN; use crate::{ + IsolatedDeclarations, diagnostics::{array_inferred, inferred_type_of_class_expression}, return_type::FunctionReturnType, - IsolatedDeclarations, }; impl<'a> IsolatedDeclarations<'a> { diff --git a/crates/oxc_isolated_declarations/src/lib.rs b/crates/oxc_isolated_declarations/src/lib.rs index 3c77d709cc0f94..fda4743da6055a 100644 --- a/crates/oxc_isolated_declarations/src/lib.rs +++ b/crates/oxc_isolated_declarations/src/lib.rs @@ -10,9 +10,9 @@ use std::{cell::RefCell, mem}; use rustc_hash::{FxHashMap, FxHashSet}; use oxc_allocator::{Allocator, CloneIn}; -use oxc_ast::{ast::*, AstBuilder, Visit, NONE}; +use oxc_ast::{AstBuilder, NONE, Visit, ast::*}; use oxc_diagnostics::OxcDiagnostic; -use oxc_span::{Atom, GetSpan, SourceType, SPAN}; +use oxc_span::{Atom, GetSpan, SPAN, SourceType}; use crate::{diagnostics::function_with_assigning_properties, scope::ScopeTree}; diff --git a/crates/oxc_isolated_declarations/src/module.rs b/crates/oxc_isolated_declarations/src/module.rs index 75462ef1a8b27b..afa4a1a5ce8af8 100644 --- a/crates/oxc_isolated_declarations/src/module.rs +++ b/crates/oxc_isolated_declarations/src/module.rs @@ -1,8 +1,8 @@ use oxc_allocator::{Box, CloneIn, Vec}; -use oxc_ast::{ast::*, NONE}; +use oxc_ast::{NONE, ast::*}; use oxc_span::{Atom, GetSpan, SPAN}; -use crate::{diagnostics::default_export_inferred, IsolatedDeclarations}; +use crate::{IsolatedDeclarations, diagnostics::default_export_inferred}; impl<'a> IsolatedDeclarations<'a> { pub(crate) fn transform_export_named_declaration( diff --git a/crates/oxc_isolated_declarations/src/return_type.rs b/crates/oxc_isolated_declarations/src/return_type.rs index 5e46cf03e91c4a..1fb98ace8ef34e 100644 --- a/crates/oxc_isolated_declarations/src/return_type.rs +++ b/crates/oxc_isolated_declarations/src/return_type.rs @@ -2,16 +2,16 @@ use std::cell::Cell; use oxc_allocator::CloneIn; use oxc_ast::{ + AstBuilder, Visit, ast::{ ArrowFunctionExpression, BindingIdentifier, Expression, Function, FunctionBody, ReturnStatement, TSType, TSTypeAliasDeclaration, TSTypeName, TSTypeQueryExprName, }, - AstBuilder, Visit, }; use oxc_span::{Atom, GetSpan, SPAN}; use oxc_syntax::scope::{ScopeFlags, ScopeId}; -use crate::{diagnostics::type_containing_private_name, IsolatedDeclarations}; +use crate::{IsolatedDeclarations, diagnostics::type_containing_private_name}; /// Infer return type from return statement. /// ```ts diff --git a/crates/oxc_isolated_declarations/src/scope.rs b/crates/oxc_isolated_declarations/src/scope.rs index e12aa447a8370c..a379228e10a89d 100644 --- a/crates/oxc_isolated_declarations/src/scope.rs +++ b/crates/oxc_isolated_declarations/src/scope.rs @@ -3,7 +3,7 @@ use std::cell::Cell; use bitflags::bitflags; use rustc_hash::FxHashMap; -use oxc_ast::{ast::*, visit::walk::*, Visit}; +use oxc_ast::{Visit, ast::*, visit::walk::*}; use oxc_span::Atom; use oxc_syntax::scope::{ScopeFlags, ScopeId}; diff --git a/crates/oxc_isolated_declarations/src/types.rs b/crates/oxc_isolated_declarations/src/types.rs index 34f8878df0a96b..69c4b94cea14e2 100644 --- a/crates/oxc_isolated_declarations/src/types.rs +++ b/crates/oxc_isolated_declarations/src/types.rs @@ -1,21 +1,21 @@ use oxc_allocator::CloneIn; use oxc_ast::{ + NONE, ast::{ ArrayExpression, ArrayExpressionElement, ArrowFunctionExpression, Expression, Function, ObjectExpression, ObjectPropertyKind, TSLiteral, TSMethodSignatureKind, TSTupleElement, TSType, TSTypeOperatorOperator, }, - NONE, }; -use oxc_span::{GetSpan, Span, SPAN}; +use oxc_span::{GetSpan, SPAN, Span}; use crate::{ + IsolatedDeclarations, diagnostics::{ arrays_with_spread_elements, function_must_have_explicit_return_type, inferred_type_of_expression, object_with_spread_assignments, shorthand_property, }, function::get_function_span, - IsolatedDeclarations, }; impl<'a> IsolatedDeclarations<'a> { diff --git a/crates/oxc_language_server/src/commands.rs b/crates/oxc_language_server/src/commands.rs index 63b90291045287..dd78ce349e26da 100644 --- a/crates/oxc_language_server/src/commands.rs +++ b/crates/oxc_language_server/src/commands.rs @@ -3,11 +3,11 @@ use serde::Deserialize; use tower_lsp::{ jsonrpc::{self, Error}, lsp_types::{ - request::ApplyWorkspaceEdit, ApplyWorkspaceEditParams, TextEdit, Url, WorkspaceEdit, + ApplyWorkspaceEditParams, TextEdit, Url, WorkspaceEdit, request::ApplyWorkspaceEdit, }, }; -use crate::{capabilities::Capabilities, Backend}; +use crate::{Backend, capabilities::Capabilities}; pub const LSP_COMMANDS: [WorkspaceCommands; 1] = [WorkspaceCommands::FixAll(FixAllCommand)]; diff --git a/crates/oxc_language_server/src/linter/isolated_lint_handler.rs b/crates/oxc_language_server/src/linter/isolated_lint_handler.rs index 785fd9a37b1947..bd36efdf1ef625 100644 --- a/crates/oxc_language_server/src/linter/isolated_lint_handler.rs +++ b/crates/oxc_language_server/src/linter/isolated_lint_handler.rs @@ -12,16 +12,16 @@ use tower_lsp::lsp_types::{self, DiagnosticRelatedInformation, DiagnosticSeverit use oxc_allocator::Allocator; use oxc_diagnostics::{Error, NamedSource}; use oxc_linter::{ - loader::{JavaScriptSource, Loader, LINT_PARTIAL_LOADER_EXT}, Linter, ModuleRecord, + loader::{JavaScriptSource, LINT_PARTIAL_LOADER_EXT, Loader}, }; use oxc_parser::{ParseOptions, Parser}; use oxc_semantic::SemanticBuilder; use oxc_span::VALID_EXTENSIONS; +use crate::DiagnosticReport; use crate::linter::error_with_position::{ErrorReport, ErrorWithPosition, FixedContent}; use crate::linter::offset_to_position; -use crate::DiagnosticReport; pub struct IsolatedLintHandler { linter: Arc, diff --git a/crates/oxc_language_server/src/linter/mod.rs b/crates/oxc_language_server/src/linter/mod.rs index 4d8e28b881ba27..4fc9e675a8314a 100644 --- a/crates/oxc_language_server/src/linter/mod.rs +++ b/crates/oxc_language_server/src/linter/mod.rs @@ -1,4 +1,4 @@ -use oxc_data_structures::rope::{get_line_column, Rope}; +use oxc_data_structures::rope::{Rope, get_line_column}; use tower_lsp::lsp_types::Position; pub mod error_with_position; diff --git a/crates/oxc_language_server/src/main.rs b/crates/oxc_language_server/src/main.rs index db87670c3d9e2b..53670b87a8b635 100644 --- a/crates/oxc_language_server/src/main.rs +++ b/crates/oxc_language_server/src/main.rs @@ -9,6 +9,7 @@ use rustc_hash::FxBuildHasher; use serde::{Deserialize, Serialize}; use tokio::sync::{Mutex, OnceCell, RwLock, SetError}; use tower_lsp::{ + Client, LanguageServer, LspService, Server, jsonrpc::{Error, ErrorCode, Result}, lsp_types::{ CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeActionResponse, @@ -18,12 +19,11 @@ use tower_lsp::{ InitializedParams, NumberOrString, Position, Range, ServerInfo, TextEdit, Url, WorkspaceEdit, }, - Client, LanguageServer, LspService, Server, }; use oxc_linter::{ConfigStoreBuilder, FixKind, LintOptions, Linter, Oxlintrc}; -use crate::capabilities::{Capabilities, CODE_ACTION_KIND_SOURCE_FIX_ALL_OXC}; +use crate::capabilities::{CODE_ACTION_KIND_SOURCE_FIX_ALL_OXC, Capabilities}; use crate::linter::error_with_position::DiagnosticReport; use crate::linter::server_linter::ServerLinter; @@ -75,11 +75,7 @@ impl Options { } fn get_config_path(&self) -> Option { - if self.config_path.is_empty() { - None - } else { - Some(PathBuf::from(&self.config_path)) - } + if self.config_path.is_empty() { None } else { Some(PathBuf::from(&self.config_path)) } } } diff --git a/crates/oxc_linter/src/ast_util.rs b/crates/oxc_linter/src/ast_util.rs index e391567169f414..30846ba52e19c3 100644 --- a/crates/oxc_linter/src/ast_util.rs +++ b/crates/oxc_linter/src/ast_util.rs @@ -1,15 +1,15 @@ use std::borrow::Cow; use oxc_ast::{ - ast::{BindingIdentifier, *}, AstKind, + ast::{BindingIdentifier, *}, }; -use oxc_ecmascript::{is_global_reference::WithoutGlobalReferenceInformation, ToBoolean}; +use oxc_ecmascript::{ToBoolean, is_global_reference::WithoutGlobalReferenceInformation}; use oxc_semantic::{AstNode, IsGlobalReference, NodeId, ReferenceId, Semantic, SymbolId}; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{AssignmentOperator, BinaryOperator, LogicalOperator, UnaryOperator}; -use crate::{utils::get_function_nearest_jsdoc_node, LintContext}; +use crate::{LintContext, utils::get_function_nearest_jsdoc_node}; /// Test if an AST node is a boolean value that never changes. Specifically we /// test for: diff --git a/crates/oxc_linter/src/config/categories.rs b/crates/oxc_linter/src/config/categories.rs index 8787e8b69a83cb..5985be28324a69 100644 --- a/crates/oxc_linter/src/config/categories.rs +++ b/crates/oxc_linter/src/config/categories.rs @@ -33,10 +33,10 @@ impl JsonSchema for OxlintCategories { "OxlintCategories".to_string() } - fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { - let severity = gen.subschema_for::(); + fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { + let severity = r#gen.subschema_for::(); let mut schema = - gen.subschema_for::>().into_object(); + r#gen.subschema_for::>().into_object(); { schema.object().additional_properties = None; diff --git a/crates/oxc_linter/src/config/config_builder.rs b/crates/oxc_linter/src/config/config_builder.rs index cb07edff4f9c01..0d3b4bcf6a0a81 100644 --- a/crates/oxc_linter/src/config/config_builder.rs +++ b/crates/oxc_linter/src/config/config_builder.rs @@ -8,10 +8,10 @@ use oxc_span::CompactStr; use rustc_hash::FxHashSet; use crate::{ - config::{ConfigStore, ESLintRule, LintPlugins, OxlintOverrides, OxlintRules}, - rules::RULES, AllowWarnDeny, LintConfig, LintFilter, LintFilterKind, Oxlintrc, RuleCategory, RuleEnum, RuleWithSeverity, + config::{ConfigStore, ESLintRule, LintPlugins, OxlintOverrides, OxlintRules}, + rules::RULES, }; #[must_use = "You dropped your builder without building a Linter! Did you mean to call .build()?"] @@ -210,11 +210,14 @@ impl ConfigStoreBuilder { // NOTE: we may want to warn users if they're configuring a rule that does not exist. let rules_to_configure = all_rules.iter().filter(query); for rule in rules_to_configure { - if let Some(mut existing_rule) = self.rules.take(rule) { - existing_rule.severity = severity; - self.rules.insert(existing_rule); - } else { - self.rules.insert(RuleWithSeverity::new(rule.clone(), severity)); + match self.rules.take(rule) { + Some(mut existing_rule) => { + existing_rule.severity = severity; + self.rules.insert(existing_rule); + } + _ => { + self.rules.insert(RuleWithSeverity::new(rule.clone(), severity)); + } } } } @@ -589,13 +592,13 @@ mod test { // Enable eslint plugin. Since it's already enabled, this does nothing. assert!(initial_plugins.contains(LintPlugins::ESLINT)); // sanity check that eslint is - // enabled + // enabled let builder = builder.and_plugins(LintPlugins::ESLINT, true); assert_eq!(initial_plugins, builder.plugins()); // Disable import plugin. Since it's not already enabled, this is also a no-op. assert!(!builder.plugins().contains(LintPlugins::IMPORT)); // sanity check that it's not - // already enabled + // already enabled let builder = builder.and_plugins(LintPlugins::IMPORT, false); assert_eq!(initial_plugins, builder.plugins()); diff --git a/crates/oxc_linter/src/config/config_store.rs b/crates/oxc_linter/src/config/config_store.rs index c0f76ca0d0115f..7409d14f137024 100644 --- a/crates/oxc_linter/src/config/config_store.rs +++ b/crates/oxc_linter/src/config/config_store.rs @@ -2,8 +2,8 @@ use std::{path::Path, sync::Arc}; use rustc_hash::FxHashSet; -use super::{overrides::OxlintOverrides, LintConfig, LintPlugins}; -use crate::{rules::RULES, RuleWithSeverity}; +use super::{LintConfig, LintPlugins, overrides::OxlintOverrides}; +use crate::{RuleWithSeverity, rules::RULES}; // TODO: support `categories` et. al. in overrides. #[derive(Debug)] @@ -143,8 +143,8 @@ impl ConfigStore { mod test { use super::{ConfigStore, OxlintOverrides}; use crate::{ - config::{LintConfig, OxlintEnv, OxlintGlobals, OxlintSettings}, AllowWarnDeny, LintPlugins, RuleEnum, RuleWithSeverity, + config::{LintConfig, OxlintEnv, OxlintGlobals, OxlintSettings}, }; macro_rules! from_json { diff --git a/crates/oxc_linter/src/config/globals.rs b/crates/oxc_linter/src/config/globals.rs index 672b4993928457..5c7d4401798a0f 100644 --- a/crates/oxc_linter/src/config/globals.rs +++ b/crates/oxc_linter/src/config/globals.rs @@ -2,7 +2,7 @@ use std::{borrow, fmt, hash, ops::Deref}; use rustc_hash::FxHashMap; use schemars::JsonSchema; -use serde::{de::Visitor, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Visitor}; /// Add or remove global variables. /// @@ -87,11 +87,7 @@ impl<'de> Deserialize<'de> for GlobalValue { impl From for GlobalValue { #[inline] fn from(value: bool) -> Self { - if value { - GlobalValue::Writeable - } else { - GlobalValue::Readonly - } + if value { GlobalValue::Writeable } else { GlobalValue::Readonly } } } diff --git a/crates/oxc_linter/src/config/mod.rs b/crates/oxc_linter/src/config/mod.rs index 862d3319ff6bdb..d766225e6ac453 100644 --- a/crates/oxc_linter/src/config/mod.rs +++ b/crates/oxc_linter/src/config/mod.rs @@ -19,7 +19,7 @@ pub use overrides::OxlintOverrides; pub use oxlintrc::Oxlintrc; pub use plugins::LintPlugins; pub use rules::{ESLintRule, OxlintRules}; -pub use settings::{jsdoc::JSDocPluginSettings, OxlintSettings}; +pub use settings::{OxlintSettings, jsdoc::JSDocPluginSettings}; #[derive(Debug, Default, Clone)] pub struct LintConfig { diff --git a/crates/oxc_linter/src/config/overrides.rs b/crates/oxc_linter/src/config/overrides.rs index b625e4326aa8d4..222c9e71043971 100644 --- a/crates/oxc_linter/src/config/overrides.rs +++ b/crates/oxc_linter/src/config/overrides.rs @@ -1,12 +1,12 @@ use std::{borrow::Cow, ops::Deref, path::Path}; use nonmax::NonMaxU32; -use schemars::{gen, schema::Schema, JsonSchema}; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use schemars::{JsonSchema, r#gen, schema::Schema}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; use oxc_index::{Idx, IndexVec}; -use crate::{config::OxlintRules, LintPlugins, OxlintEnv, OxlintGlobals}; +use crate::{LintPlugins, OxlintEnv, OxlintGlobals, config::OxlintRules}; #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct OverrideId(NonMaxU32); @@ -59,8 +59,8 @@ impl JsonSchema for OxlintOverrides { Cow::Borrowed("OxlintOverrides") } - fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema { - gen.subschema_for::>() + fn json_schema(r#gen: &mut r#gen::SchemaGenerator) -> Schema { + r#gen.subschema_for::>() } } @@ -148,8 +148,8 @@ impl JsonSchema for GlobSet { Cow::Borrowed("GlobSet") } - fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema { - gen.subschema_for::>() + fn json_schema(r#gen: &mut r#gen::SchemaGenerator) -> Schema { + r#gen.subschema_for::>() } } diff --git a/crates/oxc_linter/src/config/plugins.rs b/crates/oxc_linter/src/config/plugins.rs index 155d3b8a93b592..69c3cb2569fe4d 100644 --- a/crates/oxc_linter/src/config/plugins.rs +++ b/crates/oxc_linter/src/config/plugins.rs @@ -1,9 +1,9 @@ use bitflags::bitflags; -use schemars::{gen::SchemaGenerator, schema::Schema, JsonSchema}; +use schemars::{JsonSchema, r#gen::SchemaGenerator, schema::Schema}; use serde::{ + Deserialize, Serialize, de::{self, Deserializer}, ser::Serializer, - Deserialize, Serialize, }; bitflags! { @@ -218,8 +218,8 @@ impl JsonSchema for LintPlugins { std::borrow::Cow::Borrowed("LintPlugins") } - fn json_schema(gen: &mut SchemaGenerator) -> Schema { - gen.subschema_for::>() + fn json_schema(r#gen: &mut SchemaGenerator) -> Schema { + r#gen.subschema_for::>() } } diff --git a/crates/oxc_linter/src/config/rules.rs b/crates/oxc_linter/src/config/rules.rs index a5e72eb250f4b5..538b5aa61278bb 100644 --- a/crates/oxc_linter/src/config/rules.rs +++ b/crates/oxc_linter/src/config/rules.rs @@ -1,19 +1,19 @@ use std::{borrow::Cow, fmt}; use rustc_hash::{FxHashMap, FxHashSet}; -use schemars::{gen::SchemaGenerator, schema::Schema, JsonSchema}; +use schemars::{JsonSchema, r#gen::SchemaGenerator, schema::Schema}; use serde::{ + Deserialize, Serialize, Serializer, de::{self, Deserializer, Visitor}, ser::SerializeMap, - Deserialize, Serialize, Serializer, }; use oxc_diagnostics::{Error, OxcDiagnostic}; use crate::{ - rules::{RuleEnum, RULES}, - utils::{is_eslint_rule_adapted_to_typescript, is_jest_rule_adapted_to_vitest}, AllowWarnDeny, RuleWithSeverity, + rules::{RULES, RuleEnum}, + utils::{is_eslint_rule_adapted_to_typescript, is_jest_rule_adapted_to_vitest}, }; type RuleSet = FxHashSet; @@ -112,11 +112,7 @@ impl OxlintRules { let rules = rules_for_override .iter() .filter_map(|r| { - if r.name() == *name { - Some((r.plugin_name(), r)) - } else { - None - } + if r.name() == *name { Some((r.plugin_name(), r)) } else { None } }) .collect::>(); @@ -185,7 +181,7 @@ impl JsonSchema for OxlintRules { Cow::Borrowed("OxlintRules") } - fn json_schema(gen: &mut SchemaGenerator) -> Schema { + fn json_schema(r#gen: &mut SchemaGenerator) -> Schema { #[expect(unused)] #[derive(Debug, Clone, JsonSchema)] #[serde(untagged)] @@ -201,7 +197,7 @@ impl JsonSchema for OxlintRules { )] struct DummyRuleMap(pub FxHashMap); - gen.subschema_for::() + r#gen.subschema_for::() } } @@ -355,11 +351,11 @@ impl ESLintRule { #[expect(clippy::default_trait_access)] mod test { use serde::Deserialize; - use serde_json::{json, Value}; + use serde_json::{Value, json}; use crate::{ - rules::{RuleEnum, RULES}, AllowWarnDeny, RuleWithSeverity, + rules::{RULES, RuleEnum}, }; use super::{OxlintRules, RuleSet}; diff --git a/crates/oxc_linter/src/context/host.rs b/crates/oxc_linter/src/context/host.rs index f47b7947799ffa..44889a49e4f8cf 100644 --- a/crates/oxc_linter/src/context/host.rs +++ b/crates/oxc_linter/src/context/host.rs @@ -4,16 +4,16 @@ use oxc_semantic::Semantic; use oxc_span::SourceType; use crate::{ + FrameworkFlags, RuleWithSeverity, config::{LintConfig, LintPlugins}, disable_directives::{DisableDirectives, DisableDirectivesBuilder}, fixer::{FixKind, Message}, frameworks, module_record::ModuleRecord, options::LintOptions, - FrameworkFlags, RuleWithSeverity, }; -use super::{plugin_name_to_prefix, LintContext}; +use super::{LintContext, plugin_name_to_prefix}; /// Stores shared information about a file being linted. /// diff --git a/crates/oxc_linter/src/context/mod.rs b/crates/oxc_linter/src/context/mod.rs index c3014d38b8139a..f230f2502d7ba5 100644 --- a/crates/oxc_linter/src/context/mod.rs +++ b/crates/oxc_linter/src/context/mod.rs @@ -11,11 +11,11 @@ use oxc_span::{GetSpan, Span}; #[cfg(debug_assertions)] use crate::rule::RuleFixMeta; use crate::{ + AllowWarnDeny, FrameworkFlags, ModuleRecord, OxlintEnv, OxlintGlobals, OxlintSettings, config::GlobalValue, disable_directives::DisableDirectives, fixer::{FixKind, Message, RuleFix, RuleFixer}, javascript_globals::GLOBALS, - AllowWarnDeny, FrameworkFlags, ModuleRecord, OxlintEnv, OxlintGlobals, OxlintSettings, }; mod host; diff --git a/crates/oxc_linter/src/fixer/fix.rs b/crates/oxc_linter/src/fixer/fix.rs index 1090ffb2127863..059c6a72af1c7b 100644 --- a/crates/oxc_linter/src/fixer/fix.rs +++ b/crates/oxc_linter/src/fixer/fix.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, ops::Deref}; use bitflags::bitflags; -use oxc_span::{GetSpan, Span, SPAN}; +use oxc_span::{GetSpan, SPAN, Span}; bitflags! { /// Flags describing an automatic code fix. diff --git a/crates/oxc_linter/src/globals.rs b/crates/oxc_linter/src/globals.rs index ad642e1f518b3f..e24589f6042fb4 100644 --- a/crates/oxc_linter/src/globals.rs +++ b/crates/oxc_linter/src/globals.rs @@ -1,4 +1,4 @@ -use phf::{phf_map, phf_set, Map}; +use phf::{Map, phf_map, phf_set}; pub const PRE_DEFINE_VAR: Map<&'static str, bool> = phf_map! { "undefined" => false, diff --git a/crates/oxc_linter/src/javascript_globals.rs b/crates/oxc_linter/src/javascript_globals.rs index d5a4ca141df1fc..3781750d5f7c30 100644 --- a/crates/oxc_linter/src/javascript_globals.rs +++ b/crates/oxc_linter/src/javascript_globals.rs @@ -1,7 +1,7 @@ // Auto-generated code, DO NOT EDIT DIRECTLY! // To edit this generated file you have to run `cargo run -p javascript_globals`. -use phf::{phf_map, Map}; +use phf::{Map, phf_map}; pub static GLOBALS: Map<&'static str, Map<&'static str, bool>> = phf_map! { "builtin" => phf_map! { diff --git a/crates/oxc_linter/src/loader/mod.rs b/crates/oxc_linter/src/loader/mod.rs index 4da9ba51a5cd9a..91c56cb7bd4590 100644 --- a/crates/oxc_linter/src/loader/mod.rs +++ b/crates/oxc_linter/src/loader/mod.rs @@ -4,7 +4,7 @@ use oxc_span::SourceType; mod partial_loader; mod source; -pub use partial_loader::{PartialLoader, LINT_PARTIAL_LOADER_EXT}; +pub use partial_loader::{LINT_PARTIAL_LOADER_EXT, PartialLoader}; pub use source::JavaScriptSource; // TODO: use oxc_resolver::FileSystem. We can't do so until that crate exposes FileSystemOs diff --git a/crates/oxc_linter/src/loader/partial_loader/svelte.rs b/crates/oxc_linter/src/loader/partial_loader/svelte.rs index a03e645a656984..f5881bc61b6d0d 100644 --- a/crates/oxc_linter/src/loader/partial_loader/svelte.rs +++ b/crates/oxc_linter/src/loader/partial_loader/svelte.rs @@ -1,7 +1,7 @@ use memchr::memmem::Finder; use oxc_span::SourceType; -use super::{find_script_closing_angle, SCRIPT_END, SCRIPT_START}; +use super::{SCRIPT_END, SCRIPT_START, find_script_closing_angle}; use crate::loader::JavaScriptSource; pub struct SveltePartialLoader<'a> { diff --git a/crates/oxc_linter/src/loader/partial_loader/vue.rs b/crates/oxc_linter/src/loader/partial_loader/vue.rs index 16531733c61b3e..0a6796284c8e07 100644 --- a/crates/oxc_linter/src/loader/partial_loader/vue.rs +++ b/crates/oxc_linter/src/loader/partial_loader/vue.rs @@ -1,7 +1,7 @@ use memchr::memmem::Finder; use oxc_span::SourceType; -use super::{find_script_closing_angle, JavaScriptSource, SCRIPT_END, SCRIPT_START}; +use super::{JavaScriptSource, SCRIPT_END, SCRIPT_START, find_script_closing_angle}; pub struct VuePartialLoader<'a> { source_text: &'a str, diff --git a/crates/oxc_linter/src/module_graph_visitor.rs b/crates/oxc_linter/src/module_graph_visitor.rs index 02df77632eb75d..dc72760961df9e 100644 --- a/crates/oxc_linter/src/module_graph_visitor.rs +++ b/crates/oxc_linter/src/module_graph_visitor.rs @@ -191,7 +191,7 @@ impl ModuleGraphVisitor { leave: &mut LeaveMod, ) -> VisitFoldWhile { macro_rules! accumulate { - ($acc:expr) => { + ($acc:expr_2021) => { accumulator = $acc; if accumulator.is_done() { diff --git a/crates/oxc_linter/src/options/allow_warn_deny.rs b/crates/oxc_linter/src/options/allow_warn_deny.rs index 2be8b4aad75064..3958ce1a21eba7 100644 --- a/crates/oxc_linter/src/options/allow_warn_deny.rs +++ b/crates/oxc_linter/src/options/allow_warn_deny.rs @@ -3,8 +3,8 @@ use std::{ fmt::{self, Display}, }; -use schemars::{schema::SchemaObject, JsonSchema}; -use serde::{de, Deserialize, Serialize}; +use schemars::{JsonSchema, schema::SchemaObject}; +use serde::{Deserialize, Serialize, de}; use serde_json::{Number, Value}; use oxc_diagnostics::{OxcDiagnostic, Severity}; @@ -167,8 +167,8 @@ impl JsonSchema for AllowWarnDeny { "AllowWarnDeny".into() } - fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { - let mut string_schema = ::json_schema(gen).into_object(); + fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { + let mut string_schema = ::json_schema(r#gen).into_object(); string_schema.enum_values = Some(vec!["allow".into(), "off".into(), "warn".into(), "error".into(), "deny".into()]); string_schema.metadata().description = Some( @@ -178,7 +178,7 @@ impl JsonSchema for AllowWarnDeny { - "error" or "deny": Turn the rule on as an error (will exit with a failure code)."# .to_string(), ); - let mut int_schema = ::json_schema(gen).into_object(); + let mut int_schema = ::json_schema(r#gen).into_object(); int_schema.number().minimum = Some(0.0); int_schema.number().maximum = Some(2.0); int_schema.metadata().description = Some( diff --git a/crates/oxc_linter/src/options/mod.rs b/crates/oxc_linter/src/options/mod.rs index 767960b68e4362..1fa9fa5071e51f 100644 --- a/crates/oxc_linter/src/options/mod.rs +++ b/crates/oxc_linter/src/options/mod.rs @@ -4,7 +4,7 @@ mod filter; pub use allow_warn_deny::AllowWarnDeny; pub use filter::{InvalidFilterKind, LintFilter, LintFilterKind}; -use crate::{fixer::FixKind, FrameworkFlags}; +use crate::{FrameworkFlags, fixer::FixKind}; /// Subset of options used directly by the linter. #[derive(Debug, Default, Clone, Copy)] diff --git a/crates/oxc_linter/src/rule.rs b/crates/oxc_linter/src/rule.rs index 49e895662034c5..264e7adadbc5fa 100644 --- a/crates/oxc_linter/src/rule.rs +++ b/crates/oxc_linter/src/rule.rs @@ -10,9 +10,9 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ + AllowWarnDeny, AstNode, FixKind, RuleEnum, context::{ContextHost, LintContext}, utils::PossibleJestNode, - AllowWarnDeny, AstNode, FixKind, RuleEnum, }; pub trait Rule: Sized + Default + fmt::Debug { @@ -306,7 +306,7 @@ impl RuleWithSeverity { #[cfg(test)] mod test { - use markdown::{to_html_with_options, Options}; + use markdown::{Options, to_html_with_options}; use super::RuleCategory; use crate::rules::RULES; diff --git a/crates/oxc_linter/src/rules/eslint/array_callback_return/mod.rs b/crates/oxc_linter/src/rules/eslint/array_callback_return/mod.rs index db4b45f8d3b047..b4b8aa64df9759 100644 --- a/crates/oxc_linter/src/rules/eslint/array_callback_return/mod.rs +++ b/crates/oxc_linter/src/rules/eslint/array_callback_return/mod.rs @@ -2,19 +2,19 @@ pub mod return_checker; use std::borrow::Cow; -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use phf::phf_set; use serde_json::Value; -use self::return_checker::{check_function_body, StatementReturnStatus}; +use self::return_checker::{StatementReturnStatus, check_function_body}; use crate::{ + AstNode, ast_util::{get_enclosing_function, is_nth_argument, outermost_paren}, context::LintContext, rule::Rule, - AstNode, }; fn expect_return(method_name: &str, span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/eslint/array_callback_return/return_checker.rs b/crates/oxc_linter/src/rules/eslint/array_callback_return/return_checker.rs index f4c0cffeb07c45..4cb66d004b0680 100644 --- a/crates/oxc_linter/src/rules/eslint/array_callback_return/return_checker.rs +++ b/crates/oxc_linter/src/rules/eslint/array_callback_return/return_checker.rs @@ -1,5 +1,5 @@ use oxc_ast::ast::{BlockStatement, FunctionBody, Statement, SwitchCase}; -use oxc_ecmascript::{is_global_reference::WithoutGlobalReferenceInformation, ToBoolean}; +use oxc_ecmascript::{ToBoolean, is_global_reference::WithoutGlobalReferenceInformation}; /// `StatementReturnStatus` describes whether the CFG corresponding to /// the statement is termitated by return statement in all/some/nome of diff --git a/crates/oxc_linter/src/rules/eslint/constructor_super.rs b/crates/oxc_linter/src/rules/eslint/constructor_super.rs index 56c4492719e6af..5a92604e2837c2 100644 --- a/crates/oxc_linter/src/rules/eslint/constructor_super.rs +++ b/crates/oxc_linter/src/rules/eslint/constructor_super.rs @@ -1,7 +1,7 @@ use oxc_macros::declare_oxc_lint; // use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; // #[derive(Debug, Error, Diagnostic)] // #[error("Expected to call 'super()'.")] diff --git a/crates/oxc_linter/src/rules/eslint/default_case.rs b/crates/oxc_linter/src/rules/eslint/default_case.rs index 25dd681f578eec..be260cfeb5d8e8 100644 --- a/crates/oxc_linter/src/rules/eslint/default_case.rs +++ b/crates/oxc_linter/src/rules/eslint/default_case.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use regex::{Regex, RegexBuilder}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn default_case_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Require default cases in switch statements.") diff --git a/crates/oxc_linter/src/rules/eslint/default_case_last.rs b/crates/oxc_linter/src/rules/eslint/default_case_last.rs index d870e416778d2c..a0d430827028ce 100644 --- a/crates/oxc_linter/src/rules/eslint/default_case_last.rs +++ b/crates/oxc_linter/src/rules/eslint/default_case_last.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn default_case_last_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Enforce default clauses in switch statements to be last") diff --git a/crates/oxc_linter/src/rules/eslint/default_param_last.rs b/crates/oxc_linter/src/rules/eslint/default_param_last.rs index 02622766520882..8bac472be46739 100644 --- a/crates/oxc_linter/src/rules/eslint/default_param_last.rs +++ b/crates/oxc_linter/src/rules/eslint/default_param_last.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::FormalParameter, AstKind}; +use oxc_ast::{AstKind, ast::FormalParameter}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn default_param_last_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Default parameters should be last") diff --git a/crates/oxc_linter/src/rules/eslint/eqeqeq.rs b/crates/oxc_linter/src/rules/eslint/eqeqeq.rs index 6ce7374630122b..e1e99412c88135 100644 --- a/crates/oxc_linter/src/rules/eslint/eqeqeq.rs +++ b/crates/oxc_linter/src/rules/eslint/eqeqeq.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{BinaryExpression, Expression}, AstKind, + ast::{BinaryExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{BinaryOperator, UnaryOperator}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn eqeqeq_diagnostic(x0: &str, x1: &str, span2: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Expected {x1} and instead saw {x0}")) diff --git a/crates/oxc_linter/src/rules/eslint/for_direction.rs b/crates/oxc_linter/src/rules/eslint/for_direction.rs index cf29c8d8f5ccd1..d20b5026f7f8f6 100644 --- a/crates/oxc_linter/src/rules/eslint/for_direction.rs +++ b/crates/oxc_linter/src/rules/eslint/for_direction.rs @@ -1,16 +1,16 @@ use oxc_ast::{ + AstKind, ast::{ AssignmentExpression, AssignmentTarget, Expression, IdentifierReference, SimpleAssignmentTarget, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{AssignmentOperator, BinaryOperator, UnaryOperator, UpdateOperator}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn for_direction_diagnostic(span: Span, span1: Span) -> OxcDiagnostic { OxcDiagnostic::warn("The update clause in this loop moves the variable in the wrong direction") diff --git a/crates/oxc_linter/src/rules/eslint/func_names.rs b/crates/oxc_linter/src/rules/eslint/func_names.rs index 4b508fef0c0c42..c0ed1c71874641 100644 --- a/crates/oxc_linter/src/rules/eslint/func_names.rs +++ b/crates/oxc_linter/src/rules/eslint/func_names.rs @@ -1,11 +1,11 @@ use std::borrow::Cow; use oxc_ast::{ + AstKind, ast::{ AssignmentTarget, AssignmentTargetProperty, BindingPatternKind, Expression, Function, FunctionType, PropertyKind, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -14,7 +14,7 @@ use oxc_span::{Atom, GetSpan, Span}; use oxc_syntax::identifier::is_identifier_name; use phf::phf_set; -use crate::{ast_util::get_function_name_with_kind, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::get_function_name_with_kind, context::LintContext, rule::Rule}; fn named_diagnostic(function_name: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Unexpected named {function_name}.")) @@ -371,20 +371,12 @@ fn guess_function_name<'a>(ctx: &LintContext<'a>, parent_id: NodeId) -> Option { return prop.key.static_name().and_then(|name| { - if is_valid_identifier_name(&name) { - Some(name) - } else { - None - } + if is_valid_identifier_name(&name) { Some(name) } else { None } }); } AstKind::PropertyDefinition(prop) => { return prop.key.static_name().and_then(|name| { - if is_valid_identifier_name(&name) { - Some(name) - } else { - None - } + if is_valid_identifier_name(&name) { Some(name) } else { None } }); } _ => return None, diff --git a/crates/oxc_linter/src/rules/eslint/func_style.rs b/crates/oxc_linter/src/rules/eslint/func_style.rs index 99434d6ec6be85..7e0aee5f99454c 100644 --- a/crates/oxc_linter/src/rules/eslint/func_style.rs +++ b/crates/oxc_linter/src/rules/eslint/func_style.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::FunctionType, AstKind}; +use oxc_ast::{AstKind, ast::FunctionType}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::{AstNode, NodeId}; @@ -23,11 +23,7 @@ enum Style { impl Style { pub fn from(raw: &str) -> Self { - if raw == "declaration" { - Self::Declaration - } else { - Self::Expression - } + if raw == "declaration" { Self::Declaration } else { Self::Expression } } pub fn as_str(&self) -> &str { diff --git a/crates/oxc_linter/src/rules/eslint/getter_return.rs b/crates/oxc_linter/src/rules/eslint/getter_return.rs index ee27d7b66cfda3..d1083e4fdee25a 100644 --- a/crates/oxc_linter/src/rules/eslint/getter_return.rs +++ b/crates/oxc_linter/src/rules/eslint/getter_return.rs @@ -1,25 +1,25 @@ use oxc_ast::{ + AstKind, ast::{ - match_member_expression, ChainElement, Expression, MemberExpression, MethodDefinitionKind, - ObjectProperty, PropertyKind, + ChainElement, Expression, MemberExpression, MethodDefinitionKind, ObjectProperty, + PropertyKind, match_member_expression, }, - AstKind, }; use oxc_cfg::{ + EdgeType, ErrorEdgeKind, InstructionKind, ReturnInstructionKind, graph::{ - visit::{set_depth_first_search, Control, DfsEvent}, Direction, + visit::{Control, DfsEvent, set_depth_first_search}, }, - EdgeType, ErrorEdgeKind, InstructionKind, ReturnInstructionKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::{ContextHost, LintContext}, rule::Rule, - AstNode, }; fn getter_return_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/eslint/grouped_accessor_pairs.rs b/crates/oxc_linter/src/rules/eslint/grouped_accessor_pairs.rs index 56b89a90eed2a0..7f2269facdba7c 100644 --- a/crates/oxc_linter/src/rules/eslint/grouped_accessor_pairs.rs +++ b/crates/oxc_linter/src/rules/eslint/grouped_accessor_pairs.rs @@ -2,11 +2,11 @@ use std::borrow::Cow; use oxc_allocator::Box; use oxc_ast::{ + AstKind, ast::{ ClassElement, Expression, MethodDefinition, MethodDefinitionKind, ObjectProperty, ObjectPropertyKind, PropertyKey, PropertyKind, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -14,7 +14,7 @@ use oxc_span::{GetSpan, Span}; use rustc_hash::FxHashMap; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn grouped_accessor_pairs_diagnostic( getter_span: Span, @@ -379,88 +379,94 @@ fn report( fn test() { use crate::tester::Tester; let pass = vec![ - ("({})", None), - ("({ a })", None), - ("({ a(){}, b(){}, a(){} })", None), - ("({ a: 1, b: 2 })", None), - ("({ a, ...b, c: 1 })", None), - ("({ a, b, ...a })", None), - ("({ a: 1, [b]: 2, a: 3, [b]: 4 })", None), - ("({ a: function get(){}, b, a: function set(foo){} })", None), - ("({ get(){}, a, set(){} })", None), - ("class A {}", None), - ("(class { a(){} })", None), - ("class A { a(){} [b](){} a(){} [b](){} }", None), - ("(class { a(){} b(){} static a(){} static b(){} })", None), - ("class A { get(){} a(){} set(){} }", None), - ("({ get a(){} })", None), - ("({ set a(foo){} })", None), - ("({ a: 1, get b(){}, c, ...d })", None), - ("({ get a(){}, get b(){}, set c(foo){}, set d(foo){} })", None), - ("({ get a(){}, b: 1, set c(foo){} })", None), - ("({ set a(foo){}, b: 1, a: 2 })", None), - ("({ get a(){}, b: 1, a })", None), - ("({ set a(foo){}, b: 1, a(){} })", None), - ("({ get a(){}, b: 1, set [a](foo){} })", None), - ("({ set a(foo){}, b: 1, get 'a '(){} })", None), - ("({ get a(){}, b: 1, ...a })", None), - ("({ set a(foo){}, b: 1 }, { get a(){} })", None), - ("({ get a(){}, b: 1, ...{ set a(foo){} } })", None), - ("({ set a(foo){}, get b(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ get a(){}, set b(foo){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("class A { get a(){} }", None), - ("(class { set a(foo){} })", None), - ("class A { static set a(foo){} }", None), - ("(class { static get a(){} })", None), - ("class A { a(){} set b(foo){} c(){} }", None), - ("(class { a(){} get b(){} c(){} })", None), - ("class A { get a(){} static get b(){} set c(foo){} static set d(bar){} }", None), - ("(class { get a(){} b(){} a(foo){} })", None), - ("class A { static set a(foo){} b(){} static a(){} }", None), - ("(class { get a(){} static b(){} set [a](foo){} })", None), - ("class A { static set a(foo){} b(){} static get ' a'(){} }", None), - ("(class { set a(foo){} b(){} static get a(){} })", None), - ("class A { static set a(foo){} b(){} get a(){} }", None), - ("(class { get a(){} }, class { b(){} set a(foo){} })", None), - ("({ get a(){}, set a(foo){} })", None), - ("({ a: 1, set b(foo){}, get b(){}, c: 2 })", None), - ("({ get a(){}, set a(foo){}, set b(bar){}, get b(){} })", None), - ("({ get [a](){}, set [a](foo){} })", None), - ("({ set a(foo){}, get 'a'(){} })", None), - ("({ a: 1, b: 2, get a(){}, set a(foo){}, c: 3, a: 4 })", None), - ("({ get a(){}, set a(foo){}, set b(bar){} })", None), - ("({ get a(){}, get b(){}, set b(bar){} })", None), - ("class A { get a(){} set a(foo){} }", None), - ("(class { set a(foo){} get a(){} })", None), - ("class A { static set a(foo){} static get a(){} }", None), - ("(class { static get a(){} static set a(foo){} })", None), - ("class A { a(){} set b(foo){} get b(){} c(){} get d(){} set d(bar){} }", None), - ("(class { set a(foo){} get a(){} get b(){} set b(bar){} })", None), - ("class A { static set [a](foo){} static get [a](){} }", None), - ("(class { get a(){} set [`a`](foo){} })", None), - ("class A { static get a(){} static set a(foo){} set a(bar){} static get a(){} }", None), - ("(class { static get a(){} get a(){} set a(foo){} })", None), - ("({ get a(){}, set a(foo){} })", Some(serde_json::json!(["anyOrder"]))), - ("({ set a(foo){}, get a(){} })", Some(serde_json::json!(["anyOrder"]))), - ("({ get a(){}, set a(foo){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ set a(foo){}, get a(){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("class A { get a(){} set a(foo){} }", Some(serde_json::json!(["anyOrder"]))), - ("(class { set a(foo){} get a(){} })", Some(serde_json::json!(["anyOrder"]))), - ("class A { get a(){} set a(foo){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("(class { static set a(foo){} static get a(){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("({ get a(){}, b: 1, get a(){} })", None), - ("({ set a(foo){}, b: 1, set a(foo){} })", None), - ("({ get a(){}, b: 1, set a(foo){}, c: 2, get a(){} })", None), - ("({ set a(foo){}, b: 1, set 'a'(bar){}, c: 2, get a(){} })", None), - ("class A { get [a](){} b(){} get [a](){} c(){} set [a](foo){} }", None), - ("(class { static set a(foo){} b(){} static get a(){} static c(){} static set a(bar){} })", None), - ("class A { get '#abc'(){} b(){} set #abc(foo){} }", None), - ("class A { get #abc(){} b(){} set '#abc'(foo){} }", None), - ("class A { set '#abc'(foo){} get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { set #abc(foo){} get '#abc'(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("class faoo { set abc(val){} get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ( - "class foo { + ("({})", None), + ("({ a })", None), + ("({ a(){}, b(){}, a(){} })", None), + ("({ a: 1, b: 2 })", None), + ("({ a, ...b, c: 1 })", None), + ("({ a, b, ...a })", None), + ("({ a: 1, [b]: 2, a: 3, [b]: 4 })", None), + ("({ a: function get(){}, b, a: function set(foo){} })", None), + ("({ get(){}, a, set(){} })", None), + ("class A {}", None), + ("(class { a(){} })", None), + ("class A { a(){} [b](){} a(){} [b](){} }", None), + ("(class { a(){} b(){} static a(){} static b(){} })", None), + ("class A { get(){} a(){} set(){} }", None), + ("({ get a(){} })", None), + ("({ set a(foo){} })", None), + ("({ a: 1, get b(){}, c, ...d })", None), + ("({ get a(){}, get b(){}, set c(foo){}, set d(foo){} })", None), + ("({ get a(){}, b: 1, set c(foo){} })", None), + ("({ set a(foo){}, b: 1, a: 2 })", None), + ("({ get a(){}, b: 1, a })", None), + ("({ set a(foo){}, b: 1, a(){} })", None), + ("({ get a(){}, b: 1, set [a](foo){} })", None), + ("({ set a(foo){}, b: 1, get 'a '(){} })", None), + ("({ get a(){}, b: 1, ...a })", None), + ("({ set a(foo){}, b: 1 }, { get a(){} })", None), + ("({ get a(){}, b: 1, ...{ set a(foo){} } })", None), + ("({ set a(foo){}, get b(){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ get a(){}, set b(foo){} })", Some(serde_json::json!(["setBeforeGet"]))), + ("class A { get a(){} }", None), + ("(class { set a(foo){} })", None), + ("class A { static set a(foo){} }", None), + ("(class { static get a(){} })", None), + ("class A { a(){} set b(foo){} c(){} }", None), + ("(class { a(){} get b(){} c(){} })", None), + ("class A { get a(){} static get b(){} set c(foo){} static set d(bar){} }", None), + ("(class { get a(){} b(){} a(foo){} })", None), + ("class A { static set a(foo){} b(){} static a(){} }", None), + ("(class { get a(){} static b(){} set [a](foo){} })", None), + ("class A { static set a(foo){} b(){} static get ' a'(){} }", None), + ("(class { set a(foo){} b(){} static get a(){} })", None), + ("class A { static set a(foo){} b(){} get a(){} }", None), + ("(class { get a(){} }, class { b(){} set a(foo){} })", None), + ("({ get a(){}, set a(foo){} })", None), + ("({ a: 1, set b(foo){}, get b(){}, c: 2 })", None), + ("({ get a(){}, set a(foo){}, set b(bar){}, get b(){} })", None), + ("({ get [a](){}, set [a](foo){} })", None), + ("({ set a(foo){}, get 'a'(){} })", None), + ("({ a: 1, b: 2, get a(){}, set a(foo){}, c: 3, a: 4 })", None), + ("({ get a(){}, set a(foo){}, set b(bar){} })", None), + ("({ get a(){}, get b(){}, set b(bar){} })", None), + ("class A { get a(){} set a(foo){} }", None), + ("(class { set a(foo){} get a(){} })", None), + ("class A { static set a(foo){} static get a(){} }", None), + ("(class { static get a(){} static set a(foo){} })", None), + ("class A { a(){} set b(foo){} get b(){} c(){} get d(){} set d(bar){} }", None), + ("(class { set a(foo){} get a(){} get b(){} set b(bar){} })", None), + ("class A { static set [a](foo){} static get [a](){} }", None), + ("(class { get a(){} set [`a`](foo){} })", None), + ("class A { static get a(){} static set a(foo){} set a(bar){} static get a(){} }", None), + ("(class { static get a(){} get a(){} set a(foo){} })", None), + ("({ get a(){}, set a(foo){} })", Some(serde_json::json!(["anyOrder"]))), + ("({ set a(foo){}, get a(){} })", Some(serde_json::json!(["anyOrder"]))), + ("({ get a(){}, set a(foo){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ set a(foo){}, get a(){} })", Some(serde_json::json!(["setBeforeGet"]))), + ("class A { get a(){} set a(foo){} }", Some(serde_json::json!(["anyOrder"]))), + ("(class { set a(foo){} get a(){} })", Some(serde_json::json!(["anyOrder"]))), + ("class A { get a(){} set a(foo){} }", Some(serde_json::json!(["getBeforeSet"]))), + ( + "(class { static set a(foo){} static get a(){} })", + Some(serde_json::json!(["setBeforeGet"])), + ), + ("({ get a(){}, b: 1, get a(){} })", None), + ("({ set a(foo){}, b: 1, set a(foo){} })", None), + ("({ get a(){}, b: 1, set a(foo){}, c: 2, get a(){} })", None), + ("({ set a(foo){}, b: 1, set 'a'(bar){}, c: 2, get a(){} })", None), + ("class A { get [a](){} b(){} get [a](){} c(){} set [a](foo){} }", None), + ( + "(class { static set a(foo){} b(){} static get a(){} static c(){} static set a(bar){} })", + None, + ), + ("class A { get '#abc'(){} b(){} set #abc(foo){} }", None), + ("class A { get #abc(){} b(){} set '#abc'(foo){} }", None), + ("class A { set '#abc'(foo){} get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ("class A { set #abc(foo){} get '#abc'(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ("class faoo { set abc(val){} get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ( + "class foo { static set ['#a+b'](val) { } @@ -471,10 +477,10 @@ fn test() { } }", - Some(serde_json::json!(["getBeforeSet"])), - ), - ( - "class foo { + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class foo { set [() => {}](val) { } @@ -482,10 +488,10 @@ fn test() { } }", - Some(serde_json::json!(["getBeforeSet"])), - ), - ( - "class foo { + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class foo { get aa() { } @@ -494,76 +500,121 @@ fn test() { } }", - Some(serde_json::json!(["setBeforeGet"])), - ) - ]; + Some(serde_json::json!(["setBeforeGet"])), + ), + ]; let fail = vec![ - ("({ get a(){}, b:1, set a(foo){} })", None), - ("({ set 'abc'(foo){}, b:1, get 'abc'(){} })", None), - ("({ get [a](){}, b:1, set [a](foo){} })", None), - ("class A { get abc(){} b(){} set abc(foo){} }", None), - ("(class { set abc(foo){} b(){} get abc(){} })", None), - ("class A { static set a(foo){} b(){} static get a(){} }", None), - ("(class { static get 123(){} b(){} static set 123(foo){} })", None), - ("class A { static get [a](){} b(){} static set [a](foo){} }", None), - ("class A { get '#abc'(){} b(){} set '#abc'(foo){} }", None), - ("class A { get #abc(){} b(){} set #abc(foo){} }", None), - ("({ set a(foo){}, get a(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ get 123(){}, set 123(foo){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("({ get [a](){}, set [a](foo){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("class A { set abc(foo){} get abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("(class { get [`abc`](){} set [`abc`](foo){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("class A { static get a(){} static set a(foo){} }", Some(serde_json::json!(["setBeforeGet"]))), - ("(class { static set 'abc'(foo){} static get 'abc'(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { static set [abc](foo){} static get [abc](){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { set '#abc'(foo){} get '#abc'(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { set #abc(foo){} get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("({ get a(){}, b: 1, set a(foo){} })", Some(serde_json::json!(["anyOrder"]))), - ("({ get a(){}, b: 1, set a(foo){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("({ get a(){}, b: 1, set a(foo){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { set a(foo){} b(){} get a(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("(class { static set a(foo){} b(){} static get a(){} })", Some(serde_json::json!(["setBeforeGet"]))), - ("({ get 'abc'(){}, d(){}, set 'abc'(foo){} })", None), - ("({ set ''(foo){}, get [''](){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { set abc(foo){} get 'abc'(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("(class { set [`abc`](foo){} get abc(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ set ['abc'](foo){}, get [`abc`](){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ set 123(foo){}, get [123](){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { static set '123'(foo){} static get 123(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("(class { set [a+b](foo){} get [a+b](){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ set [f(a)](foo){}, get [f(a)](){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ get a(){}, b: 1, set a(foo){}, set c(foo){}, d(){}, get c(){} })", None), - ("({ get a(){}, set b(foo){}, set a(bar){}, get b(){} })", None), - ("({ get a(){}, set [a](foo){}, set a(bar){}, get [a](){} })", None), - ("({ a(){}, set b(foo){}, ...c, get b(){}, set c(bar){}, get c(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("({ set [a](foo){}, get [a](){}, set [-a](bar){}, get [-a](){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { get a(){} constructor (){} set a(foo){} get b(){} static c(){} set b(bar){} }", None), - ("(class { set a(foo){} static get a(){} get a(){} static set a(bar){} })", None), - ("class A { get a(){} set a(foo){} static get b(){} static set b(bar){} }", Some(serde_json::json!(["setBeforeGet"]))), - ("(class { set [a+b](foo){} get [a-b](){} get [a+b](){} set [a-b](bar){} })", None), - ("({ get a(){}, set a(foo){}, get b(){}, c: function(){}, set b(bar){} })", None), - ("({ get a(){}, get b(){}, set a(foo){} })", None), - ("({ set a(foo){}, get [a](){}, get a(){} })", None), - ("({ set [a](foo){}, set a(bar){}, get [a](){} })", None), - ("({ get a(){}, set a(foo){}, set b(bar){}, get b(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { get a(){} static set b(foo){} static get b(){} set a(foo){} }", None), - ("(class { static get a(){} set a(foo){} static set a(bar){} })", None), - ("class A { set a(foo){} get a(){} static get a(){} static set a(bar){} }", Some(serde_json::json!(["setBeforeGet"]))), - ("({ get a(){}, a: 1, set a(foo){} })", None), - ("({ a(){}, set a(foo){}, get a(){} })", Some(serde_json::json!(["getBeforeSet"]))), - ("class A { get a(){} a(){} set a(foo){} }", None), - ("class A { get a(){} a; set a(foo){} }", None), // { "ecmaVersion": 2022 }, - ("class faoo { static set #abc(foo){} static get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ("({ get a(){}, + ("({ get a(){}, b:1, set a(foo){} })", None), + ("({ set 'abc'(foo){}, b:1, get 'abc'(){} })", None), + ("({ get [a](){}, b:1, set [a](foo){} })", None), + ("class A { get abc(){} b(){} set abc(foo){} }", None), + ("(class { set abc(foo){} b(){} get abc(){} })", None), + ("class A { static set a(foo){} b(){} static get a(){} }", None), + ("(class { static get 123(){} b(){} static set 123(foo){} })", None), + ("class A { static get [a](){} b(){} static set [a](foo){} }", None), + ("class A { get '#abc'(){} b(){} set '#abc'(foo){} }", None), + ("class A { get #abc(){} b(){} set #abc(foo){} }", None), + ("({ set a(foo){}, get a(){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ get 123(){}, set 123(foo){} })", Some(serde_json::json!(["setBeforeGet"]))), + ("({ get [a](){}, set [a](foo){} })", Some(serde_json::json!(["setBeforeGet"]))), + ("class A { set abc(foo){} get abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ( + "(class { get [`abc`](){} set [`abc`](foo){} })", + Some(serde_json::json!(["setBeforeGet"])), + ), + ( + "class A { static get a(){} static set a(foo){} }", + Some(serde_json::json!(["setBeforeGet"])), + ), + ( + "(class { static set 'abc'(foo){} static get 'abc'(){} })", + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class A { static set [abc](foo){} static get [abc](){} }", + Some(serde_json::json!(["getBeforeSet"])), + ), + ("class A { set '#abc'(foo){} get '#abc'(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ("class A { set #abc(foo){} get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ("({ get a(){}, b: 1, set a(foo){} })", Some(serde_json::json!(["anyOrder"]))), + ("({ get a(){}, b: 1, set a(foo){} })", Some(serde_json::json!(["setBeforeGet"]))), + ("({ get a(){}, b: 1, set a(foo){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("class A { set a(foo){} b(){} get a(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ( + "(class { static set a(foo){} b(){} static get a(){} })", + Some(serde_json::json!(["setBeforeGet"])), + ), + ("({ get 'abc'(){}, d(){}, set 'abc'(foo){} })", None), + ("({ set ''(foo){}, get [''](){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("class A { set abc(foo){} get 'abc'(){} }", Some(serde_json::json!(["getBeforeSet"]))), + ("(class { set [`abc`](foo){} get abc(){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ set ['abc'](foo){}, get [`abc`](){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ set 123(foo){}, get [123](){} })", Some(serde_json::json!(["getBeforeSet"]))), + ( + "class A { static set '123'(foo){} static get 123(){} }", + Some(serde_json::json!(["getBeforeSet"])), + ), + ("(class { set [a+b](foo){} get [a+b](){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ set [f(a)](foo){}, get [f(a)](){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("({ get a(){}, b: 1, set a(foo){}, set c(foo){}, d(){}, get c(){} })", None), + ("({ get a(){}, set b(foo){}, set a(bar){}, get b(){} })", None), + ("({ get a(){}, set [a](foo){}, set a(bar){}, get [a](){} })", None), + ( + "({ a(){}, set b(foo){}, ...c, get b(){}, set c(bar){}, get c(){} })", + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "({ set [a](foo){}, get [a](){}, set [-a](bar){}, get [-a](){} })", + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class A { get a(){} constructor (){} set a(foo){} get b(){} static c(){} set b(bar){} }", + None, + ), + ("(class { set a(foo){} static get a(){} get a(){} static set a(bar){} })", None), + ( + "class A { get a(){} set a(foo){} static get b(){} static set b(bar){} }", + Some(serde_json::json!(["setBeforeGet"])), + ), + ("(class { set [a+b](foo){} get [a-b](){} get [a+b](){} set [a-b](bar){} })", None), + ("({ get a(){}, set a(foo){}, get b(){}, c: function(){}, set b(bar){} })", None), + ("({ get a(){}, get b(){}, set a(foo){} })", None), + ("({ set a(foo){}, get [a](){}, get a(){} })", None), + ("({ set [a](foo){}, set a(bar){}, get [a](){} })", None), + ( + "({ get a(){}, set a(foo){}, set b(bar){}, get b(){} })", + Some(serde_json::json!(["getBeforeSet"])), + ), + ("class A { get a(){} static set b(foo){} static get b(){} set a(foo){} }", None), + ("(class { static get a(){} set a(foo){} static set a(bar){} })", None), + ( + "class A { set a(foo){} get a(){} static get a(){} static set a(bar){} }", + Some(serde_json::json!(["setBeforeGet"])), + ), + ("({ get a(){}, a: 1, set a(foo){} })", None), + ("({ a(){}, set a(foo){}, get a(){} })", Some(serde_json::json!(["getBeforeSet"]))), + ("class A { get a(){} a(){} set a(foo){} }", None), + ("class A { get a(){} a; set a(foo){} }", None), // { "ecmaVersion": 2022 }, + ( + "class faoo { static set #abc(foo){} static get #abc(){} }", + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "({ get a(){}, b: 1, set a(foo){} - })", None), - ("class A { static set a(foo){} b(){} static get + })", + None, + ), + ( + "class A { static set a(foo){} b(){} static get a(){} - }", None), - ( - "const foo = { + }", + None, + ), + ( + "const foo = { set [false](value) { this.val = value; }, @@ -571,10 +622,10 @@ fn test() { return this.val; }, }", - Some(serde_json::json!(["getBeforeSet"])) - ), - ( - "const foo = { + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "const foo = { get '/a/g'() { return this.val; }, @@ -582,11 +633,14 @@ fn test() { this.val = value; }, };", - Some(serde_json::json!(["setBeforeGet"])) - ), - ("class foo { static set #abc(foo){} static get #abc(){} }", Some(serde_json::json!(["getBeforeSet"]))), - ( - "class foo { + Some(serde_json::json!(["setBeforeGet"])), + ), + ( + "class foo { static set #abc(foo){} static get #abc(){} }", + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class foo { static set ['#a+b'](val) { } @@ -594,10 +648,10 @@ fn test() { } }", - Some(serde_json::json!(["getBeforeSet"])), - ), - ( - "class foo { + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class foo { set [() => {}](val) { } @@ -605,10 +659,10 @@ fn test() { } }", - Some(serde_json::json!(["getBeforeSet"])), - ), - ( - "class foo { + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class foo { static set [23](val) { } @@ -616,10 +670,10 @@ fn test() { } }", - Some(serde_json::json!(["getBeforeSet"])), - ), - ( - "class jj { + Some(serde_json::json!(["getBeforeSet"])), + ), + ( + "class jj { static set [23](val) { } @@ -633,9 +687,9 @@ fn test() { } }", - Some(serde_json::json!(["getBeforeSet"])), - ) - ]; + Some(serde_json::json!(["getBeforeSet"])), + ), + ]; Tester::new(GroupedAccessorPairs::NAME, GroupedAccessorPairs::PLUGIN, pass, fail) .test_and_snapshot(); diff --git a/crates/oxc_linter/src/rules/eslint/guard_for_in.rs b/crates/oxc_linter/src/rules/eslint/guard_for_in.rs index 8608e80747de04..43efbbee07dde4 100644 --- a/crates/oxc_linter/src/rules/eslint/guard_for_in.rs +++ b/crates/oxc_linter/src/rules/eslint/guard_for_in.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::Statement, AstKind}; +use oxc_ast::{AstKind, ast::Statement}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn guard_for_in_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Require `for-in` loops to include an `if` statement") diff --git a/crates/oxc_linter/src/rules/eslint/init_declarations.rs b/crates/oxc_linter/src/rules/eslint/init_declarations.rs index 1bd253ff566af9..34de0f09432938 100644 --- a/crates/oxc_linter/src/rules/eslint/init_declarations.rs +++ b/crates/oxc_linter/src/rules/eslint/init_declarations.rs @@ -1,16 +1,16 @@ use oxc_ast::{ + AstKind, ast::{ BindingPatternKind, ForInStatement, ForOfStatement, ForStatementLeft, VariableDeclarationKind, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn init_declarations_diagnostic(span: Span, mode: &Mode, identifier_name: &str) -> OxcDiagnostic { let msg = if Mode::Always == *mode { @@ -32,11 +32,7 @@ enum Mode { impl Mode { pub fn from(raw: &str) -> Self { - if raw == "never" { - Self::Never - } else { - Self::Always - } + if raw == "never" { Self::Never } else { Self::Always } } } diff --git a/crates/oxc_linter/src/rules/eslint/max_depth.rs b/crates/oxc_linter/src/rules/eslint/max_depth.rs index 7132f78c77a0c1..df698ed1125875 100644 --- a/crates/oxc_linter/src/rules/eslint/max_depth.rs +++ b/crates/oxc_linter/src/rules/eslint/max_depth.rs @@ -6,7 +6,7 @@ use oxc_span::GetSpan; use oxc_span::Span; use serde_json::Value; -use crate::{ast_util::is_function_node, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::is_function_node, context::LintContext, rule::Rule}; fn max_depth_diagnostic(num: usize, max: usize, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Blocks are nested too deeply ({num}). Maximum allowed is {max}.")) @@ -157,34 +157,85 @@ fn test() { use crate::tester::Tester; let pass = vec![ - ("function foo() { if (true) { if (false) { if (true) { } } } }", Some(serde_json::json!([3]))), - ("function foo() { if (true) { } else if (false) { } else if (true) { } else if (false) {} }", Some(serde_json::json!([3]))), - ("var foo = () => { if (true) { if (false) { if (true) { } } } }", Some(serde_json::json!([3]))), // { "ecmaVersion": 6 }, + ( + "function foo() { if (true) { if (false) { if (true) { } } } }", + Some(serde_json::json!([3])), + ), + ( + "function foo() { if (true) { } else if (false) { } else if (true) { } else if (false) {} }", + Some(serde_json::json!([3])), + ), + ( + "var foo = () => { if (true) { if (false) { if (true) { } } } }", + Some(serde_json::json!([3])), + ), // { "ecmaVersion": 6 }, ("function foo() { if (true) { if (false) { if (true) { } } } }", None), - ("function foo() { if (true) { if (false) { if (true) { } } } }", Some(serde_json::json!([{ "max": 3 }]))), + ( + "function foo() { if (true) { if (false) { if (true) { } } } }", + Some(serde_json::json!([{ "max": 3 }])), + ), ("class C { static { if (1) { if (2) {} } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("class C { static { if (1) { if (2) {} } if (1) { if (2) {} } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("class C { static { if (1) { if (2) {} } } static { if (1) { if (2) {} } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, + ( + "class C { static { if (1) { if (2) {} } if (1) { if (2) {} } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 }, + ( + "class C { static { if (1) { if (2) {} } } static { if (1) { if (2) {} } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 }, ("if (1) { class C { static { if (1) { if (2) {} } } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("function foo() { if (1) { class C { static { if (1) { if (2) {} } } } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("function foo() { if (1) { if (2) { class C { static { if (1) { if (2) {} } if (1) { if (2) {} } } } } } if (1) { if (2) {} } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 } + ( + "function foo() { if (1) { class C { static { if (1) { if (2) {} } } } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 }, + ( + "function foo() { if (1) { if (2) { class C { static { if (1) { if (2) {} } if (1) { if (2) {} } } } } } if (1) { if (2) {} } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 } ]; let fail = vec![ - ("function foo() { if (true) { if (false) { if (true) { } } } }", Some(serde_json::json!([2]))), - ("var foo = () => { if (true) { if (false) { if (true) { } } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 6 }, + ( + "function foo() { if (true) { if (false) { if (true) { } } } }", + Some(serde_json::json!([2])), + ), + ( + "var foo = () => { if (true) { if (false) { if (true) { } } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 6 }, ("function foo() { if (true) {} else { for(;;) {} } }", Some(serde_json::json!([1]))), ("function foo() { while (true) { if (true) {} } }", Some(serde_json::json!([1]))), ("function foo() { for (let x of foo) { if (true) {} } }", Some(serde_json::json!([1]))), // { "ecmaVersion": 6 }, - ("function foo() { while (true) { if (true) { if (false) { } } } }", Some(serde_json::json!([1]))), - ("function foo() { if (true) { if (false) { if (true) { if (false) { if (true) { } } } } } }", None), - ("function foo() { if (true) { if (false) { if (true) { } } } }", Some(serde_json::json!([{ "max": 2 }]))), - ("function foo() { if (a) { if (b) { if (c) { if (d) { if (e) {} } } } } }", Some(serde_json::json!([{}]))), + ( + "function foo() { while (true) { if (true) { if (false) { } } } }", + Some(serde_json::json!([1])), + ), + ( + "function foo() { if (true) { if (false) { if (true) { if (false) { if (true) { } } } } } }", + None, + ), + ( + "function foo() { if (true) { if (false) { if (true) { } } } }", + Some(serde_json::json!([{ "max": 2 }])), + ), + ( + "function foo() { if (a) { if (b) { if (c) { if (d) { if (e) {} } } } } }", + Some(serde_json::json!([{}])), + ), ("function foo() { if (true) {} }", Some(serde_json::json!([{ "max": 0 }]))), ("class C { static { if (1) { if (2) { if (3) {} } } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("if (1) { class C { static { if (1) { if (2) { if (3) {} } } } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("function foo() { if (1) { class C { static { if (1) { if (2) { if (3) {} } } } } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 }, - ("function foo() { if (1) { class C { static { if (1) { if (2) {} } } } if (2) { if (3) {} } } }", Some(serde_json::json!([2]))), // { "ecmaVersion": 2022 } + ( + "if (1) { class C { static { if (1) { if (2) { if (3) {} } } } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 }, + ( + "function foo() { if (1) { class C { static { if (1) { if (2) { if (3) {} } } } } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 }, + ( + "function foo() { if (1) { class C { static { if (1) { if (2) {} } } } if (2) { if (3) {} } } }", + Some(serde_json::json!([2])), + ), // { "ecmaVersion": 2022 } ]; Tester::new(MaxDepth::NAME, MaxDepth::PLUGIN, pass, fail).test_and_snapshot(); diff --git a/crates/oxc_linter/src/rules/eslint/max_lines_per_function.rs b/crates/oxc_linter/src/rules/eslint/max_lines_per_function.rs index 2e71cd295ef7bc..e938301d93099d 100644 --- a/crates/oxc_linter/src/rules/eslint/max_lines_per_function.rs +++ b/crates/oxc_linter/src/rules/eslint/max_lines_per_function.rs @@ -8,11 +8,11 @@ use oxc_span::{GetSpan, Span}; use serde_json::Value; use crate::{ + AstNode, ast_util::{get_function_name_with_kind, is_function_node, iter_outer_expressions}, context::LintContext, rule::Rule, utils::count_comment_lines, - AstNode, }; fn max_lines_per_function_diagnostic( diff --git a/crates/oxc_linter/src/rules/eslint/max_nested_callbacks.rs b/crates/oxc_linter/src/rules/eslint/max_nested_callbacks.rs index 205fd63cd0ea9e..d49e86b422a9f3 100644 --- a/crates/oxc_linter/src/rules/eslint/max_nested_callbacks.rs +++ b/crates/oxc_linter/src/rules/eslint/max_nested_callbacks.rs @@ -6,10 +6,10 @@ use oxc_span::{GetSpan, Span}; use serde_json::Value; use crate::{ + AstNode, ast_util::{is_function_node, iter_outer_expressions}, context::LintContext, rule::Rule, - AstNode, }; fn max_nested_callbacks_diagnostic(num: usize, max: usize, span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/eslint/max_params.rs b/crates/oxc_linter/src/rules/eslint/max_params.rs index d4af06e397c219..573bf5ff72eebe 100644 --- a/crates/oxc_linter/src/rules/eslint/max_params.rs +++ b/crates/oxc_linter/src/rules/eslint/max_params.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn max_params_diagnostic(x0: &str, span1: Span) -> OxcDiagnostic { OxcDiagnostic::warn(x0.to_string()) diff --git a/crates/oxc_linter/src/rules/eslint/new_cap.rs b/crates/oxc_linter/src/rules/eslint/new_cap.rs index b97e70afe57724..28a6121b0ea4ed 100644 --- a/crates/oxc_linter/src/rules/eslint/new_cap.rs +++ b/crates/oxc_linter/src/rules/eslint/new_cap.rs @@ -1,7 +1,7 @@ -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; use oxc_ast::{ - ast::{ChainElement, ComputedMemberExpression, Expression}, AstKind, + ast::{ChainElement, ComputedMemberExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/eslint/no_alert.rs b/crates/oxc_linter/src/rules/eslint/no_alert.rs index f59ca4bb7ff360..836cf5b1b8bdff 100644 --- a/crates/oxc_linter/src/rules/eslint/no_alert.rs +++ b/crates/oxc_linter/src/rules/eslint/no_alert.rs @@ -1,10 +1,10 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::ScopeId; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_alert_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("`alert`, `confirm` and `prompt` functions are not allowed") diff --git a/crates/oxc_linter/src/rules/eslint/no_array_constructor.rs b/crates/oxc_linter/src/rules/eslint/no_array_constructor.rs index 970d178b05e36e..4b44c984b23159 100644 --- a/crates/oxc_linter/src/rules/eslint/no_array_constructor.rs +++ b/crates/oxc_linter/src/rules/eslint/no_array_constructor.rs @@ -1,10 +1,10 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::IsGlobalReference; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_array_constructor_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Do not use `new` to create arrays") diff --git a/crates/oxc_linter/src/rules/eslint/no_async_promise_executor.rs b/crates/oxc_linter/src/rules/eslint/no_async_promise_executor.rs index 5ec7a30b45f429..87bf3131cff598 100644 --- a/crates/oxc_linter/src/rules/eslint/no_async_promise_executor.rs +++ b/crates/oxc_linter/src/rules/eslint/no_async_promise_executor.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{Argument, Expression}, AstKind, + ast::{Argument, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_async_promise_executor_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Promise executor functions should not be `async`.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_await_in_loop.rs b/crates/oxc_linter/src/rules/eslint/no_await_in_loop.rs index 637fae46569748..90a3968e622841 100644 --- a/crates/oxc_linter/src/rules/eslint/no_await_in_loop.rs +++ b/crates/oxc_linter/src/rules/eslint/no_await_in_loop.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{Expression, Statement}, AstKind, + ast::{Expression, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_await_in_loop_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected `await` inside a loop.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_bitwise.rs b/crates/oxc_linter/src/rules/eslint/no_bitwise.rs index 83aba0ac3b4883..64064ad67a8acd 100644 --- a/crates/oxc_linter/src/rules/eslint/no_bitwise.rs +++ b/crates/oxc_linter/src/rules/eslint/no_bitwise.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use oxc_syntax::operator::BinaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_bitwise_diagnostic(x0: &str, span1: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Unexpected use of {x0:?}")) diff --git a/crates/oxc_linter/src/rules/eslint/no_caller.rs b/crates/oxc_linter/src/rules/eslint/no_caller.rs index d2928dc0e1c03c..f940417654c1ac 100644 --- a/crates/oxc_linter/src/rules/eslint/no_caller.rs +++ b/crates/oxc_linter/src/rules/eslint/no_caller.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::MemberExpression, AstKind}; +use oxc_ast::{AstKind, ast::MemberExpression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_caller_diagnostic(span: Span, method_name: &str) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Do not use `arguments.{method_name}`")) diff --git a/crates/oxc_linter/src/rules/eslint/no_case_declarations.rs b/crates/oxc_linter/src/rules/eslint/no_case_declarations.rs index 3ba7bc21ed4bca..f9d93458e9a582 100644 --- a/crates/oxc_linter/src/rules/eslint/no_case_declarations.rs +++ b/crates/oxc_linter/src/rules/eslint/no_case_declarations.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{Statement, VariableDeclarationKind}, AstKind, + ast::{Statement, VariableDeclarationKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_case_declarations_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected lexical declaration in case block.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_compare_neg_zero.rs b/crates/oxc_linter/src/rules/eslint/no_compare_neg_zero.rs index 5700878318f3b1..157d5ecf70f1e3 100644 --- a/crates/oxc_linter/src/rules/eslint/no_compare_neg_zero.rs +++ b/crates/oxc_linter/src/rules/eslint/no_compare_neg_zero.rs @@ -1,10 +1,10 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{BinaryOperator, UnaryOperator}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_compare_neg_zero_diagnostic(operator: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Do not use the {operator} operator to compare against -0.")) diff --git a/crates/oxc_linter/src/rules/eslint/no_cond_assign.rs b/crates/oxc_linter/src/rules/eslint/no_cond_assign.rs index e5626bdac20316..1e51805a90e570 100644 --- a/crates/oxc_linter/src/rules/eslint/no_cond_assign.rs +++ b/crates/oxc_linter/src/rules/eslint/no_cond_assign.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{AssignmentExpression, Expression}, AstKind, + ast::{AssignmentExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_cond_assign_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Expected a conditional expression and instead saw an assignment") diff --git a/crates/oxc_linter/src/rules/eslint/no_console.rs b/crates/oxc_linter/src/rules/eslint/no_console.rs index e1986345fbda84..2b4bd6703f2441 100644 --- a/crates/oxc_linter/src/rules/eslint/no_console.rs +++ b/crates/oxc_linter/src/rules/eslint/no_console.rs @@ -1,13 +1,13 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, GetSpan, Span}; use crate::{ + AstNode, context::LintContext, fixer::{RuleFix, RuleFixer}, rule::Rule, - AstNode, }; fn no_console_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/eslint/no_constant_binary_expression.rs b/crates/oxc_linter/src/rules/eslint/no_constant_binary_expression.rs index 21c7ee0ba901fd..ff9313e41518c5 100644 --- a/crates/oxc_linter/src/rules/eslint/no_constant_binary_expression.rs +++ b/crates/oxc_linter/src/rules/eslint/no_constant_binary_expression.rs @@ -1,14 +1,14 @@ -use oxc_ast::{ast::*, AstKind}; +use oxc_ast::{AstKind, ast::*}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use oxc_syntax::operator::{AssignmentOperator, BinaryOperator, LogicalOperator, UnaryOperator}; use crate::{ + AstNode, ast_util::{self, IsConstant}, context::LintContext, rule::Rule, - AstNode, }; /// `https://eslint.org/docs/latest/rules/no-constant-binary-expression` diff --git a/crates/oxc_linter/src/rules/eslint/no_constant_condition.rs b/crates/oxc_linter/src/rules/eslint/no_constant_condition.rs index 691b1f02adfc84..f0dbf46af2d42f 100644 --- a/crates/oxc_linter/src/rules/eslint/no_constant_condition.rs +++ b/crates/oxc_linter/src/rules/eslint/no_constant_condition.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{ast_util::IsConstant, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::IsConstant, context::LintContext, rule::Rule}; fn no_constant_condition_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected constant condition") diff --git a/crates/oxc_linter/src/rules/eslint/no_constructor_return.rs b/crates/oxc_linter/src/rules/eslint/no_constructor_return.rs index 166aa2f4217a1e..03b9463bf1df41 100644 --- a/crates/oxc_linter/src/rules/eslint/no_constructor_return.rs +++ b/crates/oxc_linter/src/rules/eslint/no_constructor_return.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{MethodDefinition, MethodDefinitionKind}, AstKind, + ast::{MethodDefinition, MethodDefinitionKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::NodeId; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_constructor_return_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected return statement in constructor.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_continue.rs b/crates/oxc_linter/src/rules/eslint/no_continue.rs index 97e3eb6ed73e49..1435e94764601c 100644 --- a/crates/oxc_linter/src/rules/eslint/no_continue.rs +++ b/crates/oxc_linter/src/rules/eslint/no_continue.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_continue_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected use of `continue` statement.") diff --git a/crates/oxc_linter/src/rules/eslint/no_control_regex.rs b/crates/oxc_linter/src/rules/eslint/no_control_regex.rs index 74697f2129bc38..0cd46cb3f536db 100644 --- a/crates/oxc_linter/src/rules/eslint/no_control_regex.rs +++ b/crates/oxc_linter/src/rules/eslint/no_control_regex.rs @@ -1,16 +1,16 @@ use itertools::Itertools as _; use oxc_allocator::Allocator; -use oxc_ast::{ast::Argument, AstKind}; +use oxc_ast::{AstKind, ast::Argument}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_regular_expression::{ - ast::{CapturingGroup, Character, Pattern}, - visit::{walk, Visit}, ConstructorParser, Options, + ast::{CapturingGroup, Character, Pattern}, + visit::{Visit, walk}, }; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_control_regex_diagnostic(count: usize, regex: &str, span: Span) -> OxcDiagnostic { debug_assert!(count > 0); diff --git a/crates/oxc_linter/src/rules/eslint/no_debugger.rs b/crates/oxc_linter/src/rules/eslint/no_debugger.rs index 532561862dd9f3..0dc633229b8d31 100644 --- a/crates/oxc_linter/src/rules/eslint/no_debugger.rs +++ b/crates/oxc_linter/src/rules/eslint/no_debugger.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_debugger_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("`debugger` statement is not allowed").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_delete_var.rs b/crates/oxc_linter/src/rules/eslint/no_delete_var.rs index c355a23a908b19..2e3b83a90a3e7e 100644 --- a/crates/oxc_linter/src/rules/eslint/no_delete_var.rs +++ b/crates/oxc_linter/src/rules/eslint/no_delete_var.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use oxc_syntax::operator::UnaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_delete_var_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("variables should not be deleted").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_div_regex.rs b/crates/oxc_linter/src/rules/eslint/no_div_regex.rs index d8839af7b125f7..cbb9a31f14b943 100644 --- a/crates/oxc_linter/src/rules/eslint/no_div_regex.rs +++ b/crates/oxc_linter/src/rules/eslint/no_div_regex.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_regular_expression::ast::{CharacterKind, Term}; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_div_regex_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("A regular expression literal can be confused with '/='.") diff --git a/crates/oxc_linter/src/rules/eslint/no_dupe_else_if.rs b/crates/oxc_linter/src/rules/eslint/no_dupe_else_if.rs index 753b8a084cdc35..bf652c4228890c 100644 --- a/crates/oxc_linter/src/rules/eslint/no_dupe_else_if.rs +++ b/crates/oxc_linter/src/rules/eslint/no_dupe_else_if.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{Expression, Statement}, AstKind, + ast::{Expression, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{ContentEq, GetSpan, Span}; use oxc_syntax::operator::LogicalOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_dupe_else_if_diagnostic(first_test: Span, second_test: Span) -> OxcDiagnostic { OxcDiagnostic::warn("duplicate conditions in if-else-if chains") diff --git a/crates/oxc_linter/src/rules/eslint/no_dupe_keys.rs b/crates/oxc_linter/src/rules/eslint/no_dupe_keys.rs index 4db0d44431fd0c..7772cbf8418930 100644 --- a/crates/oxc_linter/src/rules/eslint/no_dupe_keys.rs +++ b/crates/oxc_linter/src/rules/eslint/no_dupe_keys.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{ObjectPropertyKind, PropertyKey, PropertyKind}, AstKind, + ast::{ObjectPropertyKind, PropertyKey, PropertyKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use rustc_hash::{FxBuildHasher, FxHashMap}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_dupe_keys_diagnostic(first: Span, second: Span, key: &str) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Duplicate key '{key}'")) diff --git a/crates/oxc_linter/src/rules/eslint/no_duplicate_case.rs b/crates/oxc_linter/src/rules/eslint/no_duplicate_case.rs index fc4ef77b8bc68d..98c9cf617adb98 100644 --- a/crates/oxc_linter/src/rules/eslint/no_duplicate_case.rs +++ b/crates/oxc_linter/src/rules/eslint/no_duplicate_case.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{ContentEq, GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_duplicate_case_diagnostic(first: Span, second: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Duplicate case label") diff --git a/crates/oxc_linter/src/rules/eslint/no_else_return.rs b/crates/oxc_linter/src/rules/eslint/no_else_return.rs index fb96a6b18ce53d..2f8d97e77dbe38 100644 --- a/crates/oxc_linter/src/rules/eslint/no_else_return.rs +++ b/crates/oxc_linter/src/rules/eslint/no_else_return.rs @@ -1,10 +1,10 @@ -use oxc_ast::{ast::Statement, AstKind}; +use oxc_ast::{AstKind, ast::Statement}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::{ScopeId, ScopeTree}; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct NoElseReturn { @@ -281,11 +281,7 @@ fn naive_has_return(node: &Statement) -> Option { match node { Statement::BlockStatement(block) => { let last_child = block.body.last()?; - if let Statement::ReturnStatement(r) = last_child { - Some(r.span) - } else { - None - } + if let Statement::ReturnStatement(r) = last_child { Some(r.span) } else { None } } Statement::ReturnStatement(r) => Some(r.span), _ => None, diff --git a/crates/oxc_linter/src/rules/eslint/no_empty.rs b/crates/oxc_linter/src/rules/eslint/no_empty.rs index 35e518aaa0b9de..aed70397dcc931 100644 --- a/crates/oxc_linter/src/rules/eslint/no_empty.rs +++ b/crates/oxc_linter/src/rules/eslint/no_empty.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::BlockStatement, AstKind}; +use oxc_ast::{AstKind, ast::BlockStatement}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_empty_diagnostic(stmt_kind: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected empty block statements") diff --git a/crates/oxc_linter/src/rules/eslint/no_empty_character_class.rs b/crates/oxc_linter/src/rules/eslint/no_empty_character_class.rs index 9c8e4bc823e0e0..f508197c96fba9 100644 --- a/crates/oxc_linter/src/rules/eslint/no_empty_character_class.rs +++ b/crates/oxc_linter/src/rules/eslint/no_empty_character_class.rs @@ -5,11 +5,11 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_regular_expression::{ ast::CharacterClass, - visit::{walk::walk_character_class, Visit}, + visit::{Visit, walk::walk_character_class}, }; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_empty_character_class_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Empty character class will not match anything") diff --git a/crates/oxc_linter/src/rules/eslint/no_empty_function.rs b/crates/oxc_linter/src/rules/eslint/no_empty_function.rs index 17ac1dd27f0446..e6ae359c41ca29 100644 --- a/crates/oxc_linter/src/rules/eslint/no_empty_function.rs +++ b/crates/oxc_linter/src/rules/eslint/no_empty_function.rs @@ -1,14 +1,14 @@ use std::borrow::Cow; use oxc_ast::{ - ast::{IdentifierName, IdentifierReference, MethodDefinitionKind}, AstKind, + ast::{IdentifierName, IdentifierReference, MethodDefinitionKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_empty_function_diagnostic>( span: Span, diff --git a/crates/oxc_linter/src/rules/eslint/no_empty_pattern.rs b/crates/oxc_linter/src/rules/eslint/no_empty_pattern.rs index 0874e3ec1c1a14..fe044c548bcb1f 100644 --- a/crates/oxc_linter/src/rules/eslint/no_empty_pattern.rs +++ b/crates/oxc_linter/src/rules/eslint/no_empty_pattern.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_empty_pattern_diagnostic(pattern_type: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Empty {pattern_type} binding pattern")) diff --git a/crates/oxc_linter/src/rules/eslint/no_empty_static_block.rs b/crates/oxc_linter/src/rules/eslint/no_empty_static_block.rs index cf88fc495d94cf..58d83de0d2f604 100644 --- a/crates/oxc_linter/src/rules/eslint/no_empty_static_block.rs +++ b/crates/oxc_linter/src/rules/eslint/no_empty_static_block.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_empty_static_block_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected empty static blocks") diff --git a/crates/oxc_linter/src/rules/eslint/no_eq_null.rs b/crates/oxc_linter/src/rules/eslint/no_eq_null.rs index b5f1ef6f1e7dcb..d4409255b15c26 100644 --- a/crates/oxc_linter/src/rules/eslint/no_eq_null.rs +++ b/crates/oxc_linter/src/rules/eslint/no_eq_null.rs @@ -6,7 +6,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::BinaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_eq_null_diagnostic(span: Span, suggested_operator: &str) -> OxcDiagnostic { OxcDiagnostic::warn("Do not use `null` comparisons without type-checking operators.") diff --git a/crates/oxc_linter/src/rules/eslint/no_eval.rs b/crates/oxc_linter/src/rules/eslint/no_eval.rs index dc32bcdd5f2ef7..b99afd9e7ef364 100644 --- a/crates/oxc_linter/src/rules/eslint/no_eval.rs +++ b/crates/oxc_linter/src/rules/eslint/no_eval.rs @@ -4,11 +4,11 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use crate::{ + AstNode, ast_util::{self}, config::GlobalValue, context::LintContext, rule::Rule, - AstNode, }; fn no_eval_diagnostic(span: Span) -> OxcDiagnostic { @@ -250,13 +250,28 @@ fn test() { ("window.eval('foo')", None, None, None), ("window.eval('foo')", None, None, Some(PathBuf::from("foo.cjs"))), ("window.noeval('foo')", None, env_with_browser(), None), - ("function foo() { var eval = 'foo'; window[eval]('foo') }", None, env_with_browser(), None), + ( + "function foo() { var eval = 'foo'; window[eval]('foo') }", + None, + env_with_browser(), + None, + ), ("global.eval('foo')", None, None, None), ("global.noeval('foo')", None, None, Some(PathBuf::from("foo.cjs"))), - ("function foo() { var eval = 'foo'; global[eval]('foo') }", None, env_with_node(), Some(PathBuf::from("foo.cjs"))), + ( + "function foo() { var eval = 'foo'; global[eval]('foo') }", + None, + env_with_node(), + Some(PathBuf::from("foo.cjs")), + ), // ("globalThis.eval('foo')", None, None, None), // { "ecmaVersion": 2017 }, globalThis is not supported ("globalThis.noneval('foo')", None, None, None), - ("function foo() { var eval = 'foo'; globalThis[eval]('foo') }", None, env_with_browser(), None), + ( + "function foo() { var eval = 'foo'; globalThis[eval]('foo') }", + None, + env_with_browser(), + None, + ), ("this.noeval('foo');", None, None, None), ("function foo() { 'use strict'; this.eval('foo'); }", None, None, None), ("'use strict'; this.eval('foo');", None, None, None), // { "parserOptions": { "ecmaFeatures": { "globalReturn": true } } }, @@ -270,12 +285,27 @@ fn test() { ("class C extends function () { this.eval('foo'); } {}", None, None, None), // { "ecmaVersion": 6 }, ("class A { foo() { this.eval(); } }", None, None, None), // { "ecmaVersion": 6 }, ("class A { static foo() { this.eval(); } }", None, None, None), // { "ecmaVersion": 6 }, - ("class A { field = this.eval(); }", None, None, None), // { "ecmaVersion": 2022 }, + ("class A { field = this.eval(); }", None, None, None), // { "ecmaVersion": 2022 }, ("class A { field = () => this.eval(); }", None, None, None), // { "ecmaVersion": 2022 }, ("class A { static { this.eval(); } }", None, None, None), // { "ecmaVersion": 2022 }, - ("array.findLast(function (x) { return this.eval.includes(x); }, { eval: ['foo', 'bar'] });", None, None, None), - ("callbacks.findLastIndex(function (cb) { return cb(this.eval); }, this);", None, None, None), - ("['1+1'].flatMap(function (str) { return this.eval(str); }, new Evaluator);", None, None, None), + ( + "array.findLast(function (x) { return this.eval.includes(x); }, { eval: ['foo', 'bar'] });", + None, + None, + None, + ), + ( + "callbacks.findLastIndex(function (cb) { return cb(this.eval); }, this);", + None, + None, + None, + ), + ( + "['1+1'].flatMap(function (str) { return this.eval(str); }, new Evaluator);", + None, + None, + None, + ), ("(0, eval)('foo')", allow_indirect_with_true(), None, None), ("(0, window.eval)('foo')", allow_indirect_with_true(), env_with_browser(), None), ("(0, window['eval'])('foo')", allow_indirect_with_true(), env_with_browser(), None), @@ -291,13 +321,33 @@ fn test() { ("function foo() { this.eval('foo') }", allow_indirect_with_true(), None, None), ("(0, globalThis.eval)('foo')", allow_indirect_with_true(), env_with_browser(), None), ("(0, globalThis['eval'])('foo')", allow_indirect_with_true(), env_with_browser(), None), - ("var EVAL = globalThis.eval; EVAL('foo')", allow_indirect_with_true(), env_with_browser(), None), - ("function foo() { globalThis.eval('foo') }", allow_indirect_with_true(), env_with_browser(), None), - ("globalThis.globalThis.eval('foo');", allow_indirect_with_true(), env_with_browser(), None), + ( + "var EVAL = globalThis.eval; EVAL('foo')", + allow_indirect_with_true(), + env_with_browser(), + None, + ), + ( + "function foo() { globalThis.eval('foo') }", + allow_indirect_with_true(), + env_with_browser(), + None, + ), + ( + "globalThis.globalThis.eval('foo');", + allow_indirect_with_true(), + env_with_browser(), + None, + ), ("eval?.('foo')", allow_indirect_with_true(), None, None), ("window?.eval('foo')", allow_indirect_with_true(), env_with_browser(), None), ("(window?.eval)('foo')", allow_indirect_with_true(), env_with_browser(), None), - ("sinon.test(/** @this sinon.Sandbox */function() { this.eval(); });", None, None, Some(PathBuf::from("foo.cjs"))) + ( + "sinon.test(/** @this sinon.Sandbox */function() { this.eval(); });", + None, + None, + Some(PathBuf::from("foo.cjs")), + ), ]; let fail = vec![ diff --git a/crates/oxc_linter/src/rules/eslint/no_extend_native.rs b/crates/oxc_linter/src/rules/eslint/no_extend_native.rs index ce787ce2a69119..9c80f4bf223db7 100644 --- a/crates/oxc_linter/src/rules/eslint/no_extend_native.rs +++ b/crates/oxc_linter/src/rules/eslint/no_extend_native.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{CallExpression, ChainElement, Expression, MemberExpression}, AstKind, + ast::{CallExpression, ChainElement, Expression, MemberExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, ContentEq, GetSpan}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct NoExtendNative(Box); diff --git a/crates/oxc_linter/src/rules/eslint/no_extra_boolean_cast.rs b/crates/oxc_linter/src/rules/eslint/no_extra_boolean_cast.rs index 2196472e7a9680..ba94bef18e0655 100644 --- a/crates/oxc_linter/src/rules/eslint/no_extra_boolean_cast.rs +++ b/crates/oxc_linter/src/rules/eslint/no_extra_boolean_cast.rs @@ -5,7 +5,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{LogicalOperator, UnaryOperator}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_extra_double_negation_cast_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Redundant double negation") diff --git a/crates/oxc_linter/src/rules/eslint/no_extra_label.rs b/crates/oxc_linter/src/rules/eslint/no_extra_label.rs index 27f341b4083e2e..b70a77b5c442eb 100644 --- a/crates/oxc_linter/src/rules/eslint/no_extra_label.rs +++ b/crates/oxc_linter/src/rules/eslint/no_extra_label.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::LabelIdentifier, AstKind}; +use oxc_ast::{AstKind, ast::LabelIdentifier}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_extra_label_diagnostic(label: &LabelIdentifier) -> OxcDiagnostic { let label_name = &label.name; diff --git a/crates/oxc_linter/src/rules/eslint/no_fallthrough.rs b/crates/oxc_linter/src/rules/eslint/no_fallthrough.rs index 1c9190dfea2192..7db3f58ac08721 100644 --- a/crates/oxc_linter/src/rules/eslint/no_fallthrough.rs +++ b/crates/oxc_linter/src/rules/eslint/no_fallthrough.rs @@ -3,15 +3,15 @@ use std::ops::Range; use cow_utils::CowUtils; use itertools::Itertools; use oxc_ast::{ - ast::{Statement, SwitchCase, SwitchStatement}, AstKind, + ast::{Statement, SwitchCase, SwitchStatement}, }; use oxc_cfg::{ + BlockNodeId, EdgeType, ErrorEdgeKind, InstructionKind, graph::{ - visit::{neighbors_filtered_by_edge_weight, EdgeRef}, Direction, + visit::{EdgeRef, neighbors_filtered_by_edge_weight}, }, - BlockNodeId, EdgeType, ErrorEdgeKind, InstructionKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -19,7 +19,7 @@ use oxc_span::{GetSpan, Span}; use regex::Regex; use rustc_hash::{FxHashMap, FxHashSet}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_fallthrough_case_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Expected a 'break' statement before 'case'.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_import_assign.rs b/crates/oxc_linter/src/rules/eslint/no_import_assign.rs index 4b6590c1d2df82..b18f7c1767d16b 100644 --- a/crates/oxc_linter/src/rules/eslint/no_import_assign.rs +++ b/crates/oxc_linter/src/rules/eslint/no_import_assign.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::{NodeId, SymbolId}; diff --git a/crates/oxc_linter/src/rules/eslint/no_inner_declarations.rs b/crates/oxc_linter/src/rules/eslint/no_inner_declarations.rs index 877f3f4f3cba65..c8e727e038fda6 100644 --- a/crates/oxc_linter/src/rules/eslint/no_inner_declarations.rs +++ b/crates/oxc_linter/src/rules/eslint/no_inner_declarations.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_inner_declarations_diagnostic(decl_type: &str, body: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Variable or `function` declarations are not allowed in nested blocks") diff --git a/crates/oxc_linter/src/rules/eslint/no_invalid_regexp.rs b/crates/oxc_linter/src/rules/eslint/no_invalid_regexp.rs index f3245ff04aed86..8f26c1f913aa6d 100644 --- a/crates/oxc_linter/src/rules/eslint/no_invalid_regexp.rs +++ b/crates/oxc_linter/src/rules/eslint/no_invalid_regexp.rs @@ -1,5 +1,5 @@ use oxc_allocator::Allocator; -use oxc_ast::{ast::Argument, AstKind}; +use oxc_ast::{AstKind, ast::Argument}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_regular_expression::{ConstructorParser, Options}; @@ -7,7 +7,7 @@ use oxc_span::Span; use rustc_hash::FxHashSet; use serde::Deserialize; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; // Use the same prefix with `oxc_regular_expression` crate fn duplicated_flag_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/eslint/no_iterator.rs b/crates/oxc_linter/src/rules/eslint/no_iterator.rs index 53e233b1b04bff..72c34136c9d36c 100644 --- a/crates/oxc_linter/src/rules/eslint/no_iterator.rs +++ b/crates/oxc_linter/src/rules/eslint/no_iterator.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_iterator_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Reserved name '__iterator__'") diff --git a/crates/oxc_linter/src/rules/eslint/no_label_var.rs b/crates/oxc_linter/src/rules/eslint/no_label_var.rs index f87adc1825dc4f..9b6458992eca0d 100644 --- a/crates/oxc_linter/src/rules/eslint/no_label_var.rs +++ b/crates/oxc_linter/src/rules/eslint/no_label_var.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_label_var_diagnostic(name: &str, id_span: Span, label_span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Found identifier '{name}' with the same name as a label.")) diff --git a/crates/oxc_linter/src/rules/eslint/no_labels.rs b/crates/oxc_linter/src/rules/eslint/no_labels.rs index 184347cee6c238..b24e7e55f42abe 100644 --- a/crates/oxc_linter/src/rules/eslint/no_labels.rs +++ b/crates/oxc_linter/src/rules/eslint/no_labels.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{LabelIdentifier, Statement}, AstKind, + ast::{LabelIdentifier, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::NodeId; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_labels_diagnostic(message: &'static str, label_span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(message).with_label(label_span) diff --git a/crates/oxc_linter/src/rules/eslint/no_lone_blocks.rs b/crates/oxc_linter/src/rules/eslint/no_lone_blocks.rs index f22e3190dda6f2..6d9f9bf306ca9a 100644 --- a/crates/oxc_linter/src/rules/eslint/no_lone_blocks.rs +++ b/crates/oxc_linter/src/rules/eslint/no_lone_blocks.rs @@ -1,10 +1,10 @@ -use oxc_ast::ast::{Declaration, VariableDeclarationKind}; use oxc_ast::AstKind; +use oxc_ast::ast::{Declaration, VariableDeclarationKind}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_lone_blocks_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Block is unnecessary.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_loss_of_precision.rs b/crates/oxc_linter/src/rules/eslint/no_loss_of_precision.rs index 512606a84cdcc9..d95f1eeb71458c 100644 --- a/crates/oxc_linter/src/rules/eslint/no_loss_of_precision.rs +++ b/crates/oxc_linter/src/rules/eslint/no_loss_of_precision.rs @@ -1,12 +1,12 @@ use std::borrow::Cow; use cow_utils::CowUtils; -use oxc_ast::{ast::NumericLiteral, AstKind}; +use oxc_ast::{AstKind, ast::NumericLiteral}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_loss_of_precision_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("This number literal will lose precision at runtime.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_magic_numbers.rs b/crates/oxc_linter/src/rules/eslint/no_magic_numbers.rs index 6a26c182bc7ec0..9cea2a70ec6a1d 100644 --- a/crates/oxc_linter/src/rules/eslint/no_magic_numbers.rs +++ b/crates/oxc_linter/src/rules/eslint/no_magic_numbers.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{AssignmentTarget, Expression, MemberExpression, VariableDeclarationKind}, AstKind, + ast::{AssignmentTarget, Expression, MemberExpression, VariableDeclarationKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -8,7 +8,7 @@ use oxc_semantic::AstNodes; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::UnaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; enum NoMagicNumberReportReason { MustUseConst, diff --git a/crates/oxc_linter/src/rules/eslint/no_multi_assign.rs b/crates/oxc_linter/src/rules/eslint/no_multi_assign.rs index 13500b0e029879..8b10ca77da553a 100644 --- a/crates/oxc_linter/src/rules/eslint/no_multi_assign.rs +++ b/crates/oxc_linter/src/rules/eslint/no_multi_assign.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_multi_assign_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Do not use chained assignment") diff --git a/crates/oxc_linter/src/rules/eslint/no_multi_str.rs b/crates/oxc_linter/src/rules/eslint/no_multi_str.rs index c38b8ec1bf5ef0..b030dc32aa7a7b 100644 --- a/crates/oxc_linter/src/rules/eslint/no_multi_str.rs +++ b/crates/oxc_linter/src/rules/eslint/no_multi_str.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_semantic::NodeId; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_multi_str_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected multi string.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_negated_condition.rs b/crates/oxc_linter/src/rules/eslint/no_negated_condition.rs index 36a965bc9e4b2c..441399d54f1980 100644 --- a/crates/oxc_linter/src/rules/eslint/no_negated_condition.rs +++ b/crates/oxc_linter/src/rules/eslint/no_negated_condition.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{Expression, Statement}, AstKind, + ast::{Expression, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{BinaryOperator, UnaryOperator}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_negated_condition_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected negated condition.") diff --git a/crates/oxc_linter/src/rules/eslint/no_nested_ternary.rs b/crates/oxc_linter/src/rules/eslint/no_nested_ternary.rs index 8b7ce669a92eab..7fa5e3ebd6f06c 100644 --- a/crates/oxc_linter/src/rules/eslint/no_nested_ternary.rs +++ b/crates/oxc_linter/src/rules/eslint/no_nested_ternary.rs @@ -1,10 +1,10 @@ -use oxc_ast::ast::Expression; use oxc_ast::AstKind; +use oxc_ast::ast::Expression; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_nested_ternary_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Do not nest ternary expressions.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_new.rs b/crates/oxc_linter/src/rules/eslint/no_new.rs index e040eba93a0854..97b792617f0656 100644 --- a/crates/oxc_linter/src/rules/eslint/no_new.rs +++ b/crates/oxc_linter/src/rules/eslint/no_new.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_new_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Do not use 'new' for side effects.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_new_func.rs b/crates/oxc_linter/src/rules/eslint/no_new_func.rs index 762f2926dade77..549c927766daff 100644 --- a/crates/oxc_linter/src/rules/eslint/no_new_func.rs +++ b/crates/oxc_linter/src/rules/eslint/no_new_func.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_semantic::IsGlobalReference; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_new_func(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("The Function constructor is eval.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_new_native_nonconstructor.rs b/crates/oxc_linter/src/rules/eslint/no_new_native_nonconstructor.rs index 3111b3c385912c..6100138b32250b 100644 --- a/crates/oxc_linter/src/rules/eslint/no_new_native_nonconstructor.rs +++ b/crates/oxc_linter/src/rules/eslint/no_new_native_nonconstructor.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_new_native_nonconstructor_diagnostic(fn_name: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("`{fn_name}` cannot be called as a constructor.")).with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_new_wrappers.rs b/crates/oxc_linter/src/rules/eslint/no_new_wrappers.rs index 1be1ad48b56478..2f6697dc2a45d2 100644 --- a/crates/oxc_linter/src/rules/eslint/no_new_wrappers.rs +++ b/crates/oxc_linter/src/rules/eslint/no_new_wrappers.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_new_wrappers_diagnostic(builtin_name: &str, new_span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Do not use `{builtin_name}` as a constructor")) diff --git a/crates/oxc_linter/src/rules/eslint/no_nonoctal_decimal_escape.rs b/crates/oxc_linter/src/rules/eslint/no_nonoctal_decimal_escape.rs index d09fe562f0dfb4..076555771429bc 100644 --- a/crates/oxc_linter/src/rules/eslint/no_nonoctal_decimal_escape.rs +++ b/crates/oxc_linter/src/rules/eslint/no_nonoctal_decimal_escape.rs @@ -5,7 +5,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use regex::{Captures, Regex}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn replacement(escape_sequence: &str, replacement: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Don't use '{escape_sequence}' escape sequence.")) @@ -63,7 +63,7 @@ impl Rule for NoNonoctalDecimalEscape { } trait StickyRegex { fn sticky_captures<'h>(&self, haystack: &'h str, start: usize) - -> (Option>, usize); + -> (Option>, usize); } impl StickyRegex for Regex { 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 016da3197d0d56..22bb28a594f8d0 100644 --- a/crates/oxc_linter/src/rules/eslint/no_obj_calls.rs +++ b/crates/oxc_linter/src/rules/eslint/no_obj_calls.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{match_member_expression, Expression, IdentifierReference, MemberExpression}, AstKind, + ast::{Expression, IdentifierReference, MemberExpression, match_member_expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -72,11 +72,7 @@ fn is_global_obj(s: &str) -> bool { } fn global_this_member<'a>(expr: &'a MemberExpression<'_>) -> Option<&'a str> { - if expr.object().is_specific_id(GLOBAL_THIS) { - expr.static_property_name() - } else { - None - } + if expr.object().is_specific_id(GLOBAL_THIS) { expr.static_property_name() } else { None } } fn resolve_global_binding<'a, 'b: 'a>( diff --git a/crates/oxc_linter/src/rules/eslint/no_object_constructor.rs b/crates/oxc_linter/src/rules/eslint/no_object_constructor.rs index 7cc903b93749e5..5bf4cad1c034c3 100644 --- a/crates/oxc_linter/src/rules/eslint/no_object_constructor.rs +++ b/crates/oxc_linter/src/rules/eslint/no_object_constructor.rs @@ -1,10 +1,10 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::IsGlobalReference; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_object_constructor_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Disallow calls to the `Object` constructor without an argument") diff --git a/crates/oxc_linter/src/rules/eslint/no_plusplus.rs b/crates/oxc_linter/src/rules/eslint/no_plusplus.rs index 57c28e2097e12d..88e68af8ad86bd 100644 --- a/crates/oxc_linter/src/rules/eslint/no_plusplus.rs +++ b/crates/oxc_linter/src/rules/eslint/no_plusplus.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::UpdateOperator, AstKind}; +use oxc_ast::{AstKind, ast::UpdateOperator}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_plusplus_diagnostic(span: Span, operator: UpdateOperator) -> OxcDiagnostic { let diagnostic = OxcDiagnostic::warn(format!( diff --git a/crates/oxc_linter/src/rules/eslint/no_proto.rs b/crates/oxc_linter/src/rules/eslint/no_proto.rs index 4fe31a79d3a84e..06cbfe7670c0fb 100644 --- a/crates/oxc_linter/src/rules/eslint/no_proto.rs +++ b/crates/oxc_linter/src/rules/eslint/no_proto.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_proto_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("The '__proto__' property is deprecated") diff --git a/crates/oxc_linter/src/rules/eslint/no_prototype_builtins.rs b/crates/oxc_linter/src/rules/eslint/no_prototype_builtins.rs index a6435781b0dde8..498c208db3945f 100644 --- a/crates/oxc_linter/src/rules/eslint/no_prototype_builtins.rs +++ b/crates/oxc_linter/src/rules/eslint/no_prototype_builtins.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_prototype_builtins_diagnostic(method_name: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!( diff --git a/crates/oxc_linter/src/rules/eslint/no_redeclare.rs b/crates/oxc_linter/src/rules/eslint/no_redeclare.rs index e4b9b19b4538d7..7e4af9301134c0 100644 --- a/crates/oxc_linter/src/rules/eslint/no_redeclare.rs +++ b/crates/oxc_linter/src/rules/eslint/no_redeclare.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{BindingIdentifier, BindingPatternKind}, AstKind, + ast::{BindingIdentifier, BindingPatternKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/eslint/no_regex_spaces.rs b/crates/oxc_linter/src/rules/eslint/no_regex_spaces.rs index f1b6e2b7973d02..79d31f25517602 100644 --- a/crates/oxc_linter/src/rules/eslint/no_regex_spaces.rs +++ b/crates/oxc_linter/src/rules/eslint/no_regex_spaces.rs @@ -1,18 +1,18 @@ use oxc_allocator::{Allocator, Vec}; use oxc_ast::{ - ast::{Argument, CallExpression, NewExpression, RegExpLiteral}, AstKind, + ast::{Argument, CallExpression, NewExpression, RegExpLiteral}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_regular_expression::{ + ConstructorParser, Options, ast::{Character, Pattern}, visit::{RegExpAstKind, Visit}, - ConstructorParser, Options, }; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_regex_spaces_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Multiple consecutive spaces are hard to count.") diff --git a/crates/oxc_linter/src/rules/eslint/no_restricted_globals.rs b/crates/oxc_linter/src/rules/eslint/no_restricted_globals.rs index 0679e4dafb9ba4..7df1e479655cd3 100644 --- a/crates/oxc_linter/src/rules/eslint/no_restricted_globals.rs +++ b/crates/oxc_linter/src/rules/eslint/no_restricted_globals.rs @@ -5,7 +5,7 @@ use oxc_span::Span; use rustc_hash::FxHashMap; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_restricted_globals(global_name: &str, suffix: &str, span: Span) -> OxcDiagnostic { let warn_text = if suffix.is_empty() { diff --git a/crates/oxc_linter/src/rules/eslint/no_restricted_imports.rs b/crates/oxc_linter/src/rules/eslint/no_restricted_imports.rs index 32c3a504151094..080fe99ab37d84 100644 --- a/crates/oxc_linter/src/rules/eslint/no_restricted_imports.rs +++ b/crates/oxc_linter/src/rules/eslint/no_restricted_imports.rs @@ -4,15 +4,15 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use regex::Regex; use rustc_hash::FxHashMap; -use serde::{de::Error, Deserialize, Deserializer}; +use serde::{Deserialize, Deserializer, de::Error}; use serde_json::Value; use std::borrow::Cow; use crate::{ + ModuleRecord, context::LintContext, module_record::{ExportEntry, ExportImportName, ImportEntry, ImportImportName, NameSpan}, rule::Rule, - ModuleRecord, }; fn diagnostic_with_maybe_help(span: Span, msg: String, help: Option) -> OxcDiagnostic { @@ -53,8 +53,9 @@ fn diagnostic_pattern_and_everything( name: &str, source: &str, ) -> OxcDiagnostic { - let msg = - format!("* import is invalid because '{name}' from '{source}' is restricted from being used by a pattern."); + let msg = format!( + "* import is invalid because '{name}' from '{source}' is restricted from being used by a pattern." + ); diagnostic_with_maybe_help(span, msg, help) } @@ -66,8 +67,9 @@ fn diagnostic_pattern_and_everything_with_regex_import_name( source: &str, ) -> OxcDiagnostic { let regex = name.as_str(); - let msg = - format!("* import is invalid because import name matching '{regex}' pattern from '{source}' is restricted from being used."); + let msg = format!( + "* import is invalid because import name matching '{regex}' pattern from '{source}' is restricted from being used." + ); diagnostic_with_maybe_help(span, msg, help) } @@ -101,7 +103,9 @@ fn diagnostic_allowed_import_name( source: &str, allowed: &str, ) -> OxcDiagnostic { - let msg = format!("'{name}' import from '{source}' is restricted because only {allowed} import(s) is/are allowed."); + let msg = format!( + "'{name}' import from '{source}' is restricted because only {allowed} import(s) is/are allowed." + ); diagnostic_with_maybe_help(span, msg, help) } @@ -125,7 +129,9 @@ fn diagnostic_allowed_import_name_pattern( source: &str, allowed_pattern: &str, ) -> OxcDiagnostic { - let msg = format!("'{name}' import from '{source}' is restricted because only imports that match the pattern '{allowed_pattern}' are allowed from '{source}'."); + let msg = format!( + "'{name}' import from '{source}' is restricted because only imports that match the pattern '{allowed_pattern}' are allowed from '{source}'." + ); diagnostic_with_maybe_help(span, msg, help) } @@ -136,7 +142,9 @@ fn diagnostic_everything_with_allowed_import_name_pattern( source: &str, allowed_pattern: &str, ) -> OxcDiagnostic { - let msg = format!("* import is invalid because only imports that match the pattern '{allowed_pattern}' from '{source}' are allowed."); + let msg = format!( + "* import is invalid because only imports that match the pattern '{allowed_pattern}' from '{source}' are allowed." + ); diagnostic_with_maybe_help(span, msg, help) } @@ -789,43 +797,38 @@ fn get_diagnostic_from_import_name_result_path( ) -> OxcDiagnostic { match result { ImportNameResult::GeneralDisallowed => diagnostic_path(span, path.message.clone(), source), - ImportNameResult::DefaultDisallowed => { - if let Some(import_names) = &path.import_names { - diagnostic_everything( - span, - path.message.clone(), - import_names.join(", ").as_str(), - source, - ) - } else if let Some(allowed_import_names) = &path.allow_import_names { - diagnostic_everything_with_allowed_import_name( + ImportNameResult::DefaultDisallowed => match &path.import_names { + Some(import_names) => diagnostic_everything( + span, + path.message.clone(), + import_names.join(", ").as_str(), + source, + ), + _ => match &path.allow_import_names { + Some(allowed_import_names) => diagnostic_everything_with_allowed_import_name( span, path.message.clone(), source, allowed_import_names.join(", ").as_str(), - ) - } else { - diagnostic_path(span, path.message.clone(), source) - } - } - ImportNameResult::NameDisallowed(name_span) => { - if let Some(allow_import_names) = &path.allow_import_names { - diagnostic_allowed_import_name( - name_span.clone().span(), - path.message.clone(), - name_span.name(), - source, - allow_import_names.join(", ").as_str(), - ) - } else { - diagnostic_import_name( - name_span.clone().span(), - path.message.clone(), - name_span.name(), - source, - ) - } - } + ), + _ => diagnostic_path(span, path.message.clone(), source), + }, + }, + ImportNameResult::NameDisallowed(name_span) => match &path.allow_import_names { + Some(allow_import_names) => diagnostic_allowed_import_name( + name_span.clone().span(), + path.message.clone(), + name_span.name(), + source, + allow_import_names.join(", ").as_str(), + ), + _ => diagnostic_import_name( + name_span.clone().span(), + path.message.clone(), + name_span.name(), + source, + ), + }, ImportNameResult::Allowed => unreachable!("should be filtered out by the parent function"), } } @@ -841,66 +844,72 @@ fn get_diagnostic_from_import_name_result_pattern( diagnostic_pattern(span, pattern.message.clone(), source) } ImportNameResult::DefaultDisallowed => { - let diagnostic = if let Some(import_names) = &pattern.import_names { - diagnostic_pattern_and_everything( + let diagnostic = match &pattern.import_names { + Some(import_names) => diagnostic_pattern_and_everything( span, pattern.message.clone(), import_names.join(", ").as_str(), source, - ) - } else if let Some(import_name_patterns) = &pattern.import_name_pattern { - diagnostic_pattern_and_everything_with_regex_import_name( - span, - pattern.message.clone(), - import_name_patterns, - source, - ) - } else if let Some(allow_import_name_pattern) = &pattern.allow_import_name_pattern { - diagnostic_everything_with_allowed_import_name_pattern( - span, - pattern.message.clone(), - source, - allow_import_name_pattern.as_str(), - ) - } else if let Some(allowed_import_names) = &pattern.allow_import_names { - diagnostic_everything_with_allowed_import_name( - span, - pattern.message.clone(), - source, - allowed_import_names.join(", ").as_str(), - ) - } else { - diagnostic_pattern(span, pattern.message.clone(), source) + ), + _ => match &pattern.import_name_pattern { + Some(import_name_patterns) => { + diagnostic_pattern_and_everything_with_regex_import_name( + span, + pattern.message.clone(), + import_name_patterns, + source, + ) + } + _ => match &pattern.allow_import_name_pattern { + Some(allow_import_name_pattern) => { + diagnostic_everything_with_allowed_import_name_pattern( + span, + pattern.message.clone(), + source, + allow_import_name_pattern.as_str(), + ) + } + _ => match &pattern.allow_import_names { + Some(allowed_import_names) => { + diagnostic_everything_with_allowed_import_name( + span, + pattern.message.clone(), + source, + allowed_import_names.join(", ").as_str(), + ) + } + _ => diagnostic_pattern(span, pattern.message.clone(), source), + }, + }, + }, }; diagnostic } - ImportNameResult::NameDisallowed(name_span) => { - if let Some(allow_import_names) = &pattern.allow_import_names { - diagnostic_allowed_import_name( - name_span.clone().span(), - pattern.message.clone(), - name_span.name(), - source, - allow_import_names.join(", ").as_str(), - ) - } else if let Some(allow_import_name_pattern) = &pattern.allow_import_name_pattern { - diagnostic_allowed_import_name_pattern( + ImportNameResult::NameDisallowed(name_span) => match &pattern.allow_import_names { + Some(allow_import_names) => diagnostic_allowed_import_name( + name_span.clone().span(), + pattern.message.clone(), + name_span.name(), + source, + allow_import_names.join(", ").as_str(), + ), + _ => match &pattern.allow_import_name_pattern { + Some(allow_import_name_pattern) => diagnostic_allowed_import_name_pattern( name_span.clone().span(), pattern.message.clone(), name_span.name(), source, allow_import_name_pattern.as_str(), - ) - } else { - diagnostic_pattern_and_import_name( + ), + _ => diagnostic_pattern_and_import_name( name_span.clone().span(), pattern.message.clone(), name_span.name(), source, - ) - } - } + ), + }, + }, ImportNameResult::Allowed => unreachable!("should be filtered out by parent function"), } } diff --git a/crates/oxc_linter/src/rules/eslint/no_return_assign.rs b/crates/oxc_linter/src/rules/eslint/no_return_assign.rs index a725dfd350c60c..109abe1e304df1 100644 --- a/crates/oxc_linter/src/rules/eslint/no_return_assign.rs +++ b/crates/oxc_linter/src/rules/eslint/no_return_assign.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_return_assign_diagnostic(span: Span, message: &'static str) -> OxcDiagnostic { OxcDiagnostic::warn(message) diff --git a/crates/oxc_linter/src/rules/eslint/no_script_url.rs b/crates/oxc_linter/src/rules/eslint/no_script_url.rs index 629f5e04a662bc..a3e28268b7b0f7 100644 --- a/crates/oxc_linter/src/rules/eslint/no_script_url.rs +++ b/crates/oxc_linter/src/rules/eslint/no_script_url.rs @@ -4,7 +4,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_script_url_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected `javascript:` url") diff --git a/crates/oxc_linter/src/rules/eslint/no_self_assign.rs b/crates/oxc_linter/src/rules/eslint/no_self_assign.rs index 24828a93d1c989..9b370e7ccfd8f7 100644 --- a/crates/oxc_linter/src/rules/eslint/no_self_assign.rs +++ b/crates/oxc_linter/src/rules/eslint/no_self_assign.rs @@ -1,17 +1,17 @@ use oxc_ast::{ + AstKind, ast::{ - match_assignment_target, match_simple_assignment_target, ArrayExpressionElement, - AssignmentTarget, AssignmentTargetMaybeDefault, AssignmentTargetProperty, Expression, - MemberExpression, ObjectProperty, ObjectPropertyKind, SimpleAssignmentTarget, + ArrayExpressionElement, AssignmentTarget, AssignmentTargetMaybeDefault, + AssignmentTargetProperty, Expression, MemberExpression, ObjectProperty, ObjectPropertyKind, + SimpleAssignmentTarget, match_assignment_target, match_simple_assignment_target, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::AssignmentOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_self_assign_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("this expression is assigned to itself").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_self_compare.rs b/crates/oxc_linter/src/rules/eslint/no_self_compare.rs index 3c3aff413346d3..29e52e746af518 100644 --- a/crates/oxc_linter/src/rules/eslint/no_self_compare.rs +++ b/crates/oxc_linter/src/rules/eslint/no_self_compare.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{ContentEq, GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_self_compare_diagnostic(span: Span, span1: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Both sides of this comparison are exactly the same") diff --git a/crates/oxc_linter/src/rules/eslint/no_setter_return.rs b/crates/oxc_linter/src/rules/eslint/no_setter_return.rs index e53008a8e09ba0..2871e78df51a40 100644 --- a/crates/oxc_linter/src/rules/eslint/no_setter_return.rs +++ b/crates/oxc_linter/src/rules/eslint/no_setter_return.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_setter_return_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Setter cannot return a value").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs b/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs index 09affda8890b33..a84476eeb0559e 100644 --- a/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs +++ b/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs @@ -1,8 +1,8 @@ -use oxc_ast::{ast::ArrayExpressionElement, AstKind}; +use oxc_ast::{AstKind, ast::ArrayExpressionElement}; use oxc_diagnostics::{LabeledSpan, OxcDiagnostic}; use oxc_macros::declare_oxc_lint; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct NoSparseArrays; diff --git a/crates/oxc_linter/src/rules/eslint/no_template_curly_in_string.rs b/crates/oxc_linter/src/rules/eslint/no_template_curly_in_string.rs index 6e1a301fcc8b69..8f5d44eb96c9f7 100644 --- a/crates/oxc_linter/src/rules/eslint/no_template_curly_in_string.rs +++ b/crates/oxc_linter/src/rules/eslint/no_template_curly_in_string.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_template_curly_in_string_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Template placeholders will not interpolate in regular strings") diff --git a/crates/oxc_linter/src/rules/eslint/no_ternary.rs b/crates/oxc_linter/src/rules/eslint/no_ternary.rs index 63dbe112ea48eb..36a7de737cc6cd 100644 --- a/crates/oxc_linter/src/rules/eslint/no_ternary.rs +++ b/crates/oxc_linter/src/rules/eslint/no_ternary.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_ternary_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected use of ternary expression") diff --git a/crates/oxc_linter/src/rules/eslint/no_this_before_super.rs b/crates/oxc_linter/src/rules/eslint/no_this_before_super.rs index 251244be633c13..ed0f3fe007abd5 100644 --- a/crates/oxc_linter/src/rules/eslint/no_this_before_super.rs +++ b/crates/oxc_linter/src/rules/eslint/no_this_before_super.rs @@ -1,10 +1,10 @@ use oxc_ast::{ - ast::{Argument, Expression, MethodDefinitionKind}, AstKind, + ast::{Argument, Expression, MethodDefinitionKind}, }; use oxc_cfg::{ - graph::visit::{neighbors_filtered_by_edge_weight, EdgeRef}, BlockNodeId, ControlFlowGraph, EdgeType, ErrorEdgeKind, + graph::visit::{EdgeRef, neighbors_filtered_by_edge_weight}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -12,7 +12,7 @@ use oxc_semantic::NodeId; use oxc_span::{GetSpan, Span}; use rustc_hash::{FxHashMap, FxHashSet}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_this_before_super_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Expected to always call super() before this/super property access.") diff --git a/crates/oxc_linter/src/rules/eslint/no_throw_literal.rs b/crates/oxc_linter/src/rules/eslint/no_throw_literal.rs index 00108666652d74..d73771e1280311 100644 --- a/crates/oxc_linter/src/rules/eslint/no_throw_literal.rs +++ b/crates/oxc_linter/src/rules/eslint/no_throw_literal.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{ast_util::could_be_error, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::could_be_error, context::LintContext, rule::Rule}; fn no_throw_literal_diagnostic(span: Span, is_undef: bool) -> OxcDiagnostic { let message = diff --git a/crates/oxc_linter/src/rules/eslint/no_undef.rs b/crates/oxc_linter/src/rules/eslint/no_undef.rs index 8d7906820106af..7abe115f5558fd 100644 --- a/crates/oxc_linter/src/rules/eslint/no_undef.rs +++ b/crates/oxc_linter/src/rules/eslint/no_undef.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::UnaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_undef_diagnostic(name: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("'{name}' is not defined.")).with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/no_undefined.rs b/crates/oxc_linter/src/rules/eslint/no_undefined.rs index 3680becd7e0ce7..6df0939e444657 100644 --- a/crates/oxc_linter/src/rules/eslint/no_undefined.rs +++ b/crates/oxc_linter/src/rules/eslint/no_undefined.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct NoUndefined; diff --git a/crates/oxc_linter/src/rules/eslint/no_unexpected_multiline.rs b/crates/oxc_linter/src/rules/eslint/no_unexpected_multiline.rs index f2ffa0f98e9c2c..1c9151a33d1f4b 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unexpected_multiline.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unexpected_multiline.rs @@ -1,10 +1,10 @@ use memchr::{memchr, memrchr}; -use oxc_ast::{ast::BinaryOperator, AstKind}; +use oxc_ast::{AstKind, ast::BinaryOperator}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct NoUnexpectedMultiline; diff --git a/crates/oxc_linter/src/rules/eslint/no_unneeded_ternary.rs b/crates/oxc_linter/src/rules/eslint/no_unneeded_ternary.rs index 72afe988a12196..6221988a149aaa 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unneeded_ternary.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unneeded_ternary.rs @@ -1,5 +1,5 @@ -use crate::{context::LintContext, rule::Rule, AstNode}; -use oxc_ast::{ast::Expression, AstKind}; +use crate::{AstNode, context::LintContext, rule::Rule}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; @@ -98,7 +98,10 @@ fn test() { ("var a = x === 2 ? 'Yes' : false;", None), ("var a = x === 2 ? 'true' : 'false';", None), ("var a = foo ? foo : bar;", None), - ("var value = 'a';var canSet = true;var result = value || (canSet ? 'unset' : 'can not set')", None), + ( + "var value = 'a';var canSet = true;var result = value || (canSet ? 'unset' : 'can not set')", + None, + ), ("var a = foo ? bar : foo;", None), ("foo ? bar : foo;", None), ("var a = f(x ? x : 1)", None), @@ -107,7 +110,7 @@ fn test() { ("var a = foo ? 'Yes' : foo;", None), ("var a = foo ? 'Yes' : foo;", Some(serde_json::json!([{ "defaultAssignment": false }]))), ("var a = foo ? bar : foo;", Some(serde_json::json!([{ "defaultAssignment": false }]))), - ("foo ? bar : foo;", Some(serde_json::json!([{ "defaultAssignment": false }]))) + ("foo ? bar : foo;", Some(serde_json::json!([{ "defaultAssignment": false }]))), ]; let fail = vec![ diff --git a/crates/oxc_linter/src/rules/eslint/no_unreachable.rs b/crates/oxc_linter/src/rules/eslint/no_unreachable.rs index c82b9e85a7f267..7ef7eef36bc82f 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unreachable.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unreachable.rs @@ -1,10 +1,10 @@ -use oxc_ast::{ast::VariableDeclarationKind, AstKind}; +use oxc_ast::{AstKind, ast::VariableDeclarationKind}; use oxc_cfg::{ + EdgeType, ErrorEdgeKind, Instruction, InstructionKind, graph::{ - visit::{depth_first_search, Control, DfsEvent, EdgeRef}, Direction, + visit::{Control, DfsEvent, EdgeRef, depth_first_search}, }, - EdgeType, ErrorEdgeKind, Instruction, InstructionKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/eslint/no_unsafe_finally.rs b/crates/oxc_linter/src/rules/eslint/no_unsafe_finally.rs index 8881255987a2d5..3398280aa2fa09 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unsafe_finally.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unsafe_finally.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{BreakStatement, ContinueStatement}, AstKind, + ast::{BreakStatement, ContinueStatement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_unsafe_finally_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unsafe finally block") diff --git a/crates/oxc_linter/src/rules/eslint/no_unsafe_negation.rs b/crates/oxc_linter/src/rules/eslint/no_unsafe_negation.rs index 4ecc0ed4e8e21d..ac06782fb03b77 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unsafe_negation.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unsafe_negation.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{BinaryExpression, Expression}, AstKind, + ast::{BinaryExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::{BinaryOperator, UnaryOperator}; -use crate::{context::LintContext, fixer::RuleFixer, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, fixer::RuleFixer, rule::Rule}; fn no_unsafe_negation_diagnostic(operator: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Unexpected logical not in the left hand side of '{operator}' operator")) diff --git a/crates/oxc_linter/src/rules/eslint/no_unsafe_optional_chaining.rs b/crates/oxc_linter/src/rules/eslint/no_unsafe_optional_chaining.rs index a1d48ad0b7acfa..69a15ae016ee2e 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unsafe_optional_chaining.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unsafe_optional_chaining.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{match_assignment_target_pattern, Argument, AssignmentTarget, Expression}, AstKind, + ast::{Argument, AssignmentTarget, Expression, match_assignment_target_pattern}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use oxc_syntax::operator::LogicalOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_unsafe_optional_chaining_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unsafe usage of optional chaining") diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_expressions.rs b/crates/oxc_linter/src/rules/eslint/no_unused_expressions.rs index 079d33b5332ded..605293aab80ca9 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_expressions.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_expressions.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{ChainElement, Expression, UnaryOperator}, AstKind, + ast::{ChainElement, Expression, UnaryOperator}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_unused_expressions_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Disallow unused expressions") 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 be147de71ade2e..8e145aed37544a 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 @@ -1,12 +1,12 @@ //! This module checks if an unused variable is allowed. Note that this does not //! consider variables ignored by name pattern, but by where they are declared. -use oxc_ast::{ast::*, AstKind}; +use oxc_ast::{AstKind, ast::*}; use oxc_semantic::{NodeId, Semantic}; -use super::{options::ArgsOption, NoUnusedVars, Symbol}; +use super::{NoUnusedVars, Symbol, options::ArgsOption}; use crate::{ - rules::eslint::no_unused_vars::binding_pattern::{BindingContext, HasAnyUsedBinding}, ModuleRecord, + rules::eslint::no_unused_vars::binding_pattern::{BindingContext, HasAnyUsedBinding}, }; impl Symbol<'_, '_> { 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 9da6901c6f6f22..3e41033db57352 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 @@ -3,7 +3,7 @@ use oxc_semantic::{Semantic, SymbolId}; use crate::ModuleRecord; -use super::{symbol::Symbol, NoUnusedVars}; +use super::{NoUnusedVars, symbol::Symbol}; #[derive(Clone, Copy)] pub(super) struct BindingContext<'s, 'a> { diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/diagnostic.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/diagnostic.rs index ae9d678c33a972..8dbb135791394d 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/diagnostic.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/diagnostic.rs @@ -5,7 +5,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_semantic::SymbolFlags; use oxc_span::{GetSpan, Span}; -use super::{options::IgnorePattern, Symbol}; +use super::{Symbol, options::IgnorePattern}; fn pronoun_for_symbol( symbol_flags: SymbolFlags, diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_imports.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_imports.rs index 041f8db49401c3..b365fb9fdc53b3 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_imports.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_imports.rs @@ -1,7 +1,7 @@ use oxc_ast::ast::ImportDeclaration; use oxc_span::GetSpan; -use super::{count_whitespace_or_commas, NoUnusedVars, Symbol}; +use super::{NoUnusedVars, Symbol, count_whitespace_or_commas}; use crate::fixer::{RuleFix, RuleFixer}; impl NoUnusedVars { 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 f21ede19d690bc..ebd4f44a3d02f3 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,4 +1,4 @@ -use oxc_ast::{ast::*, AstKind}; +use oxc_ast::{AstKind, ast::*}; use oxc_span::{CompactStr, GetSpan, Span}; use super::Symbol; @@ -126,11 +126,7 @@ impl<'s, 'a> Symbol<'s, 'a> { 1 => { let last_property = obj.properties.len() - 1; let own_span = obj.properties.iter().enumerate().find_map(|(idx, el)| { - if self == &el.value { - Some((el.span, idx == last_property)) - } else { - None - } + if self == &el.value { Some((el.span, idx == last_property)) } else { None } }); if let Some(rest) = obj.rest.as_ref() { if rest.span.contains_inclusive(self.span()) { @@ -181,11 +177,7 @@ pub(super) enum BindingInfo { impl BindingInfo { #[inline] const fn single_or_missing(found: bool) -> Self { - if found { - BindingInfo::SingleDestructure - } else { - BindingInfo::NotFound - } + if found { BindingInfo::SingleDestructure } else { BindingInfo::NotFound } } fn multi_or_missing(found: Option<(Span, bool)>, is_object: bool) -> Self { 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 583bfa987b7b01..47e20ce48798e3 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 @@ -1,11 +1,11 @@ use oxc_ast::{ - ast::{Expression, VariableDeclarator}, AstKind, + ast::{Expression, VariableDeclarator}, }; use oxc_semantic::NodeId; use oxc_span::CompactStr; -use super::{count_whitespace_or_commas, BindingInfo, NoUnusedVars, Symbol}; +use super::{BindingInfo, NoUnusedVars, Symbol, count_whitespace_or_commas}; use crate::{ fixer::{RuleFix, RuleFixer}, rules::eslint::no_unused_vars::options::IgnorePattern, 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 fd7674a682a9ca..15fde51febe98b 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,14 +1,14 @@ use oxc_ast::{ + AstKind, ast::{ ArrayAssignmentTarget, AssignmentTarget, AssignmentTargetMaybeDefault, AssignmentTargetProperty, BindingPattern, BindingPatternKind, ClassElement, ObjectAssignmentTarget, }, - AstKind, }; use regex::Regex; -use super::{options::IgnorePattern, NoUnusedVars, Symbol}; +use super::{NoUnusedVars, Symbol, options::IgnorePattern}; #[derive(Debug, Default, Clone, Copy)] pub(super) enum FoundStatus { @@ -34,11 +34,7 @@ impl FoundStatus { #[inline] pub const fn found(is_found: bool) -> Self { - if is_found { - Self::NotIgnored - } else { - Self::NotFound - } + if is_found { Self::NotIgnored } else { Self::NotFound } } /// Mark a target as ignored if it's found. 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 6c1aab88ba4b3c..ec85bf1c0ef995 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 @@ -279,14 +279,14 @@ impl NoUnusedVars { if self.is_allowed_variable_declaration(symbol, decl) { return; }; - let report = - if let Some(last_write) = symbol.references().rev().find(|r| r.is_write()) { + let report = match symbol.references().rev().find(|r| r.is_write()) { + Some(last_write) => { // ahg let span = ctx.nodes().get_node(last_write.node_id()).kind().span(); diagnostic::assign(symbol, span, &self.vars_ignore_pattern) - } else { - diagnostic::declared(symbol, &self.vars_ignore_pattern) - }; + } + _ => diagnostic::declared(symbol, &self.vars_ignore_pattern), + }; ctx.diagnostic_with_suggestion(report, |fixer| { // NOTE: suggestions produced by this fixer are all flagged 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 44aa1dec6bcd18..6660d478d1bc1b 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 @@ -255,10 +255,11 @@ impl IgnorePattern { /// See also [`Option::expect`]. #[inline] pub fn expect(self, msg: &str) -> R { - if let Self::Some(r) = self { - r - } else { - panic!("{}", msg) + match self { + Self::Some(r) => r, + _ => { + panic!("{}", msg) + } } } @@ -571,7 +572,7 @@ impl TryFrom for NoUnusedVarsOptions { } Value::Null => Ok(Self::default()), _ => Err(OxcDiagnostic::error(format!( - "Invalid 'vars' option for no-unused-vars: Expected a string or an object, got {config}" + "Invalid 'vars' option for no-unused-vars: Expected a string or an object, got {config}" ))), } } 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 231fa1baaad9f7..d7b0c25bf487dd 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,11 +1,11 @@ use std::{cell::OnceCell, fmt}; use oxc_ast::{ + AstKind, ast::{ AssignmentTarget, BindingIdentifier, BindingPattern, IdentifierReference, ImportDeclarationSpecifier, VariableDeclarator, }, - AstKind, }; use oxc_semantic::{ AstNode, AstNodes, NodeId, Reference, ScopeId, ScopeTree, Semantic, SymbolFlags, SymbolId, @@ -74,7 +74,7 @@ impl<'s, 'a> Symbol<'s, 'a> { } #[inline] - pub fn references(&self) -> impl DoubleEndedIterator + '_ { + pub fn references(&self) -> impl DoubleEndedIterator + '_ + use<'_> { self.symbols().get_resolved_references(self.id) } 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 cc7b07c68b5b37..3c81c84ddfec3b 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,7 +1,7 @@ //! Test cases from vanilla eslint use super::NoUnusedVars; -use crate::{tester::Tester, RuleMeta as _}; +use crate::{RuleMeta as _, tester::Tester}; /// 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! 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 1ad9732779b419..d4d8c76540a11f 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 @@ -3,7 +3,7 @@ use serde_json::json; use super::NoUnusedVars; -use crate::{tester::Tester, FixKind, RuleMeta as _}; +use crate::{FixKind, RuleMeta as _, tester::Tester}; // uncomment to only run a single test. useful for step-through debugging. #[test] diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/react.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/react.rs index eea9b5117ec9fd..9d3d890ba394fe 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/react.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/react.rs @@ -1,7 +1,7 @@ //! Test cases from eslint-plugin-react (jsx/no-uses-vars) use super::NoUnusedVars; -use crate::{tester::Tester, RuleMeta as _}; +use crate::{RuleMeta as _, tester::Tester}; /// !!!! STOP !!!! /// Are you fixing a bug in this rule and want to add a test case? Please put diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/typescript_eslint.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/typescript_eslint.rs index ee39366cce71f1..bda4f88c4c7b58 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/typescript_eslint.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/typescript_eslint.rs @@ -1,7 +1,7 @@ use serde_json::json; use super::NoUnusedVars; -use crate::{tester::Tester, RuleMeta as _}; +use crate::{RuleMeta as _, tester::Tester}; // TODO: port these over. I (@DonIsaac) would love some help with this... 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 40886d58f53326..ed8a96fc6bf822 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 @@ -1,11 +1,11 @@ //! This module contains logic for checking if any [`Reference`]s to a //! [`Symbol`] are considered a usage. -use oxc_ast::{ast::*, AstKind}; +use oxc_ast::{AstKind, ast::*}; use oxc_semantic::{AstNode, NodeId, Reference, ScopeId, SymbolFlags, SymbolId}; use oxc_span::{GetSpan, Span}; -use super::{ignored::FoundStatus, NoUnusedVars, Symbol}; +use super::{NoUnusedVars, Symbol, ignored::FoundStatus}; impl<'a> Symbol<'_, 'a> { // ========================================================================= diff --git a/crates/oxc_linter/src/rules/eslint/no_useless_call.rs b/crates/oxc_linter/src/rules/eslint/no_useless_call.rs index abe26decf8a034..3406560975531d 100644 --- a/crates/oxc_linter/src/rules/eslint/no_useless_call.rs +++ b/crates/oxc_linter/src/rules/eslint/no_useless_call.rs @@ -1,13 +1,14 @@ use oxc_ast::{ + AstKind, ast::{CallExpression, ChainElement, Expression, MemberExpression}, - match_member_expression, AstKind, + match_member_expression, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::ContentEq; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_useless_call_diagnostic(name: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Avoid unnecessary use of .{name}()")) diff --git a/crates/oxc_linter/src/rules/eslint/no_useless_catch.rs b/crates/oxc_linter/src/rules/eslint/no_useless_catch.rs index 5e99dddfdbd57f..bad85f731719da 100644 --- a/crates/oxc_linter/src/rules/eslint/no_useless_catch.rs +++ b/crates/oxc_linter/src/rules/eslint/no_useless_catch.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{BindingPatternKind, Expression, Statement}, AstKind, + ast::{BindingPatternKind, Expression, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_useless_catch_diagnostic(catch: Span, rethrow: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unnecessary try/catch wrapper") diff --git a/crates/oxc_linter/src/rules/eslint/no_useless_concat.rs b/crates/oxc_linter/src/rules/eslint/no_useless_concat.rs index 2598b27db54f16..f65eaf9855bf13 100644 --- a/crates/oxc_linter/src/rules/eslint/no_useless_concat.rs +++ b/crates/oxc_linter/src/rules/eslint/no_useless_concat.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{BinaryExpression, Expression}, AstKind, + ast::{BinaryExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::{identifier::is_line_terminator, operator::BinaryOperator}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct NoUselessConcat; diff --git a/crates/oxc_linter/src/rules/eslint/no_useless_constructor.rs b/crates/oxc_linter/src/rules/eslint/no_useless_constructor.rs index 81e60207c20cf8..089eccb30a5fba 100644 --- a/crates/oxc_linter/src/rules/eslint/no_useless_constructor.rs +++ b/crates/oxc_linter/src/rules/eslint/no_useless_constructor.rs @@ -1,15 +1,15 @@ use oxc_ast::{ + AstKind, ast::{ Argument, BindingPattern, BindingPatternKind, BindingRestElement, CallExpression, Expression, FormalParameters, FunctionBody, MethodDefinition, Statement, TSAccessibility, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; /// ```js /// class A { constructor(){} } @@ -203,11 +203,7 @@ fn is_single_super_call<'a, 'f>(body: &'f FunctionBody<'a>) -> Option<&'f CallEx let Statement::ExpressionStatement(expr) = &body.statements[0] else { return None }; let Expression::CallExpression(call) = &expr.expression else { return None }; - if call.callee.is_super() { - Some(call) - } else { - None - } + if call.callee.is_super() { Some(call) } else { None } } /// Returns `false` if any parameter is an array/object unpacking binding or an diff --git a/crates/oxc_linter/src/rules/eslint/no_useless_escape.rs b/crates/oxc_linter/src/rules/eslint/no_useless_escape.rs index 75e322b19b659f..2679d525b89fb4 100644 --- a/crates/oxc_linter/src/rules/eslint/no_useless_escape.rs +++ b/crates/oxc_linter/src/rules/eslint/no_useless_escape.rs @@ -1,5 +1,5 @@ use memchr::memmem; -use oxc_ast::{ast::RegExpFlags, AstKind}; +use oxc_ast::{AstKind, ast::RegExpFlags}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_regular_expression::{ @@ -9,7 +9,7 @@ use oxc_regular_expression::{ use oxc_semantic::NodeId; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_useless_escape_diagnostic(escape_char: char, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Unnecessary escape character {escape_char:?}")).with_label(span) @@ -162,11 +162,7 @@ fn check_character( let span = character.span; let escape_char = char_text.chars().nth(1).unwrap(); let escapes = if character_class.is_some() { - if unicode_sets { - REGEX_CLASSSET_CHARACTER_ESCAPES - } else { - REGEX_GENERAL_ESCAPES - } + if unicode_sets { REGEX_CLASSSET_CHARACTER_ESCAPES } else { REGEX_GENERAL_ESCAPES } } else { REGEX_NON_CHARCLASS_ESCAPES }; diff --git a/crates/oxc_linter/src/rules/eslint/no_useless_rename.rs b/crates/oxc_linter/src/rules/eslint/no_useless_rename.rs index d1fb41ce7c4615..c920abf8075bab 100644 --- a/crates/oxc_linter/src/rules/eslint/no_useless_rename.rs +++ b/crates/oxc_linter/src/rules/eslint/no_useless_rename.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{AssignmentTarget, AssignmentTargetProperty, BindingPatternKind}, AstKind, + ast::{AssignmentTarget, AssignmentTargetProperty, BindingPatternKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_useless_rename_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn( diff --git a/crates/oxc_linter/src/rules/eslint/no_var.rs b/crates/oxc_linter/src/rules/eslint/no_var.rs index 978c70c3d31878..645bca9646fa5d 100644 --- a/crates/oxc_linter/src/rules/eslint/no_var.rs +++ b/crates/oxc_linter/src/rules/eslint/no_var.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{BindingPattern, BindingPatternKind, VariableDeclarationKind}, AstKind, + ast::{BindingPattern, BindingPatternKind, VariableDeclarationKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_var_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected var, use let or const instead.") @@ -86,13 +86,10 @@ fn is_written_to(binding_pat: &BindingPattern, ctx: &LintContext) -> bool { } } BindingPatternKind::AssignmentPattern(_) => true, - BindingPatternKind::ArrayPattern(array_pat) => array_pat.elements.iter().any(|elem| { - if let Some(elem) = elem { - is_written_to(elem, ctx) - } else { - false - } - }), + BindingPatternKind::ArrayPattern(array_pat) => array_pat + .elements + .iter() + .any(|elem| if let Some(elem) = elem { is_written_to(elem, ctx) } else { false }), } } diff --git a/crates/oxc_linter/src/rules/eslint/no_void.rs b/crates/oxc_linter/src/rules/eslint/no_void.rs index 6083f9937b4071..7350dce8046c90 100644 --- a/crates/oxc_linter/src/rules/eslint/no_void.rs +++ b/crates/oxc_linter/src/rules/eslint/no_void.rs @@ -4,7 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use oxc_syntax::operator::UnaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_void_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected `void` operator") diff --git a/crates/oxc_linter/src/rules/eslint/no_with.rs b/crates/oxc_linter/src/rules/eslint/no_with.rs index c4d72a7b269f3e..8da56a19693bd7 100644 --- a/crates/oxc_linter/src/rules/eslint/no_with.rs +++ b/crates/oxc_linter/src/rules/eslint/no_with.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_with_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Unexpected use of `with` statement.") diff --git a/crates/oxc_linter/src/rules/eslint/prefer_exponentiation_operator.rs b/crates/oxc_linter/src/rules/eslint/prefer_exponentiation_operator.rs index 4986335271b53b..2acb896c6087aa 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_exponentiation_operator.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_exponentiation_operator.rs @@ -1,11 +1,11 @@ -use oxc_ast::{ast::Expression, match_member_expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression, match_member_expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ - ast_util::is_method_call, context::LintContext, globals::GLOBAL_OBJECT_NAMES, rule::Rule, - AstNode, + AstNode, ast_util::is_method_call, context::LintContext, globals::GLOBAL_OBJECT_NAMES, + rule::Rule, }; #[derive(Debug, Default, Clone)] diff --git a/crates/oxc_linter/src/rules/eslint/prefer_numeric_literals.rs b/crates/oxc_linter/src/rules/eslint/prefer_numeric_literals.rs index c0545ef3566edc..58ba6b64adfe82 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_numeric_literals.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_numeric_literals.rs @@ -1,18 +1,18 @@ use oxc_ast::{ + AstKind, ast::{ Argument, CallExpression, Expression, IdentifierReference, MemberExpression, StaticMemberExpression, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use phf::{phf_map, phf_ordered_set, Map}; +use phf::{Map, phf_map, phf_ordered_set}; use crate::{ - ast_util::get_symbol_id_of_variable, context::LintContext, fixer::RuleFixer, rule::Rule, - AstNode, + AstNode, ast_util::get_symbol_id_of_variable, context::LintContext, fixer::RuleFixer, + rule::Rule, }; fn prefer_numeric_literals_diagnostic(span: Span, prefix_name: &str) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs b/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs index e6ad84fdb1fd37..d8bf68dbbb0d2b 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{Expression, MemberExpression}, AstKind, + ast::{Expression, MemberExpression}, }; 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}; +use crate::{AstNode, ast_util::is_method_call, context::LintContext, rule::Rule}; fn prefer_object_has_own_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn( diff --git a/crates/oxc_linter/src/rules/eslint/prefer_object_spread.rs b/crates/oxc_linter/src/rules/eslint/prefer_object_spread.rs index 2f2e4707c48b56..115af4b11d5ed9 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_object_spread.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_object_spread.rs @@ -1,17 +1,17 @@ use std::cmp::max; use oxc_allocator::Box; +use oxc_ast::AstKind; use oxc_ast::ast::Expression; use oxc_ast::ast::ObjectExpression; use oxc_ast::ast::ObjectPropertyKind; use oxc_ast::ast::PropertyKind; -use oxc_ast::AstKind; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::GetSpan; use oxc_span::Span; -use crate::{ast_util::is_method_call, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::is_method_call, context::LintContext, rule::Rule}; fn prefer_object_spread_diagnostic(span: Span, for_use_literal: bool) -> OxcDiagnostic { let help_message = if for_use_literal { @@ -612,11 +612,27 @@ fn test() { ("Object.assign({}, { foo: 'bar' })", "({ foo: 'bar'})", None), ("Object.assign({}, baz, { foo: 'bar' })", "({ ...baz, foo: 'bar'})", None), ("Object.assign({}, { foo: 'bar', baz: 'foo' })", "({ foo: 'bar', baz: 'foo'})", None), - (r"Object.assign/** comment with multi byte 😀 */({}, { '😀': '😀', '😆': '💪' })", r"({ '😀': '😀', '😆': '💪'})", None), + ( + r"Object.assign/** comment with multi byte 😀 */({}, { '😀': '😀', '😆': '💪' })", + r"({ '😀': '😀', '😆': '💪'})", + None, + ), ("Object.assign({ foo: 'bar' }, baz)", "({foo: 'bar', ...baz})", None), - ("Object.assign({ foo: 'bar' }, cats, dogs, trees, birds)", "({foo: 'bar', ...cats, ...dogs, ...trees, ...birds})", None), - ("Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, baz))", "({foo: 'bar', ...Object.assign({ bar: 'foo' }, baz)})", None), - ("Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' })))", "({foo: 'bar', ...Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' }))})", None), + ( + "Object.assign({ foo: 'bar' }, cats, dogs, trees, birds)", + "({foo: 'bar', ...cats, ...dogs, ...trees, ...birds})", + None, + ), + ( + "Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, baz))", + "({foo: 'bar', ...Object.assign({ bar: 'foo' }, baz)})", + None, + ), + ( + "Object.assign({ foo: 'bar' }, Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' })))", + "({foo: 'bar', ...Object.assign({ bar: 'foo' }, Object.assign({}, { superNested: 'butwhy' }))})", + None, + ), ("Object.assign({foo: 'bar', ...bar}, baz)", "({foo: 'bar', ...bar, ...baz})", None), ("Object.assign({}, { foo, bar, baz })", "({ foo, bar, baz})", None), ("Object.assign({}, { [bar]: 'foo' })", "({ [bar]: 'foo'})", None), @@ -634,7 +650,7 @@ fn test() { foo: 'bar', baz: "cats"}) "#, - None + None, ), ( r#" @@ -655,7 +671,7 @@ fn test() { foo: 'bar', baz: "cats"}) "#, - None + None, ), ( r#" @@ -672,7 +688,7 @@ fn test() { baz: "cats" */ weird} "#, - None + None, ), ( r#" @@ -685,7 +701,7 @@ fn test() { const test = {...bar, foo: 'bar', // inline comment baz: "cats"} "#, - None + None, ), ( r#" @@ -704,7 +720,7 @@ fn test() { foo: 'bar', baz: "cats"} "#, - None + None, ), ("Object.assign({})", "({})", None), ("Object.assign({ foo: bar })", "({foo: bar})", None), @@ -717,7 +733,7 @@ fn test() { const foo = 'bar'; ({foo: bar}) ", - None + None, ), ( " @@ -728,14 +744,18 @@ fn test() { foo = 'bar'; ({foo: bar}) ", - None + None, ), ("let a = Object.assign({})", "let a = {}", None), ("let a = Object.assign({}, a)", "let a = { ...a}", None), ("let a = Object.assign ({}, a)", "let a = { ...a}", None), ("let a = Object.assign({ a: 1 }, b)", "let a = {a: 1, ...b}", None), ("Object.assign( {}, a, b, )", "({ ...a, ...b, })", None), - ("Object.assign({}, a ? b : {}, b => c, a = 2)", "({ ...(a ? b : {}), ...(b => c), ...(a = 2)})", None), + ( + "Object.assign({}, a ? b : {}, b => c, a = 2)", + "({ ...(a ? b : {}), ...(b => c), ...(a = 2)})", + None, + ), ( " const someVar = 'foo'; @@ -745,7 +765,7 @@ fn test() { const someVar = 'foo'; ({ ...(a ? b : {}), ...(b => c), ...(a = 2)}) ", - None + None, ), ( " @@ -756,13 +776,21 @@ fn test() { someVar = 'foo'; ({ ...(a ? b : {}), ...(b => c), ...(a = 2)}) ", - None + None, ), ("[1, 2, Object.assign({}, a)]", "[1, 2, { ...a}]", None), ("const foo = Object.assign({}, a)", "const foo = { ...a}", None), - ("function foo() { return Object.assign({}, a) }", "function foo() { return { ...a} }", None), + ( + "function foo() { return Object.assign({}, a) }", + "function foo() { return { ...a} }", + None, + ), ("foo(Object.assign({}, a));", "foo({ ...a});", None), - ("const x = { foo: 'bar', baz: Object.assign({}, a) }", "const x = { foo: 'bar', baz: { ...a} }", None), + ( + "const x = { foo: 'bar', baz: Object.assign({}, a) }", + "const x = { foo: 'bar', baz: { ...a} }", + None, + ), ( " import Foo from 'foo'; @@ -772,7 +800,7 @@ fn test() { import Foo from 'foo'; ({foo: Foo}); ", - None + None, ), ( " @@ -783,7 +811,7 @@ fn test() { import Foo from 'foo'; ({ ...Foo}); ", - None + None, ), ( " @@ -794,7 +822,7 @@ fn test() { const Foo = require('foo'); ({foo: Foo}); ", - None + None, ), ( " @@ -805,7 +833,7 @@ fn test() { import { Something as somethingelse } from 'foo'; ({ ...somethingelse}); ", - None + None, ), ( " @@ -816,7 +844,7 @@ fn test() { import { foo } from 'foo'; ({foo: Foo}); ", - None + None, ), ( " @@ -827,7 +855,7 @@ fn test() { const Foo = require('foo'); ({ ...Foo}); ", - None + None, ), ( " @@ -844,7 +872,7 @@ fn test() { ...this.props.actions }; ", - None + None, ), ( " @@ -862,7 +890,7 @@ fn test() { ...this.props.actions }; ", - None + None, ), ( " @@ -880,7 +908,7 @@ fn test() { ...this.props.actions }; ", - None + None, ), ( " @@ -907,12 +935,12 @@ fn test() { ) }; ", - None + None, ), ( "eventData = Object.assign({}, eventData, { outsideLocality: `${originLocality} - ${destinationLocality}` })", "eventData = { ...eventData, outsideLocality: `${originLocality} - ${destinationLocality}`}", - None + None, ), ("Object.assign({ });", "({});", None), ("Object.assign({\n});", "({});", None), @@ -927,7 +955,7 @@ fn test() { function foo () { var globalThis = bar; } ({}); ", - None + None, ), ( " @@ -938,11 +966,15 @@ fn test() { const Foo = require('foo'); ({foo: Foo}); ", - None + None, ), ("Object.assign({ get a() {}, set b(val) {} })", "({get a() {}, set b(val) {}})", None), - ("const obj = Object.assign<{}, Record>({}, getObject());", "const obj = { ...getObject()};", None), - ("Object.assign<{}, A>({}, foo);", "({ ...foo});", None) + ( + "const obj = Object.assign<{}, Record>({}, getObject());", + "const obj = { ...getObject()};", + None, + ), + ("Object.assign<{}, A>({}, foo);", "({ ...foo});", None), ]; Tester::new(PreferObjectSpread::NAME, PreferObjectSpread::PLUGIN, pass, fail) .expect_fix(fix) diff --git a/crates/oxc_linter/src/rules/eslint/prefer_promise_reject_errors.rs b/crates/oxc_linter/src/rules/eslint/prefer_promise_reject_errors.rs index 322cccca77ae20..13cd702af61de6 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_promise_reject_errors.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_promise_reject_errors.rs @@ -1,18 +1,18 @@ use oxc_allocator::Box; use oxc_ast::ast::MemberExpression; use oxc_ast::{ - ast::{Argument, CallExpression, Expression, FormalParameters}, AstKind, + ast::{Argument, CallExpression, Expression, FormalParameters}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, ast_util::{could_be_error, is_method_call}, context::LintContext, rule::Rule, - AstNode, }; fn prefer_promise_reject_errors_diagnostic(span: Span) -> OxcDiagnostic { @@ -218,12 +218,18 @@ fn test() { ("Promise.reject(5 && foo)", None), ("new Foo((resolve, reject) => reject(5))", None), ("new Promise(function(resolve, reject) { return function(reject) { reject(5) } })", None), - ("new Promise(function(resolve, reject) { if (foo) { const reject = somethingElse; reject(5) } })", None), + ( + "new Promise(function(resolve, reject) { if (foo) { const reject = somethingElse; reject(5) } })", + None, + ), ("new Promise(function(resolve, {apply}) { apply(5) })", None), ("new Promise(function(resolve, reject) { resolve(5, reject) })", None), ("async function foo() { Promise.reject(await foo); }", None), ("Promise.reject()", Some(serde_json::json!([{ "allowEmptyReject": true }]))), - ("new Promise(function(resolve, reject) { reject() })", Some(serde_json::json!([{ "allowEmptyReject": true }]))), + ( + "new Promise(function(resolve, reject) { reject() })", + Some(serde_json::json!([{ "allowEmptyReject": true }])), + ), ("Promise.reject(obj?.foo)", None), ("Promise.reject(obj?.foo())", None), ("Promise.reject(foo = new Error())", None), diff --git a/crates/oxc_linter/src/rules/eslint/prefer_rest_params.rs b/crates/oxc_linter/src/rules/eslint/prefer_rest_params.rs index e13f440d9991f4..8011981922205e 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_rest_params.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_rest_params.rs @@ -1,4 +1,4 @@ -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; use oxc_ast::AstKind; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/eslint/prefer_spread.rs b/crates/oxc_linter/src/rules/eslint/prefer_spread.rs index 09abf5ba5ab6c4..c18f2d141ff04a 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_spread.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_spread.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{match_member_expression, CallExpression, ChainElement, Expression, MemberExpression}, AstKind, + ast::{CallExpression, ChainElement, Expression, MemberExpression, match_member_expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{ContentEq, Span}; -use crate::{ast_util::is_method_call, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::is_method_call, context::LintContext, rule::Rule}; fn eslint_prefer_spread_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Require spread operators instead of .apply()").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/radix.rs b/crates/oxc_linter/src/rules/eslint/radix.rs index 83f928f5444f81..812e75cb915211 100644 --- a/crates/oxc_linter/src/rules/eslint/radix.rs +++ b/crates/oxc_linter/src/rules/eslint/radix.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression}, AstKind, + ast::{Argument, CallExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::IsGlobalReference; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn missing_parameters(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Missing parameters.").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/require_await.rs b/crates/oxc_linter/src/rules/eslint/require_await.rs index 5538693243deeb..746a70c1e3f875 100644 --- a/crates/oxc_linter/src/rules/eslint/require_await.rs +++ b/crates/oxc_linter/src/rules/eslint/require_await.rs @@ -1,14 +1,14 @@ use oxc_ast::{ + AstKind, Visit, ast::{ArrowFunctionExpression, AwaitExpression, ForOfStatement, Function, PropertyKey}, visit::walk::walk_for_of_statement, - AstKind, Visit, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::ScopeFlags; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct RequireAwait; diff --git a/crates/oxc_linter/src/rules/eslint/require_yield.rs b/crates/oxc_linter/src/rules/eslint/require_yield.rs index da9d19924b0769..e8926b9235ded4 100644 --- a/crates/oxc_linter/src/rules/eslint/require_yield.rs +++ b/crates/oxc_linter/src/rules/eslint/require_yield.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn require_yield_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("This generator function does not have 'yield'").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/sort_imports.rs b/crates/oxc_linter/src/rules/eslint/sort_imports.rs index 78e08c31207b2a..1b9c9acade8a65 100644 --- a/crates/oxc_linter/src/rules/eslint/sort_imports.rs +++ b/crates/oxc_linter/src/rules/eslint/sort_imports.rs @@ -7,8 +7,8 @@ use std::{ use cow_utils::CowUtils; use itertools::Itertools; use oxc_ast::{ - ast::{ImportDeclaration, ImportDeclarationSpecifier, Statement}, AstKind, + ast::{ImportDeclaration, ImportDeclarationSpecifier, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/eslint/sort_keys.rs b/crates/oxc_linter/src/rules/eslint/sort_keys.rs index 9d89019d100d3c..07cd90d5bf73c4 100644 --- a/crates/oxc_linter/src/rules/eslint/sort_keys.rs +++ b/crates/oxc_linter/src/rules/eslint/sort_keys.rs @@ -3,12 +3,12 @@ use std::{cmp::Ordering, str::Chars}; use cow_utils::CowUtils; use itertools::all; -use oxc_ast::{ast::ObjectPropertyKind, AstKind}; +use oxc_ast::{AstKind, ast::ObjectPropertyKind}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct SortKeys(Box); diff --git a/crates/oxc_linter/src/rules/eslint/sort_vars.rs b/crates/oxc_linter/src/rules/eslint/sort_vars.rs index 0edb128a12dbb6..978e31fb8ff05c 100644 --- a/crates/oxc_linter/src/rules/eslint/sort_vars.rs +++ b/crates/oxc_linter/src/rules/eslint/sort_vars.rs @@ -2,14 +2,14 @@ use std::{borrow::Cow, cmp::Ordering}; use cow_utils::CowUtils; use oxc_ast::{ - ast::{BindingPatternKind, VariableDeclarator}, AstKind, + ast::{BindingPatternKind, VariableDeclarator}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn sort_vars_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Variable declarations should be sorted").with_label(span) diff --git a/crates/oxc_linter/src/rules/eslint/symbol_description.rs b/crates/oxc_linter/src/rules/eslint/symbol_description.rs index 1707bdbfffbec4..2fcade40f660d4 100644 --- a/crates/oxc_linter/src/rules/eslint/symbol_description.rs +++ b/crates/oxc_linter/src/rules/eslint/symbol_description.rs @@ -3,7 +3,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; #[derive(Debug, Default, Clone)] pub struct SymbolDescription; diff --git a/crates/oxc_linter/src/rules/eslint/unicode_bom.rs b/crates/oxc_linter/src/rules/eslint/unicode_bom.rs index 41089931e9bb9f..7bb554e681023c 100644 --- a/crates/oxc_linter/src/rules/eslint/unicode_bom.rs +++ b/crates/oxc_linter/src/rules/eslint/unicode_bom.rs @@ -1,6 +1,6 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; -use oxc_span::{Span, SPAN}; +use oxc_span::{SPAN, Span}; use crate::{context::LintContext, rule::Rule}; diff --git a/crates/oxc_linter/src/rules/eslint/use_isnan.rs b/crates/oxc_linter/src/rules/eslint/use_isnan.rs index f4f428ba748348..1c6ebacfd96cbf 100644 --- a/crates/oxc_linter/src/rules/eslint/use_isnan.rs +++ b/crates/oxc_linter/src/rules/eslint/use_isnan.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{BinaryExpression, Expression}, AstKind, + ast::{BinaryExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::BinaryOperator; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn comparison_with_na_n(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Requires calls to isNaN() when checking for NaN") diff --git a/crates/oxc_linter/src/rules/eslint/valid_typeof.rs b/crates/oxc_linter/src/rules/eslint/valid_typeof.rs index 6f31076f1887f3..5b740f48b9148c 100644 --- a/crates/oxc_linter/src/rules/eslint/valid_typeof.rs +++ b/crates/oxc_linter/src/rules/eslint/valid_typeof.rs @@ -1,11 +1,11 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use oxc_syntax::operator::UnaryOperator; -use phf::{phf_set, Set}; +use phf::{Set, phf_set}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn not_string(help: Option<&'static str>, span: Span) -> OxcDiagnostic { let mut d = diff --git a/crates/oxc_linter/src/rules/eslint/vars_on_top.rs b/crates/oxc_linter/src/rules/eslint/vars_on_top.rs index 60bed7cb0215b0..31fe8e3b9a83a2 100644 --- a/crates/oxc_linter/src/rules/eslint/vars_on_top.rs +++ b/crates/oxc_linter/src/rules/eslint/vars_on_top.rs @@ -1,10 +1,10 @@ -use oxc_ast::ast::{Declaration, Expression, Program, Statement, VariableDeclarationKind}; use oxc_ast::AstKind; +use oxc_ast::ast::{Declaration, Expression, Program, Statement, VariableDeclarationKind}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn vars_on_top_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("All 'var' declarations must be at the top of the function scope.") @@ -236,10 +236,10 @@ fn test() { first = 2; } ", -"function foo() { + "function foo() { } ", -"function foo() { + "function foo() { var first; if (true) { first = true; @@ -248,7 +248,7 @@ fn test() { } } ", -"function foo() { + "function foo() { var first; var second = 1; var third; @@ -260,14 +260,14 @@ fn test() { first = second; } ", -"function foo() { + "function foo() { var i; for (i = 0; i < 10; i++) { alert(i); } } ", -"function foo() { + "function foo() { var outer; function inner() { var inner = 1; @@ -276,14 +276,14 @@ fn test() { outer = 1; } ", -"function foo() { + "function foo() { var first; //Hello var second = 1; first = second; } ", -"function foo() { + "function foo() { var first; /* Hello Clarice @@ -292,7 +292,7 @@ fn test() { first = second; } ", -"function foo() { + "function foo() { var first; var second = 1; function bar(){ @@ -302,7 +302,7 @@ fn test() { first = second; } ", -"function foo() { + "function foo() { var first; var second = 1; function bar(){ @@ -312,7 +312,7 @@ fn test() { first = second; } ", -"function foo() { + "function foo() { var first; var bar = function(){ var third; @@ -321,7 +321,7 @@ fn test() { first = 5; } ", -"function foo() { + "function foo() { var first; first.onclick(function(){ var third; @@ -330,65 +330,65 @@ fn test() { first = 5; } ", -"function foo() { + "function foo() { var i = 0; for (let j = 0; j < 10; j++) { alert(j); } i = i + 1; }", // { "ecmaVersion": 6 }, -"'use strict'; var x; f();", -"'use strict'; 'directive'; var x; var y; f();", -"function f() { 'use strict'; var x; f(); }", -"function f() { 'use strict'; 'directive'; var x; var y; f(); }", -"import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, -"export var x; + "'use strict'; var x; f();", + "'use strict'; 'directive'; var x; var y; f();", + "function f() { 'use strict'; var x; f(); }", + "function f() { 'use strict'; 'directive'; var x; var y; f(); }", + "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", // { "ecmaVersion": 6, "sourceType": "module" }, + "export var x; var y; var z;", // { "ecmaVersion": 6, "sourceType": "module" }, -"var x; + "var x; export var y; var z;", // { "ecmaVersion": 6, "sourceType": "module" }, -"var x; + "var x; var y; export var z;", // { "ecmaVersion": 6, "sourceType": "module" }, -"class C { + "class C { static { var x; } }", // { "ecmaVersion": 2022 }, -"class C { + "class C { static { var x; foo(); } }", // { "ecmaVersion": 2022 }, -"class C { + "class C { static { var x; var y; } }", // { "ecmaVersion": 2022 }, -"class C { + "class C { static { var x; var y; foo(); } }", // { "ecmaVersion": 2022 }, -"class C { + "class C { static { let x; var y; } }", // { "ecmaVersion": 2022 }, -"class C { + "class C { static { foo(); let x; diff --git a/crates/oxc_linter/src/rules/eslint/yoda.rs b/crates/oxc_linter/src/rules/eslint/yoda.rs index 4fef16fe46aabe..8eb198e803210b 100644 --- a/crates/oxc_linter/src/rules/eslint/yoda.rs +++ b/crates/oxc_linter/src/rules/eslint/yoda.rs @@ -1,16 +1,16 @@ use oxc_ast::{ + AstKind, ast::{ BinaryExpression, BinaryOperator, Expression, LogicalExpression, LogicalOperator, UnaryOperator, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; -use oxc_ecmascript::{is_global_reference::WithoutGlobalReferenceInformation, ToBigInt}; +use oxc_ecmascript::{ToBigInt, is_global_reference::WithoutGlobalReferenceInformation}; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, utils::is_same_expression, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule, utils::is_same_expression}; fn yoda_diagnostic(span: Span, never: bool, operator: &str) -> OxcDiagnostic { let expected_side = if never { "right" } else { "left" }; diff --git a/crates/oxc_linter/src/rules/import/export.rs b/crates/oxc_linter/src/rules/import/export.rs index d493bcabac9874..065e9994c6baf3 100644 --- a/crates/oxc_linter/src/rules/import/export.rs +++ b/crates/oxc_linter/src/rules/import/export.rs @@ -6,7 +6,7 @@ use oxc_diagnostics::{LabeledSpan, OxcDiagnostic}; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; -use crate::{context::LintContext, rule::Rule, ModuleRecord}; +use crate::{ModuleRecord, context::LintContext, rule::Rule}; fn no_named_export(module_name: &str, span: Span) -> OxcDiagnostic { OxcDiagnostic::warn(format!("No named exports found in module '{module_name}'")) @@ -84,11 +84,7 @@ impl Rule for Export { let mut spans = all_export_names .iter() .filter_map(|(star_export_entry_span, export_names)| { - if export_names.contains(name) { - Some(*star_export_entry_span) - } else { - None - } + if export_names.contains(name) { Some(*star_export_entry_span) } else { None } }) .collect::>(); diff --git a/crates/oxc_linter/src/rules/import/first.rs b/crates/oxc_linter/src/rules/import/first.rs index fc44fb6ef1c1e6..1024f828f476d5 100644 --- a/crates/oxc_linter/src/rules/import/first.rs +++ b/crates/oxc_linter/src/rules/import/first.rs @@ -1,8 +1,8 @@ use std::convert::From; use oxc_ast::{ - ast::{Statement, TSModuleReference}, AstKind, + ast::{Statement, TSModuleReference}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/import/namespace.rs b/crates/oxc_linter/src/rules/import/namespace.rs index e1a2d1e17c6ccd..7c9a7a8665fd1d 100644 --- a/crates/oxc_linter/src/rules/import/namespace.rs +++ b/crates/oxc_linter/src/rules/import/namespace.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use oxc_ast::{ - ast::{BindingPatternKind, ObjectPattern}, AstKind, + ast::{BindingPatternKind, ObjectPattern}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -130,10 +130,11 @@ impl Rule for Namespace { let (source, module) = match &entry.import_name { ImportImportName::NamespaceObject => { let source = entry.module_request.name(); - if let Some(module) = loaded_modules.get(source) { - (source.to_string(), Arc::clone(module)) - } else { - return; + match loaded_modules.get(source) { + Some(module) => (source.to_string(), Arc::clone(module)), + _ => { + return; + } } } ImportImportName::Name(name) => { diff --git a/crates/oxc_linter/src/rules/import/no_amd.rs b/crates/oxc_linter/src/rules/import/no_amd.rs index c11b9aab9f7866..a265258e7e64c3 100644 --- a/crates/oxc_linter/src/rules/import/no_amd.rs +++ b/crates/oxc_linter/src/rules/import/no_amd.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{Argument, Expression}, AstKind, + ast::{Argument, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_amd_diagnostic(span: Span, name: &str) -> OxcDiagnostic { OxcDiagnostic::warn("Do not use AMD `require` and `define` calls.") diff --git a/crates/oxc_linter/src/rules/import/no_commonjs.rs b/crates/oxc_linter/src/rules/import/no_commonjs.rs index 646ea9d38a565c..859965bf398920 100644 --- a/crates/oxc_linter/src/rules/import/no_commonjs.rs +++ b/crates/oxc_linter/src/rules/import/no_commonjs.rs @@ -1,12 +1,12 @@ use oxc_ast::{ - ast::{Argument, Expression}, AstKind, + ast::{Argument, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_commonjs_diagnostic(span: Span, name: &str, actual: &str) -> OxcDiagnostic { OxcDiagnostic::warn(format!("Expected {name} instead of {actual}")) diff --git a/crates/oxc_linter/src/rules/import/no_cycle.rs b/crates/oxc_linter/src/rules/import/no_cycle.rs index 75da8164fdc17e..5511040133a6ae 100644 --- a/crates/oxc_linter/src/rules/import/no_cycle.rs +++ b/crates/oxc_linter/src/rules/import/no_cycle.rs @@ -7,10 +7,10 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use crate::{ + ModuleRecord, context::LintContext, module_graph_visitor::{ModuleGraphVisitorBuilder, ModuleGraphVisitorEvent, VisitFoldWhile}, rule::Rule, - ModuleRecord, }; fn no_cycle_diagnostic(span: Span, paths: &str) -> OxcDiagnostic { 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 affbd6ce6a3c4c..be4d0bfed86f2c 100644 --- a/crates/oxc_linter/src/rules/import/no_dynamic_require.rs +++ b/crates/oxc_linter/src/rules/import/no_dynamic_require.rs @@ -1,9 +1,9 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use crate::{context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule}; fn no_dnyamic_require_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Expected a literal string or immutable template literal") diff --git a/crates/oxc_linter/src/rules/import/no_named_as_default_member.rs b/crates/oxc_linter/src/rules/import/no_named_as_default_member.rs index 2b29c3b0b8566c..51f592bc86de30 100644 --- a/crates/oxc_linter/src/rules/import/no_named_as_default_member.rs +++ b/crates/oxc_linter/src/rules/import/no_named_as_default_member.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use oxc_ast::{ - ast::{BindingPatternKind, Expression, IdentifierReference, MemberExpression}, AstKind, + ast::{BindingPatternKind, Expression, IdentifierReference, MemberExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/import/no_webpack_loader_syntax.rs b/crates/oxc_linter/src/rules/import/no_webpack_loader_syntax.rs index ff74f0279d3fe0..17f947d2455d83 100644 --- a/crates/oxc_linter/src/rules/import/no_webpack_loader_syntax.rs +++ b/crates/oxc_linter/src/rules/import/no_webpack_loader_syntax.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, Expression}, AstKind, + ast::{Argument, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/jest/consistent_test_it.rs b/crates/oxc_linter/src/rules/jest/consistent_test_it.rs index 1e5cecaca7c0f9..904e7021d49f87 100644 --- a/crates/oxc_linter/src/rules/jest/consistent_test_it.rs +++ b/crates/oxc_linter/src/rules/jest/consistent_test_it.rs @@ -1,6 +1,6 @@ use std::{borrow::Cow, str::FromStr}; -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::ScopeId; @@ -11,8 +11,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, parse_jest_fn_call, JestFnKind, JestGeneralFnKind, - ParsedJestFnCallNew, PossibleJestNode, + JestFnKind, JestGeneralFnKind, ParsedJestFnCallNew, PossibleJestNode, + collect_possible_jest_call_node, parse_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/expect_expect.rs b/crates/oxc_linter/src/rules/jest/expect_expect.rs index 3daba584658539..268ef8521f416b 100644 --- a/crates/oxc_linter/src/rules/jest/expect_expect.rs +++ b/crates/oxc_linter/src/rules/jest/expect_expect.rs @@ -1,7 +1,7 @@ use cow_utils::CowUtils; use oxc_ast::{ - ast::{CallExpression, Expression, Statement}, AstKind, + ast::{CallExpression, Expression, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -14,7 +14,7 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - get_node_name, is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, get_node_name, is_type_of_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/max_expects.rs b/crates/oxc_linter/src/rules/jest/max_expects.rs index acf96758724b86..03ca05c55f8184 100644 --- a/crates/oxc_linter/src/rules/jest/max_expects.rs +++ b/crates/oxc_linter/src/rules/jest/max_expects.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_index::Idx; use oxc_macros::declare_oxc_lint; @@ -8,7 +8,7 @@ use rustc_hash::FxHashMap; use crate::{ context::LintContext, rule::Rule, - utils::{collect_possible_jest_call_node, PossibleJestNode}, + utils::{PossibleJestNode, collect_possible_jest_call_node}, }; fn exceeded_max_assertion(x0: usize, x1: usize, span2: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/max_nested_describe.rs b/crates/oxc_linter/src/rules/jest/max_nested_describe.rs index 09addf14e60837..6795c00418cb02 100644 --- a/crates/oxc_linter/src/rules/jest/max_nested_describe.rs +++ b/crates/oxc_linter/src/rules/jest/max_nested_describe.rs @@ -8,8 +8,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, - PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, collect_possible_jest_call_node, + is_type_of_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_alias_methods.rs b/crates/oxc_linter/src/rules/jest/no_alias_methods.rs index 806e95343d1569..52b0fd023beb48 100644 --- a/crates/oxc_linter/src/rules/jest/no_alias_methods.rs +++ b/crates/oxc_linter/src/rules/jest/no_alias_methods.rs @@ -6,7 +6,7 @@ use oxc_span::Span; use crate::{ context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, parse_expect_jest_fn_call}, }; fn no_alias_methods_diagnostic(x1: &str, x2: &str, span3: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_commented_out_tests.rs b/crates/oxc_linter/src/rules/jest/no_commented_out_tests.rs index 88941bc2d6c111..4ba7070f28e9b9 100644 --- a/crates/oxc_linter/src/rules/jest/no_commented_out_tests.rs +++ b/crates/oxc_linter/src/rules/jest/no_commented_out_tests.rs @@ -63,11 +63,7 @@ impl Rule for NoCommentedOutTests { let comments = ctx.semantic().comments(); let commented_tests = comments.iter().filter_map(|comment| { let text = ctx.source_range(comment.content_span()); - if RE.is_match(text) { - Some(comment.content_span()) - } else { - None - } + if RE.is_match(text) { Some(comment.content_span()) } else { None } }); for span in commented_tests { ctx.diagnostic(no_commented_out_tests_diagnostic(span)); diff --git a/crates/oxc_linter/src/rules/jest/no_conditional_expect.rs b/crates/oxc_linter/src/rules/jest/no_conditional_expect.rs index ab1900cbdc9f68..51fb8fc64d74e3 100644 --- a/crates/oxc_linter/src/rules/jest/no_conditional_expect.rs +++ b/crates/oxc_linter/src/rules/jest/no_conditional_expect.rs @@ -9,8 +9,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - is_type_of_jest_fn_call, parse_expect_jest_fn_call, JestFnKind, JestGeneralFnKind, - PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, is_type_of_jest_fn_call, + parse_expect_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_conditional_in_test.rs b/crates/oxc_linter/src/rules/jest/no_conditional_in_test.rs index 5fe77d1970db65..5a5b24d9459176 100644 --- a/crates/oxc_linter/src/rules/jest/no_conditional_in_test.rs +++ b/crates/oxc_linter/src/rules/jest/no_conditional_in_test.rs @@ -6,7 +6,7 @@ use oxc_span::Span; use crate::{ context::LintContext, rule::Rule, - utils::{is_type_of_jest_fn_call, JestFnKind, PossibleJestNode}, + utils::{JestFnKind, PossibleJestNode, is_type_of_jest_fn_call}, }; fn no_conditional_in_test(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_confusing_set_timeout.rs b/crates/oxc_linter/src/rules/jest/no_confusing_set_timeout.rs index 87a9a8a9d78d9f..59582bd3e857d9 100644 --- a/crates/oxc_linter/src/rules/jest/no_confusing_set_timeout.rs +++ b/crates/oxc_linter/src/rules/jest/no_confusing_set_timeout.rs @@ -1,5 +1,5 @@ use cow_utils::CowUtils; -use oxc_ast::{ast::MemberExpression, AstKind}; +use oxc_ast::{AstKind, ast::MemberExpression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_semantic::{AstNode, NodeId, ReferenceId}; @@ -9,7 +9,7 @@ use rustc_hash::FxHashMap; use crate::{ context::LintContext, rule::Rule, - utils::{collect_possible_jest_call_node, parse_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, collect_possible_jest_call_node, parse_jest_fn_call}, }; fn no_global_set_timeout_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_deprecated_functions.rs b/crates/oxc_linter/src/rules/jest/no_deprecated_functions.rs index d0922db483ebcb..d6e75c267a5bae 100644 --- a/crates/oxc_linter/src/rules/jest/no_deprecated_functions.rs +++ b/crates/oxc_linter/src/rules/jest/no_deprecated_functions.rs @@ -1,10 +1,10 @@ use std::borrow::Cow; -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use phf::{phf_map, Map}; +use phf::{Map, phf_map}; use crate::{context::LintContext, rule::Rule}; diff --git a/crates/oxc_linter/src/rules/jest/no_disabled_tests.rs b/crates/oxc_linter/src/rules/jest/no_disabled_tests.rs index 70322463f98365..eaabbd2687c4c1 100644 --- a/crates/oxc_linter/src/rules/jest/no_disabled_tests.rs +++ b/crates/oxc_linter/src/rules/jest/no_disabled_tests.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; @@ -7,8 +7,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, ParsedGeneralJestFnCall, - PossibleJestNode, + JestFnKind, JestGeneralFnKind, ParsedGeneralJestFnCall, PossibleJestNode, + parse_general_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_done_callback.rs b/crates/oxc_linter/src/rules/jest/no_done_callback.rs index 59179124580346..5509db844c96b6 100644 --- a/crates/oxc_linter/src/rules/jest/no_done_callback.rs +++ b/crates/oxc_linter/src/rules/jest/no_done_callback.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression, FormalParameters}, AstKind, + ast::{Argument, CallExpression, Expression, FormalParameters}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,7 +10,7 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - get_node_name, parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, get_node_name, parse_general_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_duplicate_hooks.rs b/crates/oxc_linter/src/rules/jest/no_duplicate_hooks.rs index 5b67ce0407d17f..e81d2a43a06493 100644 --- a/crates/oxc_linter/src/rules/jest/no_duplicate_hooks.rs +++ b/crates/oxc_linter/src/rules/jest/no_duplicate_hooks.rs @@ -9,8 +9,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, parse_jest_fn_call, JestFnKind, JestGeneralFnKind, - ParsedJestFnCallNew, PossibleJestNode, + JestFnKind, JestGeneralFnKind, ParsedJestFnCallNew, PossibleJestNode, + collect_possible_jest_call_node, parse_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_focused_tests.rs b/crates/oxc_linter/src/rules/jest/no_focused_tests.rs index 4efec57ad516b1..64c72a7a00f3d7 100644 --- a/crates/oxc_linter/src/rules/jest/no_focused_tests.rs +++ b/crates/oxc_linter/src/rules/jest/no_focused_tests.rs @@ -7,8 +7,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, MemberExpressionElement, - ParsedGeneralJestFnCall, PossibleJestNode, + JestFnKind, JestGeneralFnKind, MemberExpressionElement, ParsedGeneralJestFnCall, + PossibleJestNode, parse_general_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_hooks.rs b/crates/oxc_linter/src/rules/jest/no_hooks.rs index 46adcac92817db..2b62c00875a7db 100644 --- a/crates/oxc_linter/src/rules/jest/no_hooks.rs +++ b/crates/oxc_linter/src/rules/jest/no_hooks.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, GetSpan, Span}; @@ -6,7 +6,7 @@ use oxc_span::{CompactStr, GetSpan, Span}; use crate::{ context::LintContext, rule::Rule, - utils::{is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, is_type_of_jest_fn_call}, }; fn unexpected_hook_diagonsitc(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_identical_title.rs b/crates/oxc_linter/src/rules/jest/no_identical_title.rs index dc20201f54e18b..fe92994fda54ed 100644 --- a/crates/oxc_linter/src/rules/jest/no_identical_title.rs +++ b/crates/oxc_linter/src/rules/jest/no_identical_title.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression}, AstKind, + ast::{Argument, CallExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -9,13 +9,13 @@ use oxc_span::Span; use rustc_hash::FxHashMap; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, - PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, collect_possible_jest_call_node, + parse_general_jest_fn_call, }, - AstNode, }; fn describe_repeat(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_interpolation_in_snapshots.rs b/crates/oxc_linter/src/rules/jest/no_interpolation_in_snapshots.rs index 8a991c6f51bf9f..335e041531b57a 100644 --- a/crates/oxc_linter/src/rules/jest/no_interpolation_in_snapshots.rs +++ b/crates/oxc_linter/src/rules/jest/no_interpolation_in_snapshots.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Argument, AstKind}; +use oxc_ast::{AstKind, ast::Argument}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; @@ -6,7 +6,7 @@ use oxc_span::Span; use crate::{ context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, parse_expect_jest_fn_call}, }; fn no_interpolation_in_snapshots_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_jasmine_globals.rs b/crates/oxc_linter/src/rules/jest/no_jasmine_globals.rs index 6b4222341e9203..a406790d4bcabb 100644 --- a/crates/oxc_linter/src/rules/jest/no_jasmine_globals.rs +++ b/crates/oxc_linter/src/rules/jest/no_jasmine_globals.rs @@ -1,8 +1,8 @@ use oxc_ast::{ + AstKind, ast::{ AssignmentExpression, CallExpression, Expression, MemberExpression, SimpleAssignmentTarget, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/jest/no_large_snapshots.rs b/crates/oxc_linter/src/rules/jest/no_large_snapshots.rs index 19377cb37ea092..9f70e09b72c6ea 100644 --- a/crates/oxc_linter/src/rules/jest/no_large_snapshots.rs +++ b/crates/oxc_linter/src/rules/jest/no_large_snapshots.rs @@ -1,8 +1,8 @@ use std::{ops::Deref, path::Path}; use oxc_ast::{ - ast::{Expression, ExpressionStatement, MemberExpression}, AstKind, + ast::{Expression, ExpressionStatement, MemberExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -13,7 +13,7 @@ use rustc_hash::FxHashMap; use crate::{ context::LintContext, rule::Rule, - utils::{iter_possible_jest_call_node, parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, iter_possible_jest_call_node, parse_expect_jest_fn_call}, }; // TODO: re-word diagnostic messages diff --git a/crates/oxc_linter/src/rules/jest/no_mocks_import.rs b/crates/oxc_linter/src/rules/jest/no_mocks_import.rs index 00934de5ffd79d..cec6a753fdeef0 100644 --- a/crates/oxc_linter/src/rules/jest/no_mocks_import.rs +++ b/crates/oxc_linter/src/rules/jest/no_mocks_import.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use oxc_ast::{ast::Argument, AstKind}; +use oxc_ast::{AstKind, ast::Argument}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; diff --git a/crates/oxc_linter/src/rules/jest/no_restricted_jest_methods.rs b/crates/oxc_linter/src/rules/jest/no_restricted_jest_methods.rs index adab12518391ff..d3901c6dd8ce17 100644 --- a/crates/oxc_linter/src/rules/jest/no_restricted_jest_methods.rs +++ b/crates/oxc_linter/src/rules/jest/no_restricted_jest_methods.rs @@ -7,7 +7,7 @@ use rustc_hash::FxHashMap; use crate::{ context::LintContext, rule::Rule, - utils::{is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, is_type_of_jest_fn_call}, }; fn restricted_jest_method(x0: &str, span1: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_restricted_matchers.rs b/crates/oxc_linter/src/rules/jest/no_restricted_matchers.rs index e7b79a19bb0e12..685b7a28d81da9 100644 --- a/crates/oxc_linter/src/rules/jest/no_restricted_matchers.rs +++ b/crates/oxc_linter/src/rules/jest/no_restricted_matchers.rs @@ -11,8 +11,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - is_type_of_jest_fn_call, parse_expect_jest_fn_call, JestFnKind, - KnownMemberExpressionProperty, PossibleJestNode, + JestFnKind, KnownMemberExpressionProperty, PossibleJestNode, is_type_of_jest_fn_call, + parse_expect_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_standalone_expect/mod.rs b/crates/oxc_linter/src/rules/jest/no_standalone_expect/mod.rs index ce71466eec39f6..8c3590131374f1 100644 --- a/crates/oxc_linter/src/rules/jest/no_standalone_expect/mod.rs +++ b/crates/oxc_linter/src/rules/jest/no_standalone_expect/mod.rs @@ -6,14 +6,14 @@ use oxc_span::{CompactStr, Span}; use rustc_hash::FxHashMap; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, get_node_name, parse_expect_jest_fn_call, - parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, KnownMemberExpressionParentKind, - ParsedExpectFnCall, PossibleJestNode, + JestFnKind, JestGeneralFnKind, KnownMemberExpressionParentKind, ParsedExpectFnCall, + PossibleJestNode, collect_possible_jest_call_node, get_node_name, + parse_expect_jest_fn_call, parse_general_jest_fn_call, }, - AstNode, }; fn no_standalone_expect_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_test_prefixes.rs b/crates/oxc_linter/src/rules/jest/no_test_prefixes.rs index b47e5f8438db03..80b5ed91e3b3e1 100644 --- a/crates/oxc_linter/src/rules/jest/no_test_prefixes.rs +++ b/crates/oxc_linter/src/rules/jest/no_test_prefixes.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Expression, AstKind}; +use oxc_ast::{AstKind, ast::Expression}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; @@ -7,8 +7,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - parse_general_jest_fn_call, JestGeneralFnKind, KnownMemberExpressionProperty, - ParsedGeneralJestFnCall, PossibleJestNode, + JestGeneralFnKind, KnownMemberExpressionProperty, ParsedGeneralJestFnCall, + PossibleJestNode, parse_general_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/no_test_return_statement.rs b/crates/oxc_linter/src/rules/jest/no_test_return_statement.rs index 12058129c88319..182f3f2d0b0d63 100644 --- a/crates/oxc_linter/src/rules/jest/no_test_return_statement.rs +++ b/crates/oxc_linter/src/rules/jest/no_test_return_statement.rs @@ -1,7 +1,7 @@ use oxc_allocator::Box as OBox; use oxc_ast::{ - ast::{CallExpression, Expression, FunctionBody, Statement}, AstKind, + ast::{CallExpression, Expression, FunctionBody, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -11,7 +11,7 @@ use oxc_span::{GetSpan, Span}; use crate::{ context::LintContext, rule::Rule, - utils::{is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, is_type_of_jest_fn_call}, }; fn no_test_return_statement_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/no_untyped_mock_factory.rs b/crates/oxc_linter/src/rules/jest/no_untyped_mock_factory.rs index 52ee202354b261..09a99e86ecc9c9 100644 --- a/crates/oxc_linter/src/rules/jest/no_untyped_mock_factory.rs +++ b/crates/oxc_linter/src/rules/jest/no_untyped_mock_factory.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, Expression}, AstKind, + ast::{Argument, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; diff --git a/crates/oxc_linter/src/rules/jest/prefer_called_with.rs b/crates/oxc_linter/src/rules/jest/prefer_called_with.rs index 13fb89ec374966..1036168bba47cf 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_called_with.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_called_with.rs @@ -6,7 +6,7 @@ use oxc_span::Span; use crate::{ context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, parse_expect_jest_fn_call}, }; fn use_to_be_called_with(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_comparison_matcher.rs b/crates/oxc_linter/src/rules/jest/prefer_comparison_matcher.rs index 03dfaa54b91be4..ceae893f43b235 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_comparison_matcher.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_comparison_matcher.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, BinaryExpression, Expression}, AstKind, + ast::{Argument, BinaryExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -12,8 +12,8 @@ use crate::{ fixer::RuleFixer, rule::Rule, utils::{ - is_equality_matcher, parse_expect_jest_fn_call, KnownMemberExpressionProperty, - PossibleJestNode, + KnownMemberExpressionProperty, PossibleJestNode, is_equality_matcher, + parse_expect_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/prefer_each.rs b/crates/oxc_linter/src/rules/jest/prefer_each.rs index cd928ed521c420..2151de2550e1ea 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_each.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_each.rs @@ -8,7 +8,7 @@ use rustc_hash::FxHashSet; use crate::{ context::LintContext, rule::Rule, - utils::{parse_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, parse_jest_fn_call}, }; fn use_prefer_each(span: Span, fn_name: &str) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_equality_matcher.rs b/crates/oxc_linter/src/rules/jest/prefer_equality_matcher.rs index 75d62c6f01d07e..d25a6ebf53a7ed 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_equality_matcher.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_equality_matcher.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, Expression}, AstKind, + ast::{Argument, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,7 +10,7 @@ use oxc_syntax::operator::BinaryOperator; use crate::{ context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, parse_expect_jest_fn_call}, }; fn use_equality_matcher_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_expect_resolves.rs b/crates/oxc_linter/src/rules/jest/prefer_expect_resolves.rs index f6afa711ff156c..aa8fd9469f1eac 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_expect_resolves.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_expect_resolves.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression}, AstKind, + ast::{Argument, CallExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,7 +10,7 @@ use crate::{ context::LintContext, fixer::{RuleFix, RuleFixer}, rule::Rule, - utils::{parse_expect_jest_fn_call, ParsedExpectFnCall, PossibleJestNode}, + utils::{ParsedExpectFnCall, PossibleJestNode, parse_expect_jest_fn_call}, }; fn expect_resolves(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_hooks_in_order.rs b/crates/oxc_linter/src/rules/jest/prefer_hooks_in_order.rs index 75e40a5f7a31d1..5b906016079c67 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_hooks_in_order.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_hooks_in_order.rs @@ -9,7 +9,7 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - parse_jest_fn_call, JestFnKind, JestGeneralFnKind, ParsedJestFnCallNew, PossibleJestNode, + JestFnKind, JestGeneralFnKind, ParsedJestFnCallNew, PossibleJestNode, parse_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/prefer_hooks_on_top.rs b/crates/oxc_linter/src/rules/jest/prefer_hooks_on_top.rs index 7cdd4fc28641e8..60b920975fbb6a 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_hooks_on_top.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_hooks_on_top.rs @@ -9,8 +9,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, - PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, collect_possible_jest_call_node, + is_type_of_jest_fn_call, }, }; 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 3e806ef2cf1496..19ddd34de4a109 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs @@ -1,13 +1,13 @@ use oxc_ast::{ - ast::{TSAsExpression, TSType, TSTypeAssertion, TSTypeName, TSTypeReference}, AstKind, + ast::{TSAsExpression, TSType, TSTypeAssertion, TSTypeName, TSTypeReference}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; -use phf::{phf_set, Set}; +use phf::{Set, phf_set}; -use crate::{ast_util::outermost_paren_parent, context::LintContext, rule::Rule, AstNode}; +use crate::{AstNode, ast_util::outermost_paren_parent, context::LintContext, rule::Rule}; fn use_jest_mocked(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Prefer `jest.mocked()` over `fn as jest.Mock`.") diff --git a/crates/oxc_linter/src/rules/jest/prefer_lowercase_title/mod.rs b/crates/oxc_linter/src/rules/jest/prefer_lowercase_title/mod.rs index 9927a40418d2a1..11954148137cc7 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_lowercase_title/mod.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_lowercase_title/mod.rs @@ -1,4 +1,4 @@ -use oxc_ast::{ast::Argument, AstKind}; +use oxc_ast::{AstKind, ast::Argument}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; @@ -10,7 +10,7 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - parse_jest_fn_call, JestFnKind, JestGeneralFnKind, ParsedJestFnCallNew, PossibleJestNode, + JestFnKind, JestGeneralFnKind, ParsedJestFnCallNew, PossibleJestNode, parse_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/prefer_mock_promise_shorthand.rs b/crates/oxc_linter/src/rules/jest/prefer_mock_promise_shorthand.rs index c356d05da0a96f..253dbffed5520e 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_mock_promise_shorthand.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_mock_promise_shorthand.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression, Statement}, AstKind, + ast::{Argument, CallExpression, Expression, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -478,8 +478,14 @@ fn test() { ("aVariable.mockReturnValueOnce(Promise.resolve(42))", None), ("aVariable.mockReturnValueOnce(Promise.reject(42))", None), ("aVariable.mockReturnValue(Promise.resolve({ target: 'world', message: 'hello' }))", None), - ("aVariable.mockImplementation(() => Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValue(Promise.reject(42))", None), - ("aVariable.mockReturnValueOnce(Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValueOnce(Promise.reject(42))", None), + ( + "aVariable.mockImplementation(() => Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValue(Promise.reject(42))", + None, + ), + ( + "aVariable.mockReturnValueOnce(Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValueOnce(Promise.reject(42))", + None, + ), ("aVariable.mockReturnValueOnce(Promise.reject(new Error('oh noes!')))", None), ("vi.fn().mockReturnValue(Promise.resolve(42), xyz)", None), ("vi.fn().mockImplementation(() => Promise.reject(42), xyz)", None), @@ -488,32 +494,96 @@ fn test() { ]; let fix_vitest = vec![ - ("vi.fn().mockImplementation(() => Promise.resolve(42))", "vi.fn().mockResolvedValue(42)", None), - ("vi.fn().mockImplementation(() => Promise.reject(42))", "vi.fn().mockRejectedValue(42)", None), - ("aVariable.mockImplementation(() => Promise.resolve(42))", "aVariable.mockResolvedValue(42)", None), - ("aVariable.mockImplementation(() => { return Promise.resolve(42) })", "aVariable.mockResolvedValue(42)", None), - ("aVariable.mockImplementation(() => Promise.reject(42))", "aVariable.mockRejectedValue(42)", None), - ("aVariable.mockImplementation(() => Promise.reject(42),)", "aVariable.mockRejectedValue(42,)", None), - ("aVariable.mockImplementationOnce(() => Promise.resolve(42))", "aVariable.mockResolvedValueOnce(42)", None), - ("aVariable.mockImplementationOnce(() => Promise.reject(42))", "aVariable.mockRejectedValueOnce(42)", None), + ( + "vi.fn().mockImplementation(() => Promise.resolve(42))", + "vi.fn().mockResolvedValue(42)", + None, + ), + ( + "vi.fn().mockImplementation(() => Promise.reject(42))", + "vi.fn().mockRejectedValue(42)", + None, + ), + ( + "aVariable.mockImplementation(() => Promise.resolve(42))", + "aVariable.mockResolvedValue(42)", + None, + ), + ( + "aVariable.mockImplementation(() => { return Promise.resolve(42) })", + "aVariable.mockResolvedValue(42)", + None, + ), + ( + "aVariable.mockImplementation(() => Promise.reject(42))", + "aVariable.mockRejectedValue(42)", + None, + ), + ( + "aVariable.mockImplementation(() => Promise.reject(42),)", + "aVariable.mockRejectedValue(42,)", + None, + ), + ( + "aVariable.mockImplementationOnce(() => Promise.resolve(42))", + "aVariable.mockResolvedValueOnce(42)", + None, + ), + ( + "aVariable.mockImplementationOnce(() => Promise.reject(42))", + "aVariable.mockRejectedValueOnce(42)", + None, + ), ("vi.fn().mockReturnValue(Promise.resolve(42))", "vi.fn().mockResolvedValue(42)", None), ("vi.fn().mockReturnValue(Promise.reject(42))", "vi.fn().mockRejectedValue(42)", None), ("aVariable.mockReturnValue(Promise.resolve(42))", "aVariable.mockResolvedValue(42)", None), ("aVariable.mockReturnValue(Promise.reject(42))", "aVariable.mockRejectedValue(42)", None), - ("aVariable.mockReturnValueOnce(Promise.resolve(42))", "aVariable.mockResolvedValueOnce(42)", None), - ("aVariable.mockReturnValueOnce(Promise.reject(42))", "aVariable.mockRejectedValueOnce(42)", None), + ( + "aVariable.mockReturnValueOnce(Promise.resolve(42))", + "aVariable.mockResolvedValueOnce(42)", + None, + ), + ( + "aVariable.mockReturnValueOnce(Promise.reject(42))", + "aVariable.mockRejectedValueOnce(42)", + None, + ), // Todo: Fixed // ( // "aVariable.mockReturnValue(Promise.resolve({ target: 'world', message: 'hello' }))", - // "aVariable.mockResolvedValue({ target: 'world', message: 'hello' })", + // "aVariable.mockResolvedValue({ target: 'world', message: 'hello' })", // None, // ), - ("aVariable.mockImplementation(() => Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValue(Promise.reject(42))", "aVariable.mockRejectedValue(42).mockResolvedValue(42).mockRejectedValue(42)", None), - ("aVariable.mockReturnValueOnce(Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValueOnce(Promise.reject(42))", "aVariable.mockRejectedValueOnce(42).mockResolvedValue(42).mockRejectedValueOnce(42)", None), - ("aVariable.mockReturnValueOnce(Promise.reject(new Error('oh noes!')))", "aVariable.mockRejectedValueOnce(new Error('oh noes!'))", None), - ("vi.fn().mockReturnValue(Promise.resolve(42), xyz)", "vi.fn().mockResolvedValue(42, xyz)", None), - ("vi.fn().mockImplementation(() => Promise.reject(42), xyz)", "vi.fn().mockRejectedValue(42, xyz)", None), - ("aVariable.mockReturnValueOnce(Promise.resolve())", "aVariable.mockResolvedValueOnce(undefined)", None) + ( + "aVariable.mockImplementation(() => Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValue(Promise.reject(42))", + "aVariable.mockRejectedValue(42).mockResolvedValue(42).mockRejectedValue(42)", + None, + ), + ( + "aVariable.mockReturnValueOnce(Promise.reject(42)).mockImplementation(() => Promise.resolve(42)).mockReturnValueOnce(Promise.reject(42))", + "aVariable.mockRejectedValueOnce(42).mockResolvedValue(42).mockRejectedValueOnce(42)", + None, + ), + ( + "aVariable.mockReturnValueOnce(Promise.reject(new Error('oh noes!')))", + "aVariable.mockRejectedValueOnce(new Error('oh noes!'))", + None, + ), + ( + "vi.fn().mockReturnValue(Promise.resolve(42), xyz)", + "vi.fn().mockResolvedValue(42, xyz)", + None, + ), + ( + "vi.fn().mockImplementation(() => Promise.reject(42), xyz)", + "vi.fn().mockRejectedValue(42, xyz)", + None, + ), + ( + "aVariable.mockReturnValueOnce(Promise.resolve())", + "aVariable.mockResolvedValueOnce(undefined)", + None, + ), ]; pass.extend(pass_vitest); diff --git a/crates/oxc_linter/src/rules/jest/prefer_spy_on.rs b/crates/oxc_linter/src/rules/jest/prefer_spy_on.rs index 20c17e56489160..18bf9a12a359aa 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_spy_on.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_spy_on.rs @@ -1,9 +1,9 @@ use oxc_ast::{ + AstKind, ast::{ Argument, AssignmentExpression, CallExpression, Expression, MemberExpression, SimpleAssignmentTarget, }, - AstKind, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -14,7 +14,7 @@ use crate::{ context::LintContext, fixer::RuleFixer, rule::Rule, - utils::{get_node_name, parse_general_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, get_node_name, parse_general_jest_fn_call}, }; fn use_jest_spy_on(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_strict_equal.rs b/crates/oxc_linter/src/rules/jest/prefer_strict_equal.rs index b638bd4d46e80c..f777ddbbf3c896 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_strict_equal.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_strict_equal.rs @@ -5,7 +5,7 @@ use oxc_span::Span; use crate::{ context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, parse_expect_jest_fn_call}, }; fn use_to_strict_equal(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_to_be.rs b/crates/oxc_linter/src/rules/jest/prefer_to_be.rs index d75f9951365f60..c40b0995636e21 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_to_be.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_to_be.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression}, AstKind, + ast::{Argument, CallExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,8 +10,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - is_equality_matcher, parse_expect_jest_fn_call, KnownMemberExpressionProperty, - ParsedExpectFnCall, PossibleJestNode, + KnownMemberExpressionProperty, ParsedExpectFnCall, PossibleJestNode, is_equality_matcher, + parse_expect_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/prefer_to_contain.rs b/crates/oxc_linter/src/rules/jest/prefer_to_contain.rs index e8994992cbbdeb..1051bde37bc72f 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_to_contain.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_to_contain.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression}, AstKind, + ast::{Argument, CallExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,8 +10,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - is_equality_matcher, parse_expect_jest_fn_call, KnownMemberExpressionParentKind, - PossibleJestNode, + KnownMemberExpressionParentKind, PossibleJestNode, is_equality_matcher, + parse_expect_jest_fn_call, }, }; 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 1576827faacb33..15a041ee87f10d 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 @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{match_member_expression, CallExpression, Expression, MemberExpression}, AstKind, + ast::{CallExpression, Expression, MemberExpression, match_member_expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,7 +10,7 @@ use crate::{ context::LintContext, fixer::RuleFixer, rule::Rule, - utils::{is_equality_matcher, parse_expect_jest_fn_call, ParsedExpectFnCall, PossibleJestNode}, + utils::{ParsedExpectFnCall, PossibleJestNode, is_equality_matcher, parse_expect_jest_fn_call}, }; fn use_to_have_length(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/prefer_todo.rs b/crates/oxc_linter/src/rules/jest/prefer_todo.rs index 6e0ee4d6dc30f4..419479772a37d3 100644 --- a/crates/oxc_linter/src/rules/jest/prefer_todo.rs +++ b/crates/oxc_linter/src/rules/jest/prefer_todo.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, CallExpression, Expression}, AstKind, + ast::{Argument, CallExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,7 +10,7 @@ use crate::{ context::LintContext, fixer::{RuleFix, RuleFixer}, rule::Rule, - utils::{is_type_of_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, is_type_of_jest_fn_call}, }; fn empty_test(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/require_hook.rs b/crates/oxc_linter/src/rules/jest/require_hook.rs index e35d6792742bb3..89493c4c205a11 100644 --- a/crates/oxc_linter/src/rules/jest/require_hook.rs +++ b/crates/oxc_linter/src/rules/jest/require_hook.rs @@ -1,7 +1,7 @@ use oxc_allocator::Vec as OxcVec; use oxc_ast::{ - ast::{Argument, Expression, Statement, VariableDeclarationKind}, AstKind, + ast::{Argument, Expression, Statement, VariableDeclarationKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -12,8 +12,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - get_node_name, is_type_of_jest_fn_call, parse_jest_fn_call, JestFnKind, JestGeneralFnKind, - PossibleJestNode, + JestFnKind, JestGeneralFnKind, PossibleJestNode, get_node_name, is_type_of_jest_fn_call, + parse_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/require_to_throw_message.rs b/crates/oxc_linter/src/rules/jest/require_to_throw_message.rs index a7b24bd52f67bc..3b6f6beb7862ab 100644 --- a/crates/oxc_linter/src/rules/jest/require_to_throw_message.rs +++ b/crates/oxc_linter/src/rules/jest/require_to_throw_message.rs @@ -6,7 +6,7 @@ use oxc_span::Span; use crate::{ context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, PossibleJestNode}, + utils::{PossibleJestNode, parse_expect_jest_fn_call}, }; fn require_to_throw_message_diagnostic(x0: &str, span1: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jest/require_top_level_describe.rs b/crates/oxc_linter/src/rules/jest/require_top_level_describe.rs index 8699ea65e42592..1c1dd194bc3441 100644 --- a/crates/oxc_linter/src/rules/jest/require_top_level_describe.rs +++ b/crates/oxc_linter/src/rules/jest/require_top_level_describe.rs @@ -9,8 +9,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - collect_possible_jest_call_node, parse_jest_fn_call, JestFnKind, JestGeneralFnKind, - ParsedGeneralJestFnCall, ParsedJestFnCallNew, PossibleJestNode, + JestFnKind, JestGeneralFnKind, ParsedGeneralJestFnCall, ParsedJestFnCallNew, + PossibleJestNode, collect_possible_jest_call_node, parse_jest_fn_call, }, }; diff --git a/crates/oxc_linter/src/rules/jest/valid_describe_callback.rs b/crates/oxc_linter/src/rules/jest/valid_describe_callback.rs index 102c1a0a2c4c54..4d569dfeac5c4c 100644 --- a/crates/oxc_linter/src/rules/jest/valid_describe_callback.rs +++ b/crates/oxc_linter/src/rules/jest/valid_describe_callback.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{Argument, Expression, FunctionBody, Statement}, AstKind, + ast::{Argument, Expression, FunctionBody, Statement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -9,7 +9,7 @@ use oxc_span::{GetSpan, Span}; use crate::{ context::LintContext, rule::Rule, - utils::{parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, parse_general_jest_fn_call}, }; fn valid_describe_callback_diagnostic( diff --git a/crates/oxc_linter/src/rules/jest/valid_expect.rs b/crates/oxc_linter/src/rules/jest/valid_expect.rs index f80f46da6ac998..753cc767842404 100644 --- a/crates/oxc_linter/src/rules/jest/valid_expect.rs +++ b/crates/oxc_linter/src/rules/jest/valid_expect.rs @@ -1,18 +1,18 @@ use std::borrow::Cow; use oxc_ast::{ - ast::{Expression, MemberExpression}, AstKind, + ast::{Expression, MemberExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, - utils::{parse_expect_jest_fn_call, ExpectError, PossibleJestNode}, - AstNode, + utils::{ExpectError, PossibleJestNode, parse_expect_jest_fn_call}, }; fn valid_expect_diagnostic>>( diff --git a/crates/oxc_linter/src/rules/jest/valid_title.rs b/crates/oxc_linter/src/rules/jest/valid_title.rs index d4a1b0979e3bff..5b5444ce62325a 100644 --- a/crates/oxc_linter/src/rules/jest/valid_title.rs +++ b/crates/oxc_linter/src/rules/jest/valid_title.rs @@ -2,8 +2,8 @@ use std::hash::Hash; use cow_utils::CowUtils; use oxc_ast::{ - ast::{Argument, BinaryExpression, Expression}, AstKind, + ast::{Argument, BinaryExpression, Expression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -14,7 +14,7 @@ use rustc_hash::FxHashMap; use crate::{ context::LintContext, rule::Rule, - utils::{parse_general_jest_fn_call, JestFnKind, JestGeneralFnKind, PossibleJestNode}, + utils::{JestFnKind, JestGeneralFnKind, PossibleJestNode, parse_general_jest_fn_call}, }; fn valid_title_diagnostic(x0: &str, x1: &str, span2: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/implements_on_classes.rs b/crates/oxc_linter/src/rules/jsdoc/implements_on_classes.rs index e3568ee569cef7..2224452a0241b2 100644 --- a/crates/oxc_linter/src/rules/jsdoc/implements_on_classes.rs +++ b/crates/oxc_linter/src/rules/jsdoc/implements_on_classes.rs @@ -4,11 +4,11 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, ast_util::is_function_node, context::LintContext, rule::Rule, utils::{get_function_nearest_jsdoc_node, should_ignore_as_internal, should_ignore_as_private}, - AstNode, }; fn implements_on_classes_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/no_defaults.rs b/crates/oxc_linter/src/rules/jsdoc/no_defaults.rs index c3a1757a920455..b92e47dd70d782 100644 --- a/crates/oxc_linter/src/rules/jsdoc/no_defaults.rs +++ b/crates/oxc_linter/src/rules/jsdoc/no_defaults.rs @@ -4,11 +4,11 @@ use oxc_span::Span; use serde::Deserialize; use crate::{ + AstNode, ast_util::is_function_node, context::LintContext, rule::Rule, utils::{get_function_nearest_jsdoc_node, should_ignore_as_internal, should_ignore_as_private}, - AstNode, }; fn no_defaults_diagnostic(span: Span, x1: &str) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/require_param.rs b/crates/oxc_linter/src/rules/jsdoc/require_param.rs index 381318eda0ae57..f52ece103e46a9 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_param.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_param.rs @@ -1,7 +1,7 @@ use std::sync::Mutex; use lazy_static::lazy_static; -use oxc_ast::{ast::MethodDefinitionKind, AstKind}; +use oxc_ast::{AstKind, ast::MethodDefinitionKind}; use oxc_diagnostics::{LabeledSpan, OxcDiagnostic}; use oxc_macros::declare_oxc_lint; use oxc_semantic::{AstNode, JSDoc}; @@ -13,8 +13,8 @@ use crate::{ context::LintContext, rule::Rule, utils::{ - collect_params, default_true, get_function_nearest_jsdoc_node, should_ignore_as_avoid, - should_ignore_as_internal, should_ignore_as_private, ParamKind, + ParamKind, collect_params, default_true, get_function_nearest_jsdoc_node, + should_ignore_as_avoid, should_ignore_as_internal, should_ignore_as_private, }, }; diff --git a/crates/oxc_linter/src/rules/jsdoc/require_param_description.rs b/crates/oxc_linter/src/rules/jsdoc/require_param_description.rs index 1ffe665a78c342..bd9576bc37ab64 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_param_description.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_param_description.rs @@ -4,13 +4,13 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ - collect_params, get_function_nearest_jsdoc_node, should_ignore_as_internal, - should_ignore_as_private, ParamKind, + ParamKind, collect_params, get_function_nearest_jsdoc_node, should_ignore_as_internal, + should_ignore_as_private, }, - AstNode, }; fn missing_type_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/require_param_name.rs b/crates/oxc_linter/src/rules/jsdoc/require_param_name.rs index bc0968b8f605cf..4fc6b3d7f6a78f 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_param_name.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_param_name.rs @@ -3,11 +3,11 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, ast_util::is_function_node, context::LintContext, rule::Rule, utils::{get_function_nearest_jsdoc_node, should_ignore_as_internal, should_ignore_as_private}, - AstNode, }; fn missing_name_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/require_param_type.rs b/crates/oxc_linter/src/rules/jsdoc/require_param_type.rs index a4735cbbec8f22..f5d19d5ad8eafc 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_param_type.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_param_type.rs @@ -4,13 +4,13 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ - collect_params, get_function_nearest_jsdoc_node, should_ignore_as_internal, - should_ignore_as_private, ParamKind, + ParamKind, collect_params, get_function_nearest_jsdoc_node, should_ignore_as_internal, + should_ignore_as_private, }, - AstNode, }; fn missing_type_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/require_returns.rs b/crates/oxc_linter/src/rules/jsdoc/require_returns.rs index 8b8371b4d1b361..7f7d7fd1ed6899 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_returns.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_returns.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{BindingPatternKind, Expression, MethodDefinitionKind}, AstKind, + ast::{BindingPatternKind, Expression, MethodDefinitionKind}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -157,7 +157,7 @@ impl Rule for RequireReturns { // If `return somePromise` is found, treat this function as async match is_promise_resolve_with_value(argument, ctx) { Some(v) => e.2 = (true, v), - None => e.2 = (e.2 .0, true), + None => e.2 = (e.2.0, true), } }); continue 'visit_node; diff --git a/crates/oxc_linter/src/rules/jsdoc/require_returns_description.rs b/crates/oxc_linter/src/rules/jsdoc/require_returns_description.rs index 32f86f27f211e9..6dd4bc81c3a87c 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_returns_description.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_returns_description.rs @@ -3,11 +3,11 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, ast_util::is_function_node, context::LintContext, rule::Rule, utils::{get_function_nearest_jsdoc_node, should_ignore_as_internal, should_ignore_as_private}, - AstNode, }; fn missing_description_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/require_returns_type.rs b/crates/oxc_linter/src/rules/jsdoc/require_returns_type.rs index 6f44c6affb454f..c2f79cac13beb5 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_returns_type.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_returns_type.rs @@ -3,11 +3,11 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, ast_util::is_function_node, context::LintContext, rule::Rule, utils::{get_function_nearest_jsdoc_node, should_ignore_as_internal, should_ignore_as_private}, - AstNode, }; fn missing_type_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsdoc/require_yields.rs b/crates/oxc_linter/src/rules/jsdoc/require_yields.rs index 3dac3516452bcb..2be16b65d2f3be 100644 --- a/crates/oxc_linter/src/rules/jsdoc/require_yields.rs +++ b/crates/oxc_linter/src/rules/jsdoc/require_yields.rs @@ -7,13 +7,13 @@ use phf::phf_set; use serde::Deserialize; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ get_function_nearest_jsdoc_node, should_ignore_as_avoid, should_ignore_as_internal, should_ignore_as_private, }, - AstNode, }; fn missing_yields(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/alt_text.rs b/crates/oxc_linter/src/rules/jsx_a11y/alt_text.rs index e3b48f437b6766..c85434f6b2d1f2 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/alt_text.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/alt_text.rs @@ -1,19 +1,19 @@ use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeValue, JSXElement, JSXOpeningElement}, AstKind, + ast::{JSXAttributeItem, JSXAttributeValue, JSXElement, JSXOpeningElement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ get_element_type, get_prop_value, get_string_literal_prop_value, has_jsx_prop_ignore_case, object_has_accessible_child, }, - AstNode, }; fn missing_alt_prop(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/anchor_ambiguous_text.rs b/crates/oxc_linter/src/rules/jsx_a11y/anchor_ambiguous_text.rs index 046e8c5e636ff7..e3cc6d859ab1b9 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/anchor_ambiguous_text.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/anchor_ambiguous_text.rs @@ -1,21 +1,21 @@ use std::borrow::Cow; use oxc_ast::{ - ast::{JSXChild, JSXElement}, AstKind, + ast::{JSXChild, JSXElement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ get_element_type, get_string_literal_prop_value, has_jsx_prop_ignore_case, is_hidden_from_screen_reader, }, - AstNode, }; fn anchor_has_ambiguous_text(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/anchor_has_content.rs b/crates/oxc_linter/src/rules/jsx_a11y/anchor_has_content.rs index 70c25bd262f200..a1586e2ba2f146 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/anchor_has_content.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/anchor_has_content.rs @@ -1,12 +1,13 @@ use oxc_ast::{ - ast::{JSXAttributeItem, JSXChild, JSXElement}, AstKind, + ast::{JSXAttributeItem, JSXChild, JSXElement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::LintContext, fixer::{Fix, RuleFix}, rule::Rule, @@ -14,7 +15,6 @@ use crate::{ get_element_type, has_jsx_prop_ignore_case, is_hidden_from_screen_reader, object_has_accessible_child, }, - AstNode, }; fn missing_content(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/anchor_is_valid.rs b/crates/oxc_linter/src/rules/jsx_a11y/anchor_is_valid.rs index accbfac2fa2e60..b46bbcd04c8d60 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/anchor_is_valid.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/anchor_is_valid.rs @@ -1,8 +1,8 @@ use std::ops::Deref; use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeValue, JSXExpression}, AstKind, + ast::{JSXAttributeItem, JSXAttributeValue, JSXExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,10 +10,10 @@ use oxc_span::{CompactStr, GetSpan, Span}; use serde_json::Value; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, has_jsx_prop_ignore_case}, - AstNode, }; fn missing_href_attribute(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/aria_activedescendant_has_tabindex.rs b/crates/oxc_linter/src/rules/jsx_a11y/aria_activedescendant_has_tabindex.rs index 82d5d0260768f3..dc9c25f238b3f5 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/aria_activedescendant_has_tabindex.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/aria_activedescendant_has_tabindex.rs @@ -1,17 +1,17 @@ use oxc_ast::{ - ast::{JSXAttribute, JSXAttributeItem, JSXElementName}, AstKind, + ast::{JSXAttribute, JSXAttributeItem, JSXElementName}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::LintContext, globals::HTML_TAG, rule::Rule, utils::{get_element_type, has_jsx_prop_ignore_case, is_interactive_element, parse_jsx_value}, - AstNode, }; fn aria_activedescendant_has_tabindex_diagnostic(span: Span, el_name: &str) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/aria_props.rs b/crates/oxc_linter/src/rules/jsx_a11y/aria_props.rs index c19a92fbd66d1c..8e82c58e8eb12c 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/aria_props.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/aria_props.rs @@ -1,12 +1,12 @@ use cow_utils::CowUtils; -use oxc_ast::{ast::JSXAttributeItem, AstKind}; +use oxc_ast::{AstKind, ast::JSXAttributeItem}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use crate::{ - context::LintContext, globals::VALID_ARIA_PROPS, rule::Rule, utils::get_jsx_attribute_name, - AstNode, + AstNode, context::LintContext, globals::VALID_ARIA_PROPS, rule::Rule, + utils::get_jsx_attribute_name, }; fn aria_props_diagnostic(span: Span, prop_name: &str, suggestion: Option<&str>) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/aria_role.rs b/crates/oxc_linter/src/rules/jsx_a11y/aria_role.rs index 236b65b5e7327a..6a52b8d9c1ff06 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/aria_role.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/aria_role.rs @@ -1,17 +1,17 @@ use oxc_ast::{ - ast::{JSXAttributeValue, JSXExpression}, AstKind, + ast::{JSXAttributeValue, JSXExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::LintContext, globals::{HTML_TAG, VALID_ARIA_ROLES}, rule::Rule, utils::{get_element_type, get_prop_value, has_jsx_prop}, - AstNode, }; fn aria_role_diagnostic(span: Span, help_suffix: &str) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/aria_unsupported_elements.rs b/crates/oxc_linter/src/rules/jsx_a11y/aria_unsupported_elements.rs index 1adf3572b5d64d..844d0a5b700e7b 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/aria_unsupported_elements.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/aria_unsupported_elements.rs @@ -1,15 +1,15 @@ use cow_utils::CowUtils; -use oxc_ast::{ast::JSXAttributeItem, AstKind}; +use oxc_ast::{AstKind, ast::JSXAttributeItem}; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use phf::phf_set; use crate::{ + AstNode, LintContext, globals::RESERVED_HTML_TAG, rule::Rule, utils::{get_element_type, get_jsx_attribute_name}, - AstNode, LintContext, }; declare_oxc_lint! { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/autocomplete_valid.rs b/crates/oxc_linter/src/rules/jsx_a11y/autocomplete_valid.rs index 61c96dec9dc36d..ef7222d3c97dce 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/autocomplete_valid.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/autocomplete_valid.rs @@ -1,6 +1,6 @@ use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeValue}, AstKind, + ast::{JSXAttributeItem, JSXAttributeValue}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -10,10 +10,10 @@ use rustc_hash::FxHashSet; use serde_json::Value; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, has_jsx_prop_ignore_case}, - AstNode, }; fn autocomplete_valid_diagnostic(span: Span, autocomplete: &str) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/click_events_have_key_events.rs b/crates/oxc_linter/src/rules/jsx_a11y/click_events_have_key_events.rs index 4f6257c3e9bca1..05443b9e7b5004 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/click_events_have_key_events.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/click_events_have_key_events.rs @@ -4,6 +4,7 @@ use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ + AstNode, context::LintContext, globals::HTML_TAG, rule::Rule, @@ -11,7 +12,6 @@ use crate::{ get_element_type, has_jsx_prop, is_hidden_from_screen_reader, is_interactive_element, is_presentation_role, }, - AstNode, }; fn click_events_have_key_events_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/heading_has_content.rs b/crates/oxc_linter/src/rules/jsx_a11y/heading_has_content.rs index b6d72e72c1848f..d2777f33c5d380 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/heading_has_content.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/heading_has_content.rs @@ -4,10 +4,10 @@ use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, is_hidden_from_screen_reader, object_has_accessible_child}, - AstNode, }; fn heading_has_content_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/html_has_lang.rs b/crates/oxc_linter/src/rules/jsx_a11y/html_has_lang.rs index 4d1189331e0d58..ac4b5c49d1b563 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/html_has_lang.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/html_has_lang.rs @@ -1,16 +1,16 @@ use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeValue, JSXExpression}, AstKind, + ast::{JSXAttributeItem, JSXAttributeValue, JSXExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, get_prop_value, has_jsx_prop_ignore_case}, - AstNode, }; fn missing_lang_prop(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/iframe_has_title.rs b/crates/oxc_linter/src/rules/jsx_a11y/iframe_has_title.rs index b23b5d5b4cac16..82b1d3222ae43a 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/iframe_has_title.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/iframe_has_title.rs @@ -1,16 +1,16 @@ use oxc_ast::{ - ast::{JSXAttributeValue, JSXExpression}, AstKind, + ast::{JSXAttributeValue, JSXExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, get_prop_value, has_jsx_prop_ignore_case}, - AstNode, }; fn iframe_has_title_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/img_redundant_alt.rs b/crates/oxc_linter/src/rules/jsx_a11y/img_redundant_alt.rs index 3e8f7a25c6cb1a..dcf004d306ce61 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/img_redundant_alt.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/img_redundant_alt.rs @@ -2,8 +2,8 @@ use std::borrow::Cow; use cow_utils::CowUtils; use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeName, JSXAttributeValue, JSXExpression}, AstKind, + ast::{JSXAttributeItem, JSXAttributeName, JSXAttributeValue, JSXExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; @@ -11,12 +11,12 @@ use oxc_span::{CompactStr, Span}; use serde_json::Value; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{ get_element_type, get_prop_value, has_jsx_prop_ignore_case, is_hidden_from_screen_reader, }, - AstNode, }; fn img_redundant_alt_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/label_has_associated_control.rs b/crates/oxc_linter/src/rules/jsx_a11y/label_has_associated_control.rs index 0b70cb2c7353ff..91deb192c89704 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/label_has_associated_control.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/label_has_associated_control.rs @@ -2,18 +2,18 @@ use std::ops::Deref; use globset::{Glob, GlobSet, GlobSetBuilder}; use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeValue, JSXChild, JSXElement}, AstKind, + ast::{JSXAttributeItem, JSXAttributeValue, JSXChild, JSXElement}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{CompactStr, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, get_jsx_attribute_name, has_jsx_prop, is_react_component_name}, - AstNode, }; fn label_has_associated_control_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/lang.rs b/crates/oxc_linter/src/rules/jsx_a11y/lang.rs index 32a47da0fab7b2..f8d1deb275fd6e 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/lang.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/lang.rs @@ -1,17 +1,17 @@ use language_tags::LanguageTag; use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeValue}, AstKind, + ast::{JSXAttributeItem, JSXAttributeValue}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::{GetSpan, Span}; use crate::{ + AstNode, context::LintContext, rule::Rule, utils::{get_element_type, get_prop_value, has_jsx_prop_ignore_case}, - AstNode, }; fn lang_diagnostic(span: Span) -> OxcDiagnostic { diff --git a/crates/oxc_linter/src/rules/jsx_a11y/media_has_caption.rs b/crates/oxc_linter/src/rules/jsx_a11y/media_has_caption.rs index ad1c9266fd1456..8dd45c94331485 100644 --- a/crates/oxc_linter/src/rules/jsx_a11y/media_has_caption.rs +++ b/crates/oxc_linter/src/rules/jsx_a11y/media_has_caption.rs @@ -1,15 +1,15 @@ use std::borrow::Cow; use oxc_ast::{ - ast::{JSXAttributeItem, JSXAttributeName, JSXAttributeValue, JSXChild, JSXExpression}, AstKind, + ast::{JSXAttributeItem, JSXAttributeName, JSXAttributeValue, JSXChild, JSXExpression}, }; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use serde_json::Value; -use crate::{context::LintContext, rule::Rule, utils::get_element_type, AstNode}; +use crate::{AstNode, context::LintContext, rule::Rule, utils::get_element_type}; fn media_has_caption_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Missing element with captions inside