diff --git a/.kodiak.toml b/.kodiak.toml index 28cf327f0cc..7f7b9da6b3e 100644 --- a/.kodiak.toml +++ b/.kodiak.toml @@ -8,6 +8,7 @@ do_not_merge = true [update] autoupdate_label = "S-approved" +require_automerge_label = false # I want to use auto-merge feature of github [approve] diff --git a/.rustfmt.toml b/.rustfmt.toml index 1ffbc780ed3..729e340ee47 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,4 +1,7 @@ format_strings = true +group_imports = "StdExternalCrate" +hex_literal_case = "Lower" imports_granularity = "Crate" +reorder_impl_items = true use_field_init_shorthand = true wrap_comments = true diff --git a/crates/enum_kind/src/expand.rs b/crates/enum_kind/src/expand.rs index f3b0e8ed858..4c37f7a8c93 100644 --- a/crates/enum_kind/src/expand.rs +++ b/crates/enum_kind/src/expand.rs @@ -1,8 +1,9 @@ -use crate::{input::*, util::is_bool}; use pmutil::{smart_quote, Quote, SpanExt}; use swc_macros_common::prelude::*; use syn::*; +use crate::{input::*, util::is_bool}; + pub fn expand( Input { attrs, diff --git a/crates/enum_kind/src/parse.rs b/crates/enum_kind/src/parse.rs index 3f107ccccfc..51ecece57a0 100644 --- a/crates/enum_kind/src/parse.rs +++ b/crates/enum_kind/src/parse.rs @@ -1,11 +1,13 @@ -use crate::{input::*, util::is_bool}; use std::{fmt::Display, ops::AddAssign, result::Result as StdResult}; + use swc_macros_common::prelude::*; use syn::{ parse::{Parse, ParseStream}, *, }; +use crate::{input::*, util::is_bool}; + impl From for Input { fn from( DeriveInput { diff --git a/crates/jsdoc/src/input.rs b/crates/jsdoc/src/input.rs index 27bde6c216f..c8aa92e04b0 100644 --- a/crates/jsdoc/src/input.rs +++ b/crates/jsdoc/src/input.rs @@ -1,11 +1,13 @@ -use crate::ast::Text; -use nom::{Compare, CompareResult, InputIter, InputLength, InputTake, Slice, UnspecializedInput}; use std::{ ops::{Deref, Range, RangeFrom, RangeTo}, str::{CharIndices, Chars}, }; + +use nom::{Compare, CompareResult, InputIter, InputLength, InputTake, Slice, UnspecializedInput}; use swc_common::{comments::Comment, BytePos, Span}; +use crate::ast::Text; + #[derive(Debug, Clone, Copy)] pub struct Input<'i> { start: BytePos, diff --git a/crates/jsdoc/src/lib.rs b/crates/jsdoc/src/lib.rs index b7d40a7ec65..6e4f8a4e407 100644 --- a/crates/jsdoc/src/lib.rs +++ b/crates/jsdoc/src/lib.rs @@ -1,5 +1,3 @@ -pub use self::input::Input; -use crate::ast::*; use nom::{ bytes::complete::{tag, take_while}, error::ErrorKind, @@ -7,6 +5,9 @@ use nom::{ }; use swc_common::{Span, Spanned, SyntaxContext}; +pub use self::input::Input; +use crate::ast::*; + pub mod ast; mod input; @@ -662,9 +663,10 @@ fn skip(i: Input) -> Input { #[cfg(test)] mod tests { - use super::*; use swc_common::BytePos; + use super::*; + fn input(s: &str) -> Input { Input::new(BytePos(0), BytePos(s.as_bytes().len() as _), s) } diff --git a/crates/jsdoc/tests/fixture.rs b/crates/jsdoc/tests/fixture.rs index deeea2a1bc4..71d212c6d47 100644 --- a/crates/jsdoc/tests/fixture.rs +++ b/crates/jsdoc/tests/fixture.rs @@ -1,7 +1,8 @@ #![feature(bench_black_box)] -use dashmap::DashMap; use std::path::PathBuf; + +use dashmap::DashMap; use swc_common::{ comments::{Comment, CommentKind, Comments}, BytePos, DUMMY_SP, diff --git a/crates/node/src/bundle.rs b/crates/node/src/bundle.rs index df4c447e848..b7c8f177906 100644 --- a/crates/node/src/bundle.rs +++ b/crates/node/src/bundle.rs @@ -1,17 +1,14 @@ -use crate::{ - get_compiler, - util::{get_deserialized, MapErr}, +use std::{ + panic::{catch_unwind, AssertUnwindSafe}, + sync::Arc, }; + use anyhow::{bail, Error}; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Status, Task, }; use serde::Deserialize; -use std::{ - panic::{catch_unwind, AssertUnwindSafe}, - sync::Arc, -}; use swc::{ config::SourceMapsConfig, resolver::{environment_resolver, paths_resolver}, @@ -26,6 +23,11 @@ use swc_ecma_ast::{ }; use swc_ecma_loader::{TargetEnv, NODE_BUILTINS}; +use crate::{ + get_compiler, + util::{get_deserialized, MapErr}, +}; + struct ConfigItem { loader: Box, resolver: Box, @@ -48,8 +50,8 @@ pub(crate) struct BundleTask { #[cfg(feature = "swc_v1")] #[napi] impl Task for BundleTask { - type Output = AHashMap; type JsValue = AHashMap; + type Output = AHashMap; fn compute(&mut self) -> napi::Result { let builtins = if let TargetEnv::Node = self.config.static_items.config.target { @@ -166,8 +168,8 @@ impl Task for BundleTask { #[cfg(feature = "swc_v2")] impl Task for BundleTask { - type Output = AHashMap; type JsValue = AHashMap; + type Output = AHashMap; fn compute(&mut self) -> napi::Result { todo!() diff --git a/crates/node/src/lib.rs b/crates/node/src/lib.rs index b94ce9491f4..320deec30e4 100644 --- a/crates/node/src/lib.rs +++ b/crates/node/src/lib.rs @@ -6,8 +6,9 @@ extern crate napi_derive; /// Explicit extern crate to use allocator. extern crate swc_node_base; -use backtrace::Backtrace; use std::{env, panic::set_hook, sync::Arc}; + +use backtrace::Backtrace; use swc::Compiler; use swc_common::{self, sync::Lazy, FilePathMapping, SourceMap}; use tracing_subscriber::EnvFilter; diff --git a/crates/node/src/minify.rs b/crates/node/src/minify.rs index e094575ef56..b3fdde41985 100644 --- a/crates/node/src/minify.rs +++ b/crates/node/src/minify.rs @@ -1,16 +1,18 @@ -use crate::{ - get_compiler, - util::{deserialize_json, get_deserialized, try_with, MapErr}, -}; +use std::sync::Arc; + use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Task, }; use serde::Deserialize; -use std::sync::Arc; use swc::{config::JsMinifyOptions, TransformOutput}; use swc_common::{collections::AHashMap, sync::Lrc, FileName, SourceFile, SourceMap}; +use crate::{ + get_compiler, + util::{deserialize_json, get_deserialized, try_with, MapErr}, +}; + struct MinifyTask { c: Arc, code: String, @@ -47,9 +49,8 @@ impl MinifyTarget { #[napi] impl Task for MinifyTask { - type Output = TransformOutput; - type JsValue = TransformOutput; + type Output = TransformOutput; fn compute(&mut self) -> napi::Result { let input: MinifyTarget = deserialize_json(&self.code)?; diff --git a/crates/node/src/parse.rs b/crates/node/src/parse.rs index de93969c529..e345d10bd37 100644 --- a/crates/node/src/parse.rs +++ b/crates/node/src/parse.rs @@ -1,19 +1,21 @@ -use crate::{ - get_compiler, - util::{deserialize_json, get_deserialized, try_with, MapErr}, +use std::{ + path::{Path, PathBuf}, + sync::Arc, }; + use anyhow::Context as _; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Task, }; -use std::{ - path::{Path, PathBuf}, - sync::Arc, -}; use swc::{config::ParseOptions, Compiler}; use swc_common::FileName; +use crate::{ + get_compiler, + util::{deserialize_json, get_deserialized, try_with, MapErr}, +}; + // ----- Parsing ----- pub struct ParseTask { @@ -31,8 +33,8 @@ pub struct ParseFileTask { #[napi] impl Task for ParseTask { - type Output = String; type JsValue = String; + type Output = String; fn compute(&mut self) -> napi::Result { let options: ParseOptions = deserialize_json(&self.options)?; @@ -65,8 +67,8 @@ impl Task for ParseTask { #[napi] impl Task for ParseFileTask { - type Output = String; type JsValue = String; + type Output = String; fn compute(&mut self) -> napi::Result { let program = try_with(self.c.cm.clone(), false, |handler| { diff --git a/crates/node/src/print.rs b/crates/node/src/print.rs index 52fe8a7f75e..e0d8889e22e 100644 --- a/crates/node/src/print.rs +++ b/crates/node/src/print.rs @@ -1,18 +1,20 @@ -use crate::{ - get_compiler, - util::{deserialize_json, get_deserialized, MapErr}, -}; +use std::sync::Arc; + use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Task, }; -use std::sync::Arc; use swc::{ config::{Options, SourceMapsConfig}, Compiler, TransformOutput, }; use swc_ecma_ast::{EsVersion, Program}; +use crate::{ + get_compiler, + util::{deserialize_json, get_deserialized, MapErr}, +}; + // ----- Printing ----- pub struct PrintTask { @@ -23,8 +25,8 @@ pub struct PrintTask { #[napi] impl Task for PrintTask { - type Output = TransformOutput; type JsValue = TransformOutput; + type Output = TransformOutput; fn compute(&mut self) -> napi::Result { let program: Program = deserialize_json(&self.program_json)?; diff --git a/crates/node/src/transform.rs b/crates/node/src/transform.rs index 4cc7b727a27..0ab6d363f22 100644 --- a/crates/node/src/transform.rs +++ b/crates/node/src/transform.rs @@ -1,21 +1,23 @@ -use crate::{ - get_compiler, - util::{deserialize_json, get_deserialized, try_with, MapErr}, +use std::{ + path::{Path, PathBuf}, + sync::Arc, }; + use anyhow::Context as _; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, JsBuffer, JsBufferValue, Ref, Task, }; use path_clean::clean; -use std::{ - path::{Path, PathBuf}, - sync::Arc, -}; use swc::{config::Options, Compiler, TransformOutput}; use swc_common::FileName; use swc_ecma_ast::Program; +use crate::{ + get_compiler, + util::{deserialize_json, get_deserialized, try_with, MapErr}, +}; + /// Input to transform #[derive(Debug)] pub enum Input { @@ -35,8 +37,8 @@ pub struct TransformTask { #[napi] impl Task for TransformTask { - type Output = TransformOutput; type JsValue = TransformOutput; + type Output = TransformOutput; fn compute(&mut self) -> napi::Result { let mut options: Options = serde_json::from_slice(self.options.as_ref())?; diff --git a/crates/node/src/util.rs b/crates/node/src/util.rs index 71819c95411..afe5fdd09ed 100644 --- a/crates/node/src/util.rs +++ b/crates/node/src/util.rs @@ -1,10 +1,11 @@ -use anyhow::{anyhow, Context, Error}; -use napi::Status; -use serde::de::DeserializeOwned; use std::{ any::type_name, panic::{catch_unwind, AssertUnwindSafe}, }; + +use anyhow::{anyhow, Context, Error}; +use napi::Status; +use serde::de::DeserializeOwned; use swc::try_with_handler; use swc_common::{errors::Handler, sync::Lrc, SourceMap}; diff --git a/crates/string_enum/src/lib.rs b/crates/string_enum/src/lib.rs index cbf4a618ac4..9725618249e 100644 --- a/crates/string_enum/src/lib.rs +++ b/crates/string_enum/src/lib.rs @@ -185,6 +185,7 @@ fn make_from_str(i: &DeriveInput) -> ItemImpl { { impl ::std::str::FromStr for Type { type Err = (); + fn from_str(s: &str) -> Result { body } diff --git a/crates/string_enum/tests/simple.rs b/crates/string_enum/tests/simple.rs index 409dff430a5..694f14e644b 100644 --- a/crates/string_enum/tests/simple.rs +++ b/crates/string_enum/tests/simple.rs @@ -1,4 +1,5 @@ use std::fmt::{Debug, Display}; + use string_enum::*; pub trait Assert: Debug + Display {} diff --git a/crates/swc/benches/bugs.rs b/crates/swc/benches/bugs.rs index eea5ff85f86..216119d5b1e 100644 --- a/crates/swc/benches/bugs.rs +++ b/crates/swc/benches/bugs.rs @@ -5,6 +5,7 @@ extern crate swc_node_base; extern crate test; use std::{fs::read_to_string, io::stderr, path::Path}; + use swc::config::{IsModule, Options}; use swc_common::{errors::Handler, sync::Lrc, FilePathMapping, SourceMap}; use test::Bencher; diff --git a/crates/swc/benches/typescript.rs b/crates/swc/benches/typescript.rs index 7a17693c326..17e7253675f 100644 --- a/crates/swc/benches/typescript.rs +++ b/crates/swc/benches/typescript.rs @@ -9,6 +9,7 @@ use std::{ io::{self, stderr}, sync::Arc, }; + use swc::config::{Config, IsModule, JscConfig, Options, SourceMapsConfig}; use swc_common::{errors::Handler, FileName, FilePathMapping, Mark, SourceFile, SourceMap}; use swc_ecma_ast::{EsVersion, Program}; diff --git a/crates/swc/examples/usage.rs b/crates/swc/examples/usage.rs index 86c37f825a3..a5cb60d687b 100644 --- a/crates/swc/examples/usage.rs +++ b/crates/swc/examples/usage.rs @@ -1,4 +1,5 @@ use std::{path::Path, sync::Arc}; + use swc::{self, config::Options}; use swc_common::{ errors::{ColorConfig, Handler}, diff --git a/crates/swc/src/builder.rs b/crates/swc/src/builder.rs index 6030fccc6e1..8c654701c0f 100644 --- a/crates/swc/src/builder.rs +++ b/crates/swc/src/builder.rs @@ -1,10 +1,7 @@ -use crate::{ - config::{util::BoolOrObject, CompiledPaths, GlobalPassOption, JsMinifyOptions, ModuleConfig}, - SwcComments, -}; +use std::{cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc, sync::Arc}; + use compat::{es2015::regenerator, es2020::export_namespace_from}; use either::Either; -use std::{cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc, sync::Arc}; use swc_atoms::JsWord; use swc_common::{ chain, comments::Comments, errors::Handler, sync::Lrc, util::take::Take, FileName, Mark, @@ -20,6 +17,11 @@ use swc_ecma_transforms::{ }; use swc_ecma_visit::{as_folder, noop_visit_mut_type, VisitMut}; +use crate::{ + config::{util::BoolOrObject, CompiledPaths, GlobalPassOption, JsMinifyOptions, ModuleConfig}, + SwcComments, +}; + /// Builder is used to create a high performance `Compiler`. pub struct PassBuilder<'a, 'b, P: swc_ecma_visit::Fold> { cm: &'a Arc, diff --git a/crates/swc/src/config/mod.rs b/crates/swc/src/config/mod.rs index e5c39d621c7..5b307edab9e 100644 --- a/crates/swc/src/config/mod.rs +++ b/crates/swc/src/config/mod.rs @@ -1,15 +1,3 @@ -use self::util::BoolOrObject; -use crate::{builder::PassBuilder, plugin::PluginConfig, SwcComments, SwcImportResolver}; -use anyhow::{bail, Context, Error}; -use dashmap::DashMap; -use either::Either; -use indexmap::IndexMap; -use once_cell::sync::Lazy; -use regex::Regex; -use serde::{ - de::{Unexpected, Visitor}, - Deserialize, Deserializer, Serialize, Serializer, -}; use std::{ cell::RefCell, collections::{HashMap, HashSet}, @@ -20,6 +8,17 @@ use std::{ sync::Arc, usize, }; + +use anyhow::{bail, Context, Error}; +use dashmap::DashMap; +use either::Either; +use indexmap::IndexMap; +use once_cell::sync::Lazy; +use regex::Regex; +use serde::{ + de::{Unexpected, Visitor}, + Deserialize, Deserializer, Serialize, Serializer, +}; use swc_atoms::JsWord; pub use swc_common::chain; use swc_common::{ @@ -59,6 +58,9 @@ use swc_ecma_transforms_compat::es2015::regenerator; use swc_ecma_transforms_optimization::{inline_globals2, GlobalExprMap}; use swc_ecma_visit::{Fold, VisitMutWith}; +use self::util::BoolOrObject; +use crate::{builder::PassBuilder, plugin::PluginConfig, SwcComments, SwcImportResolver}; + #[cfg(test)] mod tests; pub mod util; diff --git a/crates/swc/src/config/tests.rs b/crates/swc/src/config/tests.rs index bb941263580..fa38b32f590 100644 --- a/crates/swc/src/config/tests.rs +++ b/crates/swc/src/config/tests.rs @@ -1,6 +1,7 @@ +use serde_json; + use super::Rc; use crate::Options; -use serde_json; #[test] fn object() { diff --git a/crates/swc/src/config/util.rs b/crates/swc/src/config/util.rs index 108ed8acfa7..1ec59b18a3c 100644 --- a/crates/swc/src/config/util.rs +++ b/crates/swc/src/config/util.rs @@ -1,6 +1,7 @@ -use super::Merge; use serde::{Deserialize, Serialize}; +use super::Merge; + /// Note: `{}` (empty object) is treated as `true`. #[derive(Clone, Serialize, Debug)] #[serde(untagged)] diff --git a/crates/swc/src/lib.rs b/crates/swc/src/lib.rs index 49f8654235d..2bb6ef539b2 100644 --- a/crates/swc/src/lib.rs +++ b/crates/swc/src/lib.rs @@ -111,10 +111,14 @@ pub extern crate swc_atoms as atoms; pub extern crate swc_common as common; pub extern crate swc_ecmascript as ecmascript; -pub use crate::builder::PassBuilder; -use crate::config::{ - BuiltInput, Config, ConfigFile, InputSourceMap, Merge, Options, Rc, RootMode, SourceMapsConfig, +use std::{ + fs::{read_to_string, File}, + io::Write, + mem::take, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, }; + use anyhow::{bail, Context, Error}; use atoms::JsWord; use common::{ @@ -126,13 +130,6 @@ use once_cell::sync::Lazy; use serde::Serialize; use serde_json::error::Category; pub use sourcemap; -use std::{ - fs::{read_to_string, File}, - io::Write, - mem::take, - path::{Path, PathBuf}, - sync::{Arc, Mutex}, -}; use swc_common::{ chain, comments::{Comment, Comments}, @@ -160,18 +157,25 @@ use swc_ecma_transforms::{ use swc_ecma_visit::{noop_visit_type, FoldWith, Visit, VisitMutWith, VisitWith}; pub use swc_node_comments::SwcComments; +pub use crate::builder::PassBuilder; +use crate::config::{ + BuiltInput, Config, ConfigFile, InputSourceMap, Merge, Options, Rc, RootMode, SourceMapsConfig, +}; + mod builder; pub mod config; mod plugin; pub mod resolver { - use crate::config::CompiledPaths; use std::path::PathBuf; + use swc_common::collections::AHashMap; use swc_ecma_loader::{ resolvers::{lru::CachingResolver, node::NodeModulesResolver, tsc::TsConfigResolver}, TargetEnv, }; + use crate::config::CompiledPaths; + pub type NodeResolver = CachingResolver; pub fn paths_resolver( diff --git a/crates/swc/tests/error_msg.rs b/crates/swc/tests/error_msg.rs index 307380cd68e..b041e916b2d 100644 --- a/crates/swc/tests/error_msg.rs +++ b/crates/swc/tests/error_msg.rs @@ -1,4 +1,5 @@ use std::path::{Path, PathBuf}; + use swc::{ config::{IsModule, Options}, try_with_handler, Compiler, diff --git a/crates/swc/tests/projects.rs b/crates/swc/tests/projects.rs index 941803661ec..c689d369deb 100644 --- a/crates/swc/tests/projects.rs +++ b/crates/swc/tests/projects.rs @@ -1,8 +1,9 @@ -use rayon::prelude::*; use std::{ fs::create_dir_all, path::{Path, PathBuf}, }; + +use rayon::prelude::*; use swc::{ config::{ BuiltInput, Config, IsModule, JscConfig, ModuleConfig, Options, SourceMapsConfig, diff --git a/crates/swc/tests/serde.rs b/crates/swc/tests/serde.rs index 4f754c81a1d..32b888f8678 100644 --- a/crates/swc/tests/serde.rs +++ b/crates/swc/tests/serde.rs @@ -1,4 +1,5 @@ use std::path::Path; + use swc_common::input::StringInput; use swc_ecma_ast::Module; use swc_ecma_parser::{lexer::Lexer, PResult, Parser, Syntax}; diff --git a/crates/swc/tests/source_map.rs b/crates/swc/tests/source_map.rs index 53eb9ebc6b5..8024bde1492 100644 --- a/crates/swc/tests/source_map.rs +++ b/crates/swc/tests/source_map.rs @@ -1,6 +1,5 @@ #![allow(unused)] -use anyhow::{Context, Error}; use std::{ env::temp_dir, fs, @@ -9,6 +8,8 @@ use std::{ process::{Command, Output}, sync::Arc, }; + +use anyhow::{Context, Error}; use swc::{ config::{Config, IsModule, Options, SourceMapsConfig}, Compiler, diff --git a/crates/swc/tests/tsc.rs b/crates/swc/tests/tsc.rs index 4cc6173c1a8..abf11c6a796 100644 --- a/crates/swc/tests/tsc.rs +++ b/crates/swc/tests/tsc.rs @@ -1,8 +1,9 @@ -use serde::de::DeserializeOwned; use std::{ fs::create_dir_all, path::{Path, PathBuf}, }; + +use serde::de::DeserializeOwned; use swc::{ config::{Config, IsModule, JscConfig, Options}, Compiler, diff --git a/crates/swc_bundler/examples/bundle.rs b/crates/swc_bundler/examples/bundle.rs index facc5c952bc..88418c4d35a 100644 --- a/crates/swc_bundler/examples/bundle.rs +++ b/crates/swc_bundler/examples/bundle.rs @@ -3,14 +3,15 @@ /// Use memory allocator extern crate swc_node_base; -use anyhow::{bail, Error}; -use path_clean::PathClean; use std::{ collections::HashMap, env, fs, path::{Path, PathBuf}, time::{Duration, Instant}, }; + +use anyhow::{bail, Error}; +use path_clean::PathClean; use swc_atoms::js_word; use swc_bundler::{Bundle, Bundler, Load, ModuleData, ModuleRecord, Resolve}; use swc_common::{ diff --git a/crates/swc_bundler/examples/path.rs b/crates/swc_bundler/examples/path.rs index ceedfa582cd..2cac4063ec9 100644 --- a/crates/swc_bundler/examples/path.rs +++ b/crates/swc_bundler/examples/path.rs @@ -1,5 +1,6 @@ -use anyhow::Error; use std::{collections::HashMap, io::stdout}; + +use anyhow::Error; use swc_bundler::{BundleKind, Bundler, Config, Hook, Load, ModuleData, ModuleRecord, Resolve}; use swc_common::{sync::Lrc, FileName, FilePathMapping, Globals, SourceMap, Span}; use swc_ecma_ast::KeyValueProp; diff --git a/crates/swc_bundler/src/bundler/chunk/cjs.rs b/crates/swc_bundler/src/bundler/chunk/cjs.rs index 1fe1c710cdd..6fedf91ee22 100644 --- a/crates/swc_bundler/src/bundler/chunk/cjs.rs +++ b/crates/swc_bundler/src/bundler/chunk/cjs.rs @@ -1,16 +1,18 @@ -use crate::{ - bundler::{chunk::merge::Ctx, load::TransformedModule}, - modules::Modules, - Bundler, Load, Resolve, -}; -use anyhow::Error; use std::sync::atomic::Ordering; + +use anyhow::Error; use swc_atoms::js_word; use swc_common::{Span, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::{ModuleItem, *}; use swc_ecma_utils::{quote_ident, undefined, ExprFactory}; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use crate::{ + bundler::{chunk::merge::Ctx, load::TransformedModule}, + modules::Modules, + Bundler, Load, Resolve, +}; + impl Bundler<'_, L, R> where L: Load, diff --git a/crates/swc_bundler/src/bundler/chunk/computed_key.rs b/crates/swc_bundler/src/bundler/chunk/computed_key.rs index 1103e20548e..c1cb25e35c7 100644 --- a/crates/swc_bundler/src/bundler/chunk/computed_key.rs +++ b/crates/swc_bundler/src/bundler/chunk/computed_key.rs @@ -1,12 +1,14 @@ -use crate::{bundler::chunk::merge::Ctx, modules::Modules, Bundler, Load, ModuleId, Resolve}; -use anyhow::{bail, Error}; use std::mem::take; + +use anyhow::{bail, Error}; use swc_atoms::js_word; use swc_common::{SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{find_ids, private_ident, ExprFactory}; use swc_ecma_visit::{noop_fold_type, noop_visit_type, Fold, Visit}; +use crate::{bundler::chunk::merge::Ctx, modules::Modules, Bundler, Load, ModuleId, Resolve}; + impl Bundler<'_, L, R> where L: Load, @@ -188,7 +190,9 @@ impl Visit for TopLevelAwaitFinder { noop_visit_type!(); fn visit_function(&mut self, _: &Function) {} + fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} + fn visit_class_member(&mut self, _: &ClassMember) {} fn visit_await_expr(&mut self, _: &AwaitExpr) { diff --git a/crates/swc_bundler/src/bundler/chunk/merge.rs b/crates/swc_bundler/src/bundler/chunk/merge.rs index c2b008ae04f..0f97aefba08 100644 --- a/crates/swc_bundler/src/bundler/chunk/merge.rs +++ b/crates/swc_bundler/src/bundler/chunk/merge.rs @@ -1,3 +1,19 @@ +use std::sync::atomic::Ordering; + +use anyhow::Error; +use indexmap::IndexSet; +use petgraph::EdgeDirection; +use swc_atoms::js_word; +use swc_common::{ + collections::{AHashMap, AHashSet}, + sync::Lock, + FileName, SyntaxContext, DUMMY_SP, +}; +use swc_ecma_ast::*; +use swc_ecma_utils::{find_ids, prepend, private_ident, quote_ident, ExprFactory}; +use swc_ecma_visit::{noop_fold_type, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; +use EdgeDirection::Outgoing; + use crate::{ bundler::{ keywords::KeywordRenamer, @@ -12,20 +28,6 @@ use crate::{ util::{CloneMap, ExprExt, VarDeclaratorExt}, Bundler, Hook, ModuleRecord, }; -use anyhow::Error; -use indexmap::IndexSet; -use petgraph::EdgeDirection; -use std::sync::atomic::Ordering; -use swc_atoms::js_word; -use swc_common::{ - collections::{AHashMap, AHashSet}, - sync::Lock, - FileName, SyntaxContext, DUMMY_SP, -}; -use swc_ecma_ast::*; -use swc_ecma_utils::{find_ids, prepend, private_ident, quote_ident, ExprFactory}; -use swc_ecma_visit::{noop_fold_type, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; -use EdgeDirection::Outgoing; pub(super) struct Ctx { /// Full dependency graph. diff --git a/crates/swc_bundler/src/bundler/chunk/mod.rs b/crates/swc_bundler/src/bundler/chunk/mod.rs index 59d5f7850ff..8fef06d61d8 100644 --- a/crates/swc_bundler/src/bundler/chunk/mod.rs +++ b/crates/swc_bundler/src/bundler/chunk/mod.rs @@ -1,12 +1,14 @@ +use std::time::Instant; + +use anyhow::{Context, Error}; +#[cfg(feature = "rayon")] +use rayon::iter::ParallelIterator; +use swc_common::collections::AHashMap; + use super::{load::TransformedModule, Bundler}; use crate::{ bundler::chunk::merge::Ctx, load::Load, resolve::Resolve, util::IntoParallelIterator, Bundle, }; -use anyhow::{Context, Error}; -#[cfg(feature = "rayon")] -use rayon::iter::ParallelIterator; -use std::time::Instant; -use swc_common::collections::AHashMap; mod cjs; mod computed_key; @@ -153,9 +155,10 @@ where #[cfg(test)] mod tests { + use swc_common::FileName; + use super::*; use crate::bundler::tests::suite; - use swc_common::FileName; #[test] fn cjs_chunk() { diff --git a/crates/swc_bundler/src/bundler/chunk/plan/mod.rs b/crates/swc_bundler/src/bundler/chunk/plan/mod.rs index d3e0f3f03ed..99a31da0ac0 100644 --- a/crates/swc_bundler/src/bundler/chunk/plan/mod.rs +++ b/crates/swc_bundler/src/bundler/chunk/plan/mod.rs @@ -1,11 +1,12 @@ +use anyhow::{bail, Error}; +use swc_common::collections::AHashMap; +use swc_graph_analyzer::{DepGraph, GraphAnalyzer}; + use crate::{ bundler::{load::TransformedModule, scope::Scope}, dep_graph::ModuleGraph, BundleKind, Bundler, Load, ModuleId, Resolve, }; -use anyhow::{bail, Error}; -use swc_common::collections::AHashMap; -use swc_graph_analyzer::{DepGraph, GraphAnalyzer}; #[cfg(test)] mod tests; diff --git a/crates/swc_bundler/src/bundler/chunk/plan/tests.rs b/crates/swc_bundler/src/bundler/chunk/plan/tests.rs index 58446b53167..ce8b2f9514b 100644 --- a/crates/swc_bundler/src/bundler/chunk/plan/tests.rs +++ b/crates/swc_bundler/src/bundler/chunk/plan/tests.rs @@ -1,7 +1,9 @@ -use crate::bundler::tests::suite; use std::collections::HashMap; + use swc_common::collections::{AHashMap, AHashSet}; +use crate::bundler::tests::suite; + fn assert_cycles(map: AHashMap, cycle_entries: Vec<&str>) { let mut tester = suite(); diff --git a/crates/swc_bundler/src/bundler/export.rs b/crates/swc_bundler/src/bundler/export.rs index 7eb22ae2af0..46cf5f5f087 100644 --- a/crates/swc_bundler/src/bundler/export.rs +++ b/crates/swc_bundler/src/bundler/export.rs @@ -1,8 +1,3 @@ -use super::{ - load::{Source, Specifier}, - Bundler, -}; -use crate::{id::Id, load::Load, resolve::Resolve}; use indexmap::IndexMap; use swc_atoms::{js_word, JsWord}; use swc_common::{FileName, SyntaxContext}; @@ -10,6 +5,12 @@ use swc_ecma_ast::*; use swc_ecma_utils::find_ids; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use super::{ + load::{Source, Specifier}, + Bundler, +}; +use crate::{id::Id, load::Load, resolve::Resolve}; + impl Bundler<'_, L, R> where L: Load, diff --git a/crates/swc_bundler/src/bundler/finalize.rs b/crates/swc_bundler/src/bundler/finalize.rs index 7570b722ebe..b32c132d764 100644 --- a/crates/swc_bundler/src/bundler/finalize.rs +++ b/crates/swc_bundler/src/bundler/finalize.rs @@ -1,8 +1,8 @@ -use crate::{hash::calc_hash, Bundle, BundleKind, Bundler, Load, ModuleType, Resolve}; +use std::path::{Path, PathBuf}; + use ahash::AHashMap; use anyhow::Error; use relative_path::RelativePath; -use std::path::{Path, PathBuf}; use swc_atoms::js_word; use swc_common::{util::move_map::MoveMap, FileName, DUMMY_SP}; use swc_ecma_ast::*; @@ -14,6 +14,8 @@ use swc_ecma_transforms_base::{ use swc_ecma_utils::{find_ids, private_ident, ExprFactory}; use swc_ecma_visit::{noop_fold_type, noop_visit_type, Fold, FoldWith, Visit, VisitWith}; +use crate::{hash::calc_hash, Bundle, BundleKind, Bundler, Load, ModuleType, Resolve}; + impl Bundler<'_, L, R> where L: Load, diff --git a/crates/swc_bundler/src/bundler/helpers/mod.rs b/crates/swc_bundler/src/bundler/helpers/mod.rs index b9c8cfb21e6..abc7ead9be9 100644 --- a/crates/swc_bundler/src/bundler/helpers/mod.rs +++ b/crates/swc_bundler/src/bundler/helpers/mod.rs @@ -1,5 +1,6 @@ -use once_cell::sync::Lazy; use std::sync::atomic::{AtomicBool, Ordering::SeqCst}; + +use once_cell::sync::Lazy; use swc_common::{FileName, FilePathMapping, SourceMap}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput}; diff --git a/crates/swc_bundler/src/bundler/import/mod.rs b/crates/swc_bundler/src/bundler/import/mod.rs index 07cf0ffb47a..3eeb9f6341f 100644 --- a/crates/swc_bundler/src/bundler/import/mod.rs +++ b/crates/swc_bundler/src/bundler/import/mod.rs @@ -1,5 +1,3 @@ -use super::Bundler; -use crate::{load::Load, resolve::Resolve}; use anyhow::{Context, Error}; use retain_mut::RetainMut; use swc_atoms::{js_word, JsWord}; @@ -12,6 +10,9 @@ use swc_ecma_ast::*; use swc_ecma_utils::{find_ids, ident::IdentLike, Id}; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use super::Bundler; +use crate::{load::Load, resolve::Resolve}; + #[cfg(test)] mod tests; diff --git a/crates/swc_bundler/src/bundler/keywords.rs b/crates/swc_bundler/src/bundler/keywords.rs index 42af90c6802..4a6fac00414 100644 --- a/crates/swc_bundler/src/bundler/keywords.rs +++ b/crates/swc_bundler/src/bundler/keywords.rs @@ -1,10 +1,11 @@ -use crate::id::Id; use swc_atoms::js_word; use swc_common::{collections::AHashMap, util::take::Take}; use swc_ecma_ast::*; use swc_ecma_utils::private_ident; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use crate::id::Id; + #[derive(Default)] pub struct KeywordRenamer { renamed: AHashMap, diff --git a/crates/swc_bundler/src/bundler/load.rs b/crates/swc_bundler/src/bundler/load.rs index 73187430f02..5b0d7df5765 100644 --- a/crates/swc_bundler/src/bundler/load.rs +++ b/crates/swc_bundler/src/bundler/load.rs @@ -1,14 +1,5 @@ #![allow(dead_code)] -use super::{export::Exports, helpers::Helpers, Bundler}; -use crate::{ - bundler::{export::RawExports, import::RawImports}, - id::{Id, ModuleId}, - load::ModuleData, - util, - util::IntoParallelIterator, - Load, Resolve, -}; use anyhow::{Context, Error}; use is_macro::Is; #[cfg(feature = "rayon")] @@ -23,6 +14,16 @@ use swc_ecma_transforms_base::resolver::resolver_with_mark; use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, FoldWith, Visit, VisitMut, VisitMutWith, VisitWith, }; + +use super::{export::Exports, helpers::Helpers, Bundler}; +use crate::{ + bundler::{export::RawExports, import::RawImports}, + id::{Id, ModuleId}, + load::ModuleData, + util, + util::IntoParallelIterator, + Load, Resolve, +}; /// Module after applying transformations. #[derive(Debug, Clone)] pub(crate) struct TransformedModule { diff --git a/crates/swc_bundler/src/bundler/mod.rs b/crates/swc_bundler/src/bundler/mod.rs index 06c8f6e644c..f196bcefecc 100644 --- a/crates/swc_bundler/src/bundler/mod.rs +++ b/crates/swc_bundler/src/bundler/mod.rs @@ -1,13 +1,15 @@ -use self::scope::Scope; -use crate::{Hook, Load, ModuleId, Resolve}; -use anyhow::{Context, Error}; use std::collections::HashMap; + +use anyhow::{Context, Error}; use swc_atoms::JsWord; use swc_common::{ collections::AHashMap, sync::Lrc, FileName, Globals, Mark, SourceMap, SyntaxContext, GLOBALS, }; use swc_ecma_ast::Module; +use self::scope::Scope; +use crate::{Hook, Load, ModuleId, Resolve}; + mod chunk; mod export; mod finalize; @@ -139,9 +141,11 @@ where } }) } + pub(crate) fn is_external(&self, src: &JsWord) -> bool { return self.config.external_modules.iter().any(|v| v == src); } + /// /// /// diff --git a/crates/swc_bundler/src/bundler/optimize.rs b/crates/swc_bundler/src/bundler/optimize.rs index 95481ce7fb6..0d57f30b20e 100644 --- a/crates/swc_bundler/src/bundler/optimize.rs +++ b/crates/swc_bundler/src/bundler/optimize.rs @@ -1,9 +1,10 @@ -use crate::{Bundler, Load, Resolve}; use swc_common::pass::Repeat; use swc_ecma_ast::*; use swc_ecma_transforms_optimization::simplify::{const_propgation::constant_propagation, dce}; use swc_ecma_visit::FoldWith; +use crate::{Bundler, Load, Resolve}; + impl Bundler<'_, L, R> where L: Load, diff --git a/crates/swc_bundler/src/bundler/scope.rs b/crates/swc_bundler/src/bundler/scope.rs index 1438fa925ed..182dab11123 100644 --- a/crates/swc_bundler/src/bundler/scope.rs +++ b/crates/swc_bundler/src/bundler/scope.rs @@ -1,10 +1,12 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +use swc_common::{sync::Lrc, FileName}; + use super::load::TransformedModule; use crate::{ id::{Id, ModuleId, ModuleIdGenerator}, util::CloneMap, }; -use std::sync::atomic::{AtomicBool, Ordering}; -use swc_common::{sync::Lrc, FileName}; #[derive(Debug, Default)] pub(super) struct Scope { diff --git a/crates/swc_bundler/src/bundler/tests.rs b/crates/swc_bundler/src/bundler/tests.rs index f9f5a6af2c6..179cc231c9e 100644 --- a/crates/swc_bundler/src/bundler/tests.rs +++ b/crates/swc_bundler/src/bundler/tests.rs @@ -1,15 +1,17 @@ //! Utilities for testing. -use super::{load::TransformedModule, Bundler, Config}; -use crate::{load::ModuleData, util::HygieneRemover, Load, ModuleRecord, Resolve}; +use std::path::PathBuf; + use anyhow::Error; use indexmap::IndexMap; -use std::path::PathBuf; use swc_common::{sync::Lrc, FileName, SourceMap, Span, GLOBALS}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput}; use swc_ecma_utils::drop_span; use swc_ecma_visit::VisitMutWith; +use super::{load::TransformedModule, Bundler, Config}; +use crate::{load::ModuleData, util::HygieneRemover, Load, ModuleRecord, Resolve}; + pub(crate) struct Tester<'a> { pub cm: Lrc, pub bundler: Bundler<'a, Loader, Resolver>, diff --git a/crates/swc_bundler/src/debug/mod.rs b/crates/swc_bundler/src/debug/mod.rs index 3505228d3e5..01bc9edf190 100644 --- a/crates/swc_bundler/src/debug/mod.rs +++ b/crates/swc_bundler/src/debug/mod.rs @@ -1,6 +1,7 @@ #![allow(dead_code)] use std::io::{stderr, Write}; + use swc_common::{sync::Lrc, SourceMap, SyntaxContext}; use swc_ecma_ast::{Ident, Module}; use swc_ecma_codegen::{text_writer::JsWriter, Emitter}; diff --git a/crates/swc_bundler/src/dep_graph.rs b/crates/swc_bundler/src/dep_graph.rs index ba51d25b392..e0af6b94b08 100644 --- a/crates/swc_bundler/src/dep_graph.rs +++ b/crates/swc_bundler/src/dep_graph.rs @@ -1,4 +1,5 @@ -use crate::ModuleId; use swc_fast_graph::digraph::FastDiGraphMap; +use crate::ModuleId; + pub(crate) type ModuleGraph = FastDiGraphMap; diff --git a/crates/swc_bundler/src/hash.rs b/crates/swc_bundler/src/hash.rs index f8966467c83..356a009a68d 100644 --- a/crates/swc_bundler/src/hash.rs +++ b/crates/swc_bundler/src/hash.rs @@ -1,6 +1,7 @@ +use std::io; + use anyhow::{Context, Error}; use crc::{crc64, crc64::Digest, Hasher64}; -use std::io; use swc_common::{sync::Lrc, SourceMap, Span}; use swc_ecma_ast::{EsVersion, Module}; use swc_ecma_codegen::{text_writer::WriteJs, Emitter}; diff --git a/crates/swc_bundler/src/id.rs b/crates/swc_bundler/src/id.rs index 07a889fb536..eeef6ac12dd 100644 --- a/crates/swc_bundler/src/id.rs +++ b/crates/swc_bundler/src/id.rs @@ -2,6 +2,7 @@ use std::{ fmt, sync::atomic::{AtomicU32, Ordering::SeqCst}, }; + use swc_atoms::JsWord; use swc_common::{collections::AHashMap, sync::Lock, FileName, Mark, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::{Expr, Ident}; diff --git a/crates/swc_bundler/src/inline.rs b/crates/swc_bundler/src/inline.rs index 54da39b0cbb..84165f2c0ea 100644 --- a/crates/swc_bundler/src/inline.rs +++ b/crates/swc_bundler/src/inline.rs @@ -1,4 +1,3 @@ -use crate::{id::Id, modules::Modules, util::Readonly}; use swc_common::{collections::AHashMap, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{ @@ -6,6 +5,8 @@ use swc_ecma_visit::{ VisitMutWith, VisitWith, }; +use crate::{id::Id, modules::Modules, util::Readonly}; + #[derive(Debug, Default)] pub(crate) struct InlineData { ids: AHashMap, @@ -85,6 +86,8 @@ impl Visit for Analyzer<'_> { impl VisitMut for Inliner { noop_visit_mut_type!(); + visit_mut_obj_and_computed!(); + /// Don't modify exported ident. fn visit_mut_export_named_specifier(&mut self, n: &mut ExportNamedSpecifier) { if n.exported.is_none() { @@ -101,8 +104,6 @@ impl VisitMut for Inliner { } } - visit_mut_obj_and_computed!(); - fn visit_mut_module_items(&mut self, n: &mut Vec) { n.visit_mut_children_with(self); diff --git a/crates/swc_bundler/src/modules/mod.rs b/crates/swc_bundler/src/modules/mod.rs index 11868d2ca19..4893279e1ca 100644 --- a/crates/swc_bundler/src/modules/mod.rs +++ b/crates/swc_bundler/src/modules/mod.rs @@ -1,10 +1,12 @@ -use crate::ModuleId; -use retain_mut::RetainMut; use std::mem::take; + +use retain_mut::RetainMut; use swc_common::{collections::AHashMap, SourceMap, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{Fold, FoldWith, Visit, VisitMut, VisitMutWith, VisitWith}; +use crate::ModuleId; + mod sort; #[derive(Debug, Clone)] diff --git a/crates/swc_bundler/src/modules/sort/chunk.rs b/crates/swc_bundler/src/modules/sort/chunk.rs index 25781195acc..fc7722b962b 100644 --- a/crates/swc_bundler/src/modules/sort/chunk.rs +++ b/crates/swc_bundler/src/modules/sort/chunk.rs @@ -1,12 +1,14 @@ -use super::stmt::sort_stmts; -use crate::{dep_graph::ModuleGraph, modules::Modules, ModuleId}; +use std::{collections::VecDeque, iter::from_fn, mem::take, time::Instant}; + use indexmap::IndexSet; use petgraph::EdgeDirection::Outgoing; -use std::{collections::VecDeque, iter::from_fn, mem::take, time::Instant}; use swc_common::{collections::AHashSet, sync::Lrc, SourceMap, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_utils::prepend_stmts; +use super::stmt::sort_stmts; +use crate::{dep_graph::ModuleGraph, modules::Modules, ModuleId}; + /// The unit of sorting. #[derive(Debug)] pub(super) struct Chunk { diff --git a/crates/swc_bundler/src/modules/sort/graph.rs b/crates/swc_bundler/src/modules/sort/graph.rs index dd65cba217d..18385c1fff1 100644 --- a/crates/swc_bundler/src/modules/sort/graph.rs +++ b/crates/swc_bundler/src/modules/sort/graph.rs @@ -1,8 +1,9 @@ +use std::{collections::VecDeque, iter::repeat}; + use petgraph::{ EdgeDirection, EdgeDirection::{Incoming, Outgoing}, }; -use std::{collections::VecDeque, iter::repeat}; use swc_common::collections::AHashSet; use swc_fast_graph::digraph::FastDiGraphMap; diff --git a/crates/swc_bundler/src/modules/sort/mod.rs b/crates/swc_bundler/src/modules/sort/mod.rs index de778b91034..5efc9b9a065 100644 --- a/crates/swc_bundler/src/modules/sort/mod.rs +++ b/crates/swc_bundler/src/modules/sort/mod.rs @@ -1,9 +1,11 @@ -use super::Modules; -use crate::{dep_graph::ModuleGraph, ModuleId}; use std::time::Instant; + use swc_common::{sync::Lrc, SourceMap, DUMMY_SP}; use swc_ecma_ast::*; +use super::Modules; +use crate::{dep_graph::ModuleGraph, ModuleId}; + mod chunk; mod graph; mod stmt; diff --git a/crates/swc_bundler/src/modules/sort/stmt.rs b/crates/swc_bundler/src/modules/sort/stmt.rs index ef6bed32954..6e2fed1136f 100644 --- a/crates/swc_bundler/src/modules/sort/stmt.rs +++ b/crates/swc_bundler/src/modules/sort/stmt.rs @@ -1,8 +1,7 @@ -use super::graph::Required; -use crate::{id::Id, modules::sort::graph::StmtDepGraph}; +use std::{collections::VecDeque, iter::from_fn, ops::Range}; + use indexmap::IndexSet; use petgraph::EdgeDirection::{Incoming as Dependants, Outgoing as Dependencies}; -use std::{collections::VecDeque, iter::from_fn, ops::Range}; use swc_atoms::js_word; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -14,6 +13,9 @@ use swc_ecma_ast::*; use swc_ecma_utils::find_ids; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use super::graph::Required; +use crate::{id::Id, modules::sort::graph::StmtDepGraph}; + pub(super) fn sort_stmts( injected_ctxt: SyntaxContext, modules: Vec>, @@ -348,6 +350,7 @@ impl FieldInitFinder { } } } + fn check_lhs_expr_of_assign(&mut self, lhs: &Expr) { if let Expr::Member(m) = lhs { match &*m.obj { @@ -539,9 +542,13 @@ impl Visit for RequirementCalculator { noop_visit_type!(); weak!(visit_arrow_expr, ArrowExpr); + weak!(visit_function, Function); + weak!(visit_class_method, ClassMethod); + weak!(visit_private_method, PrivateMethod); + weak!(visit_method_prop, MethodProp); fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) { @@ -787,11 +794,12 @@ fn calc_deps(new: &[ModuleItem]) -> StmtDepGraph { #[cfg(test)] mod tests { - use super::{calc_deps, Dependencies}; - use crate::{bundler::tests::suite, debug::print_hygiene}; use swc_common::DUMMY_SP; use swc_ecma_ast::*; + use super::{calc_deps, Dependencies}; + use crate::{bundler::tests::suite, debug::print_hygiene}; + fn assert_no_cycle(s: &str) { suite().file("main.js", s).run(|t| { let info = t.module("main.js"); diff --git a/crates/swc_bundler/src/modules/sort/tests.rs b/crates/swc_bundler/src/modules/sort/tests.rs index 9aeaecb1a91..79d3d2c076d 100644 --- a/crates/swc_bundler/src/modules/sort/tests.rs +++ b/crates/swc_bundler/src/modules/sort/tests.rs @@ -1,10 +1,11 @@ -use super::stmt::sort_stmts; -use crate::{bundler::tests::suite, debug::print_hygiene}; use swc_common::{SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::drop_span; use testing::assert_eq; +use super::stmt::sort_stmts; +use crate::{bundler::tests::suite, debug::print_hygiene}; + fn assert_sorted(src: &[&str], res: &str) { assert_sorted_with_free(src, "", res) } diff --git a/crates/swc_bundler/src/util.rs b/crates/swc_bundler/src/util.rs index 86009493281..5a00931f982 100644 --- a/crates/swc_bundler/src/util.rs +++ b/crates/swc_bundler/src/util.rs @@ -1,6 +1,7 @@ #![allow(dead_code)] use std::{clone::Clone, cmp::Eq, hash::Hash}; + use swc_common::{Span, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::ident::IdentLike; diff --git a/crates/swc_bundler/tests/common/mod.rs b/crates/swc_bundler/tests/common/mod.rs index 547864e7e99..939c50c4162 100644 --- a/crates/swc_bundler/tests/common/mod.rs +++ b/crates/swc_bundler/tests/common/mod.rs @@ -1,13 +1,14 @@ -use anyhow::{bail, Context, Error}; -use path_clean::PathClean; -use reqwest::Url; -use sha1::{Digest, Sha1}; use std::{ env::current_dir, fs::{create_dir_all, read_to_string, write}, io::Write, path::{Path, PathBuf}, }; + +use anyhow::{bail, Context, Error}; +use path_clean::PathClean; +use reqwest::Url; +use sha1::{Digest, Sha1}; use swc_bundler::{Load, ModuleData, Resolve}; use swc_common::{ comments::SingleThreadedComments, diff --git a/crates/swc_bundler/tests/deno.rs b/crates/swc_bundler/tests/deno.rs index 9d05fa2c3ff..fcad5c623f1 100644 --- a/crates/swc_bundler/tests/deno.rs +++ b/crates/swc_bundler/tests/deno.rs @@ -3,10 +3,10 @@ //! This module exists because this is way easier than using copying requires //! files. -use self::common::*; +use std::{collections::HashMap, fs::write, path::PathBuf, process::Command}; + use anyhow::Error; use ntest::timeout; -use std::{collections::HashMap, fs::write, path::PathBuf, process::Command}; use swc_atoms::js_word; use swc_bundler::{Bundler, Load, ModuleRecord}; use swc_common::{collections::AHashSet, FileName, Mark, Span, GLOBALS}; @@ -21,6 +21,8 @@ use swc_ecma_utils::{find_ids, Id}; use swc_ecma_visit::{Visit, VisitMutWith, VisitWith}; use testing::assert_eq; +use self::common::*; + #[path = "common/mod.rs"] mod common; diff --git a/crates/swc_bundler/tests/fixture.rs b/crates/swc_bundler/tests/fixture.rs index 0775b790493..48e123a2a53 100644 --- a/crates/swc_bundler/tests/fixture.rs +++ b/crates/swc_bundler/tests/fixture.rs @@ -1,5 +1,3 @@ -use self::common::*; -use anyhow::Error; use std::{ self, collections::HashMap, @@ -7,6 +5,8 @@ use std::{ io, path::{Path, PathBuf}, }; + +use anyhow::Error; use swc_atoms::js_word; use swc_bundler::{BundleKind, Bundler, Config, ModuleRecord}; use swc_common::{FileName, Globals, Span}; @@ -20,6 +20,8 @@ use swc_ecma_transforms_base::fixer::fixer; use swc_ecma_visit::FoldWith; use testing::NormalizedOutput; +use self::common::*; + #[path = "common/mod.rs"] mod common; diff --git a/crates/swc_cli/src/cli.rs b/crates/swc_cli/src/cli.rs index 6330798a9e0..8ad9302c526 100644 --- a/crates/swc_cli/src/cli.rs +++ b/crates/swc_cli/src/cli.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use structopt::StructOpt; /// Transform, compile files. diff --git a/crates/swc_common/benches/serde.rs b/crates/swc_common/benches/serde.rs index a9cd8a89464..5483022f641 100644 --- a/crates/swc_common/benches/serde.rs +++ b/crates/swc_common/benches/serde.rs @@ -3,9 +3,10 @@ extern crate test; +use std::hint::black_box; + use ast_node::ast_node; use serde::{Deserialize, Serialize}; -use std::hint::black_box; use swc_common::{Span, DUMMY_SP}; use test::Bencher; diff --git a/crates/swc_common/src/comments.rs b/crates/swc_common/src/comments.rs index c1937dacf87..b4c921e8643 100644 --- a/crates/swc_common/src/comments.rs +++ b/crates/swc_common/src/comments.rs @@ -1,14 +1,16 @@ -use crate::{ - pos::Spanned, - syntax_pos::{BytePos, Span, DUMMY_SP}, -}; -use rustc_hash::FxHashMap; use std::{ cell::{Ref, RefCell}, rc::Rc, sync::Arc, }; +use rustc_hash::FxHashMap; + +use crate::{ + pos::Spanned, + syntax_pos::{BytePos, Span, DUMMY_SP}, +}; + /// Stores comment. /// /// ## Implementation notes diff --git a/crates/swc_common/src/eq.rs b/crates/swc_common/src/eq.rs index 58943bbcdc9..c0af7fd0b38 100644 --- a/crates/swc_common/src/eq.rs +++ b/crates/swc_common/src/eq.rs @@ -1,8 +1,10 @@ -use crate::{BytePos, Span, SyntaxContext}; -use num_bigint::BigInt; use std::{cell::RefCell, cmp::PartialEq, rc::Rc, sync::Arc}; + +use num_bigint::BigInt; use string_cache::Atom; +use crate::{BytePos, Span, SyntaxContext}; + /// Derive with `#[derive(EqIgnoreSpan)]`. pub trait EqIgnoreSpan { fn eq_ignore_span(&self, other: &Self) -> bool; diff --git a/crates/swc_common/src/errors/diagnostic.rs b/crates/swc_common/src/errors/diagnostic.rs index e2735b1f1bb..58fab58651c 100644 --- a/crates/swc_common/src/errors/diagnostic.rs +++ b/crates/swc_common/src/errors/diagnostic.rs @@ -8,9 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; + use super::{snippet::Style, Applicability, CodeSuggestion, Level, Substitution, SubstitutionPart}; use crate::syntax_pos::{MultiSpan, Span}; -use std::fmt; #[must_use] #[derive(Clone, Debug, PartialEq, Hash)] @@ -69,12 +70,15 @@ impl DiagnosticStyledString { pub fn new() -> DiagnosticStyledString { Default::default() } + pub fn push_normal>(&mut self, t: S) { self.0.push(StringPart::Normal(t.into())); } + pub fn push_highlighted>(&mut self, t: S) { self.0.push(StringPart::Highlighted(t.into())); } + pub fn normal>(t: S) -> DiagnosticStyledString { DiagnosticStyledString(vec![StringPart::Normal(t.into())]) } diff --git a/crates/swc_common/src/errors/diagnostic_builder.rs b/crates/swc_common/src/errors/diagnostic_builder.rs index 4c4c784ff3e..3748effef5f 100644 --- a/crates/swc_common/src/errors/diagnostic_builder.rs +++ b/crates/swc_common/src/errors/diagnostic_builder.rs @@ -8,15 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use super::{Applicability, Diagnostic, DiagnosticId, DiagnosticStyledString, Handler, Level}; -use crate::syntax_pos::{MultiSpan, Span}; use std::{ fmt::{self, Debug}, ops::{Deref, DerefMut}, thread::panicking, }; + use tracing::debug; +use super::{Applicability, Diagnostic, DiagnosticId, DiagnosticStyledString, Handler, Level}; +use crate::syntax_pos::{MultiSpan, Span}; + /// Used for emitting structured error messages and other diagnostic /// information. /// @@ -90,6 +92,67 @@ impl<'a> DerefMut for DiagnosticBuilder<'a> { } impl<'a> DiagnosticBuilder<'a> { + forward!(pub fn note_expected_found(&mut self, + label: &dyn fmt::Display, + expected: DiagnosticStyledString, + found: DiagnosticStyledString, + ) -> &mut Self); + + forward!(pub fn note_expected_found_extra(&mut self, + label: &dyn fmt::Display, + expected: DiagnosticStyledString, + found: DiagnosticStyledString, + expected_extra: &dyn fmt::Display, + found_extra: &dyn fmt::Display, + ) -> &mut Self); + + forward!(pub fn note(&mut self, msg: &str) -> &mut Self); + + forward!(pub fn span_note>(&mut self, + sp: S, + msg: &str, + ) -> &mut Self); + + forward!(pub fn warn(&mut self, msg: &str) -> &mut Self); + + forward!(pub fn span_warn>(&mut self, sp: S, msg: &str) -> &mut Self); + + forward!(pub fn help(&mut self , msg: &str) -> &mut Self); + + forward!(pub fn span_help>(&mut self, + sp: S, + msg: &str, + ) -> &mut Self); + + forward!(pub fn span_suggestion_short( + &mut self, + sp: Span, + msg: &str, + suggestion: String, + ) -> &mut Self); + + forward!(pub fn multipart_suggestion( + &mut self, + msg: &str, + suggestion: Vec<(Span, String)>, + ) -> &mut Self); + + forward!(pub fn span_suggestion(&mut self, + sp: Span, + msg: &str, + suggestion: String, + ) -> &mut Self); + + forward!(pub fn span_suggestions(&mut self, + sp: Span, + msg: &str, + suggestions: Vec, + ) -> &mut Self); + + forward!(pub fn set_span>(&mut self, sp: S) -> &mut Self); + + forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self); + /// Emit the diagnostic. pub fn emit(&mut self) { if self.cancelled() { @@ -163,58 +226,6 @@ impl<'a> DiagnosticBuilder<'a> { self } - forward!(pub fn note_expected_found(&mut self, - label: &dyn fmt::Display, - expected: DiagnosticStyledString, - found: DiagnosticStyledString, - ) -> &mut Self); - - forward!(pub fn note_expected_found_extra(&mut self, - label: &dyn fmt::Display, - expected: DiagnosticStyledString, - found: DiagnosticStyledString, - expected_extra: &dyn fmt::Display, - found_extra: &dyn fmt::Display, - ) -> &mut Self); - - forward!(pub fn note(&mut self, msg: &str) -> &mut Self); - forward!(pub fn span_note>(&mut self, - sp: S, - msg: &str, - ) -> &mut Self); - forward!(pub fn warn(&mut self, msg: &str) -> &mut Self); - forward!(pub fn span_warn>(&mut self, sp: S, msg: &str) -> &mut Self); - forward!(pub fn help(&mut self , msg: &str) -> &mut Self); - forward!(pub fn span_help>(&mut self, - sp: S, - msg: &str, - ) -> &mut Self); - - forward!(pub fn span_suggestion_short( - &mut self, - sp: Span, - msg: &str, - suggestion: String, - ) -> &mut Self); - - forward!(pub fn multipart_suggestion( - &mut self, - msg: &str, - suggestion: Vec<(Span, String)>, - ) -> &mut Self); - - forward!(pub fn span_suggestion(&mut self, - sp: Span, - msg: &str, - suggestion: String, - ) -> &mut Self); - - forward!(pub fn span_suggestions(&mut self, - sp: Span, - msg: &str, - suggestions: Vec, - ) -> &mut Self); - pub fn multipart_suggestion_with_applicability( &mut self, msg: &str, @@ -277,8 +288,6 @@ impl<'a> DiagnosticBuilder<'a> { ); self } - forward!(pub fn set_span>(&mut self, sp: S) -> &mut Self); - forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self); pub fn allow_suggestions(&mut self, allow: bool) -> &mut Self { self.allow_suggestions = allow; diff --git a/crates/swc_common/src/errors/emitter.rs b/crates/swc_common/src/errors/emitter.rs index 05ff6b747a0..3753a2fe430 100644 --- a/crates/swc_common/src/errors/emitter.rs +++ b/crates/swc_common/src/errors/emitter.rs @@ -8,6 +8,20 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::{ + borrow::Cow, + cmp::{min, Reverse}, + collections::HashMap, + io::{self, prelude::*}, + ops::Range, +}; + +#[cfg(feature = "tty-emitter")] +use atty; +#[cfg(feature = "tty-emitter")] +use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; +use unicode_width; + use self::Destination::*; use super::{ snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString}, @@ -18,18 +32,6 @@ use crate::{ sync::Lrc, syntax_pos::{MultiSpan, SourceFile, Span}, }; -#[cfg(feature = "tty-emitter")] -use atty; -use std::{ - borrow::Cow, - cmp::{min, Reverse}, - collections::HashMap, - io::{self, prelude::*}, - ops::Range, -}; -#[cfg(feature = "tty-emitter")] -use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; -use unicode_width; const ANONYMIZED_LINE_NUM: &str = "LL"; diff --git a/crates/swc_common/src/errors/mod.rs b/crates/swc_common/src/errors/mod.rs index 091961d0619..1d48d71f567 100644 --- a/crates/swc_common/src/errors/mod.rs +++ b/crates/swc_common/src/errors/mod.rs @@ -8,6 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::{ + borrow::Cow, + cell::RefCell, + error, fmt, + io::Write, + panic, + sync::atomic::{AtomicUsize, Ordering::SeqCst}, +}; + +use scoped_tls::scoped_thread_local; +#[cfg(feature = "tty-emitter")] +use termcolor::{Color, ColorSpec}; + use self::Level::*; pub use self::{ diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic}, @@ -20,17 +33,6 @@ use crate::{ sync::{Lock, LockCell, Lrc}, syntax_pos::{BytePos, FileLinesResult, FileName, Loc, MultiSpan, Span, NO_EXPANSION}, }; -use scoped_tls::scoped_thread_local; -use std::{ - borrow::Cow, - cell::RefCell, - error, fmt, - io::Write, - panic, - sync::atomic::{AtomicUsize, Ordering::SeqCst}, -}; -#[cfg(feature = "tty-emitter")] -use termcolor::{Color, ColorSpec}; mod diagnostic; mod diagnostic_builder; @@ -468,6 +470,7 @@ impl Handler { } result } + pub fn struct_span_warn_with_code<'a, S: Into>( &'a self, sp: S, @@ -482,6 +485,7 @@ impl Handler { } result } + pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> { let mut result = DiagnosticBuilder::new(self, Level::Warning, msg); if !self.flags.can_emit_warnings { @@ -489,6 +493,7 @@ impl Handler { } result } + pub fn struct_span_err<'a, S: Into>( &'a self, sp: S, @@ -498,6 +503,7 @@ impl Handler { result.set_span(sp); result } + pub fn struct_span_err_with_code<'a, S: Into>( &'a self, sp: S, @@ -509,11 +515,13 @@ impl Handler { result.code(code); result } + // FIXME: This method should be removed (every error should have an associated // error code). pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> { DiagnosticBuilder::new(self, Level::Error, msg) } + pub fn struct_err_with_code<'a>( &'a self, msg: &str, @@ -523,6 +531,7 @@ impl Handler { result.code(code); result } + pub fn struct_span_fatal<'a, S: Into>( &'a self, sp: S, @@ -532,6 +541,7 @@ impl Handler { result.set_span(sp); result } + pub fn struct_span_fatal_with_code<'a, S: Into>( &'a self, sp: S, @@ -543,6 +553,7 @@ impl Handler { result.code(code); result } + pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> { DiagnosticBuilder::new(self, Level::Fatal, msg) } @@ -561,6 +572,7 @@ impl Handler { self.emit(&sp.into(), msg, Fatal); FatalError } + pub fn span_fatal_with_code>( &self, sp: S, @@ -570,9 +582,11 @@ impl Handler { self.emit_with_code(&sp.into(), msg, code, Fatal); FatalError } + pub fn span_err>(&self, sp: S, msg: &str) { self.emit(&sp.into(), msg, Error); } + pub fn mut_span_err<'a, S: Into>( &'a self, sp: S, @@ -582,19 +596,24 @@ impl Handler { result.set_span(sp); result } + pub fn span_err_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { self.emit_with_code(&sp.into(), msg, code, Error); } + pub fn span_warn>(&self, sp: S, msg: &str) { self.emit(&sp.into(), msg, Warning); } + pub fn span_warn_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { self.emit_with_code(&sp.into(), msg, code, Warning); } + pub fn span_bug>(&self, sp: S, msg: &str) -> ! { self.emit(&sp.into(), msg, Bug); panic!("{}", ExplicitBug); } + pub fn delay_span_bug>(&self, sp: S, msg: &str) { if self.flags.treat_err_as_bug { // FIXME: don't abort here if report_delayed_bugs is off @@ -604,29 +623,36 @@ impl Handler { diagnostic.set_span(sp.into()); self.delay_as_bug(diagnostic); } + fn delay_as_bug(&self, diagnostic: Diagnostic) { if self.flags.report_delayed_bugs { DiagnosticBuilder::new_diagnostic(self, diagnostic.clone()).emit(); } self.delayed_span_bugs.borrow_mut().push(diagnostic); } + pub fn span_bug_no_panic>(&self, sp: S, msg: &str) { self.emit(&sp.into(), msg, Bug); } + pub fn span_note_without_error>(&self, sp: S, msg: &str) { self.emit(&sp.into(), msg, Note); } + pub fn span_note_diag<'a>(&'a self, sp: Span, msg: &str) -> DiagnosticBuilder<'a> { let mut db = DiagnosticBuilder::new(self, Note, msg); db.set_span(sp); db } + pub fn span_unimpl>(&self, sp: S, msg: &str) -> ! { self.span_bug(sp, &format!("unimplemented {}", msg)); } + pub fn failure(&self, msg: &str) { DiagnosticBuilder::new(self, FailureNote, msg).emit() } + pub fn fatal(&self, msg: &str) -> FatalError { if self.flags.treat_err_as_bug { self.bug(msg); @@ -634,6 +660,7 @@ impl Handler { DiagnosticBuilder::new(self, Fatal, msg).emit(); FatalError } + pub fn err(&self, msg: &str) { if self.flags.treat_err_as_bug { self.bug(msg); @@ -641,19 +668,23 @@ impl Handler { let mut db = DiagnosticBuilder::new(self, Error, msg); db.emit(); } + pub fn warn(&self, msg: &str) { let mut db = DiagnosticBuilder::new(self, Warning, msg); db.emit(); } + pub fn note_without_error(&self, msg: &str) { let mut db = DiagnosticBuilder::new(self, Note, msg); db.emit(); } + pub fn bug(&self, msg: &str) -> ! { let mut db = DiagnosticBuilder::new(self, Bug, msg); db.emit(); panic!("{}", ExplicitBug); } + pub fn unimpl(&self, msg: &str) -> ! { self.bug(&format!("unimplemented {}", msg)); } @@ -725,6 +756,7 @@ impl Handler { } FatalError.raise(); } + pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) { if lvl == Warning && !self.flags.can_emit_warnings { return; @@ -736,6 +768,7 @@ impl Handler { self.abort_if_errors(); } } + pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) { if lvl == Warning && !self.flags.can_emit_warnings { return; diff --git a/crates/swc_common/src/input.rs b/crates/swc_common/src/input.rs index a2aeccec377..5ab349677f0 100644 --- a/crates/swc_common/src/input.rs +++ b/crates/swc_common/src/input.rs @@ -1,7 +1,9 @@ -use crate::syntax_pos::{BytePos, SourceFile}; -use debug_unreachable::debug_unreachable; use std::str; +use debug_unreachable::debug_unreachable; + +use crate::syntax_pos::{BytePos, SourceFile}; + pub type SourceFileInput<'a> = StringInput<'a>; /// Implementation of [Input]. @@ -253,9 +255,10 @@ pub trait Input: Clone { #[cfg(test)] mod tests { + use std::sync::Arc; + use super::*; use crate::{FileName, FilePathMapping, SourceMap}; - use std::sync::Arc; fn with_test_sess(src: &str, f: F) where diff --git a/crates/swc_common/src/lib.rs b/crates/swc_common/src/lib.rs index 079486e33e7..c840bc91303 100644 --- a/crates/swc_common/src/lib.rs +++ b/crates/swc_common/src/lib.rs @@ -30,6 +30,14 @@ #![deny(unused)] #![cfg_attr(docsrs, feature(doc_cfg))] +use std::fmt::Debug; + +pub use ast_node::{ast_node, ast_serde, DeserializeEnum, Spanned}; +pub use from_variant::FromVariant; +use serde::Serialize; +pub use swc_eq_ignore_macros::{EqIgnoreSpan, TypeEq}; +pub use swc_visit::chain; + pub use self::{ eq::{EqIgnoreSpan, TypeEq}, errors::{SourceMapper, SourceMapperDyn}, @@ -41,12 +49,6 @@ pub use self::{ source_map::{FileLines, FileLoader, FilePathMapping, SourceMap, SpanSnippetError}, syntax_pos::LineCol, }; -pub use ast_node::{ast_node, ast_serde, DeserializeEnum, Spanned}; -pub use from_variant::FromVariant; -use serde::Serialize; -use std::fmt::Debug; -pub use swc_eq_ignore_macros::{EqIgnoreSpan, TypeEq}; -pub use swc_visit::chain; #[doc(hidden)] pub mod private; diff --git a/crates/swc_common/src/pass.rs b/crates/swc_common/src/pass.rs index cadf359031f..e91bab0724e 100644 --- a/crates/swc_common/src/pass.rs +++ b/crates/swc_common/src/pass.rs @@ -1,6 +1,7 @@ //! This module reexports items from `swc_visit` with some swc-specific traits. use std::borrow::Cow; + pub use swc_visit::*; /// A named compiler pass. diff --git a/crates/swc_common/src/plugin.rs b/crates/swc_common/src/plugin.rs index d2290eb2d15..f6d1426aad2 100644 --- a/crates/swc_common/src/plugin.rs +++ b/crates/swc_common/src/plugin.rs @@ -4,10 +4,12 @@ //! `swc_common`. #![allow(unused)] -use crate::{syntax_pos::Mark, SyntaxContext}; -use anyhow::Error; use std::any::type_name; +use anyhow::Error; + +use crate::{syntax_pos::Mark, SyntaxContext}; + #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] #[cfg_attr( diff --git a/crates/swc_common/src/pos.rs b/crates/swc_common/src/pos.rs index dbebc09cedd..e89692ba138 100644 --- a/crates/swc_common/src/pos.rs +++ b/crates/swc_common/src/pos.rs @@ -1,9 +1,10 @@ +use std::{borrow::Cow, rc::Rc, sync::Arc}; + pub use crate::syntax_pos::{ hygiene, BytePos, CharPos, FileName, Globals, Loc, LocWithOpt, Mark, MultiSpan, SourceFile, SourceFileAndBytePos, SourceFileAndLine, Span, SpanLinesError, SyntaxContext, DUMMY_SP, GLOBALS, NO_EXPANSION, }; -use std::{borrow::Cow, rc::Rc, sync::Arc}; /// /// # Derive diff --git a/crates/swc_common/src/rustc_data_structures/stable_hasher.rs b/crates/swc_common/src/rustc_data_structures/stable_hasher.rs index 14ccf4d9793..d8b1841bcfc 100644 --- a/crates/swc_common/src/rustc_data_structures/stable_hasher.rs +++ b/crates/swc_common/src/rustc_data_structures/stable_hasher.rs @@ -1,10 +1,11 @@ -use siphasher::sip128::{Hash128, Hasher128, SipHasher24}; use std::{ hash::{BuildHasher, Hash, Hasher}, marker::PhantomData, mem, }; +use siphasher::sip128::{Hash128, Hasher128, SipHasher24}; + /// When hashing something that ends up affecting properties like symbol names, /// we want these symbol names to be calculated independently of other factors /// like what architecture you're compiling *from*. @@ -327,6 +328,7 @@ impl HashStable for String { impl ToStableHashKey for String { type KeyType = String; + #[inline] fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType { self.clone() diff --git a/crates/swc_common/src/source_map.rs b/crates/swc_common/src/source_map.rs index 033263ff34b..5a3afbb8197 100644 --- a/crates/swc_common/src/source_map.rs +++ b/crates/swc_common/src/source_map.rs @@ -16,16 +16,6 @@ //! `spans` and used pervasively in the compiler. They are absolute positions //! within the SourceMap, which upon request can be converted to line and column //! information, source code snippets, etc. -pub use crate::syntax_pos::*; -use crate::{ - collections::AHashMap, - errors::SourceMapper, - rustc_data_structures::stable_hasher::StableHasher, - sync::{Lock, LockGuard, Lrc, MappedLockGuard}, -}; -use once_cell::sync::Lazy; -#[cfg(feature = "sourcemap")] -use sourcemap::SourceMapBuilder; use std::{ cmp, cmp::{max, min}, @@ -35,8 +25,20 @@ use std::{ path::{Path, PathBuf}, sync::atomic::{AtomicUsize, Ordering::SeqCst}, }; + +use once_cell::sync::Lazy; +#[cfg(feature = "sourcemap")] +use sourcemap::SourceMapBuilder; use tracing::debug; +pub use crate::syntax_pos::*; +use crate::{ + collections::AHashMap, + errors::SourceMapper, + rustc_data_structures::stable_hasher::StableHasher, + sync::{Lock, LockGuard, Lrc, MappedLockGuard}, +}; + static CURRENT_DIR: Lazy> = Lazy::new(|| env::current_dir().ok()); // _____________________________________________________________________________ @@ -1200,21 +1202,27 @@ impl SourceMapper for SourceMap { fn lookup_char_pos(&self, pos: BytePos) -> Loc { self.lookup_char_pos(pos) } + fn span_to_lines(&self, sp: Span) -> FileLinesResult { self.span_to_lines(sp) } + fn span_to_string(&self, sp: Span) -> String { self.span_to_string(sp) } + fn span_to_filename(&self, sp: Span) -> FileName { self.span_to_filename(sp) } + fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option { self.merge_spans(sp_lhs, sp_rhs) } + fn call_span_if_macro(&self, sp: Span) -> Span { sp } + fn doctest_offset_line(&self, line: usize) -> usize { self.doctest_offset_line(line) } diff --git a/crates/swc_common/src/sync.rs b/crates/swc_common/src/sync.rs index bc624892cf9..6cea583ccc5 100644 --- a/crates/swc_common/src/sync.rs +++ b/crates/swc_common/src/sync.rs @@ -33,35 +33,37 @@ //! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + //! Sync depending on the value of cfg!(parallel_queries). -#[cfg(feature = "concurrent")] -use parking_lot::{Mutex as InnerLock, RwLock as InnerRwLock}; #[cfg(not(feature = "concurrent"))] use std::cell::{RefCell as InnerRwLock, RefCell as InnerLock}; -use std::fmt; - -#[cfg(feature = "concurrent")] -pub use self::concurrent::*; -#[cfg(not(feature = "concurrent"))] -pub use self::single::*; use std::{ cmp::Ordering, collections::HashMap, + fmt, fmt::{Debug, Formatter}, hash::{BuildHasher, Hash}, }; +#[cfg(feature = "concurrent")] +use parking_lot::{Mutex as InnerLock, RwLock as InnerRwLock}; + +#[cfg(feature = "concurrent")] +pub use self::concurrent::*; +#[cfg(not(feature = "concurrent"))] +pub use self::single::*; + #[cfg(feature = "concurrent")] mod concurrent { + pub use std::{ + marker::{Send, Sync}, + sync::Arc as Lrc, + }; + pub use once_cell::sync::{Lazy, OnceCell}; pub use parking_lot::{ MappedMutexGuard as MappedLockGuard, MappedRwLockReadGuard as MappedReadGuard, MappedRwLockWriteGuard as MappedWriteGuard, MutexGuard as LockGuard, RwLockReadGuard as ReadGuard, RwLockWriteGuard as WriteGuard, }; - pub use std::{ - marker::{Send, Sync}, - sync::Arc as Lrc, - }; } #[cfg(not(feature = "concurrent"))] diff --git a/crates/swc_common/src/syntax_pos.rs b/crates/swc_common/src/syntax_pos.rs index 75e6cb4873e..1b9b5b28be2 100644 --- a/crates/swc_common/src/syntax_pos.rs +++ b/crates/swc_common/src/syntax_pos.rs @@ -1,8 +1,3 @@ -pub use self::hygiene::{Mark, SyntaxContext}; -use crate::{rustc_data_structures::stable_hasher::StableHasher, sync::Lrc}; -#[cfg(feature = "parking_lot")] -use parking_lot::Mutex; -use serde::{Deserialize, Serialize}; #[cfg(not(feature = "parking_lot"))] use std::sync::Mutex; use std::{ @@ -12,8 +7,15 @@ use std::{ ops::{Add, Sub}, path::PathBuf, }; + +#[cfg(feature = "parking_lot")] +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; use url::Url; +pub use self::hygiene::{Mark, SyntaxContext}; +use crate::{rustc_data_structures::stable_hasher::StableHasher, sync::Lrc}; + mod analyze_source_file; pub mod hygiene; @@ -202,6 +204,7 @@ impl Span { pub fn lo(self) -> BytePos { self.lo } + #[inline] pub fn new(mut lo: BytePos, mut hi: BytePos, ctxt: SyntaxContext) -> Self { if lo > hi { @@ -215,6 +218,7 @@ impl Span { pub fn with_lo(&self, lo: BytePos) -> Span { Span::new(lo, self.hi, self.ctxt) } + #[inline] pub fn hi(self) -> BytePos { self.hi @@ -224,10 +228,12 @@ impl Span { pub fn with_hi(&self, hi: BytePos) -> Span { Span::new(self.lo, hi, self.ctxt) } + #[inline] pub fn ctxt(self) -> SyntaxContext { self.ctxt } + #[inline] pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span { Span::new(self.lo, self.hi, ctxt) @@ -245,6 +251,7 @@ impl Span { pub fn shrink_to_lo(self) -> Span { self.with_hi(self.lo) } + /// Returns a new span representing an empty span at the end of this span #[inline] pub fn shrink_to_hi(self) -> Span { @@ -742,6 +749,7 @@ impl SourceFile { pub fn byte_length(&self) -> u32 { self.end_pos.0 - self.start_pos.0 } + pub fn count_lines(&self) -> usize { self.lines.len() } diff --git a/crates/swc_common/src/syntax_pos/analyze_source_file.rs b/crates/swc_common/src/syntax_pos/analyze_source_file.rs index ded19f88cfe..30ab86b2545 100644 --- a/crates/swc_common/src/syntax_pos/analyze_source_file.rs +++ b/crates/swc_common/src/syntax_pos/analyze_source_file.rs @@ -7,9 +7,10 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -use super::*; use unicode_width::UnicodeWidthChar; +use super::*; + /// Finds all newlines, multi-byte characters, and non-narrow characters in a /// SourceFile. /// diff --git a/crates/swc_common/src/syntax_pos/hygiene.rs b/crates/swc_common/src/syntax_pos/hygiene.rs index f54bcb439a8..7a65f926adc 100644 --- a/crates/swc_common/src/syntax_pos/hygiene.rs +++ b/crates/swc_common/src/syntax_pos/hygiene.rs @@ -15,14 +15,16 @@ //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216. //! DOI=10.1017/S0956796812000093 -use super::GLOBALS; -use crate::collections::AHashMap; -use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, fmt, }; +use serde::{Deserialize, Serialize}; + +use super::GLOBALS; +use crate::collections::AHashMap; + /// A SyntaxContext represents a chain of macro expansions (represented by /// marks). #[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -75,8 +77,7 @@ impl Mark { pub fn fresh(parent: Mark) -> Self { // Note: msvc tries to link against proxied fn for normal build, // have to limit build target to wasm only to avoid it. - #[cfg(feature = "plugin-mode")] - #[cfg(target_arch = "wasm32")] + #[cfg(all(feature = "plugin-mode", target_arch = "wasm32"))] return Mark(unsafe { __mark_fresh_proxy( parent @@ -88,20 +89,12 @@ impl Mark { .expect("Should able to convert i32 into mark") }); - #[cfg(not(feature = "plugin-mode"))] - return HygieneData::with(|data| { - data.marks.push(MarkData { - parent, - is_builtin: false, - }); - Mark(data.marks.len() as u32 - 1) - }); - // https://github.com/swc-project/swc/pull/3492#discussion_r802224857 // This is unreachable path for noraml execution. However for some // cases like running plugin's test without targeting wasm32-*, we'll // allow to not panic in here at least. - #[cfg(all(feature = "plugin-mode", not(target_arch = "wasm32")))] + + #[cfg(not(all(feature = "plugin-mode", target_arch = "wasm32")))] return HygieneData::with(|data| { data.marks.push(MarkData { parent, diff --git a/crates/swc_common/src/util/iter.rs b/crates/swc_common/src/util/iter.rs index 0c9c473f0e3..8189cc9e227 100644 --- a/crates/swc_common/src/util/iter.rs +++ b/crates/swc_common/src/util/iter.rs @@ -29,6 +29,7 @@ where I: IntoIterator, { type Item = I::Item; + fn next(&mut self) -> Option { if let Some(b) = self.base.next() { return Some(b); diff --git a/crates/swc_common/src/util/take.rs b/crates/swc_common/src/util/take.rs index ec539481d4e..8dfd21394c2 100644 --- a/crates/swc_common/src/util/take.rs +++ b/crates/swc_common/src/util/take.rs @@ -1,6 +1,7 @@ -use crate::{Span, DUMMY_SP}; use std::mem::replace; +use crate::{Span, DUMMY_SP}; + /// Helper for people who are working on `VisitMut`. /// /// diff --git a/crates/swc_common/tests/concurrent.rs b/crates/swc_common/tests/concurrent.rs index 3d8305bc600..4441c6f5b0a 100644 --- a/crates/swc_common/tests/concurrent.rs +++ b/crates/swc_common/tests/concurrent.rs @@ -1,7 +1,8 @@ #![cfg(feature = "concurrent")] -use rayon::prelude::*; use std::{env, path::PathBuf, sync::Arc}; + +use rayon::prelude::*; use swc_common::{sync::Lrc, FilePathMapping, SourceFile, SourceMap}; #[test] diff --git a/crates/swc_css_ast/src/at_rule/charset.rs b/crates/swc_css_ast/src/at_rule/charset.rs index ba069fac0db..17f0499fd35 100644 --- a/crates/swc_css_ast/src/at_rule/charset.rs +++ b/crates/swc_css_ast/src/at_rule/charset.rs @@ -1,6 +1,7 @@ -use crate::Str; use swc_common::{ast_node, Span}; +use crate::Str; + #[ast_node("CharsetRule")] pub struct CharsetRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/color_profile.rs b/crates/swc_css_ast/src/at_rule/color_profile.rs index 2d6bcf6047d..f64ec863fef 100644 --- a/crates/swc_css_ast/src/at_rule/color_profile.rs +++ b/crates/swc_css_ast/src/at_rule/color_profile.rs @@ -1,6 +1,7 @@ -use crate::{DashedIdent, DeclarationBlockItem, Ident}; use swc_common::{ast_node, Span}; +use crate::{DashedIdent, DeclarationBlockItem, Ident}; + #[ast_node] pub enum ColorProfileName { #[tag("DashedIdent")] diff --git a/crates/swc_css_ast/src/at_rule/counter_style.rs b/crates/swc_css_ast/src/at_rule/counter_style.rs index 370af1b7a21..d2a880ad54f 100644 --- a/crates/swc_css_ast/src/at_rule/counter_style.rs +++ b/crates/swc_css_ast/src/at_rule/counter_style.rs @@ -1,6 +1,7 @@ -use crate::{CustomIdent, DeclarationBlockItem}; use swc_common::{ast_node, Span}; +use crate::{CustomIdent, DeclarationBlockItem}; + #[ast_node("CounterStyleRule")] pub struct CounterStyleRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/document.rs b/crates/swc_css_ast/src/at_rule/document.rs index c8a3557d626..1cf6bb2c221 100644 --- a/crates/swc_css_ast/src/at_rule/document.rs +++ b/crates/swc_css_ast/src/at_rule/document.rs @@ -1,6 +1,7 @@ -use crate::{Function, Rule, Url}; use swc_common::{ast_node, Span}; +use crate::{Function, Rule, Url}; + #[ast_node("DocumentRule")] pub struct DocumentRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/import.rs b/crates/swc_css_ast/src/at_rule/import.rs index 1f784a03078..170ff8f47e0 100644 --- a/crates/swc_css_ast/src/at_rule/import.rs +++ b/crates/swc_css_ast/src/at_rule/import.rs @@ -1,6 +1,7 @@ -use crate::{Declaration, Function, Ident, MediaQueryList, Str, SupportsCondition, Url}; use swc_common::{ast_node, Span}; +use crate::{Declaration, Function, Ident, MediaQueryList, Str, SupportsCondition, Url}; + #[ast_node] pub enum ImportHref { #[tag("Url")] diff --git a/crates/swc_css_ast/src/at_rule/keyframe.rs b/crates/swc_css_ast/src/at_rule/keyframe.rs index f72e962b1ac..0bc00ce114e 100644 --- a/crates/swc_css_ast/src/at_rule/keyframe.rs +++ b/crates/swc_css_ast/src/at_rule/keyframe.rs @@ -1,6 +1,7 @@ -use crate::{Block, CustomIdent, Ident, Percent, Str}; use swc_common::{ast_node, Span}; +use crate::{Block, CustomIdent, Ident, Percent, Str}; + #[ast_node("KeyframesRule")] pub struct KeyframesRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/layer.rs b/crates/swc_css_ast/src/at_rule/layer.rs index 6d3cad1c236..58086fb78ce 100644 --- a/crates/swc_css_ast/src/at_rule/layer.rs +++ b/crates/swc_css_ast/src/at_rule/layer.rs @@ -1,6 +1,7 @@ -use crate::{Ident, Rule}; use swc_common::{ast_node, Span}; +use crate::{Ident, Rule}; + #[ast_node("LayerName")] pub struct LayerName { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/media.rs b/crates/swc_css_ast/src/at_rule/media.rs index 58d51b1683b..1863bac2681 100644 --- a/crates/swc_css_ast/src/at_rule/media.rs +++ b/crates/swc_css_ast/src/at_rule/media.rs @@ -1,7 +1,8 @@ -use crate::{Dimension, Ident, Number, Ratio, Rule}; use string_enum::StringEnum; use swc_common::{ast_node, EqIgnoreSpan, Span}; +use crate::{Dimension, Ident, Number, Ratio, Rule}; + #[ast_node("MediaRule")] pub struct MediaRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/mod.rs b/crates/swc_css_ast/src/at_rule/mod.rs index 4403dcd5fc4..d6fa6539947 100644 --- a/crates/swc_css_ast/src/at_rule/mod.rs +++ b/crates/swc_css_ast/src/at_rule/mod.rs @@ -1,10 +1,11 @@ +use is_macro::Is; +use swc_common::{ast_node, Span}; + pub use self::{ charset::*, color_profile::*, counter_style::*, document::*, import::*, keyframe::*, layer::*, media::*, page::*, property::*, support::*, }; use crate::{Block, DashedIdent, Ident, SimpleBlock, Str, Url, Value}; -use is_macro::Is; -use swc_common::{ast_node, Span}; mod charset; mod color_profile; diff --git a/crates/swc_css_ast/src/at_rule/page.rs b/crates/swc_css_ast/src/at_rule/page.rs index 1e5bfa30dbc..4016284c991 100644 --- a/crates/swc_css_ast/src/at_rule/page.rs +++ b/crates/swc_css_ast/src/at_rule/page.rs @@ -1,6 +1,7 @@ -use crate::{DeclarationBlockItem, Ident}; use swc_common::{ast_node, Span}; +use crate::{DeclarationBlockItem, Ident}; + #[ast_node("PageRule")] pub struct PageRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/property.rs b/crates/swc_css_ast/src/at_rule/property.rs index c2e7ce0d54b..703cee91bd9 100644 --- a/crates/swc_css_ast/src/at_rule/property.rs +++ b/crates/swc_css_ast/src/at_rule/property.rs @@ -1,6 +1,7 @@ -use crate::{DashedIdent, DeclarationBlockItem}; use swc_common::{ast_node, Span}; +use crate::{DashedIdent, DeclarationBlockItem}; + #[ast_node("PropertyRule")] pub struct PropertyRule { pub span: Span, diff --git a/crates/swc_css_ast/src/at_rule/support.rs b/crates/swc_css_ast/src/at_rule/support.rs index 4b36a4d4204..f8961fea48a 100644 --- a/crates/swc_css_ast/src/at_rule/support.rs +++ b/crates/swc_css_ast/src/at_rule/support.rs @@ -1,6 +1,7 @@ -use crate::{Declaration, Rule}; use swc_common::{ast_node, Span}; +use crate::{Declaration, Rule}; + #[ast_node("SupportsRule")] pub struct SupportsRule { pub span: Span, diff --git a/crates/swc_css_ast/src/selector.rs b/crates/swc_css_ast/src/selector.rs index 8d5e23bd510..a3db2daddb9 100644 --- a/crates/swc_css_ast/src/selector.rs +++ b/crates/swc_css_ast/src/selector.rs @@ -1,9 +1,10 @@ -use crate::{Ident, Str, Tokens}; use is_macro::Is; use string_enum::StringEnum; use swc_atoms::JsWord; use swc_common::{ast_node, EqIgnoreSpan, Span}; +use crate::{Ident, Str, Tokens}; + #[ast_node("SelectorList")] pub struct SelectorList { pub span: Span, diff --git a/crates/swc_css_ast/src/style_rule.rs b/crates/swc_css_ast/src/style_rule.rs index 444adf1f11d..5fb9dbb3156 100644 --- a/crates/swc_css_ast/src/style_rule.rs +++ b/crates/swc_css_ast/src/style_rule.rs @@ -1,7 +1,8 @@ -use crate::{AtRule, DashedIdent, Ident, SelectorList, Tokens, Value}; use is_macro::Is; use swc_common::{ast_node, Span}; +use crate::{AtRule, DashedIdent, Ident, SelectorList, Tokens, Value}; + #[ast_node("Stylesheet")] pub struct Stylesheet { pub span: Span, diff --git a/crates/swc_css_ast/src/value.rs b/crates/swc_css_ast/src/value.rs index 0b6033bbfd1..22bb327dc21 100644 --- a/crates/swc_css_ast/src/value.rs +++ b/crates/swc_css_ast/src/value.rs @@ -1,8 +1,9 @@ -use crate::{DashedIdent, Ident, SimpleBlock, Str, Tokens}; use string_enum::StringEnum; use swc_atoms::JsWord; use swc_common::{ast_node, EqIgnoreSpan, Span}; +use crate::{DashedIdent, Ident, SimpleBlock, Str, Tokens}; + #[ast_node] pub enum Value { #[tag("SimpleBlock")] diff --git a/crates/swc_css_codegen/src/ctx.rs b/crates/swc_css_codegen/src/ctx.rs index 249394ed6a9..4d077fac7d2 100644 --- a/crates/swc_css_codegen/src/ctx.rs +++ b/crates/swc_css_codegen/src/ctx.rs @@ -1,6 +1,7 @@ -use crate::{writer::CssWriter, CodeGenerator}; use std::ops::{Deref, DerefMut}; +use crate::{writer::CssWriter, CodeGenerator}; + impl CodeGenerator where W: CssWriter, diff --git a/crates/swc_css_codegen/src/emit.rs b/crates/swc_css_codegen/src/emit.rs index 708b18b1470..7824cfa31a2 100644 --- a/crates/swc_css_codegen/src/emit.rs +++ b/crates/swc_css_codegen/src/emit.rs @@ -1,4 +1,5 @@ use std::fmt::Result; + use swc_common::Spanned; /// diff --git a/crates/swc_css_codegen/src/lib.rs b/crates/swc_css_codegen/src/lib.rs index a491858720f..c111f0565f7 100644 --- a/crates/swc_css_codegen/src/lib.rs +++ b/crates/swc_css_codegen/src/lib.rs @@ -1,14 +1,16 @@ #![deny(clippy::all)] #![allow(clippy::needless_update)] -pub use self::emit::*; -use self::{ctx::Ctx, list::ListFormat}; pub use std::fmt::Result; + use swc_common::Spanned; use swc_css_ast::*; use swc_css_codegen_macros::emitter; use writer::CssWriter; +pub use self::emit::*; +use self::{ctx::Ctx, list::ListFormat}; + #[macro_use] mod macros; mod ctx; diff --git a/crates/swc_css_codegen/src/writer/basic.rs b/crates/swc_css_codegen/src/writer/basic.rs index 274b00e77bb..cb6c0b986f5 100644 --- a/crates/swc_css_codegen/src/writer/basic.rs +++ b/crates/swc_css_codegen/src/writer/basic.rs @@ -1,10 +1,12 @@ -use super::CssWriter; use std::{ fmt::{Result, Write}, str::from_utf8, }; + use swc_common::Span; +use super::CssWriter; + pub struct BasicCssWriterConfig<'a> { pub indent: &'a str, } @@ -91,9 +93,9 @@ where let b4; let char_as_u8 = char as u8; - let bytes = if char_as_u8 > 0x0F { + let bytes = if char_as_u8 > 0x0f { let high = (char_as_u8 >> 4) as usize; - let low = (char_as_u8 & 0x0F) as usize; + let low = (char_as_u8 & 0x0f) as usize; b4 = [b'\\', HEX_DIGITS[high], HEX_DIGITS[low], b' ']; diff --git a/crates/swc_css_codegen/src/writer/mod.rs b/crates/swc_css_codegen/src/writer/mod.rs index d07eee996b4..f6df4c154b1 100644 --- a/crates/swc_css_codegen/src/writer/mod.rs +++ b/crates/swc_css_codegen/src/writer/mod.rs @@ -1,5 +1,6 @@ -use auto_impl::auto_impl; use std::fmt::Result; + +use auto_impl::auto_impl; use swc_common::Span; pub mod basic; diff --git a/crates/swc_css_codegen/tests/fixture.rs b/crates/swc_css_codegen/tests/fixture.rs index 2ae6d564a55..e54eaf85061 100644 --- a/crates/swc_css_codegen/tests/fixture.rs +++ b/crates/swc_css_codegen/tests/fixture.rs @@ -2,6 +2,7 @@ use std::{ mem::take, path::{Path, PathBuf}, }; + use swc_common::{FileName, Span}; use swc_css_ast::{HexColor, ImportantFlag, Number, Str, Stylesheet, UrlValueRaw}; use swc_css_codegen::{ @@ -97,8 +98,11 @@ fn run(input: &Path, minify: bool) { struct NormalizeTest; impl VisitMut for NormalizeTest { - fn visit_mut_span(&mut self, n: &mut Span) { - *n = Default::default() + fn visit_mut_hex_color(&mut self, n: &mut HexColor) { + n.visit_mut_children_with(self); + + n.value = "fff".into(); + n.raw = "fff".into(); } fn visit_mut_important_flag(&mut self, n: &mut ImportantFlag) { @@ -108,31 +112,28 @@ impl VisitMut for NormalizeTest { n.value.raw = n.value.raw.to_lowercase().into(); } - fn visit_mut_url_value_raw(&mut self, n: &mut UrlValueRaw) { - n.visit_mut_children_with(self); - - n.before = "".into(); - n.after = "".into(); - n.raw = "".into(); - } - fn visit_mut_number(&mut self, n: &mut Number) { n.visit_mut_children_with(self); n.raw = "".into(); } + fn visit_mut_span(&mut self, n: &mut Span) { + *n = Default::default() + } + fn visit_mut_str(&mut self, n: &mut Str) { n.visit_mut_children_with(self); n.raw = "".into(); } - fn visit_mut_hex_color(&mut self, n: &mut HexColor) { + fn visit_mut_url_value_raw(&mut self, n: &mut UrlValueRaw) { n.visit_mut_children_with(self); - n.value = "fff".into(); - n.raw = "fff".into(); + n.before = "".into(); + n.after = "".into(); + n.raw = "".into(); } } diff --git a/crates/swc_css_minifier/tests/fixture.rs b/crates/swc_css_minifier/tests/fixture.rs index 3afe63365ec..23f91149b83 100644 --- a/crates/swc_css_minifier/tests/fixture.rs +++ b/crates/swc_css_minifier/tests/fixture.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use swc_css_ast::Stylesheet; use swc_css_codegen::{ writer::basic::{BasicCssWriter, BasicCssWriterConfig}, diff --git a/crates/swc_css_parser/src/lexer/mod.rs b/crates/swc_css_parser/src/lexer/mod.rs index fc8e6d46ae4..38ceca7dddf 100644 --- a/crates/swc_css_parser/src/lexer/mod.rs +++ b/crates/swc_css_parser/src/lexer/mod.rs @@ -1,11 +1,13 @@ +use std::char::REPLACEMENT_CHARACTER; + +use swc_atoms::{js_word, JsWord}; +use swc_common::{input::Input, BytePos, Span}; +use swc_css_ast::{NumberType, Token, TokenAndSpan}; + use crate::{ error::{Error, ErrorKind}, parser::{input::ParserInput, PResult, ParserConfig}, }; -use std::char::REPLACEMENT_CHARACTER; -use swc_atoms::{js_word, JsWord}; -use swc_common::{input::Input, BytePos, Span}; -use swc_css_ast::{NumberType, Token, TokenAndSpan}; pub(crate) type LexResult = Result; diff --git a/crates/swc_css_parser/src/lib.rs b/crates/swc_css_parser/src/lib.rs index f846263a31b..185d6e9d56d 100644 --- a/crates/swc_css_parser/src/lib.rs +++ b/crates/swc_css_parser/src/lib.rs @@ -1,16 +1,18 @@ #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(unused_must_use)] +#![deny(clippy::all)] #![allow(clippy::needless_return)] #![allow(clippy::nonminimal_bool)] #![allow(clippy::wrong_self_convention)] +use swc_common::{input::StringInput, BytePos, SourceFile}; +use swc_css_ast::Tokens; + use crate::{ error::Error, lexer::Lexer, parser::{input::TokensInput, PResult, Parser, ParserConfig}, }; -use swc_common::{input::StringInput, BytePos, SourceFile}; -use swc_css_ast::Tokens; #[macro_use] mod macros; diff --git a/crates/swc_css_parser/src/parser/at_rule.rs b/crates/swc_css_parser/src/parser/at_rule.rs index aaa99ca5f60..9f99071f544 100644 --- a/crates/swc_css_parser/src/parser/at_rule.rs +++ b/crates/swc_css_parser/src/parser/at_rule.rs @@ -1,11 +1,12 @@ +use swc_common::{BytePos, Span}; +use swc_css_ast::*; + use super::{input::ParserInput, PResult, Parser}; use crate::{ error::{Error, ErrorKind}, parser::{Ctx, RuleContext}, Parse, }; -use swc_common::{BytePos, Span}; -use swc_css_ast::*; #[derive(Debug, Default)] pub(super) struct AtRuleContext {} diff --git a/crates/swc_css_parser/src/parser/base.rs b/crates/swc_css_parser/src/parser/base.rs index b90ed7fc647..1ddaede0c55 100644 --- a/crates/swc_css_parser/src/parser/base.rs +++ b/crates/swc_css_parser/src/parser/base.rs @@ -1,11 +1,12 @@ +use swc_common::Span; +use swc_css_ast::*; + use super::{input::ParserInput, PResult, Parser}; use crate::{ error::{Error, ErrorKind}, parser::{Ctx, RuleContext}, Parse, }; -use swc_common::Span; -use swc_css_ast::*; impl Parse for Parser where diff --git a/crates/swc_css_parser/src/parser/input.rs b/crates/swc_css_parser/src/parser/input.rs index 2db51b01980..4edf970c16b 100644 --- a/crates/swc_css_parser/src/parser/input.rs +++ b/crates/swc_css_parser/src/parser/input.rs @@ -1,9 +1,11 @@ -use super::PResult; -use crate::error::{Error, ErrorKind}; use std::fmt::Debug; + use swc_common::{BytePos, Span, SyntaxContext}; use swc_css_ast::{Token, TokenAndSpan, Tokens}; +use super::PResult; +use crate::error::{Error, ErrorKind}; + pub trait ParserInput { type State: Debug; diff --git a/crates/swc_css_parser/src/parser/mod.rs b/crates/swc_css_parser/src/parser/mod.rs index 97eb085f23f..34374d37011 100644 --- a/crates/swc_css_parser/src/parser/mod.rs +++ b/crates/swc_css_parser/src/parser/mod.rs @@ -1,7 +1,9 @@ +use std::mem::take; + +use swc_css_ast::*; + use self::input::{Buffer, ParserInput}; use crate::{error::Error, Parse}; -use std::mem::take; -use swc_css_ast::*; #[macro_use] mod macros; diff --git a/crates/swc_css_parser/src/parser/selector/mod.rs b/crates/swc_css_parser/src/parser/selector/mod.rs index 735eb1b879a..3e35022bd80 100644 --- a/crates/swc_css_parser/src/parser/selector/mod.rs +++ b/crates/swc_css_parser/src/parser/selector/mod.rs @@ -1,11 +1,12 @@ +use swc_atoms::JsWord; +use swc_common::{BytePos, Span}; +use swc_css_ast::*; + use super::{input::ParserInput, PResult, Parser}; use crate::{ error::{Error, ErrorKind}, Parse, }; -use swc_atoms::JsWord; -use swc_common::{BytePos, Span}; -use swc_css_ast::*; impl Parse for Parser where diff --git a/crates/swc_css_parser/src/parser/traits.rs b/crates/swc_css_parser/src/parser/traits.rs index 82928c9cb9f..c9903e5135b 100644 --- a/crates/swc_css_parser/src/parser/traits.rs +++ b/crates/swc_css_parser/src/parser/traits.rs @@ -1,6 +1,7 @@ +use swc_common::Span; + use super::PResult; use crate::Parse; -use swc_common::Span; pub(super) trait ParseDelmited: Parse { fn eat_delimiter(&mut self) -> PResult; diff --git a/crates/swc_css_parser/src/parser/util.rs b/crates/swc_css_parser/src/parser/util.rs index 5f1c9d24700..8c052514388 100644 --- a/crates/swc_css_parser/src/parser/util.rs +++ b/crates/swc_css_parser/src/parser/util.rs @@ -1,7 +1,9 @@ -use super::{input::ParserInput, Ctx, PResult, Parse, Parser}; use std::ops::{Deref, DerefMut}; + use swc_common::Span; +use super::{input::ParserInput, Ctx, PResult, Parse, Parser}; + pub(crate) trait ItemBlock { type Item; diff --git a/crates/swc_css_parser/src/parser/value/mod.rs b/crates/swc_css_parser/src/parser/value/mod.rs index de20187f661..8820bd2c349 100644 --- a/crates/swc_css_parser/src/parser/value/mod.rs +++ b/crates/swc_css_parser/src/parser/value/mod.rs @@ -1,10 +1,11 @@ +use swc_common::{BytePos, Spanned}; +use swc_css_ast::*; + use super::{input::ParserInput, Ctx, PResult, Parser}; use crate::{ error::{Error, ErrorKind}, Parse, }; -use swc_common::{BytePos, Spanned}; -use swc_css_ast::*; #[cfg(test)] mod tests; @@ -1327,9 +1328,8 @@ where } fn is_length_unit(unit: &str) -> bool { - match &*unit.to_ascii_lowercase() { - // Relative Lengths - // Font-relative Lengths + matches!( + &*unit.to_ascii_lowercase(), "em" | "rem" | "ex" | "rex" | "cap" | "rcap" | @@ -1344,42 +1344,26 @@ fn is_length_unit(unit: &str) -> bool { "vmin" | "svmin" | "lvmin" | "dvmin" | "vmax" | "svmax" | "lvmax" | "dvmax" | // Absolute lengths - "cm" | "mm" | "q" | "in" | "pc" | "pt" | "px" | "mozmm" => true, - _ => false, - } + "cm" | "mm" | "q" | "in" | "pc" | "pt" | "px" | "mozmm" + ) } fn is_angle_unit(unit: &str) -> bool { - match &*unit.to_ascii_lowercase() { - "deg" | "grad" | "rad" | "turn" => true, - _ => false, - } + matches!(&*unit.to_ascii_lowercase(), "deg" | "grad" | "rad" | "turn") } fn is_time_unit(unit: &str) -> bool { - match &*unit.to_ascii_lowercase() { - "s" | "ms" => true, - _ => false, - } + matches!(&*unit.to_ascii_lowercase(), "s" | "ms") } fn is_frequency_unit(unit: &str) -> bool { - match &*unit.to_ascii_lowercase() { - "hz" | "khz" => true, - _ => false, - } + matches!(&*unit.to_ascii_lowercase(), "hz" | "khz") } fn is_resolution_unit(unit: &str) -> bool { - match &*unit.to_ascii_lowercase() { - "dpi" | "dpcm" | "dppx" | "x" => true, - _ => false, - } + matches!(&*unit.to_ascii_lowercase(), "dpi" | "dpcm" | "dppx" | "x") } fn is_flex_unit(unit: &str) -> bool { - match &*unit.to_ascii_lowercase() { - "fr" => true, - _ => false, - } + matches!(&*unit.to_ascii_lowercase(), "fr") } diff --git a/crates/swc_css_parser/tests/fixture.rs b/crates/swc_css_parser/tests/fixture.rs index 2d4071dcc19..26de18b65e3 100644 --- a/crates/swc_css_parser/tests/fixture.rs +++ b/crates/swc_css_parser/tests/fixture.rs @@ -1,6 +1,7 @@ #![allow(clippy::needless_update)] use std::path::PathBuf; + use swc_common::{errors::Handler, input::SourceFileInput, Span, Spanned}; use swc_css_ast::*; use swc_css_parser::{ @@ -280,125 +281,234 @@ macro_rules! mtd { impl Visit for SpanVisualizer<'_> { mtd!(AtRule, visit_at_rule); + mtd!(BinValue, visit_bin_value); + mtd!(SelectorList, visit_selector_list); + mtd!(ComplexSelector, visit_complex_selector); + mtd!(Combinator, visit_combinator); + mtd!(CompoundSelector, visit_compound_selector); + mtd!(TypeSelector, visit_type_selector); + mtd!(TagNameSelector, visit_tag_name_selector); + mtd!(NsPrefix, visit_ns_prefix); + mtd!(WqName, visit_wq_name); + mtd!(UniversalSelector, visit_universal_selector); + mtd!(IdSelector, visit_id_selector); + mtd!(ClassSelector, visit_class_selector); + mtd!(AttributeSelector, visit_attribute_selector); + mtd!(AttributeSelectorMatcher, visit_attribute_selector_matcher); + mtd!(AttributeSelectorValue, visit_attribute_selector_value); + mtd!(AttributeSelectorModifier, visit_attribute_selector_modifier); + mtd!(SubclassSelector, visit_subclass_selector); + mtd!(NestingSelector, visit_nesting_selector); + mtd!(PseudoClassSelector, visit_pseudo_class_selector); + mtd!(PseudoElementSelector, visit_pseudo_element_selector); + mtd!(AnPlusB, visit_an_plus_b); + mtd!(Delimiter, visit_delimiter); + mtd!(Block, visit_block); + mtd!(SimpleBlock, visit_simple_block); + mtd!(Function, visit_function); + mtd!(HexColor, visit_hex_color); + mtd!(Number, visit_number); + mtd!(Ratio, visit_ratio); + mtd!(Percent, visit_percent); + mtd!(Declaration, visit_declaration); + mtd!(DeclarationName, visit_declaration_name); + mtd!(ImportantFlag, visit_important_flag); + mtd!(Nth, visit_nth); + mtd!(Rule, visit_rule); + mtd!(Str, visit_str); + mtd!(QualifiedRule, visit_qualified_rule); + mtd!(Stylesheet, visit_stylesheet); + mtd!(Ident, visit_ident); + mtd!(CustomIdent, visit_custom_ident); + mtd!(DashedIdent, visit_dashed_ident); + mtd!(Tokens, visit_tokens); + mtd!(Dimension, visit_dimension); + mtd!(Length, visit_length); + mtd!(Angle, visit_angle); + mtd!(Time, visit_time); + mtd!(Frequency, visit_frequency); + mtd!(Resolution, visit_resolution); + mtd!(Flex, visit_flex); + mtd!(UnknownDimension, visit_unknown_dimension); + mtd!(Url, visit_url); + mtd!(UrlValue, visit_url_value); + mtd!(UrlValueRaw, visit_url_value_raw); + mtd!(UrlModifier, visit_url_modifier); + mtd!(Value, visit_value); mtd!(CharsetRule, visit_charset_rule); + mtd!(DocumentRule, visit_document_rule); + mtd!( DocumentRuleMatchingFunction, visit_document_rule_matching_function ); + mtd!(FontFaceRule, visit_font_face_rule); + mtd!(ImportRule, visit_import_rule); + mtd!(ImportHref, visit_import_href); + mtd!(ImportLayerName, visit_import_layer_name); + mtd!(ImportSupportsType, visit_import_supports_type); + mtd!(KeyframesRule, visit_keyframes_rule); + mtd!(KeyframeBlock, visit_keyframe_block); + mtd!(KeyframeSelector, visit_keyframe_selector); + mtd!(LayerName, visit_layer_name); + mtd!(LayerNameList, visit_layer_name_list); + mtd!(LayerPrelude, visit_layer_prelude); + mtd!(LayerRule, visit_layer_rule); + mtd!(MediaRule, visit_media_rule); + mtd!(MediaQueryList, visit_media_query_list); + mtd!(MediaQuery, visit_media_query); + mtd!(MediaCondition, visit_media_condition); + mtd!(MediaConditionWithoutOr, visit_media_condition_without_or); + mtd!(MediaConditionAllType, visit_media_condition_all_type); + mtd!( MediaConditionWithoutOrType, visit_media_condition_without_or_type ); + mtd!(MediaNot, visit_media_not); + mtd!(MediaAnd, visit_media_and); + mtd!(MediaOr, visit_media_or); + mtd!(MediaInParens, visit_media_in_parens); + mtd!(MediaFeatureName, visit_media_feature_name); + mtd!(MediaFeatureValue, visit_media_feature_value); + mtd!(MediaFeature, visit_media_feature); + mtd!(MediaFeaturePlain, visit_media_feature_plain); + mtd!(MediaFeatureBoolean, visit_media_feature_boolean); + mtd!(MediaFeatureRange, visit_media_feature_range); + mtd!( MediaFeatureRangeInterval, visit_media_feature_range_interval ); + mtd!(SupportsRule, visit_supports_rule); + mtd!(SupportsCondition, visit_supports_condition); + mtd!(SupportsConditionType, visit_supports_condition_type); + mtd!(SupportsNot, visit_supports_not); + mtd!(SupportsAnd, visit_supports_and); + mtd!(SupportsOr, visit_supports_or); + mtd!(SupportsInParens, visit_supports_in_parens); + mtd!(SupportsFeature, visit_supports_feature); + mtd!(NamespaceUri, visit_namespace_uri); + mtd!(NamespaceRule, visit_namespace_rule); + mtd!(PageRule, visit_page_rule); + mtd!(PageSelectorList, visit_page_selector_list); + mtd!(PageSelector, visit_page_selector); + mtd!(PageSelectorType, visit_page_selector_type); + mtd!(PageSelectorPseudo, visit_page_selector_pseudo); + mtd!(AtRuleName, visit_at_rule_name); + mtd!(PageMarginRule, visit_page_margin_rule); + mtd!(UnknownAtRule, visit_unknown_at_rule); + mtd!(ViewportRule, visit_viewport_rule); + mtd!(ColorProfileName, visit_color_profile_name); + mtd!(ColorProfileRule, visit_color_profile_rule); + mtd!(CounterStyleRule, visit_counter_style_rule); + mtd!(PropertyRule, visit_property_rule); fn visit_token_and_span(&mut self, n: &TokenAndSpan) { diff --git a/crates/swc_ecma_ast/src/class.rs b/crates/swc_ecma_ast/src/class.rs index ca070c6ed70..6f6d9158dbd 100644 --- a/crates/swc_ecma_ast/src/class.rs +++ b/crates/swc_ecma_ast/src/class.rs @@ -1,3 +1,7 @@ +use is_macro::Is; +use serde::{Deserialize, Serialize}; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ expr::Expr, function::{Function, ParamOrTsParamProp}, @@ -10,9 +14,6 @@ use crate::{ }, EmptyStmt, }; -use is_macro::Is; -use serde::{Deserialize, Serialize}; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; #[ast_node] #[derive(Eq, Hash, EqIgnoreSpan)] diff --git a/crates/swc_ecma_ast/src/decl.rs b/crates/swc_ecma_ast/src/decl.rs index 06c0b55af56..c6fd2ba7bec 100644 --- a/crates/swc_ecma_ast/src/decl.rs +++ b/crates/swc_ecma_ast/src/decl.rs @@ -1,3 +1,7 @@ +use is_macro::Is; +use string_enum::StringEnum; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ class::Class, expr::Expr, @@ -6,9 +10,6 @@ use crate::{ pat::Pat, typescript::{TsEnumDecl, TsInterfaceDecl, TsModuleDecl, TsTypeAliasDecl}, }; -use is_macro::Is; -use string_enum::StringEnum; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] diff --git a/crates/swc_ecma_ast/src/expr.rs b/crates/swc_ecma_ast/src/expr.rs index 92623a10251..9c2e3fd55c6 100644 --- a/crates/swc_ecma_ast/src/expr.rs +++ b/crates/swc_ecma_ast/src/expr.rs @@ -1,4 +1,9 @@ #![allow(clippy::vec_box)] +use is_macro::Is; +use serde::{self, Deserialize, Serialize}; +use string_enum::StringEnum; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, Spanned, DUMMY_SP}; + use crate::{ class::Class, function::Function, @@ -15,10 +20,6 @@ use crate::{ }, ComputedPropName, Invalid, }; -use is_macro::Is; -use serde::{self, Deserialize, Serialize}; -use string_enum::StringEnum; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, Spanned, DUMMY_SP}; #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] diff --git a/crates/swc_ecma_ast/src/function.rs b/crates/swc_ecma_ast/src/function.rs index dcfd1bebcc2..6ece40fee16 100644 --- a/crates/swc_ecma_ast/src/function.rs +++ b/crates/swc_ecma_ast/src/function.rs @@ -1,11 +1,12 @@ +use is_macro::Is; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ class::Decorator, pat::Pat, stmt::BlockStmt, typescript::{TsParamProp, TsTypeAnn, TsTypeParamDecl}, }; -use is_macro::Is; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; /// Common parts of function and method. #[ast_node] diff --git a/crates/swc_ecma_ast/src/ident.rs b/crates/swc_ecma_ast/src/ident.rs index 80f9fdb2b93..8f5cfc12884 100644 --- a/crates/swc_ecma_ast/src/ident.rs +++ b/crates/swc_ecma_ast/src/ident.rs @@ -1,12 +1,14 @@ -use crate::typescript::TsTypeAnn; -use serde::{Deserialize, Serialize}; use std::fmt::Display; + +use serde::{Deserialize, Serialize}; use swc_atoms::{js_word, JsWord}; use swc_common::{ ast_node, util::take::Take, EqIgnoreSpan, Span, Spanned, SyntaxContext, DUMMY_SP, }; use unicode_xid::UnicodeXID; +use crate::typescript::TsTypeAnn; + /// Identifier used as a pattern. #[derive(Spanned, Clone, Debug, PartialEq, Eq, Hash, EqIgnoreSpan, Serialize, Deserialize)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] diff --git a/crates/swc_ecma_ast/src/jsx.rs b/crates/swc_ecma_ast/src/jsx.rs index 76ee8b1c66a..73766596546 100644 --- a/crates/swc_ecma_ast/src/jsx.rs +++ b/crates/swc_ecma_ast/src/jsx.rs @@ -1,12 +1,13 @@ +use is_macro::Is; +use swc_atoms::JsWord; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ expr::{Expr, SpreadElement}, ident::Ident, lit::Lit, typescript::TsTypeParamInstantiation, }; -use is_macro::Is; -use swc_atoms::JsWord; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; /// Used for `obj` property of `JSXMemberExpr`. #[ast_node] diff --git a/crates/swc_ecma_ast/src/lib.rs b/crates/swc_ecma_ast/src/lib.rs index fe6d0e6e748..5d5240d7234 100644 --- a/crates/swc_ecma_ast/src/lib.rs +++ b/crates/swc_ecma_ast/src/lib.rs @@ -9,6 +9,9 @@ // #![deny(variant_size_differences)] +use serde::{Deserialize, Serialize}; +use swc_common::{ast_node, EqIgnoreSpan, Span}; + pub use self::{ class::{ Class, ClassMember, ClassMethod, ClassProp, Constructor, Decorator, MethodKind, @@ -68,8 +71,6 @@ pub use self::{ TsTypeQuery, TsTypeQueryExpr, TsTypeRef, TsUnionOrIntersectionType, TsUnionType, }, }; -use serde::{Deserialize, Serialize}; -use swc_common::{ast_node, EqIgnoreSpan, Span}; #[macro_use] mod macros; @@ -141,7 +142,6 @@ pub struct EncodeJsWord; #[cfg(feature = "rkyv")] impl rkyv::with::ArchiveWith for EncodeJsWord { type Archived = rkyv::Archived; - type Resolver = rkyv::Resolver; unsafe fn resolve_with( @@ -190,7 +190,6 @@ where #[cfg(feature = "rkyv")] impl rkyv::with::ArchiveWith> for EncodeJsWord { type Archived = rkyv::Archived>; - type Resolver = rkyv::Resolver>; unsafe fn resolve_with( diff --git a/crates/swc_ecma_ast/src/lit.rs b/crates/swc_ecma_ast/src/lit.rs index f5cb8cea2f3..288f4332d90 100644 --- a/crates/swc_ecma_ast/src/lit.rs +++ b/crates/swc_ecma_ast/src/lit.rs @@ -1,15 +1,17 @@ -use crate::jsx::JSXText; -use num_bigint::BigInt as BigIntValue; -use serde::{Deserialize, Serialize}; use std::{ borrow::Cow, fmt::{self, Display, Formatter}, hash::{Hash, Hasher}, mem, }; + +use num_bigint::BigInt as BigIntValue; +use serde::{Deserialize, Serialize}; use swc_atoms::{js_word, JsWord}; use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; +use crate::jsx::JSXText; + #[ast_node] #[derive(Eq, Hash, EqIgnoreSpan)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] @@ -75,7 +77,6 @@ pub struct EncodeBigInt; #[cfg(feature = "rkyv")] impl rkyv::with::ArchiveWith for EncodeBigInt { type Archived = rkyv::Archived; - type Resolver = rkyv::Resolver; unsafe fn resolve_with( diff --git a/crates/swc_ecma_ast/src/module.rs b/crates/swc_ecma_ast/src/module.rs index 2d2ad8a0489..4bc570f110a 100644 --- a/crates/swc_ecma_ast/src/module.rs +++ b/crates/swc_ecma_ast/src/module.rs @@ -1,8 +1,9 @@ -use crate::{module_decl::ModuleDecl, stmt::Stmt}; use is_macro::Is; use swc_atoms::JsWord; use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; +use crate::{module_decl::ModuleDecl, stmt::Stmt}; + #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] diff --git a/crates/swc_ecma_ast/src/module_decl.rs b/crates/swc_ecma_ast/src/module_decl.rs index 5fe93036803..565fa61c9f2 100644 --- a/crates/swc_ecma_ast/src/module_decl.rs +++ b/crates/swc_ecma_ast/src/module_decl.rs @@ -1,3 +1,6 @@ +use is_macro::Is; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ decl::Decl, expr::{ClassExpr, Expr, FnExpr}, @@ -6,8 +9,6 @@ use crate::{ typescript::{TsExportAssignment, TsImportEqualsDecl, TsInterfaceDecl, TsNamespaceExportDecl}, ObjectLit, }; -use is_macro::Is; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] diff --git a/crates/swc_ecma_ast/src/pat.rs b/crates/swc_ecma_ast/src/pat.rs index 9ed42972ffd..dc6096e9689 100644 --- a/crates/swc_ecma_ast/src/pat.rs +++ b/crates/swc_ecma_ast/src/pat.rs @@ -1,3 +1,6 @@ +use is_macro::Is; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ expr::Expr, ident::{BindingIdent, Ident}, @@ -5,8 +8,6 @@ use crate::{ typescript::TsTypeAnn, Invalid, }; -use is_macro::Is; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] diff --git a/crates/swc_ecma_ast/src/prop.rs b/crates/swc_ecma_ast/src/prop.rs index a4a03d8ef3b..b5537f1e81f 100644 --- a/crates/swc_ecma_ast/src/prop.rs +++ b/crates/swc_ecma_ast/src/prop.rs @@ -1,3 +1,6 @@ +use is_macro::Is; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span}; + use crate::{ expr::Expr, function::Function, @@ -7,8 +10,6 @@ use crate::{ stmt::BlockStmt, typescript::TsTypeAnn, }; -use is_macro::Is; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span}; #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] diff --git a/crates/swc_ecma_ast/src/stmt.rs b/crates/swc_ecma_ast/src/stmt.rs index 1743286f891..afd1530ed7e 100644 --- a/crates/swc_ecma_ast/src/stmt.rs +++ b/crates/swc_ecma_ast/src/stmt.rs @@ -1,11 +1,12 @@ +use is_macro::Is; +use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; + use crate::{ decl::{Decl, VarDecl}, expr::Expr, ident::Ident, pat::Pat, }; -use is_macro::Is; -use swc_common::{ast_node, util::take::Take, EqIgnoreSpan, Span, DUMMY_SP}; /// Use when only block statements are allowed. #[ast_node("BlockStatement")] diff --git a/crates/swc_ecma_ast/src/typescript.rs b/crates/swc_ecma_ast/src/typescript.rs index 65046575419..9bde8910eac 100644 --- a/crates/swc_ecma_ast/src/typescript.rs +++ b/crates/swc_ecma_ast/src/typescript.rs @@ -1,5 +1,15 @@ #![allow(clippy::vec_box)] #![allow(missing_copy_implementations)] +use std::fmt; + +use is_macro::Is; +use serde::{ + de::{self, Unexpected, Visitor}, + Deserialize, Deserializer, Serialize, +}; +use string_enum::StringEnum; +use swc_common::{ast_node, EqIgnoreSpan, Span}; + use crate::{ class::Decorator, expr::Expr, @@ -9,14 +19,6 @@ use crate::{ pat::{ArrayPat, AssignPat, ObjectPat, Pat, RestPat}, BigInt, BindingIdent, TplElement, }; -use is_macro::Is; -use serde::{ - de::{self, Unexpected, Visitor}, - Deserialize, Deserializer, Serialize, -}; -use std::fmt; -use string_enum::StringEnum; -use swc_common::{ast_node, EqIgnoreSpan, Span}; #[ast_node("TsTypeAnnotation")] #[derive(Eq, Hash, EqIgnoreSpan)] @@ -686,6 +688,7 @@ impl<'de> Deserialize<'de> for TruePlusMinus { impl<'de> Visitor<'de> for TruePlusMinusVisitor { type Value = TruePlusMinus; + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("one of '+', '-', true") } diff --git a/crates/swc_ecma_codegen/benches/bench.rs b/crates/swc_ecma_codegen/benches/bench.rs index 432f13211d0..79fc40651ec 100644 --- a/crates/swc_ecma_codegen/benches/bench.rs +++ b/crates/swc_ecma_codegen/benches/bench.rs @@ -5,6 +5,7 @@ extern crate swc_node_base; extern crate test; use std::hint::black_box; + use swc_common::FileName; use swc_ecma_codegen::{self, Emitter}; use swc_ecma_parser::{Parser, StringInput, Syntax}; diff --git a/crates/swc_ecma_codegen/benches/with_parse.rs b/crates/swc_ecma_codegen/benches/with_parse.rs index 8d834047ef8..886109a40ad 100644 --- a/crates/swc_ecma_codegen/benches/with_parse.rs +++ b/crates/swc_ecma_codegen/benches/with_parse.rs @@ -4,6 +4,7 @@ extern crate test; use std::hint::black_box; + use swc_common::FileName; use swc_ecma_codegen::{self, Emitter}; use swc_ecma_parser::{Parser, StringInput, Syntax}; diff --git a/crates/swc_ecma_codegen/examples/gen.rs b/crates/swc_ecma_codegen/examples/gen.rs index a9534e887a2..75a0b92b775 100644 --- a/crates/swc_ecma_codegen/examples/gen.rs +++ b/crates/swc_ecma_codegen/examples/gen.rs @@ -2,6 +2,7 @@ extern crate swc_node_base; use std::{env, fs, path::Path, time::Instant}; + use swc_common::input::SourceFileInput; use swc_ecma_ast::*; use swc_ecma_codegen::{text_writer::JsWriter, Emitter}; diff --git a/crates/swc_ecma_codegen/src/comments.rs b/crates/swc_ecma_codegen/src/comments.rs index 2388cbb6843..ae11006f8ef 100644 --- a/crates/swc_ecma_codegen/src/comments.rs +++ b/crates/swc_ecma_codegen/src/comments.rs @@ -1,6 +1,7 @@ -use super::*; use swc_common::comments::CommentKind; +use super::*; + macro_rules! write_comments { ($e:expr, $prefix_space:expr, $cmts:expr) => {{ let cmts = match $cmts { diff --git a/crates/swc_ecma_codegen/src/decl.rs b/crates/swc_ecma_codegen/src/decl.rs index 6895f90fd45..76c0de7e76a 100644 --- a/crates/swc_ecma_codegen/src/decl.rs +++ b/crates/swc_ecma_codegen/src/decl.rs @@ -1,9 +1,10 @@ -use super::{list::ListFormat, Emitter, Result}; -use crate::text_writer::WriteJs; use swc_common::Spanned; use swc_ecma_ast::*; use swc_ecma_codegen_macros::emitter; +use super::{list::ListFormat, Emitter, Result}; +use crate::text_writer::WriteJs; + impl<'a, W> Emitter<'a, W> where W: WriteJs, diff --git a/crates/swc_ecma_codegen/src/jsx.rs b/crates/swc_ecma_codegen/src/jsx.rs index 60f7a6b327f..60ae148c31c 100644 --- a/crates/swc_ecma_codegen/src/jsx.rs +++ b/crates/swc_ecma_codegen/src/jsx.rs @@ -1,9 +1,10 @@ -use super::{Emitter, Result}; -use crate::{list::ListFormat, text_writer::WriteJs}; use swc_common::Spanned; use swc_ecma_ast::*; use swc_ecma_codegen_macros::emitter; +use super::{Emitter, Result}; +use crate::{list::ListFormat, text_writer::WriteJs}; + impl<'a, W> Emitter<'a, W> where W: WriteJs, diff --git a/crates/swc_ecma_codegen/src/lib.rs b/crates/swc_ecma_codegen/src/lib.rs index 49a86916819..8af61531762 100644 --- a/crates/swc_ecma_codegen/src/lib.rs +++ b/crates/swc_ecma_codegen/src/lib.rs @@ -3,6 +3,15 @@ #![allow(clippy::nonminimal_bool)] #![allow(unused_variables)] +use std::{borrow::Cow, fmt::Write, io}; + +use memchr::memmem::Finder; +use once_cell::sync::Lazy; +use swc_atoms::JsWord; +use swc_common::{comments::Comments, sync::Lrc, BytePos, SourceMap, Span, Spanned, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_codegen_macros::emitter; + pub use self::config::Config; use self::{ list::ListFormat, @@ -10,13 +19,6 @@ use self::{ util::{SourceMapperExt, SpanExt, StartsWithAlphaNum}, }; use crate::util::EndsWithAlphaNum; -use memchr::memmem::Finder; -use once_cell::sync::Lazy; -use std::{borrow::Cow, fmt::Write, io}; -use swc_atoms::JsWord; -use swc_common::{comments::Comments, sync::Lrc, BytePos, SourceMap, Span, Spanned, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_codegen_macros::emitter; #[macro_use] pub mod macros; @@ -583,6 +585,7 @@ where Callee::Import(ref n) => emit!(n), } } + #[emitter] fn emit_super(&mut self, node: &Super) -> Result { keyword!(node.span, "super"); diff --git a/crates/swc_ecma_codegen/src/list.rs b/crates/swc_ecma_codegen/src/list.rs index 4e4d357d28e..f04eac5b470 100644 --- a/crates/swc_ecma_codegen/src/list.rs +++ b/crates/swc_ecma_codegen/src/list.rs @@ -184,6 +184,7 @@ impl ListFormat { _ => unreachable!(), } } + pub fn closing_bracket(self) -> &'static str { match self & ListFormat::BracketsMask { ListFormat::Braces => "}", diff --git a/crates/swc_ecma_codegen/src/tests.rs b/crates/swc_ecma_codegen/src/tests.rs index 061ef2aecd1..8f3743ba496 100644 --- a/crates/swc_ecma_codegen/src/tests.rs +++ b/crates/swc_ecma_codegen/src/tests.rs @@ -1,15 +1,17 @@ -use self::swc_ecma_parser::{EsConfig, Parser, StringInput, Syntax}; -use super::*; -use crate::{config::Config, text_writer::omit_trailing_semi}; use std::{ fmt::Debug, io::Write, sync::{Arc, RwLock}, }; + use swc_common::{comments::SingleThreadedComments, FileName, SourceMap}; use swc_ecma_parser; use testing::DebugUsingDisplay; +use self::swc_ecma_parser::{EsConfig, Parser, StringInput, Syntax}; +use super::*; +use crate::{config::Config, text_writer::omit_trailing_semi}; + struct Builder { cfg: Config, cm: Lrc, diff --git a/crates/swc_ecma_codegen/src/text_writer.rs b/crates/swc_ecma_codegen/src/text_writer.rs index e0557aeb1a3..00e1ccf1652 100644 --- a/crates/swc_ecma_codegen/src/text_writer.rs +++ b/crates/swc_ecma_codegen/src/text_writer.rs @@ -1,6 +1,7 @@ +use swc_common::Span; + pub use self::{basic_impl::JsWriter, semicolon::omit_trailing_semi}; use super::*; -use swc_common::Span; mod basic_impl; mod semicolon; diff --git a/crates/swc_ecma_codegen/src/text_writer/basic_impl.rs b/crates/swc_ecma_codegen/src/text_writer/basic_impl.rs index 12ac94b22f7..0036cbe2ae7 100644 --- a/crates/swc_ecma_codegen/src/text_writer/basic_impl.rs +++ b/crates/swc_ecma_codegen/src/text_writer/basic_impl.rs @@ -1,8 +1,10 @@ -use super::{Result, WriteJs}; use std::io::{self, Write}; + use swc_common::{sync::Lrc, BytePos, LineCol, SourceMap, Span}; use swc_ecma_ast::EsVersion; +use super::{Result, WriteJs}; + /// /// ----- /// @@ -110,6 +112,7 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> { fn target(&self) -> EsVersion { self.target } + fn increase_indent(&mut self) -> Result { self.indent += 1; Ok(()) @@ -119,6 +122,7 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> { self.indent -= 1; Ok(()) } + fn write_semi(&mut self, span: Option) -> Result { self.write(span, ";")?; Ok(()) diff --git a/crates/swc_ecma_codegen/src/text_writer/semicolon.rs b/crates/swc_ecma_codegen/src/text_writer/semicolon.rs index d75b2ed534c..231b63fdefd 100644 --- a/crates/swc_ecma_codegen/src/text_writer/semicolon.rs +++ b/crates/swc_ecma_codegen/src/text_writer/semicolon.rs @@ -1,6 +1,7 @@ -use super::{Result, WriteJs}; use swc_common::Span; +use super::{Result, WriteJs}; + pub fn omit_trailing_semi(w: W) -> impl WriteJs { OmitTrailingSemi { inner: w, @@ -35,25 +36,36 @@ macro_rules! with_semi { impl WriteJs for OmitTrailingSemi { with_semi!(increase_indent()); + with_semi!(decrease_indent()); + with_semi!(write_space()); + + with_semi!(write_comment(span: Span, s: &str)); + + with_semi!(write_keyword(span: Option, s: &'static str)); + + with_semi!(write_operator(span: Option, s: &str)); + + with_semi!(write_param(s: &str)); + + with_semi!(write_property(s: &str)); + + with_semi!(write_line()); + + with_semi!(write_lit(span: Span, s: &str)); + + with_semi!(write_str_lit(span: Span, s: &str)); + + with_semi!(write_str(s: &str)); + + with_semi!(write_symbol(span: Span, s: &str)); + fn write_semi(&mut self, _: Option) -> Result { self.pending_semi = true; Ok(()) } - with_semi!(write_space()); - with_semi!(write_comment(span: Span, s: &str)); - with_semi!(write_keyword(span: Option, s: &'static str)); - with_semi!(write_operator(span: Option, s: &str)); - with_semi!(write_param(s: &str)); - with_semi!(write_property(s: &str)); - with_semi!(write_line()); - with_semi!(write_lit(span: Span, s: &str)); - with_semi!(write_str_lit(span: Span, s: &str)); - with_semi!(write_str(s: &str)); - with_semi!(write_symbol(span: Span, s: &str)); - fn write_punct(&mut self, span: Option, s: &'static str) -> Result { match s { "\"" | "'" | "[" | "!" | "/" | "{" | "(" | "~" | "-" | "+" | "#" => { diff --git a/crates/swc_ecma_codegen/src/typescript.rs b/crates/swc_ecma_codegen/src/typescript.rs index 4168f0bb569..5554f95bf5f 100644 --- a/crates/swc_ecma_codegen/src/typescript.rs +++ b/crates/swc_ecma_codegen/src/typescript.rs @@ -1,9 +1,10 @@ -use super::{Emitter, Result}; -use crate::{list::ListFormat, text_writer::WriteJs}; use swc_common::Spanned; use swc_ecma_ast::*; use swc_ecma_codegen_macros::emitter; +use super::{Emitter, Result}; +use crate::{list::ListFormat, text_writer::WriteJs}; + impl<'a, W> Emitter<'a, W> where W: WriteJs, diff --git a/crates/swc_ecma_codegen/src/util.rs b/crates/swc_ecma_codegen/src/util.rs index 9b4d4bff493..0d26d672b42 100644 --- a/crates/swc_ecma_codegen/src/util.rs +++ b/crates/swc_ecma_codegen/src/util.rs @@ -1,8 +1,10 @@ -use super::list::ListFormat; use std::{rc::Rc, sync::Arc}; + use swc_common::{errors::SourceMapper, BytePos, SourceMap, SourceMapperDyn, Span, Spanned}; use swc_ecma_ast::*; +use super::list::ListFormat; + pub trait SpanExt: Spanned { #[inline] fn is_synthesized(&self) -> bool { diff --git a/crates/swc_ecma_codegen/tests/fixture.rs b/crates/swc_ecma_codegen/tests/fixture.rs index 51cc0f49a81..2acab339046 100644 --- a/crates/swc_ecma_codegen/tests/fixture.rs +++ b/crates/swc_ecma_codegen/tests/fixture.rs @@ -1,4 +1,5 @@ use std::path::{Path, PathBuf}; + use swc_common::input::SourceFileInput; use swc_ecma_ast::EsVersion; use swc_ecma_codegen::{ diff --git a/crates/swc_ecma_codegen/tests/test262.rs b/crates/swc_ecma_codegen/tests/test262.rs index 8a0a23b3d94..a2d6cd26272 100644 --- a/crates/swc_ecma_codegen/tests/test262.rs +++ b/crates/swc_ecma_codegen/tests/test262.rs @@ -7,6 +7,7 @@ use std::{ path::{Path, PathBuf}, sync::{Arc, RwLock}, }; + use swc_common::comments::SingleThreadedComments; use swc_ecma_codegen::{self, text_writer::WriteJs, Emitter}; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax}; diff --git a/crates/swc_ecma_dep_graph/src/lib.rs b/crates/swc_ecma_dep_graph/src/lib.rs index 7bbe486a91b..8f1cc068994 100644 --- a/crates/swc_ecma_dep_graph/src/lib.rs +++ b/crates/swc_ecma_dep_graph/src/lib.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; + use swc_atoms::{js_word, JsWord}; use swc_common::{ comments::{Comment, Comments}, @@ -335,7 +336,6 @@ fn parse_dynamic_import_assertions(arg: Option<&ast::ExprOrSpread>) -> ImportAss #[cfg(test)] mod tests { - use super::*; use ast::EsVersion; use pretty_assertions::assert_eq; use swc_common::{ @@ -344,6 +344,8 @@ mod tests { }; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig}; + use super::*; + fn helper( file_name: &str, source: &str, diff --git a/crates/swc_ecma_ext_transforms/src/jest.rs b/crates/swc_ecma_ext_transforms/src/jest.rs index 1d68c4aedb7..66af9e62bb8 100644 --- a/crates/swc_ecma_ext_transforms/src/jest.rs +++ b/crates/swc_ecma_ext_transforms/src/jest.rs @@ -72,11 +72,11 @@ impl Jest { impl VisitMut for Jest { noop_visit_mut_type!(); - fn visit_mut_stmts(&mut self, stmts: &mut Vec) { - self.visit_mut_stmt_like(stmts) - } - fn visit_mut_module_items(&mut self, items: &mut Vec) { self.visit_mut_stmt_like(items) } + + fn visit_mut_stmts(&mut self, stmts: &mut Vec) { + self.visit_mut_stmt_like(stmts) + } } diff --git a/crates/swc_ecma_lints/src/config.rs b/crates/swc_ecma_lints/src/config.rs index c1ce41b4324..de7ca04eebd 100644 --- a/crates/swc_ecma_lints/src/config.rs +++ b/crates/swc_ecma_lints/src/config.rs @@ -1,11 +1,13 @@ +use std::fmt::Debug; + +use serde::{Deserialize, Serialize}; + #[cfg(feature = "non_critical_lints")] use crate::rules::non_critical_lints::no_console::NoConsoleConfig; #[cfg(feature = "non_critical_lints")] use crate::rules::non_critical_lints::prefer_regex_literals::PreferRegexLiteralsConfig; #[cfg(feature = "non_critical_lints")] use crate::rules::non_critical_lints::quotes::QuotesConfig; -use serde::{Deserialize, Serialize}; -use std::fmt::Debug; #[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/swc_ecma_lints/src/rule.rs b/crates/swc_ecma_lints/src/rule.rs index 614b983c019..fabefbe1d5d 100644 --- a/crates/swc_ecma_lints/src/rule.rs +++ b/crates/swc_ecma_lints/src/rule.rs @@ -1,7 +1,8 @@ +use std::{fmt::Debug, sync::Arc}; + use auto_impl::auto_impl; use parking_lot::Mutex; use rayon::prelude::*; -use std::{fmt::Debug, sync::Arc}; use swc_common::errors::{Diagnostic, DiagnosticBuilder, Emitter, Handler, HANDLER}; use swc_ecma_ast::{Module, Script}; use swc_ecma_visit::{Visit, VisitWith}; diff --git a/crates/swc_ecma_lints/src/rules/const_assign.rs b/crates/swc_ecma_lints/src/rules/const_assign.rs index 7ed22e3abc0..f1d8632614f 100644 --- a/crates/swc_ecma_lints/src/rules/const_assign.rs +++ b/crates/swc_ecma_lints/src/rules/const_assign.rs @@ -1,9 +1,10 @@ -use crate::rule::{visitor_rule, Rule}; use swc_common::{collections::AHashMap, errors::HANDLER, Span}; use swc_ecma_ast::*; use swc_ecma_utils::ident::IdentLike; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use crate::rule::{visitor_rule, Rule}; + pub fn const_assign() -> Box { visitor_rule(ConstAssign::default()) } diff --git a/crates/swc_ecma_lints/src/rules/duplicate_bindings.rs b/crates/swc_ecma_lints/src/rules/duplicate_bindings.rs index 4c215ab4b46..a6e1b42b43e 100644 --- a/crates/swc_ecma_lints/src/rules/duplicate_bindings.rs +++ b/crates/swc_ecma_lints/src/rules/duplicate_bindings.rs @@ -1,4 +1,5 @@ use std::collections::hash_map::Entry; + use swc_common::{collections::AHashMap, errors::HANDLER, Span}; use swc_ecma_ast::*; use swc_ecma_utils::ident::IdentLike; diff --git a/crates/swc_ecma_lints/src/rules/duplicate_exports.rs b/crates/swc_ecma_lints/src/rules/duplicate_exports.rs index 9b8a8e1af49..aa090c32d45 100644 --- a/crates/swc_ecma_lints/src/rules/duplicate_exports.rs +++ b/crates/swc_ecma_lints/src/rules/duplicate_exports.rs @@ -1,4 +1,5 @@ use std::collections::hash_map::Entry; + use swc_atoms::{js_word, JsWord}; use swc_common::{collections::AHashMap, errors::HANDLER, Span}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_lints/src/rules/mod.rs b/crates/swc_ecma_lints/src/rules/mod.rs index 2e1da9cbaec..0959737545e 100644 --- a/crates/swc_ecma_lints/src/rules/mod.rs +++ b/crates/swc_ecma_lints/src/rules/mod.rs @@ -1,9 +1,11 @@ -use crate::{config::LintConfig, rule::Rule}; use std::sync::Arc; + use swc_common::{SourceMap, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_fold_type, Fold}; +use crate::{config::LintConfig, rule::Rule}; + mod const_assign; mod duplicate_bindings; mod duplicate_exports; diff --git a/crates/swc_ecma_lints/src/rules/no_alert.rs b/crates/swc_ecma_lints/src/rules/no_alert.rs index 703a7042630..e69a7297165 100644 --- a/crates/swc_ecma_lints/src/rules/no_alert.rs +++ b/crates/swc_ecma_lints/src/rules/no_alert.rs @@ -1,13 +1,14 @@ -use crate::{ - config::{LintRuleReaction, RuleConfig}, - rule::{visitor_rule, Rule}, -}; use swc_atoms::JsWord; use swc_common::{collections::AHashSet, errors::HANDLER, Span, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_utils::{collect_decls_with_ctxt, ident::IdentLike}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use crate::{ + config::{LintRuleReaction, RuleConfig}, + rule::{visitor_rule, Rule}, +}; + const FN_NAMES: &[&str] = &["alert", "confirm", "prompt"]; const GLOBAL_THIS_PROP: &str = "globalThis"; const OBJ_NAMES: &[&str] = &["window", GLOBAL_THIS_PROP]; diff --git a/crates/swc_ecma_lints/src/rules/no_console.rs b/crates/swc_ecma_lints/src/rules/no_console.rs index 6ffaf4a973d..3d3d2630e31 100644 --- a/crates/swc_ecma_lints/src/rules/no_console.rs +++ b/crates/swc_ecma_lints/src/rules/no_console.rs @@ -1,12 +1,13 @@ -use crate::{ - config::{LintRuleReaction, RuleConfig}, - rule::{visitor_rule, Rule}, -}; use serde::{Deserialize, Serialize}; use swc_common::{collections::AHashSet, errors::HANDLER, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_type, Visit}; +use crate::{ + config::{LintRuleReaction, RuleConfig}, + rule::{visitor_rule, Rule}, +}; + const MESSAGE: &str = "Unexpected console statement"; #[derive(Debug, Default, Clone, Serialize, Deserialize)] diff --git a/crates/swc_ecma_lints/src/rules/no_debugger.rs b/crates/swc_ecma_lints/src/rules/no_debugger.rs index 320dd531758..33c60d741e5 100644 --- a/crates/swc_ecma_lints/src/rules/no_debugger.rs +++ b/crates/swc_ecma_lints/src/rules/no_debugger.rs @@ -1,10 +1,11 @@ +use swc_common::{errors::HANDLER, Span}; +use swc_ecma_ast::*; +use swc_ecma_visit::{noop_visit_type, Visit}; + use crate::{ config::{LintRuleReaction, RuleConfig}, rule::{visitor_rule, Rule}, }; -use swc_common::{errors::HANDLER, Span}; -use swc_ecma_ast::*; -use swc_ecma_visit::{noop_visit_type, Visit}; const MESSAGE: &str = "Unexpected 'debugger' statement"; diff --git a/crates/swc_ecma_lints/src/rules/prefer_regex_literals.rs b/crates/swc_ecma_lints/src/rules/prefer_regex_literals.rs index f316892c823..81dea07ca42 100644 --- a/crates/swc_ecma_lints/src/rules/prefer_regex_literals.rs +++ b/crates/swc_ecma_lints/src/rules/prefer_regex_literals.rs @@ -1,13 +1,14 @@ -use crate::{ - config::{LintRuleReaction, RuleConfig}, - rule::{visitor_rule, Rule}, -}; use serde::{Deserialize, Serialize}; use swc_common::{collections::AHashSet, errors::HANDLER, Span, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_utils::{collect_decls_with_ctxt, ident::IdentLike}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use crate::{ + config::{LintRuleReaction, RuleConfig}, + rule::{visitor_rule, Rule}, +}; + const UNEXPECTED_REG_EXP_MESSAGE: &str = "Use a regular expression literal instead of the 'RegExp' constructor"; const UNEXPECTED_REDUNDANT_REG_EXP_MESSAGE: &str = diff --git a/crates/swc_ecma_lints/src/rules/quotes.rs b/crates/swc_ecma_lints/src/rules/quotes.rs index 42ae9c8333e..5fb9000f38d 100644 --- a/crates/swc_ecma_lints/src/rules/quotes.rs +++ b/crates/swc_ecma_lints/src/rules/quotes.rs @@ -1,16 +1,18 @@ -use crate::{ - config::{LintRuleReaction, RuleConfig}, - rule::{visitor_rule, Rule}, -}; -use serde::{Deserialize, Serialize}; use std::{ fmt::{self, Debug}, sync::Arc, }; + +use serde::{Deserialize, Serialize}; use swc_common::{errors::HANDLER, SourceMap, Span}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_type, Visit}; +use crate::{ + config::{LintRuleReaction, RuleConfig}, + rule::{visitor_rule, Rule}, +}; + const MUST_USE_SINGLE_QUOTES_MESSAGE: &str = "String must use singlequotes"; const MUST_USE_DOUBLE_QUOTES_MESSAGE: &str = "String must use doublequotes"; const MUST_USE_BACKTICK_QUOTES_MESSAGE: &str = "String must use backtick quotes"; diff --git a/crates/swc_ecma_loader/src/resolve.rs b/crates/swc_ecma_loader/src/resolve.rs index 3c99f6eb320..d427e678862 100644 --- a/crates/swc_ecma_loader/src/resolve.rs +++ b/crates/swc_ecma_loader/src/resolve.rs @@ -1,5 +1,6 @@ -use anyhow::Error; use std::sync::Arc; + +use anyhow::Error; use swc_common::{ sync::{Send, Sync}, FileName, diff --git a/crates/swc_ecma_loader/src/resolvers/lru.rs b/crates/swc_ecma_loader/src/resolvers/lru.rs index df7720140b8..4cf707bb1fe 100644 --- a/crates/swc_ecma_loader/src/resolvers/lru.rs +++ b/crates/swc_ecma_loader/src/resolvers/lru.rs @@ -1,9 +1,11 @@ -use crate::resolve::Resolve; +use std::sync::Mutex; + use anyhow::Error; use lru::LruCache; -use std::sync::Mutex; use swc_common::FileName; +use crate::resolve::Resolve; + #[derive(Debug)] pub struct CachingResolver where diff --git a/crates/swc_ecma_loader/src/resolvers/node.rs b/crates/swc_ecma_loader/src/resolvers/node.rs index b1661159c78..789b7e7e40e 100644 --- a/crates/swc_ecma_loader/src/resolvers/node.rs +++ b/crates/swc_ecma_loader/src/resolvers/node.rs @@ -2,7 +2,12 @@ //! //! See: https://github.com/goto-bus-stop/node-resolve -use crate::{resolve::Resolve, TargetEnv, NODE_BUILTINS}; +use std::{ + fs::File, + io::BufReader, + path::{Component, Path, PathBuf}, +}; + use anyhow::{bail, Context, Error}; use dashmap::{DashMap, DashSet}; #[cfg(windows)] @@ -10,14 +15,11 @@ use normpath::BasePath; use once_cell::sync::Lazy; use path_clean::PathClean; use serde::Deserialize; -use std::{ - fs::File, - io::BufReader, - path::{Component, Path, PathBuf}, -}; use swc_common::{collections::AHashMap, FileName}; use tracing::debug; +use crate::{resolve::Resolve, TargetEnv, NODE_BUILTINS}; + static PACKAGE: &str = "package.json"; /// Map of cached `browser` fields from deserialized package.json diff --git a/crates/swc_ecma_loader/src/resolvers/tsc.rs b/crates/swc_ecma_loader/src/resolvers/tsc.rs index 3f1cf098115..ff9c71fcb6d 100644 --- a/crates/swc_ecma_loader/src/resolvers/tsc.rs +++ b/crates/swc_ecma_loader/src/resolvers/tsc.rs @@ -1,11 +1,13 @@ -use crate::resolve::Resolve; +use std::path::{Component, PathBuf}; + use anyhow::{bail, Context, Error}; use dashmap::DashMap; use once_cell::sync::Lazy; use regex::Regex; -use std::path::{Component, PathBuf}; use swc_common::FileName; +use crate::resolve::Resolve; + #[derive(Debug)] enum Pattern { Regex(Regex), diff --git a/crates/swc_ecma_loader/tests/tsc_resolver.rs b/crates/swc_ecma_loader/tests/tsc_resolver.rs index 884a8b46ef7..220563e77e1 100644 --- a/crates/swc_ecma_loader/tests/tsc_resolver.rs +++ b/crates/swc_ecma_loader/tests/tsc_resolver.rs @@ -1,7 +1,8 @@ #![cfg(feature = "tsc")] -use anyhow::{anyhow, Error}; use std::collections::HashMap; + +use anyhow::{anyhow, Error}; use swc_common::{collections::AHashMap, FileName}; use swc_ecma_loader::{resolve::Resolve, resolvers::tsc::TsConfigResolver}; diff --git a/crates/swc_ecma_minifier/examples/minifier.rs b/crates/swc_ecma_minifier/examples/minifier.rs index 4aa328dd7ea..24f7e7e5c72 100644 --- a/crates/swc_ecma_minifier/examples/minifier.rs +++ b/crates/swc_ecma_minifier/examples/minifier.rs @@ -1,6 +1,7 @@ extern crate swc_node_base; use std::{env::args, fs, path::Path}; + use swc_common::{input::SourceFileInput, sync::Lrc, Mark, SourceMap}; use swc_ecma_codegen::text_writer::JsWriter; use swc_ecma_minifier::{ diff --git a/crates/swc_ecma_minifier/src/analyzer/ctx.rs b/crates/swc_ecma_minifier/src/analyzer/ctx.rs index 3009886b3cd..f60a0ef4bd3 100644 --- a/crates/swc_ecma_minifier/src/analyzer/ctx.rs +++ b/crates/swc_ecma_minifier/src/analyzer/ctx.rs @@ -1,9 +1,11 @@ #![allow(dead_code)] -use super::{storage::Storage, UsageAnalyzer}; use std::ops::{Deref, DerefMut}; + use swc_ecma_ast::VarDeclKind; +use super::{storage::Storage, UsageAnalyzer}; + impl UsageAnalyzer where S: Storage, diff --git a/crates/swc_ecma_minifier/src/analyzer/mod.rs b/crates/swc_ecma_minifier/src/analyzer/mod.rs index ad0afc20230..6eaca8caacd 100644 --- a/crates/swc_ecma_minifier/src/analyzer/mod.rs +++ b/crates/swc_ecma_minifier/src/analyzer/mod.rs @@ -1,11 +1,3 @@ -use self::{ - ctx::Ctx, - storage::{Storage, *}, -}; -use crate::{ - marks::Marks, - util::{can_end_conditionally, idents_used_by}, -}; use swc_atoms::{js_word, JsWord}; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -16,6 +8,15 @@ use swc_ecma_utils::{find_ids, ident::IdentLike, Id}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use swc_timer::timer; +use self::{ + ctx::Ctx, + storage::{Storage, *}, +}; +use crate::{ + marks::Marks, + util::{can_end_conditionally, idents_used_by}, +}; + mod ctx; pub(crate) mod storage; diff --git a/crates/swc_ecma_minifier/src/analyzer/storage/mod.rs b/crates/swc_ecma_minifier/src/analyzer/storage/mod.rs index f22ef83d3b4..4b8b6185567 100644 --- a/crates/swc_ecma_minifier/src/analyzer/storage/mod.rs +++ b/crates/swc_ecma_minifier/src/analyzer/storage/mod.rs @@ -1,9 +1,10 @@ -use super::{ctx::Ctx, ScopeKind}; use swc_atoms::JsWord; use swc_common::SyntaxContext; use swc_ecma_ast::*; use swc_ecma_utils::Id; +use super::{ctx::Ctx, ScopeKind}; + pub mod normal; pub(crate) trait Storage: Sized + Default { diff --git a/crates/swc_ecma_minifier/src/analyzer/storage/normal.rs b/crates/swc_ecma_minifier/src/analyzer/storage/normal.rs index 96ed0933905..9154018aa55 100644 --- a/crates/swc_ecma_minifier/src/analyzer/storage/normal.rs +++ b/crates/swc_ecma_minifier/src/analyzer/storage/normal.rs @@ -1,10 +1,12 @@ -use super::{ScopeDataLike, Storage, VarDataLike}; -use crate::analyzer::{ctx::Ctx, ProgramData, ScopeData, ScopeKind, VarUsageInfo}; use std::collections::hash_map::Entry; + use swc_common::collections::AHashSet; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; +use super::{ScopeDataLike, Storage, VarDataLike}; +use crate::analyzer::{ctx::Ctx, ProgramData, ScopeData, ScopeKind, VarUsageInfo}; + impl Storage for ProgramData { type ScopeData = ScopeData; type VarData = VarUsageInfo; diff --git a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs index 6b572b229f5..a24aad3f8a8 100644 --- a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs +++ b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs @@ -1,12 +1,13 @@ +use swc_common::{collections::AHashSet, pass::Repeated, util::take::Take, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{find_ids, ident::IdentLike, Id, StmtLike}; +use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; + use super::util::drop_invalid_stmts; use crate::{ analyzer::{ProgramData, UsageAnalyzer}, util::{is_hoisted_var_decl_without_init, sort::is_sorted_by_key, IsModuleItem, ModuleItemExt}, }; -use swc_common::{collections::AHashSet, pass::Repeated, util::take::Take, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{find_ids, ident::IdentLike, Id, StmtLike}; -use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; pub(super) struct DeclHoisterConfig { pub hoist_fns: bool, @@ -235,11 +236,11 @@ impl Hoister<'_> { impl VisitMut for Hoister<'_> { noop_visit_mut_type!(); - fn visit_mut_stmts(&mut self, stmts: &mut Vec) { - self.handle_stmt_likes(stmts); - } - fn visit_mut_module_items(&mut self, stmts: &mut Vec) { self.handle_stmt_likes(stmts); } + + fn visit_mut_stmts(&mut self, stmts: &mut Vec) { + self.handle_stmt_likes(stmts); + } } diff --git a/crates/swc_ecma_minifier/src/compress/mod.rs b/crates/swc_ecma_minifier/src/compress/mod.rs index f9813d490d9..c8a8778db2f 100644 --- a/crates/swc_ecma_minifier/src/compress/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/mod.rs @@ -1,18 +1,3 @@ -pub(crate) use self::pure::pure_optimizer; -use self::{hoist_decls::DeclHoisterConfig, optimize::optimizer}; -use crate::{ - analyzer::{analyze, UsageAnalyzer}, - compress::hoist_decls::decl_hoister, - debug::dump, - marks::Marks, - mode::Mode, - option::CompressOptions, - util::{now, unit::CompileUnit, Optional}, - DISABLE_BUGGY_PASSES, MAX_PAR_DEPTH, -}; -#[cfg(feature = "pretty_assertions")] -use pretty_assertions::assert_eq; -use rayon::prelude::*; use std::{ borrow::Cow, fmt, @@ -20,6 +5,10 @@ use std::{ thread, time::Instant, }; + +#[cfg(feature = "pretty_assertions")] +use pretty_assertions::assert_eq; +use rayon::prelude::*; use swc_common::{ chain, pass::{CompilerPass, Repeated}, @@ -35,6 +24,19 @@ use swc_ecma_visit::{as_folder, noop_visit_mut_type, VisitMut, VisitMutWith, Vis use swc_timer::timer; use tracing::error; +pub(crate) use self::pure::pure_optimizer; +use self::{hoist_decls::DeclHoisterConfig, optimize::optimizer}; +use crate::{ + analyzer::{analyze, UsageAnalyzer}, + compress::hoist_decls::decl_hoister, + debug::dump, + marks::Marks, + mode::Mode, + option::CompressOptions, + util::{now, unit::CompileUnit, Optional}, + DISABLE_BUGGY_PASSES, MAX_PAR_DEPTH, +}; + mod hoist_decls; mod optimize; mod pure; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs b/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs index eea81c288cb..b94f7492a2a 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs @@ -1,12 +1,14 @@ -use super::Optimizer; -use crate::{compress::optimize::is_left_access_to_arguments, mode::Mode}; use std::iter::repeat_with; + use swc_atoms::js_word; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{find_ids, ident::IdentLike, private_ident, Id}; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use super::Optimizer; +use crate::{compress::optimize::is_left_access_to_arguments, mode::Mode}; + /// Methods related to the option `arguments`. impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/bools.rs b/crates/swc_ecma_minifier/src/compress/optimize/bools.rs index 316355b2f2a..798fd06fc1a 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/bools.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/bools.rs @@ -1,13 +1,14 @@ +use swc_atoms::js_word; +use swc_common::{util::take::Take, Spanned}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ident::IdentLike, undefined, ExprExt, Type, Value::Known}; + use super::Optimizer; use crate::{ compress::{optimize::Ctx, util::negate_cost}, debug::dump, mode::Mode, }; -use swc_atoms::js_word; -use swc_common::{util::take::Take, Spanned}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ident::IdentLike, undefined, ExprExt, Type, Value::Known}; /// Methods related to the options `bools` and `bool_as_ints`. impl Optimizer<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/optimize/collapse_vars.rs b/crates/swc_ecma_minifier/src/compress/optimize/collapse_vars.rs index e80cec75493..fe9e945068d 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/collapse_vars.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/collapse_vars.rs @@ -1,8 +1,9 @@ -use super::Optimizer; -use crate::mode::Mode; use swc_ecma_ast::*; use swc_ecma_utils::ident::IdentLike; +use super::Optimizer; +use crate::mode::Mode; + /// Methods related to the option `collapse_vars`. impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs index 965a9279d2d..88e135bec2a 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs @@ -1,3 +1,10 @@ +use std::mem::swap; + +use swc_common::{util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_transforms_base::ext::ExprRefExt; +use swc_ecma_utils::{ident::IdentLike, ExprExt, ExprFactory, StmtLike}; + use super::Optimizer; use crate::{ compress::{ @@ -8,11 +15,6 @@ use crate::{ util::SpanExt, DISABLE_BUGGY_PASSES, }; -use std::mem::swap; -use swc_common::{util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_transforms_base::ext::ExprRefExt; -use swc_ecma_utils::{ident::IdentLike, ExprExt, ExprFactory, StmtLike}; /// Methods related to the option `conditionals`. All methods are noop if /// `conditionals` is false. @@ -56,6 +58,7 @@ where _ => {} } } + /// This method may change return value. /// /// - `a ? b : false` => `a && b` diff --git a/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs b/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs index c98720cdf1c..a4aff16ce5d 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs @@ -1,9 +1,10 @@ -use super::Optimizer; -use crate::mode::Mode; use swc_common::util::take::Take; use swc_ecma_ast::*; use swc_ecma_utils::ident::IdentLike; +use super::Optimizer; +use crate::mode::Mode; + /// Methods related to option `dead_code`. impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs b/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs index e58344e4e35..ed6eacd2ffc 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs @@ -1,11 +1,13 @@ -use super::Optimizer; -use crate::{compress::util::eval_as_number, mode::Mode, DISABLE_BUGGY_PASSES}; use std::num::FpCategory; + use swc_atoms::js_word; use swc_common::{util::take::Take, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, undefined, ExprExt, Value::Known}; +use super::Optimizer; +use crate::{compress::util::eval_as_number, mode::Mode, DISABLE_BUGGY_PASSES}; + /// Methods related to the option `evaluate`. impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/fns.rs b/crates/swc_ecma_minifier/src/compress/optimize/fns.rs index 5dc57da12bf..9a6d79ba787 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/fns.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/fns.rs @@ -1,3 +1,8 @@ +use std::cmp::Ordering; + +use swc_common::util::take::Take; +use swc_ecma_ast::*; + use super::Optimizer; use crate::{ compress::util::is_directive, @@ -5,9 +10,6 @@ use crate::{ util::{sort::is_sorted_by, ModuleItemExt}, DISABLE_BUGGY_PASSES, }; -use std::cmp::Ordering; -use swc_common::util::take::Take; -use swc_ecma_ast::*; impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/hoist_props.rs b/crates/swc_ecma_minifier/src/compress/optimize/hoist_props.rs index e54916107cd..010eb893dbb 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/hoist_props.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/hoist_props.rs @@ -1,8 +1,9 @@ -use super::Optimizer; -use crate::mode::Mode; use swc_ecma_ast::*; use swc_ecma_utils::ident::IdentLike; +use super::Optimizer; +use crate::mode::Mode; + /// Methods related to the option `hoist_props`. impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs index 000e562b2b4..29461024840 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs @@ -1,3 +1,8 @@ +use swc_common::{util::take::Take, Spanned, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{prepend, undefined, StmtLike}; +use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; + use super::Optimizer; use crate::{ compress::util::{always_terminates, is_pure_undefined}, @@ -5,10 +10,6 @@ use crate::{ mode::Mode, util::ExprOptExt, }; -use swc_common::{util::take::Take, Spanned, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{prepend, undefined, StmtLike}; -use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; /// Methods related to the option `if_return`. All methods are noop if /// `if_return` is false. @@ -571,6 +572,7 @@ impl Visit for ReturnFinder { } fn visit_function(&mut self, _: &Function) {} + fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/iife.rs b/crates/swc_ecma_minifier/src/compress/optimize/iife.rs index d40ccdf53aa..7a1d7525594 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/iife.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/iife.rs @@ -1,18 +1,20 @@ +use std::{ + collections::HashMap, + mem::{replace, swap}, +}; + +use swc_atoms::js_word; +use swc_common::{collections::AHashMap, pass::Either, util::take::Take, Spanned, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{contains_arguments, ident::IdentLike, undefined, ExprFactory, Id}; +use swc_ecma_visit::VisitMutWith; + use super::Optimizer; use crate::{ compress::optimize::Ctx, mode::Mode, util::{idents_captured_by, idents_used_by, make_number}, }; -use std::{ - collections::HashMap, - mem::{replace, swap}, -}; -use swc_atoms::js_word; -use swc_common::{collections::AHashMap, pass::Either, util::take::Take, Spanned, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{contains_arguments, ident::IdentLike, undefined, ExprFactory, Id}; -use swc_ecma_visit::VisitMutWith; /// Methods related to the option `negate_iife`. impl Optimizer<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/optimize/inline.rs b/crates/swc_ecma_minifier/src/compress/optimize/inline.rs index 07d2bb9cb87..36f4a906139 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/inline.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/inline.rs @@ -1,3 +1,8 @@ +use swc_atoms::js_word; +use swc_common::{util::take::Take, Spanned}; +use swc_ecma_ast::*; +use swc_ecma_utils::{find_ids, ident::IdentLike, ExprExt, UsageFinder}; + use super::Optimizer; use crate::{ compress::optimize::util::{class_has_side_effect, is_valid_for_lhs}, @@ -5,10 +10,6 @@ use crate::{ mode::Mode, util::{idents_captured_by, idents_used_by}, }; -use swc_atoms::js_word; -use swc_common::{util::take::Take, Spanned}; -use swc_ecma_ast::*; -use swc_ecma_utils::{find_ids, ident::IdentLike, ExprExt, UsageFinder}; /// Methods related to option `inline`. impl Optimizer<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/optimize/join_vars.rs b/crates/swc_ecma_minifier/src/compress/optimize/join_vars.rs index 9526a2eeed2..25f11b50e49 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/join_vars.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/join_vars.rs @@ -1,11 +1,12 @@ +use swc_common::util::take::Take; +use swc_ecma_ast::*; + use super::Optimizer; use crate::{ compress::util::{drop_invalid_stmts, is_directive}, mode::Mode, util::ModuleItemExt, }; -use swc_common::util::take::Take; -use swc_ecma_ast::*; /// Methods related to option `join_vars`. impl Optimizer<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/optimize/loops.rs b/crates/swc_ecma_minifier/src/compress/optimize/loops.rs index 6fccfc5e649..0408b2d5a8c 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/loops.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/loops.rs @@ -1,10 +1,11 @@ +use swc_common::{util::take::Take, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ExprExt, Value::Known}; + use crate::{ compress::{optimize::Optimizer, util::UnreachableHandler}, mode::Mode, }; -use swc_common::{util::take::Take, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ExprExt, Value::Known}; /// Methods related to the option `loops`. impl Optimizer<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs index 3cca71ed924..a697b4fc890 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs @@ -1,18 +1,8 @@ #![allow(dead_code)] -use self::util::MultiReplacer; -use super::util::{drop_invalid_stmts, is_fine_for_if_cons}; -use crate::{ - analyzer::{ProgramData, UsageAnalyzer}, - compress::util::is_pure_undefined, - debug::{dump, AssertValid}, - marks::Marks, - mode::Mode, - option::CompressOptions, - util::{contains_leaping_yield, make_number, ModuleItemExt}, -}; -use retain_mut::RetainMut; use std::{fmt::Write, iter::once, mem::take}; + +use retain_mut::RetainMut; use swc_atoms::{js_word, JsWord}; use swc_common::{ collections::AHashMap, iter::IdentifyLast, pass::Repeated, util::take::Take, Mark, Spanned, @@ -27,6 +17,18 @@ use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; use tracing::{span, Level}; use Value::Known; +use self::util::MultiReplacer; +use super::util::{drop_invalid_stmts, is_fine_for_if_cons}; +use crate::{ + analyzer::{ProgramData, UsageAnalyzer}, + compress::util::is_pure_undefined, + debug::{dump, AssertValid}, + marks::Marks, + mode::Mode, + option::CompressOptions, + util::{contains_leaping_yield, make_number, ModuleItemExt}, +}; + mod arguments; mod bools; mod collapse_vars; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/ops.rs b/crates/swc_ecma_minifier/src/compress/optimize/ops.rs index 2f38bbe5b42..a1ddd9adc61 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/ops.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/ops.rs @@ -1,14 +1,15 @@ +use swc_atoms::js_word; +use swc_common::{util::take::Take, EqIgnoreSpan}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ident::IdentLike, ExprExt, Type, Value}; +use Value::Known; + use super::Optimizer; use crate::{ compress::util::negate, mode::Mode, util::{make_bool, ValueExt}, }; -use swc_atoms::js_word; -use swc_common::{util::take::Take, EqIgnoreSpan}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ident::IdentLike, ExprExt, Type, Value}; -use Value::Known; impl Optimizer<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs index 61beccaf519..0507ffac6d3 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs @@ -1,3 +1,16 @@ +use std::mem::take; + +use retain_mut::RetainMut; +use swc_atoms::js_word; +use swc_common::{util::take::Take, Spanned, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ + contains_arguments, contains_this_expr, ident::IdentLike, undefined, ExprExt, Id, StmtLike, + UsageFinder, +}; +use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use tracing::{span, Level}; + use super::{is_pure_undefined, Optimizer}; use crate::{ compress::{ @@ -9,17 +22,6 @@ use crate::{ option::CompressOptions, util::{idents_used_by, idents_used_by_ignoring_nested, ExprOptExt, ModuleItemExt}, }; -use retain_mut::RetainMut; -use std::mem::take; -use swc_atoms::js_word; -use swc_common::{util::take::Take, Spanned, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ - contains_arguments, contains_this_expr, ident::IdentLike, undefined, ExprExt, Id, StmtLike, - UsageFinder, -}; -use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; -use tracing::{span, Level}; /// Methods related to the option `sequences`. All methods are noop if /// `sequences` is false. diff --git a/crates/swc_ecma_minifier/src/compress/optimize/strings.rs b/crates/swc_ecma_minifier/src/compress/optimize/strings.rs index d69430c3dbc..afd2f836371 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/strings.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/strings.rs @@ -1,10 +1,11 @@ -use super::Optimizer; -use crate::mode::Mode; use swc_atoms::js_word; use swc_common::{util::take::Take, Spanned}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, ExprExt, Value::Known}; +use super::Optimizer; +use crate::mode::Mode; + impl Optimizer<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index 3da0d2dc983..55f15817efe 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -1,11 +1,13 @@ -use super::Optimizer; -use crate::{mode::Mode, util::ExprOptExt}; use std::mem::take; + use swc_common::{util::take::Take, EqIgnoreSpan, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, prepend, ExprExt, StmtExt, Type, Value::Known}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use super::Optimizer; +use crate::{mode::Mode, util::ExprOptExt}; + /// Methods related to option `switches`. impl Optimizer<'_, M> where @@ -341,5 +343,6 @@ impl Visit for BreakFinder { fn visit_while_stmt(&mut self, _: &WhileStmt) {} fn visit_function(&mut self, _: &Function) {} + fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/unused.rs b/crates/swc_ecma_minifier/src/compress/optimize/unused.rs index 1218002017f..f7be48a9190 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/unused.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/unused.rs @@ -1,12 +1,13 @@ +use swc_atoms::js_word; +use swc_common::{util::take::Take, Span, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{contains_ident_ref, ident::IdentLike}; + use super::Optimizer; use crate::{ compress::optimize::util::class_has_side_effect, debug::dump, mode::Mode, option::PureGetterOption, }; -use swc_atoms::js_word; -use swc_common::{util::take::Take, Span, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{contains_ident_ref, ident::IdentLike}; /// Methods related to the option `unused`. impl Optimizer<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/optimize/util.rs b/crates/swc_ecma_minifier/src/compress/optimize/util.rs index 7a194e5f463..303d9e689d5 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/util.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/util.rs @@ -1,7 +1,5 @@ -use crate::mode::Mode; - -use super::{Ctx, Optimizer}; use std::ops::{Deref, DerefMut}; + use swc_atoms::JsWord; use swc_common::{collections::AHashMap, Span}; use swc_ecma_ast::*; @@ -9,6 +7,9 @@ use swc_ecma_utils::{ident::IdentLike, prop_name_eq, ExprExt, Id}; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; use tracing::debug; +use super::{Ctx, Optimizer}; +use crate::mode::Mode; + impl<'b, M> Optimizer<'b, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/arrows.rs b/crates/swc_ecma_minifier/src/compress/pure/arrows.rs index 986e8223b8b..52bc26b015d 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/arrows.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/arrows.rs @@ -1,9 +1,10 @@ -use super::Pure; -use crate::mode::Mode; use swc_common::{util::take::Take, Spanned}; use swc_ecma_ast::*; use swc_ecma_utils::contains_this_expr; +use super::Pure; +use crate::mode::Mode; + /// Methods related to the option `arrows`. impl Pure<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/pure/bools.rs b/crates/swc_ecma_minifier/src/compress/pure/bools.rs index 14971b7739d..57ad9cc466e 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/bools.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/bools.rs @@ -1,3 +1,10 @@ +use std::mem::swap; + +use swc_atoms::js_word; +use swc_common::{util::take::Take, EqIgnoreSpan, Span, Spanned, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ExprExt, Type, Value}; + use super::Pure; use crate::{ compress::util::{is_pure_undefined, negate, negate_cost}, @@ -5,11 +12,6 @@ use crate::{ option::CompressOptions, util::make_bool, }; -use std::mem::swap; -use swc_atoms::js_word; -use swc_common::{util::take::Take, EqIgnoreSpan, Span, Spanned, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ExprExt, Type, Value}; impl Pure<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/pure/conds.rs b/crates/swc_ecma_minifier/src/compress/pure/conds.rs index 25a5946655d..fec25b02668 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/conds.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/conds.rs @@ -1,10 +1,12 @@ -use super::Pure; -use crate::{compress::util::negate_cost, debug::dump, mode::Mode, util::make_bool}; use std::mem::swap; + use swc_common::{util::take::Take, EqIgnoreSpan, Spanned}; use swc_ecma_ast::*; use swc_ecma_utils::{ExprExt, Type, Value}; +use super::Pure; +use crate::{compress::util::negate_cost, debug::dump, mode::Mode, util::make_bool}; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/ctx.rs b/crates/swc_ecma_minifier/src/compress/pure/ctx.rs index 0e4d937dcc4..764b30abb79 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/ctx.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/ctx.rs @@ -1,6 +1,7 @@ -use super::Pure; use std::ops::{Deref, DerefMut}; +use super::Pure; + #[derive(Default, Clone, Copy)] pub(super) struct Ctx { pub par_depth: u8, diff --git a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs index 685392e13dc..1cdf3fbea9e 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs @@ -1,12 +1,13 @@ +use swc_common::{util::take::Take, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ExprExt, StmtLike, Value}; + use super::Pure; use crate::{ compress::util::{always_terminates, is_fine_for_if_cons}, mode::Mode, util::ModuleItemExt, }; -use swc_common::{util::take::Take, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ExprExt, StmtLike, Value}; /// Methods related to option `dead_code`. impl Pure<'_, M> diff --git a/crates/swc_ecma_minifier/src/compress/pure/drop_console.rs b/crates/swc_ecma_minifier/src/compress/pure/drop_console.rs index 18636280f38..5c662a4df4d 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/drop_console.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/drop_console.rs @@ -1,8 +1,9 @@ -use super::Pure; use swc_common::DUMMY_SP; use swc_ecma_ast::*; use swc_ecma_utils::undefined; +use super::Pure; + impl Pure<'_, M> { pub(super) fn drop_console(&mut self, e: &mut Expr) { if !self.options.drop_console { diff --git a/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs b/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs index c1a8ae7b653..c76c706a7bd 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs @@ -1,12 +1,13 @@ +use swc_atoms::js_word; +use swc_common::{util::take::Take, Spanned, SyntaxContext}; +use swc_ecma_ast::*; +use swc_ecma_utils::{undefined, ExprExt, Value}; + use super::Pure; use crate::{ compress::util::{eval_as_number, is_pure_undefined_or_null}, mode::Mode, }; -use swc_atoms::js_word; -use swc_common::{util::take::Take, Spanned, SyntaxContext}; -use swc_ecma_ast::*; -use swc_ecma_utils::{undefined, ExprExt, Value}; impl Pure<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/pure/if_return.rs b/crates/swc_ecma_minifier/src/compress/pure/if_return.rs index 825a168a064..4692b5c7018 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/if_return.rs @@ -1,8 +1,9 @@ -use super::Pure; -use crate::compress::util::{is_fine_for_if_cons, negate}; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; +use super::Pure; +use crate::compress::util::{is_fine_for_if_cons, negate}; + impl Pure<'_, M> { /// # Input /// diff --git a/crates/swc_ecma_minifier/src/compress/pure/loops.rs b/crates/swc_ecma_minifier/src/compress/pure/loops.rs index eb908dc5302..bbb61c14e20 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/loops.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/loops.rs @@ -1,9 +1,10 @@ -use super::Pure; -use crate::mode::Mode; use swc_common::{util::take::Take, Spanned}; use swc_ecma_ast::*; use swc_ecma_utils::{ExprExt, Value}; +use super::Pure; +use crate::mode::Mode; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/misc.rs b/crates/swc_ecma_minifier/src/compress/pure/misc.rs index 5ddf6ecf789..5fda9d27d4d 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/misc.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/misc.rs @@ -1,9 +1,10 @@ use std::num::FpCategory; +use swc_common::{util::take::Take, DUMMY_SP}; +use swc_ecma_ast::*; + use super::Pure; use crate::{compress::util::is_pure_undefined, mode::Mode}; -use swc_common::{util::take::Take, DUMMY_SP}; -use swc_ecma_ast::*; impl Pure<'_, M> where diff --git a/crates/swc_ecma_minifier/src/compress/pure/mod.rs b/crates/swc_ecma_minifier/src/compress/pure/mod.rs index cff60c88e7a..0b7095d7305 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/mod.rs @@ -1,3 +1,9 @@ +use rayon::prelude::*; +use swc_common::{pass::Repeated, util::take::Take, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; +use tracing::{span, Level}; + use self::{ctx::Ctx, misc::DropOpts}; use crate::{ debug::{dump, AssertValid}, @@ -7,11 +13,6 @@ use crate::{ util::ModuleItemExt, MAX_PAR_DEPTH, }; -use rayon::prelude::*; -use swc_common::{pass::Repeated, util::take::Take, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; -use tracing::{span, Level}; mod arrows; mod bools; diff --git a/crates/swc_ecma_minifier/src/compress/pure/numbers.rs b/crates/swc_ecma_minifier/src/compress/pure/numbers.rs index 013f3ad9624..5bd23c11941 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/numbers.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/numbers.rs @@ -1,8 +1,9 @@ -use super::Pure; -use crate::mode::Mode; use swc_common::util::take::Take; use swc_ecma_ast::*; +use super::Pure; +use crate::mode::Mode; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/properties.rs b/crates/swc_ecma_minifier/src/compress/pure/properties.rs index 90ee013a29a..54c7cb35d32 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/properties.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/properties.rs @@ -1,10 +1,11 @@ -use super::Pure; -use crate::{compress::util::is_valid_identifier, mode::Mode, util::deeply_contains_this_expr}; use swc_atoms::js_word; use swc_common::SyntaxContext; use swc_ecma_ast::*; use swc_ecma_utils::{prop_name_eq, ExprExt}; +use super::Pure; +use crate::{compress::util::is_valid_identifier, mode::Mode, util::deeply_contains_this_expr}; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/sequences.rs b/crates/swc_ecma_minifier/src/compress/pure/sequences.rs index 0315692d773..870343d42a8 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/sequences.rs @@ -1,10 +1,11 @@ -use super::Pure; -use crate::mode::Mode; use swc_atoms::js_word; use swc_common::{util::take::Take, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{ExprExt, ExprFactory}; +use super::Pure; +use crate::mode::Mode; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/strings.rs b/crates/swc_ecma_minifier/src/compress/pure/strings.rs index d66752956b9..b7417194f98 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/strings.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/strings.rs @@ -1,11 +1,13 @@ -use super::Pure; -use crate::mode::Mode; use std::mem::take; + use swc_atoms::{js_word, JsWord}; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{ExprExt, Type, Value}; +use super::Pure; +use crate::mode::Mode; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/unsafes.rs b/crates/swc_ecma_minifier/src/compress/pure/unsafes.rs index 3f0cad0b684..98020649979 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/unsafes.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/unsafes.rs @@ -1,9 +1,10 @@ -use super::Pure; -use crate::mode::Mode; use swc_atoms::js_word; use swc_ecma_ast::*; use swc_ecma_utils::ExprExt; +use super::Pure; +use crate::mode::Mode; + impl Pure<'_, M> where M: Mode, diff --git a/crates/swc_ecma_minifier/src/compress/pure/vars.rs b/crates/swc_ecma_minifier/src/compress/pure/vars.rs index bfe32ecc4d4..236905fc859 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/vars.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/vars.rs @@ -1,5 +1,3 @@ -use super::Pure; -use crate::mode::Mode; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{prepend, StmtLike}; @@ -7,6 +5,9 @@ use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith, }; +use super::Pure; +use crate::mode::Mode; + impl Pure<'_, M> where M: Mode, @@ -272,6 +273,15 @@ pub(super) struct VarPrepender { impl VisitMut for VarPrepender { noop_visit_mut_type!(); + /// Noop + fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {} + + /// Noop + fn visit_mut_constructor(&mut self, _: &mut Constructor) {} + + /// Noop + fn visit_mut_function(&mut self, _: &mut Function) {} + fn visit_mut_var_decl(&mut self, v: &mut VarDecl) { if self.vars.is_empty() { return; @@ -288,13 +298,4 @@ impl VisitMut for VarPrepender { v.decls = decls; } } - - /// Noop - fn visit_mut_function(&mut self, _: &mut Function) {} - - /// Noop - fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {} - - /// Noop - fn visit_mut_constructor(&mut self, _: &mut Constructor) {} } diff --git a/crates/swc_ecma_minifier/src/compress/util/mod.rs b/crates/swc_ecma_minifier/src/compress/util/mod.rs index 586d1322cc2..2e70941d040 100644 --- a/crates/swc_ecma_minifier/src/compress/util/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/util/mod.rs @@ -1,5 +1,5 @@ -use crate::{debug::dump, util::ModuleItemExt}; use std::f64; + use swc_atoms::js_word; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; @@ -8,6 +8,8 @@ use swc_ecma_utils::{ExprExt, Id, UsageFinder, Value}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, FoldWith, VisitMut, VisitMutWith, VisitWith}; use unicode_xid::UnicodeXID; +use crate::{debug::dump, util::ModuleItemExt}; + #[cfg(test)] mod tests; diff --git a/crates/swc_ecma_minifier/src/compress/util/tests.rs b/crates/swc_ecma_minifier/src/compress/util/tests.rs index ab0de0e6f05..8c8a7f5f660 100644 --- a/crates/swc_ecma_minifier/src/compress/util/tests.rs +++ b/crates/swc_ecma_minifier/src/compress/util/tests.rs @@ -1,6 +1,3 @@ -use crate::{compress::util::negate, debug::dump}; - -use super::negate_cost; use swc_common::{input::SourceFileInput, util::take::Take, FileName}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, Parser}; @@ -8,6 +5,9 @@ use swc_ecma_transforms::fixer; use swc_ecma_visit::{noop_visit_mut_type, FoldWith, VisitMut, VisitMutWith}; use tracing::{info, warn}; +use super::negate_cost; +use crate::{compress::util::negate, debug::dump}; + struct UnwrapParen; impl VisitMut for UnwrapParen { noop_visit_mut_type!(); diff --git a/crates/swc_ecma_minifier/src/debug.rs b/crates/swc_ecma_minifier/src/debug.rs index 4beae674458..c9cfadd68ff 100644 --- a/crates/swc_ecma_minifier/src/debug.rs +++ b/crates/swc_ecma_minifier/src/debug.rs @@ -1,5 +1,6 @@ -use once_cell::sync::Lazy; use std::{env, process::Command}; + +use once_cell::sync::Lazy; use swc_common::{sync::Lrc, SourceMap, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_codegen::{text_writer::JsWriter, Emitter}; diff --git a/crates/swc_ecma_minifier/src/eval.rs b/crates/swc_ecma_minifier/src/eval.rs index 82601f67b29..65b368e9fa7 100644 --- a/crates/swc_ecma_minifier/src/eval.rs +++ b/crates/swc_ecma_minifier/src/eval.rs @@ -1,9 +1,5 @@ -use crate::{ - compress::{compressor, pure_optimizer}, - marks::Marks, - mode::Mode, -}; use std::sync::{Arc, Mutex}; + use swc_atoms::js_word; use swc_common::{collections::AHashMap, util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; @@ -11,6 +7,12 @@ use swc_ecma_transforms::optimization::simplify::{expr_simplifier, ExprSimplifie use swc_ecma_utils::{ident::IdentLike, undefined, ExprExt, Id}; use swc_ecma_visit::{FoldWith, VisitMutWith}; +use crate::{ + compress::{compressor, pure_optimizer}, + marks::Marks, + mode::Mode, +}; + pub struct Evaluator { module: Module, marks: Marks, diff --git a/crates/swc_ecma_minifier/src/lib.rs b/crates/swc_ecma_minifier/src/lib.rs index 292f2ca87b8..4f1ca9ac3b2 100644 --- a/crates/swc_ecma_minifier/src/lib.rs +++ b/crates/swc_ecma_minifier/src/lib.rs @@ -18,6 +18,14 @@ #![allow(clippy::vec_box)] #![allow(unstable_name_collisions)] +use mode::Minification; +use pass::postcompress::postcompress_optimizer; +use swc_common::{comments::Comments, sync::Lrc, SourceMap, GLOBALS}; +use swc_ecma_ast::Module; +use swc_ecma_visit::{FoldWith, VisitMutWith}; +use swc_timer::timer; +use timing::Timings; + pub use crate::pass::unique_scope::unique_scope; use crate::{ compress::compressor, @@ -30,13 +38,6 @@ use crate::{ precompress::precompress_optimizer, }, }; -use mode::Minification; -use pass::postcompress::postcompress_optimizer; -use swc_common::{comments::Comments, sync::Lrc, SourceMap, GLOBALS}; -use swc_ecma_ast::Module; -use swc_ecma_visit::{FoldWith, VisitMutWith}; -use swc_timer::timer; -use timing::Timings; mod analyzer; mod compress; diff --git a/crates/swc_ecma_minifier/src/metadata/mod.rs b/crates/swc_ecma_minifier/src/metadata/mod.rs index d3ffd29fe1a..6f1a89c746c 100644 --- a/crates/swc_ecma_minifier/src/metadata/mod.rs +++ b/crates/swc_ecma_minifier/src/metadata/mod.rs @@ -1,4 +1,3 @@ -use crate::marks::Marks; use swc_common::{ comments::{Comment, CommentKind, Comments}, Mark, Span, SyntaxContext, @@ -9,6 +8,8 @@ use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith, }; +use crate::marks::Marks; + #[cfg(test)] mod tests; diff --git a/crates/swc_ecma_minifier/src/option/terser.rs b/crates/swc_ecma_minifier/src/option/terser.rs index 97af0c94f96..c5a17e48781 100644 --- a/crates/swc_ecma_minifier/src/option/terser.rs +++ b/crates/swc_ecma_minifier/src/option/terser.rs @@ -1,7 +1,5 @@ //! Compatibility for terser config. -use super::{true_by_default, CompressOptions, TopLevelOptions}; -use crate::option::PureGetterOption; use serde::{Deserialize, Serialize}; use serde_json::Value; use swc_atoms::JsWord; @@ -12,6 +10,9 @@ use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, Parser}; use swc_ecma_utils::drop_span; +use super::{true_by_default, CompressOptions, TopLevelOptions}; +use crate::option::PureGetterOption; + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] #[serde(untagged)] diff --git a/crates/swc_ecma_minifier/src/pass/global_defs.rs b/crates/swc_ecma_minifier/src/pass/global_defs.rs index 3e8a11c5661..fe5e085e1e3 100644 --- a/crates/swc_ecma_minifier/src/pass/global_defs.rs +++ b/crates/swc_ecma_minifier/src/pass/global_defs.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; + use swc_common::{collections::AHashSet, pass::CompilerPass, EqIgnoreSpan, Mark, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; diff --git a/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/mod.rs b/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/mod.rs index 3953e74953f..7c1c70d72b7 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/mod.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/mod.rs @@ -1,4 +1,3 @@ -use self::scope::Scope; use swc_atoms::JsWord; use swc_common::collections::{AHashMap, AHashSet}; use swc_ecma_ast::*; @@ -6,6 +5,8 @@ use swc_ecma_utils::{ident::IdentLike, Id}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use tracing::trace; +use self::scope::Scope; + mod scope; pub(super) struct Analyzer { diff --git a/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/scope.rs b/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/scope.rs index ac77f132e12..309a2d148b9 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/scope.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_names/analyzer/scope.rs @@ -1,4 +1,3 @@ -use crate::util::base54::incr_base54; use rayon::prelude::*; use swc_atoms::{js_word, JsWord}; use swc_common::{ @@ -7,6 +6,8 @@ use swc_common::{ }; use swc_ecma_utils::Id; +use crate::util::base54::incr_base54; + #[derive(Debug, Default)] pub(crate) struct Scope { pub data: ScopeData, diff --git a/crates/swc_ecma_minifier/src/pass/mangle_names/mod.rs b/crates/swc_ecma_minifier/src/pass/mangle_names/mod.rs index 25a0aa7b53f..e12fd0a9be7 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_names/mod.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_names/mod.rs @@ -1,8 +1,9 @@ -use super::compute_char_freq::CharFreqInfo; -use crate::{marks::Marks, option::MangleOptions}; use swc_common::chain; use swc_ecma_visit::VisitMut; +use super::compute_char_freq::CharFreqInfo; +use crate::{marks::Marks, option::MangleOptions}; + mod analyzer; mod preserver; mod private_name; diff --git a/crates/swc_ecma_minifier/src/pass/mangle_names/preserver.rs b/crates/swc_ecma_minifier/src/pass/mangle_names/preserver.rs index 9b58e908a96..94a2ca7d800 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_names/preserver.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_names/preserver.rs @@ -1,9 +1,10 @@ -use crate::option::MangleOptions; use swc_common::collections::AHashSet; use swc_ecma_ast::*; use swc_ecma_utils::{find_ids, ident::IdentLike, Id}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use crate::option::MangleOptions; + pub(super) fn idents_to_preserve(options: MangleOptions, n: &N) -> AHashSet where N: VisitWith, diff --git a/crates/swc_ecma_minifier/src/pass/mangle_names/private_name.rs b/crates/swc_ecma_minifier/src/pass/mangle_names/private_name.rs index fca2eaf31c3..1666da770b9 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_names/private_name.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_names/private_name.rs @@ -1,10 +1,11 @@ -use crate::util::base54::incr_base54; use swc_atoms::JsWord; use swc_common::collections::AHashMap; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; +use crate::util::base54::incr_base54; + pub fn private_name_mangler(keep_private_props: bool) -> impl Fold + VisitMut { as_folder(PrivateNameMangler { keep_private_props, diff --git a/crates/swc_ecma_minifier/src/pass/mangle_names/real_impl.rs b/crates/swc_ecma_minifier/src/pass/mangle_names/real_impl.rs index 92753249a82..8b80c799d90 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_names/real_impl.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_names/real_impl.rs @@ -1,9 +1,10 @@ -use super::{analyzer::Analyzer, preserver::idents_to_preserve}; -use crate::{marks::Marks, option::MangleOptions, pass::compute_char_freq::CharFreqInfo}; use swc_ecma_ast::*; use swc_ecma_transforms::hygiene::rename; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; +use super::{analyzer::Analyzer, preserver::idents_to_preserve}; +use crate::{marks::Marks, option::MangleOptions, pass::compute_char_freq::CharFreqInfo}; + pub(crate) fn name_mangler( options: MangleOptions, _char_freq_info: CharFreqInfo, diff --git a/crates/swc_ecma_minifier/src/pass/mangle_props.rs b/crates/swc_ecma_minifier/src/pass/mangle_props.rs index 31a5b1f7cec..7dbde5931b1 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_props.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_props.rs @@ -1,10 +1,6 @@ -use crate::{ - analyzer::{analyze, ProgramData}, - option::ManglePropertiesOptions, - util::base54::incr_base54, -}; -use once_cell::sync::Lazy; use std::collections::HashSet; + +use once_cell::sync::Lazy; use swc_atoms::{js_word, JsWord}; use swc_common::collections::{AHashMap, AHashSet}; use swc_ecma_ast::{ @@ -14,6 +10,12 @@ use swc_ecma_ast::{ use swc_ecma_utils::ident::IdentLike; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use crate::{ + analyzer::{analyze, ProgramData}, + option::ManglePropertiesOptions, + util::base54::incr_base54, +}; + pub static JS_ENVIRONMENT_PROPS: Lazy> = Lazy::new(|| { let domprops: Vec = serde_json::from_str(include_str!("../lists/domprops.json")) .expect("failed to parse domprops.json for property mangler"); diff --git a/crates/swc_ecma_minifier/src/pass/postcompress.rs b/crates/swc_ecma_minifier/src/pass/postcompress.rs index bc4433fd331..7ab5b12bb46 100644 --- a/crates/swc_ecma_minifier/src/pass/postcompress.rs +++ b/crates/swc_ecma_minifier/src/pass/postcompress.rs @@ -1,8 +1,9 @@ -use crate::{option::CompressOptions, DISABLE_BUGGY_PASSES}; use swc_common::util::take::Take; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use crate::{option::CompressOptions, DISABLE_BUGGY_PASSES}; + pub fn postcompress_optimizer(options: &CompressOptions) -> impl '_ + VisitMut { PostcompressOptimizer { options } } diff --git a/crates/swc_ecma_minifier/src/pass/precompress.rs b/crates/swc_ecma_minifier/src/pass/precompress.rs index 2cdb47a2885..78fbe76a045 100644 --- a/crates/swc_ecma_minifier/src/pass/precompress.rs +++ b/crates/swc_ecma_minifier/src/pass/precompress.rs @@ -1,14 +1,15 @@ +use swc_atoms::js_word; +use swc_common::{collections::AHashMap, util::take::Take}; +use swc_ecma_ast::*; +use swc_ecma_utils::{ident::IdentLike, Id}; +use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; + use crate::{ analyzer::{analyze, ProgramData, UsageAnalyzer}, marks::Marks, option::CompressOptions, util::ModuleItemExt, }; -use swc_atoms::js_word; -use swc_common::{collections::AHashMap, util::take::Take}; -use swc_ecma_ast::*; -use swc_ecma_utils::{ident::IdentLike, Id}; -use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; /// Optimizer invoked before invoking compressor. /// diff --git a/crates/swc_ecma_minifier/src/util/mod.rs b/crates/swc_ecma_minifier/src/util/mod.rs index 5a1c4852874..06068a87a8c 100644 --- a/crates/swc_ecma_minifier/src/util/mod.rs +++ b/crates/swc_ecma_minifier/src/util/mod.rs @@ -1,4 +1,5 @@ use std::time::Instant; + use swc_common::{ collections::AHashSet, pass::{CompilerPass, Repeated}, @@ -227,6 +228,7 @@ impl Visit for LeapFinder { } fn visit_function(&mut self, _: &Function) {} + fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} } @@ -359,6 +361,8 @@ pub(crate) struct IdentUsageCollector { impl Visit for IdentUsageCollector { noop_visit_type!(); + visit_obj_and_computed!(); + fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) { if self.ignore_nested { return; @@ -387,8 +391,6 @@ impl Visit for IdentUsageCollector { self.ids.insert(n.to_id()); } - visit_obj_and_computed!(); - fn visit_prop_name(&mut self, n: &PropName) { if let PropName::Computed(..) = n { n.visit_children_with(self); @@ -405,6 +407,8 @@ pub(crate) struct CapturedIdCollector { impl Visit for CapturedIdCollector { noop_visit_type!(); + visit_obj_and_computed!(); + fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) { let old = self.is_nested; self.is_nested = true; @@ -432,8 +436,6 @@ impl Visit for CapturedIdCollector { } } - visit_obj_and_computed!(); - fn visit_prop_name(&mut self, n: &PropName) { if let PropName::Computed(..) = n { n.visit_children_with(self); diff --git a/crates/swc_ecma_minifier/src/util/unit.rs b/crates/swc_ecma_minifier/src/util/unit.rs index c54bb842a50..0d8071685e7 100644 --- a/crates/swc_ecma_minifier/src/util/unit.rs +++ b/crates/swc_ecma_minifier/src/util/unit.rs @@ -1,11 +1,13 @@ -use crate::debug::{dump, AssertValid}; use std::fmt::Debug; + use swc_common::Mark; use swc_ecma_ast::*; use swc_ecma_transforms::{fixer, hygiene}; use swc_ecma_utils::DropSpan; use swc_ecma_visit::{as_folder, FoldWith, VisitMut, VisitMutWith, VisitWith}; +use crate::debug::{dump, AssertValid}; + /// Indicates a unit of minifaction. pub(crate) trait CompileUnit: swc_ecma_codegen::Node diff --git a/crates/swc_ecma_minifier/tests/compress.rs b/crates/swc_ecma_minifier/tests/compress.rs index 4b43d1ff7ff..9af448c9c71 100644 --- a/crates/swc_ecma_minifier/tests/compress.rs +++ b/crates/swc_ecma_minifier/tests/compress.rs @@ -2,10 +2,6 @@ extern crate swc_node_base; -use ansi_term::Color; -use anyhow::{bail, Context, Error}; -use once_cell::sync::Lazy; -use serde::Deserialize; use std::{ env, fmt::{self, Debug}, @@ -15,6 +11,11 @@ use std::{ process::Command, time::Instant, }; + +use ansi_term::Color; +use anyhow::{bail, Context, Error}; +use once_cell::sync::Lazy; +use serde::Deserialize; use swc_common::{ comments::SingleThreadedComments, errors::Handler, sync::Lrc, EqIgnoreSpan, FileName, Mark, SourceMap, Spanned, @@ -500,598 +501,747 @@ impl Visit for Shower<'_> { self.show("ArrayLit", n); n.visit_children_with(self) } + fn visit_array_pat(&mut self, n: &ArrayPat) { self.show("ArrayPat", n); n.visit_children_with(self) } + fn visit_arrow_expr(&mut self, n: &ArrowExpr) { self.show("ArrowExpr", n); n.visit_children_with(self) } + fn visit_assign_expr(&mut self, n: &AssignExpr) { self.show("AssignExpr", n); n.visit_children_with(self) } + fn visit_assign_pat(&mut self, n: &AssignPat) { self.show("AssignPat", n); n.visit_children_with(self) } + fn visit_assign_pat_prop(&mut self, n: &AssignPatProp) { self.show("AssignPatProp", n); n.visit_children_with(self) } + fn visit_assign_prop(&mut self, n: &AssignProp) { self.show("AssignProp", n); n.visit_children_with(self) } + fn visit_await_expr(&mut self, n: &AwaitExpr) { self.show("AwaitExpr", n); n.visit_children_with(self) } + fn visit_bin_expr(&mut self, n: &BinExpr) { self.show("BinExpr", n); n.visit_children_with(self) } + fn visit_block_stmt(&mut self, n: &BlockStmt) { self.show("BlockStmt", n); n.visit_children_with(self) } + fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) { self.show("BlockStmtOrExpr", n); n.visit_children_with(self) } + fn visit_bool(&mut self, n: &Bool) { self.show("Bool", n); n.visit_children_with(self) } + fn visit_break_stmt(&mut self, n: &BreakStmt) { self.show("BreakStmt", n); n.visit_children_with(self) } + fn visit_call_expr(&mut self, n: &CallExpr) { self.show("CallExpr", n); n.visit_children_with(self) } + fn visit_catch_clause(&mut self, n: &CatchClause) { self.show("CatchClause", n); n.visit_children_with(self) } + fn visit_class(&mut self, n: &Class) { self.show("Class", n); n.visit_children_with(self) } + fn visit_class_decl(&mut self, n: &ClassDecl) { self.show("ClassDecl", n); n.visit_children_with(self) } + fn visit_class_expr(&mut self, n: &ClassExpr) { self.show("ClassExpr", n); n.visit_children_with(self) } + fn visit_class_member(&mut self, n: &ClassMember) { self.show("ClassMember", n); n.visit_children_with(self) } + fn visit_class_method(&mut self, n: &ClassMethod) { self.show("ClassMethod", n); n.visit_children_with(self) } + fn visit_class_prop(&mut self, n: &ClassProp) { self.show("ClassProp", n); n.visit_children_with(self) } + fn visit_computed_prop_name(&mut self, n: &ComputedPropName) { self.show("ComputedPropName", n); n.visit_children_with(self) } + fn visit_cond_expr(&mut self, n: &CondExpr) { self.show("CondExpr", n); n.visit_children_with(self) } + fn visit_constructor(&mut self, n: &Constructor) { self.show("Constructor", n); n.visit_children_with(self) } + fn visit_continue_stmt(&mut self, n: &ContinueStmt) { self.show("ContinueStmt", n); n.visit_children_with(self) } + fn visit_debugger_stmt(&mut self, n: &DebuggerStmt) { self.show("DebuggerStmt", n); n.visit_children_with(self) } + fn visit_decl(&mut self, n: &Decl) { self.show("Decl", n); n.visit_children_with(self) } + fn visit_decorator(&mut self, n: &Decorator) { self.show("Decorator", n); n.visit_children_with(self) } + fn visit_default_decl(&mut self, n: &DefaultDecl) { self.show_name("DefaultDecl", n); n.visit_children_with(self) } + fn visit_do_while_stmt(&mut self, n: &DoWhileStmt) { self.show("DoWhileStmt", n); n.visit_children_with(self) } + fn visit_empty_stmt(&mut self, n: &EmptyStmt) { self.show("EmptyStmt", n); n.visit_children_with(self) } + fn visit_export_all(&mut self, n: &ExportAll) { self.show("ExportAll", n); n.visit_children_with(self) } + fn visit_export_decl(&mut self, n: &ExportDecl) { self.show("ExportDecl", n); n.visit_children_with(self) } + fn visit_export_default_decl(&mut self, n: &ExportDefaultDecl) { self.show("ExportDefaultDecl", n); n.visit_children_with(self) } + fn visit_export_default_expr(&mut self, n: &ExportDefaultExpr) { self.show("ExportDefaultExpr", n); n.visit_children_with(self) } + fn visit_export_default_specifier(&mut self, n: &ExportDefaultSpecifier) { self.show_name("ExportDefaultSpecifier", n); n.visit_children_with(self) } + fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) { self.show("ExportNamedSpecifier", n); n.visit_children_with(self) } + fn visit_export_namespace_specifier(&mut self, n: &ExportNamespaceSpecifier) { self.show("ExportNamespaceSpecifier", n); n.visit_children_with(self) } + fn visit_export_specifier(&mut self, n: &ExportSpecifier) { self.show("ExportSpecifier", n); n.visit_children_with(self) } + fn visit_expr(&mut self, n: &Expr) { self.show("Expr", n); n.visit_children_with(self) } + fn visit_expr_or_spread(&mut self, n: &ExprOrSpread) { self.show("ExprOrSpread", n); n.visit_children_with(self) } + fn visit_callee(&mut self, n: &Callee) { self.show("Callee", n); n.visit_children_with(self) } + fn visit_fn_decl(&mut self, n: &FnDecl) { self.show("FnDecl", n); n.visit_children_with(self) } + fn visit_fn_expr(&mut self, n: &FnExpr) { self.show("FnExpr", n); n.visit_children_with(self) } + fn visit_for_in_stmt(&mut self, n: &ForInStmt) { self.show("ForInStmt", n); n.visit_children_with(self) } + fn visit_for_of_stmt(&mut self, n: &ForOfStmt) { self.show("ForOfStmt", n); n.visit_children_with(self) } + fn visit_for_stmt(&mut self, n: &ForStmt) { self.show("ForStmt", n); n.visit_children_with(self) } + fn visit_function(&mut self, n: &Function) { self.show("Function", n); n.visit_children_with(self) } + fn visit_getter_prop(&mut self, n: &GetterProp) { self.show("GetterProp", n); n.visit_children_with(self) } + fn visit_ident(&mut self, n: &Ident) { self.show("Ident", n); n.visit_children_with(self) } + fn visit_if_stmt(&mut self, n: &IfStmt) { self.show("IfStmt", n); n.visit_children_with(self) } + fn visit_import_decl(&mut self, n: &ImportDecl) { self.show("ImportDecl", n); n.visit_children_with(self) } + fn visit_import_default_specifier(&mut self, n: &ImportDefaultSpecifier) { self.show_name("ImportDefaultSpecifier", n); n.visit_children_with(self) } + fn visit_import_named_specifier(&mut self, n: &ImportNamedSpecifier) { self.show("ImportNamedSpecifier", n); n.visit_children_with(self) } + fn visit_import_specifier(&mut self, n: &ImportSpecifier) { self.show_name("ImportSpecifier", n); n.visit_children_with(self) } + fn visit_import_star_as_specifier(&mut self, n: &ImportStarAsSpecifier) { self.show_name("ImportStarAsSpecifier", n); n.visit_children_with(self) } + fn visit_invalid(&mut self, n: &Invalid) { self.show("Invalid", n); n.visit_children_with(self) } + fn visit_jsx_attr(&mut self, n: &JSXAttr) { self.show("JSXAttr", n); n.visit_children_with(self) } + fn visit_jsx_attr_name(&mut self, n: &JSXAttrName) { self.show("JSXAttrName", n); n.visit_children_with(self) } + fn visit_jsx_attr_or_spread(&mut self, n: &JSXAttrOrSpread) { self.show("JSXAttrOrSpread", n); n.visit_children_with(self) } + fn visit_jsx_attr_value(&mut self, n: &JSXAttrValue) { self.show("JSXAttrValue", n); n.visit_children_with(self) } + fn visit_jsx_closing_element(&mut self, n: &JSXClosingElement) { self.show("JSXClosingElement", n); n.visit_children_with(self) } + fn visit_jsx_closing_fragment(&mut self, n: &JSXClosingFragment) { self.show("JSXClosingFragment", n); n.visit_children_with(self) } + fn visit_jsx_element(&mut self, n: &JSXElement) { self.show("JSXElement", n); n.visit_children_with(self) } + fn visit_jsx_element_child(&mut self, n: &JSXElementChild) { self.show("JSXElementChild", n); n.visit_children_with(self) } + fn visit_jsx_element_name(&mut self, n: &JSXElementName) { self.show("JSXElementName", n); n.visit_children_with(self) } + fn visit_jsx_empty_expr(&mut self, n: &JSXEmptyExpr) { self.show("JSXEmptyExpr", n); n.visit_children_with(self) } + fn visit_jsx_expr(&mut self, n: &JSXExpr) { self.show("JSXExpr", n); n.visit_children_with(self) } + fn visit_jsx_expr_container(&mut self, n: &JSXExprContainer) { self.show("JSXExprContainer", n); n.visit_children_with(self) } + fn visit_jsx_fragment(&mut self, n: &JSXFragment) { self.show("JSXFragment", n); n.visit_children_with(self) } + fn visit_jsx_member_expr(&mut self, n: &JSXMemberExpr) { self.show("JSXMemberExpr", n); n.visit_children_with(self) } + fn visit_jsx_namespaced_name(&mut self, n: &JSXNamespacedName) { self.show("JSXNamespacedName", n); n.visit_children_with(self) } + fn visit_jsx_object(&mut self, n: &JSXObject) { self.show("JSXObject", n); n.visit_children_with(self) } + fn visit_jsx_opening_element(&mut self, n: &JSXOpeningElement) { self.show("JSXOpeningElement", n); n.visit_children_with(self) } + fn visit_jsx_opening_fragment(&mut self, n: &JSXOpeningFragment) { self.show("JSXOpeningFragment", n); n.visit_children_with(self) } + fn visit_jsx_spread_child(&mut self, n: &JSXSpreadChild) { self.show("JSXSpreadChild", n); n.visit_children_with(self) } + fn visit_jsx_text(&mut self, n: &JSXText) { self.show("JSXText", n); n.visit_children_with(self) } + fn visit_key_value_pat_prop(&mut self, n: &KeyValuePatProp) { self.show("KeyValuePatProp", n); n.visit_children_with(self) } + fn visit_key_value_prop(&mut self, n: &KeyValueProp) { self.show("KeyValueProp", n); n.visit_children_with(self) } + fn visit_labeled_stmt(&mut self, n: &LabeledStmt) { self.show("LabeledStmt", n); n.visit_children_with(self) } + fn visit_lit(&mut self, n: &Lit) { self.show("Lit", n); n.visit_children_with(self) } + fn visit_member_expr(&mut self, n: &MemberExpr) { self.show("MemberExpr", n); n.visit_children_with(self) } + fn visit_super_prop_expr(&mut self, n: &SuperPropExpr) { self.show("SuperPropExpr", n); n.visit_children_with(self) } + fn visit_meta_prop_expr(&mut self, n: &MetaPropExpr) { self.show("MetaPropExpr", n); n.visit_children_with(self) } + fn visit_method_prop(&mut self, n: &MethodProp) { self.show("MethodProp", n); n.visit_children_with(self) } + fn visit_module(&mut self, n: &Module) { self.show("Module", n); n.visit_children_with(self) } + fn visit_module_decl(&mut self, n: &ModuleDecl) { self.show("ModuleDecl", n); n.visit_children_with(self) } + fn visit_named_export(&mut self, n: &NamedExport) { self.show("NamedExport", n); n.visit_children_with(self) } + fn visit_new_expr(&mut self, n: &NewExpr) { self.show("NewExpr", n); n.visit_children_with(self) } + fn visit_null(&mut self, n: &Null) { self.show_name("Null", n); n.visit_children_with(self) } + fn visit_number(&mut self, n: &Number) { self.show("Number", n); n.visit_children_with(self) } + fn visit_object_lit(&mut self, n: &ObjectLit) { self.show("ObjectLit", n); n.visit_children_with(self) } + fn visit_object_pat(&mut self, n: &ObjectPat) { self.show("ObjectPat", n); n.visit_children_with(self) } + fn visit_object_pat_prop(&mut self, n: &ObjectPatProp) { self.show("ObjectPatProp", n); n.visit_children_with(self) } + fn visit_opt_chain_expr(&mut self, n: &OptChainExpr) { self.show("OptChainExpr", n); n.visit_children_with(self) } + fn visit_param(&mut self, n: &Param) { self.show("Param", n); n.visit_children_with(self) } + fn visit_param_or_ts_param_prop(&mut self, n: &ParamOrTsParamProp) { self.show("ParamOrTsParamProp", n); n.visit_children_with(self) } + fn visit_paren_expr(&mut self, n: &ParenExpr) { self.show("ParenExpr", n); n.visit_children_with(self) } + fn visit_pat(&mut self, n: &Pat) { self.show("Pat", n); n.visit_children_with(self) } + fn visit_pat_or_expr(&mut self, n: &PatOrExpr) { self.show("PatOrExpr", n); n.visit_children_with(self) } + fn visit_private_method(&mut self, n: &PrivateMethod) { self.show("PrivateMethod", n); n.visit_children_with(self) } + fn visit_private_name(&mut self, n: &PrivateName) { self.show("PrivateName", n); n.visit_children_with(self) } + fn visit_private_prop(&mut self, n: &PrivateProp) { self.show("PrivateProp", n); n.visit_children_with(self) } + fn visit_program(&mut self, n: &Program) { self.show("Program", n); n.visit_children_with(self) } + fn visit_prop(&mut self, n: &Prop) { self.show("Prop", n); n.visit_children_with(self) } + fn visit_prop_name(&mut self, n: &PropName) { self.show("PropName", n); n.visit_children_with(self) } + fn visit_prop_or_spread(&mut self, n: &PropOrSpread) { self.show("PropOrSpread", n); n.visit_children_with(self) } + fn visit_regex(&mut self, n: &Regex) { self.show_name("Regex", n); n.visit_children_with(self) } + fn visit_rest_pat(&mut self, n: &RestPat) { self.show("RestPat", n); n.visit_children_with(self) } + fn visit_return_stmt(&mut self, n: &ReturnStmt) { self.show("ReturnStmt", n); n.visit_children_with(self) } + fn visit_script(&mut self, n: &Script) { self.show("Script", n); n.visit_children_with(self) } + fn visit_seq_expr(&mut self, n: &SeqExpr) { self.show("SeqExpr", n); n.visit_children_with(self) } + fn visit_setter_prop(&mut self, n: &SetterProp) { self.show("SetterProp", n); n.visit_children_with(self) } + fn visit_spread_element(&mut self, n: &SpreadElement) { self.show("SpreadElement", n); n.visit_children_with(self) } + fn visit_str(&mut self, n: &Str) { self.show("Str", n); n.visit_children_with(self) } + fn visit_super(&mut self, n: &Super) { self.show("Super", n); n.visit_children_with(self) } + fn visit_switch_case(&mut self, n: &SwitchCase) { self.show("SwitchCase", n); n.visit_children_with(self) } + fn visit_switch_stmt(&mut self, n: &SwitchStmt) { self.show("SwitchStmt", n); n.visit_children_with(self) } + fn visit_tagged_tpl(&mut self, n: &TaggedTpl) { self.show("TaggedTpl", n); n.visit_children_with(self) } + fn visit_this_expr(&mut self, n: &ThisExpr) { self.show("ThisExpr", n); n.visit_children_with(self) } + fn visit_throw_stmt(&mut self, n: &ThrowStmt) { self.show("ThrowStmt", n); n.visit_children_with(self) } + fn visit_tpl(&mut self, n: &Tpl) { self.show("Tpl", n); n.visit_children_with(self) } + fn visit_tpl_element(&mut self, n: &TplElement) { self.show("TplElement", n); n.visit_children_with(self) } + fn visit_try_stmt(&mut self, n: &TryStmt) { self.show("TryStmt", n); n.visit_children_with(self) } + fn visit_ts_array_type(&mut self, n: &TsArrayType) { self.show("TsArrayType", n); n.visit_children_with(self) } + fn visit_ts_as_expr(&mut self, n: &TsAsExpr) { self.show("TsAsExpr", n); n.visit_children_with(self) } + fn visit_ts_call_signature_decl(&mut self, n: &TsCallSignatureDecl) { self.show("TsCallSignatureDecl", n); n.visit_children_with(self) } + fn visit_ts_conditional_type(&mut self, n: &TsConditionalType) { self.show("TsConditionalType", n); n.visit_children_with(self) } + fn visit_ts_const_assertion(&mut self, n: &TsConstAssertion) { self.show("TsConstAssertion", n); n.visit_children_with(self) } + fn visit_ts_construct_signature_decl(&mut self, n: &TsConstructSignatureDecl) { self.show("TsConstructSignatureDecl", n); n.visit_children_with(self) } + fn visit_ts_constructor_type(&mut self, n: &TsConstructorType) { self.show("TsConstructorType", n); n.visit_children_with(self) } + fn visit_ts_entity_name(&mut self, n: &TsEntityName) { self.show("TsEntityName", n); n.visit_children_with(self) } + fn visit_ts_enum_decl(&mut self, n: &TsEnumDecl) { self.show("TsEnumDecl", n); n.visit_children_with(self) } + fn visit_ts_enum_member(&mut self, n: &TsEnumMember) { self.show("TsEnumMember", n); n.visit_children_with(self) } + fn visit_ts_enum_member_id(&mut self, n: &TsEnumMemberId) { self.show("TsEnumMemberId", n); n.visit_children_with(self) } + fn visit_ts_export_assignment(&mut self, n: &TsExportAssignment) { self.show("TsExportAssignment", n); n.visit_children_with(self) } + fn visit_ts_expr_with_type_args(&mut self, n: &TsExprWithTypeArgs) { self.show("TsExprWithTypeArgs", n); n.visit_children_with(self) } + fn visit_ts_external_module_ref(&mut self, n: &TsExternalModuleRef) { self.show("TsExternalModuleRef", n); n.visit_children_with(self) } + fn visit_ts_fn_or_constructor_type(&mut self, n: &TsFnOrConstructorType) { self.show("TsFnOrConstructorType", n); n.visit_children_with(self) } + fn visit_ts_fn_param(&mut self, n: &TsFnParam) { self.show("TsFnParam", n); n.visit_children_with(self) } + fn visit_ts_fn_type(&mut self, n: &TsFnType) { self.show("TsFnType", n); n.visit_children_with(self) } + fn visit_ts_import_equals_decl(&mut self, n: &TsImportEqualsDecl) { self.show("TsImportEqualsDecl", n); n.visit_children_with(self) } + fn visit_ts_import_type(&mut self, n: &TsImportType) { self.show("TsImportType", n); n.visit_children_with(self) } + fn visit_ts_index_signature(&mut self, n: &TsIndexSignature) { self.show("TsIndexSignature", n); n.visit_children_with(self) } + fn visit_ts_indexed_access_type(&mut self, n: &TsIndexedAccessType) { self.show("TsIndexedAccessType", n); n.visit_children_with(self) } + fn visit_ts_infer_type(&mut self, n: &TsInferType) { self.show("TsInferType", n); n.visit_children_with(self) } + fn visit_ts_interface_body(&mut self, n: &TsInterfaceBody) { self.show("TsInterfaceBody", n); n.visit_children_with(self) } + fn visit_ts_interface_decl(&mut self, n: &TsInterfaceDecl) { self.show("TsInterfaceDecl", n); n.visit_children_with(self) } + fn visit_ts_intersection_type(&mut self, n: &TsIntersectionType) { self.show("TsIntersectionType", n); n.visit_children_with(self) } + fn visit_ts_keyword_type(&mut self, n: &TsKeywordType) { self.show("TsKeywordType", n); n.visit_children_with(self) @@ -1101,118 +1251,147 @@ impl Visit for Shower<'_> { self.show("TsLit", n); n.visit_children_with(self) } + fn visit_ts_lit_type(&mut self, n: &TsLitType) { self.show("TsLitType", n); n.visit_children_with(self) } + fn visit_ts_mapped_type(&mut self, n: &TsMappedType) { self.show("TsMappedType", n); n.visit_children_with(self) } + fn visit_ts_method_signature(&mut self, n: &TsMethodSignature) { self.show("TsMethodSignature", n); n.visit_children_with(self) } + fn visit_ts_module_block(&mut self, n: &TsModuleBlock) { self.show("TsModuleBlock", n); n.visit_children_with(self) } + fn visit_ts_module_decl(&mut self, n: &TsModuleDecl) { self.show("TsModuleDecl", n); n.visit_children_with(self) } + fn visit_ts_module_name(&mut self, n: &TsModuleName) { self.show("TsModuleName", n); n.visit_children_with(self) } + fn visit_ts_module_ref(&mut self, n: &TsModuleRef) { self.show("TsModuleRef", n); n.visit_children_with(self) } + fn visit_ts_namespace_body(&mut self, n: &TsNamespaceBody) { self.show("TsNamespaceBody", n); n.visit_children_with(self) } + fn visit_ts_namespace_decl(&mut self, n: &TsNamespaceDecl) { self.show("TsNamespaceDecl", n); n.visit_children_with(self) } + fn visit_ts_namespace_export_decl(&mut self, n: &TsNamespaceExportDecl) { self.show("TsNamespaceExportDecl", n); n.visit_children_with(self) } + fn visit_ts_non_null_expr(&mut self, n: &TsNonNullExpr) { self.show("TsNonNullExpr", n); n.visit_children_with(self) } + fn visit_ts_optional_type(&mut self, n: &TsOptionalType) { self.show("TsOptionalType", n); n.visit_children_with(self) } + fn visit_ts_param_prop(&mut self, n: &TsParamProp) { self.show("TsParamProp", n); n.visit_children_with(self) } + fn visit_ts_param_prop_param(&mut self, n: &TsParamPropParam) { self.show("TsParamPropParam", n); n.visit_children_with(self) } + fn visit_ts_parenthesized_type(&mut self, n: &TsParenthesizedType) { self.show("TsParenthesizedType", n); n.visit_children_with(self) } + fn visit_ts_property_signature(&mut self, n: &TsPropertySignature) { self.show("TsPropertySignature", n); n.visit_children_with(self) } + fn visit_ts_qualified_name(&mut self, n: &TsQualifiedName) { self.show("TsQualifiedName", n); n.visit_children_with(self) } + fn visit_ts_rest_type(&mut self, n: &TsRestType) { self.show("TsRestType", n); n.visit_children_with(self) } + fn visit_ts_this_type(&mut self, n: &TsThisType) { self.show("TsThisType", n); n.visit_children_with(self) } + fn visit_ts_this_type_or_ident(&mut self, n: &TsThisTypeOrIdent) { self.show("TsThisTypeOrIdent", n); n.visit_children_with(self) } + fn visit_ts_tuple_element(&mut self, n: &TsTupleElement) { self.show("TsTupleElement", n); n.visit_children_with(self) } + fn visit_ts_tuple_type(&mut self, n: &TsTupleType) { self.show("TsTupleType", n); n.visit_children_with(self) } + fn visit_ts_type(&mut self, n: &TsType) { self.show("TsType", n); n.visit_children_with(self) } + fn visit_ts_type_alias_decl(&mut self, n: &TsTypeAliasDecl) { self.show("TsTypeAliasDecl", n); n.visit_children_with(self) } + fn visit_ts_type_ann(&mut self, n: &TsTypeAnn) { self.show("TsTypeAnn", n); n.visit_children_with(self) } + fn visit_ts_type_assertion(&mut self, n: &TsTypeAssertion) { self.show("TsTypeAssertion", n); n.visit_children_with(self) } + fn visit_ts_type_element(&mut self, n: &TsTypeElement) { self.show("TsTypeElement", n); n.visit_children_with(self) } + fn visit_ts_type_lit(&mut self, n: &TsTypeLit) { self.show("TsTypeLit", n); n.visit_children_with(self) } + fn visit_ts_type_operator(&mut self, n: &TsTypeOperator) { self.show("TsTypeOperator", n); n.visit_children_with(self) @@ -1222,70 +1401,87 @@ impl Visit for Shower<'_> { self.show("TsTypeParam", n); n.visit_children_with(self) } + fn visit_ts_type_param_decl(&mut self, n: &TsTypeParamDecl) { self.show("TsTypeParamDecl", n); n.visit_children_with(self) } + fn visit_ts_type_param_instantiation(&mut self, n: &TsTypeParamInstantiation) { self.show("TsTypeParamInstantiation", n); n.visit_children_with(self) } + fn visit_ts_type_predicate(&mut self, n: &TsTypePredicate) { self.show("TsTypePredicate", n); n.visit_children_with(self) } + fn visit_ts_type_query(&mut self, n: &TsTypeQuery) { self.show("TsTypeQuery", n); n.visit_children_with(self) } + fn visit_ts_type_query_expr(&mut self, n: &TsTypeQueryExpr) { self.show("TsTypeQueryExpr", n); n.visit_children_with(self) } + fn visit_ts_type_ref(&mut self, n: &TsTypeRef) { self.show("TsTypeRef", n); n.visit_children_with(self) } + fn visit_ts_union_or_intersection_type(&mut self, n: &TsUnionOrIntersectionType) { self.show("TsUnionOrIntersectionType", n); n.visit_children_with(self) } + fn visit_ts_union_type(&mut self, n: &TsUnionType) { self.show("TsUnionType", n); n.visit_children_with(self) } + fn visit_unary_expr(&mut self, n: &UnaryExpr) { self.show("UnaryExpr", n); n.visit_children_with(self) } + fn visit_update_expr(&mut self, n: &UpdateExpr) { self.show("UpdateExpr", n); n.visit_children_with(self) } + fn visit_var_decl(&mut self, n: &VarDecl) { self.show("VarDecl", n); n.visit_children_with(self) } + fn visit_var_decl_or_expr(&mut self, n: &VarDeclOrExpr) { self.show("VarDeclOrExpr", n); n.visit_children_with(self) } + fn visit_var_decl_or_pat(&mut self, n: &VarDeclOrPat) { self.show("VarDeclOrPat", n); n.visit_children_with(self) } + fn visit_var_declarator(&mut self, n: &VarDeclarator) { self.show("VarDeclarator", n); n.visit_children_with(self) } + fn visit_while_stmt(&mut self, n: &WhileStmt) { self.show("WhileStmt", n); n.visit_children_with(self) } + fn visit_with_stmt(&mut self, n: &WithStmt) { self.show("WithStmt", n); n.visit_children_with(self) } + fn visit_yield_expr(&mut self, n: &YieldExpr) { self.show("YieldExpr", n); n.visit_children_with(self) diff --git a/crates/swc_ecma_minifier/tests/exec.rs b/crates/swc_ecma_minifier/tests/exec.rs index df58062ea60..679b4a17949 100644 --- a/crates/swc_ecma_minifier/tests/exec.rs +++ b/crates/swc_ecma_minifier/tests/exec.rs @@ -2,10 +2,11 @@ extern crate swc_node_base; +use std::process::Command; + use ansi_term::Color; use anyhow::{bail, Context, Error}; use serde::Deserialize; -use std::process::Command; use swc_common::{ comments::SingleThreadedComments, errors::Handler, input::SourceFileInput, sync::Lrc, FileName, Mark, SourceMap, diff --git a/crates/swc_ecma_minifier/tests/mangle.rs b/crates/swc_ecma_minifier/tests/mangle.rs index 8989ce385ec..609e78be5a4 100644 --- a/crates/swc_ecma_minifier/tests/mangle.rs +++ b/crates/swc_ecma_minifier/tests/mangle.rs @@ -1,6 +1,7 @@ #![deny(warnings)] use std::path::{Path, PathBuf}; + use swc_common::{input::SourceFileInput, sync::Lrc, FileName, Mark, SourceFile, SourceMap}; use swc_ecma_ast::*; use swc_ecma_codegen::{ diff --git a/crates/swc_ecma_parser/benches/lexer.rs b/crates/swc_ecma_parser/benches/lexer.rs index eb04b1c7c48..3badb0bded3 100644 --- a/crates/swc_ecma_parser/benches/lexer.rs +++ b/crates/swc_ecma_parser/benches/lexer.rs @@ -5,6 +5,7 @@ extern crate swc_node_base; extern crate test; use std::hint::black_box; + use swc_common::FileName; use swc_ecma_parser::{lexer::Lexer, StringInput, Syntax}; use test::Bencher; diff --git a/crates/swc_ecma_parser/examples/perf.rs b/crates/swc_ecma_parser/examples/perf.rs index 4129650c389..1ac3681dcda 100644 --- a/crates/swc_ecma_parser/examples/perf.rs +++ b/crates/swc_ecma_parser/examples/perf.rs @@ -3,6 +3,7 @@ extern crate swc_node_base; use std::{collections::hash_map::DefaultHasher, hash::Hash, hint::black_box}; + use swc_common::{self, sync::Lrc, SourceMap}; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig}; diff --git a/crates/swc_ecma_parser/src/error.rs b/crates/swc_ecma_parser/src/error.rs index f8dfeea0331..645e624e65d 100644 --- a/crates/swc_ecma_parser/src/error.rs +++ b/crates/swc_ecma_parser/src/error.rs @@ -1,13 +1,15 @@ #![allow(dead_code)] -use crate::token::Token; use std::{borrow::Cow, fmt::Debug}; + use swc_atoms::JsWord; use swc_common::{ errors::{DiagnosticBuilder, Handler}, Span, Spanned, }; +use crate::token::Token; + /// Note: this struct is 8 bytes. #[derive(Debug, Clone, PartialEq)] pub struct Error { diff --git a/crates/swc_ecma_parser/src/lexer/jsx.rs b/crates/swc_ecma_parser/src/lexer/jsx.rs index ec762bbc0ea..37daf386315 100644 --- a/crates/swc_ecma_parser/src/lexer/jsx.rs +++ b/crates/swc_ecma_parser/src/lexer/jsx.rs @@ -1,6 +1,7 @@ -use super::*; use either::Either; +use super::*; + impl<'a, I: Input> Lexer<'a, I> { pub(super) fn read_jsx_token(&mut self) -> LexResult> { debug_assert!(self.syntax.jsx()); diff --git a/crates/swc_ecma_parser/src/lexer/mod.rs b/crates/swc_ecma_parser/src/lexer/mod.rs index 12c7cb68c9c..efea359435d 100644 --- a/crates/swc_ecma_parser/src/lexer/mod.rs +++ b/crates/swc_ecma_parser/src/lexer/mod.rs @@ -1,5 +1,13 @@ //! ECMAScript lexer. +use std::{cell::RefCell, char, iter::FusedIterator, rc::Rc}; + +use either::Either::{Left, Right}; +use smallvec::{smallvec, SmallVec}; +use swc_atoms::{js_word, JsWord}; +use swc_common::{comments::Comments, BytePos, Span}; +use swc_ecma_ast::{op, EsVersion}; + use self::{comments_buffer::CommentsBuffer, state::State, util::*}; pub use self::{ input::Input, @@ -10,12 +18,6 @@ use crate::{ token::*, Context, Syntax, }; -use either::Either::{Left, Right}; -use smallvec::{smallvec, SmallVec}; -use std::{cell::RefCell, char, iter::FusedIterator, rc::Rc}; -use swc_atoms::{js_word, JsWord}; -use swc_common::{comments::Comments, BytePos, Span}; -use swc_ecma_ast::{op, EsVersion}; mod comments_buffer; pub mod input; @@ -46,8 +48,8 @@ impl From for Char { pub(crate) struct CharIter(SmallVec<[char; 7]>); impl IntoIterator for Char { - type Item = char; type IntoIter = CharIter; + type Item = char; #[allow(unsafe_code)] fn into_iter(self) -> Self::IntoIter { @@ -834,7 +836,7 @@ impl<'a, I: Input> Lexer<'a, I> { let start = self.cur_pos(); let val = self.read_int_u32(16, 0, raw)?; match val { - Some(val) if 0x0010_FFFF >= val => match char::from_u32(val) { + Some(val) if 0x0010_ffff >= val => match char::from_u32(val) { Some(c) => Ok(c.into()), None => self.error(start, SyntaxError::InvalidCodePoint)?, }, diff --git a/crates/swc_ecma_parser/src/lexer/number.rs b/crates/swc_ecma_parser/src/lexer/number.rs index be3db957ce5..cf6c9581543 100644 --- a/crates/swc_ecma_parser/src/lexer/number.rs +++ b/crates/swc_ecma_parser/src/lexer/number.rs @@ -2,14 +2,16 @@ //! //! //! See https://tc39.github.io/ecma262/#sec-literals-numeric-literals -use super::*; -use crate::error::SyntaxError; +use std::fmt::Write; + use either::Either; use num_bigint::BigInt as BigIntValue; -use std::fmt::Write; use swc_common::SyntaxContext; use tracing::trace; +use super::*; +use crate::error::SyntaxError; + impl<'a, I: Input> Lexer<'a, I> { /// Reads an integer, octal integer, or floating-point number pub(super) fn read_number( @@ -425,9 +427,10 @@ impl<'a, I: Input> Lexer<'a, I> { #[cfg(test)] mod tests { + use std::{f64::INFINITY, panic}; + use super::{input::StringInput, *}; use crate::EsConfig; - use std::{f64::INFINITY, panic}; fn lex(s: &'static str, f: F) -> Ret where @@ -566,7 +569,7 @@ mod tests { #[test] fn read_num_sep() { assert_eq!(1_000, int(10, "1_000")); - assert_eq!(0xAEBECE, int(16, "AE_BE_CE")); + assert_eq!(0xaebece, int(16, "AE_BE_CE")); assert_eq!(0b1010000110000101, int(2, "1010_0001_1000_0101")); assert_eq!(0o0666, int(8, "0_6_6_6")); } diff --git a/crates/swc_ecma_parser/src/lexer/state.rs b/crates/swc_ecma_parser/src/lexer/state.rs index a767c884357..ad255c7a85f 100644 --- a/crates/swc_ecma_parser/src/lexer/state.rs +++ b/crates/swc_ecma_parser/src/lexer/state.rs @@ -1,14 +1,16 @@ +use std::mem::take; + +use enum_kind::Kind; +#[cfg(not(debug_assertions))] +use smallvec::SmallVec; +use swc_common::BytePos; +use tracing::trace; + use super::{ comments_buffer::{BufferedComment, BufferedCommentKind}, Context, Input, Lexer, }; use crate::{error::Error, input::Tokens, lexer::util::CharExt, token::*, EsVersion, Syntax}; -use enum_kind::Kind; -#[cfg(not(debug_assertions))] -use smallvec::SmallVec; -use std::mem::take; -use swc_common::BytePos; -use tracing::trace; /// State of lexer. /// @@ -125,6 +127,7 @@ impl Tokens for Lexer<'_, I> { fn syntax(&self) -> Syntax { self.syntax } + fn target(&self) -> EsVersion { self.target } @@ -136,6 +139,7 @@ impl Tokens for Lexer<'_, I> { fn set_expr_allowed(&mut self, allow: bool) { self.set_expr_allowed(allow) } + fn token_context(&self) -> &TokenContexts { &self.state.context } @@ -167,6 +171,7 @@ impl Tokens for Lexer<'_, I> { impl<'a, I: Input> Iterator for Lexer<'a, I> { type Item = TokenAndSpan; + fn next(&mut self) -> Option { let mut start = self.cur_pos(); @@ -628,9 +633,11 @@ impl TokenContexts { pub fn len(&self) -> usize { self.0.len() } + pub fn is_empty(&self) -> bool { self.0.is_empty() } + pub fn pop(&mut self) -> Option { let opt = self.0.pop(); if cfg!(feature = "debug") { @@ -638,9 +645,11 @@ impl TokenContexts { } opt } + pub fn current(&self) -> Option { self.0.last().cloned() } + fn push(&mut self, t: TokenContext) { self.0.push(t); diff --git a/crates/swc_ecma_parser/src/lexer/tests.rs b/crates/swc_ecma_parser/src/lexer/tests.rs index 39da15adce0..73d220487a8 100644 --- a/crates/swc_ecma_parser/src/lexer/tests.rs +++ b/crates/swc_ecma_parser/src/lexer/tests.rs @@ -1,5 +1,10 @@ extern crate test; +use std::{ops::Range, str}; + +use swc_common::SyntaxContext; +use test::{black_box, Bencher}; + use super::{ state::{lex, lex_module_errors, lex_tokens, with_lexer}, *, @@ -8,9 +13,6 @@ use crate::{ error::{Error, SyntaxError}, lexer::state::lex_errors, }; -use std::{ops::Range, str}; -use swc_common::SyntaxContext; -use test::{black_box, Bencher}; fn sp(r: Range) -> Span { Span { diff --git a/crates/swc_ecma_parser/src/lexer/util.rs b/crates/swc_ecma_parser/src/lexer/util.rs index ca92dc91a96..3d21c003df1 100644 --- a/crates/swc_ecma_parser/src/lexer/util.rs +++ b/crates/swc_ecma_parser/src/lexer/util.rs @@ -5,13 +5,8 @@ //! //! //! [babylon/util/identifier.js]:https://github.com/babel/babel/blob/master/packages/babylon/src/util/identifier.js -use super::{comments_buffer::BufferedComment, input::Input, Char, LexResult, Lexer}; -use crate::{ - error::{Error, SyntaxError}, - lexer::comments_buffer::BufferedCommentKind, - Tokens, -}; use std::char; + use swc_common::{ comments::{Comment, CommentKind}, BytePos, Span, SyntaxContext, @@ -19,6 +14,13 @@ use swc_common::{ use tracing::warn; use unicode_xid::UnicodeXID; +use super::{comments_buffer::BufferedComment, input::Input, Char, LexResult, Lexer}; +use crate::{ + error::{Error, SyntaxError}, + lexer::comments_buffer::BufferedCommentKind, + Tokens, +}; + /// Collector for raw string. /// /// Methods of this struct is noop if the value is [None]. @@ -31,6 +33,7 @@ impl Raw { st.push_str(s) } } + #[inline] pub fn push(&mut self, c: char) { if let Some(ref mut st) = self.0 { @@ -78,9 +81,11 @@ impl<'a, I: Input> Lexer<'a, I> { pub(super) fn cur(&mut self) -> Option { self.input.cur() } + pub(super) fn peek(&mut self) -> Option { self.input.peek() } + pub(super) fn peek_ahead(&mut self) -> Option { self.input.peek_ahead() } @@ -88,6 +93,7 @@ impl<'a, I: Input> Lexer<'a, I> { pub(super) fn cur_pos(&mut self) -> BytePos { self.input.cur_pos() } + pub(super) fn last_pos(&self) -> BytePos { self.input.last_pos() } diff --git a/crates/swc_ecma_parser/src/lib.rs b/crates/swc_ecma_parser/src/lib.rs index a919e6d873e..169d1253754 100644 --- a/crates/swc_ecma_parser/src/lib.rs +++ b/crates/swc_ecma_parser/src/lib.rs @@ -123,12 +123,13 @@ #![allow(clippy::vec_box)] #![allow(clippy::wrong_self_convention)] +use serde::{Deserialize, Serialize}; +use swc_ecma_ast::EsVersion; + pub use self::{ lexer::input::{Input, StringInput}, parser::*, }; -use serde::{Deserialize, Serialize}; -use swc_ecma_ast::EsVersion; #[deprecated(note = "Use `EsVersion` instead")] pub type JscTarget = EsVersion; @@ -258,6 +259,7 @@ impl Syntax { Syntax::Typescript(_) => true, } } + pub fn allow_super_outside_method(self) -> bool { match self { Syntax::Es(EsConfig { diff --git a/crates/swc_ecma_parser/src/parser/class_and_fn.rs b/crates/swc_ecma_parser/src/parser/class_and_fn.rs index 1c5e318c500..c4a78ece198 100644 --- a/crates/swc_ecma_parser/src/parser/class_and_fn.rs +++ b/crates/swc_ecma_parser/src/parser/class_and_fn.rs @@ -1,9 +1,10 @@ -use super::{ident::MaybeOptionalIdentParser, *}; -use crate::{error::SyntaxError, lexer::TokenContext, parser::stmt::IsDirective, Tokens}; use either::Either; use swc_atoms::js_word; use swc_common::{Spanned, SyntaxContext}; +use super::{ident::MaybeOptionalIdentParser, *}; +use crate::{error::SyntaxError, lexer::TokenContext, parser::stmt::IsDirective, Tokens}; + /// Parser for function expression and function declaration. impl<'a, I: Tokens> Parser { pub(super) fn parse_async_fn_expr(&mut self) -> PResult> { @@ -1314,6 +1315,7 @@ impl OutputType for Box { fn finish_fn(_span: Span, ident: Option, function: Function) -> Self { Box::new(Expr::Fn(FnExpr { ident, function })) } + fn finish_class(_span: Span, ident: Option, class: Class) -> Self { Box::new(Expr::Class(ClassExpr { ident, class })) } @@ -1335,6 +1337,7 @@ impl OutputType for ExportDefaultDecl { decl: DefaultDecl::Fn(FnExpr { ident, function }), } } + fn finish_class(span: Span, ident: Option, class: Class) -> Self { ExportDefaultDecl { span, @@ -1357,6 +1360,7 @@ impl OutputType for Decl { function, }) } + fn finish_class(_: Span, ident: Ident, class: Class) -> Self { Decl::Class(ClassDecl { declare: false, @@ -1485,10 +1489,11 @@ struct MakeMethodArgs { mod tests { #![allow(unused)] - use super::*; use swc_common::DUMMY_SP as span; use swc_ecma_visit::assert_eq_ignore_span; + use super::*; + fn lhs(s: &'static str) -> Box { test_parser(s, Syntax::default(), |p| p.parse_lhs_expr()) } diff --git a/crates/swc_ecma_parser/src/parser/expr.rs b/crates/swc_ecma_parser/src/parser/expr.rs index ee564bfb27d..474ab9d45b9 100644 --- a/crates/swc_ecma_parser/src/parser/expr.rs +++ b/crates/swc_ecma_parser/src/parser/expr.rs @@ -1,10 +1,11 @@ +use either::Either; +use swc_atoms::js_word; +use swc_common::{ast_node, util::take::Take, Spanned}; + use super::{pat::PatType, util::ExprExt, *}; use crate::{ lexer::TokenContext, parser::class_and_fn::IsSimpleParameterList, token::AssignOpToken, }; -use either::Either; -use swc_atoms::js_word; -use swc_common::{ast_node, util::take::Take, Spanned}; mod ops; #[cfg(test)] @@ -1298,6 +1299,7 @@ impl<'a, I: Tokens> Parser { } } } + /// Parse call, dot, and `[]`-subscript expressions. pub(super) fn parse_lhs_expr(&mut self) -> PResult> { trace_cur!(self, parse_lhs_expr); diff --git a/crates/swc_ecma_parser/src/parser/expr/ops.rs b/crates/swc_ecma_parser/src/parser/expr/ops.rs index cd7a4d6c621..4da4b99165c 100644 --- a/crates/swc_ecma_parser/src/parser/expr/ops.rs +++ b/crates/swc_ecma_parser/src/parser/expr/ops.rs @@ -1,8 +1,9 @@ //! Parser for unary operations and binary operations. -use super::*; use swc_common::Spanned; use tracing::trace; +use super::*; + impl<'a, I: Tokens> Parser { /// Name from spec: 'LogicalORExpression' pub(super) fn parse_bin_expr(&mut self) -> PResult> { @@ -375,10 +376,11 @@ impl<'a, I: Tokens> Parser { #[cfg(test)] mod tests { - use super::*; use swc_common::DUMMY_SP as span; use swc_ecma_visit::assert_eq_ignore_span; + use super::*; + fn bin(s: &'static str) -> Box { test_parser(s, Syntax::default(), |p| p.parse_bin_expr()) } diff --git a/crates/swc_ecma_parser/src/parser/expr/tests.rs b/crates/swc_ecma_parser/src/parser/expr/tests.rs index debf6b226ad..11294d76a4a 100644 --- a/crates/swc_ecma_parser/src/parser/expr/tests.rs +++ b/crates/swc_ecma_parser/src/parser/expr/tests.rs @@ -1,12 +1,14 @@ extern crate test; -use super::*; -use crate::EsConfig; use std::hint::black_box; + use swc_common::DUMMY_SP as span; use swc_ecma_visit::assert_eq_ignore_span; use test::Bencher; +use super::*; +use crate::EsConfig; + fn syntax() -> Syntax { Syntax::Es(EsConfig { allow_super_outside_method: true, diff --git a/crates/swc_ecma_parser/src/parser/expr/verifier.rs b/crates/swc_ecma_parser/src/parser/expr/verifier.rs index 855332ca31f..ffd1cc9595f 100644 --- a/crates/swc_ecma_parser/src/parser/expr/verifier.rs +++ b/crates/swc_ecma_parser/src/parser/expr/verifier.rs @@ -1,9 +1,10 @@ -use super::*; #[cfg(feature = "verify")] use swc_common::{Span, Spanned}; #[cfg(feature = "verify")] use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use super::*; + impl<'a, I: Tokens> Parser { #[cfg(feature = "verify")] pub(in crate::parser) fn verify_expr(&mut self, expr: Box) -> PResult> { diff --git a/crates/swc_ecma_parser/src/parser/ident.rs b/crates/swc_ecma_parser/src/parser/ident.rs index 5c4658cd28b..f33e10a1582 100644 --- a/crates/swc_ecma_parser/src/parser/ident.rs +++ b/crates/swc_ecma_parser/src/parser/ident.rs @@ -1,9 +1,10 @@ //! 12.1 Identifiers -use super::*; -use crate::token::Keyword; use either::Either; use swc_atoms::js_word; +use super::*; +use crate::token::Keyword; + impl<'a, I: Tokens> Parser { pub(super) fn parse_maybe_private_name(&mut self) -> PResult> { let is_private = is!(self, '#'); diff --git a/crates/swc_ecma_parser/src/parser/input.rs b/crates/swc_ecma_parser/src/parser/input.rs index e452a49f3d7..b6179907ddc 100644 --- a/crates/swc_ecma_parser/src/parser/input.rs +++ b/crates/swc_ecma_parser/src/parser/input.rs @@ -1,3 +1,8 @@ +use std::{cell::RefCell, mem, mem::take, rc::Rc}; + +use lexer::TokenContexts; +use swc_common::{BytePos, Span}; + use super::Parser; use crate::{ error::Error, @@ -5,9 +10,6 @@ use crate::{ token::*, Context, EsVersion, Syntax, }; -use lexer::TokenContexts; -use std::{cell::RefCell, mem, mem::take, rc::Rc}; -use swc_common::{BytePos, Span}; /// Clone should be cheap if you are parsing typescript because typescript /// syntax requires backtracking. @@ -97,6 +99,7 @@ impl Tokens for TokensInput { fn syntax(&self) -> Syntax { self.syntax } + fn target(&self) -> EsVersion { self.target } @@ -159,6 +162,7 @@ impl Capturing { captured: Default::default(), } } + /// Take captured tokens pub fn take(&mut self) -> Vec { mem::take(&mut *self.captured.borrow_mut()) @@ -205,6 +209,7 @@ impl Tokens for Capturing { fn syntax(&self) -> Syntax { self.inner.syntax() } + fn target(&self) -> EsVersion { self.inner.target() } @@ -257,6 +262,7 @@ impl Parser { pub fn input(&mut self) -> &mut I { &mut self.input.iter } + pub(crate) fn input_ref(&self) -> &I { &self.input.iter } @@ -452,6 +458,7 @@ impl Buffer { pub fn syntax(&self) -> Syntax { self.iter.syntax() } + #[inline] pub fn target(&self) -> EsVersion { self.iter.target() @@ -466,10 +473,12 @@ impl Buffer { pub(crate) fn token_context(&self) -> &lexer::TokenContexts { self.iter.token_context() } + #[inline] pub(crate) fn token_context_mut(&mut self) -> &mut lexer::TokenContexts { self.iter.token_context_mut() } + #[inline] pub(crate) fn set_token_context(&mut self, c: lexer::TokenContexts) { self.iter.set_token_context(c) diff --git a/crates/swc_ecma_parser/src/parser/jsx.rs b/crates/swc_ecma_parser/src/parser/jsx.rs index 2af4d85b5ae..affc5ecd653 100644 --- a/crates/swc_ecma_parser/src/parser/jsx.rs +++ b/crates/swc_ecma_parser/src/parser/jsx.rs @@ -1,7 +1,8 @@ -use super::*; use either::Either; use swc_common::{Span, Spanned, SyntaxContext}; +use super::*; + #[cfg(test)] mod tests; diff --git a/crates/swc_ecma_parser/src/parser/jsx/tests.rs b/crates/swc_ecma_parser/src/parser/jsx/tests.rs index 5079c46e93a..f93a2896448 100644 --- a/crates/swc_ecma_parser/src/parser/jsx/tests.rs +++ b/crates/swc_ecma_parser/src/parser/jsx/tests.rs @@ -1,8 +1,9 @@ -use super::*; -use crate::parser::test_parser; use swc_common::DUMMY_SP as span; use swc_ecma_visit::assert_eq_ignore_span; +use super::*; +use crate::parser::test_parser; + fn jsx(src: &'static str) -> Box { test_parser( src, diff --git a/crates/swc_ecma_parser/src/parser/mod.rs b/crates/swc_ecma_parser/src/parser/mod.rs index 63e4283e18e..38e94a63045 100644 --- a/crates/swc_ecma_parser/src/parser/mod.rs +++ b/crates/swc_ecma_parser/src/parser/mod.rs @@ -1,4 +1,10 @@ #![deny(non_snake_case)] +use std::ops::{Deref, DerefMut}; + +use swc_atoms::JsWord; +use swc_common::{comments::Comments, input::Input, BytePos, Span}; +use swc_ecma_ast::*; + pub use self::input::{Capturing, Tokens, TokensInput}; use self::{input::Buffer, util::ParseObject}; use crate::{ @@ -7,16 +13,13 @@ use crate::{ token::{Token, Word}, Context, EsVersion, Syntax, }; -use std::ops::{Deref, DerefMut}; -use swc_atoms::JsWord; -use swc_common::{comments::Comments, input::Input, BytePos, Span}; -use swc_ecma_ast::*; #[cfg(test)] extern crate test; -use crate::error::Error; #[cfg(test)] use test::Bencher; +use crate::error::Error; + #[macro_use] mod macros; mod class_and_fn; diff --git a/crates/swc_ecma_parser/src/parser/object.rs b/crates/swc_ecma_parser/src/parser/object.rs index 8c855e0eeb4..8c77b4728ce 100644 --- a/crates/swc_ecma_parser/src/parser/object.rs +++ b/crates/swc_ecma_parser/src/parser/object.rs @@ -1,9 +1,10 @@ //! Parser for object literal. +use swc_atoms::js_word; +use swc_common::Spanned; + use super::*; use crate::{lexer::TokenContext, parser::class_and_fn::is_not_this, token::Keyword}; -use swc_atoms::js_word; -use swc_common::Spanned; impl<'a, I: Tokens> Parser { /// Parse a object literal or object pattern. diff --git a/crates/swc_ecma_parser/src/parser/pat.rs b/crates/swc_ecma_parser/src/parser/pat.rs index 2518bfab965..d84ab7c1228 100644 --- a/crates/swc_ecma_parser/src/parser/pat.rs +++ b/crates/swc_ecma_parser/src/parser/pat.rs @@ -1,12 +1,14 @@ //! 13.3.3 Destructuring Binding Patterns +use std::iter; + +use swc_atoms::js_word; +use swc_common::Spanned; + use super::{util::ExprExt, *}; use crate::{ parser::{class_and_fn::is_not_this, expr::PatOrExprOrSpread}, token::AssignOpToken, }; -use std::iter; -use swc_atoms::js_word; -use swc_common::Spanned; impl<'a, I: Tokens> Parser { pub(super) fn parse_opt_binding_ident(&mut self) -> PResult> { @@ -824,10 +826,11 @@ impl<'a, I: Tokens> Parser { #[cfg(test)] mod tests { - use super::*; use swc_common::DUMMY_SP as span; use swc_ecma_visit::assert_eq_ignore_span; + use super::*; + fn array_pat(s: &'static str) -> Pat { test_parser(s, Syntax::default(), |p| p.parse_array_binding_pat()) } diff --git a/crates/swc_ecma_parser/src/parser/stmt.rs b/crates/swc_ecma_parser/src/parser/stmt.rs index 82e1b12a7c0..41d6500c003 100644 --- a/crates/swc_ecma_parser/src/parser/stmt.rs +++ b/crates/swc_ecma_parser/src/parser/stmt.rs @@ -1,9 +1,10 @@ -use super::{pat::PatType, *}; -use crate::error::SyntaxError; use swc_atoms::js_word; use swc_common::Spanned; use typed_arena::Arena; +use super::{pat::PatType, *}; +use crate::error::SyntaxError; + mod module_item; impl<'a, I: Tokens> Parser { @@ -1192,11 +1193,12 @@ impl<'a, I: Tokens> StmtLikeParser<'a, Stmt> for Parser { #[cfg(test)] mod tests { - use super::*; - use crate::{EsConfig, TsConfig}; use swc_common::{comments::SingleThreadedComments, DUMMY_SP as span}; use swc_ecma_visit::assert_eq_ignore_span; + use super::*; + use crate::{EsConfig, TsConfig}; + fn stmt(s: &'static str) -> Stmt { test_parser(s, Syntax::default(), |p| p.parse_stmt(true)) } diff --git a/crates/swc_ecma_parser/src/parser/tests.rs b/crates/swc_ecma_parser/src/parser/tests.rs index e13b9b708cc..2385368f230 100644 --- a/crates/swc_ecma_parser/src/parser/tests.rs +++ b/crates/swc_ecma_parser/src/parser/tests.rs @@ -1,6 +1,7 @@ +use swc_common::{comments::SingleThreadedComments, BytePos}; + use super::*; use crate::{test_parser, EsConfig, TsConfig}; -use swc_common::{comments::SingleThreadedComments, BytePos}; fn program(src: &'static str) -> Program { test_parser(src, Default::default(), |p| p.parse_program()) diff --git a/crates/swc_ecma_parser/src/parser/typescript.rs b/crates/swc_ecma_parser/src/parser/typescript.rs index 44021dcc2f5..67f04a21bc8 100644 --- a/crates/swc_ecma_parser/src/parser/typescript.rs +++ b/crates/swc_ecma_parser/src/parser/typescript.rs @@ -1,9 +1,10 @@ -use super::*; -use crate::{lexer::TokenContexts, parser::class_and_fn::IsSimpleParameterList}; use either::Either; use swc_atoms::js_word; use swc_common::{Spanned, SyntaxContext}; +use super::*; +use crate::{lexer::TokenContexts, parser::class_and_fn::IsSimpleParameterList}; + impl Parser { /// `tsNextTokenCanFollowModifier` fn ts_next_token_can_follow_modifier(&mut self) -> PResult { @@ -923,6 +924,7 @@ impl Parser { type_args, }) } + /// `tsParseInterfaceDeclaration` pub(super) fn parse_ts_interface_decl(&mut self, start: BytePos) -> PResult { debug_assert!(self.input.syntax().typescript()); @@ -2658,13 +2660,14 @@ fn make_decl_declare(mut decl: Decl) -> Decl { #[cfg(test)] mod tests { - use crate::{ - lexer::Lexer, test_parser, token::*, Capturing, EsVersion, Parser, Syntax, TsConfig, - }; use swc_common::DUMMY_SP; use swc_ecma_ast::*; use swc_ecma_visit::assert_eq_ignore_span; + use crate::{ + lexer::Lexer, test_parser, token::*, Capturing, EsVersion, Parser, Syntax, TsConfig, + }; + #[test] fn issue_708_1() { let actual = test_parser( diff --git a/crates/swc_ecma_parser/src/parser/util.rs b/crates/swc_ecma_parser/src/parser/util.rs index aa1a264b46d..7d4cd601336 100644 --- a/crates/swc_ecma_parser/src/parser/util.rs +++ b/crates/swc_ecma_parser/src/parser/util.rs @@ -1,6 +1,7 @@ +use swc_atoms::js_word; + use super::*; use crate::token::Keyword; -use swc_atoms::js_word; impl Context { pub(crate) fn is_reserved(self, word: &Word) -> bool { diff --git a/crates/swc_ecma_parser/src/token.rs b/crates/swc_ecma_parser/src/token.rs index 8df5b045601..e82e73d8303 100644 --- a/crates/swc_ecma_parser/src/token.rs +++ b/crates/swc_ecma_parser/src/token.rs @@ -1,19 +1,21 @@ //! Ported from [babel/babylon][] //! //! [babel/babylon]:https://github.com/babel/babel/blob/2d378d076eb0c5fe63234a8b509886005c01d7ee/packages/babylon/src/tokenizer/types.js -pub(crate) use self::{AssignOpToken::*, BinOpToken::*, Keyword::*, Token::*}; -use crate::{error::Error, lexer::LexResult}; -use enum_kind::Kind; -use num_bigint::BigInt as BigIntValue; use std::{ borrow::Cow, fmt::{self, Debug, Display, Formatter}, }; + +use enum_kind::Kind; +use num_bigint::BigInt as BigIntValue; use swc_atoms::{js_word, JsWord}; use swc_common::{Span, Spanned}; pub(crate) use swc_ecma_ast::AssignOp as AssignOpToken; use swc_ecma_ast::BinaryOp; +pub(crate) use self::{AssignOpToken::*, BinOpToken::*, Keyword::*, Token::*}; +use crate::{error::Error, lexer::LexResult}; + #[derive(Kind, Clone, PartialEq)] #[kind(functions(starts_expr = "bool", before_expr = "bool"))] pub enum Token { diff --git a/crates/swc_ecma_parser/tests/comments.rs b/crates/swc_ecma_parser/tests/comments.rs index acde0f38be9..03c2ef9c942 100644 --- a/crates/swc_ecma_parser/tests/comments.rs +++ b/crates/swc_ecma_parser/tests/comments.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use swc_common::{ comments::SingleThreadedComments, errors::{DiagnosticBuilder, Handler}, diff --git a/crates/swc_ecma_parser/tests/jsx.rs b/crates/swc_ecma_parser/tests/jsx.rs index 7707ce7f696..8ce8615995a 100644 --- a/crates/swc_ecma_parser/tests/jsx.rs +++ b/crates/swc_ecma_parser/tests/jsx.rs @@ -1,8 +1,9 @@ -use pretty_assertions::assert_eq; use std::{ fs::read_to_string, path::{Path, PathBuf}, }; + +use pretty_assertions::assert_eq; use swc_common::{errors::Handler, sync::Lrc, SourceMap}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, PResult, Parser, StringInput}; diff --git a/crates/swc_ecma_parser/tests/span.rs b/crates/swc_ecma_parser/tests/span.rs index 9392ab8b5b9..0f4e2017f68 100644 --- a/crates/swc_ecma_parser/tests/span.rs +++ b/crates/swc_ecma_parser/tests/span.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use swc_common::{comments::SingleThreadedComments, errors::Handler, Spanned}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, EsConfig, Parser, StringInput, Syntax, TsConfig}; @@ -75,606 +76,757 @@ impl Visit for Shower<'_> { self.show("ArrayLit", n); n.visit_children_with(self) } + fn visit_array_pat(&mut self, n: &ArrayPat) { self.show("ArrayPat", n); n.visit_children_with(self) } + fn visit_arrow_expr(&mut self, n: &ArrowExpr) { self.show("ArrowExpr", n); n.visit_children_with(self) } + fn visit_assign_expr(&mut self, n: &AssignExpr) { self.show("AssignExpr", n); n.visit_children_with(self) } + fn visit_assign_pat(&mut self, n: &AssignPat) { self.show("AssignPat", n); n.visit_children_with(self) } + fn visit_assign_pat_prop(&mut self, n: &AssignPatProp) { self.show("AssignPatProp", n); n.visit_children_with(self) } + fn visit_assign_prop(&mut self, n: &AssignProp) { self.show("AssignProp", n); n.visit_children_with(self) } + fn visit_await_expr(&mut self, n: &AwaitExpr) { self.show("AwaitExpr", n); n.visit_children_with(self) } + fn visit_bin_expr(&mut self, n: &BinExpr) { self.show("BinExpr", n); n.visit_children_with(self) } + fn visit_block_stmt(&mut self, n: &BlockStmt) { self.show("BlockStmt", n); n.visit_children_with(self) } + fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) { self.show("BlockStmtOrExpr", n); n.visit_children_with(self) } + fn visit_bool(&mut self, n: &Bool) { self.show("Bool", n); n.visit_children_with(self) } + fn visit_break_stmt(&mut self, n: &BreakStmt) { self.show("BreakStmt", n); n.visit_children_with(self) } + fn visit_call_expr(&mut self, n: &CallExpr) { self.show("CallExpr", n); n.visit_children_with(self) } + fn visit_catch_clause(&mut self, n: &CatchClause) { self.show("CatchClause", n); n.visit_children_with(self) } + fn visit_class(&mut self, n: &Class) { self.show("Class", n); n.visit_children_with(self) } + fn visit_class_decl(&mut self, n: &ClassDecl) { self.show("ClassDecl", n); n.visit_children_with(self) } + fn visit_class_expr(&mut self, n: &ClassExpr) { self.show("ClassExpr", n); n.visit_children_with(self) } + fn visit_class_member(&mut self, n: &ClassMember) { self.show("ClassMember", n); n.visit_children_with(self) } + fn visit_class_method(&mut self, n: &ClassMethod) { self.show("ClassMethod", n); n.visit_children_with(self) } + fn visit_class_prop(&mut self, n: &ClassProp) { self.show("ClassProp", n); n.visit_children_with(self) } + fn visit_computed_prop_name(&mut self, n: &ComputedPropName) { self.show("ComputedPropName", n); n.visit_children_with(self) } + fn visit_cond_expr(&mut self, n: &CondExpr) { self.show("CondExpr", n); n.visit_children_with(self) } + fn visit_constructor(&mut self, n: &Constructor) { self.show("Constructor", n); n.visit_children_with(self) } + fn visit_continue_stmt(&mut self, n: &ContinueStmt) { self.show("ContinueStmt", n); n.visit_children_with(self) } + fn visit_debugger_stmt(&mut self, n: &DebuggerStmt) { self.show("DebuggerStmt", n); n.visit_children_with(self) } + fn visit_decl(&mut self, n: &Decl) { self.show("Decl", n); n.visit_children_with(self) } + fn visit_decorator(&mut self, n: &Decorator) { self.show("Decorator", n); n.visit_children_with(self) } + fn visit_default_decl(&mut self, n: &DefaultDecl) { self.show("DefaultDecl", n); n.visit_children_with(self) } + fn visit_do_while_stmt(&mut self, n: &DoWhileStmt) { self.show("DoWhileStmt", n); n.visit_children_with(self) } + fn visit_empty_stmt(&mut self, n: &EmptyStmt) { self.show("EmptyStmt", n); n.visit_children_with(self) } + fn visit_export_all(&mut self, n: &ExportAll) { self.show("ExportAll", n); n.visit_children_with(self) } + fn visit_export_decl(&mut self, n: &ExportDecl) { self.show("ExportDecl", n); n.visit_children_with(self) } + fn visit_export_default_decl(&mut self, n: &ExportDefaultDecl) { self.show("ExportDefaultDecl", n); n.visit_children_with(self) } + fn visit_export_default_expr(&mut self, n: &ExportDefaultExpr) { self.show("ExportDefaultExpr", n); n.visit_children_with(self) } + fn visit_export_default_specifier(&mut self, n: &ExportDefaultSpecifier) { self.show("ExportDefaultSpecifier", n); n.visit_children_with(self) } + fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) { self.show("ExportNamedSpecifier", n); n.visit_children_with(self) } + fn visit_export_namespace_specifier(&mut self, n: &ExportNamespaceSpecifier) { self.show("ExportNamespaceSpecifier", n); n.visit_children_with(self) } + fn visit_export_specifier(&mut self, n: &ExportSpecifier) { self.show("ExportSpecifier", n); n.visit_children_with(self) } + fn visit_expr(&mut self, n: &Expr) { self.show("Expr", n); n.visit_children_with(self) } + fn visit_expr_or_spread(&mut self, n: &ExprOrSpread) { self.show("ExprOrSpread", n); n.visit_children_with(self) } + fn visit_callee(&mut self, n: &Callee) { self.show("Callee", n); n.visit_children_with(self) } + fn visit_expr_stmt(&mut self, n: &ExprStmt) { self.show("ExprStmt", n); n.visit_children_with(self) } + fn visit_fn_decl(&mut self, n: &FnDecl) { self.show("FnDecl", n); n.visit_children_with(self) } + fn visit_fn_expr(&mut self, n: &FnExpr) { self.show("FnExpr", n); n.visit_children_with(self) } + fn visit_for_in_stmt(&mut self, n: &ForInStmt) { self.show("ForInStmt", n); n.visit_children_with(self) } + fn visit_for_of_stmt(&mut self, n: &ForOfStmt) { self.show("ForOfStmt", n); n.visit_children_with(self) } + fn visit_for_stmt(&mut self, n: &ForStmt) { self.show("ForStmt", n); n.visit_children_with(self) } + fn visit_function(&mut self, n: &Function) { self.show("Function", n); n.visit_children_with(self) } + fn visit_getter_prop(&mut self, n: &GetterProp) { self.show("GetterProp", n); n.visit_children_with(self) } + fn visit_ident(&mut self, n: &Ident) { self.show("Ident", n); n.visit_children_with(self) } + fn visit_if_stmt(&mut self, n: &IfStmt) { self.show("IfStmt", n); n.visit_children_with(self) } + fn visit_import_decl(&mut self, n: &ImportDecl) { self.show("ImportDecl", n); n.visit_children_with(self) } + fn visit_import_default_specifier(&mut self, n: &ImportDefaultSpecifier) { self.show("ImportDefaultSpecifier", n); n.visit_children_with(self) } + fn visit_import_named_specifier(&mut self, n: &ImportNamedSpecifier) { self.show("ImportNamedSpecifier", n); n.visit_children_with(self) } + fn visit_import_specifier(&mut self, n: &ImportSpecifier) { self.show("ImportSpecifier", n); n.visit_children_with(self) } + fn visit_import_star_as_specifier(&mut self, n: &ImportStarAsSpecifier) { self.show("ImportStarAsSpecifier", n); n.visit_children_with(self) } + fn visit_invalid(&mut self, n: &Invalid) { self.show("Invalid", n); n.visit_children_with(self) } + fn visit_jsx_attr(&mut self, n: &JSXAttr) { self.show("JSXAttr", n); n.visit_children_with(self) } + fn visit_jsx_attr_name(&mut self, n: &JSXAttrName) { self.show("JSXAttrName", n); n.visit_children_with(self) } + fn visit_jsx_attr_or_spread(&mut self, n: &JSXAttrOrSpread) { self.show("JSXAttrOrSpread", n); n.visit_children_with(self) } + fn visit_jsx_attr_value(&mut self, n: &JSXAttrValue) { self.show("JSXAttrValue", n); n.visit_children_with(self) } + fn visit_jsx_closing_element(&mut self, n: &JSXClosingElement) { self.show("JSXClosingElement", n); n.visit_children_with(self) } + fn visit_jsx_closing_fragment(&mut self, n: &JSXClosingFragment) { self.show("JSXClosingFragment", n); n.visit_children_with(self) } + fn visit_jsx_element(&mut self, n: &JSXElement) { self.show("JSXElement", n); n.visit_children_with(self) } + fn visit_jsx_element_child(&mut self, n: &JSXElementChild) { self.show("JSXElementChild", n); n.visit_children_with(self) } + fn visit_jsx_element_name(&mut self, n: &JSXElementName) { self.show("JSXElementName", n); n.visit_children_with(self) } + fn visit_jsx_empty_expr(&mut self, n: &JSXEmptyExpr) { self.show("JSXEmptyExpr", n); n.visit_children_with(self) } + fn visit_jsx_expr(&mut self, n: &JSXExpr) { self.show("JSXExpr", n); n.visit_children_with(self) } + fn visit_jsx_expr_container(&mut self, n: &JSXExprContainer) { self.show("JSXExprContainer", n); n.visit_children_with(self) } + fn visit_jsx_fragment(&mut self, n: &JSXFragment) { self.show("JSXFragment", n); n.visit_children_with(self) } + fn visit_jsx_member_expr(&mut self, n: &JSXMemberExpr) { self.show("JSXMemberExpr", n); n.visit_children_with(self) } + fn visit_jsx_namespaced_name(&mut self, n: &JSXNamespacedName) { self.show("JSXNamespacedName", n); n.visit_children_with(self) } + fn visit_jsx_object(&mut self, n: &JSXObject) { self.show("JSXObject", n); n.visit_children_with(self) } + fn visit_jsx_opening_element(&mut self, n: &JSXOpeningElement) { self.show("JSXOpeningElement", n); n.visit_children_with(self) } + fn visit_jsx_opening_fragment(&mut self, n: &JSXOpeningFragment) { self.show("JSXOpeningFragment", n); n.visit_children_with(self) } + fn visit_jsx_spread_child(&mut self, n: &JSXSpreadChild) { self.show("JSXSpreadChild", n); n.visit_children_with(self) } + fn visit_jsx_text(&mut self, n: &JSXText) { self.show("JSXText", n); n.visit_children_with(self) } + fn visit_key_value_pat_prop(&mut self, n: &KeyValuePatProp) { self.show("KeyValuePatProp", n); n.visit_children_with(self) } + fn visit_key_value_prop(&mut self, n: &KeyValueProp) { self.show("KeyValueProp", n); n.visit_children_with(self) } + fn visit_labeled_stmt(&mut self, n: &LabeledStmt) { self.show("LabeledStmt", n); n.visit_children_with(self) } + fn visit_lit(&mut self, n: &Lit) { self.show("Lit", n); n.visit_children_with(self) } + fn visit_member_expr(&mut self, n: &MemberExpr) { self.show("MemberExpr", n); n.visit_children_with(self) } + fn visit_meta_prop_expr(&mut self, n: &MetaPropExpr) { self.show("MetaPropExpr", n); n.visit_children_with(self) } + fn visit_method_prop(&mut self, n: &MethodProp) { self.show("MethodProp", n); n.visit_children_with(self) } + fn visit_module(&mut self, n: &Module) { self.show("Module", n); n.visit_children_with(self) } + fn visit_module_decl(&mut self, n: &ModuleDecl) { self.show("ModuleDecl", n); n.visit_children_with(self) } + fn visit_module_item(&mut self, n: &ModuleItem) { self.show("ModuleItem", n); n.visit_children_with(self) } + fn visit_named_export(&mut self, n: &NamedExport) { self.show("NamedExport", n); n.visit_children_with(self) } + fn visit_new_expr(&mut self, n: &NewExpr) { self.show("NewExpr", n); n.visit_children_with(self) } + fn visit_null(&mut self, n: &Null) { self.show("Null", n); n.visit_children_with(self) } + fn visit_number(&mut self, n: &Number) { self.show("Number", n); n.visit_children_with(self) } + fn visit_object_lit(&mut self, n: &ObjectLit) { self.show("ObjectLit", n); n.visit_children_with(self) } + fn visit_object_pat(&mut self, n: &ObjectPat) { self.show("ObjectPat", n); n.visit_children_with(self) } + fn visit_object_pat_prop(&mut self, n: &ObjectPatProp) { self.show("ObjectPatProp", n); n.visit_children_with(self) } + fn visit_opt_chain_expr(&mut self, n: &OptChainExpr) { self.show("OptChainExpr", n); n.visit_children_with(self) } + fn visit_param(&mut self, n: &Param) { self.show("Param", n); n.visit_children_with(self) } + fn visit_param_or_ts_param_prop(&mut self, n: &ParamOrTsParamProp) { self.show("ParamOrTsParamProp", n); n.visit_children_with(self) } + fn visit_paren_expr(&mut self, n: &ParenExpr) { self.show("ParenExpr", n); n.visit_children_with(self) } + fn visit_pat(&mut self, n: &Pat) { self.show("Pat", n); n.visit_children_with(self) } + fn visit_pat_or_expr(&mut self, n: &PatOrExpr) { self.show("PatOrExpr", n); n.visit_children_with(self) } + fn visit_private_method(&mut self, n: &PrivateMethod) { self.show("PrivateMethod", n); n.visit_children_with(self) } + fn visit_private_name(&mut self, n: &PrivateName) { self.show("PrivateName", n); n.visit_children_with(self) } + fn visit_private_prop(&mut self, n: &PrivateProp) { self.show("PrivateProp", n); n.visit_children_with(self) } + fn visit_program(&mut self, n: &Program) { self.show("Program", n); n.visit_children_with(self) } + fn visit_prop(&mut self, n: &Prop) { self.show("Prop", n); n.visit_children_with(self) } + fn visit_prop_name(&mut self, n: &PropName) { self.show("PropName", n); n.visit_children_with(self) } + fn visit_prop_or_spread(&mut self, n: &PropOrSpread) { self.show("PropOrSpread", n); n.visit_children_with(self) } + fn visit_regex(&mut self, n: &Regex) { self.show("Regex", n); n.visit_children_with(self) } + fn visit_rest_pat(&mut self, n: &RestPat) { self.show("RestPat", n); n.visit_children_with(self) } + fn visit_return_stmt(&mut self, n: &ReturnStmt) { self.show("ReturnStmt", n); n.visit_children_with(self) } + fn visit_script(&mut self, n: &Script) { self.show("Script", n); n.visit_children_with(self) } + fn visit_seq_expr(&mut self, n: &SeqExpr) { self.show("SeqExpr", n); n.visit_children_with(self) } + fn visit_setter_prop(&mut self, n: &SetterProp) { self.show("SetterProp", n); n.visit_children_with(self) } + fn visit_spread_element(&mut self, n: &SpreadElement) { self.show("SpreadElement", n); n.visit_children_with(self) } + fn visit_stmt(&mut self, n: &Stmt) { self.show("Stmt", n); n.visit_children_with(self) } + fn visit_str(&mut self, n: &Str) { self.show("Str", n); n.visit_children_with(self) } + fn visit_super(&mut self, n: &Super) { self.show("Super", n); n.visit_children_with(self) } + fn visit_switch_case(&mut self, n: &SwitchCase) { self.show("SwitchCase", n); n.visit_children_with(self) } + fn visit_switch_stmt(&mut self, n: &SwitchStmt) { self.show("SwitchStmt", n); n.visit_children_with(self) } + fn visit_tagged_tpl(&mut self, n: &TaggedTpl) { self.show("TaggedTpl", n); n.visit_children_with(self) } + fn visit_this_expr(&mut self, n: &ThisExpr) { self.show("ThisExpr", n); n.visit_children_with(self) } + fn visit_throw_stmt(&mut self, n: &ThrowStmt) { self.show("ThrowStmt", n); n.visit_children_with(self) } + fn visit_tpl(&mut self, n: &Tpl) { self.show("Tpl", n); n.visit_children_with(self) } + fn visit_tpl_element(&mut self, n: &TplElement) { self.show("TplElement", n); n.visit_children_with(self) } + fn visit_try_stmt(&mut self, n: &TryStmt) { self.show("TryStmt", n); n.visit_children_with(self) } + fn visit_ts_array_type(&mut self, n: &TsArrayType) { self.show("TsArrayType", n); n.visit_children_with(self) } + fn visit_ts_as_expr(&mut self, n: &TsAsExpr) { self.show("TsAsExpr", n); n.visit_children_with(self) } + fn visit_ts_call_signature_decl(&mut self, n: &TsCallSignatureDecl) { self.show("TsCallSignatureDecl", n); n.visit_children_with(self) } + fn visit_ts_conditional_type(&mut self, n: &TsConditionalType) { self.show("TsConditionalType", n); n.visit_children_with(self) } + fn visit_ts_const_assertion(&mut self, n: &TsConstAssertion) { self.show("TsConstAssertion", n); n.visit_children_with(self) } + fn visit_ts_construct_signature_decl(&mut self, n: &TsConstructSignatureDecl) { self.show("TsConstructSignatureDecl", n); n.visit_children_with(self) } + fn visit_ts_constructor_type(&mut self, n: &TsConstructorType) { self.show("TsConstructorType", n); n.visit_children_with(self) } + fn visit_ts_entity_name(&mut self, n: &TsEntityName) { self.show("TsEntityName", n); n.visit_children_with(self) } + fn visit_ts_enum_decl(&mut self, n: &TsEnumDecl) { self.show("TsEnumDecl", n); n.visit_children_with(self) } + fn visit_ts_enum_member(&mut self, n: &TsEnumMember) { self.show("TsEnumMember", n); n.visit_children_with(self) } + fn visit_ts_enum_member_id(&mut self, n: &TsEnumMemberId) { self.show("TsEnumMemberId", n); n.visit_children_with(self) } + fn visit_ts_export_assignment(&mut self, n: &TsExportAssignment) { self.show("TsExportAssignment", n); n.visit_children_with(self) } + fn visit_ts_expr_with_type_args(&mut self, n: &TsExprWithTypeArgs) { self.show("TsExprWithTypeArgs", n); n.visit_children_with(self) } + fn visit_ts_external_module_ref(&mut self, n: &TsExternalModuleRef) { self.show("TsExternalModuleRef", n); n.visit_children_with(self) } + fn visit_ts_fn_or_constructor_type(&mut self, n: &TsFnOrConstructorType) { self.show("TsFnOrConstructorType", n); n.visit_children_with(self) } + fn visit_ts_fn_param(&mut self, n: &TsFnParam) { self.show("TsFnParam", n); n.visit_children_with(self) } + fn visit_ts_fn_type(&mut self, n: &TsFnType) { self.show("TsFnType", n); n.visit_children_with(self) } + fn visit_ts_import_equals_decl(&mut self, n: &TsImportEqualsDecl) { self.show("TsImportEqualsDecl", n); n.visit_children_with(self) } + fn visit_ts_import_type(&mut self, n: &TsImportType) { self.show("TsImportType", n); n.visit_children_with(self) } + fn visit_ts_index_signature(&mut self, n: &TsIndexSignature) { self.show("TsIndexSignature", n); n.visit_children_with(self) } + fn visit_ts_indexed_access_type(&mut self, n: &TsIndexedAccessType) { self.show("TsIndexedAccessType", n); n.visit_children_with(self) } + fn visit_ts_infer_type(&mut self, n: &TsInferType) { self.show("TsInferType", n); n.visit_children_with(self) } + fn visit_ts_interface_body(&mut self, n: &TsInterfaceBody) { self.show("TsInterfaceBody", n); n.visit_children_with(self) } + fn visit_ts_interface_decl(&mut self, n: &TsInterfaceDecl) { self.show("TsInterfaceDecl", n); n.visit_children_with(self) } + fn visit_ts_intersection_type(&mut self, n: &TsIntersectionType) { self.show("TsIntersectionType", n); n.visit_children_with(self) } + fn visit_ts_keyword_type(&mut self, n: &TsKeywordType) { self.show("TsKeywordType", n); n.visit_children_with(self) @@ -684,118 +836,147 @@ impl Visit for Shower<'_> { self.show("TsLit", n); n.visit_children_with(self) } + fn visit_ts_lit_type(&mut self, n: &TsLitType) { self.show("TsLitType", n); n.visit_children_with(self) } + fn visit_ts_mapped_type(&mut self, n: &TsMappedType) { self.show("TsMappedType", n); n.visit_children_with(self) } + fn visit_ts_method_signature(&mut self, n: &TsMethodSignature) { self.show("TsMethodSignature", n); n.visit_children_with(self) } + fn visit_ts_module_block(&mut self, n: &TsModuleBlock) { self.show("TsModuleBlock", n); n.visit_children_with(self) } + fn visit_ts_module_decl(&mut self, n: &TsModuleDecl) { self.show("TsModuleDecl", n); n.visit_children_with(self) } + fn visit_ts_module_name(&mut self, n: &TsModuleName) { self.show("TsModuleName", n); n.visit_children_with(self) } + fn visit_ts_module_ref(&mut self, n: &TsModuleRef) { self.show("TsModuleRef", n); n.visit_children_with(self) } + fn visit_ts_namespace_body(&mut self, n: &TsNamespaceBody) { self.show("TsNamespaceBody", n); n.visit_children_with(self) } + fn visit_ts_namespace_decl(&mut self, n: &TsNamespaceDecl) { self.show("TsNamespaceDecl", n); n.visit_children_with(self) } + fn visit_ts_namespace_export_decl(&mut self, n: &TsNamespaceExportDecl) { self.show("TsNamespaceExportDecl", n); n.visit_children_with(self) } + fn visit_ts_non_null_expr(&mut self, n: &TsNonNullExpr) { self.show("TsNonNullExpr", n); n.visit_children_with(self) } + fn visit_ts_optional_type(&mut self, n: &TsOptionalType) { self.show("TsOptionalType", n); n.visit_children_with(self) } + fn visit_ts_param_prop(&mut self, n: &TsParamProp) { self.show("TsParamProp", n); n.visit_children_with(self) } + fn visit_ts_param_prop_param(&mut self, n: &TsParamPropParam) { self.show("TsParamPropParam", n); n.visit_children_with(self) } + fn visit_ts_parenthesized_type(&mut self, n: &TsParenthesizedType) { self.show("TsParenthesizedType", n); n.visit_children_with(self) } + fn visit_ts_property_signature(&mut self, n: &TsPropertySignature) { self.show("TsPropertySignature", n); n.visit_children_with(self) } + fn visit_ts_qualified_name(&mut self, n: &TsQualifiedName) { self.show("TsQualifiedName", n); n.visit_children_with(self) } + fn visit_ts_rest_type(&mut self, n: &TsRestType) { self.show("TsRestType", n); n.visit_children_with(self) } + fn visit_ts_this_type(&mut self, n: &TsThisType) { self.show("TsThisType", n); n.visit_children_with(self) } + fn visit_ts_this_type_or_ident(&mut self, n: &TsThisTypeOrIdent) { self.show("TsThisTypeOrIdent", n); n.visit_children_with(self) } + fn visit_ts_tuple_element(&mut self, n: &TsTupleElement) { self.show("TsTupleElement", n); n.visit_children_with(self) } + fn visit_ts_tuple_type(&mut self, n: &TsTupleType) { self.show("TsTupleType", n); n.visit_children_with(self) } + fn visit_ts_type(&mut self, n: &TsType) { self.show("TsType", n); n.visit_children_with(self) } + fn visit_ts_type_alias_decl(&mut self, n: &TsTypeAliasDecl) { self.show("TsTypeAliasDecl", n); n.visit_children_with(self) } + fn visit_ts_type_ann(&mut self, n: &TsTypeAnn) { self.show("TsTypeAnn", n); n.visit_children_with(self) } + fn visit_ts_type_assertion(&mut self, n: &TsTypeAssertion) { self.show("TsTypeAssertion", n); n.visit_children_with(self) } + fn visit_ts_type_element(&mut self, n: &TsTypeElement) { self.show("TsTypeElement", n); n.visit_children_with(self) } + fn visit_ts_type_lit(&mut self, n: &TsTypeLit) { self.show("TsTypeLit", n); n.visit_children_with(self) } + fn visit_ts_type_operator(&mut self, n: &TsTypeOperator) { self.show("TsTypeOperator", n); n.visit_children_with(self) @@ -805,70 +986,87 @@ impl Visit for Shower<'_> { self.show("TsTypeParam", n); n.visit_children_with(self) } + fn visit_ts_type_param_decl(&mut self, n: &TsTypeParamDecl) { self.show("TsTypeParamDecl", n); n.visit_children_with(self) } + fn visit_ts_type_param_instantiation(&mut self, n: &TsTypeParamInstantiation) { self.show("TsTypeParamInstantiation", n); n.visit_children_with(self) } + fn visit_ts_type_predicate(&mut self, n: &TsTypePredicate) { self.show("TsTypePredicate", n); n.visit_children_with(self) } + fn visit_ts_type_query(&mut self, n: &TsTypeQuery) { self.show("TsTypeQuery", n); n.visit_children_with(self) } + fn visit_ts_type_query_expr(&mut self, n: &TsTypeQueryExpr) { self.show("TsTypeQueryExpr", n); n.visit_children_with(self) } + fn visit_ts_type_ref(&mut self, n: &TsTypeRef) { self.show("TsTypeRef", n); n.visit_children_with(self) } + fn visit_ts_union_or_intersection_type(&mut self, n: &TsUnionOrIntersectionType) { self.show("TsUnionOrIntersectionType", n); n.visit_children_with(self) } + fn visit_ts_union_type(&mut self, n: &TsUnionType) { self.show("TsUnionType", n); n.visit_children_with(self) } + fn visit_unary_expr(&mut self, n: &UnaryExpr) { self.show("UnaryExpr", n); n.visit_children_with(self) } + fn visit_update_expr(&mut self, n: &UpdateExpr) { self.show("UpdateExpr", n); n.visit_children_with(self) } + fn visit_var_decl(&mut self, n: &VarDecl) { self.show("VarDecl", n); n.visit_children_with(self) } + fn visit_var_decl_or_expr(&mut self, n: &VarDeclOrExpr) { self.show("VarDeclOrExpr", n); n.visit_children_with(self) } + fn visit_var_decl_or_pat(&mut self, n: &VarDeclOrPat) { self.show("VarDeclOrPat", n); n.visit_children_with(self) } + fn visit_var_declarator(&mut self, n: &VarDeclarator) { self.show("VarDeclarator", n); n.visit_children_with(self) } + fn visit_while_stmt(&mut self, n: &WhileStmt) { self.show("WhileStmt", n); n.visit_children_with(self) } + fn visit_with_stmt(&mut self, n: &WithStmt) { self.show("WithStmt", n); n.visit_children_with(self) } + fn visit_yield_expr(&mut self, n: &YieldExpr) { self.show("YieldExpr", n); n.visit_children_with(self) diff --git a/crates/swc_ecma_parser/tests/test262.rs b/crates/swc_ecma_parser/tests/test262.rs index 65e4ecc5648..49f4a4b950c 100644 --- a/crates/swc_ecma_parser/tests/test262.rs +++ b/crates/swc_ecma_parser/tests/test262.rs @@ -2,13 +2,14 @@ extern crate test; -use common::Normalizer; use std::{ env, fs::{read_dir, File}, io::{self, Read}, path::Path, }; + +use common::Normalizer; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, PResult, Parser, StringInput, Syntax}; use swc_ecma_visit::FoldWith; diff --git a/crates/swc_ecma_parser/tests/typescript.rs b/crates/swc_ecma_parser/tests/typescript.rs index 2b063e4a212..10fc1767282 100644 --- a/crates/swc_ecma_parser/tests/typescript.rs +++ b/crates/swc_ecma_parser/tests/typescript.rs @@ -1,18 +1,20 @@ #![allow(clippy::needless_update)] -use crate::common::Normalizer; -use pretty_assertions::assert_eq; use std::{ fs::File, io::Read, path::{Path, PathBuf}, }; + +use pretty_assertions::assert_eq; use swc_common::{comments::SingleThreadedComments, FileName}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, PResult, Parser, StringInput, Syntax, TsConfig}; use swc_ecma_visit::FoldWith; use testing::StdErr; +use crate::common::Normalizer; + #[path = "common/mod.rs"] mod common; diff --git a/crates/swc_ecma_preset_env/src/corejs2/builtin.rs b/crates/swc_ecma_preset_env/src/corejs2/builtin.rs index 27eef47c81c..4fd6d2323ce 100644 --- a/crates/swc_ecma_preset_env/src/corejs2/builtin.rs +++ b/crates/swc_ecma_preset_env/src/corejs2/builtin.rs @@ -1,7 +1,8 @@ -use crate::{BrowserData, Versions}; use once_cell::sync::Lazy; use swc_common::collections::AHashMap; +use crate::{BrowserData, Versions}; + pub(crate) static BUILTINS: Lazy> = Lazy::new(|| { let map: AHashMap<_, BrowserData>> = serde_json::from_str(include_str!("builtin.json")).expect("failed to parse json"); diff --git a/crates/swc_ecma_preset_env/src/corejs2/entry.rs b/crates/swc_ecma_preset_env/src/corejs2/entry.rs index b16a3afadb8..c192803aa7e 100644 --- a/crates/swc_ecma_preset_env/src/corejs2/entry.rs +++ b/crates/swc_ecma_preset_env/src/corejs2/entry.rs @@ -1,11 +1,12 @@ -use super::builtin::BUILTINS; -use crate::{version::should_enable, Versions}; use indexmap::IndexSet; use swc_atoms::js_word; use swc_common::{util::move_map::MoveMap, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{Fold, FoldWith}; +use super::builtin::BUILTINS; +use crate::{version::should_enable, Versions}; + #[derive(Debug)] pub struct Entry { is_any_target: bool, diff --git a/crates/swc_ecma_preset_env/src/corejs2/mod.rs b/crates/swc_ecma_preset_env/src/corejs2/mod.rs index 0117dc2bc19..cc19c654627 100644 --- a/crates/swc_ecma_preset_env/src/corejs2/mod.rs +++ b/crates/swc_ecma_preset_env/src/corejs2/mod.rs @@ -1,14 +1,15 @@ +use indexmap::IndexSet; +use swc_atoms::{js_word, JsWord}; +use swc_common::DUMMY_SP; +use swc_ecma_ast::*; +use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; + pub(crate) use self::entry::Entry; use self::{ builtin::BUILTINS, data::{BUILTIN_TYPES, INSTANCE_PROPERTIES, STATIC_PROPERTIES}, }; use crate::{util::DataMapExt, version::should_enable, Versions}; -use indexmap::IndexSet; -use swc_atoms::{js_word, JsWord}; -use swc_common::DUMMY_SP; -use swc_ecma_ast::*; -use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; mod builtin; mod data; diff --git a/crates/swc_ecma_preset_env/src/corejs3/compat.rs b/crates/swc_ecma_preset_env/src/corejs3/compat.rs index 7cc6cc1544a..b64d6696d6b 100644 --- a/crates/swc_ecma_preset_env/src/corejs3/compat.rs +++ b/crates/swc_ecma_preset_env/src/corejs3/compat.rs @@ -1,9 +1,10 @@ //! Ported from https://github.com/zloirock/core-js/tree/master/packages/core-js-compat -use crate::Versions; use once_cell::sync::Lazy; use swc_common::collections::AHashMap; +use crate::Versions; + pub static DATA: Lazy> = Lazy::new(|| { serde_json::from_str(include_str!("compat.json")) .expect("failed parse corejs3-compat data.json") diff --git a/crates/swc_ecma_preset_env/src/corejs3/entry.rs b/crates/swc_ecma_preset_env/src/corejs3/entry.rs index d89addbdbd7..2307266fe05 100644 --- a/crates/swc_ecma_preset_env/src/corejs3/entry.rs +++ b/crates/swc_ecma_preset_env/src/corejs3/entry.rs @@ -1,5 +1,3 @@ -use super::compat::DATA as CORE_JS_COMPAT_DATA; -use crate::{version::should_enable, Version, Versions}; use indexmap::IndexSet; use once_cell::sync::Lazy; use swc_atoms::js_word; @@ -7,6 +5,9 @@ use swc_common::{collections::AHashMap, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{Fold, FoldWith}; +use super::compat::DATA as CORE_JS_COMPAT_DATA; +use crate::{version::should_enable, Version, Versions}; + static ENTRIES: Lazy>> = Lazy::new(|| { serde_json::from_str::>>(include_str!("entries.json")) .expect("failed to parse entries.json from core js 3") diff --git a/crates/swc_ecma_preset_env/src/corejs3/usage.rs b/crates/swc_ecma_preset_env/src/corejs3/usage.rs index 765df3fc033..a67ce52e81d 100644 --- a/crates/swc_ecma_preset_env/src/corejs3/usage.rs +++ b/crates/swc_ecma_preset_env/src/corejs3/usage.rs @@ -1,3 +1,9 @@ +use indexmap::IndexSet; +use swc_atoms::{js_word, JsWord}; +use swc_common::DUMMY_SP; +use swc_ecma_ast::*; +use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; + use super::data::BUILTINS; use crate::{ corejs3::{ @@ -11,11 +17,6 @@ use crate::{ version::should_enable, Versions, }; -use indexmap::IndexSet; -use swc_atoms::{js_word, JsWord}; -use swc_common::DUMMY_SP; -use swc_ecma_ast::*; -use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; pub(crate) struct UsageVisitor { shipped_proposals: bool, @@ -86,6 +87,7 @@ impl UsageVisitor { self.add(features) } } + fn add_property_deps(&mut self, obj: &Expr, prop: &JsWord) { let obj = match obj { Expr::Ident(i) => &i.sym, diff --git a/crates/swc_ecma_preset_env/src/lib.rs b/crates/swc_ecma_preset_env/src/lib.rs index 79f9d2f4e69..eb5227c9870 100644 --- a/crates/swc_ecma_preset_env/src/lib.rs +++ b/crates/swc_ecma_preset_env/src/lib.rs @@ -2,13 +2,13 @@ #![allow(dead_code)] #![recursion_limit = "256"] -pub use self::{transform_data::Feature, version::Version}; +use std::path::PathBuf; + use anyhow::{Context, Error}; use dashmap::DashMap; use once_cell::sync::Lazy; use serde::Deserialize; use st_map::StaticMap; -use std::path::PathBuf; use swc_atoms::{js_word, JsWord}; use swc_common::{ chain, @@ -24,6 +24,8 @@ use swc_ecma_transforms::{ use swc_ecma_utils::prepend_stmts; use swc_ecma_visit::{Fold, FoldWith, VisitWith}; +pub use self::{transform_data::Feature, version::Version}; + #[macro_use] mod util; mod corejs2; diff --git a/crates/swc_ecma_preset_env/src/transform_data.rs b/crates/swc_ecma_preset_env/src/transform_data.rs index b1675f453d3..bc4b4f85c84 100644 --- a/crates/swc_ecma_preset_env/src/transform_data.rs +++ b/crates/swc_ecma_preset_env/src/transform_data.rs @@ -1,8 +1,9 @@ -use crate::{version::should_enable, BrowserData, Version, Versions}; use once_cell::sync::Lazy; use string_enum::StringEnum; use swc_common::collections::AHashMap; +use crate::{version::should_enable, BrowserData, Version, Versions}; + impl Feature { pub fn should_enable(self, target: Versions, bugfixes: bool, default: bool) -> bool { let f = if bugfixes { diff --git a/crates/swc_ecma_preset_env/src/version.rs b/crates/swc_ecma_preset_env/src/version.rs index 6fbb80f0fa8..82ea98b8cc0 100644 --- a/crates/swc_ecma_preset_env/src/version.rs +++ b/crates/swc_ecma_preset_env/src/version.rs @@ -1,7 +1,9 @@ -use crate::Versions; -use serde::{de, de::Visitor, Deserialize, Deserializer}; use std::{cmp, cmp::Ordering, fmt, str::FromStr}; +use serde::{de, de::Visitor, Deserialize, Deserializer}; + +use crate::Versions; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Version { pub major: u16, diff --git a/crates/swc_ecma_preset_env/tests/test.rs b/crates/swc_ecma_preset_env/tests/test.rs index 12e10a33680..7d7a18f67f1 100644 --- a/crates/swc_ecma_preset_env/tests/test.rs +++ b/crates/swc_ecma_preset_env/tests/test.rs @@ -1,8 +1,5 @@ #![allow(dead_code)] -use pretty_assertions::assert_eq; -use serde::Deserialize; -use serde_json::Value; use std::{ cmp::Ordering, env, @@ -11,6 +8,10 @@ use std::{ io::Read, path::{Path, PathBuf}, }; + +use pretty_assertions::assert_eq; +use serde::Deserialize; +use serde_json::Value; use swc_common::{ chain, collections::AHashMap, comments::SingleThreadedComments, input::StringInput, FromVariant, Mark, diff --git a/crates/swc_ecma_transforms/src/lib.rs b/crates/swc_ecma_transforms/src/lib.rs index 380b7d6f6a9..e338bfb1a1b 100644 --- a/crates/swc_ecma_transforms/src/lib.rs +++ b/crates/swc_ecma_transforms/src/lib.rs @@ -2,11 +2,6 @@ #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(unused)] -pub use self::{ - fixer::fixer, - hygiene::hygiene, - resolver::{resolver, resolver_with_mark}, -}; pub use swc_ecma_transforms_base::{ assumptions::Assumptions, fixer, helpers, hygiene, pass, perf, resolver, }; @@ -31,3 +26,9 @@ pub use swc_ecma_transforms_react as react; #[cfg(feature = "swc_ecma_transforms_typescript")] #[cfg_attr(docsrs, doc(cfg(feature = "typescript")))] pub use swc_ecma_transforms_typescript as typescript; + +pub use self::{ + fixer::fixer, + hygiene::hygiene, + resolver::{resolver, resolver_with_mark}, +}; diff --git a/crates/swc_ecma_transforms_base/benches/base.rs b/crates/swc_ecma_transforms_base/benches/base.rs index 4a251a353e4..a8950660c9f 100644 --- a/crates/swc_ecma_transforms_base/benches/base.rs +++ b/crates/swc_ecma_transforms_base/benches/base.rs @@ -6,6 +6,7 @@ extern crate test; static GLOBAL: System = System; use std::alloc::System; + use swc_common::{chain, FileName}; use swc_ecma_parser::{Parser, StringInput, Syntax}; use swc_ecma_transforms_base::helpers; diff --git a/crates/swc_ecma_transforms_base/src/ext.rs b/crates/swc_ecma_transforms_base/src/ext.rs index d2c69fe0b5d..512fc132dcb 100644 --- a/crates/swc_ecma_transforms_base/src/ext.rs +++ b/crates/swc_ecma_transforms_base/src/ext.rs @@ -2,6 +2,7 @@ //! bump. use std::ops::DerefMut; + use swc_ecma_ast::*; use swc_ecma_utils::ExprExt; diff --git a/crates/swc_ecma_transforms_base/src/fixer.rs b/crates/swc_ecma_transforms_base/src/fixer.rs index 817b4ac0dde..ec968b286e8 100644 --- a/crates/swc_ecma_transforms_base/src/fixer.rs +++ b/crates/swc_ecma_transforms_base/src/fixer.rs @@ -72,6 +72,7 @@ impl VisitMut for Fixer<'_> { noop_visit_mut_type!(); array!(visit_mut_array_lit, ArrayLit); + // array!(ArrayPat); fn visit_mut_arrow_expr(&mut self, node: &mut ArrowExpr) { @@ -399,6 +400,7 @@ impl VisitMut for Fixer<'_> { node.value.visit_mut_with(self); } + fn visit_mut_key_value_prop(&mut self, prop: &mut KeyValueProp) { prop.visit_mut_children_with(self); diff --git a/crates/swc_ecma_transforms_base/src/helpers/mod.rs b/crates/swc_ecma_transforms_base/src/helpers/mod.rs index 67f3ed8e057..82aea0df83f 100644 --- a/crates/swc_ecma_transforms_base/src/helpers/mod.rs +++ b/crates/swc_ecma_transforms_base/src/helpers/mod.rs @@ -1,6 +1,7 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + use once_cell::sync::Lazy; use scoped_tls::scoped_thread_local; -use std::sync::atomic::{AtomicBool, Ordering}; use swc_common::{FileName, FilePathMapping, Mark, SourceMap, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput}; @@ -87,6 +88,7 @@ impl Helpers { pub const fn mark(&self) -> Mark { self.mark.0 } + pub const fn external(&self) -> bool { self.external } @@ -336,11 +338,12 @@ impl VisitMut for Marker { #[cfg(test)] mod tests { - use super::*; - use crate::pass::noop; use swc_ecma_visit::{as_folder, FoldWith}; use testing::DebugUsingDisplay; + use super::*; + use crate::pass::noop; + #[test] fn external_helper() { let input = "_throw() diff --git a/crates/swc_ecma_transforms_base/src/hygiene/mod.rs b/crates/swc_ecma_transforms_base/src/hygiene/mod.rs index 5571d40c7c3..927498eea88 100644 --- a/crates/swc_ecma_transforms_base/src/hygiene/mod.rs +++ b/crates/swc_ecma_transforms_base/src/hygiene/mod.rs @@ -1,14 +1,15 @@ -use self::{ - ops::Operator, - usage_analyzer::{Data, UsageAnalyzer}, -}; -use crate::hygiene::{unique_scope::unique_scope, usage_analyzer::CurScope}; use swc_atoms::JsWord; use swc_common::{chain, collections::AHashMap}; use swc_ecma_ast::*; use swc_ecma_utils::Id; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith, VisitWith}; +use self::{ + ops::Operator, + usage_analyzer::{Data, UsageAnalyzer}, +}; +use crate::hygiene::{unique_scope::unique_scope, usage_analyzer::CurScope}; + mod ops; #[cfg(test)] mod tests; diff --git a/crates/swc_ecma_transforms_base/src/hygiene/ops.rs b/crates/swc_ecma_transforms_base/src/hygiene/ops.rs index d1ebbc3a7fc..db23bb422c5 100644 --- a/crates/swc_ecma_transforms_base/src/hygiene/ops.rs +++ b/crates/swc_ecma_transforms_base/src/hygiene/ops.rs @@ -1,4 +1,5 @@ use std::collections::hash_map::Entry; + use swc_atoms::JsWord; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -184,13 +185,6 @@ impl<'a> VisitMut for Operator<'a> { } } - fn visit_mut_super_prop_expr(&mut self, expr: &mut SuperPropExpr) { - expr.span.visit_mut_with(self); - if let SuperProp::Computed(c) = &mut expr.prop { - c.visit_mut_with(self); - } - } - fn visit_mut_module_items(&mut self, items: &mut Vec) { let mut stmts = Vec::with_capacity(items.len()); @@ -388,6 +382,13 @@ impl<'a> VisitMut for Operator<'a> { c.visit_mut_with(self) } } + + fn visit_mut_super_prop_expr(&mut self, expr: &mut SuperPropExpr) { + expr.span.visit_mut_with(self); + if let SuperProp::Computed(c) = &mut expr.prop { + c.visit_mut_with(self); + } + } } struct VarFolder<'a, 'b> { diff --git a/crates/swc_ecma_transforms_base/src/hygiene/tests.rs b/crates/swc_ecma_transforms_base/src/hygiene/tests.rs index 3b4ff297591..d56ed5c1fd7 100644 --- a/crates/swc_ecma_transforms_base/src/hygiene/tests.rs +++ b/crates/swc_ecma_transforms_base/src/hygiene/tests.rs @@ -1,5 +1,3 @@ -use super::*; -use crate::tests::{HygieneVisualizer, Tester}; use swc_atoms::JsWord; use swc_common::{collections::AHashMap, hygiene::*, DUMMY_SP}; use swc_ecma_parser::Syntax; @@ -7,6 +5,9 @@ use swc_ecma_utils::quote_ident; use swc_ecma_visit::{Fold, FoldWith}; use testing::{assert_eq, DebugUsingDisplay}; +use super::*; +use crate::tests::{HygieneVisualizer, Tester}; + struct Marker { map: AHashMap, } diff --git a/crates/swc_ecma_transforms_base/src/hygiene/usage_analyzer.rs b/crates/swc_ecma_transforms_base/src/hygiene/usage_analyzer.rs index c0d739dcefa..13ec5369966 100644 --- a/crates/swc_ecma_transforms_base/src/hygiene/usage_analyzer.rs +++ b/crates/swc_ecma_transforms_base/src/hygiene/usage_analyzer.rs @@ -1,6 +1,5 @@ -use super::{ops::Operations, LOG}; -use crate::scope::ScopeKind; use std::{cell::RefCell, mem::take}; + use swc_atoms::{js_word, JsWord}; use swc_common::{collections::AHashMap, SyntaxContext}; use swc_ecma_ast::*; @@ -8,6 +7,9 @@ use swc_ecma_utils::{ident::IdentLike, Id, StmtOrModuleItem}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use tracing::{debug, span, trace, Level}; +use super::{ops::Operations, LOG}; +use crate::scope::ScopeKind; + #[derive(Debug, Default)] pub(super) struct Data { @@ -65,6 +67,7 @@ impl CurScope<'_> { v.remove_usage(id); } } + fn remove_decl(&self, id: &Id) { { let mut b = self.data.decls.borrow_mut(); diff --git a/crates/swc_ecma_transforms_base/src/pass.rs b/crates/swc_ecma_transforms_base/src/pass.rs index c81588fa570..ac6465d165f 100644 --- a/crates/swc_ecma_transforms_base/src/pass.rs +++ b/crates/swc_ecma_transforms_base/src/pass.rs @@ -13,6 +13,7 @@ impl Fold for Noop { fn fold_module(&mut self, m: Module) -> Module { m } + #[inline(always)] fn fold_script(&mut self, s: Script) -> Script { s diff --git a/crates/swc_ecma_transforms_base/src/resolver/mod.rs b/crates/swc_ecma_transforms_base/src/resolver/mod.rs index 7c543286a3e..73d3adffd45 100644 --- a/crates/swc_ecma_transforms_base/src/resolver/mod.rs +++ b/crates/swc_ecma_transforms_base/src/resolver/mod.rs @@ -1,5 +1,5 @@ -use crate::scope::{IdentType, ScopeKind}; use std::cell::RefCell; + use swc_atoms::JsWord; use swc_common::{collections::AHashSet, Mark, SyntaxContext}; use swc_ecma_ast::*; @@ -9,6 +9,8 @@ use swc_ecma_visit::{ }; use tracing::{debug, span, Level}; +use crate::scope::{IdentType, ScopeKind}; + #[cfg(test)] mod tests; @@ -379,51 +381,94 @@ macro_rules! noop { impl<'a> VisitMut for Resolver<'a> { noop!(visit_mut_accessibility, Accessibility); + noop!(visit_mut_true_plus_minus, TruePlusMinus); + noop!(visit_mut_ts_keyword_type, TsKeywordType); + noop!(visit_mut_ts_keyword_type_kind, TsKeywordTypeKind); + noop!(visit_mut_ts_type_operator_op, TsTypeOperatorOp); + noop!(visit_mut_ts_enum_member_id, TsEnumMemberId); + noop!(visit_mut_ts_external_module_ref, TsExternalModuleRef); + noop!(visit_mut_ts_module_name, TsModuleName); + noop!(visit_mut_ts_this_type, TsThisType); typed_ref!(visit_mut_ts_array_type, TsArrayType); + typed_ref!(visit_mut_ts_conditional_type, TsConditionalType); + typed_ref!( visit_mut_ts_type_param_instantiation, TsTypeParamInstantiation ); + typed_ref!(visit_mut_ts_type_query, TsTypeQuery); + typed_ref!(visit_mut_ts_type_query_expr, TsTypeQueryExpr); + typed_ref!(visit_mut_ts_type_operator, TsTypeOperator); + typed_ref!(visit_mut_ts_type, TsType); + typed_ref!(visit_mut_ts_type_ann, TsTypeAnn); + typed!( visit_mut_ts_union_or_intersection_type, TsUnionOrIntersectionType ); + typed!(visit_mut_ts_fn_or_constructor_type, TsFnOrConstructorType); + typed_ref!(visit_mut_ts_union_type, TsUnionType); + typed_ref!(visit_mut_ts_infer_type, TsInferType); + typed_ref!(visit_mut_ts_import_type, TsImportType); + typed_ref!(visit_mut_ts_tuple_type, TsTupleType); + typed_ref!(visit_mut_ts_intersection_type, TsIntersectionType); + typed_ref!(visit_mut_ts_type_ref, TsTypeRef); + typed_decl!(visit_mut_ts_type_param_decl, TsTypeParamDecl); + typed!(visit_mut_ts_fn_param, TsFnParam); + typed!(visit_mut_ts_indexed_access_type, TsIndexedAccessType); + typed!(visit_mut_ts_index_signature, TsIndexSignature); + typed!(visit_mut_ts_interface_body, TsInterfaceBody); + typed!(visit_mut_ts_parenthesized_type, TsParenthesizedType); + typed!(visit_mut_ts_type_lit, TsTypeLit); + typed!(visit_mut_ts_type_element, TsTypeElement); + typed!(visit_mut_ts_optional_type, TsOptionalType); + typed!(visit_mut_ts_rest_type, TsRestType); + typed!(visit_mut_ts_type_predicate, TsTypePredicate); + typed_ref!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent); + typed_ref!(visit_mut_ts_expr_with_type_args, TsExprWithTypeArgs); + visit_mut_obj_and_computed!(); + + // TODO: How should I handle this? + typed!(visit_mut_ts_namespace_export_decl, TsNamespaceExportDecl); + + track_ident_mut!(); + fn visit_mut_arrow_expr(&mut self, e: &mut ArrowExpr) { let child_mark = Mark::fresh(Mark::root()); @@ -821,8 +866,6 @@ impl<'a> VisitMut for Resolver<'a> { /// See https://github.com/swc-project/swc/issues/2854 fn visit_mut_jsx_attr_name(&mut self, _: &mut JSXAttrName) {} - visit_mut_obj_and_computed!(); - fn visit_mut_method_prop(&mut self, m: &mut MethodProp) { m.key.visit_mut_with(self); @@ -859,11 +902,6 @@ impl<'a> VisitMut for Resolver<'a> { stmts.visit_mut_children_with(self) } - // TODO: How should I handle this? - typed!(visit_mut_ts_namespace_export_decl, TsNamespaceExportDecl); - - track_ident_mut!(); - fn visit_mut_named_export(&mut self, e: &mut NamedExport) { if e.src.is_some() { return; diff --git a/crates/swc_ecma_transforms_base/src/resolver/tests.rs b/crates/swc_ecma_transforms_base/src/resolver/tests.rs index 0f9595059c0..60581b6ed7d 100644 --- a/crates/swc_ecma_transforms_base/src/resolver/tests.rs +++ b/crates/swc_ecma_transforms_base/src/resolver/tests.rs @@ -1,8 +1,9 @@ -use super::*; -use crate::hygiene::Config; use swc_ecma_parser::Syntax; use swc_ecma_visit::Fold; +use super::*; +use crate::hygiene::Config; + // struct TsHygiene { // top_level_mark: Mark, // } diff --git a/crates/swc_ecma_transforms_base/src/tests.rs b/crates/swc_ecma_transforms_base/src/tests.rs index 802aa4ab752..40e8e5473b9 100644 --- a/crates/swc_ecma_transforms_base/src/tests.rs +++ b/crates/swc_ecma_transforms_base/src/tests.rs @@ -1,4 +1,3 @@ -use crate::{fixer::fixer, helpers::HELPERS, hygiene::hygiene_with_config}; use swc_common::{ comments::SingleThreadedComments, errors::{Handler, HANDLER}, @@ -11,6 +10,8 @@ use swc_ecma_parser::{error::Error, lexer::Lexer, Parser, StringInput, Syntax}; use swc_ecma_utils::DropSpan; use swc_ecma_visit::{as_folder, Fold, FoldWith}; +use crate::{fixer::fixer, helpers::HELPERS, hygiene::hygiene_with_config}; + pub struct Tester<'a> { pub cm: Lrc, pub handler: &'a Handler, diff --git a/crates/swc_ecma_transforms_base/tests/fixer_test262.rs b/crates/swc_ecma_transforms_base/tests/fixer_test262.rs index 968ba5a6906..21d18d3b5ab 100644 --- a/crates/swc_ecma_transforms_base/tests/fixer_test262.rs +++ b/crates/swc_ecma_transforms_base/tests/fixer_test262.rs @@ -8,6 +8,7 @@ use std::{ path::Path, sync::{Arc, RwLock}, }; + use swc_ecma_ast::*; use swc_ecma_codegen::{self, Emitter}; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax}; diff --git a/crates/swc_ecma_transforms_base/tests/fixture.rs b/crates/swc_ecma_transforms_base/tests/fixture.rs index 5122a6d686a..3b9c740c1b4 100644 --- a/crates/swc_ecma_transforms_base/tests/fixture.rs +++ b/crates/swc_ecma_transforms_base/tests/fixture.rs @@ -1,4 +1,5 @@ use std::path::{Path, PathBuf}; + use swc_common::{chain, sync::Lrc, Mark, SourceMap, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_codegen::Emitter; @@ -105,6 +106,8 @@ struct TsHygiene { } impl VisitMut for TsHygiene { + visit_mut_obj_and_computed!(); + fn visit_mut_ident(&mut self, i: &mut Ident) { if SyntaxContext::empty().apply_mark(self.top_level_mark) == i.span.ctxt { println!("ts_hygiene: {} is top-level", i.sym); @@ -116,8 +119,6 @@ impl VisitMut for TsHygiene { i.span = i.span.with_ctxt(SyntaxContext::empty()); } - visit_mut_obj_and_computed!(); - fn visit_mut_prop_name(&mut self, n: &mut PropName) { if let PropName::Computed(n) = n { n.visit_mut_with(self); diff --git a/crates/swc_ecma_transforms_base/tests/ts_resolver.rs b/crates/swc_ecma_transforms_base/tests/ts_resolver.rs index d3a869af709..860f790a928 100644 --- a/crates/swc_ecma_transforms_base/tests/ts_resolver.rs +++ b/crates/swc_ecma_transforms_base/tests/ts_resolver.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use swc_common::{input::SourceFileInput, Mark, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_parser::{lexer::Lexer, Parser, Syntax, TsConfig}; diff --git a/crates/swc_ecma_transforms_classes/src/super_field.rs b/crates/swc_ecma_transforms_classes/src/super_field.rs index f18bfd4edc7..899c98a18d9 100644 --- a/crates/swc_ecma_transforms_classes/src/super_field.rs +++ b/crates/swc_ecma_transforms_classes/src/super_field.rs @@ -1,5 +1,5 @@ -use super::get_prototype_of; use std::iter; + use swc_atoms::js_word; use swc_common::{util::take::Take, Mark, Span, DUMMY_SP}; use swc_ecma_ast::*; @@ -7,6 +7,8 @@ use swc_ecma_transforms_base::helper; use swc_ecma_utils::{alias_ident_for, is_rest_arguments, quote_ident, ExprFactory}; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; +use super::get_prototype_of; + /// Process function body. /// /// # In @@ -64,21 +66,6 @@ impl<'a> VisitMut for SuperFieldAccessFolder<'a> { visit_mut_only_key!(); - fn visit_mut_function(&mut self, n: &mut Function) { - if self.folding_constructor { - return; - } - - if self.folding_constructor && !self.in_injected_define_property_call { - let old = self.in_nested_scope; - self.in_nested_scope = true; - n.visit_mut_children_with(self); - self.in_nested_scope = old; - } else { - n.visit_mut_children_with(self); - } - } - fn visit_mut_expr(&mut self, n: &mut Expr) { match n { Expr::This(ThisExpr { span }) if self.in_nested_scope => { @@ -121,6 +108,21 @@ impl<'a> VisitMut for SuperFieldAccessFolder<'a> { n.visit_mut_children_with(self) } + + fn visit_mut_function(&mut self, n: &mut Function) { + if self.folding_constructor { + return; + } + + if self.folding_constructor && !self.in_injected_define_property_call { + let old = self.in_nested_scope; + self.in_nested_scope = true; + n.visit_mut_children_with(self); + self.in_nested_scope = old; + } else { + n.visit_mut_children_with(self); + } + } } impl<'a> SuperFieldAccessFolder<'a> { diff --git a/crates/swc_ecma_transforms_compat/src/bugfixes/async_arrows_in_class.rs b/crates/swc_ecma_transforms_compat/src/bugfixes/async_arrows_in_class.rs index 7c1185703f2..a2efd99a1d8 100644 --- a/crates/swc_ecma_transforms_compat/src/bugfixes/async_arrows_in_class.rs +++ b/crates/swc_ecma_transforms_compat/src/bugfixes/async_arrows_in_class.rs @@ -1,9 +1,10 @@ -use crate::es2015::arrow; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::prepend; use swc_ecma_visit::{noop_fold_type, Fold, FoldWith, InjectVars}; +use crate::es2015::arrow; + /// Safari 10.3 had an issue where async arrow function expressions within any /// class method would throw. After an initial fix, any references to the /// instance via `this` within those methods would also throw. This is fixed by @@ -94,9 +95,10 @@ impl Fold for AsyncArrowsInClass { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| async_arrows_in_class(), diff --git a/crates/swc_ecma_transforms_compat/src/bugfixes/edge_default_param.rs b/crates/swc_ecma_transforms_compat/src/bugfixes/edge_default_param.rs index cb0bbe43e9b..7f348b7f667 100644 --- a/crates/swc_ecma_transforms_compat/src/bugfixes/edge_default_param.rs +++ b/crates/swc_ecma_transforms_compat/src/bugfixes/edge_default_param.rs @@ -58,9 +58,10 @@ impl VisitMut for EdgeDefaultParam { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| edge_default_param(), diff --git a/crates/swc_ecma_transforms_compat/src/bugfixes/mod.rs b/crates/swc_ecma_transforms_compat/src/bugfixes/mod.rs index faa4dd3c2a6..89276fdcc1f 100644 --- a/crates/swc_ecma_transforms_compat/src/bugfixes/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/bugfixes/mod.rs @@ -1,10 +1,11 @@ +use swc_common::chain; +use swc_ecma_visit::Fold; + pub use self::{ async_arrows_in_class::async_arrows_in_class, edge_default_param::edge_default_param, safari_id_destructuring_collision_in_function_expression::safari_id_destructuring_collision_in_function_expression, template_literal_caching::template_literal_caching, }; -use swc_common::chain; -use swc_ecma_visit::Fold; mod async_arrows_in_class; mod edge_default_param; diff --git a/crates/swc_ecma_transforms_compat/src/bugfixes/safari_id_destructuring_collision_in_function_expression.rs b/crates/swc_ecma_transforms_compat/src/bugfixes/safari_id_destructuring_collision_in_function_expression.rs index 8c429b67304..ce9f4d02fc7 100644 --- a/crates/swc_ecma_transforms_compat/src/bugfixes/safari_id_destructuring_collision_in_function_expression.rs +++ b/crates/swc_ecma_transforms_compat/src/bugfixes/safari_id_destructuring_collision_in_function_expression.rs @@ -30,12 +30,6 @@ impl VisitMut for SafariIdDestructuringCollisionInFunctionExpression { } } - fn visit_mut_ident(&mut self, ident: &mut Ident) { - if self.in_body && !self.fn_expr_name.eq(&ident.sym) { - self.other_ident_syms.insert(ident.sym.clone()); - } - } - fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) { if let Some(ident) = &n.ident { self.fn_expr_name = ident.sym.clone(); @@ -60,13 +54,20 @@ impl VisitMut for SafariIdDestructuringCollisionInFunctionExpression { } } } + + fn visit_mut_ident(&mut self, ident: &mut Ident) { + if self.in_body && !self.fn_expr_name.eq(&ident.sym) { + self.other_ident_syms.insert(ident.sym.clone()); + } + } } #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| safari_id_destructuring_collision_in_function_expression(), diff --git a/crates/swc_ecma_transforms_compat/src/bugfixes/template_literal_caching.rs b/crates/swc_ecma_transforms_compat/src/bugfixes/template_literal_caching.rs index 726f6502fc8..deb0feed32e 100644 --- a/crates/swc_ecma_transforms_compat/src/bugfixes/template_literal_caching.rs +++ b/crates/swc_ecma_transforms_compat/src/bugfixes/template_literal_caching.rs @@ -158,9 +158,10 @@ impl Fold for TemplateLiteralCaching { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| template_literal_caching(), diff --git a/crates/swc_ecma_transforms_compat/src/es2015/arrow.rs b/crates/swc_ecma_transforms_compat/src/es2015/arrow.rs index e969e3be438..4316b1c57d9 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/arrow.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/arrow.rs @@ -69,6 +69,14 @@ struct Arrow { impl VisitMut for Arrow { noop_visit_mut_type!(); + fn visit_mut_class(&mut self, c: &mut Class) { + if c.super_class.is_some() { + self.in_subclass = true; + } + c.visit_mut_children_with(self); + self.in_subclass = false; + } + fn visit_mut_constructor(&mut self, c: &mut Constructor) { c.params.visit_mut_children_with(self); @@ -97,14 +105,6 @@ impl VisitMut for Arrow { } } - fn visit_mut_class(&mut self, c: &mut Class) { - if c.super_class.is_some() { - self.in_subclass = true; - } - c.visit_mut_children_with(self); - self.in_subclass = false; - } - fn visit_mut_expr(&mut self, expr: &mut Expr) { match expr { Expr::Arrow(ArrowExpr { diff --git a/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs b/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs index ad48463a35b..b5e733d8b0e 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs @@ -66,9 +66,10 @@ impl VisitMut for BlockScopedFns { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| block_scoped_functions(), diff --git a/crates/swc_ecma_transforms_compat/src/es2015/block_scoping.rs b/crates/swc_ecma_transforms_compat/src/es2015/block_scoping.rs index dee8a1f37bf..de03fb02901 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/block_scoping.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/block_scoping.rs @@ -1,5 +1,6 @@ -use smallvec::SmallVec; use std::mem::take; + +use smallvec::SmallVec; use swc_atoms::js_word; use swc_common::{collections::AHashMap, util::take::Take, Mark, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; @@ -906,10 +907,15 @@ impl MutationHandler<'_> { impl VisitMut for MutationHandler<'_> { noop_visit_mut_type!(); - fn visit_mut_ident(&mut self, n: &mut Ident) { - if let Some(&ctxt) = self.map.get(&n.to_id()) { - n.span = n.span.with_ctxt(ctxt) - } + visit_mut_obj_and_computed!(); + + fn visit_mut_arrow_expr(&mut self, n: &mut ArrowExpr) { + let old = self.in_function; + self.in_function = true; + + n.visit_mut_children_with(self); + + self.in_function = old; } fn visit_mut_expr(&mut self, n: &mut Expr) { @@ -933,15 +939,6 @@ impl VisitMut for MutationHandler<'_> { } } - fn visit_mut_arrow_expr(&mut self, n: &mut ArrowExpr) { - let old = self.in_function; - self.in_function = true; - - n.visit_mut_children_with(self); - - self.in_function = old; - } - fn visit_mut_function(&mut self, n: &mut Function) { let old = self.in_function; let arguments = self.arguments.take(); @@ -953,6 +950,12 @@ impl VisitMut for MutationHandler<'_> { self.arguments = arguments; } + fn visit_mut_ident(&mut self, n: &mut Ident) { + if let Some(&ctxt) = self.map.get(&n.to_id()) { + n.span = n.span.with_ctxt(ctxt) + } + } + fn visit_mut_return_stmt(&mut self, n: &mut ReturnStmt) { n.visit_mut_children_with(self); if self.in_function || self.map.is_empty() { @@ -963,8 +966,6 @@ impl VisitMut for MutationHandler<'_> { n.arg = Some(Box::new(self.make_reassignment(val))) } - - visit_mut_obj_and_computed!(); } #[derive(Debug)] diff --git a/crates/swc_ecma_transforms_compat/src/es2015/classes/constructor.rs b/crates/swc_ecma_transforms_compat/src/es2015/classes/constructor.rs index b24bd51d8d2..8d15b3f56db 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/classes/constructor.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/classes/constructor.rs @@ -1,4 +1,5 @@ use std::iter; + use swc_atoms::{js_word, JsWord}; use swc_common::{util::take::Take, Mark, DUMMY_SP}; use swc_ecma_ast::*; @@ -70,7 +71,9 @@ impl Visit for SuperCallFinder { noop_visit_type!(); mark_as_complex!(visit_arrow_expr, ArrowExpr); + mark_as_complex!(visit_if_stmt, IfStmt); + mark_as_complex!(visit_prop_name, PropName); fn visit_assign_expr(&mut self, node: &AssignExpr) { @@ -304,11 +307,15 @@ pub(super) enum SuperFoldingMode { impl VisitMut for ConstructorFolder<'_> { noop_visit_mut_type!(); + visit_mut_only_key!(); ignore_return!(visit_mut_function, Function); + ignore_return!(visit_mut_class, Class); + ignore_return!(visit_mut_arrow_expr, ArrowExpr); + ignore_return!(visit_mut_constructor, Constructor); fn visit_mut_call_expr(&mut self, e: &mut CallExpr) { diff --git a/crates/swc_ecma_transforms_compat/src/es2015/classes/mod.rs b/crates/swc_ecma_transforms_compat/src/es2015/classes/mod.rs index 6a895dfbfd7..2b61c91855d 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/classes/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/classes/mod.rs @@ -1,11 +1,5 @@ -use self::{ - constructor::{ - constructor_fn, make_possible_return_value, replace_this_in_constructor, ConstructorFolder, - ReturningMode, SuperCallFinder, SuperFoldingMode, VarRenamer, - }, - prop_name::HashKey, -}; use std::iter; + use swc_common::{comments::Comments, util::take::Take, Mark, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{helper, native::is_native, perf::Check}; @@ -20,6 +14,14 @@ use swc_ecma_visit::{ }; use tracing::debug; +use self::{ + constructor::{ + constructor_fn, make_possible_return_value, replace_this_in_constructor, ConstructorFolder, + ReturningMode, SuperCallFinder, SuperFoldingMode, VarRenamer, + }, + prop_name::HashKey, +}; + mod constructor; mod prop_name; diff --git a/crates/swc_ecma_transforms_compat/src/es2015/computed_props.rs b/crates/swc_ecma_transforms_compat/src/es2015/computed_props.rs index 1b42bcbe211..1923a4ad802 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/computed_props.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/computed_props.rs @@ -62,14 +62,6 @@ struct ComputedProps { impl VisitMut for ComputedProps { noop_visit_mut_type!(); - fn visit_mut_module_items(&mut self, n: &mut Vec) { - self.visit_mut_stmt_like(n); - } - - fn visit_mut_stmts(&mut self, n: &mut Vec) { - self.visit_mut_stmt_like(n); - } - fn visit_mut_expr(&mut self, expr: &mut Expr) { expr.visit_mut_children_with(self); @@ -315,6 +307,14 @@ impl VisitMut for ComputedProps { }); }; } + + fn visit_mut_module_items(&mut self, n: &mut Vec) { + self.visit_mut_stmt_like(n); + } + + fn visit_mut_stmts(&mut self, n: &mut Vec) { + self.visit_mut_stmt_like(n); + } } fn is_complex>(node: &T) -> bool { diff --git a/crates/swc_ecma_transforms_compat/src/es2015/destructuring.rs b/crates/swc_ecma_transforms_compat/src/es2015/destructuring.rs index e2254e6929e..61642d61e85 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/destructuring.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/destructuring.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::iter; + +use serde::Deserialize; use swc_atoms::js_word; use swc_common::{util::take::Take, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; @@ -479,6 +480,7 @@ impl VisitMut for Destructuring { noop_visit_mut_type!(); impl_for_for_stmt!(visit_mut_for_in_stmt, ForInStmt); + impl_for_for_stmt!(visit_mut_for_of_stmt, ForOfStmt); impl_visit_mut_fn!(); diff --git a/crates/swc_ecma_transforms_compat/src/es2015/function_name.rs b/crates/swc_ecma_transforms_compat/src/es2015/function_name.rs index 342d00746a6..65745fff522 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/function_name.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/function_name.rs @@ -137,12 +137,18 @@ impl VisitMut for Rename { noop_visit_mut_type!(); impl_for!(visit_mut_fn_expr, FnExpr); + impl_for!(visit_mut_class_expr, ClassExpr); noop!(visit_mut_object_lit, ObjectLit); + noop!(visit_mut_array_lit, ArrayLit); + noop!(visit_mut_call_expr, CallExpr); + noop!(visit_mut_new_expr, NewExpr); + noop!(visit_mut_bin_expr, BinExpr); + noop!(visit_mut_unary_expr, UnaryExpr); } diff --git a/crates/swc_ecma_transforms_compat/src/es2015/mod.rs b/crates/swc_ecma_transforms_compat/src/es2015/mod.rs index 7ee2c8a5b02..a1cac75fbfa 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/mod.rs @@ -1,3 +1,7 @@ +use serde::Deserialize; +use swc_common::{chain, comments::Comments, pass::Optional, Mark}; +use swc_ecma_visit::Fold; + pub use self::{ arrow::arrow, block_scoped_fn::block_scoped_functions, block_scoping::block_scoping, classes::classes, computed_props::computed_properties, destructuring::destructuring, @@ -7,9 +11,6 @@ pub use self::{ spread::spread, sticky_regex::sticky_regex, template_literal::template_literal, typeof_symbol::typeof_symbol, }; -use serde::Deserialize; -use swc_common::{chain, comments::Comments, pass::Optional, Mark}; -use swc_ecma_visit::Fold; mod arrow; mod block_scoped_fn; @@ -98,11 +99,12 @@ pub struct Config { #[cfg(test)] mod tests { - use super::*; use swc_common::Mark; use swc_ecma_transforms_base::resolver::resolver; use swc_ecma_transforms_testing::{test, test_exec}; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |t| es2015( diff --git a/crates/swc_ecma_transforms_compat/src/es2015/new_target.rs b/crates/swc_ecma_transforms_compat/src/es2015/new_target.rs index 2224b8e6dc9..af64d47074b 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/new_target.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/new_target.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; + use swc_common::{pass::CompilerPass, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::perf::{should_work, Check}; diff --git a/crates/swc_ecma_transforms_compat/src/es2015/object_super.rs b/crates/swc_ecma_transforms_compat/src/es2015/object_super.rs index 7cb2bd699e9..216ed99cef0 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/object_super.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/object_super.rs @@ -19,6 +19,7 @@ pub fn object_super() -> impl Fold + VisitMut { impl VisitMut for ObjectSuper { noop_visit_mut_type!(); + fn visit_mut_module_items(&mut self, n: &mut Vec) { n.visit_mut_children_with(self); if !self.extra_vars.is_empty() { @@ -43,6 +44,7 @@ impl VisitMut for ObjectSuper { ); } } + fn visit_mut_stmts(&mut self, stmts: &mut Vec) { stmts.visit_mut_children_with(self); if !self.extra_vars.is_empty() { @@ -153,6 +155,7 @@ impl SuperReplacer { ident } } + fn get_proto(&mut self) -> ExprOrSpread { Expr::Call(CallExpr { span: DUMMY_SP, @@ -178,6 +181,7 @@ impl SuperReplacer { SuperProp::Computed(ComputedPropName { expr, .. }) => expr, } } + /// # In /// ```js /// super.foo(a) @@ -334,6 +338,7 @@ impl SuperReplacer { type_args: Default::default(), }) } + fn to_bin_expr(left: Box, op: AssignOp, rhs: Box) -> BinExpr { BinExpr { span: DUMMY_SP, @@ -342,6 +347,7 @@ impl SuperReplacer { right: rhs, } } + fn call_set_helper( &mut self, super_token: Span, @@ -362,6 +368,7 @@ impl SuperReplacer { type_args: Default::default(), }) } + fn super_to_set_call( &mut self, super_token: Span, @@ -461,12 +468,13 @@ impl SuperReplacer { } #[cfg(test)] mod tests { - use super::*; - use crate::es2015::{function_name, shorthand_property::shorthand}; use swc_common::{chain, Mark}; use swc_ecma_parser::{EsConfig, Syntax}; use swc_ecma_transforms_base::resolver::resolver_with_mark; use swc_ecma_transforms_testing::test; + + use super::*; + use crate::es2015::{function_name, shorthand_property::shorthand}; test!( ::swc_ecma_parser::Syntax::default(), |_| { diff --git a/crates/swc_ecma_transforms_compat/src/es2015/regenerator/case.rs b/crates/swc_ecma_transforms_compat/src/es2015/regenerator/case.rs index d40d4e73b21..0ef11f0d5ec 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/regenerator/case.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/regenerator/case.rs @@ -1,6 +1,6 @@ -use super::leap::{CatchEntry, Entry, FinallyEntry, LeapManager, TryEntry}; -use smallvec::SmallVec; use std::mem::take; + +use smallvec::SmallVec; use swc_atoms::JsWord; use swc_common::{ util::{map::Map, move_map::MoveMap, take::Take}, @@ -14,6 +14,8 @@ use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith, }; +use super::leap::{CatchEntry, Entry, FinallyEntry, LeapManager, TryEntry}; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(super) struct Loc { id: u32, @@ -1540,16 +1542,21 @@ macro_rules! leap { impl Visit for LeapFinder { noop_visit_type!(); + leap!(visit_yield_expr, YieldExpr); + + leap!(visit_break_stmt, BreakStmt); + + leap!(visit_continue_stmt, ContinueStmt); + + leap!(visit_return_stmt, ReturnStmt); + + leap!(visit_throw_stmt, ThrowStmt); + /// Ignored fn visit_function(&mut self, _: &Function) {} + /// Ignored fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} - - leap!(visit_yield_expr, YieldExpr); - leap!(visit_break_stmt, BreakStmt); - leap!(visit_continue_stmt, ContinueStmt); - leap!(visit_return_stmt, ReturnStmt); - leap!(visit_throw_stmt, ThrowStmt); } fn contains_leap(node: &T) -> bool diff --git a/crates/swc_ecma_transforms_compat/src/es2015/regenerator/leap.rs b/crates/swc_ecma_transforms_compat/src/es2015/regenerator/leap.rs index 5d6b870d5e0..a3a5e70153f 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/regenerator/leap.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/regenerator/leap.rs @@ -1,11 +1,12 @@ #![allow(dead_code)] -use super::case::Loc; use is_macro::Is; use smallvec::SmallVec; use swc_atoms::JsWord; use swc_ecma_utils::Id; +use super::case::Loc; + #[derive(Debug, Default)] pub(super) struct LeapManager { stack: SmallVec<[Entry; 16]>, @@ -15,6 +16,7 @@ impl LeapManager { pub fn push(&mut self, entry: Entry) { self.stack.push(entry); } + pub fn pop(&mut self) -> Option { self.stack.pop() } @@ -48,6 +50,7 @@ impl LeapManager { None } + pub fn find_break_loc(&self, label: Option<&JsWord>) -> Option { self.find_leap_loc( |entry| match *entry { diff --git a/crates/swc_ecma_transforms_compat/src/es2015/regenerator/mod.rs b/crates/swc_ecma_transforms_compat/src/es2015/regenerator/mod.rs index 508d7e9974a..9b074702224 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/regenerator/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/regenerator/mod.rs @@ -1,6 +1,6 @@ -use self::{case::CaseHandler, hoist::hoist}; -use serde::{Deserialize, Serialize}; use std::mem::take; + +use serde::{Deserialize, Serialize}; use swc_atoms::{js_word, JsWord}; use swc_common::{util::take::Take, Mark, Spanned, DUMMY_SP}; use swc_ecma_ast::*; @@ -11,6 +11,8 @@ use swc_ecma_visit::{ as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith, VisitWith, }; +use self::{case::CaseHandler, hoist::hoist}; + mod case; mod hoist; mod leap; diff --git a/crates/swc_ecma_transforms_compat/src/es2015/shorthand_property.rs b/crates/swc_ecma_transforms_compat/src/es2015/shorthand_property.rs index 257de20ce0a..a54d806de4b 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/shorthand_property.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/shorthand_property.rs @@ -84,9 +84,10 @@ impl VisitMut for Shorthand { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| shorthand(), diff --git a/crates/swc_ecma_transforms_compat/src/es2015/spread.rs b/crates/swc_ecma_transforms_compat/src/es2015/spread.rs index be196893a5e..4713d142cab 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/spread.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/spread.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::mem; + +use serde::Deserialize; use swc_atoms::js_word; use swc_common::{util::take::Take, Span, Spanned, DUMMY_SP}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_transforms_compat/src/es2015/sticky_regex.rs b/crates/swc_ecma_transforms_compat/src/es2015/sticky_regex.rs index 6805996c1e5..2118374a185 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/sticky_regex.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/sticky_regex.rs @@ -70,9 +70,10 @@ impl VisitMut for StickyRegex { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| sticky_regex(), diff --git a/crates/swc_ecma_transforms_compat/src/es2015/template_literal.rs b/crates/swc_ecma_transforms_compat/src/es2015/template_literal.rs index c59e0890ecc..97b6a90c518 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/template_literal.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/template_literal.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::{iter, mem}; + +use serde::Deserialize; use swc_atoms::js_word; use swc_common::{util::take::Take, BytePos, Spanned, DUMMY_SP}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_transforms_compat/src/es2015/typeof_symbol.rs b/crates/swc_ecma_transforms_compat/src/es2015/typeof_symbol.rs index 2f4d08c3e96..a6bafd452a3 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/typeof_symbol.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/typeof_symbol.rs @@ -168,10 +168,11 @@ fn is_non_symbol_literal(e: &Expr) -> bool { #[cfg(test)] mod tests { - use super::*; use swc_ecma_parser::Syntax; use swc_ecma_transforms_testing::test; + use super::*; + test!( Syntax::default(), |_| typeof_symbol(), diff --git a/crates/swc_ecma_transforms_compat/src/es2016/exponentation.rs b/crates/swc_ecma_transforms_compat/src/es2016/exponentation.rs index 9f661807587..754391bbd5e 100644 --- a/crates/swc_ecma_transforms_compat/src/es2016/exponentation.rs +++ b/crates/swc_ecma_transforms_compat/src/es2016/exponentation.rs @@ -137,9 +137,10 @@ fn mk_call(span: Span, left: Box, right: Box) -> Expr { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::{test, test_exec}; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| exponentation(), diff --git a/crates/swc_ecma_transforms_compat/src/es2016/mod.rs b/crates/swc_ecma_transforms_compat/src/es2016/mod.rs index 7f46c747928..e40c11ce1ef 100644 --- a/crates/swc_ecma_transforms_compat/src/es2016/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2016/mod.rs @@ -1,6 +1,7 @@ -pub use self::exponentation::exponentation; use swc_ecma_visit::Fold; +pub use self::exponentation::exponentation; + mod exponentation; pub fn es2016() -> impl Fold { diff --git a/crates/swc_ecma_transforms_compat/src/es2017/async_to_generator.rs b/crates/swc_ecma_transforms_compat/src/es2017/async_to_generator.rs index 02f949bce70..71aabfaabf7 100644 --- a/crates/swc_ecma_transforms_compat/src/es2017/async_to_generator.rs +++ b/crates/swc_ecma_transforms_compat/src/es2017/async_to_generator.rs @@ -1,4 +1,5 @@ use std::iter; + use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{helper, perf::Check}; @@ -363,8 +364,11 @@ impl VisitMut for AsyncFnBodyHandler { noop_visit_mut_type!(); noop!(visit_mut_fn_expr, FnExpr); + noop!(visit_mut_constructor, Constructor); + noop!(visit_mut_arrow_expr, ArrowExpr); + noop!(visit_mut_fn_decl, FnDecl); fn visit_mut_expr(&mut self, expr: &mut Expr) { diff --git a/crates/swc_ecma_transforms_compat/src/es2017/mod.rs b/crates/swc_ecma_transforms_compat/src/es2017/mod.rs index 056eb80a4ca..2e996a031c2 100644 --- a/crates/swc_ecma_transforms_compat/src/es2017/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2017/mod.rs @@ -1,6 +1,7 @@ -pub use self::async_to_generator::async_to_generator; use swc_ecma_visit::Fold; +pub use self::async_to_generator::async_to_generator; + mod async_to_generator; pub fn es2017() -> impl Fold { diff --git a/crates/swc_ecma_transforms_compat/src/es2018/mod.rs b/crates/swc_ecma_transforms_compat/src/es2018/mod.rs index 7482223a1d2..a4184ad96a4 100644 --- a/crates/swc_ecma_transforms_compat/src/es2018/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2018/mod.rs @@ -1,7 +1,8 @@ -pub use self::object_rest_spread::object_rest_spread; use serde::Deserialize; use swc_ecma_visit::Fold; +pub use self::object_rest_spread::object_rest_spread; + pub mod object_rest_spread; pub fn es2018(c: Config) -> impl Fold { diff --git a/crates/swc_ecma_transforms_compat/src/es2018/object_rest_spread.rs b/crates/swc_ecma_transforms_compat/src/es2018/object_rest_spread.rs index 8dbc4767b4f..00384c3ab76 100644 --- a/crates/swc_ecma_transforms_compat/src/es2018/object_rest_spread.rs +++ b/crates/swc_ecma_transforms_compat/src/es2018/object_rest_spread.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::{iter, mem}; + +use serde::Deserialize; use swc_common::{chain, util::take::Take, Mark, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{ @@ -200,7 +201,9 @@ impl VisitMut for ObjectRest { noop_visit_mut_type!(); impl_for_for_stmt!(visit_mut_for_in_stmt, ForInStmt); + impl_for_for_stmt!(visit_mut_for_of_stmt, ForOfStmt); + impl_visit_mut_fn!(); /// Handles assign expression diff --git a/crates/swc_ecma_transforms_compat/src/es2019/mod.rs b/crates/swc_ecma_transforms_compat/src/es2019/mod.rs index 75426a0e76e..417b961cb31 100644 --- a/crates/swc_ecma_transforms_compat/src/es2019/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2019/mod.rs @@ -1,6 +1,7 @@ -pub use self::optional_catch_binding::optional_catch_binding; use swc_ecma_visit::Fold; +pub use self::optional_catch_binding::optional_catch_binding; + mod optional_catch_binding; pub fn es2019() -> impl Fold { diff --git a/crates/swc_ecma_transforms_compat/src/es2019/optional_catch_binding.rs b/crates/swc_ecma_transforms_compat/src/es2019/optional_catch_binding.rs index 2545eb01990..461ed545b84 100644 --- a/crates/swc_ecma_transforms_compat/src/es2019/optional_catch_binding.rs +++ b/crates/swc_ecma_transforms_compat/src/es2019/optional_catch_binding.rs @@ -23,9 +23,10 @@ impl VisitMut for OptionalCatchBinding { #[cfg(test)] mod tests { - use super::optional_catch_binding as tr; use swc_ecma_transforms_testing::test; + use super::optional_catch_binding as tr; + test!( ::swc_ecma_parser::Syntax::default(), |_| tr(), diff --git a/crates/swc_ecma_transforms_compat/src/es2020/mod.rs b/crates/swc_ecma_transforms_compat/src/es2020/mod.rs index aaf230110d4..8d252911ea3 100644 --- a/crates/swc_ecma_transforms_compat/src/es2020/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2020/mod.rs @@ -1,10 +1,11 @@ +use serde::Deserialize; +use swc_common::chain; +use swc_ecma_visit::Fold; + pub use self::{ export_namespace_from::export_namespace_from, nullish_coalescing::nullish_coalescing, opt_chaining::optional_chaining, }; -use serde::Deserialize; -use swc_common::chain; -use swc_ecma_visit::Fold; mod export_namespace_from; pub mod nullish_coalescing; diff --git a/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/mod.rs b/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/mod.rs index c813b0bdd8e..221d28c1c82 100644 --- a/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/mod.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::mem::take; + +use serde::Deserialize; use swc_common::{util::take::Take, Span, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{alias_if_required, undefined, StmtLike}; diff --git a/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/tests.rs b/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/tests.rs index d8e3a224b6b..d4623f1b45c 100644 --- a/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/tests.rs +++ b/crates/swc_ecma_transforms_compat/src/es2020/nullish_coalescing/tests.rs @@ -1,7 +1,8 @@ -use super::*; use swc_ecma_parser::{EsConfig, Syntax}; use swc_ecma_transforms_testing::{test, test_exec}; +use super::*; + fn tr(c: Config) -> impl Fold { nullish_coalescing(c) } diff --git a/crates/swc_ecma_transforms_compat/src/es2020/opt_chaining.rs b/crates/swc_ecma_transforms_compat/src/es2020/opt_chaining.rs index 2d65798542b..b5ae1e979a3 100644 --- a/crates/swc_ecma_transforms_compat/src/es2020/opt_chaining.rs +++ b/crates/swc_ecma_transforms_compat/src/es2020/opt_chaining.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::{iter::once, mem}; + +use serde::Deserialize; use swc_atoms::js_word; use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_transforms_compat/src/es2021/mod.rs b/crates/swc_ecma_transforms_compat/src/es2021/mod.rs index d1dcca8c248..5c7cb494465 100644 --- a/crates/swc_ecma_transforms_compat/src/es2021/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2021/mod.rs @@ -1,6 +1,7 @@ -pub use self::logical_assignments::logical_assignments; use swc_ecma_visit::{Fold, VisitMut}; +pub use self::logical_assignments::logical_assignments; + mod logical_assignments; pub fn es2021() -> impl Fold + VisitMut { diff --git a/crates/swc_ecma_transforms_compat/src/es2022/class_properties/mod.rs b/crates/swc_ecma_transforms_compat/src/es2022/class_properties/mod.rs index 931d6d869da..6911ca24461 100644 --- a/crates/swc_ecma_transforms_compat/src/es2022/class_properties/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2022/class_properties/mod.rs @@ -1,11 +1,5 @@ #![allow(dead_code)] -use self::{ - class_name_tdz::ClassNameTdzFolder, - private_field::{BrandCheckHandler, FieldAccessFolder, Private, PrivateKind, PrivateRecord}, - this_in_static::ThisInStaticFolder, - used_name::UsedNameCollector, -}; use swc_common::{collections::AHashSet, util::take::Take, Mark, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{helper, perf::Check}; @@ -19,6 +13,13 @@ use swc_ecma_visit::{ as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith, VisitWith, }; +use self::{ + class_name_tdz::ClassNameTdzFolder, + private_field::{BrandCheckHandler, FieldAccessFolder, Private, PrivateKind, PrivateRecord}, + this_in_static::ThisInStaticFolder, + used_name::UsedNameCollector, +}; + mod class_name_tdz; mod private_field; mod this_in_static; diff --git a/crates/swc_ecma_transforms_compat/src/es2022/class_properties/private_field.rs b/crates/swc_ecma_transforms_compat/src/es2022/class_properties/private_field.rs index 330097d5a7b..b8dbc2b07ca 100644 --- a/crates/swc_ecma_transforms_compat/src/es2022/class_properties/private_field.rs +++ b/crates/swc_ecma_transforms_compat/src/es2022/class_properties/private_field.rs @@ -1,4 +1,5 @@ use std::iter; + use swc_atoms::JsWord; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -160,6 +161,7 @@ impl<'a> VisitMut for FieldAccessFolder<'a> { noop_visit_mut_type!(); take_vars!(visit_mut_function, Function); + take_vars!(visit_mut_constructor, Constructor); fn visit_mut_expr(&mut self, e: &mut Expr) { diff --git a/crates/swc_ecma_transforms_compat/src/es2022/class_properties/used_name.rs b/crates/swc_ecma_transforms_compat/src/es2022/class_properties/used_name.rs index 05c976aaaa4..ec424879652 100644 --- a/crates/swc_ecma_transforms_compat/src/es2022/class_properties/used_name.rs +++ b/crates/swc_ecma_transforms_compat/src/es2022/class_properties/used_name.rs @@ -17,10 +17,15 @@ impl<'a> Visit for UsedNameCollector<'a> { noop_visit_type!(); noop!(visit_arrow_expr, ArrowExpr); + noop!(visit_function, Function); + noop!(visit_setter_prop, SetterProp); + noop!(visit_getter_prop, GetterProp); + noop!(visit_method_prop, MethodProp); + noop!(visit_constructor, Constructor); fn visit_expr(&mut self, expr: &Expr) { diff --git a/crates/swc_ecma_transforms_compat/src/es2022/mod.rs b/crates/swc_ecma_transforms_compat/src/es2022/mod.rs index e95289c7165..0552a6c75f4 100644 --- a/crates/swc_ecma_transforms_compat/src/es2022/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2022/mod.rs @@ -1,9 +1,10 @@ +use swc_common::chain; +use swc_ecma_visit::Fold; + pub use self::{ class_properties::class_properties, private_in_object::private_in_object, static_blocks::static_blocks, }; -use swc_common::chain; -use swc_ecma_visit::Fold; pub mod class_properties; pub mod private_in_object; diff --git a/crates/swc_ecma_transforms_compat/src/es2022/private_in_object.rs b/crates/swc_ecma_transforms_compat/src/es2022/private_in_object.rs index c17db140ab0..ab975f56e29 100644 --- a/crates/swc_ecma_transforms_compat/src/es2022/private_in_object.rs +++ b/crates/swc_ecma_transforms_compat/src/es2022/private_in_object.rs @@ -2,6 +2,7 @@ use std::{ borrow::Cow, mem::{replace, take}, }; + use swc_atoms::JsWord; use swc_common::{ collections::AHashSet, pass::CompilerPass, util::take::Take, Mark, Spanned, DUMMY_SP, diff --git a/crates/swc_ecma_transforms_compat/src/es3/member_expr_lits.rs b/crates/swc_ecma_transforms_compat/src/es3/member_expr_lits.rs index 00cd124a063..575e04ce445 100644 --- a/crates/swc_ecma_transforms_compat/src/es3/member_expr_lits.rs +++ b/crates/swc_ecma_transforms_compat/src/es3/member_expr_lits.rs @@ -65,9 +65,10 @@ impl Fold for MemberExprLit { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| MemberExprLit, diff --git a/crates/swc_ecma_transforms_compat/src/es3/mod.rs b/crates/swc_ecma_transforms_compat/src/es3/mod.rs index 5425ec42ccd..c8556f53aad 100644 --- a/crates/swc_ecma_transforms_compat/src/es3/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es3/mod.rs @@ -1,9 +1,10 @@ +use swc_common::chain; +use swc_ecma_visit::Fold; + pub use self::{ member_expr_lits::member_expression_literals, prop_lits::property_literals, reserved_word::reserved_words, }; -use swc_common::chain; -use swc_ecma_visit::Fold; mod member_expr_lits; mod prop_lits; diff --git a/crates/swc_ecma_transforms_compat/src/es3/prop_lits.rs b/crates/swc_ecma_transforms_compat/src/es3/prop_lits.rs index 22081eb965e..a1534f77318 100644 --- a/crates/swc_ecma_transforms_compat/src/es3/prop_lits.rs +++ b/crates/swc_ecma_transforms_compat/src/es3/prop_lits.rs @@ -81,9 +81,10 @@ impl Fold for PropertyLiteral { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + test!( ::swc_ecma_parser::Syntax::default(), |_| PropertyLiteral, diff --git a/crates/swc_ecma_transforms_compat/src/es3/reserved_word.rs b/crates/swc_ecma_transforms_compat/src/es3/reserved_word.rs index 4322e14c9fc..61e8338da0c 100644 --- a/crates/swc_ecma_transforms_compat/src/es3/reserved_word.rs +++ b/crates/swc_ecma_transforms_compat/src/es3/reserved_word.rs @@ -84,9 +84,10 @@ fn fold_ident(preserve_import: bool, i: Ident) -> Ident { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + macro_rules! identical { ($name:ident, $src:literal) => { test!( diff --git a/crates/swc_ecma_transforms_compat/src/reserved_words.rs b/crates/swc_ecma_transforms_compat/src/reserved_words.rs index 20670ff2a35..77c08f6c22a 100644 --- a/crates/swc_ecma_transforms_compat/src/reserved_words.rs +++ b/crates/swc_ecma_transforms_compat/src/reserved_words.rs @@ -25,6 +25,8 @@ impl Parallel for EsReservedWord { impl VisitMut for EsReservedWord { noop_visit_mut_type!(); + visit_mut_obj_and_computed!(); + fn visit_mut_export_specifier(&mut self, _n: &mut ExportSpecifier) {} fn visit_mut_ident(&mut self, i: &mut Ident) { @@ -35,8 +37,6 @@ impl VisitMut for EsReservedWord { s.local.visit_mut_with(self); } - visit_mut_obj_and_computed!(); - fn visit_mut_prop_name(&mut self, _n: &mut PropName) {} } diff --git a/crates/swc_ecma_transforms_compat/tests/es2015_block_scoping.rs b/crates/swc_ecma_transforms_compat/tests/es2015_block_scoping.rs index 93d2e0e129b..f41edf22406 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2015_block_scoping.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2015_block_scoping.rs @@ -1,4 +1,5 @@ use std::{fs::read_to_string, path::PathBuf}; + use swc_common::{chain, Mark}; use swc_ecma_parser::Syntax; use swc_ecma_transforms_base::resolver::resolver; diff --git a/crates/swc_ecma_transforms_compat/tests/es2015_classes.rs b/crates/swc_ecma_transforms_compat/tests/es2015_classes.rs index ea566da6e15..e8f942683aa 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2015_classes.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2015_classes.rs @@ -1,4 +1,5 @@ use std::{fs::read_to_string, path::PathBuf}; + use swc_common::{chain, Mark}; use swc_ecma_parser::Syntax; use swc_ecma_transforms_base::resolver::resolver; diff --git a/crates/swc_ecma_transforms_compat/tests/es2015_for_of.rs b/crates/swc_ecma_transforms_compat/tests/es2015_for_of.rs index 6326a3f1e1c..f868b0aa9fb 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2015_for_of.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2015_for_of.rs @@ -1,4 +1,5 @@ use std::{fs::read_to_string, path::PathBuf}; + use swc_common::{chain, comments::NoopComments, Mark}; use swc_ecma_parser::Syntax; use swc_ecma_transforms_base::resolver::resolver_with_mark; diff --git a/crates/swc_ecma_transforms_compat/tests/es2015_new_target.rs b/crates/swc_ecma_transforms_compat/tests/es2015_new_target.rs index a03b5a3fba7..498e595452e 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2015_new_target.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2015_new_target.rs @@ -1,4 +1,5 @@ use std::{fs::read_to_string, path::PathBuf}; + use swc_ecma_transforms_compat::es2015::new_target::new_target; use swc_ecma_transforms_testing::{exec_tr, test, test_fixture}; diff --git a/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs b/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs index d3b85f2eed6..0069dc5bc7f 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs @@ -1,5 +1,5 @@ -use crate::es2015::regenerator; use std::{fs::read_to_string, path::PathBuf}; + use swc_common::{chain, Mark, Spanned}; use swc_ecma_ast::*; use swc_ecma_parser::Syntax; @@ -13,6 +13,8 @@ use swc_ecma_transforms_compat::{ use swc_ecma_transforms_testing::{compare_stdout, test, test_exec}; use swc_ecma_visit::{Fold, FoldWith}; +use crate::es2015::regenerator; + struct ParenRemover; impl Fold for ParenRemover { fn fold_expr(&mut self, expr: Expr) -> Expr { diff --git a/crates/swc_ecma_transforms_compat/tests/es2020_optional_chaining.rs b/crates/swc_ecma_transforms_compat/tests/es2020_optional_chaining.rs index 8baf6ddebd7..a545a81b841 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2020_optional_chaining.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2020_optional_chaining.rs @@ -1,4 +1,5 @@ use std::{fs::read_to_string, path::PathBuf}; + use swc_ecma_parser::{Syntax, TsConfig}; use swc_ecma_transforms_compat::es2020::{opt_chaining::Config, optional_chaining}; use swc_ecma_transforms_testing::{compare_stdout, test, test_exec}; diff --git a/crates/swc_ecma_transforms_compat/tests/es2022_class_properties.rs b/crates/swc_ecma_transforms_compat/tests/es2022_class_properties.rs index cc5cb695218..05909890737 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2022_class_properties.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2022_class_properties.rs @@ -1,6 +1,7 @@ #![allow(deprecated)] use std::{fs::read_to_string, path::PathBuf}; + use swc_common::chain; use swc_ecma_parser::{EsConfig, Syntax, TsConfig}; use swc_ecma_transforms_base::resolver::resolver; diff --git a/crates/swc_ecma_transforms_compat/tests/es2022_private_in_object.rs b/crates/swc_ecma_transforms_compat/tests/es2022_private_in_object.rs index 37e8f6a704f..d0e836b4173 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2022_private_in_object.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2022_private_in_object.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::path::PathBuf; + +use serde::Deserialize; use swc_common::chain; use swc_ecma_parser::{EsConfig, Syntax}; use swc_ecma_transforms_base::pass::noop; diff --git a/crates/swc_ecma_transforms_compat/tests/es2022_static_blocks.rs b/crates/swc_ecma_transforms_compat/tests/es2022_static_blocks.rs index b05e7b2e4a5..6a05d74f9e6 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2022_static_blocks.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2022_static_blocks.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use swc_common::chain; use swc_ecma_parser::{EsConfig, Syntax}; use swc_ecma_transforms_compat::es2022::{class_properties, static_blocks}; diff --git a/crates/swc_ecma_transforms_macros/src/fast.rs b/crates/swc_ecma_transforms_macros/src/fast.rs index 84ec9e2cc93..7553c3b8c7d 100644 --- a/crates/swc_ecma_transforms_macros/src/fast.rs +++ b/crates/swc_ecma_transforms_macros/src/fast.rs @@ -1,9 +1,10 @@ -use crate::common::Mode; use pmutil::q; use proc_macro2::TokenStream; use swc_macros_common::call_site; use syn::{FnArg, Ident, ImplItem, ImplItemMethod, ItemImpl, Pat, Path, Stmt}; +use crate::common::Mode; + pub fn expand(attr: TokenStream, item: ItemImpl) -> ItemImpl { let expander = Expander { handler: syn::parse2(attr).expect("Usage should be like #[fast_path(ArrowVisitor)]"), diff --git a/crates/swc_ecma_transforms_macros/src/parallel.rs b/crates/swc_ecma_transforms_macros/src/parallel.rs index 5f3c8c71a9f..e6ff8ee815b 100644 --- a/crates/swc_ecma_transforms_macros/src/parallel.rs +++ b/crates/swc_ecma_transforms_macros/src/parallel.rs @@ -1,8 +1,9 @@ -use crate::common::Mode; use pmutil::q; use proc_macro2::{Span, TokenStream}; use syn::{Expr, Ident, ImplItem, ImplItemMethod, ItemImpl, Meta, Type}; +use crate::common::Mode; + pub fn expand(attr: TokenStream, mut item: ItemImpl) -> ItemImpl { let mode = { let p = &item.trait_.as_ref().unwrap().1; @@ -278,6 +279,7 @@ fn make_par_visit_method( { fn method_name(&mut self, nodes: &mut Vec) { use std::mem::take; + use swc_common::errors::HANDLER; use swc_ecma_transforms_base::perf::{ParExplode, Parallel}; use swc_ecma_visit::VisitMutWith; diff --git a/crates/swc_ecma_transforms_module/src/amd.rs b/crates/swc_ecma_transforms_module/src/amd.rs index 25a6d9bd617..96309e2cb2a 100644 --- a/crates/swc_ecma_transforms_module/src/amd.rs +++ b/crates/swc_ecma_transforms_module/src/amd.rs @@ -1,15 +1,11 @@ -use super::util::{ - self, define_es_module, define_property, has_use_strict, initialize_to_undefined, - local_name_for_src, make_descriptor, use_strict, Exports, ModulePass, Scope, -}; -use crate::path::{ImportResolver, NoopImportResolver}; -use anyhow::Context; -use indexmap::IndexSet; -use serde::{Deserialize, Serialize}; use std::{ cell::{Ref, RefCell, RefMut}, iter, }; + +use anyhow::Context; +use indexmap::IndexSet; +use serde::{Deserialize, Serialize}; use swc_atoms::js_word; use swc_common::{FileName, Mark, Span, DUMMY_SP}; use swc_ecma_ast::*; @@ -20,6 +16,12 @@ use swc_ecma_utils::{ }; use swc_ecma_visit::{noop_fold_type, Fold, FoldWith, VisitWith}; +use super::util::{ + self, define_es_module, define_property, has_use_strict, initialize_to_undefined, + local_name_for_src, make_descriptor, use_strict, Exports, ModulePass, Scope, +}; +use crate::path::{ImportResolver, NoopImportResolver}; + pub fn amd(config: Config) -> impl Fold { Amd { config, @@ -74,6 +76,8 @@ where { noop_fold_type!(); + mark_as_nested!(); + fn fold_expr(&mut self, expr: Expr) -> Expr { let top_level = self.in_top_level; @@ -662,8 +666,6 @@ where ..var } } - - mark_as_nested!(); } impl ModulePass for Amd diff --git a/crates/swc_ecma_transforms_module/src/common_js.rs b/crates/swc_ecma_transforms_module/src/common_js.rs index 76a10a1aba6..1cd02061f48 100644 --- a/crates/swc_ecma_transforms_module/src/common_js.rs +++ b/crates/swc_ecma_transforms_module/src/common_js.rs @@ -1,14 +1,9 @@ -pub use super::util::Config; -use super::util::{ - define_es_module, define_property, has_use_strict, initialize_to_undefined, make_descriptor, - make_require_call, use_strict, ModulePass, Scope, -}; -use crate::path::{ImportResolver, NoopImportResolver}; -use indexmap::IndexSet; use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, }; + +use indexmap::IndexSet; use swc_atoms::{js_word, JsWord}; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -22,6 +17,13 @@ use swc_ecma_utils::{ }; use swc_ecma_visit::{noop_fold_type, noop_visit_type, Fold, FoldWith, Visit, VisitWith}; +pub use super::util::Config; +use super::util::{ + define_es_module, define_property, has_use_strict, initialize_to_undefined, make_descriptor, + make_require_call, use_strict, ModulePass, Scope, +}; +use crate::path::{ImportResolver, NoopImportResolver}; + pub fn common_js( top_level_mark: Mark, config: Config, @@ -81,9 +83,13 @@ impl Visit for LazyIdentifierVisitor { noop_visit_type!(); fn visit_import_decl(&mut self, _: &ImportDecl) {} + fn visit_export_decl(&mut self, _: &ExportDecl) {} + fn visit_named_export(&mut self, _: &NamedExport) {} + fn visit_export_default_decl(&mut self, _: &ExportDefaultDecl) {} + fn visit_export_default_expr(&mut self, _: &ExportDefaultExpr) {} fn visit_export_all(&mut self, export: &ExportAll) { @@ -91,13 +97,19 @@ impl Visit for LazyIdentifierVisitor { } fn visit_labeled_stmt(&mut self, _: &LabeledStmt) {} + fn visit_continue_stmt(&mut self, _: &ContinueStmt) {} fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} + fn visit_function(&mut self, _: &Function) {} + fn visit_constructor(&mut self, _: &Constructor) {} + fn visit_setter_prop(&mut self, _: &SetterProp) {} + fn visit_getter_prop(&mut self, _: &GetterProp) {} + fn visit_class_prop(&mut self, _: &ClassProp) {} fn visit_prop_name(&mut self, prop_name: &PropName) { @@ -139,6 +151,8 @@ where { noop_fold_type!(); + mark_as_nested!(); + fn fold_module_items(&mut self, items: Vec) -> Vec { let mut emitted_esmodule = false; let mut stmts = Vec::with_capacity(items.len() + 4); @@ -879,8 +893,6 @@ where node.fold_children_with(self) } - - mark_as_nested!(); } impl

ModulePass for CommonJs

diff --git a/crates/swc_ecma_transforms_module/src/hoist.rs b/crates/swc_ecma_transforms_module/src/hoist.rs index 03ebd0a022c..acd788935fd 100644 --- a/crates/swc_ecma_transforms_module/src/hoist.rs +++ b/crates/swc_ecma_transforms_module/src/hoist.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; + use swc_atoms::JsWord; use swc_common::{collections::AHashMap, pass::CompilerPass, util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_transforms_module/src/import_analysis.rs b/crates/swc_ecma_transforms_module/src/import_analysis.rs index 15ae46e4475..e39278ab028 100644 --- a/crates/swc_ecma_transforms_module/src/import_analysis.rs +++ b/crates/swc_ecma_transforms_module/src/import_analysis.rs @@ -1,5 +1,5 @@ -use super::util::Scope; use std::{cell::RefCell, rc::Rc}; + use swc_atoms::{js_word, JsWord}; use swc_common::collections::AHashSet; use swc_ecma_ast::*; @@ -8,6 +8,8 @@ use swc_ecma_visit::{ as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitWith, }; +use super::util::Scope; + pub fn import_analyzer(scope: Rc>) -> impl Fold + VisitMut { as_folder(ImportAnalyzer { scope, diff --git a/crates/swc_ecma_transforms_module/src/path.rs b/crates/swc_ecma_transforms_module/src/path.rs index d0dd11bedab..7906ac4637c 100644 --- a/crates/swc_ecma_transforms_module/src/path.rs +++ b/crates/swc_ecma_transforms_module/src/path.rs @@ -1,11 +1,12 @@ -use anyhow::Error; -use pathdiff::diff_paths; use std::{ borrow::Cow, env::current_dir, path::{Component, PathBuf}, sync::Arc, }; + +use anyhow::Error; +use pathdiff::diff_paths; use swc_atoms::JsWord; use swc_common::FileName; use swc_ecma_loader::resolve::Resolve; diff --git a/crates/swc_ecma_transforms_module/src/rewriter.rs b/crates/swc_ecma_transforms_module/src/rewriter.rs index 37f07299c5a..5f64b8b262e 100644 --- a/crates/swc_ecma_transforms_module/src/rewriter.rs +++ b/crates/swc_ecma_transforms_module/src/rewriter.rs @@ -1,9 +1,10 @@ -use crate::path::ImportResolver; use anyhow::Context; use swc_common::FileName; use swc_ecma_ast::*; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; +use crate::path::ImportResolver; + /// Import rewriter, which rewrites imports as es modules. pub fn import_rewriter(base: FileName, resolver: R) -> impl Fold + VisitMut where diff --git a/crates/swc_ecma_transforms_module/src/umd.rs b/crates/swc_ecma_transforms_module/src/umd.rs index bd8fec19ff9..8d4632b5cb3 100644 --- a/crates/swc_ecma_transforms_module/src/umd.rs +++ b/crates/swc_ecma_transforms_module/src/umd.rs @@ -1,12 +1,6 @@ -use self::config::BuiltConfig; -pub use self::config::Config; -use super::util::{ - self, define_es_module, define_property, has_use_strict, initialize_to_undefined, - local_name_for_src, make_descriptor, make_require_call, use_strict, Exports, ModulePass, Scope, -}; -use crate::path::{ImportResolver, NoopImportResolver}; -use indexmap::IndexSet; use std::cell::{Ref, RefCell, RefMut}; + +use indexmap::IndexSet; use swc_atoms::js_word; use swc_common::{sync::Lrc, FileName, Mark, SourceMap, DUMMY_SP}; use swc_ecma_ast::*; @@ -17,6 +11,14 @@ use swc_ecma_utils::{ }; use swc_ecma_visit::{noop_fold_type, Fold, FoldWith, VisitWith}; +use self::config::BuiltConfig; +pub use self::config::Config; +use super::util::{ + self, define_es_module, define_property, has_use_strict, initialize_to_undefined, + local_name_for_src, make_descriptor, make_require_call, use_strict, Exports, ModulePass, Scope, +}; +use crate::path::{ImportResolver, NoopImportResolver}; + mod config; pub fn umd(cm: Lrc, root_mark: Mark, config: Config) -> impl Fold { @@ -77,6 +79,8 @@ where { noop_fold_type!(); + mark_as_nested!(); + fn fold_expr(&mut self, expr: Expr) -> Expr { let exports = self.exports.0.clone(); let top_level = self.in_top_level; @@ -797,8 +801,6 @@ where ..var } } - - mark_as_nested!(); } impl ModulePass for Umd diff --git a/crates/swc_ecma_transforms_module/src/umd/config.rs b/crates/swc_ecma_transforms_module/src/umd/config.rs index 519c7707d8c..e142f9899a7 100644 --- a/crates/swc_ecma_transforms_module/src/umd/config.rs +++ b/crates/swc_ecma_transforms_module/src/umd/config.rs @@ -1,13 +1,15 @@ -use super::super::util; +use std::collections::HashMap; + use inflector::Inflector; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; use swc_atoms::JsWord; use swc_common::{errors::HANDLER, sync::Lrc, FileName, SourceMap}; use swc_ecma_ast::{Expr, Ident}; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax}; use swc_ecma_utils::quote_ident; +use super::super::util; + #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Config { @@ -66,6 +68,7 @@ impl BuiltConfig { src.split('/').last().unwrap().to_camel_case().into() } + pub fn determine_export_name(&self, filename: FileName) -> Ident { match filename { FileName::Real(ref path) => { diff --git a/crates/swc_ecma_transforms_module/src/util.rs b/crates/swc_ecma_transforms_module/src/util.rs index 7f0033f3176..9c45ed53f76 100644 --- a/crates/swc_ecma_transforms_module/src/util.rs +++ b/crates/swc_ecma_transforms_module/src/util.rs @@ -1,13 +1,13 @@ -use crate::path::ImportResolver; -use anyhow::Context; -use indexmap::{IndexMap, IndexSet}; -use inflector::Inflector; -use serde::{Deserialize, Serialize}; use std::{ cell::{Ref, RefMut}, collections::hash_map::Entry, iter, }; + +use anyhow::Context; +use indexmap::{IndexMap, IndexSet}; +use inflector::Inflector; +use serde::{Deserialize, Serialize}; use swc_atoms::{js_word, JsWord}; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -21,6 +21,8 @@ use swc_ecma_utils::{ }; use swc_ecma_visit::{Fold, FoldWith, VisitWith}; +use crate::path::ImportResolver; + pub(super) trait ModulePass: Fold { fn config(&self) -> &Config; fn scope(&self) -> Ref; diff --git a/crates/swc_ecma_transforms_module/tests/common_js.rs b/crates/swc_ecma_transforms_module/tests/common_js.rs index 140165cefe8..ec9e683b2c9 100644 --- a/crates/swc_ecma_transforms_module/tests/common_js.rs +++ b/crates/swc_ecma_transforms_module/tests/common_js.rs @@ -1,4 +1,5 @@ use std::{cell::RefCell, path::PathBuf, rc::Rc}; + use swc_common::{chain, Mark}; use swc_ecma_parser::{EsConfig, Syntax, TsConfig}; use swc_ecma_transforms_base::{ diff --git a/crates/swc_ecma_transforms_optimization/src/const_modules.rs b/crates/swc_ecma_transforms_optimization/src/const_modules.rs index a623f37b62c..bd01a8054a0 100644 --- a/crates/swc_ecma_transforms_optimization/src/const_modules.rs +++ b/crates/swc_ecma_transforms_optimization/src/const_modules.rs @@ -1,6 +1,7 @@ +use std::{collections::HashMap, sync::Arc}; + use dashmap::DashMap; use once_cell::sync::Lazy; -use std::{collections::HashMap, sync::Arc}; use swc_atoms::JsWord; use swc_common::{errors::HANDLER, sync::Lrc, util::move_map::MoveMap, FileName, SourceMap}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_transforms_optimization/src/inline_globals.rs b/crates/swc_ecma_transforms_optimization/src/inline_globals.rs index 224974856da..1ed4b241f3e 100644 --- a/crates/swc_ecma_transforms_optimization/src/inline_globals.rs +++ b/crates/swc_ecma_transforms_optimization/src/inline_globals.rs @@ -214,11 +214,12 @@ impl VisitMut for InlineGlobals { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::{test, Tester}; use swc_ecma_utils::DropSpan; use swc_ecma_visit::as_folder; + use super::*; + fn mk_map( tester: &mut Tester<'_>, values: &[(&str, &str)], diff --git a/crates/swc_ecma_transforms_optimization/src/json_parse.rs b/crates/swc_ecma_transforms_optimization/src/json_parse.rs index e8aea4e2b7b..649f65130f0 100644 --- a/crates/swc_ecma_transforms_optimization/src/json_parse.rs +++ b/crates/swc_ecma_transforms_optimization/src/json_parse.rs @@ -1,5 +1,6 @@ -use serde_json::Value; use std::usize; + +use serde_json::Value; use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::perf::Parallel; @@ -142,9 +143,10 @@ fn jsonify(e: Expr) -> Value { #[cfg(test)] mod tests { - use super::*; use swc_ecma_transforms_testing::test; + use super::*; + struct Normalizer; impl Fold for Normalizer { fn fold_str(&mut self, mut node: Str) -> Str { diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs index 1940074ccb4..e9c497b76a7 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs @@ -1,4 +1,5 @@ use std::{borrow::Cow, cmp::min, iter::once, mem::take}; + use swc_atoms::js_word; use swc_common::{ pass::{CompilerPass, Repeated}, diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/branch/tests.rs b/crates/swc_ecma_transforms_optimization/src/simplify/branch/tests.rs index 72ffa9d4fd1..29fe42b7af0 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/branch/tests.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/branch/tests.rs @@ -1,6 +1,7 @@ -use super::{super::expr_simplifier, dead_branch_remover}; use swc_common::chain; +use super::{super::expr_simplifier, dead_branch_remover}; + macro_rules! test_stmt { ($l:expr, $r:expr) => { swc_ecma_transforms_testing::test_transform( diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs index b8f2dafb355..ca730e268e9 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs @@ -1,9 +1,9 @@ -use crate::util::Readonly; -#[cfg(feature = "concurrent")] -use rayon::prelude::*; use std::borrow::Cow; #[cfg(feature = "concurrent")] use std::sync::Arc; + +#[cfg(feature = "concurrent")] +use rayon::prelude::*; use swc_common::{ collections::{AHashMap, AHashSet}, pass::{CompilerPass, Repeated}, @@ -19,6 +19,8 @@ use swc_ecma_visit::{ }; use tracing::{debug, span, trace, Level}; +use crate::util::Readonly; + /// Note: This becomes parallel if `concurrent` feature is enabled. pub fn dce(config: Config) -> impl Fold + VisitMut + Repeated + CompilerPass { as_folder(TreeShaker { diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs index 3b9f6e87696..60a6f3af039 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs @@ -1,4 +1,5 @@ use std::{borrow::Cow, iter, iter::once}; + use swc_atoms::{js_word, JsWord}; use swc_common::{ pass::{CompilerPass, Repeated}, diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/expr/tests.rs b/crates/swc_ecma_transforms_optimization/src/simplify/expr/tests.rs index 3115cd10209..8703e31eae3 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/expr/tests.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/expr/tests.rs @@ -1,6 +1,7 @@ -use super::expr_simplifier; use swc_ecma_transforms_testing::test_transform; +use super::expr_simplifier; + fn fold(src: &str, expected: &str) { test_transform( ::swc_ecma_parser::Syntax::default(), diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs index 90dad356e7f..6d0c3dc7133 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs @@ -1,5 +1,5 @@ -use self::scope::{Scope, ScopeKind, VarType}; use std::borrow::Cow; + use swc_common::{ pass::{CompilerPass, Repeated}, util::take::Take, @@ -13,6 +13,8 @@ use swc_ecma_visit::{ }; use tracing::{span, Level}; +use self::scope::{Scope, ScopeKind, VarType}; + mod scope; #[derive(Debug, Default)] @@ -738,11 +740,11 @@ struct IdentListVisitor<'a, 'b> { impl Visit for IdentListVisitor<'_, '_> { noop_visit_type!(); + visit_obj_and_computed!(); + fn visit_ident(&mut self, node: &Ident) { self.scope.add_write(&node.to_id(), true); } - - visit_obj_and_computed!(); } /// Mark idents as `written`. @@ -753,9 +755,9 @@ struct WriteVisitor<'a, 'b> { impl Visit for WriteVisitor<'_, '_> { noop_visit_type!(); + visit_obj_and_computed!(); + fn visit_ident(&mut self, node: &Ident) { self.scope.add_write(&node.to_id(), false); } - - visit_obj_and_computed!(); } diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/inlining/scope.rs b/crates/swc_ecma_transforms_optimization/src/simplify/inlining/scope.rs index d715eb193c5..a0444ab2cf0 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/inlining/scope.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/inlining/scope.rs @@ -1,12 +1,12 @@ #![allow(dead_code)] -use super::{Inlining, Phase}; -use indexmap::map::{Entry, IndexMap}; use std::{ borrow::Cow, cell::{Cell, RefCell}, collections::VecDeque, }; + +use indexmap::map::{Entry, IndexMap}; use swc_atoms::js_word; use swc_common::collections::{AHashMap, AHashSet}; use swc_ecma_ast::*; @@ -14,6 +14,8 @@ use swc_ecma_transforms_base::ext::ExprRefExt; use swc_ecma_utils::{ident::IdentLike, Id}; use tracing::{span, Level}; +use super::{Inlining, Phase}; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ScopeKind { /// If / Switch diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/mod.rs index ddf239a935b..57432145f94 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/mod.rs @@ -1,10 +1,11 @@ //! Ported from closure compiler. +use swc_common::{chain, pass::Repeat}; +use swc_ecma_transforms_base::pass::RepeatedJsPass; + pub use self::{ branch::dead_branch_remover, expr::{expr_simplifier, Config as ExprSimplifierConfig}, }; -use swc_common::{chain, pass::Repeat}; -use swc_ecma_transforms_base::pass::RepeatedJsPass; mod branch; pub mod const_propgation; diff --git a/crates/swc_ecma_transforms_optimization/tests/const_modules.rs b/crates/swc_ecma_transforms_optimization/tests/const_modules.rs index 1d0aa32da7d..8a896246833 100644 --- a/crates/swc_ecma_transforms_optimization/tests/const_modules.rs +++ b/crates/swc_ecma_transforms_optimization/tests/const_modules.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; + use swc_ecma_transforms_optimization::const_modules; use swc_ecma_transforms_testing::{test, Tester}; use swc_ecma_visit::Fold; diff --git a/crates/swc_ecma_transforms_optimization/tests/fixture.rs b/crates/swc_ecma_transforms_optimization/tests/fixture.rs index 5b0ad267135..5c13566f71e 100644 --- a/crates/swc_ecma_transforms_optimization/tests/fixture.rs +++ b/crates/swc_ecma_transforms_optimization/tests/fixture.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; + use swc_common::pass::Repeat; use swc_ecma_parser::{EsConfig, Syntax}; use swc_ecma_transforms_optimization::simplify::{dce::dce, expr_simplifier}; diff --git a/crates/swc_ecma_transforms_optimization/tests/simplify.rs b/crates/swc_ecma_transforms_optimization/tests/simplify.rs index b8ea866a5ac..298c7efcec2 100644 --- a/crates/swc_ecma_transforms_optimization/tests/simplify.rs +++ b/crates/swc_ecma_transforms_optimization/tests/simplify.rs @@ -1,6 +1,7 @@ //! Copied from PeepholeIntegrationTest from the google closure compiler. use std::{cell::RefCell, rc::Rc}; + use swc_common::{chain, Mark}; use swc_ecma_parser::{EsConfig, Syntax, TsConfig}; use swc_ecma_transforms_base::{ diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs index b465c33acad..13ab740a3be 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs @@ -1,10 +1,11 @@ -use super::EnumKind; use swc_atoms::{js_word, JsWord}; use swc_common::{collections::AHashMap, util::move_map::MoveMap, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{member_expr, quote_ident, undefined, ExprFactory}; use swc_ecma_visit::{noop_fold_type, Fold, FoldWith}; +use super::EnumKind; + /// https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata/blob/master/src/parameter/parameterVisitor.ts pub(super) struct ParamMetadata; diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs index 07f7728c948..2b3d2f1fe55 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs @@ -1,7 +1,6 @@ -use self::metadata::{Metadata, ParamMetadata}; -use super::{contains_decorator, DecoratorFinder}; -use smallvec::SmallVec; use std::mem::take; + +use smallvec::SmallVec; use swc_atoms::JsWord; use swc_common::{collections::AHashMap, util::move_map::MoveMap, DUMMY_SP}; use swc_ecma_ast::*; @@ -13,6 +12,9 @@ use swc_ecma_utils::{ }; use swc_ecma_visit::{noop_fold_type, Fold, FoldWith, Visit, VisitWith}; +use self::metadata::{Metadata, ParamMetadata}; +use super::{contains_decorator, DecoratorFinder}; + mod metadata; #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs index bcba59721f4..d586f6bc966 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs @@ -1,6 +1,7 @@ +use std::{iter, mem::take}; + use either::Either; use serde::Deserialize; -use std::{iter, mem::take}; use swc_common::{Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::helper; diff --git a/crates/swc_ecma_transforms_react/src/display_name/mod.rs b/crates/swc_ecma_transforms_react/src/display_name/mod.rs index b255e295a73..6c527daba32 100644 --- a/crates/swc_ecma_transforms_react/src/display_name/mod.rs +++ b/crates/swc_ecma_transforms_react/src/display_name/mod.rs @@ -1,4 +1,5 @@ use std::ops::DerefMut; + use swc_atoms::js_word; use swc_common::DUMMY_SP; use swc_ecma_ast::*; @@ -135,6 +136,7 @@ impl VisitMut for Folder { add_display_name(expr, name) } } + /// Don't recurse into object. fn visit_mut_object_lit(&mut self, _: &mut ObjectLit) {} } diff --git a/crates/swc_ecma_transforms_react/src/display_name/tests.rs b/crates/swc_ecma_transforms_react/src/display_name/tests.rs index 8e1de9ec3b4..1a8ebf0ada1 100644 --- a/crates/swc_ecma_transforms_react/src/display_name/tests.rs +++ b/crates/swc_ecma_transforms_react/src/display_name/tests.rs @@ -1,6 +1,7 @@ -use super::*; use swc_ecma_transforms_testing::test; +use super::*; + fn tr() -> impl Fold { display_name() } diff --git a/crates/swc_ecma_transforms_react/src/jsx/mod.rs b/crates/swc_ecma_transforms_react/src/jsx/mod.rs index 4217c90258c..03c5e07fd27 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/mod.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/mod.rs @@ -1,12 +1,11 @@ #![allow(clippy::redundant_allocation)] -use self::static_check::should_use_create_element; -use crate::refresh::options::{deserialize_refresh, RefreshOptions}; +use std::{borrow::Cow, iter, iter::once, mem, sync::Arc}; + use dashmap::DashMap; use once_cell::sync::Lazy; use regex::Regex; use serde::{Deserialize, Serialize}; -use std::{borrow::Cow, iter, iter::once, mem, sync::Arc}; use string_enum::StringEnum; use swc_atoms::{js_word, JsWord}; use swc_common::{ @@ -25,6 +24,9 @@ use swc_ecma_utils::{ }; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; +use self::static_check::should_use_create_element; +use crate::refresh::options::{deserialize_refresh, RefreshOptions}; + mod static_check; #[cfg(test)] mod tests; diff --git a/crates/swc_ecma_transforms_react/src/jsx/tests.rs b/crates/swc_ecma_transforms_react/src/jsx/tests.rs index 8c26c058070..396bc2bd257 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/tests.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/tests.rs @@ -1,8 +1,7 @@ #![allow(dead_code)] -use super::*; -use crate::{display_name, react}; use std::path::PathBuf; + use swc_common::{chain, Mark}; use swc_ecma_parser::EsConfig; use swc_ecma_transforms_base::resolver::resolver_with_mark; @@ -13,6 +12,9 @@ use swc_ecma_transforms_compat::{ use swc_ecma_transforms_module::common_js::common_js; use swc_ecma_transforms_testing::{parse_options, test, test_fixture_allowing_error, Tester}; +use super::*; +use crate::{display_name, react}; + fn tr(t: &mut Tester, options: Options, top_level_mark: Mark) -> impl Fold { chain!( resolver_with_mark(top_level_mark), diff --git a/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs b/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs index f4f063f1d41..9fbf7546de2 100644 --- a/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs +++ b/crates/swc_ecma_transforms_react/src/jsx_self/tests.rs @@ -1,6 +1,7 @@ -use super::*; use swc_ecma_transforms_testing::test; +use super::*; + fn tr() -> impl Fold { jsx_self(true) } diff --git a/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs b/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs index 7f3c5660476..931138b8d19 100644 --- a/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs +++ b/crates/swc_ecma_transforms_react/src/jsx_src/tests.rs @@ -1,7 +1,8 @@ -use super::*; use swc_common::{sync::Lrc, FilePathMapping}; use swc_ecma_transforms_testing::{test, test_exec}; +use super::*; + fn tr() -> impl Fold { let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); jsx_src(true, cm) diff --git a/crates/swc_ecma_transforms_react/src/lib.rs b/crates/swc_ecma_transforms_react/src/lib.rs index 1cbf68f8e42..d9138575060 100644 --- a/crates/swc_ecma_transforms_react/src/lib.rs +++ b/crates/swc_ecma_transforms_react/src/lib.rs @@ -1,5 +1,8 @@ #![deny(clippy::all)] +use swc_common::{chain, comments::Comments, sync::Lrc, Mark, SourceMap}; +use swc_ecma_visit::Fold; + pub use self::{ display_name::display_name, jsx::{jsx, parse_expr_for_jsx, JsxDirectives, Options, Runtime}, @@ -8,8 +11,6 @@ pub use self::{ pure_annotations::pure_annotations, refresh::{options::RefreshOptions, refresh}, }; -use swc_common::{chain, comments::Comments, sync::Lrc, Mark, SourceMap}; -use swc_ecma_visit::Fold; mod display_name; mod jsx; diff --git a/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs b/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs index 773459f08ba..7cf3e664124 100644 --- a/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs +++ b/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs @@ -1,4 +1,3 @@ -use super::*; use swc_common::{comments::SingleThreadedComments, sync::Lrc, FileName, Mark, SourceMap}; use swc_ecma_codegen::{text_writer::JsWriter, Emitter}; use swc_ecma_parser::{Parser, StringInput}; @@ -6,6 +5,8 @@ use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_testing::Tester; use swc_ecma_visit::FoldWith; +use super::*; + fn parse( tester: &mut Tester, src: &str, diff --git a/crates/swc_ecma_transforms_react/src/refresh/hook.rs b/crates/swc_ecma_transforms_react/src/refresh/hook.rs index 02060acd078..aaaf1c75269 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/hook.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/hook.rs @@ -1,8 +1,9 @@ +use std::mem; + use indexmap::IndexSet; use once_cell::sync::Lazy; use regex::Regex; use sha1::{Digest, Sha1}; -use std::mem; use swc_atoms::JsWord; use swc_common::{util::take::Take, SourceMap, Spanned, DUMMY_SP}; use swc_ecma_ast::*; @@ -11,9 +12,8 @@ use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith, }; -use crate::RefreshOptions; - use super::util::{is_builtin_hook, make_call_expr, make_call_stmt, CollectIdent}; +use crate::RefreshOptions; // function that use hooks struct HookSig { diff --git a/crates/swc_ecma_transforms_react/src/refresh/mod.rs b/crates/swc_ecma_transforms_react/src/refresh/mod.rs index 125444c4184..36139ace8f8 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/mod.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/mod.rs @@ -1,10 +1,3 @@ -use self::{ - hook::HookRegister, - util::{ - collect_ident_in_jsx, is_body_arrow_fn, is_import_or_require, make_assign_stmt, - CollectIdent, - }, -}; use indexmap::IndexSet; use swc_atoms::JsWord; use swc_common::{ @@ -15,6 +8,14 @@ use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, private_ident, quote_ident, quote_str, Id}; use swc_ecma_visit::{as_folder, Fold, Visit, VisitMut, VisitMutWith}; +use self::{ + hook::HookRegister, + util::{ + collect_ident_in_jsx, is_body_arrow_fn, is_import_or_require, make_assign_stmt, + CollectIdent, + }, +}; + pub mod options; use options::RefreshOptions; mod hook; diff --git a/crates/swc_ecma_transforms_react/src/refresh/tests.rs b/crates/swc_ecma_transforms_react/src/refresh/tests.rs index 78c45cfa684..ec061103044 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/tests.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/tests.rs @@ -1,9 +1,10 @@ -use super::*; use swc_common::{chain, Mark}; use swc_ecma_transforms_base::resolver::{resolver, resolver_with_mark}; use swc_ecma_transforms_module::common_js::common_js; use swc_ecma_transforms_testing::{test, Tester}; +use super::*; + fn tr(t: &mut Tester) -> impl Fold { let top_level_mark = Mark::fresh(Mark::root()); diff --git a/crates/swc_ecma_transforms_testing/src/lib.rs b/crates/swc_ecma_transforms_testing/src/lib.rs index 177ac2e597d..4a903c2e598 100644 --- a/crates/swc_ecma_transforms_testing/src/lib.rs +++ b/crates/swc_ecma_transforms_testing/src/lib.rs @@ -1,10 +1,6 @@ #![deny(clippy::all)] #![allow(clippy::result_unit_err)] -use ansi_term::Color; -use anyhow::{bail, Context, Error}; -use serde::de::DeserializeOwned; -use sha1::{Digest, Sha1}; use std::{ env, fs::{self, create_dir_all, read_to_string, OpenOptions}, @@ -15,6 +11,11 @@ use std::{ rc::Rc, sync::{Arc, RwLock}, }; + +use ansi_term::Color; +use anyhow::{bail, Context, Error}; +use serde::de::DeserializeOwned; +use sha1::{Digest, Sha1}; use swc_common::{ chain, comments::SingleThreadedComments, diff --git a/crates/swc_ecma_transforms_typescript/examples/ts_to_js.rs b/crates/swc_ecma_transforms_typescript/examples/ts_to_js.rs index 129f3f3de1f..83288910e4f 100644 --- a/crates/swc_ecma_transforms_typescript/examples/ts_to_js.rs +++ b/crates/swc_ecma_transforms_typescript/examples/ts_to_js.rs @@ -3,6 +3,7 @@ //! This program will emit output to stdout. use std::{env, path::Path}; + use swc_common::{ self, comments::SingleThreadedComments, diff --git a/crates/swc_ecma_transforms_typescript/src/strip.rs b/crates/swc_ecma_transforms_typescript/src/strip.rs index b042abf87f6..553c3234e03 100644 --- a/crates/swc_ecma_transforms_typescript/src/strip.rs +++ b/crates/swc_ecma_transforms_typescript/src/strip.rs @@ -1,5 +1,6 @@ -use serde::{Deserialize, Serialize}; use std::mem::take; + +use serde::{Deserialize, Serialize}; use swc_atoms::{js_word, JsWord}; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -1774,6 +1775,8 @@ impl Visit for Strip where C: Comments, { + visit_obj_and_computed!(); + fn visit_assign_pat_prop(&mut self, n: &AssignPatProp) { if !self.in_var_pat { n.key.visit_with(self); @@ -1875,8 +1878,6 @@ where } } - visit_obj_and_computed!(); - fn visit_module_items(&mut self, n: &[ModuleItem]) { let old = self.non_top_level; self.non_top_level = false; @@ -1960,6 +1961,17 @@ impl VisitMut for Strip where C: Comments, { + type_to_none!(visit_mut_opt_ts_type, Box); + + type_to_none!(visit_mut_opt_ts_type_ann, TsTypeAnn); + + type_to_none!(visit_mut_opt_ts_type_param_decl, TsTypeParamDecl); + + type_to_none!( + visit_mut_opt_ts_type_param_instantiation, + TsTypeParamInstantiation + ); + fn visit_mut_array_pat(&mut self, n: &mut ArrayPat) { n.visit_mut_children_with(self); n.optional = false; @@ -2510,14 +2522,6 @@ where }); } - type_to_none!(visit_mut_opt_ts_type, Box); - type_to_none!(visit_mut_opt_ts_type_ann, TsTypeAnn); - type_to_none!(visit_mut_opt_ts_type_param_decl, TsTypeParamDecl); - type_to_none!( - visit_mut_opt_ts_type_param_instantiation, - TsTypeParamInstantiation - ); - fn visit_mut_pat_or_expr(&mut self, node: &mut PatOrExpr) { // Coerce bindingident to assign expr where parenthesis exists due to TsAsExpr // like (warn as any) = v; diff --git a/crates/swc_ecma_transforms_typescript/tests/strip_correctness.rs b/crates/swc_ecma_transforms_typescript/tests/strip_correctness.rs index b11cf4fbf58..61ac95eec9b 100644 --- a/crates/swc_ecma_transforms_typescript/tests/strip_correctness.rs +++ b/crates/swc_ecma_transforms_typescript/tests/strip_correctness.rs @@ -3,6 +3,7 @@ use std::{ path::PathBuf, sync::{Arc, RwLock}, }; + use swc_common::{FileName, Mark}; use swc_ecma_ast::*; use swc_ecma_codegen::{self, Emitter}; diff --git a/crates/swc_ecma_utils/src/constructor.rs b/crates/swc_ecma_utils/src/constructor.rs index abbc5c961bd..1bb6e9a24f9 100644 --- a/crates/swc_ecma_utils/src/constructor.rs +++ b/crates/swc_ecma_utils/src/constructor.rs @@ -1,9 +1,11 @@ -use crate::{prepend_stmts, ExprFactory}; use std::iter; + use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_fold_type, noop_visit_mut_type, Fold, FoldWith, VisitMut, VisitMutWith}; +use crate::{prepend_stmts, ExprFactory}; + pub fn inject_after_super(c: &mut Constructor, mut exprs: Vec>) { // Allow using super multiple time let mut folder = Injector { diff --git a/crates/swc_ecma_utils/src/factory.rs b/crates/swc_ecma_utils/src/factory.rs index f4363227e84..3b217d6ca31 100644 --- a/crates/swc_ecma_utils/src/factory.rs +++ b/crates/swc_ecma_utils/src/factory.rs @@ -1,4 +1,5 @@ use std::iter; + use swc_atoms::js_word; use swc_common::{Span, Spanned, DUMMY_SP}; use swc_ecma_ast::*; diff --git a/crates/swc_ecma_utils/src/function/fn_env_hoister.rs b/crates/swc_ecma_utils/src/function/fn_env_hoister.rs index 87d3fe44ff5..2d6c3429f9f 100644 --- a/crates/swc_ecma_utils/src/function/fn_env_hoister.rs +++ b/crates/swc_ecma_utils/src/function/fn_env_hoister.rs @@ -72,6 +72,7 @@ impl FnEnvHoister { extend_super(&mut decls, super_get, super_set); decls } + pub fn to_stmt(self) -> Option { let decls = self.to_decl(); diff --git a/crates/swc_ecma_utils/src/lib.rs b/crates/swc_ecma_utils/src/lib.rs index 5003c5dcbeb..7b7da55a59d 100644 --- a/crates/swc_ecma_utils/src/lib.rs +++ b/crates/swc_ecma_utils/src/lib.rs @@ -4,6 +4,25 @@ #[doc(hidden)] pub extern crate swc_ecma_ast; +use std::{ + borrow::Cow, + f64::{INFINITY, NAN}, + hash::Hash, + num::FpCategory, + ops::Add, +}; + +use swc_atoms::{js_word, JsWord}; +#[deprecated(since = "0.50.0", note = "Use `swc_common::errors::HANDLER` directly")] +pub use swc_common::errors::HANDLER; +use swc_common::{collections::AHashSet, Mark, Span, Spanned, SyntaxContext, DUMMY_SP}; +use swc_ecma_ast::*; +use swc_ecma_visit::{ + noop_visit_mut_type, noop_visit_type, visit_mut_obj_and_computed, visit_obj_and_computed, + Visit, VisitMut, VisitMutWith, VisitWith, +}; +use tracing::trace; + pub use self::{ factory::{ExprFactory, IntoIndirectCall}, ident::{id, Id}, @@ -17,23 +36,6 @@ pub use self::{ Purity::{MayBeImpure, Pure}, }; use crate::ident::IdentLike; -use std::{ - borrow::Cow, - f64::{INFINITY, NAN}, - hash::Hash, - num::FpCategory, - ops::Add, -}; -use swc_atoms::{js_word, JsWord}; -#[deprecated(since = "0.50.0", note = "Use `swc_common::errors::HANDLER` directly")] -pub use swc_common::errors::HANDLER; -use swc_common::{collections::AHashSet, Mark, Span, Spanned, SyntaxContext, DUMMY_SP}; -use swc_ecma_ast::*; -use swc_ecma_visit::{ - noop_visit_mut_type, noop_visit_type, visit_mut_obj_and_computed, visit_obj_and_computed, - Visit, VisitMut, VisitMutWith, VisitWith, -}; -use tracing::trace; #[macro_use] mod macros; @@ -241,10 +243,12 @@ impl StmtLike for Stmt { fn try_into_stmt(self) -> Result { Ok(self) } + #[inline] fn as_stmt(&self) -> Option<&Stmt> { Some(self) } + #[inline] fn from_stmt(stmt: Stmt) -> Self { stmt @@ -259,6 +263,7 @@ impl ModuleItemLike for ModuleItem { _ => Err(self), } } + #[inline] fn try_from_module_decl(decl: ModuleDecl) -> Result { Ok(ModuleItem::ModuleDecl(decl)) @@ -272,6 +277,7 @@ impl StmtLike for ModuleItem { _ => Err(self), } } + #[inline] fn as_stmt(&self) -> Option<&Stmt> { match *self { @@ -279,6 +285,7 @@ impl StmtLike for ModuleItem { _ => None, } } + #[inline] fn from_stmt(stmt: Stmt) -> Self { ModuleItem::Stmt(stmt) @@ -1297,6 +1304,7 @@ impl Purity { impl Add for Purity { type Output = Self; + fn add(self, rhs: Self) -> Self { match (self, rhs) { (Pure, Pure) => Pure, @@ -1877,13 +1885,13 @@ pub struct UsageFinder<'a> { impl<'a> Visit for UsageFinder<'a> { noop_visit_type!(); + visit_obj_and_computed!(); + fn visit_ident(&mut self, i: &Ident) { if i.span.ctxt == self.ident.span.ctxt && i.sym == self.ident.sym { self.found = true; } } - - visit_obj_and_computed!(); } impl<'a> UsageFinder<'a> { @@ -2100,13 +2108,13 @@ pub struct IdentReplacer<'a> { impl VisitMut for IdentReplacer<'_> { noop_visit_mut_type!(); + visit_mut_obj_and_computed!(); + fn visit_mut_ident(&mut self, node: &mut Ident) { if node.sym == self.from.0 && node.span.ctxt == self.from.1 { *node = self.to.clone(); } } - - visit_mut_obj_and_computed!(); } pub struct BindingCollector diff --git a/crates/swc_ecma_utils/src/macros.rs b/crates/swc_ecma_utils/src/macros.rs index a5663d54fd9..8e5ca70d2ce 100644 --- a/crates/swc_ecma_utils/src/macros.rs +++ b/crates/swc_ecma_utils/src/macros.rs @@ -95,10 +95,11 @@ macro_rules! member_expr { #[cfg(test)] mod tests { - use crate::drop_span; use swc_common::DUMMY_SP as span; use swc_ecma_ast::*; + use crate::drop_span; + #[test] fn quote_member_expr() { let expr: Box = drop_span(member_expr!(span, Function.prototype.bind)); diff --git a/crates/swc_ecma_utils/src/value.rs b/crates/swc_ecma_utils/src/value.rs index caed0d064e0..3fc65593509 100644 --- a/crates/swc_ecma_utils/src/value.rs +++ b/crates/swc_ecma_utils/src/value.rs @@ -1,6 +1,7 @@ -use self::Value::{Known, Unknown}; use std::ops::Not; +use self::Value::{Known, Unknown}; + /// Runtime value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Value { @@ -99,6 +100,7 @@ impl Value { impl Not for Value { type Output = Self; + fn not(self) -> Self { match self { Value::Known(b) => Value::Known(!b), diff --git a/crates/swc_ecma_utils/src/var.rs b/crates/swc_ecma_utils/src/var.rs index acd2e1a5230..480a1da15b6 100644 --- a/crates/swc_ecma_utils/src/var.rs +++ b/crates/swc_ecma_utils/src/var.rs @@ -1,7 +1,8 @@ -use crate::Id; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; +use crate::Id; + /// This collects variables bindings while ignoring if it's nested in /// expression. pub struct VarCollector<'a> { diff --git a/crates/swc_ecma_visit/src/lib.rs b/crates/swc_ecma_visit/src/lib.rs index 8ed44e87038..8ca1e1fd9df 100644 --- a/crates/swc_ecma_visit/src/lib.rs +++ b/crates/swc_ecma_visit/src/lib.rs @@ -4,8 +4,9 @@ #[doc(hidden)] pub extern crate swc_ecma_ast; -use num_bigint::BigInt as BigIntValue; use std::{borrow::Cow, fmt::Debug}; + +use num_bigint::BigInt as BigIntValue; use swc_atoms::JsWord; use swc_common::{pass::CompilerPass, Span, DUMMY_SP}; use swc_ecma_ast::*; @@ -225,17 +226,23 @@ where V: VisitMut, { delegate!(visit_mut_ident, Ident); + delegate!(visit_mut_span, Span); delegate!(visit_mut_expr, Expr); + delegate!(visit_mut_decl, Decl); + delegate!(visit_mut_stmt, Stmt); + delegate!(visit_mut_pat, Pat); delegate!(visit_mut_ts_type, TsType); delegate!(visit_mut_module, Module); + delegate!(visit_mut_script, Script); + delegate!(visit_mut_program, Program); } @@ -254,15 +261,23 @@ where V: VisitMut, { method!(fold_ident, Ident); + method!(fold_span, Span); method!(fold_expr, Expr); + method!(fold_decl, Decl); + method!(fold_stmt, Stmt); + method!(fold_pat, Pat); method!(fold_ts_type, TsType); + method!(fold_script, Script); + + method!(fold_program, Program); + #[inline(always)] fn fold_module(&mut self, mut n: Module) -> Module { #[cfg(all(debug_assertions, feature = "debug"))] @@ -273,8 +288,6 @@ where n.visit_mut_with(&mut self.0); n } - method!(fold_script, Script); - method!(fold_program, Program); } /// Note: Ignoring more types is not considered as a breaking change. diff --git a/crates/swc_estree_ast/src/class.rs b/crates/swc_estree_ast/src/class.rs index 13aea4a1a79..4d18c4e8745 100644 --- a/crates/swc_estree_ast/src/class.rs +++ b/crates/swc_estree_ast/src/class.rs @@ -1,3 +1,7 @@ +use serde::{ser::SerializeMap, Deserialize, Serialize}; +use serde_json::Value; +use swc_common::ast_serde; + use crate::{ common::{ Access, BaseNode, Decorator, Identifier, Param, PrivateName, SuperTypeParams, @@ -10,9 +14,6 @@ use crate::{ stmt::{BlockStatement, Statement}, typescript::{TSDeclareMethod, TSExpressionWithTypeArguments, TSIndexSignature}, }; -use serde::{ser::SerializeMap, Deserialize, Serialize}; -use serde_json::Value; -use swc_common::ast_serde; #[derive(Debug, Clone, PartialEq)] #[ast_serde] diff --git a/crates/swc_estree_ast/src/comment.rs b/crates/swc_estree_ast/src/comment.rs index 249fa36107e..9c4aafd35cd 100644 --- a/crates/swc_estree_ast/src/comment.rs +++ b/crates/swc_estree_ast/src/comment.rs @@ -1,7 +1,8 @@ -use crate::common::Loc; use serde::{Deserialize, Serialize}; use swc_common::ast_serde; +use crate::common::Loc; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum CommentType { #[serde(rename = "CommentLine")] diff --git a/crates/swc_estree_ast/src/common.rs b/crates/swc_estree_ast/src/common.rs index 48efcfc7363..af137ab2bf9 100644 --- a/crates/swc_estree_ast/src/common.rs +++ b/crates/swc_estree_ast/src/common.rs @@ -1,10 +1,11 @@ +use serde::{Deserialize, Serialize}; +use swc_atoms::JsWord; +use swc_common::ast_serde; + use crate::{ class::*, comment::Comment, decl::*, expr::*, flow::*, jsx::*, lit::*, module::*, object::*, pat::*, stmt::*, typescript::*, }; -use serde::{Deserialize, Serialize}; -use swc_atoms::JsWord; -use swc_common::ast_serde; #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] diff --git a/crates/swc_estree_ast/src/expr.rs b/crates/swc_estree_ast/src/expr.rs index 88cd385b7fa..cbfe5243577 100644 --- a/crates/swc_estree_ast/src/expr.rs +++ b/crates/swc_estree_ast/src/expr.rs @@ -1,3 +1,7 @@ +use serde::{Deserialize, Serialize}; +use swc_atoms::JsWord; +use swc_common::ast_serde; + use crate::{ class::{ClassBody, ClassImpl}, common::{ @@ -16,9 +20,6 @@ use crate::{ TSAsExpression, TSNonNullExpression, TSTypeAssertion, TSTypeParameterInstantiation, }, }; -use serde::{Deserialize, Serialize}; -use swc_atoms::JsWord; -use swc_common::ast_serde; #[derive(Debug, Clone, PartialEq)] #[ast_serde] diff --git a/crates/swc_estree_ast/src/flavor.rs b/crates/swc_estree_ast/src/flavor.rs index 7f5cad2c92b..4304a0295be 100644 --- a/crates/swc_estree_ast/src/flavor.rs +++ b/crates/swc_estree_ast/src/flavor.rs @@ -49,6 +49,7 @@ impl Flavor { pub(crate) fn skip_none(v: &Option) -> bool { matches!(Self::current(), Flavor::Acorn { .. }) && v.is_none() } + pub(crate) fn skip_none_and_false(v: &Option) -> bool { matches!(Self::current(), Flavor::Acorn { .. }) && matches!(v, None | Some(false)) } diff --git a/crates/swc_estree_ast/src/lit.rs b/crates/swc_estree_ast/src/lit.rs index a07522b6e9f..ff68a8872c5 100644 --- a/crates/swc_estree_ast/src/lit.rs +++ b/crates/swc_estree_ast/src/lit.rs @@ -1,9 +1,11 @@ -use crate::{common::BaseNode, expr::Expression, flavor::Flavor, typescript::TSType}; -use serde::{ser::SerializeMap, Deserialize, Serialize}; use std::borrow::Cow; + +use serde::{ser::SerializeMap, Deserialize, Serialize}; use swc_atoms::JsWord; use swc_common::ast_serde; +use crate::{common::BaseNode, expr::Expression, flavor::Flavor, typescript::TSType}; + #[derive(Debug, Clone, PartialEq)] pub enum Literal { String(StringLiteral), diff --git a/crates/swc_estree_ast/src/module.rs b/crates/swc_estree_ast/src/module.rs index b4b0cdb395a..c6c8531dee2 100644 --- a/crates/swc_estree_ast/src/module.rs +++ b/crates/swc_estree_ast/src/module.rs @@ -1,3 +1,8 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use swc_atoms::JsWord; +use swc_common::ast_serde; + use crate::{ class::ClassDeclaration, comment::Comment, @@ -8,10 +13,6 @@ use crate::{ stmt::Statement, typescript::TSDeclareFunction, }; -use serde::{Deserialize, Serialize}; -use serde_json::Value; -use swc_atoms::JsWord; -use swc_common::ast_serde; #[derive(Debug, Clone, PartialEq)] #[ast_serde] diff --git a/crates/swc_estree_ast/src/ser.rs b/crates/swc_estree_ast/src/ser.rs index b9c5e627304..576504a64ae 100644 --- a/crates/swc_estree_ast/src/ser.rs +++ b/crates/swc_estree_ast/src/ser.rs @@ -1,6 +1,7 @@ -use crate::flavor::Flavor; use serde::Serializer; +use crate::flavor::Flavor; + pub(crate) fn serialize_optional(o: &Option, s: S) -> Result where S: Serializer, diff --git a/crates/swc_estree_compat/benches/babelify.rs b/crates/swc_estree_compat/benches/babelify.rs index 49788fcefab..c4ef159f589 100644 --- a/crates/swc_estree_compat/benches/babelify.rs +++ b/crates/swc_estree_compat/benches/babelify.rs @@ -4,6 +4,7 @@ extern crate test; use std::{hint::black_box, io::stderr, sync::Arc}; + use swc::config::IsModule; use swc_common::{errors::Handler, FileName, FilePathMapping, Mark, SourceFile, SourceMap}; use swc_ecma_ast::{EsVersion, Program}; diff --git a/crates/swc_estree_compat/src/babelify/class.rs b/crates/swc_estree_compat/src/babelify/class.rs index 6b3f0541cbb..bd9590605ad 100644 --- a/crates/swc_estree_compat/src/babelify/class.rs +++ b/crates/swc_estree_compat/src/babelify/class.rs @@ -1,4 +1,3 @@ -use crate::babelify::{extract_class_body_span, Babelify, Context}; use copyless::BoxHelper; use serde_json::value::Value; use swc_ecma_ast::{ @@ -11,6 +10,8 @@ use swc_estree_ast::{ StaticBlock as BabelStaticBlock, }; +use crate::babelify::{extract_class_body_span, Babelify, Context}; + impl Babelify for Class { type Output = ClassExpression; diff --git a/crates/swc_estree_compat/src/babelify/decl.rs b/crates/swc_estree_compat/src/babelify/decl.rs index 7cc86e779c3..6445269a0c0 100644 --- a/crates/swc_estree_compat/src/babelify/decl.rs +++ b/crates/swc_estree_compat/src/babelify/decl.rs @@ -1,11 +1,11 @@ -use crate::babelify::{extract_class_body_span, Babelify, Context}; use copyless::BoxHelper; +use swc_ecma_ast::{ClassDecl, Decl, FnDecl, VarDecl, VarDeclKind, VarDeclarator}; use swc_estree_ast::{ ClassBody, ClassDeclaration, Declaration, FunctionDeclaration, VariableDeclaration, VariableDeclarationKind, VariableDeclarator, }; -use swc_ecma_ast::{ClassDecl, Decl, FnDecl, VarDecl, VarDeclKind, VarDeclarator}; +use crate::babelify::{extract_class_body_span, Babelify, Context}; impl Babelify for Decl { type Output = Declaration; diff --git a/crates/swc_estree_compat/src/babelify/expr.rs b/crates/swc_estree_compat/src/babelify/expr.rs index f243dc92e55..209fcff5b12 100644 --- a/crates/swc_estree_compat/src/babelify/expr.rs +++ b/crates/swc_estree_compat/src/babelify/expr.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_atoms::js_word; @@ -22,6 +21,8 @@ use swc_estree_ast::{ UpdateExpression, YieldExpression, }; +use crate::babelify::{Babelify, Context}; + #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ExprOutput { Expr(Box), diff --git a/crates/swc_estree_compat/src/babelify/function.rs b/crates/swc_estree_compat/src/babelify/function.rs index 67187bd3ac4..2eb42e6c055 100644 --- a/crates/swc_estree_compat/src/babelify/function.rs +++ b/crates/swc_estree_compat/src/babelify/function.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use swc_ecma_ast::{Function, Param, ParamOrTsParamProp, Pat}; use swc_estree_ast::{ @@ -6,6 +5,8 @@ use swc_estree_ast::{ Param as BabelParam, Pattern, RestElement, }; +use crate::babelify::{Babelify, Context}; + impl Babelify for Function { type Output = FunctionExpression; diff --git a/crates/swc_estree_compat/src/babelify/ident.rs b/crates/swc_estree_compat/src/babelify/ident.rs index bf042fb3c1b..852346b9041 100644 --- a/crates/swc_estree_compat/src/babelify/ident.rs +++ b/crates/swc_estree_compat/src/babelify/ident.rs @@ -1,8 +1,9 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use swc_ecma_ast::{BindingIdent, Ident, PrivateName}; use swc_estree_ast::{Identifier, PrivateName as BabelPrivateName}; +use crate::babelify::{Babelify, Context}; + impl Babelify for BindingIdent { type Output = Identifier; diff --git a/crates/swc_estree_compat/src/babelify/jsx.rs b/crates/swc_estree_compat/src/babelify/jsx.rs index 8cc810ce61b..95279629425 100644 --- a/crates/swc_estree_compat/src/babelify/jsx.rs +++ b/crates/swc_estree_compat/src/babelify/jsx.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use swc_common::{BytePos, Span, Spanned}; use swc_ecma_ast::{ @@ -18,6 +17,8 @@ use swc_estree_ast::{ JSXSpreadAttribute, JSXSpreadChild as BabelJSXSpreadChild, JSXText as BabelJSXText, }; +use crate::babelify::{Babelify, Context}; + impl Babelify for JSXObject { type Output = JSXMemberExprObject; diff --git a/crates/swc_estree_compat/src/babelify/lit.rs b/crates/swc_estree_compat/src/babelify/lit.rs index 82320569ee7..828de12a233 100644 --- a/crates/swc_estree_compat/src/babelify/lit.rs +++ b/crates/swc_estree_compat/src/babelify/lit.rs @@ -1,11 +1,11 @@ -use crate::babelify::{Babelify, Context}; +use serde::{Deserialize, Serialize}; +use swc_ecma_ast::{BigInt, Bool, Lit, Null, Number, Regex, Str}; use swc_estree_ast::{ BigIntLiteral, BooleanLiteral, JSXText as BabelJSXText, Literal, NullLiteral, NumericLiteral, RegExpLiteral, StringLiteral, }; -use serde::{Deserialize, Serialize}; -use swc_ecma_ast::{BigInt, Bool, Lit, Null, Number, Regex, Str}; +use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum LitOutput { diff --git a/crates/swc_estree_compat/src/babelify/mod.rs b/crates/swc_estree_compat/src/babelify/mod.rs index d1f92a31f99..87ddf0193ed 100644 --- a/crates/swc_estree_compat/src/babelify/mod.rs +++ b/crates/swc_estree_compat/src/babelify/mod.rs @@ -1,6 +1,7 @@ +use std::sync::Arc; + use rayon::prelude::*; use serde::{de::DeserializeOwned, Serialize}; -use std::sync::Arc; use swc_common::{ comments::{CommentKind, Comments}, sync::Lrc, diff --git a/crates/swc_estree_compat/src/babelify/module.rs b/crates/swc_estree_compat/src/babelify/module.rs index 1be169083d2..83b64f27ae3 100644 --- a/crates/swc_estree_compat/src/babelify/module.rs +++ b/crates/swc_estree_compat/src/babelify/module.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use serde::{Deserialize, Serialize}; use swc_common::{comments::Comment, Span}; use swc_ecma_ast::{Module, ModuleItem, Program, Script}; @@ -9,6 +8,8 @@ use swc_estree_ast::{ }; use swc_node_comments::SwcComments; +use crate::babelify::{Babelify, Context}; + impl Babelify for Program { type Output = File; diff --git a/crates/swc_estree_compat/src/babelify/module_decl.rs b/crates/swc_estree_compat/src/babelify/module_decl.rs index 9a3f563cc27..69c73aeb90f 100644 --- a/crates/swc_estree_compat/src/babelify/module_decl.rs +++ b/crates/swc_estree_compat/src/babelify/module_decl.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_ecma_ast::{ @@ -19,6 +18,8 @@ use swc_estree_ast::{ TSNamespaceExportDeclaration, }; +use crate::babelify::{Babelify, Context}; + #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ModuleDeclOutput { Import(ImportDeclaration), diff --git a/crates/swc_estree_compat/src/babelify/operators.rs b/crates/swc_estree_compat/src/babelify/operators.rs index 928396fda91..3353fc7dfc2 100644 --- a/crates/swc_estree_compat/src/babelify/operators.rs +++ b/crates/swc_estree_compat/src/babelify/operators.rs @@ -1,8 +1,8 @@ -use crate::babelify::{Babelify, Context}; -use swc_estree_ast::{BinaryExprOp, LogicalExprOp, UnaryExprOp, UpdateExprOp}; - use serde::{Deserialize, Serialize}; use swc_ecma_ast::{AssignOp, BinaryOp, UnaryOp, UpdateOp}; +use swc_estree_ast::{BinaryExprOp, LogicalExprOp, UnaryExprOp, UpdateExprOp}; + +use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum BinaryOpOutput { @@ -73,6 +73,7 @@ impl Babelify for BinaryOp { // the correct way to handle this case. impl Babelify for AssignOp { type Output = String; + fn babelify(self, _ctx: &Context) -> Self::Output { match self { AssignOp::Assign => "=".into(), diff --git a/crates/swc_estree_compat/src/babelify/pat.rs b/crates/swc_estree_compat/src/babelify/pat.rs index 929d4d0f127..05fee1b8895 100644 --- a/crates/swc_estree_compat/src/babelify/pat.rs +++ b/crates/swc_estree_compat/src/babelify/pat.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_common::Spanned; @@ -11,6 +10,8 @@ use swc_estree_ast::{ Param, Pattern, PatternLike, RestElement, }; +use crate::babelify::{Babelify, Context}; + #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PatOutput { Id(Identifier), diff --git a/crates/swc_estree_compat/src/babelify/prop.rs b/crates/swc_estree_compat/src/babelify/prop.rs index 5c0a8e186d2..d7e2128992a 100644 --- a/crates/swc_estree_compat/src/babelify/prop.rs +++ b/crates/swc_estree_compat/src/babelify/prop.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use swc_common::Spanned; use swc_ecma_ast::{ @@ -9,6 +8,8 @@ use swc_estree_ast::{ ObjectMember, ObjectMethod, ObjectMethodKind, ObjectPropVal, ObjectProperty, }; +use crate::babelify::{Babelify, Context}; + impl Babelify for Prop { type Output = ObjectMember; diff --git a/crates/swc_estree_compat/src/babelify/stmt.rs b/crates/swc_estree_compat/src/babelify/stmt.rs index 6423ce1558a..bb15f44bd86 100644 --- a/crates/swc_estree_compat/src/babelify/stmt.rs +++ b/crates/swc_estree_compat/src/babelify/stmt.rs @@ -1,4 +1,3 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; use swc_ecma_ast::{ BlockStmt, BreakStmt, CatchClause, ContinueStmt, DebuggerStmt, Decl, DoWhileStmt, EmptyStmt, @@ -13,6 +12,8 @@ use swc_estree_ast::{ TryStatement, WhileStatement, WithStatement, }; +use crate::babelify::{Babelify, Context}; + impl Babelify for BlockStmt { type Output = BlockStatement; diff --git a/crates/swc_estree_compat/src/babelify/typescript.rs b/crates/swc_estree_compat/src/babelify/typescript.rs index 00b6016195f..9f2ea781197 100644 --- a/crates/swc_estree_compat/src/babelify/typescript.rs +++ b/crates/swc_estree_compat/src/babelify/typescript.rs @@ -1,6 +1,22 @@ -use crate::babelify::{Babelify, Context}; use copyless::BoxHelper; +use serde::{Deserialize, Serialize}; use swc_atoms::{js_word, JsWord}; +use swc_common::Spanned; +use swc_ecma_ast::{ + Accessibility, Pat, TruePlusMinus, TsArrayType, TsAsExpr, TsCallSignatureDecl, + TsConditionalType, TsConstAssertion, TsConstructSignatureDecl, TsConstructorType, TsEntityName, + TsEnumDecl, TsEnumMember, TsEnumMemberId, TsExportAssignment, TsExprWithTypeArgs, + TsExternalModuleRef, TsFnOrConstructorType, TsFnParam, TsFnType, TsImportEqualsDecl, + TsImportType, TsIndexSignature, TsIndexedAccessType, TsInferType, TsInterfaceBody, + TsInterfaceDecl, TsIntersectionType, TsKeywordType, TsKeywordTypeKind, TsLit, TsLitType, + TsMappedType, TsMethodSignature, TsModuleBlock, TsModuleDecl, TsModuleName, TsModuleRef, + TsNamespaceBody, TsNamespaceDecl, TsNamespaceExportDecl, TsNonNullExpr, TsOptionalType, + TsParamProp, TsParamPropParam, TsParenthesizedType, TsPropertySignature, TsQualifiedName, + TsRestType, TsThisType, TsThisTypeOrIdent, TsTplLitType, TsTupleElement, TsTupleType, TsType, + TsTypeAliasDecl, TsTypeAnn, TsTypeAssertion, TsTypeElement, TsTypeLit, TsTypeOperator, + TsTypeOperatorOp, TsTypeParam, TsTypeParamDecl, TsTypeParamInstantiation, TsTypePredicate, + TsTypeQuery, TsTypeQueryExpr, TsTypeRef, TsUnionOrIntersectionType, TsUnionType, +}; use swc_estree_ast::{ Access, ArrayPattern, IdOrRest, IdOrString, Identifier, ObjectPattern, RestElement, TSAnyKeyword, TSArrayType, TSAsExpression, TSBigIntKeyword, TSBooleanKeyword, @@ -21,23 +37,7 @@ use swc_estree_ast::{ TSUndefinedKeyword, TSUnionType, TSUnknownKeyword, TSVoidKeyword, }; -use serde::{Deserialize, Serialize}; -use swc_common::Spanned; -use swc_ecma_ast::{ - Accessibility, Pat, TruePlusMinus, TsArrayType, TsAsExpr, TsCallSignatureDecl, - TsConditionalType, TsConstAssertion, TsConstructSignatureDecl, TsConstructorType, TsEntityName, - TsEnumDecl, TsEnumMember, TsEnumMemberId, TsExportAssignment, TsExprWithTypeArgs, - TsExternalModuleRef, TsFnOrConstructorType, TsFnParam, TsFnType, TsImportEqualsDecl, - TsImportType, TsIndexSignature, TsIndexedAccessType, TsInferType, TsInterfaceBody, - TsInterfaceDecl, TsIntersectionType, TsKeywordType, TsKeywordTypeKind, TsLit, TsLitType, - TsMappedType, TsMethodSignature, TsModuleBlock, TsModuleDecl, TsModuleName, TsModuleRef, - TsNamespaceBody, TsNamespaceDecl, TsNamespaceExportDecl, TsNonNullExpr, TsOptionalType, - TsParamProp, TsParamPropParam, TsParenthesizedType, TsPropertySignature, TsQualifiedName, - TsRestType, TsThisType, TsThisTypeOrIdent, TsTplLitType, TsTupleElement, TsTupleType, TsType, - TsTypeAliasDecl, TsTypeAnn, TsTypeAssertion, TsTypeElement, TsTypeLit, TsTypeOperator, - TsTypeOperatorOp, TsTypeParam, TsTypeParamDecl, TsTypeParamInstantiation, TsTypePredicate, - TsTypeQuery, TsTypeQueryExpr, TsTypeRef, TsUnionOrIntersectionType, TsUnionType, -}; +use crate::babelify::{Babelify, Context}; impl Babelify for TsTypeAnn { type Output = TSTypeAnnotation; diff --git a/crates/swc_estree_compat/src/swcify/class.rs b/crates/swc_estree_compat/src/swcify/class.rs index debaf62369d..04c1f7f546e 100644 --- a/crates/swc_estree_compat/src/swcify/class.rs +++ b/crates/swc_estree_compat/src/swcify/class.rs @@ -1,10 +1,11 @@ -use super::Context; -use crate::swcify::Swcify; use swc_ecma_ast::{ClassMember, Function, MethodKind, ParamOrTsParamProp, TsExprWithTypeArgs}; use swc_estree_ast::{ ClassBody, ClassBodyEl, ClassImpl, ClassMethodKind, TSExpressionWithTypeArguments, }; +use super::Context; +use crate::swcify::Swcify; + impl Swcify for ClassBody { type Output = Vec; diff --git a/crates/swc_estree_compat/src/swcify/ctx.rs b/crates/swc_estree_compat/src/swcify/ctx.rs index cd8f6353013..3791bca9f8a 100644 --- a/crates/swc_estree_compat/src/swcify/ctx.rs +++ b/crates/swc_estree_compat/src/swcify/ctx.rs @@ -1,4 +1,5 @@ use std::sync::Arc; + use swc_common::{BytePos, FileName, SourceFile, SourceMap, Span, SyntaxContext, DUMMY_SP}; use swc_estree_ast::{BaseNode, LineCol, Loc}; use swc_node_comments::SwcComments; diff --git a/crates/swc_estree_compat/src/swcify/expr.rs b/crates/swc_estree_compat/src/swcify/expr.rs index f6b42c2e7f4..c69e853fc3d 100644 --- a/crates/swc_estree_compat/src/swcify/expr.rs +++ b/crates/swc_estree_compat/src/swcify/expr.rs @@ -1,4 +1,3 @@ -use crate::swcify::Swcify; use swc_atoms::js_word; use swc_common::{Spanned, DUMMY_SP}; use swc_ecma_ast::{ @@ -29,6 +28,7 @@ use swc_estree_ast::{ }; use super::Context; +use crate::swcify::Swcify; impl Swcify for Expression { type Output = Box; diff --git a/crates/swc_estree_compat/src/swcify/jsx.rs b/crates/swc_estree_compat/src/swcify/jsx.rs index 28ebac9904e..bd5db6d7cfa 100644 --- a/crates/swc_estree_compat/src/swcify/jsx.rs +++ b/crates/swc_estree_compat/src/swcify/jsx.rs @@ -1,6 +1,7 @@ -use crate::swcify::{Context, Swcify}; use swc_ecma_ast::Ident; +use crate::swcify::{Context, Swcify}; + impl Swcify for swc_estree_ast::JSXNamespacedName { type Output = swc_ecma_ast::JSXNamespacedName; diff --git a/crates/swc_estree_compat/src/swcify/lit.rs b/crates/swc_estree_compat/src/swcify/lit.rs index eb68365322a..70b6f636ec5 100644 --- a/crates/swc_estree_compat/src/swcify/lit.rs +++ b/crates/swc_estree_compat/src/swcify/lit.rs @@ -1,5 +1,3 @@ -use super::Context; -use crate::swcify::Swcify; use swc_common::DUMMY_SP; use swc_ecma_ast::{BigInt, Bool, Expr, Lit, Null, Number, Regex, Str, Tpl, TplElement}; use swc_estree_ast::{ @@ -8,6 +6,9 @@ use swc_estree_ast::{ TemplateLiteralExpr, }; +use super::Context; +use crate::swcify::Swcify; + impl Swcify for Literal { type Output = Lit; diff --git a/crates/swc_estree_compat/src/swcify/mod.rs b/crates/swc_estree_compat/src/swcify/mod.rs index beac7a49132..8075c3d1b94 100644 --- a/crates/swc_estree_compat/src/swcify/mod.rs +++ b/crates/swc_estree_compat/src/swcify/mod.rs @@ -1,6 +1,7 @@ -pub use self::ctx::Context; use std::fmt::Debug; +pub use self::ctx::Context; + mod class; mod ctx; mod expr; diff --git a/crates/swc_estree_compat/src/swcify/pat.rs b/crates/swc_estree_compat/src/swcify/pat.rs index 09daa904231..cce8ba01b2e 100644 --- a/crates/swc_estree_compat/src/swcify/pat.rs +++ b/crates/swc_estree_compat/src/swcify/pat.rs @@ -1,4 +1,3 @@ -use crate::swcify::{Context, Swcify}; use swc_common::Spanned; use swc_ecma_ast::*; use swc_estree_ast::{ @@ -6,6 +5,8 @@ use swc_estree_ast::{ PatternLike, RestElement, }; +use crate::swcify::{Context, Swcify}; + impl Swcify for LVal { type Output = Pat; diff --git a/crates/swc_estree_compat/src/swcify/stmt.rs b/crates/swc_estree_compat/src/swcify/stmt.rs index bd5c53ccf98..fd32b87b7b0 100644 --- a/crates/swc_estree_compat/src/swcify/stmt.rs +++ b/crates/swc_estree_compat/src/swcify/stmt.rs @@ -1,5 +1,3 @@ -use super::Context; -use crate::swcify::Swcify; use swc_common::DUMMY_SP; use swc_ecma_ast::{ BlockStmt, BreakStmt, ClassDecl, ClassExpr, ContinueStmt, DebuggerStmt, Decl, DefaultDecl, @@ -24,6 +22,9 @@ use swc_estree_ast::{ VariableDeclarator, WhileStatement, WithStatement, }; +use super::Context; +use crate::swcify::Swcify; + impl Swcify for BlockStatement { type Output = BlockStmt; diff --git a/crates/swc_estree_compat/src/swcify/typescript.rs b/crates/swc_estree_compat/src/swcify/typescript.rs index aa65ea0c3ea..9009634c784 100644 --- a/crates/swc_estree_compat/src/swcify/typescript.rs +++ b/crates/swc_estree_compat/src/swcify/typescript.rs @@ -1,5 +1,3 @@ -use super::Context; -use crate::swcify::Swcify; use swc_ecma_ast::{ Accessibility, Ident, TsEntityName, TsQualifiedName, TsType, TsTypeAnn, TsTypeParam, TsTypeParamDecl, TsTypeParamInstantiation, @@ -10,6 +8,9 @@ use swc_estree_ast::{ TypeParamDeclOrNoop, }; +use super::Context; +use crate::swcify::Swcify; + impl Swcify for TSTypeParameterInstantiation { type Output = TsTypeParamInstantiation; diff --git a/crates/swc_estree_compat/tests/convert.rs b/crates/swc_estree_compat/tests/convert.rs index 1c1c7f23602..bf63bf652f4 100644 --- a/crates/swc_estree_compat/tests/convert.rs +++ b/crates/swc_estree_compat/tests/convert.rs @@ -1,15 +1,16 @@ #![feature(test)] extern crate test; -use anyhow::{Context as AnyhowContext, Error}; -use copyless::BoxHelper; -use pretty_assertions::assert_eq; -use serde_json::{Number, Value}; use std::{ env, fs, path::{Path, PathBuf}, sync::Arc, }; + +use anyhow::{Context as AnyhowContext, Error}; +use copyless::BoxHelper; +use pretty_assertions::assert_eq; +use serde_json::{Number, Value}; use swc::{config::IsModule, Compiler}; use swc_common::{ errors::{ColorConfig, Handler}, diff --git a/crates/swc_estree_compat/tests/flavor.rs b/crates/swc_estree_compat/tests/flavor.rs index 5ca50176cb6..d218db27b95 100644 --- a/crates/swc_estree_compat/tests/flavor.rs +++ b/crates/swc_estree_compat/tests/flavor.rs @@ -1,9 +1,10 @@ -use anyhow::Context; -use serde_json::{Number, Value}; use std::{ path::{Path, PathBuf}, process::{Command, Stdio}, }; + +use anyhow::Context; +use serde_json::{Number, Value}; use swc::SwcComments; use swc_ecma_ast::EsVersion; use swc_ecma_parser::{lexer::Lexer, EsConfig, Parser, StringInput, Syntax}; diff --git a/crates/swc_fast_graph/src/digraph.rs b/crates/swc_fast_graph/src/digraph.rs index ee4c027c7fd..e977ded06df 100644 --- a/crates/swc_fast_graph/src/digraph.rs +++ b/crates/swc_fast_graph/src/digraph.rs @@ -3,6 +3,16 @@ #![allow(dead_code)] // We don't want to modify copied source code. +use std::{ + cmp::Ordering, + fmt, + hash::{self, Hash}, + iter::{Cloned, DoubleEndedIterator, FromIterator}, + marker::PhantomData, + ops::Deref, + slice::Iter, +}; + use indexmap::{ map::{Iter as IndexMapIter, IterMut as IndexMapIterMut, Keys}, IndexMap, @@ -12,15 +22,6 @@ use petgraph::{ visit::{GraphBase, IntoNeighbors, IntoNeighborsDirected, NodeCount, Visitable}, Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected, }; -use std::{ - cmp::Ordering, - fmt, - hash::{self, Hash}, - iter::{Cloned, DoubleEndedIterator, FromIterator}, - marker::PhantomData, - ops::Deref, - slice::Iter, -}; use swc_common::collections::AHashSet; /// A `GraphMap` with directed edges. @@ -525,6 +526,7 @@ where Ty: EdgeType, { type Item = N; + fn next(&mut self) -> Option { if Ty::is_directed() { (&mut self.iter) @@ -553,6 +555,7 @@ where Ty: EdgeType, { type Item = N; + fn next(&mut self) -> Option { if Ty::is_directed() { let self_dir = self.dir; @@ -589,6 +592,7 @@ where Ty: EdgeType, { type Item = (N, N, &'a E); + fn next(&mut self) -> Option { match self.iter.next() { None => None, @@ -618,6 +622,7 @@ where Ty: EdgeType, { type Item = (N, N, &'a E); + fn next(&mut self) -> Option { self.inner.next().map(|(&(a, b), v)| (a, b, v)) } @@ -671,6 +676,7 @@ where Ty: EdgeType, { type Item = (N, N, &'a mut E); + fn next(&mut self) -> Option { self.inner .next() @@ -766,6 +772,7 @@ impl<'b, T> Ord for Ptr<'b, T> { impl<'b, T> Deref for Ptr<'b, T> { type Target = T; + fn deref(&self) -> &T { self.0 } @@ -802,6 +809,7 @@ where Ty: EdgeType, { type Item = N; + fn next(&mut self) -> Option { self.iter.next().map(|(&n, _)| n) } @@ -823,6 +831,7 @@ where Ty: EdgeType, { type Item = (N, &'a N); + fn next(&mut self) -> Option { self.iter.next().map(|(n, _)| (*n, n)) } @@ -842,7 +851,6 @@ where N: Copy + PartialEq, { type EdgeId = (N, N); - type NodeId = N; } @@ -852,9 +860,11 @@ where Ty: EdgeType, { type Map = AHashSet; + fn visit_map(&self) -> AHashSet { AHashSet::with_capacity_and_hasher(self.node_count(), Default::default()) } + fn reset_map(&self, map: &mut Self::Map) { map.clear(); } @@ -866,6 +876,7 @@ where Ty: EdgeType, { type Neighbors = Neighbors<'a, N, Ty>; + fn neighbors(self, n: Self::NodeId) -> Self::Neighbors { self.neighbors(n) } @@ -877,6 +888,7 @@ where Ty: EdgeType, { type NeighborsDirected = NeighborsDirected<'a, N, Ty>; + fn neighbors_directed(self, n: N, dir: Direction) -> Self::NeighborsDirected { self.neighbors_directed(n, dir) } diff --git a/crates/swc_graph_analyzer/src/lib.rs b/crates/swc_graph_analyzer/src/lib.rs index 62e5f565b20..9762da87dda 100644 --- a/crates/swc_graph_analyzer/src/lib.rs +++ b/crates/swc_graph_analyzer/src/lib.rs @@ -1,6 +1,7 @@ +use std::{fmt::Debug, hash::Hash, marker::PhantomData}; + use ahash::AHashSet; use auto_impl::auto_impl; -use std::{fmt::Debug, hash::Hash, marker::PhantomData}; use swc_fast_graph::digraph::FastDiGraphMap; #[auto_impl(&, Box, Rc, Arc)] diff --git a/crates/swc_macros_common/src/binder.rs b/crates/swc_macros_common/src/binder.rs index 5ffb79ed2d4..754982d844c 100644 --- a/crates/swc_macros_common/src/binder.rs +++ b/crates/swc_macros_common/src/binder.rs @@ -32,7 +32,6 @@ //! ----- //! //! Adopted from `synstructure`. -use crate::{def_site, is_attr_name, syn_ext::PairExt}; use pmutil::{prelude::*, *}; use proc_macro2::{Span, TokenStream}; use quote::ToTokens; @@ -42,6 +41,8 @@ use syn::{ *, }; +use crate::{def_site, is_attr_name, syn_ext::PairExt}; + /// Used to bind whole struct or enum. #[derive(Debug, Clone)] pub struct Binder<'a> { @@ -56,6 +57,7 @@ impl<'a> Binder<'a> { pub const fn new(ident: &'a Ident, body: &'a Data, attrs: &'a [Attribute]) -> Self { Binder { ident, body, attrs } } + pub fn new_from(input: &'a DeriveInput) -> Self { Self::new(&input.ident, &input.data, &input.attrs) } @@ -111,6 +113,7 @@ impl<'a> VariantBinder<'a> { pub const fn data(&self) -> &Fields { self.data } + pub const fn attrs(&self) -> &[Attribute] { self.attrs } diff --git a/crates/swc_macros_common/src/derive.rs b/crates/swc_macros_common/src/derive.rs index 86e1774a0d0..bae469dbc79 100644 --- a/crates/swc_macros_common/src/derive.rs +++ b/crates/swc_macros_common/src/derive.rs @@ -1,10 +1,12 @@ -use crate::def_site; +use std::iter; + use pmutil::ToTokensExt; use proc_macro2::TokenStream; use quote::ToTokens; -use std::iter; use syn::{punctuated::Pair, *}; +use crate::def_site; + mod generics; /// Generics of derived impl item. @@ -79,6 +81,7 @@ impl<'a> Derive<'a> { pub fn unsafety(&mut self, unsafety: Option) { self.out.unsafety = unsafety; } + pub fn input(&self) -> &DeriveInput { self.input } diff --git a/crates/swc_macros_common/src/derive/generics.rs b/crates/swc_macros_common/src/derive/generics.rs index ee3894789bf..3786ec7f15c 100644 --- a/crates/swc_macros_common/src/derive/generics.rs +++ b/crates/swc_macros_common/src/derive/generics.rs @@ -1,8 +1,10 @@ -use super::*; -use quote::quote; use std::collections::BTreeSet; + +use quote::quote; use syn::visit::{self, Visit}; +use super::*; + impl<'a> Derive<'a> { pub fn all_generic_fields(&self) -> Vec<&'a Field> { struct TypeVisitor<'a> { @@ -31,6 +33,7 @@ impl<'a> Derive<'a> { visit::visit_path(self, path) } + fn visit_macro(&mut self, _: &Macro) {} } diff --git a/crates/swc_macros_common/src/prelude.rs b/crates/swc_macros_common/src/prelude.rs index 5b292400aa4..cea32240e5e 100644 --- a/crates/swc_macros_common/src/prelude.rs +++ b/crates/swc_macros_common/src/prelude.rs @@ -1,3 +1,7 @@ +pub use proc_macro2::{Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; +pub use quote::ToTokens; +pub use syn::punctuated::{Pair as Element, Punctuated}; + pub use super::{ binder::{BindedField, Binder, VariantBinder}, call_site, def_site, @@ -5,6 +9,3 @@ pub use super::{ doc_str, is_attr_name, print, syn_ext::{ItemImplExt, PairExt}, }; -pub use proc_macro2::{Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; -pub use quote::ToTokens; -pub use syn::punctuated::{Pair as Element, Punctuated}; diff --git a/crates/swc_macros_common/src/syn_ext.rs b/crates/swc_macros_common/src/syn_ext.rs index a191a417b36..493baddd770 100644 --- a/crates/swc_macros_common/src/syn_ext.rs +++ b/crates/swc_macros_common/src/syn_ext.rs @@ -1,8 +1,9 @@ -use crate::def_site; use pmutil::ToTokensExt; use quote::quote; use syn::{punctuated::Pair, *}; +use crate::def_site; + /// Extension trait for `ItemImpl` (impl block). pub trait ItemImplExt { /// Instead of diff --git a/crates/swc_node_bundler/benches/bench.rs b/crates/swc_node_bundler/benches/bench.rs index abe628045db..e1af8e5412c 100644 --- a/crates/swc_node_bundler/benches/bench.rs +++ b/crates/swc_node_bundler/benches/bench.rs @@ -5,12 +5,13 @@ extern crate test; -use anyhow::Error; use std::{ collections::HashMap, hint::black_box, path::{Path, PathBuf}, }; + +use anyhow::Error; use swc::resolver::NodeResolver; use swc_atoms::js_word; use swc_bundler::{Bundler, Load, ModuleData, ModuleRecord}; diff --git a/crates/swc_node_bundler/src/loaders/json.rs b/crates/swc_node_bundler/src/loaders/json.rs index 3aa851cc031..59b4172f98c 100644 --- a/crates/swc_node_bundler/src/loaders/json.rs +++ b/crates/swc_node_bundler/src/loaders/json.rs @@ -1,5 +1,6 @@ -use anyhow::{anyhow, Error}; use std::sync::Arc; + +use anyhow::{anyhow, Error}; use swc_common::{input::SourceFileInput, SourceFile, DUMMY_SP}; use swc_ecma_ast::{EsVersion, *}; use swc_ecma_parser::{lexer::Lexer, Parser, Syntax}; diff --git a/crates/swc_node_bundler/src/loaders/swc.rs b/crates/swc_node_bundler/src/loaders/swc.rs index bef688767a3..d7ea1fa8b9c 100644 --- a/crates/swc_node_bundler/src/loaders/swc.rs +++ b/crates/swc_node_bundler/src/loaders/swc.rs @@ -1,7 +1,7 @@ -use crate::loaders::json::load_json_as_module; +use std::{collections::HashMap, env, sync::Arc}; + use anyhow::{bail, Context, Error}; use helpers::Helpers; -use std::{collections::HashMap, env, sync::Arc}; use swc::{ config::{GlobalInliningPassEnvs, InputSourceMap, IsModule, JscConfig, TransformConfig}, try_with_handler, @@ -26,6 +26,8 @@ use swc_ecma_transforms::{ }; use swc_ecma_visit::FoldWith; +use crate::loaders::json::load_json_as_module; + /// JavaScript loader pub struct SwcLoader { compiler: Arc, diff --git a/crates/swc_node_bundler/src/v1/mod.rs b/crates/swc_node_bundler/src/v1/mod.rs index ab53d75ca69..a7b43f7ede1 100644 --- a/crates/swc_node_bundler/src/v1/mod.rs +++ b/crates/swc_node_bundler/src/v1/mod.rs @@ -1,16 +1,18 @@ +use std::{collections::HashMap, fmt, marker::PhantomData, path::PathBuf}; + +use serde::Deserialize; +use string_enum::StringEnum; +use swc_atoms::JsWord; +use swc_common::{collections::AHashMap, FileName}; +use swc_ecma_ast::EsVersion; +use swc_ecma_loader::TargetEnv; + pub use self::{ module::ModuleConfig, optimization::OptimizationConfig, output::OutputConfig, resolve::{AliasConfig, ResolveConfig}, }; -use serde::Deserialize; -use std::{collections::HashMap, fmt, marker::PhantomData, path::PathBuf}; -use string_enum::StringEnum; -use swc_atoms::JsWord; -use swc_common::{collections::AHashMap, FileName}; -use swc_ecma_ast::EsVersion; -use swc_ecma_loader::TargetEnv; mod module; mod optimization; diff --git a/crates/swc_node_bundler/src/v1/optimization.rs b/crates/swc_node_bundler/src/v1/optimization.rs index cf59717c49f..a798990b503 100644 --- a/crates/swc_node_bundler/src/v1/optimization.rs +++ b/crates/swc_node_bundler/src/v1/optimization.rs @@ -1,6 +1,7 @@ -use crate::v1::JsCallback; use serde::Deserialize; +use crate::v1::JsCallback; + #[derive(Debug, Deserialize)] #[serde(rename = "Optimization", rename_all = "camelCase")] pub struct OptimizationConfig { diff --git a/crates/swc_node_bundler/src/v1/output.rs b/crates/swc_node_bundler/src/v1/output.rs index 1335c3bed49..c90a9ee35cf 100644 --- a/crates/swc_node_bundler/src/v1/output.rs +++ b/crates/swc_node_bundler/src/v1/output.rs @@ -1,6 +1,7 @@ -use serde::Deserialize; use std::path::PathBuf; +use serde::Deserialize; + #[derive(Debug, Deserialize)] #[serde(rename = "Output")] #[serde(rename_all = "camelCase")] diff --git a/crates/swc_node_bundler/src/v1/resolve.rs b/crates/swc_node_bundler/src/v1/resolve.rs index 2341bdf61a8..eb986d248c3 100644 --- a/crates/swc_node_bundler/src/v1/resolve.rs +++ b/crates/swc_node_bundler/src/v1/resolve.rs @@ -1,5 +1,6 @@ -use serde::Deserialize; use std::{collections::HashMap, path::PathBuf}; + +use serde::Deserialize; use swc_atoms::JsWord; /// https://webpack.js.org/configuration/resolve/ diff --git a/crates/swc_node_bundler/tests/fixture.rs b/crates/swc_node_bundler/tests/fixture.rs index 168ce58b349..82169ea7a0a 100644 --- a/crates/swc_node_bundler/tests/fixture.rs +++ b/crates/swc_node_bundler/tests/fixture.rs @@ -1,4 +1,3 @@ -use anyhow::Error; use std::{ collections::HashMap, fs::{create_dir_all, read_dir}, @@ -6,6 +5,8 @@ use std::{ path::PathBuf, sync::Arc, }; + +use anyhow::Error; use swc::{config::SourceMapsConfig, resolver::environment_resolver}; use swc_atoms::js_word; use swc_bundler::{BundleKind, Bundler, Config, ModuleRecord}; diff --git a/crates/swc_node_comments/src/lib.rs b/crates/swc_node_comments/src/lib.rs index 3d881a33491..ed9bfca2ded 100644 --- a/crates/swc_node_comments/src/lib.rs +++ b/crates/swc_node_comments/src/lib.rs @@ -1,7 +1,8 @@ #![cfg_attr(test, deny(warnings))] -use dashmap::DashMap; use std::sync::Arc; + +use dashmap::DashMap; use swc_common::{ comments::{Comment, CommentKind, Comments}, BytePos, DUMMY_SP, diff --git a/crates/swc_plugin/src/lib.rs b/crates/swc_plugin/src/lib.rs index 96d4c056a6e..0f9b5da2925 100644 --- a/crates/swc_plugin/src/lib.rs +++ b/crates/swc_plugin/src/lib.rs @@ -15,8 +15,9 @@ pub mod syntax_pos { mod handler; pub mod errors { - pub use crate::handler::HANDLER; pub use swc_common::errors::{Diagnostic, Handler, Level}; + + pub use crate::handler::HANDLER; } mod context; diff --git a/crates/swc_plugin_macro/src/lib.rs b/crates/swc_plugin_macro/src/lib.rs index 887d8ea5362..a72d29d1533 100644 --- a/crates/swc_plugin_macro/src/lib.rs +++ b/crates/swc_plugin_macro/src/lib.rs @@ -1,6 +1,5 @@ extern crate proc_macro; use proc_macro::TokenStream; - use proc_macro2::{Ident, Span}; use quote::quote; use syn::{Item as SynItem, ItemFn}; diff --git a/crates/swc_plugin_runner/src/resolve.rs b/crates/swc_plugin_runner/src/resolve.rs index 60714275146..a886167ed3b 100644 --- a/crates/swc_plugin_runner/src/resolve.rs +++ b/crates/swc_plugin_runner/src/resolve.rs @@ -1,13 +1,14 @@ -use anyhow::{anyhow, bail, Context, Error}; -use once_cell::sync::Lazy; -use parking_lot::Mutex; -use serde::Deserialize; use std::{ env::current_dir, fs::read_to_string, path::{Path, PathBuf}, sync::Arc, }; + +use anyhow::{anyhow, bail, Context, Error}; +use once_cell::sync::Lazy; +use parking_lot::Mutex; +use serde::Deserialize; use swc_common::collections::AHashMap; use wasmer_cache::FileSystemCache; diff --git a/crates/swc_plugin_runner/tests/integration.rs b/crates/swc_plugin_runner/tests/integration.rs index afc75961729..2982a1f7113 100644 --- a/crates/swc_plugin_runner/tests/integration.rs +++ b/crates/swc_plugin_runner/tests/integration.rs @@ -1,9 +1,10 @@ -use anyhow::{anyhow, Error}; use std::{ env, fs, path::{Path, PathBuf}, process::{Command, Stdio}, }; + +use anyhow::{anyhow, Error}; use swc_common::{errors::HANDLER, plugin::Serialized, FileName}; use swc_ecma_ast::{CallExpr, Callee, EsVersion, Expr, Lit, MemberExpr, Program, Str}; use swc_ecma_parser::{lexer::Lexer, EsConfig, Parser, StringInput, Syntax}; diff --git a/crates/swc_stylis/src/prefixer.rs b/crates/swc_stylis/src/prefixer.rs index 6bf67b1a68a..bc8bd653582 100644 --- a/crates/swc_stylis/src/prefixer.rs +++ b/crates/swc_stylis/src/prefixer.rs @@ -1,4 +1,5 @@ use std::mem::take; + use swc_common::DUMMY_SP; use swc_css_ast::*; use swc_css_utils::replace_ident; diff --git a/crates/swc_visit/tests/arc.rs b/crates/swc_visit/tests/arc.rs index 7b1e61b2620..f2b0de6c924 100644 --- a/crates/swc_visit/tests/arc.rs +++ b/crates/swc_visit/tests/arc.rs @@ -1,4 +1,5 @@ use std::sync::Arc; + use swc_visit::define; pub struct Item { diff --git a/crates/swc_visit/tests/fold.rs b/crates/swc_visit/tests/fold.rs index 12fc9ab6c3e..8d3fb7fd772 100644 --- a/crates/swc_visit/tests/fold.rs +++ b/crates/swc_visit/tests/fold.rs @@ -1,4 +1,5 @@ use std::any::Any; + use swc_visit::define; /// Visitable nodes. diff --git a/crates/swc_visit/tests/opt_vec.rs b/crates/swc_visit/tests/opt_vec.rs index 7dbbc92c203..fa9c4cb6f75 100644 --- a/crates/swc_visit/tests/opt_vec.rs +++ b/crates/swc_visit/tests/opt_vec.rs @@ -1,4 +1,5 @@ use std::any::Any; + use swc_visit::define; /// Visitable nodes. diff --git a/crates/swc_visit/tests/vec_opt.rs b/crates/swc_visit/tests/vec_opt.rs index 71fa91e1ad5..8384f53e77a 100644 --- a/crates/swc_visit/tests/vec_opt.rs +++ b/crates/swc_visit/tests/vec_opt.rs @@ -1,4 +1,5 @@ use std::any::Any; + use swc_visit::define; /// Visitable nodes. diff --git a/crates/swc_visit_macros/src/lib.rs b/crates/swc_visit_macros/src/lib.rs index 30c72ff9f4c..1d5f760a3a5 100644 --- a/crates/swc_visit_macros/src/lib.rs +++ b/crates/swc_visit_macros/src/lib.rs @@ -1,9 +1,10 @@ extern crate proc_macro; +use std::{collections::HashSet, mem::replace}; + use inflector::Inflector; use pmutil::{q, Quote}; use proc_macro2::Ident; -use std::{collections::HashSet, mem::replace}; use swc_macros_common::{call_site, def_site}; use syn::{ parse_quote::parse, punctuated::Punctuated, spanned::Spanned, Arm, AttrStyle, Attribute, Block, diff --git a/crates/swc_webpack_ast/benches/webpack_ast.rs b/crates/swc_webpack_ast/benches/webpack_ast.rs index 2c4bb3762b1..fdd930d2103 100644 --- a/crates/swc_webpack_ast/benches/webpack_ast.rs +++ b/crates/swc_webpack_ast/benches/webpack_ast.rs @@ -1,6 +1,7 @@ #![feature(test)] use std::path::Path; + use swc_ecma_parser::{EsConfig, Parser, StringInput, Syntax}; use test::Bencher; diff --git a/crates/swc_webpack_ast/src/lib.rs b/crates/swc_webpack_ast/src/lib.rs index 0e3c49ce7d1..3ef018eae42 100644 --- a/crates/swc_webpack_ast/src/lib.rs +++ b/crates/swc_webpack_ast/src/lib.rs @@ -1,6 +1,5 @@ #![allow(clippy::vec_box)] -use crate::reducer::ast_reducer; use anyhow::{anyhow, Context, Error}; use serde::Serialize; use swc_common::{ @@ -15,6 +14,8 @@ use swc_estree_ast::flavor::Flavor; use swc_estree_compat::babelify::Babelify; use swc_timer::timer; +use crate::reducer::ast_reducer; + pub mod reducer; #[derive(Serialize)] diff --git a/crates/swc_webpack_ast/src/reducer/mod.rs b/crates/swc_webpack_ast/src/reducer/mod.rs index 130b4242dc6..7e8e56f5dca 100644 --- a/crates/swc_webpack_ast/src/reducer/mod.rs +++ b/crates/swc_webpack_ast/src/reducer/mod.rs @@ -1,5 +1,5 @@ -use self::{flatten::contains_import, typescript::ts_remover}; use std::{iter::once, sync::Arc}; + use swc_atoms::js_word; use swc_common::{ collections::{AHashMap, AHashSet}, @@ -12,6 +12,8 @@ use swc_ecma_utils::{ident::IdentLike, Id, IsEmpty, StmtLike, StmtOrModuleItem}; use swc_ecma_visit::{Visit, VisitMut, VisitMutWith, VisitWith}; use swc_timer::timer; +use self::{flatten::contains_import, typescript::ts_remover}; + mod flatten; mod typescript; diff --git a/crates/swc_webpack_ast/tests/fixture.rs b/crates/swc_webpack_ast/tests/fixture.rs index 34016d62605..4c72134cea5 100644 --- a/crates/swc_webpack_ast/tests/fixture.rs +++ b/crates/swc_webpack_ast/tests/fixture.rs @@ -1,4 +1,5 @@ use std::{fs, path::PathBuf}; + use swc_common::{chain, Mark, Span}; use swc_ecma_ast::*; use swc_ecma_parser::{EsConfig, Parser, StringInput, Syntax, TsConfig}; diff --git a/crates/testing/src/diag_errors.rs b/crates/testing/src/diag_errors.rs index af666ccd8b0..b1c2ba9a2b3 100644 --- a/crates/testing/src/diag_errors.rs +++ b/crates/testing/src/diag_errors.rs @@ -1,4 +1,5 @@ use std::sync::RwLock; + use swc_common::{ errors::{Diagnostic, DiagnosticBuilder, Emitter, Handler, HandlerFlags, SourceMapperDyn}, sync::Lrc, diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs index 1ce3638a445..3fda6d35740 100644 --- a/crates/testing/src/lib.rs +++ b/crates/testing/src/lib.rs @@ -1,8 +1,3 @@ -pub use self::output::{NormalizedOutput, StdErr, StdOut, TestOutput}; -use difference::Changeset; -use once_cell::sync::Lazy; -pub use pretty_assertions::{assert_eq, assert_ne}; -use regex::Regex; use std::{ env, fmt, fmt::{Debug, Display, Formatter}, @@ -13,6 +8,11 @@ use std::{ sync::RwLock, thread, }; + +use difference::Changeset; +use once_cell::sync::Lazy; +pub use pretty_assertions::{assert_eq, assert_ne}; +use regex::Regex; use swc_common::{ collections::AHashMap, errors::{Diagnostic, Handler}, @@ -22,6 +22,8 @@ use swc_common::{ pub use testing_macros::fixture; use tracing_subscriber::EnvFilter; +pub use self::output::{NormalizedOutput, StdErr, StdOut, TestOutput}; + pub mod json; #[macro_use] mod macros; diff --git a/crates/testing/src/output.rs b/crates/testing/src/output.rs index 94456bbce1c..5433cb05315 100644 --- a/crates/testing/src/output.rs +++ b/crates/testing/src/output.rs @@ -1,6 +1,3 @@ -use tracing::{debug, error}; - -use crate::paths; use std::{ fmt, fs::{create_dir_all, File}, @@ -9,6 +6,10 @@ use std::{ path::Path, }; +use tracing::{debug, error}; + +use crate::paths; + #[must_use] pub struct TestOutput { /// Errors produced by `swc_common::error::Handler`. @@ -159,6 +160,7 @@ impl From for NormalizedOutput { impl Deref for NormalizedOutput { type Target = str; + fn deref(&self) -> &str { &self.0 } diff --git a/crates/testing/src/paths.rs b/crates/testing/src/paths.rs index 7584ce41c1d..9c7af6b6b41 100644 --- a/crates/testing/src/paths.rs +++ b/crates/testing/src/paths.rs @@ -1,6 +1,7 @@ -use once_cell::sync::Lazy; use std::{env, path::PathBuf, sync::Arc}; +use once_cell::sync::Lazy; + pub fn manifest_dir() -> PathBuf { env::var("CARGO_MANIFEST_DIR") .map(PathBuf::from) diff --git a/crates/testing/src/string_errors.rs b/crates/testing/src/string_errors.rs index 5103d2b7dc8..ddc55d727f7 100644 --- a/crates/testing/src/string_errors.rs +++ b/crates/testing/src/string_errors.rs @@ -1,13 +1,15 @@ -use super::StdErr; use std::{ io::{self, Write}, sync::{Arc, RwLock}, }; + use swc_common::{ errors::{EmitterWriter, Handler, HandlerFlags, SourceMapperDyn}, sync::Lrc, }; +use super::StdErr; + /// Creates a new handler for testing. pub(crate) fn new_handler( cm: Lrc, @@ -36,6 +38,7 @@ impl Write for BufferedError { fn write(&mut self, d: &[u8]) -> io::Result { self.0.write().unwrap().write(d) } + fn flush(&mut self) -> io::Result<()> { Ok(()) } diff --git a/crates/testing_macros/src/fixture.rs b/crates/testing_macros/src/fixture.rs index ab005acbf95..048d0d306e4 100644 --- a/crates/testing_macros/src/fixture.rs +++ b/crates/testing_macros/src/fixture.rs @@ -1,13 +1,14 @@ +use std::{ + env, + path::{Component, PathBuf}, +}; + use anyhow::{Context, Error}; use glob::glob; use pmutil::q; use proc_macro2::Span; use regex::Regex; use relative_path::RelativePath; -use std::{ - env, - path::{Component, PathBuf}, -}; use syn::{ parse::{Parse, ParseStream}, Ident, ItemFn, Lit, LitStr, Meta, NestedMeta, Token, diff --git a/crates/testing_macros/tests/test.rs b/crates/testing_macros/tests/test.rs index c531cc3f562..7d817662752 100644 --- a/crates/testing_macros/tests/test.rs +++ b/crates/testing_macros/tests/test.rs @@ -1,6 +1,7 @@ #![deny(unused)] use std::path::PathBuf; + use testing_macros::fixture; #[fixture("tests/simple/*.ts")] diff --git a/crates/wasm/src/lib.rs b/crates/wasm/src/lib.rs index 5d74b895ab3..37cbcbc0322 100644 --- a/crates/wasm/src/lib.rs +++ b/crates/wasm/src/lib.rs @@ -1,6 +1,7 @@ +use std::sync::Arc; + use anyhow::{Context, Error}; use once_cell::sync::Lazy; -use std::sync::Arc; use swc::{ config::{JsMinifyOptions, Options, ParseOptions, SourceMapsConfig}, try_with_handler, Compiler,