diff --git a/crates/swc_bundler/src/bundler/chunk/cjs.rs b/crates/swc_bundler/src/bundler/chunk/cjs.rs index daf2ac5de82b..49885693e2c4 100644 --- a/crates/swc_bundler/src/bundler/chunk/cjs.rs +++ b/crates/swc_bundler/src/bundler/chunk/cjs.rs @@ -65,13 +65,14 @@ where }); module.sort(info.id, &ctx.graph, &ctx.cycles, &self.cm); - let stmt = ModuleItem::Stmt(wrap_module( + let stmt = wrap_module( SyntaxContext::empty(), SyntaxContext::empty().apply_mark(self.unresolved_mark), info.local_ctxt(), load_var, module.into(), - )); + ) + .into(); let wrapped = Modules::from( info.id, @@ -150,7 +151,7 @@ fn wrap_module( // var load = __swcpack_require__.bind(void 0, moduleDecl) - Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, declare: false, @@ -168,7 +169,8 @@ fn wrap_module( definite: false, }], ..Default::default() - }))) + } + .into() } struct RequireReplacer<'a, 'b, L, R> @@ -248,16 +250,15 @@ where // Side effect import if i.specifiers.is_empty() { self.replaced = true; - *node = ModuleItem::Stmt( - CallExpr { - span: DUMMY_SP, - callee: load_var.as_callee(), - args: vec![], + *node = CallExpr { + span: DUMMY_SP, + callee: load_var.as_callee(), + args: vec![], - ..Default::default() - } - .into_stmt(), - ); + ..Default::default() + } + .into_stmt() + .into(); return; } @@ -291,7 +292,7 @@ where } ImportSpecifier::Namespace(ns) => { self.replaced = true; - *node = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + *node = VarDecl { span: i.span, kind: VarDeclKind::Var, declare: false, @@ -311,14 +312,15 @@ where definite: false, }], ..Default::default() - })))); + } + .into(); return; } } } self.replaced = true; - *node = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + *node = VarDecl { span: i.span, kind: VarDeclKind::Var, declare: false, @@ -339,7 +341,8 @@ where definite: false, }], ..Default::default() - })))); + } + .into(); } } } diff --git a/crates/swc_bundler/src/bundler/chunk/computed_key.rs b/crates/swc_bundler/src/bundler/chunk/computed_key.rs index d7229406eb7c..7deeb2286729 100644 --- a/crates/swc_bundler/src/bundler/chunk/computed_key.rs +++ b/crates/swc_bundler/src/bundler/chunk/computed_key.rs @@ -82,7 +82,7 @@ where }); additional_items.push(( module_id, - ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { + NamedExport { span: DUMMY_SP, specifiers: vec![specifier], src: None, @@ -94,7 +94,8 @@ where } .into_with(), ), - })), + } + .into(), )); } } @@ -112,7 +113,7 @@ where module.append_all(additional_items); - let return_stmt = Stmt::Return(ReturnStmt { + let return_stmt = ReturnStmt { span: DUMMY_SP, arg: Some( ObjectLit { @@ -121,7 +122,8 @@ where } .into(), ), - }); + } + .into(); module.iter().for_each(|(_, v)| { if let ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ref export)) = v { @@ -179,10 +181,7 @@ where }], }; - module.append( - id, - ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(var_decl)))), - ); + module.append(id, var_decl.into()); // print_hygiene( // "wrap", @@ -233,7 +232,7 @@ impl Fold for ExportToReturn { }; let stmt = match decl { - ModuleDecl::Import(_) => return ModuleItem::ModuleDecl(decl), + ModuleDecl::Import(_) => return decl.into(), ModuleDecl::ExportDecl(export) => { match &export.decl { Decl::Class(ClassDecl { ident, .. }) | Decl::Fn(FnDecl { ident, .. }) => { @@ -246,7 +245,7 @@ impl Fold for ExportToReturn { _ => unreachable!(), } - Some(Stmt::Decl(export.decl)) + Some(ModuleItem::from(export.decl)) } ModuleDecl::ExportDefaultDecl(export) => match export.decl { @@ -259,11 +258,14 @@ impl Fold for ExportToReturn { ident.clone(), ); - Some(Stmt::Decl(Decl::Class(ClassDecl { - ident, - class: expr.class, - declare: false, - }))) + Some( + ClassDecl { + ident, + class: expr.class, + declare: false, + } + .into(), + ) } DefaultDecl::Fn(expr) => { let ident = expr.ident; @@ -274,18 +276,19 @@ impl Fold for ExportToReturn { ident.clone(), ); - Some(Stmt::Decl(Decl::Fn(FnDecl { - ident, - function: expr.function, - declare: false, - }))) + Some( + FnDecl { + ident, + function: expr.function, + declare: false, + } + .into(), + ) } DefaultDecl::TsInterfaceDecl(_) => None, }, ModuleDecl::ExportDefaultExpr(_) => None, - ModuleDecl::ExportAll(export) => { - return ModuleItem::ModuleDecl(ModuleDecl::ExportAll(export)) - } + ModuleDecl::ExportAll(export) => return export.into(), ModuleDecl::ExportNamed(export) => { for specifier in &export.specifiers { match specifier { @@ -322,7 +325,7 @@ impl Fold for ExportToReturn { { None } else { - return ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(export)); + return export.into(); } } ModuleDecl::TsImportEquals(_) => None, @@ -331,9 +334,9 @@ impl Fold for ExportToReturn { }; if let Some(stmt) = stmt { - ModuleItem::Stmt(stmt) + stmt } else { - ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP })) + EmptyStmt { span: DUMMY_SP }.into() } } } diff --git a/crates/swc_bundler/src/bundler/chunk/merge.rs b/crates/swc_bundler/src/bundler/chunk/merge.rs index e260df1e78a1..5eedbe9be599 100644 --- a/crates/swc_bundler/src/bundler/chunk/merge.rs +++ b/crates/swc_bundler/src/bundler/chunk/merge.rs @@ -578,7 +578,7 @@ where ModuleItem::ModuleDecl(ModuleDecl::Import(mut import)) => { // Preserve imports from node.js builtin modules. if self.config.external_modules.contains(&import.src.value) { - new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(import))); + new.push(import.into()); continue; } @@ -589,7 +589,7 @@ where .find(|s| s.0.src.value == import.src.value) { if !self.scope.get_module(src.module_id).unwrap().is_es6 { - new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(import))); + new.push(import.into()); continue; } } @@ -661,7 +661,7 @@ where } import.specifiers.clear(); - new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(import))); + new.push(import.into()); } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export)) => { // At here, we create multiple items. @@ -679,13 +679,14 @@ where // match c.ident { Some(ident) => { - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Class( + new.push( ClassDecl { ident: ident.clone(), class: c.class, declare: false, - }, - )))); + } + .into(), + ); new.push(ident.assign_to(local.clone()).into_module_item( injected_ctxt, @@ -706,11 +707,14 @@ where // match f.ident { Some(ident) => { - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl { - ident: ident.clone(), - function: f.function, - declare: false, - })))); + new.push( + FnDecl { + ident: ident.clone(), + function: f.function, + declare: false, + } + .into(), + ); new.push(ident.assign_to(local.clone()).into_module_item( injected_ctxt, @@ -724,11 +728,14 @@ where // // See: https://github.com/denoland/deno/issues/9346 let ident = private_ident!("default"); - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl { - ident: ident.clone(), - function: f.function, - declare: false, - })))); + new.push( + FnDecl { + ident: ident.clone(), + function: f.function, + declare: false, + } + .into(), + ); new.push(ident.assign_to(local.clone()).into_module_item( injected_ctxt, @@ -762,7 +769,7 @@ where exported: Some(ModuleExportName::Ident(exported)), is_type_only: false, }); - extra.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + extra.push( NamedExport { span: export.span, specifiers: vec![specifier], @@ -775,8 +782,9 @@ where } .into_with(), ), - }, - ))); + } + .into(), + ); } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(export)) => { @@ -814,7 +822,7 @@ where is_type_only: false, }); tracing::trace!("Exporting `default` with `export default expr`"); - extra.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + extra.push( NamedExport { span: export.span, specifiers: vec![specifier], @@ -827,8 +835,9 @@ where } .into_with(), ), - }, - ))); + } + .into(), + ); } ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export)) => { @@ -838,13 +847,13 @@ where let local = match export.decl { Decl::Class(c) => { let i = c.ident.clone(); - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Class(c)))); + new.push(c.into()); i } Decl::Fn(f) => { let i = f.ident.clone(); - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Fn(f)))); + new.push(f.into()); i } @@ -852,56 +861,54 @@ where let ids: Vec = find_pat_ids(&v); // - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(v)))); - - let export = - ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { - span: export.span, - specifiers: ids - .into_iter() - .map(|id| { - let exported = Ident::new( - id.sym.clone(), - id.span, - info.export_ctxt(), - ); - - tracing::trace!( - "Exporting `{}{:?}` with `export decl`", - id.sym, - id.ctxt - ); - - new.push( - id.clone() - .assign_to(exported.clone()) - .into_module_item( - injected_ctxt, - "prepare -> export decl -> var", - ), - ); + new.push(v.into()); + + let export = NamedExport { + span: export.span, + specifiers: ids + .into_iter() + .map(|id| { + let exported = Ident::new( + id.sym.clone(), + id.span, + info.export_ctxt(), + ); - ExportNamedSpecifier { - span: DUMMY_SP, - orig: ModuleExportName::Ident(id), - exported: Some(ModuleExportName::Ident( - exported, - )), - is_type_only: false, - } - }) - .map(ExportSpecifier::Named) - .collect(), - src: None, - type_only: false, - with: Some( - ExportMetadata { - injected: true, - ..Default::default() + tracing::trace!( + "Exporting `{}{:?}` with `export decl`", + id.sym, + id.ctxt + ); + + new.push( + id.clone() + .assign_to(exported.clone()) + .into_module_item( + injected_ctxt, + "prepare -> export decl -> var", + ), + ); + + ExportNamedSpecifier { + span: DUMMY_SP, + orig: ModuleExportName::Ident(id), + exported: Some(ModuleExportName::Ident(exported)), + is_type_only: false, } - .into_with(), - ), - })); + }) + .map(ExportSpecifier::Named) + .collect(), + src: None, + type_only: false, + with: Some( + ExportMetadata { + injected: true, + ..Default::default() + } + .into_with(), + ), + } + .into(); extra.push(export); continue; } @@ -936,7 +943,7 @@ where is_type_only: false, }); - extra.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + extra.push( NamedExport { span: export.span, specifiers: vec![specifier], @@ -949,8 +956,9 @@ where } .into_with(), ), - }, - ))); + } + .into(), + ); } ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { @@ -1057,15 +1065,16 @@ where } if !vars.is_empty() { - new.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var( - Box::new(VarDecl { + new.push( + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: Default::default(), decls: vars, ..Default::default() - }), - )))); + } + .into(), + ); } continue; } @@ -1159,15 +1168,16 @@ where is_type_only: false, }, ); - extra.push(ModuleItem::ModuleDecl( - ModuleDecl::ExportNamed(NamedExport { + extra.push( + NamedExport { span: ns.span, specifiers: vec![specifier], src: None, with: None, type_only: false, - }), - )); + } + .into(), + ); } None => { unreachable!( @@ -1357,7 +1367,7 @@ impl VisitMut for ImportMetaHandler<'_, '_> { Ok(key_value_props) => { prepend_stmt( &mut n.body, - ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: n.span, kind: VarDeclKind::Const, declare: false, @@ -1375,7 +1385,8 @@ impl VisitMut for ImportMetaHandler<'_, '_> { definite: false, }], ..Default::default() - })))), + } + .into(), ); } Err(err) => self.err = Some(err), diff --git a/crates/swc_bundler/src/bundler/finalize.rs b/crates/swc_bundler/src/bundler/finalize.rs index da14b24dae4c..b3bd6220c884 100644 --- a/crates/swc_bundler/src/bundler/finalize.rs +++ b/crates/swc_bundler/src/bundler/finalize.rs @@ -190,7 +190,7 @@ where _ => unreachable!(), } - Some(Stmt::Decl(export.decl)) + Some(export.decl.into()) } ModuleDecl::ExportNamed(NamedExport { @@ -266,11 +266,14 @@ where }, )))); - Some(Stmt::Decl(Decl::Class(ClassDecl { - ident, - class: expr.class, - declare: false, - }))) + Some( + ClassDecl { + ident, + class: expr.class, + declare: false, + } + .into(), + ) } DefaultDecl::Fn(expr) => { let ident = expr.ident; @@ -287,11 +290,14 @@ where }, )))); - Some(Stmt::Decl(Decl::Fn(FnDecl { - ident, - function: expr.function, - declare: false, - }))) + Some( + FnDecl { + ident, + function: expr.function, + declare: false, + } + .into(), + ) } DefaultDecl::TsInterfaceDecl(_) => None, }, @@ -306,13 +312,16 @@ where init: Some(export.expr), definite: false, }; - Some(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Const, - declare: false, - decls: vec![var], - ..Default::default() - })))) + Some( + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Const, + declare: false, + decls: vec![var], + ..Default::default() + } + .into(), + ) } ModuleDecl::ExportAll(_) => None, @@ -321,16 +330,19 @@ where .collect(), ..Default::default() }; - body.stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some( - ObjectLit { - span: DUMMY_SP, - props, - } - .into(), - ), - })); + body.stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some( + ObjectLit { + span: DUMMY_SP, + props, + } + .into(), + ), + } + .into(), + ); let f = Function { is_generator: false, diff --git a/crates/swc_bundler/src/inline.rs b/crates/swc_bundler/src/inline.rs index 36520ad86026..a58b24c0cac8 100644 --- a/crates/swc_bundler/src/inline.rs +++ b/crates/swc_bundler/src/inline.rs @@ -148,7 +148,7 @@ impl VisitMut for Inliner { match n { Stmt::Decl(Decl::Var(var)) if var.decls.is_empty() => { - *n = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *n = EmptyStmt { span: DUMMY_SP }.into(); } _ => {} } diff --git a/crates/swc_bundler/src/util.rs b/crates/swc_bundler/src/util.rs index e12ed60b38a9..ca8e140ad055 100644 --- a/crates/swc_bundler/src/util.rs +++ b/crates/swc_bundler/src/util.rs @@ -17,7 +17,7 @@ const TRACK: bool = false; pub(crate) trait VarDeclaratorExt: Into { fn into_module_item(self, injected_ctxt: SyntaxContext, name: &str) -> ModuleItem { - ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: DUMMY_SP, ctxt: injected_ctxt, kind: VarDeclKind::Const, @@ -35,7 +35,8 @@ pub(crate) trait VarDeclaratorExt: Into { } else { vec![self.into()] }, - })))) + } + .into() } } diff --git a/crates/swc_ecma_ast/src/decl.rs b/crates/swc_ecma_ast/src/decl.rs index 65b04d8ee678..af6d89e7ab84 100644 --- a/crates/swc_ecma_ast/src/decl.rs +++ b/crates/swc_ecma_ast/src/decl.rs @@ -35,18 +35,61 @@ pub enum Decl { TsModule(Box), } -bridge_decl_from!(Box, VarDecl); -bridge_decl_from!(Box, UsingDecl); -bridge_decl_from!(Box, TsInterfaceDecl); -bridge_decl_from!(Box, TsTypeAliasDecl); -bridge_decl_from!(Box, TsEnumDecl); -bridge_decl_from!(Box, TsModuleDecl); -bridge_stmt_from!(Decl, ClassDecl); -bridge_stmt_from!(Decl, FnDecl); +boxed!( + Decl, + [ + VarDecl, + UsingDecl, + TsInterfaceDecl, + TsTypeAliasDecl, + TsEnumDecl, + TsModuleDecl + ] +); + +macro_rules! decl_from { + ($($variant_ty:ty),*) => { + $( + bridge_from!(crate::Stmt, Decl, $variant_ty); + bridge_from!(crate::ModuleItem, crate::Stmt, $variant_ty); + )* + }; +} + +decl_from!( + ClassDecl, + FnDecl, + VarDecl, + UsingDecl, + TsInterfaceDecl, + TsTypeAliasDecl, + TsEnumDecl, + TsModuleDecl +); + +macro_rules! decl_from_boxed { + ($($variant_ty:ty),*) => { + $( + bridge_from!(Box, Decl, $variant_ty); + bridge_from!(Box, Decl, Box<$variant_ty>); + bridge_from!(crate::Stmt, Decl, Box<$variant_ty>); + bridge_from!(crate::ModuleItem, crate::Stmt, Box<$variant_ty>); + )* + }; +} + +decl_from_boxed!( + VarDecl, + UsingDecl, + TsInterfaceDecl, + TsTypeAliasDecl, + TsEnumDecl, + TsModuleDecl +); impl Take for Decl { fn dummy() -> Self { - Decl::Var(Take::dummy()) + Decl::Var(Default::default()) } } diff --git a/crates/swc_ecma_ast/src/macros.rs b/crates/swc_ecma_ast/src/macros.rs index 1d3e8c1b771b..8cea2656f6f8 100644 --- a/crates/swc_ecma_ast/src/macros.rs +++ b/crates/swc_ecma_ast/src/macros.rs @@ -185,6 +185,14 @@ macro_rules! test_de { }; } +macro_rules! boxed { + ($T:ty, [$($variant_ty:ty),*]) => { + $( + bridge_from!($T, Box<$variant_ty>, $variant_ty); + )* + }; +} + /// Implement `From<$src>` for `$dst`, by using implementation of `From<$src>` /// for `$bridge`. /// @@ -220,18 +228,3 @@ macro_rules! bridge_pat_from { bridge_from!(Box, crate::Pat, $src); }; } - -macro_rules! bridge_stmt_from { - ($bridge:ty, $src:ty) => { - bridge_from!(crate::Stmt, $bridge, $src); - bridge_from!(crate::ModuleItem, crate::Stmt, $src); - }; -} - -macro_rules! bridge_decl_from { - ($bridge:ty, $src:ty) => { - bridge_from!(crate::Decl, $bridge, $src); - bridge_from!(crate::Stmt, crate::Decl, $src); - bridge_from!(crate::ModuleItem, crate::Stmt, $src); - }; -} diff --git a/crates/swc_ecma_ast/src/module.rs b/crates/swc_ecma_ast/src/module.rs index 6b941b503138..fe9456d323e1 100644 --- a/crates/swc_ecma_ast/src/module.rs +++ b/crates/swc_ecma_ast/src/module.rs @@ -126,6 +126,6 @@ pub enum ModuleItem { impl Take for ModuleItem { fn dummy() -> Self { - ModuleItem::Stmt(Take::dummy()) + Self::Stmt(Default::default()) } } diff --git a/crates/swc_ecma_ast/src/module_decl.rs b/crates/swc_ecma_ast/src/module_decl.rs index 076ce6711e14..df23cd837afd 100644 --- a/crates/swc_ecma_ast/src/module_decl.rs +++ b/crates/swc_ecma_ast/src/module_decl.rs @@ -43,9 +43,31 @@ pub enum ModuleDecl { TsNamespaceExport(TsNamespaceExportDecl), } +boxed!(ModuleDecl, [TsImportEqualsDecl]); + +macro_rules! module_decl { + ([$($variant:ty),*]) => { + $( + bridge_from!(crate::ModuleItem, crate::ModuleDecl, $variant); + )* + }; +} + +module_decl!([ + ImportDecl, + ExportDecl, + NamedExport, + ExportDefaultDecl, + ExportDefaultExpr, + ExportAll, + TsImportEqualsDecl, + TsExportAssignment, + TsNamespaceExportDecl +]); + impl Take for ModuleDecl { fn dummy() -> Self { - ModuleDecl::Import(ImportDecl::dummy()) + ImportDecl::dummy().into() } } diff --git a/crates/swc_ecma_ast/src/stmt.rs b/crates/swc_ecma_ast/src/stmt.rs index 8e0dabab6646..32665b359a73 100644 --- a/crates/swc_ecma_ast/src/stmt.rs +++ b/crates/swc_ecma_ast/src/stmt.rs @@ -108,6 +108,39 @@ pub enum Stmt { Expr(ExprStmt), } +boxed!(Stmt, [TryStmt]); + +macro_rules! stmt_from { + ($($varant_ty:ty),*) => { + $( + bridge_from!(Box, crate::Stmt, $varant_ty); + bridge_from!(crate::ModuleItem, crate::Stmt, $varant_ty); + )* + }; +} + +stmt_from!( + ExprStmt, + BlockStmt, + EmptyStmt, + DebuggerStmt, + WithStmt, + ReturnStmt, + LabeledStmt, + BreakStmt, + ContinueStmt, + IfStmt, + SwitchStmt, + ThrowStmt, + TryStmt, + WhileStmt, + DoWhileStmt, + ForStmt, + ForInStmt, + ForOfStmt, + Decl +); + impl Stmt { pub fn is_use_strict(&self) -> bool { match self { @@ -176,8 +209,6 @@ impl Take for Stmt { } } -bridge_stmt_from!(Box, TryStmt); - #[ast_node("ExpressionStatement")] #[derive(Eq, Hash, EqIgnoreSpan, Default)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] diff --git a/crates/swc_ecma_compat_bugfixes/src/template_literal_caching.rs b/crates/swc_ecma_compat_bugfixes/src/template_literal_caching.rs index 765e05e894e2..8dce1fb3cfe5 100644 --- a/crates/swc_ecma_compat_bugfixes/src/template_literal_caching.rs +++ b/crates/swc_ecma_compat_bugfixes/src/template_literal_caching.rs @@ -41,13 +41,16 @@ impl TemplateLiteralCaching { fn create_var_decl(&mut self) -> Option { if !self.decls.is_empty() { - return Some(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Let, - declare: false, - decls: self.decls.clone(), - ..Default::default() - })))); + return Some( + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Let, + declare: false, + decls: self.decls.clone(), + ..Default::default() + } + .into(), + ); } None } @@ -140,7 +143,7 @@ impl Fold for TemplateLiteralCaching { fn fold_module(&mut self, n: Module) -> Module { let mut body = n.body.fold_children_with(self); if let Some(var) = self.create_var_decl() { - prepend_stmt(&mut body, ModuleItem::Stmt(var)) + prepend_stmt(&mut body, var.into()) } Module { body, ..n } diff --git a/crates/swc_ecma_compat_es2015/src/arrow.rs b/crates/swc_ecma_compat_es2015/src/arrow.rs index 68544da4b0fa..a15584d95092 100644 --- a/crates/swc_ecma_compat_es2015/src/arrow.rs +++ b/crates/swc_ecma_compat_es2015/src/arrow.rs @@ -203,7 +203,7 @@ impl VisitMut for Arrow { let decl = self.hoister.take().to_stmt(); if let Some(stmt) = decl { - prepend_stmt(stmts, ModuleItem::Stmt(stmt)); + prepend_stmt(stmts, stmt.into()); } } diff --git a/crates/swc_ecma_compat_es2015/src/block_scoped_fn.rs b/crates/swc_ecma_compat_es2015/src/block_scoped_fn.rs index 1ae481bdec2b..95c3e1f7b456 100644 --- a/crates/swc_ecma_compat_es2015/src/block_scoped_fn.rs +++ b/crates/swc_ecma_compat_es2015/src/block_scoped_fn.rs @@ -40,7 +40,7 @@ impl VisitMut for BlockScopedFns { if let Stmt::Decl(Decl::Fn(decl)) = stmt { if IdentUsageFinder::find(&decl.ident.to_id(), &decl.function) { - extra_stmts.push(Stmt::Decl(Decl::Fn(decl))); + extra_stmts.push(decl.into()); continue; } stmts.push( diff --git a/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs b/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs index c2e6a47fa205..0ccaf410d53d 100644 --- a/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs +++ b/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs @@ -317,10 +317,13 @@ impl BlockScoping { right: "object".into(), } .into(), - cons: Box::new(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(ret.clone().make_member(quote_ident!("v")).into()), - })), + cons: Box::new( + ReturnStmt { + span: DUMMY_SP, + arg: Some(ret.clone().make_member(quote_ident!("v")).into()), + } + .into(), + ), alt: None, } .into(), @@ -332,10 +335,10 @@ impl BlockScoping { IfStmt { span: DUMMY_SP, test: ret.clone().make_eq(quote_str!("break")).into(), - cons: Stmt::Break(BreakStmt { + cons: BreakStmt { span: DUMMY_SP, label: None, - }) + } .into(), alt: None, } @@ -404,11 +407,14 @@ impl BlockScoping { /// which fixes https://github.com/swc-project/swc/issues/6573 fn blockify_for_stmt_body(&self, body: &mut Box) -> bool { if !body.is_block() { - *body = Box::new(Stmt::Block(BlockStmt { - span: Default::default(), - stmts: vec![*body.take()], - ..Default::default() - })); + *body = Box::new( + BlockStmt { + span: Default::default(), + stmts: vec![*body.take()], + ..Default::default() + } + .into(), + ); true } else { false @@ -615,7 +621,7 @@ impl BlockScoping { if !self.vars.is_empty() { prepend_stmt( stmts, - T::from_stmt( + T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -767,7 +773,7 @@ impl VisitMut for FlowHelper<'_> { "continue".into() }; - *node = Stmt::Return(ReturnStmt { + *node = ReturnStmt { span, arg: Some( Lit::Str(Str { @@ -777,7 +783,8 @@ impl VisitMut for FlowHelper<'_> { }) .into(), ), - }); + } + .into(); } Stmt::Break(BreakStmt { label, .. }) => { if (self.in_switch_case || self.in_nested_loop) && !self.has_outer_label(label) { @@ -792,7 +799,7 @@ impl VisitMut for FlowHelper<'_> { self.has_break = true; "break".into() }; - *node = Stmt::Return(ReturnStmt { + *node = ReturnStmt { span, arg: Some( Lit::Str(Str { @@ -802,13 +809,14 @@ impl VisitMut for FlowHelper<'_> { }) .into(), ), - }); + } + .into(); } Stmt::Return(s) => { self.has_return = true; s.visit_mut_with(self); - *node = Stmt::Return(ReturnStmt { + *node = ReturnStmt { span, arg: Some( ObjectLit { @@ -828,7 +836,8 @@ impl VisitMut for FlowHelper<'_> { } .into(), ), - }); + } + .into(); } _ => node.visit_mut_children_with(self), } diff --git a/crates/swc_ecma_compat_es2015/src/classes/constructor.rs b/crates/swc_ecma_compat_es2015/src/classes/constructor.rs index 58ee2a518d2b..9e77911341fd 100644 --- a/crates/swc_ecma_compat_es2015/src/classes/constructor.rs +++ b/crates/swc_ecma_compat_es2015/src/classes/constructor.rs @@ -330,7 +330,7 @@ impl VisitMut for ConstructorFolder<'_> { .into_stmt() } Some(SuperFoldingMode::Var) => { - *stmt = Stmt::Decl(Decl::Var(Box::new(VarDecl { + *stmt = VarDecl { span: DUMMY_SP, declare: false, kind: VarDeclKind::Var, @@ -345,13 +345,15 @@ impl VisitMut for ConstructorFolder<'_> { definite: false, }], ..Default::default() - }))) + } + .into() } None => { - *stmt = Stmt::Return(ReturnStmt { + *stmt = ReturnStmt { span: DUMMY_SP, arg: Some(expr), - }) + } + .into() } } } diff --git a/crates/swc_ecma_compat_es2015/src/classes/mod.rs b/crates/swc_ecma_compat_es2015/src/classes/mod.rs index 470c30634f3f..fe8415120fc0 100644 --- a/crates/swc_ecma_compat_es2015/src/classes/mod.rs +++ b/crates/swc_ecma_compat_es2015/src/classes/mod.rs @@ -138,10 +138,10 @@ where let mut decl = self.fold_class_as_var_decl(ident.clone(), class); decl.visit_mut_children_with(self); - buf.push(T::from_stmt(decl.into())); + buf.push(T::from(decl.into())); buf.push( - match T::try_from_module_decl(ModuleDecl::ExportNamed( + match T::try_from_module_decl( NamedExport { span: DUMMY_SP, specifiers: vec![ExportNamedSpecifier { @@ -156,8 +156,9 @@ where src: None, type_only: false, with: None, - }, - )) { + } + .into(), + ) { Ok(t) => t, Err(..) => unreachable!(), }, @@ -176,12 +177,13 @@ where let mut decl = self.fold_class_as_var_decl(ident, class); decl.visit_mut_children_with(self); buf.push( - match T::try_from_module_decl(ModuleDecl::ExportDecl( + match T::try_from_module_decl( ExportDecl { span, decl: decl.into(), - }, - )) { + } + .into(), + ) { Ok(t) => t, Err(..) => unreachable!(), }, @@ -204,7 +206,7 @@ where } stmt.visit_mut_children_with(self); - buf.push(T::from_stmt(stmt)); + buf.push(T::from(stmt)); } } first = false; @@ -712,20 +714,26 @@ where let is_last_return = matches!(body.last(), Some(Stmt::Return(..))); if !is_last_return { if is_always_initialized { - body.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(this.into()), - })); + body.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(this.into()), + } + .into(), + ); } else { let possible_return_value = Box::new(make_possible_return_value(ReturningMode::Returning { mark: this_mark, arg: None, })); - body.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(possible_return_value), - })); + body.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(possible_return_value), + } + .into(), + ); } } } @@ -750,18 +758,21 @@ where inject_class_call_check(&mut body, class_name.clone()); } - stmts.push(Stmt::Decl(Decl::Fn(FnDecl { - ident: class_name.clone(), - function: constructor_fn(Constructor { - body: Some(BlockStmt { - span: DUMMY_SP, - stmts: body, - ..Default::default() + stmts.push( + FnDecl { + ident: class_name.clone(), + function: constructor_fn(Constructor { + body: Some(BlockStmt { + span: DUMMY_SP, + stmts: body, + ..Default::default() + }), + ..constructor }), - ..constructor - }), - declare: false, - }))); + declare: false, + } + .into(), + ); } // convert class methods @@ -803,10 +814,13 @@ where class_name_sym.ctxt = class_name.ctxt; // `return Foo` - stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(class_name_sym.into()), - })); + stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(class_name_sym.into()), + } + .into(), + ); stmts } @@ -1148,21 +1162,24 @@ where } let span = method.span(); let prop = *v.key_prop.clone(); - res.push(Stmt::Expr(ExprStmt { - span, - expr: AssignExpr { + res.push( + ExprStmt { span, - op: op!("="), - left: MemberExpr { + expr: AssignExpr { span, - obj: Box::new(proto.clone().into()), - prop: mk_key_prop_member(prop), + op: op!("="), + left: MemberExpr { + span, + obj: Box::new(proto.clone().into()), + prop: mk_key_prop_member(prop), + } + .into(), + right: escape_keywords(method), } .into(), - right: escape_keywords(method), } .into(), - })); + ); !(v.get.is_none() && v.set.is_none()) } else { true @@ -1173,21 +1190,24 @@ where if let Some(method) = v.method.take() { let span = method.span(); let prop = *v.key_prop.clone(); - res.push(Stmt::Expr(ExprStmt { - span, - expr: AssignExpr { + res.push( + ExprStmt { span, - op: op!("="), - left: MemberExpr { + expr: AssignExpr { span, - obj: Box::new(class_name.clone().into()), - prop: mk_key_prop_member(prop), + op: op!("="), + left: MemberExpr { + span, + obj: Box::new(class_name.clone().into()), + prop: mk_key_prop_member(prop), + } + .into(), + right: escape_keywords(method), } .into(), - right: escape_keywords(method), } .into(), - })); + ); !(v.get.is_none() && v.set.is_none()) } else { true diff --git a/crates/swc_ecma_compat_es2015/src/computed_props.rs b/crates/swc_ecma_compat_es2015/src/computed_props.rs index ccb45c7ae445..e813a7b4ab4c 100644 --- a/crates/swc_ecma_compat_es2015/src/computed_props.rs +++ b/crates/swc_ecma_compat_es2015/src/computed_props.rs @@ -389,7 +389,7 @@ impl ComputedProps { // Add variable declaration // e.g. var ref if !folder.vars.is_empty() { - stmts_updated.push(T::from_stmt( + stmts_updated.push(T::from( VarDecl { kind: VarDeclKind::Var, decls: folder.vars, diff --git a/crates/swc_ecma_compat_es2015/src/destructuring.rs b/crates/swc_ecma_compat_es2015/src/destructuring.rs index 35c0d9f400ca..6f6360a3fbc1 100644 --- a/crates/swc_ecma_compat_es2015/src/destructuring.rs +++ b/crates/swc_ecma_compat_es2015/src/destructuring.rs @@ -1088,7 +1088,7 @@ impl Destructuring { // Add variable declaration // e.g. var ref if !folder.vars.is_empty() { - stmts_updated.push(T::from_stmt( + stmts_updated.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -1107,7 +1107,7 @@ impl Destructuring { // Add variable declaration // e.g. var ref if !folder.vars.is_empty() { - stmts_updated.push(T::from_stmt( + stmts_updated.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -1118,7 +1118,7 @@ impl Destructuring { )); } - stmts_updated.push(T::from_stmt(stmt)); + stmts_updated.push(T::from(stmt)); } } } diff --git a/crates/swc_ecma_compat_es2015/src/for_of.rs b/crates/swc_ecma_compat_es2015/src/for_of.rs index 231b090e642f..d6e788e36999 100644 --- a/crates/swc_ecma_compat_es2015/src/for_of.rs +++ b/crates/swc_ecma_compat_es2015/src/for_of.rs @@ -186,7 +186,7 @@ impl ForOf { } } - let stmt = Stmt::For(ForStmt { + let stmt = ForStmt { span, init: Some( VarDecl { @@ -201,7 +201,8 @@ impl ForOf { test, update, body: Box::new(Stmt::Block(body)), - }); + } + .into(); return match label { Some(label) => LabeledStmt { @@ -307,7 +308,7 @@ impl ForOf { } .into(); - let stmt = Stmt::For(ForStmt { + let stmt = ForStmt { span, init: Some( VarDecl { @@ -320,7 +321,8 @@ impl ForOf { test: Some(test), update: None, body: Box::new(Stmt::Block(body)), - }); + } + .into(); return match label { Some(label) => LabeledStmt { span, @@ -485,16 +487,17 @@ impl ForOf { } .into(), ), - body: Box::new(Stmt::Block(body)), + body: Box::new(body.into()), } .into(); let for_stmt = match label { - Some(label) => Stmt::Labeled(LabeledStmt { + Some(label) => LabeledStmt { span, label, body: Box::new(for_stmt), - }), + } + .into(), None => for_stmt, }; diff --git a/crates/swc_ecma_compat_es2015/src/generator.rs b/crates/swc_ecma_compat_es2015/src/generator.rs index 4b1d17027b09..bef7288e1cbb 100644 --- a/crates/swc_ecma_compat_es2015/src/generator.rs +++ b/crates/swc_ecma_compat_es2015/src/generator.rs @@ -126,10 +126,13 @@ impl VisitMut for Wrapper { } stmts.extend(v.hoisted_fns.into_iter().map(Decl::Fn).map(Stmt::Decl)); - stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(generator_object), - })); + stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(generator_object), + } + .into(), + ); f.body.as_mut().unwrap().stmts = stmts; } } @@ -523,18 +526,21 @@ impl VisitMut for Generator { if contains_yield(&elem) && !pending_expressions.is_empty() { self.emit_worker( OpCode::Statement, - Some(OpArgs::Stmt(Box::new(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: if pending_expressions.len() == 1 { - pending_expressions.remove(0) - } else { - SeqExpr { - span: DUMMY_SP, - exprs: pending_expressions.take(), - } - .into() - }, - })))), + Some(OpArgs::Stmt(Box::new( + ExprStmt { + span: DUMMY_SP, + expr: if pending_expressions.len() == 1 { + pending_expressions.remove(0) + } else { + SeqExpr { + span: DUMMY_SP, + exprs: pending_expressions.take(), + } + .into() + }, + } + .into(), + ))), None, ); } @@ -976,7 +982,7 @@ impl VisitMut for Generator { if self.in_statement_containing_yield { let label = self.find_break_target(b.label.as_ref().map(|l| l.sym.clone())); if label.0 > 0 { - *node = Stmt::Return(self.create_inline_break(label, Some(b.span))); + *node = self.create_inline_break(label, Some(b.span)).into(); return; } } @@ -1029,7 +1035,7 @@ impl VisitMut for Generator { return; } - *node = Stmt::Expr(ExprStmt { + *node = ExprStmt { span: v.span, expr: if exprs.len() == 1 { exprs.remove(0) @@ -1040,7 +1046,8 @@ impl VisitMut for Generator { } .into() }, - }); + } + .into(); } Stmt::Decl(Decl::Fn(f)) => { self.hoisted_fns.push(f.take()); @@ -1212,10 +1219,13 @@ impl Generator { } } && !expressions.is_empty() { - self.emit_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Expr::from_exprs(expressions.take()), - })); + self.emit_stmt( + ExprStmt { + span: DUMMY_SP, + expr: Expr::from_exprs(expressions.take()), + } + .into(), + ); } let mut expression: Expr = match property { @@ -1476,14 +1486,14 @@ impl Generator { self.transform_and_emit_stmts(node.stmts, 0); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::Block(node)); + self.emit_stmt(node.into()); } } fn transform_and_emit_expr_stmt(&mut self, mut node: ExprStmt) { node.visit_mut_with(self); - self.emit_stmt(Stmt::Expr(node)); + self.emit_stmt(node.into()); } fn transform_and_emit_var_decl_list(&mut self, mut node: Box) { @@ -1517,18 +1527,21 @@ impl Generator { variables_written += cnt; cnt = 0; - self.emit_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: if pending_expressions.len() == 1 { - pending_expressions.pop().unwrap() - } else { - SeqExpr { - span: DUMMY_SP, - exprs: take(&mut pending_expressions), - } - .into() - }, - })) + self.emit_stmt( + ExprStmt { + span: DUMMY_SP, + expr: if pending_expressions.len() == 1 { + pending_expressions.pop().unwrap() + } else { + SeqExpr { + span: DUMMY_SP, + exprs: take(&mut pending_expressions), + } + .into() + }, + } + .into(), + ) } } } @@ -1578,11 +1591,11 @@ impl Generator { self.mark_label(end_label); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::If(node)); + self.emit_stmt(node.into()); } } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::If(node)); + self.emit_stmt(node.into()); } } @@ -1616,7 +1629,7 @@ impl Generator { self.end_loop_block(); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::DoWhile(node)); + self.emit_stmt(node.into()); } } @@ -1649,7 +1662,7 @@ impl Generator { } else { node.visit_mut_children_with(self); - self.emit_stmt(Stmt::While(node)); + self.emit_stmt(node.into()); } } @@ -1684,10 +1697,13 @@ impl Generator { } VarDeclOrExpr::Expr(mut init) => { init.visit_mut_with(self); - self.emit_stmt(Stmt::Expr(ExprStmt { - span: init.span(), - expr: init, - })); + self.emit_stmt( + ExprStmt { + span: init.span(), + expr: init, + } + .into(), + ); } } } @@ -1706,17 +1722,20 @@ impl Generator { if let Some(mut incrementor) = node.update { incrementor.visit_mut_with(self); - self.emit_stmt(Stmt::Expr(ExprStmt { - span: incrementor.span(), - expr: incrementor, - })); + self.emit_stmt( + ExprStmt { + span: incrementor.span(), + expr: incrementor, + } + .into(), + ); } self.emit_break(condition_label, None); self.end_loop_block(); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::For(node)); + self.emit_stmt(node.into()); } } @@ -1756,24 +1775,27 @@ impl Generator { ); node.right.visit_mut_with(self); - self.emit_stmt(Stmt::ForIn(ForInStmt { - span: DUMMY_SP, - left: ForHead::Pat(key.clone().into()), - right: node.right.take(), - body: Box::new(Stmt::Expr(ExprStmt { + self.emit_stmt( + ForInStmt { span: DUMMY_SP, - expr: CallExpr { + left: ForHead::Pat(key.clone().into()), + right: node.right.take(), + body: Box::new(Stmt::Expr(ExprStmt { span: DUMMY_SP, - callee: keys_array - .clone() - .make_member(quote_ident!("push")) - .as_callee(), - args: vec![key.as_arg()], - ..Default::default() - } - .into(), - })), - })); + expr: CallExpr { + span: DUMMY_SP, + callee: keys_array + .clone() + .make_member(quote_ident!("push")) + .as_callee(), + args: vec![key.as_arg()], + ..Default::default() + } + .into(), + })), + } + .into(), + ); self.emit_assignment(keys_index.clone().into(), 0.into(), None); @@ -1826,22 +1848,25 @@ impl Generator { self.transform_and_emit_embedded_stmt(*node.body); self.mark_label(increment_label); - self.emit_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: UpdateExpr { + self.emit_stmt( + ExprStmt { span: DUMMY_SP, - prefix: false, - op: op!("++"), - arg: Box::new(keys_index.clone().into()), + expr: UpdateExpr { + span: DUMMY_SP, + prefix: false, + op: op!("++"), + arg: Box::new(keys_index.clone().into()), + } + .into(), } .into(), - })); + ); self.emit_break(condition_label, None); self.end_loop_block(); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::ForIn(node)); + self.emit_stmt(node.into()); } } @@ -1852,7 +1877,7 @@ impl Generator { } else { // invalid continue without a containing loop. Leave the node as is, // per #17875. - self.emit_stmt(Stmt::Continue(node)) + self.emit_stmt(node.into()) } } @@ -1863,7 +1888,7 @@ impl Generator { } else { // invalid break without a containing loop. Leave the node as is, // per #17875. - self.emit_stmt(Stmt::Break(node)) + self.emit_stmt(node.into()) } } @@ -1891,7 +1916,7 @@ impl Generator { self.end_with_block(); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::With(node)); + self.emit_stmt(node.into()); } } @@ -1981,11 +2006,14 @@ impl Generator { if !pending_clauses.is_empty() { clauses_written += pending_clauses.len(); - self.emit_stmt(Stmt::Switch(SwitchStmt { - span: DUMMY_SP, - discriminant: expression.clone().into(), - cases: take(&mut pending_clauses), - })); + self.emit_stmt( + SwitchStmt { + span: DUMMY_SP, + discriminant: expression.clone().into(), + cases: take(&mut pending_clauses), + } + .into(), + ); } if default_clauses_skipped > 0 { @@ -2007,7 +2035,7 @@ impl Generator { self.end_switch_block() } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::Switch(node)) + self.emit_stmt(node.into()) } } @@ -2031,7 +2059,7 @@ impl Generator { self.end_labeled_block(); } else { node.visit_mut_with(self); - self.emit_stmt(Stmt::Labeled(node)); + self.emit_stmt(node.into()); } } @@ -2075,18 +2103,18 @@ impl Generator { // .mark endLabel self.begin_exception_block(); - self.transform_and_emit_embedded_stmt(Stmt::Block(node.block)); + self.transform_and_emit_embedded_stmt(node.block.into()); if let Some(catch) = node.handler { self.begin_catch_block(VarDeclarator { name: catch.param.clone().unwrap(), ..Take::dummy() }); - self.transform_and_emit_embedded_stmt(Stmt::Block(catch.body)); + self.transform_and_emit_embedded_stmt(catch.body.into()); } if let Some(finalizer) = node.finalizer { self.begin_finally_block(); - self.transform_and_emit_embedded_stmt(Stmt::Block(finalizer)); + self.transform_and_emit_embedded_stmt(finalizer.into()); } self.end_exception_block(); @@ -3000,7 +3028,7 @@ impl Generator { stmts.insert( 0, - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: CallExpr { span: DUMMY_SP, @@ -3023,7 +3051,8 @@ impl Generator { ..Default::default() } .into(), - }), + } + .into(), ); } @@ -3032,16 +3061,19 @@ impl Generator { // label, so we add an assignment statement to // reflect the change in labels. - stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: AssignExpr { + stmts.push( + ExprStmt { span: DUMMY_SP, - op: op!("="), - left: self.state.clone().make_member(quote_ident!("label")).into(), - right: (self.label_number + 1).into(), + expr: AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: self.state.clone().make_member(quote_ident!("label")).into(), + right: (self.label_number + 1).into(), + } + .into(), } .into(), - })); + ); } stmts @@ -3267,16 +3299,19 @@ impl Generator { /// Writes an Assign operation to the current label's statement list. fn write_assign(&mut self, left: AssignTarget, right: Box, op_loc: Option) { - self.write_stmt(Stmt::Expr(ExprStmt { - span: op_loc.unwrap_or(DUMMY_SP), - expr: AssignExpr { - span: DUMMY_SP, - op: op!("="), - left, - right, + self.write_stmt( + ExprStmt { + span: op_loc.unwrap_or(DUMMY_SP), + expr: AssignExpr { + span: DUMMY_SP, + op: op!("="), + left, + right, + } + .into(), } .into(), - })) + ) } /// Writes a Throw operation to the current label's statement list. @@ -3288,10 +3323,13 @@ impl Generator { self.last_operation_was_completion = true; // let inst = self.create_instruction(Instruction::Return); - self.write_stmt(Stmt::Throw(ThrowStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: expr, - })) + self.write_stmt( + ThrowStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: expr, + } + .into(), + ) } /// Writes a Return operation to the current label's statement list. @@ -3303,23 +3341,26 @@ impl Generator { self.last_operation_was_completion = true; let inst = self.create_instruction(Instruction::Return); - self.write_stmt(Stmt::Return(ReturnStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems: match expr { - Some(expr) => { - vec![Some(inst.as_arg()), Some(expr.as_arg())] - } - _ => { - vec![Some(inst.as_arg())] - } - }, - } - .into(), - ), - })) + self.write_stmt( + ReturnStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: match expr { + Some(expr) => { + vec![Some(inst.as_arg()), Some(expr.as_arg())] + } + _ => { + vec![Some(inst.as_arg())] + } + }, + } + .into(), + ), + } + .into(), + ) } /// Writes a Break operation to the current label's statement list. @@ -3331,16 +3372,19 @@ impl Generator { let inst = self.create_instruction(Instruction::Break); let label = self.create_label(Some(label)); - self.write_stmt(Stmt::Return(ReturnStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems: vec![Some(inst.as_arg()), Some(label.as_arg())], - } - .into(), - ), - })) + self.write_stmt( + ReturnStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(inst.as_arg()), Some(label.as_arg())], + } + .into(), + ), + } + .into(), + ) } /// Writes a BreakWhenTrue operation to the current label's statement list. @@ -3351,21 +3395,24 @@ impl Generator { fn write_break_when_true(&mut self, label: Label, cond: Box, op_loc: Option) { let inst = self.create_instruction(Instruction::Break); let label = self.create_label(Some(label)); - self.write_stmt(Stmt::If(IfStmt { - span: DUMMY_SP, - test: cond, - cons: Box::new(Stmt::Return(ReturnStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems: vec![Some(inst.as_arg()), Some(label.as_arg())], - } - .into(), - ), - })), - alt: None, - })) + self.write_stmt( + IfStmt { + span: DUMMY_SP, + test: cond, + cons: Box::new(Stmt::Return(ReturnStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(inst.as_arg()), Some(label.as_arg())], + } + .into(), + ), + })), + alt: None, + } + .into(), + ) } /// Writes a BreakWhenFalse operation to the current label's statement list. @@ -3376,26 +3423,29 @@ impl Generator { fn write_break_when_false(&mut self, label: Label, cond: Box, op_loc: Option) { let inst = self.create_instruction(Instruction::Break); let label = self.create_label(Some(label)); - self.write_stmt(Stmt::If(IfStmt { - span: DUMMY_SP, - test: UnaryExpr { + self.write_stmt( + IfStmt { span: DUMMY_SP, - op: op!("!"), - arg: cond, + test: UnaryExpr { + span: DUMMY_SP, + op: op!("!"), + arg: cond, + } + .into(), + cons: Box::new(Stmt::Return(ReturnStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(inst.as_arg()), Some(label.as_arg())], + } + .into(), + ), + })), + alt: None, } .into(), - cons: Box::new(Stmt::Return(ReturnStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems: vec![Some(inst.as_arg()), Some(label.as_arg())], - } - .into(), - ), - })), - alt: None, - })) + ) } /// Writes a Yield operation to the current label's statement list. @@ -3414,16 +3464,19 @@ impl Generator { vec![Some(inst.as_arg())] } }; - self.write_stmt(Stmt::Return(ReturnStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems, - } - .into(), - ), - })); + self.write_stmt( + ReturnStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems, + } + .into(), + ), + } + .into(), + ); } /// Writes a YieldStar instruction to the current label's statement list. @@ -3434,16 +3487,19 @@ impl Generator { self.last_operation_was_abrupt = true; let arg1 = self.create_instruction(Instruction::YieldStar); - self.write_stmt(Stmt::Return(ReturnStmt { - span: op_loc.unwrap_or(DUMMY_SP), - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems: vec![Some(arg1.as_arg()), Some(expr.as_arg())], - } - .into(), - ), - })) + self.write_stmt( + ReturnStmt { + span: op_loc.unwrap_or(DUMMY_SP), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(arg1.as_arg()), Some(expr.as_arg())], + } + .into(), + ), + } + .into(), + ) } /// Writes an Endfinally instruction to the current label's statement list. @@ -3451,16 +3507,19 @@ impl Generator { self.last_operation_was_abrupt = true; let arg = self.create_instruction(Instruction::Endfinally); - self.write_stmt(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some( - ArrayLit { - span: DUMMY_SP, - elems: vec![Some(arg.as_arg())], - } - .into(), - ), - })) + self.write_stmt( + ReturnStmt { + span: DUMMY_SP, + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(arg.as_arg())], + } + .into(), + ), + } + .into(), + ) } fn hoist_variable_declaration(&mut self, id: &Ident) { diff --git a/crates/swc_ecma_compat_es2015/src/parameters.rs b/crates/swc_ecma_compat_es2015/src/parameters.rs index 440dd3409e22..f51eaa3d3893 100644 --- a/crates/swc_ecma_compat_es2015/src/parameters.rs +++ b/crates/swc_ecma_compat_es2015/src/parameters.rs @@ -171,27 +171,30 @@ impl Params { pat: ident.clone().into(), decorators: Vec::new(), }); - loose_stmt.push(Stmt::If(IfStmt { - span, - test: BinExpr { - span: DUMMY_SP, - left: Box::new(Ident::from(ident).into()), - op: op!("==="), - right: Expr::undefined(DUMMY_SP), - } - .into(), - cons: Box::new(Stmt::Expr(ExprStmt { + loose_stmt.push( + IfStmt { span, - expr: AssignExpr { - span, - left: left.try_into().unwrap(), - op: op!("="), - right, + test: BinExpr { + span: DUMMY_SP, + left: Box::new(Ident::from(ident).into()), + op: op!("==="), + right: Expr::undefined(DUMMY_SP), } .into(), - })), - alt: None, - })) + cons: Box::new(Stmt::Expr(ExprStmt { + span, + expr: AssignExpr { + span, + left: left.try_into().unwrap(), + op: op!("="), + right, + } + .into(), + })), + alt: None, + } + .into(), + ) } else { let binding = private_ident!(span, "param"); params.push(Param { @@ -303,113 +306,121 @@ impl Params { } }; - unpack_rest = Some(Stmt::For(ForStmt { - span, - init: Some( - VarDecl { - kind: VarDeclKind::Var, - span, - decls: vec![ - // _len = arguments.length - i - VarDeclarator { - span, - name: len_ident.clone().into(), - init: Some( - member_expr!( - Default::default(), - span, - arguments.length - ) - .into(), - ), - definite: false, - }, - // a1 = new Array(_len - $i) - VarDeclarator { - span, - name: arg.clone().into(), - init: Some(Box::new(Expr::New(NewExpr { + unpack_rest = Some( + ForStmt { + span, + init: Some( + VarDecl { + kind: VarDeclKind::Var, + span, + decls: vec![ + // _len = arguments.length - i + VarDeclarator { span, - callee: Box::new( - quote_ident!(self.unresolved_ctxt, "Array").into(), + name: len_ident.clone().into(), + init: Some( + member_expr!( + Default::default(), + span, + arguments.length + ) + .into(), ), - args: Some(vec![{ - // `len` or `len - $i` - make_minus_i(&len_ident, true).as_arg() - }]), - ..Default::default() - }))), - definite: false, - }, - // _key = 0 - VarDeclarator { - span, - name: idx_ident.clone().into(), - init: Some(Box::new(Expr::Lit(Lit::Num(Number { + definite: false, + }, + // a1 = new Array(_len - $i) + VarDeclarator { span, - value: i as f64, - raw: None, - })))), - definite: false, - }, - ], - declare: false, - ..Default::default() - } - .into(), - ), - // `_key < _len` - test: Some( - BinExpr { - span, - left: Box::new(idx_ident.clone().into()), - op: op!("<"), - right: Box::new(len_ident.clone().into()), - } - .into(), - ), - // _key++ - update: Some( - UpdateExpr { - span, - op: op!("++"), - prefix: false, - arg: Box::new(idx_ident.clone().into()), - } - .into(), - ), - body: Box::new(Stmt::Block(BlockStmt { - span: DUMMY_SP, - stmts: vec![{ - let prop = Box::new(Expr::Ident(idx_ident.clone())); - // a1[_key - i] = arguments[_key]; - - AssignExpr { - span, - left: arg - .computed_member(make_minus_i(&idx_ident, false)) - .into(), - op: op!("="), - right: Box::new( - MemberExpr { - span: DUMMY_SP, - obj: Box::new( - quote_ident!(Default::default(), span, "arguments") - .into(), - ), - prop: MemberProp::Computed(ComputedPropName { + name: arg.clone().into(), + init: Some(Box::new(Expr::New(NewExpr { span, - expr: prop, - }), - } - .into(), - ), + callee: Box::new( + quote_ident!(self.unresolved_ctxt, "Array") + .into(), + ), + args: Some(vec![{ + // `len` or `len - $i` + make_minus_i(&len_ident, true).as_arg() + }]), + ..Default::default() + }))), + definite: false, + }, + // _key = 0 + VarDeclarator { + span, + name: idx_ident.clone().into(), + init: Some(Box::new(Expr::Lit(Lit::Num(Number { + span, + value: i as f64, + raw: None, + })))), + definite: false, + }, + ], + declare: false, + ..Default::default() } - .into_stmt() - }], - ..Default::default() - })), - })) + .into(), + ), + // `_key < _len` + test: Some( + BinExpr { + span, + left: Box::new(idx_ident.clone().into()), + op: op!("<"), + right: Box::new(len_ident.clone().into()), + } + .into(), + ), + // _key++ + update: Some( + UpdateExpr { + span, + op: op!("++"), + prefix: false, + arg: Box::new(idx_ident.clone().into()), + } + .into(), + ), + body: Box::new(Stmt::Block(BlockStmt { + span: DUMMY_SP, + stmts: vec![{ + let prop = Box::new(Expr::Ident(idx_ident.clone())); + // a1[_key - i] = arguments[_key]; + + AssignExpr { + span, + left: arg + .computed_member(make_minus_i(&idx_ident, false)) + .into(), + op: op!("="), + right: Box::new( + MemberExpr { + span: DUMMY_SP, + obj: Box::new( + quote_ident!( + Default::default(), + span, + "arguments" + ) + .into(), + ), + prop: MemberProp::Computed(ComputedPropName { + span, + expr: prop, + }), + } + .into(), + ), + } + .into_stmt() + }], + ..Default::default() + })), + } + .into(), + ) } _ => unreachable!(), } @@ -514,10 +525,13 @@ impl VisitMut for Params { if let BlockStmtOrExpr::Expr(v) = body { let mut stmts = vec![]; prepend_stmt(&mut stmts, decls); - stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(v.take()), - })); + stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(v.take()), + } + .into(), + ); *body = BlockStmtOrExpr::BlockStmt(BlockStmt { span: DUMMY_SP, stmts, @@ -784,7 +798,7 @@ impl VisitMut for Params { let decl = self.hoister.take().to_stmt(); if let Some(stmt) = decl { - prepend_stmt(stmts, ModuleItem::Stmt(stmt)); + prepend_stmt(stmts, stmt.into()); } } diff --git a/crates/swc_ecma_compat_es2015/src/spread.rs b/crates/swc_ecma_compat_es2015/src/spread.rs index 195504e98daa..f9f9cd9d411c 100644 --- a/crates/swc_ecma_compat_es2015/src/spread.rs +++ b/crates/swc_ecma_compat_es2015/src/spread.rs @@ -209,7 +209,7 @@ impl Spread { if !self.vars.is_empty() { prepend_stmt( items, - T::from_stmt( + T::from( VarDecl { kind: VarDeclKind::Var, decls: self.vars.take(), diff --git a/crates/swc_ecma_compat_es2015/src/template_literal.rs b/crates/swc_ecma_compat_es2015/src/template_literal.rs index 312a260a81dc..5a544ffa4280 100644 --- a/crates/swc_ecma_compat_es2015/src/template_literal.rs +++ b/crates/swc_ecma_compat_es2015/src/template_literal.rs @@ -5,9 +5,7 @@ use swc_atoms::JsWord; use swc_common::{util::take::Take, BytePos, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{helper, perf::Parallel}; -use swc_ecma_utils::{ - is_literal, prepend_stmts, private_ident, quote_ident, ExprFactory, StmtLike, -}; +use swc_ecma_utils::{is_literal, prepend_stmts, private_ident, quote_ident, ExprFactory}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; use swc_trace_macro::swc_trace; @@ -356,11 +354,14 @@ impl VisitMut for TemplateLiteral { ..Default::default() }; - self.added.push(Stmt::Decl(Decl::Fn(FnDecl { - declare: false, - ident: fn_ident.clone(), - function: f.into(), - }))); + self.added.push( + FnDecl { + declare: false, + ident: fn_ident.clone(), + function: f.into(), + } + .into(), + ); *e = CallExpr { span: DUMMY_SP, @@ -388,7 +389,7 @@ impl VisitMut for TemplateLiteral { fn visit_mut_module(&mut self, m: &mut Module) { m.visit_mut_children_with(self); - prepend_stmts(&mut m.body, self.added.drain(..).map(ModuleItem::from_stmt)); + prepend_stmts(&mut m.body, self.added.drain(..).map(ModuleItem::from)); } fn visit_mut_script(&mut self, m: &mut Script) { diff --git a/crates/swc_ecma_compat_es2017/src/async_to_generator.rs b/crates/swc_ecma_compat_es2017/src/async_to_generator.rs index ad77a64c0b2c..eadd4d540367 100644 --- a/crates/swc_ecma_compat_es2017/src/async_to_generator.rs +++ b/crates/swc_ecma_compat_es2017/src/async_to_generator.rs @@ -107,9 +107,9 @@ impl AsyncToGenerator { }; stmt.visit_mut_with(&mut actual); - stmts_updated.extend(actual.hoist_stmts.into_iter().map(T::from_stmt)); + stmts_updated.extend(actual.hoist_stmts.into_iter().map(T::from)); stmts_updated.push(stmt); - stmts_updated.extend(actual.extra_stmts.into_iter().map(T::from_stmt)); + stmts_updated.extend(actual.extra_stmts.into_iter().map(T::from)); } *stmts = stmts_updated; @@ -153,18 +153,21 @@ impl VisitMut for Actual { stmts: visitor .to_stmt() .into_iter() - .chain(iter::once(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some( - CallExpr { - span: DUMMY_SP, - callee: expr.as_callee(), - args: vec![], - ..Default::default() - } - .into(), - ), - }))) + .chain(iter::once( + ReturnStmt { + span: DUMMY_SP, + arg: Some( + CallExpr { + span: DUMMY_SP, + callee: expr.as_callee(), + args: vec![], + ..Default::default() + } + .into(), + ), + } + .into(), + )) .collect(), ..Default::default() }), @@ -205,7 +208,7 @@ impl VisitMut for Actual { let FnWrapperResult { name_fn, ref_fn } = wrapper.into(); *f = name_fn; - self.extra_stmts.push(Stmt::Decl(ref_fn.into())); + self.extra_stmts.push(ref_fn.into()); } fn visit_mut_module_item(&mut self, item: &mut ModuleItem) { @@ -224,14 +227,12 @@ impl VisitMut for Actual { let FnWrapperResult { name_fn, ref_fn } = wrapper.into(); - *item = ModuleItem::ModuleDecl( - ExportDefaultDecl { - span: export_default.span, - decl: name_fn.into(), - } - .into(), - ); - self.extra_stmts.push(Stmt::Decl(ref_fn.into())); + *item = ExportDefaultDecl { + span: export_default.span, + decl: name_fn.into(), + } + .into(); + self.extra_stmts.push(ref_fn.into()); }; } else { export_default.visit_mut_children_with(self); @@ -624,16 +625,19 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { ); } ForHead::Pat(p) => { - for_loop_body.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: AssignExpr { + for_loop_body.push( + ExprStmt { span: DUMMY_SP, - op: op!("="), - left: p.try_into().unwrap(), - right: Box::new(value.into()), + expr: AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: p.try_into().unwrap(), + right: Box::new(value.into()), + } + .into(), } .into(), - })); + ); } ForHead::UsingDecl(..) => { @@ -676,7 +680,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { definite: false, }); - let for_stmt = Stmt::For(ForStmt { + let for_stmt = ForStmt { span: s.span, // var _iterator = _async_iterator(lol()), _step; init: Some( @@ -754,7 +758,8 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { .into(), ), body: Box::new(Stmt::Block(for_loop_body)), - }); + } + .into(); BlockStmt { span: body_span, @@ -765,7 +770,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { let catch_clause = { // _didIteratorError = true; - let mark_as_errorred = Stmt::Expr(ExprStmt { + let mark_as_errorred = ExprStmt { span: DUMMY_SP, expr: AssignExpr { span: DUMMY_SP, @@ -774,9 +779,10 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { right: true.into(), } .into(), - }); + } + .into(); // _iteratorError = err; - let store_error = Stmt::Expr(ExprStmt { + let store_error = ExprStmt { span: DUMMY_SP, expr: AssignExpr { span: DUMMY_SP, @@ -785,7 +791,8 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { right: Box::new(err_param.clone().into()), } .into(), - }); + } + .into(); CatchClause { span: DUMMY_SP, @@ -798,11 +805,12 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { }; let finally_block = { - let throw_iterator_error = Stmt::Throw(ThrowStmt { + let throw_iterator_error = ThrowStmt { span: DUMMY_SP, arg: iterator_error.clone().into(), - }); - let throw_iterator_error = Stmt::If(IfStmt { + } + .into(); + let throw_iterator_error = IfStmt { span: DUMMY_SP, test: did_iteration_error.clone().into(), cons: Box::new(Stmt::Block(BlockStmt { @@ -811,7 +819,8 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { ..Default::default() })), alt: None, - }); + } + .into(); let iterator_return: Expr = CallExpr { span: DUMMY_SP, @@ -827,7 +836,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { // yield _iterator.return(); // or // yield _awaitAsyncGenerator(_iterator.return()); - let yield_stmt = Stmt::Expr(ExprStmt { + let yield_stmt = ExprStmt { span: DUMMY_SP, expr: YieldExpr { span: DUMMY_SP, @@ -845,9 +854,10 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { }), } .into(), - }); + } + .into(); - let conditional_yield = Stmt::If(IfStmt { + let conditional_yield = IfStmt { span: DUMMY_SP, // _iteratorAbruptCompletion && _iterator.return != null test: BinExpr { @@ -872,7 +882,8 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { ..Default::default() })), alt: None, - }); + } + .into(); let body = BlockStmt { stmts: vec![conditional_yield], ..Default::default() @@ -933,9 +944,10 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { try_stmt.into(), ]; - *stmt = Stmt::Block(BlockStmt { + *stmt = BlockStmt { span: s.span, stmts, ..Default::default() - }) + } + .into() } diff --git a/crates/swc_ecma_compat_es2018/src/object_rest.rs b/crates/swc_ecma_compat_es2018/src/object_rest.rs index ea958209f03d..81d65f23a148 100644 --- a/crates/swc_ecma_compat_es2018/src/object_rest.rs +++ b/crates/swc_ecma_compat_es2018/src/object_rest.rs @@ -307,7 +307,7 @@ impl VisitMut for ObjectRest { var_decl.visit_mut_with(self); self.vars.append(&mut var_decl.decls); - *decl = ModuleDecl::ExportNamed(export); + *decl = export.into(); } _ => { decl.visit_mut_children_with(self); @@ -469,7 +469,7 @@ impl ObjectRest { // Add variable declaration // e.g. var ref if !folder.mutable_vars.is_empty() { - buf.push(T::from_stmt( + buf.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -481,7 +481,7 @@ impl ObjectRest { } if !folder.vars.is_empty() { - buf.push(T::from_stmt( + buf.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -494,13 +494,7 @@ impl ObjectRest { buf.push(stmt); - buf.extend( - folder - .exprs - .into_iter() - .map(|v| v.into_stmt()) - .map(T::from_stmt), - ); + buf.extend(folder.exprs.into_iter().map(|v| v.into_stmt()).map(T::from)); } *stmts = buf; diff --git a/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs b/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs index 5cd22d3f4e04..0ed7bc205ea4 100644 --- a/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs +++ b/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs @@ -74,35 +74,40 @@ impl VisitMut for ExportNamespaceFrom { } } - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { - span, - specifiers: import_specifiers, - src: src.clone(), - type_only: false, - with: with.clone(), - phase: Default::default(), - }))); + stmts.push( + ImportDecl { + span, + specifiers: import_specifiers, + src: src.clone(), + type_only: false, + with: with.clone(), + phase: Default::default(), + } + .into(), + ); - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + stmts.push( NamedExport { span, specifiers: export_specifiers, src: None, type_only: false, with: None, - }, - ))); + } + .into(), + ); if !origin_specifiers.is_empty() { - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + stmts.push( NamedExport { span, specifiers: origin_specifiers, src: Some(src), type_only: false, with, - }, - ))); + } + .into(), + ); } } _ => { diff --git a/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs b/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs index c718dae7956a..99323e5f1527 100644 --- a/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs +++ b/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs @@ -39,7 +39,7 @@ impl NullishCoalescing { stmt.visit_mut_with(self); if !self.vars.is_empty() { - buf.push(T::from_stmt( + buf.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs b/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs index e9f3eb43c91b..b2e6ea49d016 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs @@ -189,8 +189,8 @@ impl MemberInitRecord { for value in self.record { match value { - MemberInit::PubProp(PubProp { span, name, value }) => { - value_init.push(Stmt::Expr(ExprStmt { + MemberInit::PubProp(PubProp { span, name, value }) => value_init.push( + ExprStmt { span, expr: (if self.c.set_public_fields { let class = class_ident.clone(); @@ -217,11 +217,12 @@ impl MemberInitRecord { .into() }) .into(), - })) - } + } + .into(), + ), MemberInit::PrivProp(PrivProp { span, name, value }) => { value_init.push(if self.c.private_as_properties { - Stmt::Expr(ExprStmt { + ExprStmt { span, expr: CallExpr { span, @@ -234,7 +235,8 @@ impl MemberInitRecord { ..Default::default() } .into(), - }) + } + .into() } else { VarDecl { span, @@ -256,7 +258,7 @@ impl MemberInitRecord { getter, setter, }) => normal_init.push(if self.c.private_as_properties { - Stmt::Expr(ExprStmt { + ExprStmt { span, expr: CallExpr { span, @@ -269,7 +271,8 @@ impl MemberInitRecord { ..Default::default() } .into(), - }) + } + .into() } else { VarDecl { span, @@ -290,20 +293,23 @@ impl MemberInitRecord { fn_name, }) => { if self.c.private_as_properties { - normal_init.push(Stmt::Expr(ExprStmt { - span, - expr: CallExpr { + normal_init.push( + ExprStmt { span, - callee: obj_def_prop(), - args: vec![ - class_ident.clone().as_arg(), - name.as_arg(), - get_method_desc(Box::new(fn_name.into())).as_arg(), - ], - ..Default::default() + expr: CallExpr { + span, + callee: obj_def_prop(), + args: vec![ + class_ident.clone().as_arg(), + name.as_arg(), + get_method_desc(Box::new(fn_name.into())).as_arg(), + ], + ..Default::default() + } + .into(), } .into(), - })) + ) } else { unreachable!() } diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs b/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs index 9d2125c91123..c7f37a63c768 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs @@ -94,59 +94,54 @@ struct ClassExtra { #[swc_trace] impl ClassExtra { - fn prepend_with>(self, stmts: &mut Vec) { + fn prepend_with(self, stmts: &mut Vec) { if !self.vars.is_empty() { prepend_stmt( stmts, - Stmt::from(VarDecl { + T::from(Stmt::from(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, decls: self.vars, ..Default::default() - }) - .into(), + })), ) } if !self.lets.is_empty() { prepend_stmt( stmts, - Stmt::from(VarDecl { + T::from(Stmt::from(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, decls: self.lets, ..Default::default() - }) - .into(), + })), ) } stmts.extend(self.stmts.into_iter().map(|stmt| stmt.into())) } - fn merge_with>(self, stmts: &mut Vec, class: T) { + fn merge_with(self, stmts: &mut Vec, class: T) { if !self.vars.is_empty() { - stmts.push( - Stmt::from(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - decls: self.vars, - ..Default::default() - }) - .into(), - ) + stmts.push(T::from(Stmt::from(VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + decls: self.vars, + ..Default::default() + }))) } if !self.lets.is_empty() { - stmts.push( - Stmt::from(VarDecl { + stmts.push(T::from( + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, decls: self.lets, ..Default::default() - }) + } .into(), - ) + )); } stmts.push(class); @@ -190,12 +185,15 @@ impl VisitMut for ClassProperties { let ident = ident.unwrap_or_else(|| private_ident!("_class")); let (decl, extra) = self.visit_mut_class_as_decl(ident.clone(), class); - extra.merge_with(&mut stmts, Stmt::Decl(Decl::Class(decl))); + extra.merge_with(&mut stmts, decl.into()); - stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(ident.into()), - })); + stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(ident.into()), + } + .into(), + ); *body = BlockStmtOrExpr::BlockStmt(BlockStmt { span: DUMMY_SP, @@ -353,13 +351,10 @@ impl ClassProperties { let (decl, extra) = self.visit_mut_class_as_decl(ident.clone(), class); - extra.merge_with( - &mut buf, - T::from_stmt(Stmt::Decl(Decl::Class(decl))), - ); + extra.merge_with(&mut buf, T::from(decl.into())); buf.push( - match T::try_from_module_decl(ModuleDecl::ExportNamed( + match T::try_from_module_decl( NamedExport { span, specifiers: vec![ExportNamedSpecifier { @@ -374,8 +369,9 @@ impl ClassProperties { src: None, type_only: false, with: None, - }, - )) { + } + .into(), + ) { Ok(t) => t, Err(..) => unreachable!(), }, @@ -394,12 +390,13 @@ impl ClassProperties { let (decl, extra) = self.visit_mut_class_as_decl(ident, class); extra.merge_with( &mut buf, - match T::try_from_module_decl(ModuleDecl::ExportDecl( + match T::try_from_module_decl( ExportDecl { span, - decl: Decl::Class(decl), - }, - )) { + decl: decl.into(), + } + .into(), + ) { Ok(t) => t, Err(..) => unreachable!(), }, @@ -425,11 +422,11 @@ impl ClassProperties { declare: false, })) => { let (decl, extra) = self.visit_mut_class_as_decl(ident, class); - extra.merge_with(&mut buf, T::from_stmt(Stmt::Decl(Decl::Class(decl)))) + extra.merge_with(&mut buf, T::from(decl.into())) } _ => { stmt.visit_mut_children_with(self); - buf.push(T::from_stmt(stmt)) + buf.push(T::from(stmt)) } } } @@ -956,11 +953,14 @@ impl ClassProperties { in_pat: false, }); - private_method_fn_decls.push(Stmt::Decl(Decl::Fn(FnDecl { - ident: fn_name, - function: method.function, - declare: false, - }))) + private_method_fn_decls.push( + FnDecl { + ident: fn_name, + function: method.function, + declare: false, + } + .into(), + ) } ClassMember::StaticBlock(..) => { diff --git a/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs b/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs index fc81f0a07366..a000b3c01291 100644 --- a/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs +++ b/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs @@ -407,7 +407,7 @@ impl OptionalChaining { if !self.vars.is_empty() { prepend_stmt( stmts, - T::from_stmt( + T::from( VarDecl { span: DUMMY_SP, declare: false, diff --git a/crates/swc_ecma_compat_es2022/src/private_in_object.rs b/crates/swc_ecma_compat_es2022/src/private_in_object.rs index acc1396936b9..c3c67efef37c 100644 --- a/crates/swc_ecma_compat_es2022/src/private_in_object.rs +++ b/crates/swc_ecma_compat_es2022/src/private_in_object.rs @@ -184,10 +184,13 @@ impl VisitMut for PrivateInObject { }) = m { for expr in take(&mut self.cls.constructor_exprs) { - body.stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr, - })); + body.stmts.push( + ExprStmt { + span: DUMMY_SP, + expr, + } + .into(), + ); } } } @@ -261,10 +264,13 @@ impl VisitMut for PrivateInObject { stmts: vec![], ..Default::default() }; - bs.stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(p.right.take()), - })); + bs.stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(p.right.take()), + } + .into(), + ); bs.visit_mut_with(self); p.right = CallExpr { diff --git a/crates/swc_ecma_compat_es3/src/reserved_word.rs b/crates/swc_ecma_compat_es3/src/reserved_word.rs index 3b38ea2c4a4a..3e681423e4ad 100644 --- a/crates/swc_ecma_compat_es3/src/reserved_word.rs +++ b/crates/swc_ecma_compat_es3/src/reserved_word.rs @@ -50,7 +50,7 @@ impl VisitMut for ReservedWord { return; } - *module_item = ModuleItem::Stmt(decl.take().into()); + *module_item = decl.take().into(); let mut orig = ident.clone(); orig.visit_mut_with(self); @@ -101,7 +101,7 @@ impl VisitMut for ReservedWord { ); } - *module_item = ModuleItem::Stmt(Decl::Var(var.take()).into()); + *module_item = var.take().into(); } _ => {} @@ -111,16 +111,14 @@ impl VisitMut for ReservedWord { }); if !extra_exports.is_empty() { - let module_item = ModuleItem::ModuleDecl( - NamedExport { - span: DUMMY_SP, - specifiers: extra_exports, - src: None, - type_only: false, - with: None, - } - .into(), - ); + let module_item = NamedExport { + span: DUMMY_SP, + specifiers: extra_exports, + src: None, + type_only: false, + with: None, + } + .into(); n.push(module_item); } diff --git a/crates/swc_ecma_ext_transforms/src/jest.rs b/crates/swc_ecma_ext_transforms/src/jest.rs index 1c6eb13528db..d0f792b3e802 100644 --- a/crates/swc_ecma_ext_transforms/src/jest.rs +++ b/crates/swc_ecma_ext_transforms/src/jest.rs @@ -43,15 +43,15 @@ impl Jest { .. }) => { if self.should_hoist(callee) { - hoisted.push(T::from_stmt(stmt)) + hoisted.push(T::from(stmt)) } else { - new.push(T::from_stmt(stmt)) + new.push(T::from(stmt)) } } - _ => new.push(T::from_stmt(stmt)), + _ => new.push(T::from(stmt)), }, - _ => new.push(T::from_stmt(stmt)), + _ => new.push(T::from(stmt)), }, Err(node) => new.push(node), }; diff --git a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs index 11e1666f2091..be315596507f 100644 --- a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs +++ b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs @@ -115,7 +115,7 @@ impl Hoister<'_> { match stmt { Stmt::Decl(Decl::Fn(..)) if self.config.hoist_fns => { // Move functions to top. - fn_decls.push(T::from_stmt(stmt)) + fn_decls.push(T::from(stmt)) } Stmt::Decl(Decl::Var(var)) @@ -172,18 +172,21 @@ impl Hoister<'_> { if exprs.is_empty() { continue; } - new_stmts.push(T::from_stmt(Stmt::Expr(ExprStmt { - span: var.span, - expr: if exprs.len() == 1 { - exprs.into_iter().next().unwrap() - } else { - SeqExpr { - span: DUMMY_SP, - exprs, - } - .into() - }, - }))) + new_stmts.push(T::from( + ExprStmt { + span: var.span, + expr: if exprs.len() == 1 { + exprs.into_iter().next().unwrap() + } else { + SeqExpr { + span: DUMMY_SP, + exprs, + } + .into() + }, + } + .into(), + )) } Stmt::Decl(Decl::Var(v)) @@ -234,10 +237,10 @@ impl Hoister<'_> { })); } - Stmt::Decl(Decl::Var(..)) => new_stmts.push(T::from_stmt(stmt)), + Stmt::Decl(Decl::Var(..)) => new_stmts.push(T::from(stmt)), _ => { if let Stmt::Throw(..) = stmt { - fn_decls.push(T::from_stmt( + fn_decls.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -249,7 +252,7 @@ impl Hoister<'_> { )); } found_non_var_decl = true; - new_stmts.push(T::from_stmt(stmt)) + new_stmts.push(T::from(stmt)) } } } @@ -257,7 +260,7 @@ impl Hoister<'_> { } } - fn_decls.push(T::from_stmt( + fn_decls.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, diff --git a/crates/swc_ecma_minifier/src/compress/optimize/bools.rs b/crates/swc_ecma_minifier/src/compress/optimize/bools.rs index 342334f2e384..80e6273f322b 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/bools.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/bools.rs @@ -97,7 +97,7 @@ impl Optimizer<'_> { if let Stmt::Expr(cons) = &mut *stmt.cons { self.changed = true; report_change!("conditionals: `if (foo) bar;` => `foo && bar`"); - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: BinExpr { span: stmt.test.span(), @@ -106,7 +106,8 @@ impl Optimizer<'_> { right: cons.expr.take(), } .into(), - }); + } + .into(); } } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs index 49fe57d3f3b9..52b8660915a7 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs @@ -154,7 +154,7 @@ impl Optimizer<'_> { } .into(); } else { - new.extend(cur.take().map(Stmt::If).map(T::from_stmt)); + new.extend(cur.take().map(Stmt::If).map(T::from)); cur = Some(stmt); } @@ -165,21 +165,21 @@ impl Optimizer<'_> { } } _ => { - new.extend(cur.take().map(Stmt::If).map(T::from_stmt)); + new.extend(cur.take().map(Stmt::If).map(T::from)); - new.push(T::from_stmt(stmt)); + new.push(T::from(stmt)); } } } Err(item) => { - new.extend(cur.take().map(Stmt::If).map(T::from_stmt)); + new.extend(cur.take().map(Stmt::If).map(T::from)); new.push(item); } } } - new.extend(cur.map(Stmt::If).map(T::from_stmt)); + new.extend(cur.map(Stmt::If).map(T::from)); *stmts = new; } @@ -214,10 +214,11 @@ impl Optimizer<'_> { if let Stmt::Empty(..) = &*stmt.cons { if (self.options.conditionals || self.options.unused) && stmt.alt.is_none() { - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: stmt.test.take(), - }); + } + .into(); self.changed = true; report_change!("conditionals: `if (foo);` => `foo` "); return; @@ -255,10 +256,11 @@ impl Optimizer<'_> { } .into(); self.compress_logical_exprs_as_bang_bang(&mut expr, true); - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: expr.into(), - }); + } + .into(); } _ => { report_change!("Optimizing `if (foo); else bar();` as `foo || bar();`"); @@ -271,10 +273,11 @@ impl Optimizer<'_> { } .into(); self.compress_logical_exprs_as_bang_bang(&mut expr, false); - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: expr.into(), - }); + } + .into(); } } return; @@ -292,10 +295,11 @@ impl Optimizer<'_> { self.changed = true; report_change!("conditionals: Merging cons and alt as only one argument differs"); - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: Box::new(v), - }); + } + .into(); return; } @@ -306,7 +310,7 @@ impl Optimizer<'_> { not compressable)" ); self.changed = true; - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: CondExpr { span: DUMMY_SP, @@ -315,7 +319,8 @@ impl Optimizer<'_> { alt: Box::new(alt.take()), } .into(), - }) + } + .into() } } @@ -811,14 +816,17 @@ impl Optimizer<'_> { s.alt = Some(if alt.len() == 1 { Box::new(alt.into_iter().next().unwrap()) } else { - Box::new(Stmt::Block(BlockStmt { - span: DUMMY_SP, - stmts: alt, - ..Default::default() - })) + Box::new( + BlockStmt { + span: DUMMY_SP, + stmts: alt, + ..Default::default() + } + .into(), + ) }); - new.push(Stmt::If(s)) + new.push(s.into()) } _ => { unreachable!() @@ -875,16 +883,19 @@ impl Optimizer<'_> { swap(&mut cons, &mut alt); } - new_stmts.push(T::from_stmt(Stmt::If(IfStmt { - span, - test, - cons, - alt: None, - }))); - new_stmts.push(T::from_stmt(*alt)); + new_stmts.push(T::from( + IfStmt { + span, + test, + cons, + alt: None, + } + .into(), + )); + new_stmts.push(T::from(*alt)); } _ => { - new_stmts.push(T::from_stmt(stmt)); + new_stmts.push(T::from(stmt)); } }, Err(stmt) => new_stmts.push(stmt), 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 304b7731d7fd..a2604c644132 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs @@ -392,19 +392,25 @@ impl Optimizer<'_> { let expr = self.ignore_return_value(&mut cur); if let Some(cur) = expr { - new.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Box::new(cur), - })) + new.push( + ExprStmt { + span: DUMMY_SP, + expr: Box::new(cur), + } + .into(), + ) } else { trace_op!("if_return: Ignoring return value"); } } _ => { - new.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(cur), - })); + new.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(cur), + } + .into(), + ); } } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/loops.rs b/crates/swc_ecma_minifier/src/compress/optimize/loops.rs index ae1feb8f50d7..e9e48e31c0af 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/loops.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/loops.rs @@ -26,28 +26,34 @@ impl Optimizer<'_> { self.changed = true; report_change!("loops: Removing a for loop with instant break"); - self.prepend_stmts - .extend(f.init.take().map(|init| match init { - VarDeclOrExpr::VarDecl(var) => Stmt::Decl(Decl::Var(var)), - VarDeclOrExpr::Expr(expr) => Stmt::Expr(ExprStmt { + self.prepend_stmts.extend(f.init.take().map(|init| { + match init { + VarDeclOrExpr::VarDecl(var) => var.into(), + VarDeclOrExpr::Expr(expr) => ExprStmt { span: DUMMY_SP, expr, - }), - })); + } + .into(), + } + })); self.prepend_stmts.extend(f.test.take().map(|expr| { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr, - }) + } + .into() })); if label.is_some() { - self.prepend_stmts.push(Stmt::Break(BreakStmt { - span: DUMMY_SP, - label, - })); + self.prepend_stmts.push( + BreakStmt { + span: DUMMY_SP, + label, + } + .into(), + ); } - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }) + *s = EmptyStmt { span: DUMMY_SP }.into() } /// @@ -89,18 +95,23 @@ impl Optimizer<'_> { } self.changed |= f.init.is_some() | f.update.is_some(); - self.prepend_stmts - .extend(f.init.take().map(|init| match init { - VarDeclOrExpr::VarDecl(var) => Stmt::Decl(Decl::Var(var)), - VarDeclOrExpr::Expr(expr) => Stmt::Expr(ExprStmt { + self.prepend_stmts.extend(f.init.take().map(|init| { + match init { + VarDeclOrExpr::VarDecl(var) => var.into(), + VarDeclOrExpr::Expr(expr) => ExprStmt { span: DUMMY_SP, expr, - }), - })); - self.prepend_stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: f.test.take().unwrap(), + } + .into(), + } })); + self.prepend_stmts.push( + ExprStmt { + span: DUMMY_SP, + expr: f.test.take().unwrap(), + } + .into(), + ); f.update = None; *stmt = *f.body.take(); } else if let Known(true) = val { diff --git a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs index 4fef938c4b39..b3f706b2fe17 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs @@ -455,21 +455,21 @@ impl Optimizer<'_> { stmt.visit_with(&mut AssertValid); } - new.extend(self.prepend_stmts.drain(..).map(T::from_stmt)); + new.extend(self.prepend_stmts.drain(..).map(T::from)); match stmt.try_into_stmt() { Ok(Stmt::Block(s)) if s.ctxt.has_mark(self.marks.fake_block) => { - new.extend(s.stmts.into_iter().map(T::from_stmt)); + new.extend(s.stmts.into_iter().map(T::from)); } Ok(s) => { - new.push(T::from_stmt(s)); + new.push(T::from(s)); } Err(stmt) => { new.push(stmt); } } - new.extend(self.append_stmts.drain(..).map(T::from_stmt)); + new.extend(self.append_stmts.drain(..).map(T::from)); } *stmts = new; } @@ -516,7 +516,7 @@ impl Optimizer<'_> { stmts.visit_with(&mut AssertValid); } - // stmts.extend(self.append_stmts.drain(..).map(T::from_stmt)); + // stmts.extend(self.append_stmts.drain(..).map(T::from)); drop_invalid_stmts(stmts); @@ -1330,7 +1330,7 @@ impl Optimizer<'_> { Stmt::Block(bs) => { if bs.stmts.is_empty() { report_change!("Converting empty block to empty statement"); - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } @@ -1385,7 +1385,7 @@ impl Optimizer<'_> { if block.stmts.is_empty() { self.changed = true; report_change!("optimizer: Removing empty block"); - *stmt = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *stmt = EmptyStmt { span: DUMMY_SP }.into(); return; } } @@ -1447,7 +1447,7 @@ impl Optimizer<'_> { match s { Stmt::Block(block) if block.stmts.is_empty() => { - *s = Stmt::Empty(EmptyStmt { span: block.span }); + *s = EmptyStmt { span: block.span }.into(); } Stmt::Block(block) if block.stmts.len() == 1 && is_fine_for_if_cons(&block.stmts[0]) => @@ -1472,10 +1472,11 @@ impl Optimizer<'_> { if let Stmt::Expr(cons) = &mut *stmt.cons { self.changed = true; report_change!("Converting if statement to a form `test && cons`"); - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: stmt.span, expr: Box::new(stmt.test.take().make_bin(op!("&&"), *cons.expr.take())), - }); + } + .into(); } } } @@ -1525,10 +1526,13 @@ impl VisitMut for Optimizer<'_> { self.changed = true; report_change!("Converting a body of an arrow expression to BlockStmt"); - stmts.push(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some(v.take()), - })); + stmts.push( + ReturnStmt { + span: DUMMY_SP, + arg: Some(v.take()), + } + .into(), + ); n.body = Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt { span: DUMMY_SP, stmts, @@ -2543,14 +2547,14 @@ impl VisitMut for Optimizer<'_> { match s { // We use var decl with no declarator to indicate we dropped an decl. Stmt::Decl(Decl::Var(v)) if v.decls.is_empty() => { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); self.prepend_stmts = old_prepend; self.append_stmts = old_append; return; } Stmt::Expr(es) => { if es.expr.is_invalid() { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); self.prepend_stmts = old_prepend; self.append_stmts = old_append; return; @@ -2617,7 +2621,7 @@ impl VisitMut for Optimizer<'_> { report_change!("Creating a fake block because of prepend or append"); let span = s.span(); - *s = Stmt::Block(BlockStmt { + *s = BlockStmt { span, ctxt: SyntaxContext::empty().apply_mark(self.marks.fake_block), stmts: self @@ -2632,7 +2636,8 @@ impl VisitMut for Optimizer<'_> { _ => true, }) .collect(), - }); + } + .into(); #[cfg(debug_assertions)] { @@ -2660,7 +2665,7 @@ impl VisitMut for Optimizer<'_> { if let Stmt::Expr(ExprStmt { expr, .. }) = s { if is_pure_undefined(&self.expr_ctx, expr) { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } @@ -2675,7 +2680,7 @@ impl VisitMut for Optimizer<'_> { } { report_change!("Removing 'use strict'"); - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } @@ -2688,7 +2693,7 @@ impl VisitMut for Optimizer<'_> { self.changed = true; report_change!("unused: Dropping an expression without side effect"); dump_change_detail!("unused: Dropping \n{}\n", dump(&*expr, false)); - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } } @@ -2700,7 +2705,7 @@ impl VisitMut for Optimizer<'_> { match s { // We use var decl with no declarator to indicate we dropped an decl. Stmt::Decl(Decl::Var(v)) if v.decls.is_empty() => { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } _ => {} @@ -3064,18 +3069,21 @@ impl VisitMut for Optimizer<'_> { if can_prepend { can_prepend = false; - self.prepend_stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: if side_effects.len() == 1 { - side_effects.remove(0) - } else { - SeqExpr { - span: DUMMY_SP, - exprs: side_effects.take(), - } - .into() - }, - })); + self.prepend_stmts.push( + ExprStmt { + span: DUMMY_SP, + expr: if side_effects.len() == 1 { + side_effects.remove(0) + } else { + SeqExpr { + span: DUMMY_SP, + exprs: side_effects.take(), + } + .into() + }, + } + .into(), + ); } else { // We prepend side effects to the initializer. @@ -3090,18 +3098,21 @@ impl VisitMut for Optimizer<'_> { // We append side effects. if !side_effects.is_empty() { - self.append_stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: if side_effects.len() == 1 { - side_effects.remove(0) - } else { - SeqExpr { - span: DUMMY_SP, - exprs: side_effects, - } - .into() - }, - })); + self.append_stmts.push( + ExprStmt { + span: DUMMY_SP, + expr: if side_effects.len() == 1 { + side_effects.remove(0) + } else { + SeqExpr { + span: DUMMY_SP, + exprs: side_effects, + } + .into() + }, + } + .into(), + ); } vars.retain_mut(|var| { diff --git a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs index 0715f36e2c83..72b7e3fcbb1c 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs @@ -159,7 +159,7 @@ impl Optimizer<'_> { match stmt.try_into_stmt() { Ok(stmt) => { if is_directive(&stmt) { - new_stmts.push(T::from_stmt(stmt)); + new_stmts.push(T::from(stmt)); continue; } // If @@ -170,19 +170,19 @@ impl Optimizer<'_> { Stmt::If(mut stmt) => { stmt.test.prepend_exprs(take(&mut exprs)); - new_stmts.push(T::from_stmt(Stmt::If(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::Switch(mut stmt) => { stmt.discriminant.prepend_exprs(take(&mut exprs)); - new_stmts.push(T::from_stmt(Stmt::Switch(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::With(mut stmt) => { stmt.obj.prepend_exprs(take(&mut exprs)); - new_stmts.push(T::from_stmt(Stmt::With(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::Return(mut stmt @ ReturnStmt { arg: Some(..), .. }) => { @@ -198,13 +198,13 @@ impl Optimizer<'_> { } } - new_stmts.push(T::from_stmt(Stmt::Return(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::Throw(mut stmt) => { stmt.arg.prepend_exprs(take(&mut exprs)); - new_stmts.push(T::from_stmt(Stmt::Throw(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::For(mut stmt @ ForStmt { init: None, .. }) @@ -270,7 +270,7 @@ impl Optimizer<'_> { )); } - new_stmts.push(T::from_stmt(Stmt::For(stmt))); + new_stmts.push(T::from(stmt.into())); continue; } @@ -291,19 +291,19 @@ impl Optimizer<'_> { unreachable!() } } - new_stmts.push(T::from_stmt(Stmt::For(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::ForIn(mut stmt) => { stmt.right.prepend_exprs(take(&mut exprs)); - new_stmts.push(T::from_stmt(Stmt::ForIn(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::ForOf(mut stmt) => { stmt.right.prepend_exprs(take(&mut exprs)); - new_stmts.push(T::from_stmt(Stmt::ForOf(stmt))); + new_stmts.push(T::from(stmt.into())); } Stmt::Decl(Decl::Var(var)) @@ -315,31 +315,37 @@ impl Optimizer<'_> { } ) && var.decls.iter().all(|v| v.init.is_none()) => { - new_stmts.push(T::from_stmt(Stmt::Decl(Decl::Var(var)))); + new_stmts.push(T::from(var.into())); } Stmt::Decl(Decl::Fn(..)) => { - new_stmts.push(T::from_stmt(stmt)); + new_stmts.push(T::from(stmt)); } _ => { if !exprs.is_empty() { - new_stmts.push(T::from_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Expr::from_exprs(take(&mut exprs)), - }))) + new_stmts.push(T::from( + ExprStmt { + span: DUMMY_SP, + expr: Expr::from_exprs(take(&mut exprs)), + } + .into(), + )) } - new_stmts.push(T::from_stmt(stmt)); + new_stmts.push(T::from(stmt)); } } } Err(item) => { if !exprs.is_empty() { - new_stmts.push(T::from_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Expr::from_exprs(take(&mut exprs)), - }))) + new_stmts.push(T::from( + ExprStmt { + span: DUMMY_SP, + expr: Expr::from_exprs(take(&mut exprs)), + } + .into(), + )) } new_stmts.push(item); @@ -348,10 +354,13 @@ impl Optimizer<'_> { } if !exprs.is_empty() { - new_stmts.push(T::from_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Expr::from_exprs(take(&mut exprs)), - }))) + new_stmts.push(T::from( + ExprStmt { + span: DUMMY_SP, + expr: Expr::from_exprs(take(&mut exprs)), + } + .into(), + )) } *stmts = new_stmts; @@ -412,12 +421,12 @@ impl Optimizer<'_> { .into_iter() .map(|expr| ExprStmt { span, expr }) .map(Stmt::Expr) - .map(T::from_stmt), + .map(T::from), ); } _ => { - new_stmts.push(T::from_stmt(stmt)); + new_stmts.push(T::from(stmt)); } }, Err(stmt) => { @@ -484,11 +493,11 @@ impl Optimizer<'_> { op(stmts); if !self.prepend_stmts.is_empty() { - prepend_stmts(stmts, self.prepend_stmts.drain(..).map(T::from_stmt)); + prepend_stmts(stmts, self.prepend_stmts.drain(..).map(T::from)); } if !self.append_stmts.is_empty() { - stmts.extend(self.append_stmts.drain(..).map(T::from_stmt)); + stmts.extend(self.append_stmts.drain(..).map(T::from)); } self.prepend_stmts = old_prepend; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index 32d65ba6145d..c6c877e2f822 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -145,17 +145,18 @@ impl Optimizer<'_> { } stmts.extend(last.cons); - *s = Stmt::Block(BlockStmt { + *s = BlockStmt { stmts, ..Default::default() - }) + } + .into() } else { report_change!("switches: Removing unreachable cases from a constant switch"); stmt.cases = cases; if !var_ids.is_empty() { - *s = Stmt::Block(BlockStmt { + *s = BlockStmt { stmts: vec![ VarDecl { span: DUMMY_SP, @@ -168,7 +169,8 @@ impl Optimizer<'_> { s.take(), ], ..Default::default() - }) + } + .into() } } } @@ -347,10 +349,11 @@ impl Optimizer<'_> { [] => { self.changed = true; report_change!("switches: Removing empty switch"); - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: sw.span, expr: sw.discriminant.take(), - }) + } + .into() } [case] => { if contains_nested_break(case) { @@ -372,7 +375,7 @@ impl Optimizer<'_> { } .into(); - *s = Stmt::If(IfStmt { + *s = IfStmt { span: sw.span, test, cons: Box::new(Stmt::Block(BlockStmt { @@ -381,7 +384,8 @@ impl Optimizer<'_> { ..Default::default() })), alt: None, - }) + } + .into() } else { // is default let mut stmts = vec![Stmt::Expr(ExprStmt { @@ -389,11 +393,12 @@ impl Optimizer<'_> { expr: discriminant, })]; stmts.extend(case.cons); - *s = Stmt::Block(BlockStmt { + *s = BlockStmt { span: sw.span, stmts, ..Default::default() - }) + } + .into() } } [first, second] if first.test.is_none() || second.test.is_none() => { @@ -412,7 +417,7 @@ impl Optimizer<'_> { } else { (second, first) }; - *s = Stmt::If(IfStmt { + *s = IfStmt { span: sw.span, test: BinExpr { span: DUMMY_SP, @@ -435,7 +440,8 @@ impl Optimizer<'_> { }) .into(), ), - }) + } + .into() } else { let mut stmts = vec![Stmt::If(IfStmt { span: DUMMY_SP, @@ -464,11 +470,12 @@ impl Optimizer<'_> { alt: None, })]; stmts.extend(second.cons.take()); - *s = Stmt::Block(BlockStmt { + *s = BlockStmt { span: sw.span, stmts, ..Default::default() - }) + } + .into() } } _ => (), diff --git a/crates/swc_ecma_minifier/src/compress/optimize/unused.rs b/crates/swc_ecma_minifier/src/compress/optimize/unused.rs index 64e7778dd770..b7f01caf5d45 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/unused.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/unused.rs @@ -490,18 +490,21 @@ impl Optimizer<'_> { let mut side_effects = extract_class_side_effect(&self.expr_ctx, *class.class); if !side_effects.is_empty() { - self.prepend_stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: if side_effects.len() > 1 { - SeqExpr { - span: DUMMY_SP, - exprs: side_effects, - } - .into() - } else { - side_effects.remove(0) - }, - })) + self.prepend_stmts.push( + ExprStmt { + span: DUMMY_SP, + expr: if side_effects.len() > 1 { + SeqExpr { + span: DUMMY_SP, + exprs: side_effects, + } + .into() + } else { + side_effects.remove(0) + }, + } + .into(), + ) } } } 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 c8440d4704ac..b905025d3b54 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs @@ -77,12 +77,15 @@ impl Pure<'_> { let mut cons = bs.take(); cons.stmts.remove(0); - ls.body = Box::new(Stmt::If(IfStmt { - span: ls.span, - test, - cons: Box::new(Stmt::Block(cons)), - alt: None, - })); + ls.body = Box::new( + IfStmt { + span: ls.span, + test, + cons: Box::new(Stmt::Block(cons)), + alt: None, + } + .into(), + ); return None; } } @@ -112,12 +115,15 @@ impl Pure<'_> { let mut new_cons = bs.take(); new_cons.stmts[0] = cons; - ls.body = Box::new(Stmt::If(IfStmt { - span: ls.span, - test, - cons: Box::new(Stmt::Block(new_cons)), - alt: None, - })); + ls.body = Box::new( + IfStmt { + span: ls.span, + test, + cons: Box::new(Stmt::Block(new_cons)), + alt: None, + } + .into(), + ); return None; } } @@ -240,7 +246,7 @@ impl Pure<'_> { |(mut decls, mut hoisted_fns, mut new_stmts), stmt| { match stmt.take().try_into_stmt() { Ok(Stmt::Decl(Decl::Fn(f))) => { - hoisted_fns.push(Stmt::Decl(Decl::Fn(f)).into()); + hoisted_fns.push(T::from(Stmt::from(f))); } Ok(t) => { let ids = extract_var_ids(&t).into_iter().map(|i| VarDeclarator { @@ -258,16 +264,13 @@ impl Pure<'_> { ); if !decls.is_empty() { - new_stmts.push( - Stmt::from(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - decls, - declare: false, - ..Default::default() - }) - .into(), - ); + new_stmts.push(T::from(Stmt::from(VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + decls, + declare: false, + ..Default::default() + }))); } new_stmts.extend(stmts.drain(..=idx)); @@ -290,10 +293,11 @@ impl Pure<'_> { match stmt.as_stmt_mut() { Some(s) if s.eq_ignore_span(last) => { if need_break { - *s = Stmt::Break(BreakStmt { + *s = BreakStmt { label: None, span: s.span(), - }); + } + .into(); } else { s.take(); } @@ -418,11 +422,11 @@ impl Pure<'_> { Stmt::Block(v) if is_ok(&v) => { let stmts = v.stmts; maybe_par!( - stmts.into_iter().map(T::from_stmt).collect(), + stmts.into_iter().map(T::from).collect(), *crate::LIGHT_TASK_PARALLELS ) } - _ => vec![T::from_stmt(v)], + _ => vec![T::from(v)], }, Err(v) => vec![v], }) @@ -437,11 +441,11 @@ impl Pure<'_> { Stmt::Block(v) if is_ok(&v) => { let stmts = v.stmts; maybe_par!( - stmts.into_iter().map(T::from_stmt).collect(), + stmts.into_iter().map(T::from).collect(), *crate::LIGHT_TASK_PARALLELS ) } - _ => vec![T::from_stmt(v)], + _ => vec![T::from(v)], }, Err(v) => vec![v], }) @@ -454,9 +458,9 @@ impl Pure<'_> { .for_each(|stmt| match stmt.try_into_stmt() { Ok(v) => match v { Stmt::Block(v) if is_ok(&v) => { - new.extend(v.stmts.into_iter().map(T::from_stmt)); + new.extend(v.stmts.into_iter().map(T::from)); } - _ => new.push(T::from_stmt(v)), + _ => new.push(T::from(v)), }, Err(v) => new.push(v), }); @@ -475,10 +479,11 @@ impl Pure<'_> { { report_change!("unused: Removing `return void` in end of a function"); self.changed = true; - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span: *span, expr: arg.take(), - }); + } + .into(); } } } @@ -513,10 +518,13 @@ impl Pure<'_> { Stmt::If(mut s) => { if let Value::Known(v) = s.test.cast_to_bool(&self.expr_ctx).1 { let mut var_ids = vec![]; - new.push(T::from_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: s.test.take(), - }))); + new.push(T::from( + ExprStmt { + span: DUMMY_SP, + expr: s.test.take(), + } + .into(), + )); if v { if let Some(alt) = s.alt.take() { @@ -532,7 +540,7 @@ impl Pure<'_> { .collect(); } if !var_ids.is_empty() { - new.push(T::from_stmt( + new.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -543,7 +551,7 @@ impl Pure<'_> { .into(), )) } - new.push(T::from_stmt(*s.cons.take())); + new.push(T::from(*s.cons.take())); } else { var_ids = s .cons @@ -557,7 +565,7 @@ impl Pure<'_> { }) .collect(); if !var_ids.is_empty() { - new.push(T::from_stmt( + new.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -569,14 +577,14 @@ impl Pure<'_> { )) } if let Some(alt) = s.alt.take() { - new.push(T::from_stmt(*alt)); + new.push(T::from(*alt)); } } } else { - new.push(T::from_stmt(Stmt::If(s))); + new.push(T::from(s.into())); } } - _ => new.push(T::from_stmt(stmt)), + _ => new.push(T::from(stmt)), }, Err(stmt) => new.push(stmt), }); 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 886389c0720c..56d527c65f91 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/if_return.rs @@ -114,14 +114,17 @@ impl Pure<'_> { s.cons = if cons.len() == 1 && is_fine_for_if_cons(&cons[0]) { Box::new(cons.into_iter().next().unwrap()) } else { - Box::new(Stmt::Block(BlockStmt { - span: DUMMY_SP, - stmts: cons, - ..Default::default() - })) + Box::new( + BlockStmt { + span: DUMMY_SP, + stmts: cons, + ..Default::default() + } + .into(), + ) }; - new.push(Stmt::If(s)) + new.push(s.into()) } _ => { unreachable!() @@ -150,11 +153,14 @@ impl Pure<'_> { match &mut **alt_of_alt { Stmt::Block(..) => {} Stmt::Expr(..) => { - *alt_of_alt = Box::new(Stmt::Block(BlockStmt { - span: DUMMY_SP, - stmts: vec![*alt_of_alt.take()], - ..Default::default() - })); + *alt_of_alt = Box::new( + BlockStmt { + span: DUMMY_SP, + stmts: vec![*alt_of_alt.take()], + ..Default::default() + } + .into(), + ); } _ => { return; @@ -168,12 +174,13 @@ impl Pure<'_> { Stmt::Block(alt_of_alt) => { prepend_stmt( &mut alt_of_alt.stmts, - Stmt::If(IfStmt { + IfStmt { span: *span_of_alt, test: test_of_alt.take(), cons: cons_of_alt.take(), alt: None, - }), + } + .into(), ); } diff --git a/crates/swc_ecma_minifier/src/compress/pure/loops.rs b/crates/swc_ecma_minifier/src/compress/pure/loops.rs index 11e4924e0498..8b7ef1f99a27 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/loops.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/loops.rs @@ -17,13 +17,14 @@ impl Pure<'_> { Stmt::While(stmt) => { self.changed = true; report_change!("loops: Converting a while loop to a for loop"); - *s = Stmt::For(ForStmt { + *s = ForStmt { span: stmt.span, init: None, test: Some(stmt.test.take()), update: None, body: stmt.body.take(), - }); + } + .into(); } Stmt::DoWhile(stmt) => { let val = stmt.test.as_pure_bool(&self.expr_ctx); @@ -31,13 +32,14 @@ impl Pure<'_> { self.changed = true; report_change!("loops: Converting an always-true do-while loop to a for loop"); - *s = Stmt::For(ForStmt { + *s = ForStmt { span: stmt.span, init: None, test: Some(stmt.test.take()), update: None, body: stmt.body.take(), - }); + } + .into(); } } _ => {} diff --git a/crates/swc_ecma_minifier/src/compress/pure/misc.rs b/crates/swc_ecma_minifier/src/compress/pure/misc.rs index 958589a00de7..ddea65eafd31 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/misc.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/misc.rs @@ -828,10 +828,10 @@ impl Pure<'_> { let span = ret.span; match ret.arg.take() { Some(arg) => { - *s = Stmt::Expr(ExprStmt { span, expr: arg }); + *s = ExprStmt { span, expr: arg }.into(); } None => { - *s = Stmt::Empty(EmptyStmt { span }); + *s = EmptyStmt { span }.into(); } } diff --git a/crates/swc_ecma_minifier/src/compress/pure/mod.rs b/crates/swc_ecma_minifier/src/compress/pure/mod.rs index 73c8229c208e..9050eeccd22f 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/mod.rs @@ -891,7 +891,7 @@ impl VisitMut for Pure<'_> { match s { Stmt::Expr(ExprStmt { expr, .. }) if expr.is_invalid() => { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } _ => {} @@ -911,7 +911,7 @@ impl VisitMut for Pure<'_> { if self.options.drop_debugger { if let Stmt::Debugger(..) = s { self.changed = true; - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); report_change!("drop_debugger: Dropped a debugger statement"); return; } @@ -935,7 +935,7 @@ impl VisitMut for Pure<'_> { if let Stmt::Expr(es) = s { if es.expr.is_invalid() { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } } diff --git a/crates/swc_ecma_minifier/src/compress/pure/vars.rs b/crates/swc_ecma_minifier/src/compress/pure/vars.rs index 14c8b9382ffc..5f07bf785675 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/vars.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/vars.rs @@ -69,7 +69,7 @@ impl Pure<'_> { match stmt.try_into_stmt() { Ok(stmt) => { if is_directive(&stmt) { - return new.push(T::from_stmt(stmt)); + return new.push(T::from(stmt)); } match stmt { @@ -78,8 +78,8 @@ impl Pure<'_> { v.decls.extend(var.decls); } _ => { - if let Some(s) = cur.take().map(|c| Stmt::Decl(Decl::Var(c))) { - new.push(T::from_stmt(s)); + if let Some(s) = cur.take().map(|c| c.into()) { + new.push(T::from(s)); } cur = Some(var); } @@ -100,13 +100,13 @@ impl Pure<'_> { cur.decls.append(&mut var.decls); var.decls = cur.decls.take(); - new.push(T::from_stmt(Stmt::For(stmt))); + new.push(T::from(stmt.into())); } _ => { if let Some(s) = cur.take() { - new.push(T::from_stmt(Stmt::Decl(Decl::Var(s)))); + new.push(T::from(s.into())); } - new.push(T::from_stmt(Stmt::For(stmt))); + new.push(T::from(stmt.into())); } } } @@ -120,26 +120,26 @@ impl Pure<'_> { .and_then(|v| if v.decls.is_empty() { None } else { Some(v) }) .map(VarDeclOrExpr::VarDecl); - new.push(T::from_stmt(Stmt::For(stmt))); + new.push(T::from(stmt.into())); } _ => { if let Some(s) = cur.take() { - new.push(T::from_stmt(Stmt::Decl(Decl::Var(s)))); + new.push(T::from(s.into())); } - new.push(T::from_stmt(Stmt::For(stmt))); + new.push(T::from(stmt.into())); } }, _ => { if let Some(s) = cur.take() { - new.push(T::from_stmt(Stmt::Decl(Decl::Var(s)))); + new.push(T::from(s.into())); } - new.push(T::from_stmt(stmt)); + new.push(T::from(stmt)); } } } Err(item) => { if let Some(s) = cur.take() { - new.push(T::from_stmt(Stmt::Decl(Decl::Var(s)))); + new.push(T::from(s.into())); } new.push(item); } @@ -147,7 +147,7 @@ impl Pure<'_> { }); if let Some(s) = cur.take() { - new.push(T::from_stmt(Stmt::Decl(Decl::Var(s)))); + new.push(T::from(s.into())); } drop_invalid_stmts(&mut new); @@ -273,7 +273,7 @@ impl Pure<'_> { _ => { prepend_stmt( stmts, - T::from_stmt( + T::from( VarDecl { span: DUMMY_SP, kind: target, diff --git a/crates/swc_ecma_minifier/src/compress/util/mod.rs b/crates/swc_ecma_minifier/src/compress/util/mod.rs index abaa49ea2514..4697290bb7d2 100644 --- a/crates/swc_ecma_minifier/src/compress/util/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/util/mod.rs @@ -658,7 +658,7 @@ impl UnreachableHandler { let mut v = Self::default(); s.visit_mut_with(&mut v); if v.vars.is_empty() { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); } else { *s = VarDecl { span: DUMMY_SP, diff --git a/crates/swc_ecma_minifier/src/pass/merge_exports.rs b/crates/swc_ecma_minifier/src/pass/merge_exports.rs index 7e9b0bf5c59d..1701435e2e53 100644 --- a/crates/swc_ecma_minifier/src/pass/merge_exports.rs +++ b/crates/swc_ecma_minifier/src/pass/merge_exports.rs @@ -42,28 +42,30 @@ impl VisitMut for Merger { }); if !self.specifiers.is_empty() { - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + stmts.push( NamedExport { src: None, specifiers: self.specifiers.take(), span: DUMMY_SP, type_only: Default::default(), with: Default::default(), - }, - ))); + } + .into(), + ); } // export {}, to preserve module semantics if was_module && stmts.iter().all(|s| matches!(s, ModuleItem::Stmt(..))) { - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + stmts.push( NamedExport { src: None, specifiers: Default::default(), span: DUMMY_SP, type_only: Default::default(), with: Default::default(), - }, - ))); + } + .into(), + ); } } diff --git a/crates/swc_ecma_minifier/src/pass/postcompress.rs b/crates/swc_ecma_minifier/src/pass/postcompress.rs index 16643890c480..7f2941df753f 100644 --- a/crates/swc_ecma_minifier/src/pass/postcompress.rs +++ b/crates/swc_ecma_minifier/src/pass/postcompress.rs @@ -56,31 +56,35 @@ impl VisitMut for PostcompressOptimizer<'_> { Expr::Fn(f) => { if f.ident.is_some() { if self.options.top_level() { - *m = ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { + *m = ExportDefaultDecl { span: e.span, decl: DefaultDecl::Fn(f.take()), - }) + } + .into() } } else { - *m = ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { + *m = ExportDefaultDecl { span: e.span, decl: DefaultDecl::Fn(f.take()), - }) + } + .into() } } Expr::Class(c) => { if c.ident.is_some() { if self.options.top_level() { - *m = ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { + *m = ExportDefaultDecl { span: e.span, decl: DefaultDecl::Class(c.take()), - }) + } + .into() } } else { - *m = ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { + *m = ExportDefaultDecl { span: e.span, decl: DefaultDecl::Class(c.take()), - }) + } + .into() } } _ => (), diff --git a/crates/swc_ecma_minifier/src/util/mod.rs b/crates/swc_ecma_minifier/src/util/mod.rs index 75c183b98a05..dbe10aeb0b44 100644 --- a/crates/swc_ecma_minifier/src/util/mod.rs +++ b/crates/swc_ecma_minifier/src/util/mod.rs @@ -33,8 +33,8 @@ pub trait ModuleItemExt: fn into_module_item(self) -> ModuleItem { match self.into_module_decl() { - Ok(v) => ModuleItem::ModuleDecl(v), - Err(v) => ModuleItem::Stmt(v), + Ok(v) => v.into(), + Err(v) => v.into(), } } 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 e0db38b63f11..16bb7a6bc752 100644 --- a/crates/swc_ecma_parser/src/parser/class_and_fn.rs +++ b/crates/swc_ecma_parser/src/parser/class_and_fn.rs @@ -1620,21 +1620,23 @@ impl OutputType for Decl { ) -> Result { let ident = ident.ok_or(SyntaxError::ExpectedIdent)?; - Ok(Decl::Fn(FnDecl { + Ok(FnDecl { declare: false, ident, function, - })) + } + .into()) } fn finish_class(_: Span, ident: Option, class: Box) -> Result { let ident = ident.ok_or(SyntaxError::ExpectedIdent)?; - Ok(Decl::Class(ClassDecl { + Ok(ClassDecl { declare: false, ident, class, - })) + } + .into()) } } diff --git a/crates/swc_ecma_parser/src/parser/stmt.rs b/crates/swc_ecma_parser/src/parser/stmt.rs index 29f1dc406fff..63ab239de0df 100644 --- a/crates/swc_ecma_parser/src/parser/stmt.rs +++ b/crates/swc_ecma_parser/src/parser/stmt.rs @@ -133,7 +133,7 @@ impl<'a, I: Tokens> Parser { let v = self.parse_using_decl(start, true)?; if let Some(v) = v { - return Ok(Stmt::Decl(Decl::Using(v))); + return Ok(v.into()); } } @@ -144,7 +144,7 @@ impl<'a, I: Tokens> Parser { eat!(self, ';'); let span = span!(self, start); - return Ok(Stmt::Expr(ExprStmt { span, expr })); + return Ok(ExprStmt { span, expr }.into()); } let is_typescript = self.input.syntax().typescript(); @@ -164,7 +164,7 @@ impl<'a, I: Tokens> Parser { assert_and_bump!(self, "await"); let v = self.parse_using_decl(start, true)?; if let Some(v) = v { - return Ok(Stmt::Decl(Decl::Using(v))); + return Ok(v.into()); } } } @@ -198,18 +198,19 @@ impl<'a, I: Tokens> Parser { } return Ok(if is_break { - Stmt::Break(BreakStmt { span, label }) + BreakStmt { span, label }.into() } else { - Stmt::Continue(ContinueStmt { span, label }) + ContinueStmt { span, label }.into() }); } tok!("debugger") => { bump!(self); expect!(self, ';'); - return Ok(Stmt::Debugger(DebuggerStmt { + return Ok(DebuggerStmt { span: span!(self, start), - })); + } + .into()); } tok!("do") => { @@ -261,10 +262,11 @@ impl<'a, I: Tokens> Parser { let _ = self.parse_catch_clause(); let _ = self.parse_finally_block(); - return Ok(Stmt::Expr(ExprStmt { + return Ok(ExprStmt { span, expr: Invalid { span }.into(), - })); + } + .into()); } // Error recovery @@ -274,10 +276,11 @@ impl<'a, I: Tokens> Parser { let _ = self.parse_finally_block(); - return Ok(Stmt::Expr(ExprStmt { + return Ok(ExprStmt { span, expr: Invalid { span }.into(), - })); + } + .into()); } tok!("try") => { @@ -294,12 +297,12 @@ impl<'a, I: Tokens> Parser { tok!("var") => { let v = self.parse_var_stmt(false)?; - return Ok(Stmt::Decl(Decl::Var(v))); + return Ok(v.into()); } tok!("const") if include_decl => { let v = self.parse_var_stmt(false)?; - return Ok(Stmt::Decl(Decl::Var(v))); + return Ok(v.into()); } // 'let' can start an identifier reference. @@ -312,14 +315,14 @@ impl<'a, I: Tokens> Parser { if is_keyword { let v = self.parse_var_stmt(false)?; - return Ok(Stmt::Decl(Decl::Var(v))); + return Ok(v.into()); } } tok!("using") if include_decl => { let v = self.parse_using_decl(start, false)?; if let Some(v) = v { - return Ok(Stmt::Decl(Decl::Using(v))); + return Ok(v.into()); } } @@ -330,9 +333,7 @@ impl<'a, I: Tokens> Parser { { let start = self.input.cur_pos(); bump!(self); - return Ok(Stmt::Decl(Decl::TsInterface( - self.parse_ts_interface_decl(start)?, - ))); + return Ok(self.parse_ts_interface_decl(start)?.into()); } } @@ -343,9 +344,7 @@ impl<'a, I: Tokens> Parser { { let start = self.input.cur_pos(); bump!(self); - return Ok(Stmt::Decl(Decl::TsTypeAlias( - self.parse_ts_type_alias_decl(start)?, - ))); + return Ok(self.parse_ts_type_alias_decl(start)?.into()); } } @@ -356,9 +355,7 @@ impl<'a, I: Tokens> Parser { { let start = self.input.cur_pos(); bump!(self); - return Ok(Stmt::Decl(Decl::TsEnum( - self.parse_ts_enum_decl(start, false)?, - ))); + return Ok(self.parse_ts_enum_decl(start, false)?.into()); } } @@ -374,9 +371,10 @@ impl<'a, I: Tokens> Parser { } if eat_exact!(self, ';') { - return Ok(Stmt::Empty(EmptyStmt { + return Ok(EmptyStmt { span: span!(self, start), - })); + } + .into()); } // Handle async function foo() {} @@ -412,15 +410,16 @@ impl<'a, I: Tokens> Parser { eat!(self, ';'); - return Ok(Stmt::Expr(ExprStmt { + return Ok(ExprStmt { span: span!(self, start), expr, - })); + } + .into()); } if self.input.syntax().typescript() { if let Some(decl) = self.parse_ts_expr_stmt(decorators, ident.clone())? { - return Ok(Stmt::Decl(decl)); + return Ok(decl.into()); } } } @@ -452,10 +451,11 @@ impl<'a, I: Tokens> Parser { } if eat!(self, ';') { - Ok(Stmt::Expr(ExprStmt { + Ok(ExprStmt { span: span!(self, start), expr, - })) + } + .into()) } else { if let Token::BinOp(..) = *cur!(self, false)? { self.emit_err(self.input.cur_span(), SyntaxError::TS1005); @@ -567,7 +567,7 @@ impl<'a, I: Tokens> Parser { match &mut cur { Some(cur) => { - self.adjust_if_else_clause(cur, Box::new(Stmt::If(alt))); + self.adjust_if_else_clause(cur, Box::new(alt.into())); } _ => { cur = Some(alt); @@ -580,7 +580,7 @@ impl<'a, I: Tokens> Parser { if let Some(last) = last { self.adjust_if_else_clause(&mut cur, Box::new(last)); } - Some(Stmt::If(cur)) + Some(cur.into()) } _ => last, } @@ -608,10 +608,11 @@ impl<'a, I: Tokens> Parser { p.include_in_expr(true).parse_expr().map(Some)? }; expect!(p, ';'); - Ok(Stmt::Return(ReturnStmt { + Ok(ReturnStmt { span: span!(p, start), arg, - })) + } + .into()) }); if !self.ctx().in_function && !self.input.syntax().allow_return_outside_function() { @@ -674,11 +675,12 @@ impl<'a, I: Tokens> Parser { // eof or rbrace expect!(self, '}'); - Ok(Stmt::Switch(SwitchStmt { + Ok(SwitchStmt { span: span!(self, switch_start), discriminant, cases, - })) + } + .into()) } fn parse_throw_stmt(&mut self) -> PResult { @@ -695,7 +697,7 @@ impl<'a, I: Tokens> Parser { expect!(self, ';'); let span = span!(self, start); - Ok(Stmt::Throw(ThrowStmt { span, arg })) + Ok(ThrowStmt { span, arg }.into()) } fn parse_try_stmt(&mut self) -> PResult { @@ -713,12 +715,13 @@ impl<'a, I: Tokens> Parser { } let span = span!(self, start); - Ok(Stmt::Try(Box::new(TryStmt { + Ok(TryStmt { span, block, handler, finalizer, - }))) + } + .into()) } fn parse_catch_clause(&mut self) -> PResult> { @@ -1059,7 +1062,7 @@ impl<'a, I: Tokens> Parser { let span = span!(self, start); - Ok(Stmt::DoWhile(DoWhileStmt { span, test, body })) + Ok(DoWhileStmt { span, test, body }.into()) } fn parse_while_stmt(&mut self) -> PResult { @@ -1079,7 +1082,7 @@ impl<'a, I: Tokens> Parser { let body = self.with_ctx(ctx).parse_stmt(false).map(Box::new)?; let span = span!(self, start); - Ok(Stmt::While(WhileStmt { span, test, body })) + Ok(WhileStmt { span, test, body }.into()) } fn parse_with_stmt(&mut self) -> PResult { @@ -1108,7 +1111,7 @@ impl<'a, I: Tokens> Parser { let body = self.with_ctx(ctx).parse_stmt(false).map(Box::new)?; let span = span!(self, start); - Ok(Stmt::With(WithStmt { span, obj, body })) + Ok(WithStmt { span, obj, body }.into()) } pub(super) fn parse_block(&mut self, allow_directives: bool) -> PResult { @@ -1173,11 +1176,12 @@ impl<'a, I: Tokens> Parser { } } - Ok(Stmt::Labeled(LabeledStmt { + Ok(LabeledStmt { span: span!(p, start), label: l, body, - })) + } + .into()) }) } @@ -1213,33 +1217,36 @@ impl<'a, I: Tokens> Parser { syntax_error!(self, await_token, SyntaxError::AwaitForStmt); } - Stmt::For(ForStmt { + ForStmt { span, init, test, update, body, - }) + } + .into() } TempForHead::ForIn { left, right } => { if let Some(await_token) = await_token { syntax_error!(self, await_token, SyntaxError::AwaitForStmt); } - Stmt::ForIn(ForInStmt { + ForInStmt { span, left, right, body, - }) + } + .into() } - TempForHead::ForOf { left, right } => Stmt::ForOf(ForOfStmt { + TempForHead::ForOf { left, right } => ForOfStmt { span, is_await: await_token.is_some(), left, right, body, - }), + } + .into(), }) } diff --git a/crates/swc_ecma_parser/src/parser/stmt/module_item.rs b/crates/swc_ecma_parser/src/parser/stmt/module_item.rs index bf249256141b..056b55eb8de6 100644 --- a/crates/swc_ecma_parser/src/parser/stmt/module_item.rs +++ b/crates/swc_ecma_parser/src/parser/stmt/module_item.rs @@ -9,10 +9,10 @@ impl Parser { eat!(self, ';'); - return Ok(Stmt::Expr(ExprStmt { + return Ok(ExprStmt { span: span!(self, start), expr, - }) + } .into()); } @@ -21,10 +21,10 @@ impl Parser { eat!(self, ';'); - return Ok(Stmt::Expr(ExprStmt { + return Ok(ExprStmt { span: span!(self, start), expr, - }) + } .into()); } @@ -66,14 +66,15 @@ impl Parser { None }; expect!(self, ';'); - return Ok(ModuleItem::from(ModuleDecl::Import(ImportDecl { + return Ok(ImportDecl { span: span!(self, start), src, specifiers: vec![], type_only: false, with, phase: Default::default(), - }))); + } + .into()); } let mut type_only = false; @@ -192,14 +193,15 @@ impl Parser { expect!(self, ';'); - Ok(ModuleItem::from(ModuleDecl::Import(ImportDecl { + Ok(ImportDecl { span: span!(self, start), specifiers, src, type_only, with, phase, - }))) + } + .into()) } /// Parse `foo`, `foo2 as bar` in `import { foo, foo2 as bar }` @@ -367,10 +369,11 @@ impl Parser { if declare { // TODO: Remove if let Some(decl) = self.try_parse_ts_declare(after_export_start, decorators.clone())? { - return Ok(ModuleDecl::ExportDecl(ExportDecl { + return Ok(ExportDecl { span: span!(self, start), decl, - })); + } + .into()); } } @@ -381,10 +384,11 @@ impl Parser { }; // TODO: remove clone if let Some(decl) = self.try_parse_ts_export_decl(decorators.clone(), sym) { - return Ok(ModuleDecl::ExportDecl(ExportDecl { + return Ok(ExportDecl { span: span!(self, start), decl, - })); + } + .into()); } } @@ -488,16 +492,16 @@ impl Parser { if is!(self, "class") { let class_start = cur_pos!(self); let decl = self.parse_default_class(start, class_start, decorators, false)?; - return Ok(ModuleDecl::ExportDefaultDecl(decl)); + return Ok(decl.into()); } else if is!(self, "async") && peeked_is!(self, "function") && !self.input.has_linebreak_between_cur_and_peeked() { let decl = self.parse_default_async_fn(start, decorators)?; - return Ok(ModuleDecl::ExportDefaultDecl(decl)); + return Ok(decl.into()); } else if is!(self, "function") { let decl = self.parse_default_fn(start, decorators)?; - return Ok(ModuleDecl::ExportDefaultDecl(decl)); + return Ok(decl.into()); } else if self.input.syntax().export_default_from() && (is!(self, "from") || (is!(self, ',') && (peeked_is!(self, '{') || peeked_is!(self, '*')))) @@ -506,10 +510,11 @@ impl Parser { } else { let expr = self.include_in_expr(true).parse_assignment_expr()?; expect!(self, ';'); - return Ok(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr { + return Ok(ExportDefaultExpr { span: span!(self, start), expr, - })); + } + .into()); } } @@ -548,10 +553,11 @@ impl Parser { .parse_ts_enum_decl(enum_start, /* is_const */ true) .map(Decl::from) .map(|decl| { - ModuleDecl::ExportDecl(ExportDecl { + ExportDecl { span: span!(self, start), decl, - }) + } + .into() }); } else if !type_only && (is!(self, "var") @@ -596,12 +602,13 @@ impl Parser { // improve error message for `export * from foo` let (src, with) = self.parse_from_clause_and_semi()?; - return Ok(ModuleDecl::ExportAll(ExportAll { + return Ok(ExportAll { span: span!(self, start), src, type_only, with, - })); + } + .into()); } let mut specifiers = vec![]; @@ -643,13 +650,14 @@ impl Parser { if has_default || has_ns { if is!(self, "from") { let (src, with) = self.parse_from_clause_and_semi()?; - return Ok(ModuleDecl::ExportNamed(NamedExport { + return Ok(NamedExport { span: span!(self, start), specifiers, src: Some(src), type_only, with, - })); + } + .into()); } else if !self.input.syntax().export_default_from() { // emit error expect!(self, "from"); @@ -716,19 +724,21 @@ impl Parser { Some(v) => (Some(v.0), v.1), None => (None, None), }; - return Ok(ModuleDecl::ExportNamed(NamedExport { + return Ok(NamedExport { span: span!(self, start), specifiers, src, type_only, with, - })); + } + .into()); }; - Ok(ModuleDecl::ExportDecl(ExportDecl { + Ok(ExportDecl { span: span!(self, start), decl, - })) + } + .into()) } fn parse_named_export_specifier(&mut self, type_only: bool) -> PResult { diff --git a/crates/swc_ecma_parser/src/parser/typescript.rs b/crates/swc_ecma_parser/src/parser/typescript.rs index 48d760483c7d..714ed00d1044 100644 --- a/crates/swc_ecma_parser/src/parser/typescript.rs +++ b/crates/swc_ecma_parser/src/parser/typescript.rs @@ -2388,7 +2388,7 @@ impl Parser { return p .parse_fn_decl(decorators) .map(|decl| match decl { - Decl::Fn(f) => Decl::Fn(FnDecl { + Decl::Fn(f) => FnDecl { declare: true, function: Box::new(Function { span: Span { @@ -2398,7 +2398,8 @@ impl Parser { ..*f.function }), ..f - }), + } + .into(), _ => decl, }) .map(Some); @@ -2408,7 +2409,7 @@ impl Parser { return p .parse_class_decl(start, start, decorators, false) .map(|decl| match decl { - Decl::Class(c) => Decl::Class(ClassDecl { + Decl::Class(c) => ClassDecl { declare: true, class: Box::new(Class { span: Span { @@ -2418,7 +2419,8 @@ impl Parser { ..*c.class }), ..c - }), + } + .into(), _ => decl, }) .map(Some); @@ -2839,21 +2841,21 @@ mod tests { span: DUMMY_SP, shebang: None, body: { - let first = - ModuleItem::Stmt(Stmt::Decl(Decl::TsTypeAlias(Box::new(TsTypeAliasDecl { + let first = TsTypeAliasDecl { + span: DUMMY_SP, + declare: false, + id: Ident::new_no_ctxt("test".into(), DUMMY_SP), + type_params: None, + type_ann: Box::new(TsType::TsLitType(TsLitType { span: DUMMY_SP, - declare: false, - id: Ident::new_no_ctxt("test".into(), DUMMY_SP), - type_params: None, - type_ann: Box::new(TsType::TsLitType(TsLitType { + lit: TsLit::Number(Number { span: DUMMY_SP, - lit: TsLit::Number(Number { - span: DUMMY_SP, - value: -1.0, - raw: Some("-1".into()), - }), - })), - })))); + value: -1.0, + raw: Some("-1".into()), + }), + })), + } + .into(); vec![first] }, }; @@ -2873,7 +2875,7 @@ mod tests { span: DUMMY_SP, shebang: None, body: { - let second = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + let second = VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: false, @@ -2892,7 +2894,8 @@ mod tests { definite: false, }], ..Default::default() - })))); + } + .into(); vec![second] }, }; diff --git a/crates/swc_ecma_preset_env/src/lib.rs b/crates/swc_ecma_preset_env/src/lib.rs index 0946b638acc1..94502b06a016 100644 --- a/crates/swc_ecma_preset_env/src/lib.rs +++ b/crates/swc_ecma_preset_env/src/lib.rs @@ -461,7 +461,7 @@ impl VisitMut for Polyfills { prepend_stmts( &mut m.body, v.into_iter().map(|src| { - ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { + ImportDecl { span, specifiers: vec![], src: Str { @@ -473,14 +473,15 @@ impl VisitMut for Polyfills { type_only: false, with: None, phase: Default::default(), - })) + } + .into() }), ); } else { prepend_stmts( &mut m.body, required.into_iter().map(|src| { - ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { + ImportDecl { span, specifiers: vec![], src: Str { @@ -492,7 +493,8 @@ impl VisitMut for Polyfills { type_only: false, with: None, phase: Default::default(), - })) + } + .into() }), ); } @@ -509,7 +511,7 @@ impl VisitMut for Polyfills { prepend_stmts( &mut m.body, v.into_iter().map(|src| { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: CallExpr { span, @@ -529,14 +531,15 @@ impl VisitMut for Polyfills { ..Default::default() } .into(), - }) + } + .into() }), ); } else { prepend_stmts( &mut m.body, required.into_iter().map(|src| { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: CallExpr { span, @@ -555,7 +558,8 @@ impl VisitMut for Polyfills { ..Default::default() } .into(), - }) + } + .into() }), ); } diff --git a/crates/swc_ecma_transforms_base/src/fixer.rs b/crates/swc_ecma_transforms_base/src/fixer.rs index ed0bec5a5cd8..265e64e6c8b2 100644 --- a/crates/swc_ecma_transforms_base/src/fixer.rs +++ b/crates/swc_ecma_transforms_base/src/fixer.rs @@ -522,11 +522,14 @@ impl VisitMut for Fixer<'_> { node.visit_mut_children_with(self); if will_eat_else_token(&node.cons) { - node.cons = Box::new(Stmt::Block(BlockStmt { - span: node.cons.span(), - stmts: vec![*node.cons.take()], - ..Default::default() - })); + node.cons = Box::new( + BlockStmt { + span: node.cons.span(), + stmts: vec![*node.cons.take()], + ..Default::default() + } + .into(), + ); } } diff --git a/crates/swc_ecma_transforms_base/src/helpers/mod.rs b/crates/swc_ecma_transforms_base/src/helpers/mod.rs index 4a2e1398646e..cc59f2ad26a6 100644 --- a/crates/swc_ecma_transforms_base/src/helpers/mod.rs +++ b/crates/swc_ecma_transforms_base/src/helpers/mod.rs @@ -450,22 +450,17 @@ impl InjectHelpers { ..Default::default() }; let ctxt = SyntaxContext::empty().apply_mark(mark); - let decl = Decl::Var( - VarDecl { - kind: VarDeclKind::Var, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: Pat::Ident( - Ident::new(format!("_{}", name).into(), DUMMY_SP, ctxt).into(), - ), - init: Some(c.into()), - definite: false, - }], - ..Default::default() - } - .into(), - ); - Stmt::Decl(decl) + VarDecl { + kind: VarDeclKind::Var, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: Pat::Ident(Ident::new(format!("_{}", name).into(), DUMMY_SP, ctxt).into()), + init: Some(c.into()), + definite: false, + }], + ..Default::default() + } + .into() } fn map_helper_ref_ident(&mut self, ref_ident: &Ident) -> Option { diff --git a/crates/swc_ecma_transforms_base/src/rename/ops.rs b/crates/swc_ecma_transforms_base/src/rename/ops.rs index 80158c4635a3..4a0b967df148 100644 --- a/crates/swc_ecma_transforms_base/src/rename/ops.rs +++ b/crates/swc_ecma_transforms_base/src/rename/ops.rs @@ -277,25 +277,28 @@ where let orig_ident = ident.clone(); match self.rename_ident(&mut ident) { Ok(..) => { - *item = ModuleItem::Stmt(Stmt::Decl(Decl::Class(ClassDecl { + *item = ClassDecl { ident: ident.clone(), class: class.take(), declare: *declare, - }))); + } + .into(); export!( ModuleExportName::Ident(orig_ident), ModuleExportName::Ident(ident.take()) ); } Err(..) => { - *item = ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { + *item = ExportDecl { span: *span, - decl: Decl::Class(ClassDecl { + decl: ClassDecl { ident: ident.take(), class: class.take(), declare: *declare, - }), - })) + } + .into(), + } + .into() } } } @@ -315,25 +318,28 @@ where let orig_ident = ident.clone(); match self.rename_ident(&mut ident) { Ok(..) => { - *item = ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl { + *item = FnDecl { ident: ident.clone(), function, declare: *declare, - }))); + } + .into(); export!( ModuleExportName::Ident(orig_ident), ModuleExportName::Ident(ident) ); } Err(..) => { - *item = ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { + *item = ExportDecl { span: *span, - decl: Decl::Fn(FnDecl { + decl: FnDecl { ident, function, declare: *declare, - }), - })) + } + .into(), + } + .into() } } } @@ -354,29 +360,32 @@ where }); if renamed.is_empty() { - *item = ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { + *item = ExportDecl { span, - decl: Decl::Var(Box::new(VarDecl { + decl: VarDecl { decls, ..*var.take() - })), - })); + } + .into(), + } + .into(); return; } - *item = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + *item = VarDecl { decls, ..*var.take() - })))); - self.extra - .push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( - NamedExport { - span, - specifiers: renamed, - src: None, - type_only: false, - with: None, - }, - ))); + } + .into(); + self.extra.push( + NamedExport { + span, + specifiers: renamed, + src: None, + type_only: false, + with: None, + } + .into(), + ); } _ => { item.visit_mut_children_with(self); diff --git a/crates/swc_ecma_transforms_base/tests/fixer_test262.rs b/crates/swc_ecma_transforms_base/tests/fixer_test262.rs index 9729d9069f8d..0c57f9783732 100644 --- a/crates/swc_ecma_transforms_base/tests/fixer_test262.rs +++ b/crates/swc_ecma_transforms_base/tests/fixer_test262.rs @@ -361,8 +361,8 @@ impl Fold for Normalizer { match stmt { Stmt::Expr(ExprStmt { span, expr }) => match *expr { - Expr::Paren(ParenExpr { expr, .. }) => Stmt::Expr(ExprStmt { span, expr }), - _ => Stmt::Expr(ExprStmt { span, expr }), + Expr::Paren(ParenExpr { expr, .. }) => ExprStmt { span, expr }.into(), + _ => ExprStmt { span, expr }.into(), }, _ => stmt, } diff --git a/crates/swc_ecma_transforms_module/src/common_js.rs b/crates/swc_ecma_transforms_module/src/common_js.rs index f8a6ccde113e..8e5c83022c3b 100644 --- a/crates/swc_ecma_transforms_module/src/common_js.rs +++ b/crates/swc_ecma_transforms_module/src/common_js.rs @@ -348,17 +348,11 @@ where if decl_mod_ident { let stmt = if is_lazy { - Stmt::Decl(Decl::Fn(lazy_require( - import_expr, - mod_ident, - self.const_var_kind, - ))) + lazy_require(import_expr, mod_ident, self.const_var_kind).into() } else { - Stmt::Decl( - import_expr - .into_var_decl(self.const_var_kind, mod_ident.into()) - .into(), - ) + import_expr + .into_var_decl(self.const_var_kind, mod_ident.into()) + .into() }; stmts.push(stmt); @@ -447,7 +441,7 @@ where let mut var_decl = require.into_var_decl(self.const_var_kind, id.into()); var_decl.span = span; - Stmt::Decl(var_decl.into()) + var_decl.into() } .into() } diff --git a/crates/swc_ecma_transforms_module/src/module_decl_strip.rs b/crates/swc_ecma_transforms_module/src/module_decl_strip.rs index 096c59895ef3..6e7ab4648067 100644 --- a/crates/swc_ecma_transforms_module/src/module_decl_strip.rs +++ b/crates/swc_ecma_transforms_module/src/module_decl_strip.rs @@ -70,23 +70,17 @@ impl VisitMut for ModuleDeclStrip { match module_decl { ModuleDecl::Import(..) => continue, ModuleDecl::ExportDecl(ExportDecl { decl, .. }) => { - list.push(Stmt::Decl(decl).into()); + list.push(decl.into()); } ModuleDecl::ExportNamed(..) => continue, ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { decl, .. }) => match decl { - DefaultDecl::Class(class_expr) => list.extend( - class_expr - .as_class_decl() - .map(|decl| Stmt::Decl(Decl::Class(decl))) - .map(From::from), - ), - DefaultDecl::Fn(fn_expr) => list.extend( - fn_expr - .as_fn_decl() - .map(|decl| Stmt::Decl(Decl::Fn(decl))) - .map(From::from), - ), + DefaultDecl::Class(class_expr) => { + list.extend(class_expr.as_class_decl().map(From::from)) + } + DefaultDecl::Fn(fn_expr) => { + list.extend(fn_expr.as_fn_decl().map(From::from)) + } DefaultDecl::TsInterfaceDecl(_) => continue, }, ModuleDecl::ExportDefaultExpr(..) => { @@ -271,12 +265,12 @@ impl VisitMut for ModuleDeclStrip { ExportItem::new((n.span, Default::default()), ident.clone()), ); - self.export_default = Some(Stmt::Decl( + self.export_default = Some( n.expr .take() .into_var_decl(self.const_var_kind, ident.into()) .into(), - )); + ); } /// ```javascript diff --git a/crates/swc_ecma_transforms_module/src/system_js.rs b/crates/swc_ecma_transforms_module/src/system_js.rs index 893c029a99d9..c773528777b9 100644 --- a/crates/swc_ecma_transforms_module/src/system_js.rs +++ b/crates/swc_ecma_transforms_module/src/system_js.rs @@ -284,55 +284,61 @@ impl SystemJs { } .into(), ); - meta.setter_fn_stmts.push(Stmt::ForIn(ForInStmt { - span: DUMMY_SP, - left: VarDecl { - kind: VarDeclKind::Var, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: key_ident.clone().into(), - init: None, - definite: false, - }], - ..Default::default() - } - .into(), - right: target.clone().into(), - - body: Box::new(Stmt::Block(BlockStmt { + meta.setter_fn_stmts.push( + ForInStmt { span: DUMMY_SP, - stmts: vec![Stmt::If(IfStmt { + left: VarDecl { + kind: VarDeclKind::Var, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: key_ident.clone().into(), + init: None, + definite: false, + }], + ..Default::default() + } + .into(), + right: target.clone().into(), + + body: Box::new(Stmt::Block(BlockStmt { span: DUMMY_SP, - test: Box::new(Expr::Bin(BinExpr { + stmts: vec![Stmt::If(IfStmt { span: DUMMY_SP, - op: op!("&&"), - left: Box::new( - key_ident - .clone() - .make_bin(op!("!=="), quote_str!("default")), - ), - right: Box::new( - key_ident - .clone() - .make_bin(op!("!=="), quote_str!("__esModule")), - ), - })), - cons: Box::new(Stmt::Block(BlockStmt { - stmts: vec![AssignExpr { + test: Box::new(Expr::Bin(BinExpr { span: DUMMY_SP, - op: op!("="), - left: export_obj.clone().computed_member(key_ident.clone()).into(), - right: target.computed_member(key_ident).into(), - } - .into_stmt()], - ..Default::default() - })), - alt: None, - })], + op: op!("&&"), + left: Box::new( + key_ident + .clone() + .make_bin(op!("!=="), quote_str!("default")), + ), + right: Box::new( + key_ident + .clone() + .make_bin(op!("!=="), quote_str!("__esModule")), + ), + })), + cons: Box::new(Stmt::Block(BlockStmt { + stmts: vec![AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: export_obj + .clone() + .computed_member(key_ident.clone()) + .into(), + right: target.computed_member(key_ident).into(), + } + .into_stmt()], + ..Default::default() + })), + alt: None, + })], - ..Default::default() - })), - })); + ..Default::default() + })), + } + .into(), + ); for (sym, value) in meta .export_names .drain(..) @@ -471,49 +477,54 @@ impl SystemJs { if let Some(expr) = self.hoist_var_decl(var_decl) { expr.into_stmt() } else { - Stmt::Empty(EmptyStmt { span: DUMMY_SP }) + EmptyStmt { span: DUMMY_SP }.into() } // } else { // return Stmt::Decl(Decl::Var(var_decl)); // } } else { - Stmt::Decl(decl) + decl.into() } } Stmt::For(for_stmt) => { if let Some(init) = for_stmt.init { if let VarDeclOrExpr::VarDecl(var_decl) = init { if var_decl.kind == VarDeclKind::Var { - Stmt::For(ForStmt { + ForStmt { init: self .hoist_var_decl(var_decl) .map(|expr| VarDeclOrExpr::Expr(Box::new(expr))), ..for_stmt - }) + } + .into() } else { - Stmt::For(ForStmt { + ForStmt { init: Some(VarDeclOrExpr::VarDecl(var_decl)), ..for_stmt - }) + } + .into() } } else { - Stmt::For(ForStmt { + ForStmt { init: Some(init), ..for_stmt - }) + } + .into() } } else { - Stmt::For(for_stmt) + for_stmt.into() } } - Stmt::ForIn(for_in_stmt) => Stmt::ForIn(ForInStmt { + Stmt::ForIn(for_in_stmt) => ForInStmt { left: self.hoist_for_var_decl(for_in_stmt.left), ..for_in_stmt - }), - Stmt::ForOf(for_of_stmt) => Stmt::ForOf(ForOfStmt { + } + .into(), + Stmt::ForOf(for_of_stmt) => ForOfStmt { left: self.hoist_for_var_decl(for_of_stmt.left), ..for_of_stmt - }), + } + .into(), _ => stmt, } } @@ -856,7 +867,7 @@ impl Fold for SystemJs { fn_decl.ident.to_id(), fn_decl.ident.sym.clone(), ); - before_body_stmts.push(Stmt::Decl(Decl::Fn(fn_decl))); + before_body_stmts.push(fn_decl.into()); } Decl::Var(var_decl) => { let mut decl = VarDecl { @@ -904,11 +915,14 @@ impl Fold for SystemJs { self.export_names.push("default".into()); self.export_values.push(ident.clone().into()); self.add_export_name(ident.to_id(), "default".into()); - before_body_stmts.push(Stmt::Decl(Decl::Fn(FnDecl { - ident: ident.clone(), - declare: false, - function: fn_expr.function, - }))); + before_body_stmts.push( + FnDecl { + ident: ident.clone(), + declare: false, + function: fn_expr.function, + } + .into(), + ); } else { self.export_names.push("default".into()); self.export_values.push(fn_expr.into()); @@ -953,9 +967,9 @@ impl Fold for SystemJs { ); } Decl::Fn(fn_decl) => { - before_body_stmts.push(Stmt::Decl(Decl::Fn(fn_decl))); + before_body_stmts.push(fn_decl.into()); } - _ => execute_stmts.push(Stmt::Decl(decl)), + _ => execute_stmts.push(decl.into()), }, _ => execute_stmts.push(stmt), }, diff --git a/crates/swc_ecma_transforms_optimization/src/const_modules.rs b/crates/swc_ecma_transforms_optimization/src/const_modules.rs index 27f5cc45b22c..663edda2fa5a 100644 --- a/crates/swc_ecma_transforms_optimization/src/const_modules.rs +++ b/crates/swc_ecma_transforms_optimization/src/const_modules.rs @@ -141,7 +141,7 @@ impl VisitMut for ConstModules { None } else { - Some(ModuleItem::ModuleDecl(ModuleDecl::Import(import))) + Some(import.into()) } } _ => Some(item), 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 c2c4072f0986..743de0be1a84 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs @@ -401,10 +401,13 @@ impl VisitMut for Remover { if let Stmt::If(IfStmt { alt: Some(..), .. }) = *cons { return IfStmt { test, - cons: Box::new(Stmt::Block(BlockStmt { - stmts: vec![*cons], - ..Default::default() - })), + cons: Box::new( + BlockStmt { + stmts: vec![*cons], + ..Default::default() + } + .into(), + ), alt, span, } @@ -420,19 +423,19 @@ impl VisitMut for Remover { // Preserve effect of the test if !p.is_pure() { if let Some(expr) = ignore_result(test, true, &self.expr_ctx) { - stmts.push(Stmt::Expr(ExprStmt { span, expr })) + stmts.push(ExprStmt { span, expr }.into()) } } if v { // Preserve variables if let Some(var) = alt.and_then(|alt| alt.extract_var_ids_as_var()) { - stmts.push(Stmt::Decl(Decl::Var(Box::new(var)))) + stmts.push(var.into()) } stmts.push(*cons); } else { if let Some(var) = cons.extract_var_ids_as_var() { - stmts.push(Stmt::Decl(Decl::Var(Box::new(var)))) + stmts.push(var.into()) } if let Some(alt) = alt { @@ -441,7 +444,7 @@ impl VisitMut for Remover { } if stmts.is_empty() { - return Stmt::Empty(EmptyStmt { span }); + return EmptyStmt { span }.into(); } if cfg!(feature = "debug") { @@ -450,11 +453,12 @@ impl VisitMut for Remover { self.changed = true; - let mut block = Stmt::Block(BlockStmt { + let mut block: Stmt = BlockStmt { span, stmts, ..Default::default() - }); + } + .into(); block.visit_mut_with(self); return block; } @@ -468,33 +472,34 @@ impl VisitMut for Remover { self.changed = true; return if let Some(expr) = ignore_result(test, true, &self.expr_ctx) { - Stmt::Expr(ExprStmt { span, expr }) + ExprStmt { span, expr }.into() } else { - Stmt::Empty(EmptyStmt { span }) + EmptyStmt { span }.into() }; } } - Stmt::If(IfStmt { + IfStmt { span, test, cons, alt, - }) + } + .into() } Stmt::Decl(Decl::Var(v)) if v.decls.is_empty() => { if cfg!(feature = "debug") { debug!("Dropping an empty var declaration"); } - Stmt::Empty(EmptyStmt { span: v.span }) + EmptyStmt { span: v.span }.into() } Stmt::Labeled(LabeledStmt { label, span, body, .. }) if body.is_empty() => { debug!("Dropping an empty label statement: `{}`", label); - Stmt::Empty(EmptyStmt { span }) + EmptyStmt { span }.into() } Stmt::Labeled(LabeledStmt { @@ -508,19 +513,19 @@ impl VisitMut for Remover { } => { debug!("Dropping a label statement with instant break: `{}`", label); - Stmt::Empty(EmptyStmt { span }) + EmptyStmt { span }.into() } // `1;` -> `;` Stmt::Expr(ExprStmt { span, expr, .. }) => { // Directives if let Expr::Lit(Lit::Str(..)) = &*expr { - return Stmt::Expr(ExprStmt { span, expr }); + return ExprStmt { span, expr }.into(); } match ignore_result(expr, false, &self.expr_ctx) { - Some(e) => Stmt::Expr(ExprStmt { span, expr: e }), - None => Stmt::Empty(EmptyStmt { span: DUMMY_SP }), + Some(e) => ExprStmt { span, expr: e }.into(), + None => EmptyStmt { span: DUMMY_SP }.into(), } } @@ -530,7 +535,7 @@ impl VisitMut for Remover { debug!("Drooping an empty block statement"); } - Stmt::Empty(EmptyStmt { span }) + EmptyStmt { span }.into() } else if stmts.len() == 1 && !is_block_scoped_stuff(&stmts[0]) && stmt_depth(&stmts[0]) <= 1 @@ -543,7 +548,7 @@ impl VisitMut for Remover { v.visit_mut_with(self); v } else { - Stmt::Block(BlockStmt { span, stmts, ctxt }) + BlockStmt { span, stmts, ctxt }.into() } } Stmt::Try(s) => { @@ -567,7 +572,7 @@ impl VisitMut for Remover { var.map(Box::new) .map(Decl::from) .map(Stmt::from) - .unwrap_or_else(|| Stmt::Empty(EmptyStmt { span })) + .unwrap_or_else(|| EmptyStmt { span }.into()) }; } @@ -578,15 +583,16 @@ impl VisitMut for Remover { debug!("Converting a try statement to a block statement"); } - return Stmt::Block(block); + return block.into(); } - Stmt::Try(Box::new(TryStmt { + TryStmt { span, block, handler, finalizer, - })) + } + .into() } Stmt::Switch(mut s) => { @@ -594,11 +600,11 @@ impl VisitMut for Remover { .iter() .any(|case| matches!(case.test.as_deref(), Some(Expr::Update(..)))) { - return Stmt::Switch(s); + return s.into(); } if let Expr::Update(..) = &*s.discriminant { if s.cases.len() != 1 { - return Stmt::Switch(s); + return s.into(); } } @@ -668,8 +674,8 @@ impl VisitMut for Remover { debug!("Removing an empty switch statement"); } return match ignore_result(s.discriminant, true, &self.expr_ctx) { - Some(expr) => Stmt::Expr(ExprStmt { span: s.span, expr }), - None => Stmt::Empty(EmptyStmt { span: s.span }), + Some(expr) => ExprStmt { span: s.span, expr }.into(), + None => EmptyStmt { span: s.span }.into(), }; } @@ -687,11 +693,12 @@ impl VisitMut for Remover { prepend_stmt(&mut stmts, expr.into_stmt()); } - let mut block = Stmt::Block(BlockStmt { + let mut block: Stmt = BlockStmt { span: s.span, stmts, ..Default::default() - }); + } + .into(); block.visit_mut_with(self); return block; } @@ -803,7 +810,7 @@ impl VisitMut for Remover { if !exprs.is_empty() { prepend_stmt( &mut stmts, - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: if exprs.len() == 1 { exprs.remove(0) @@ -814,18 +821,20 @@ impl VisitMut for Remover { } .into() }, - }), + } + .into(), ); } if cfg!(feature = "debug") { debug!("Switch -> Block as we know discriminant"); } - let mut block = Stmt::Block(BlockStmt { + let mut block: Stmt = BlockStmt { span: s.span, stmts, ..Default::default() - }); + } + .into(); block.visit_mut_with(self); return block; } @@ -867,11 +876,12 @@ impl VisitMut for Remover { ) } - let mut block = Stmt::Block(BlockStmt { + let mut block: Stmt = BlockStmt { span: s.span, stmts, ..Default::default() - }); + } + .into(); block.visit_mut_with(self); @@ -982,7 +992,7 @@ impl VisitMut for Remover { if !exprs.is_empty() { prepend_stmt( &mut stmts, - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: if exprs.len() == 1 { exprs.remove(0) @@ -993,18 +1003,20 @@ impl VisitMut for Remover { } .into() }, - }), + } + .into(), ); } if cfg!(feature = "debug") { debug!("Stmt -> Block as all cases are empty"); } - let mut block = Stmt::Block(BlockStmt { + let mut block: Stmt = BlockStmt { span: s.span, stmts, ..Default::default() - }); + } + .into(); block.visit_mut_with(self); return block; } @@ -1057,7 +1069,7 @@ impl VisitMut for Remover { } .into(); } - return Stmt::Empty(EmptyStmt { span: s.span }); + return EmptyStmt { span: s.span }.into(); } } @@ -1080,15 +1092,16 @@ impl VisitMut for Remover { let body = if let Some(var) = decl { var.into() } else { - Stmt::Empty(EmptyStmt { span: s.span }) + EmptyStmt { span: s.span }.into() }; if s.init.is_some() { - Stmt::For(ForStmt { + ForStmt { body: Box::new(body), update: None, ..s - }) + } + .into() } else { body } @@ -1098,51 +1111,54 @@ impl VisitMut for Remover { if let (purity, Known(v)) = s.test.cast_to_bool(&self.expr_ctx) { if v { if purity.is_pure() { - Stmt::While(WhileStmt { + WhileStmt { test: Lit::Bool(Bool { span: s.test.span(), value: true, }) .into(), ..s - }) + } + .into() } else { - Stmt::While(s) + s.into() } } else { let body = s.body.extract_var_ids_as_var(); let body = body.map(Box::new).map(Decl::Var).map(Stmt::Decl); - let body = body.unwrap_or(Stmt::Empty(EmptyStmt { span: s.span })); + let body = body.unwrap_or(EmptyStmt { span: s.span }.into()); if purity.is_pure() { body } else { - Stmt::While(WhileStmt { + WhileStmt { body: Box::new(body), ..s - }) + } + .into() } } } else { - Stmt::While(s) + s.into() } } Stmt::DoWhile(s) => { - if has_conditional_stopper(&[Stmt::DoWhile(s.clone())]) { - return Stmt::DoWhile(s); + if has_conditional_stopper(&[s.clone().into()]) { + return s.into(); } if let Known(v) = s.test.as_pure_bool(&self.expr_ctx) { if v { // `for(;;);` is shorter than `do ; while(true);` - Stmt::For(ForStmt { + ForStmt { span: s.span, init: None, test: None, update: None, body: s.body, - }) + } + .into() } else { let mut body = prepare_loop_body_for_inlining(*s.body); body.visit_mut_with(self); @@ -1159,7 +1175,7 @@ impl VisitMut for Remover { } } } else { - Stmt::DoWhile(s) + s.into() } } @@ -1195,7 +1211,7 @@ impl VisitMut for Remover { debug!("Dropping a useless variable declaration"); } - return Stmt::Empty(EmptyStmt { span: v.span }); + return EmptyStmt { span: v.span }.into(); } VarDecl { decls, ..*v }.into() @@ -1314,7 +1330,7 @@ impl Remover { for t in iter { match t.try_into_stmt() { Ok(Stmt::Decl(Decl::Fn(f))) => { - hoisted_fns.push(T::from_stmt(Stmt::Decl(Decl::Fn(f)))); + hoisted_fns.push(T::from(f.into())); } Ok(t) => { let ids = extract_var_ids(&t).into_iter().map(|i| { @@ -1332,7 +1348,7 @@ impl Remover { } if !decls.is_empty() { - new_stmts.push(T::from_stmt( + new_stmts.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -1344,7 +1360,7 @@ impl Remover { )); } - let stmt_like = T::from_stmt(stmt); + let stmt_like = T::from(stmt); new_stmts.push(stmt_like); new_stmts.extend(hoisted_fns); @@ -1378,7 +1394,7 @@ impl Remover { stmts .into_iter() .filter(|s| !matches!(s, Stmt::Empty(..))) - .map(T::from_stmt), + .map(T::from), ); continue; } @@ -1399,10 +1415,13 @@ impl Remover { let expr = ignore_result(test, true, &self.expr_ctx); if let Some(expr) = expr { - new_stmts.push(T::from_stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr, - }))); + new_stmts.push(T::from( + ExprStmt { + span: DUMMY_SP, + expr, + } + .into(), + )); } } @@ -1411,13 +1430,13 @@ impl Remover { if let Some(var) = alt.and_then(|alt| alt.extract_var_ids_as_var()) { - new_stmts.push(T::from_stmt(var.into())) + new_stmts.push(T::from(var.into())) } *cons } else { // Hoist vars from cons if let Some(var) = cons.extract_var_ids_as_var() { - new_stmts.push(T::from_stmt(var.into())) + new_stmts.push(T::from(var.into())) } match alt { Some(alt) => *alt, @@ -1425,19 +1444,20 @@ impl Remover { } } } - _ => Stmt::If(IfStmt { + _ => IfStmt { test, cons, alt, span, - }), + } + .into(), } } _ => stmt, }; - T::from_stmt(stmt) + T::from(stmt) } Err(stmt_like) => stmt_like, }; 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 1542c62566b3..56d85c701c99 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs @@ -919,7 +919,7 @@ impl VisitMut for TreeShaker { { debug!("Dropping an import because it's not used"); self.changed = true; - *n = ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP })); + *n = EmptyStmt { span: DUMMY_SP }.into(); } } _ => { @@ -970,20 +970,21 @@ impl VisitMut for TreeShaker { self.changed = true; if exprs.is_empty() { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); return; } else { - *s = Stmt::Expr(ExprStmt { + *s = ExprStmt { span, expr: Expr::from_exprs(exprs), - }); + } + .into(); } } } if let Stmt::Decl(Decl::Var(v)) = s { if v.decls.is_empty() { - *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); + *s = EmptyStmt { span: DUMMY_SP }.into(); } } diff --git a/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs b/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs index 7c4ee7aef273..3bca37705697 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs @@ -215,22 +215,28 @@ impl Decorator2022_03 { } .into(); - self.state.extra_stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr, - })); + self.state.extra_stmts.push( + ExprStmt { + span: DUMMY_SP, + expr, + } + .into(), + ); if let Some(init) = self.state.init_static.take() { - self.state.extra_stmts.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: CallExpr { + self.state.extra_stmts.push( + ExprStmt { span: DUMMY_SP, - callee: init.as_callee(), - args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], - ..Default::default() + expr: CallExpr { + span: DUMMY_SP, + callee: init.as_callee(), + args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], + ..Default::default() + } + .into(), } .into(), - })); + ); } } @@ -724,7 +730,7 @@ impl Decorator2022_03 { })); self.state = old_state; - Stmt::Decl(Decl::Class(c.take())) + c.take().into() } fn process_decorators(&mut self, decorators: &mut [Decorator]) { @@ -914,10 +920,11 @@ impl VisitMut for Decorator2022_03 { match p.kind { MethodKind::Method => { - let call_stmt = Stmt::Return(ReturnStmt { + let call_stmt = ReturnStmt { span: DUMMY_SP, arg: Some(init.into()), - }); + } + .into(); p.kind = MethodKind::Getter; p.function.body = Some(BlockStmt { @@ -927,7 +934,7 @@ impl VisitMut for Decorator2022_03 { }); } MethodKind::Getter => { - let call_stmt = Stmt::Return(ReturnStmt { + let call_stmt = ReturnStmt { span: DUMMY_SP, arg: Some( CallExpr { @@ -938,7 +945,8 @@ impl VisitMut for Decorator2022_03 { } .into(), ), - }); + } + .into(); p.function.body = Some(BlockStmt { span: DUMMY_SP, @@ -947,7 +955,7 @@ impl VisitMut for Decorator2022_03 { }); } MethodKind::Setter => { - let call_stmt = Stmt::Return(ReturnStmt { + let call_stmt = ReturnStmt { span: DUMMY_SP, arg: Some( CallExpr { @@ -962,7 +970,8 @@ impl VisitMut for Decorator2022_03 { } .into(), ), - }); + } + .into(); p.function.body = Some(BlockStmt { span: DUMMY_SP, @@ -1533,7 +1542,7 @@ impl VisitMut for Decorator2022_03 { let span = *span; let new_stmt = self.handle_class_decl(c); - *s = ModuleItem::Stmt(new_stmt); + *s = new_stmt.into(); self.extra_exports .push(ExportSpecifier::Named(ExportNamedSpecifier { span, @@ -1562,7 +1571,7 @@ impl VisitMut for Decorator2022_03 { is_type_only: false, })); - *s = ModuleItem::Stmt(new_stmt); + *s = new_stmt.into(); } _ => { s.visit_mut_children_with(self); @@ -1583,23 +1592,23 @@ impl VisitMut for Decorator2022_03 { if !self.extra_lets.is_empty() { insert_builder.push_back( index, - Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, decls: self.extra_lets.take(), declare: false, ..Default::default() - }))) + } .into(), ); } if !self.pre_class_inits.is_empty() { insert_builder.push_back( index, - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: Expr::from_exprs(self.pre_class_inits.take()), - }) + } .into(), ); } @@ -1629,13 +1638,14 @@ impl VisitMut for Decorator2022_03 { if !self.extra_exports.is_empty() { insert_builder.push_back( n.len() + 1, - ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { + NamedExport { span: DUMMY_SP, specifiers: self.extra_exports.take(), src: None, type_only: false, with: None, - })), + } + .into(), ); } @@ -1787,22 +1797,24 @@ impl VisitMut for Decorator2022_03 { if !self.extra_lets.is_empty() { insert_builder.push_back( index, - Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, decls: self.extra_lets.take(), declare: false, ..Default::default() - }))), + } + .into(), ); } if !self.pre_class_inits.is_empty() { insert_builder.push_back( index, - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: Expr::from_exprs(self.pre_class_inits.take()), - }), + } + .into(), ); } } 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 b5b434cc3f5b..2fc0b44ed8ab 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs @@ -65,7 +65,7 @@ impl TscDecorator { s.visit_mut_with(self); if !self.vars.is_empty() { - new.push(T::from_stmt( + new.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, @@ -81,12 +81,13 @@ impl TscDecorator { self.prepended_exprs .drain(..) .map(|expr| { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr, - }) + } + .into() }) - .map(T::from_stmt), + .map(T::from), ); new.push(s); @@ -95,12 +96,13 @@ impl TscDecorator { self.appended_exprs .drain(..) .map(|expr| { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr, - }) + } + .into() }) - .map(T::from_stmt), + .map(T::from), ); } diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs index 840fc80cf4fe..b612c76a186a 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs @@ -99,11 +99,12 @@ impl Fold for Decorators { class, }) => { if !contains_decorator(&class) { - return Decl::Class(ClassDecl { + return ClassDecl { ident, declare: false, class, - }); + } + .into(); } let decorate_call = Box::new(self.fold_class_inner(ident.clone(), class)); @@ -156,10 +157,11 @@ impl Fold for Decorators { class, )); - ModuleDecl::ExportDefaultExpr(ExportDefaultExpr { + ExportDefaultExpr { span, expr: decorate_call, - }) + } + .into() } _ => decl, } @@ -243,9 +245,7 @@ impl Fold for Decorators { }) => handle_class!(class, ident), _ => { - let item = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( - ExportDefaultExpr { span, expr }, - )); + let item: ModuleItem = ExportDefaultExpr { span, expr }.into(); buf.push(item.fold_with(self)); } }, @@ -586,42 +586,48 @@ impl Decorators { None } .into_iter() - .chain(iter::once(Stmt::Decl(Decl::Class(ClassDecl { - ident: ident.clone(), - class: Class { - decorators: Default::default(), - body: vec![constructor], - ..*class - } - .into(), - declare: false, - })))) - .chain(iter::once(Stmt::Return(ReturnStmt { - span: DUMMY_SP, - arg: Some( - ObjectLit { - span: DUMMY_SP, - props: vec![ - PropOrSpread::Prop(Box::new(Prop::KeyValue( - KeyValueProp { - key: PropName::Ident(quote_ident!("F")), - value: Box::new(Expr::Ident(ident)), - }, - ))), - PropOrSpread::Prop(Box::new(Prop::KeyValue( - KeyValueProp { - key: PropName::Ident(quote_ident!("d")), - value: Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: descriptors, - })), - }, - ))), - ], + .chain(iter::once( + ClassDecl { + ident: ident.clone(), + class: Class { + decorators: Default::default(), + body: vec![constructor], + ..*class } .into(), - ), - }))) + declare: false, + } + .into(), + )) + .chain(iter::once( + ReturnStmt { + span: DUMMY_SP, + arg: Some( + ObjectLit { + span: DUMMY_SP, + props: vec![ + PropOrSpread::Prop(Box::new(Prop::KeyValue( + KeyValueProp { + key: PropName::Ident(quote_ident!("F")), + value: Box::new(Expr::Ident(ident)), + }, + ))), + PropOrSpread::Prop(Box::new(Prop::KeyValue( + KeyValueProp { + key: PropName::Ident(quote_ident!("d")), + value: Box::new(Expr::Array(ArrayLit { + span: DUMMY_SP, + elems: descriptors, + })), + }, + ))), + ], + } + .into(), + ), + } + .into(), + )) .collect(), ..Default::default() }), diff --git a/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs b/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs index 84d99915dde6..859efab6b11e 100644 --- a/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs +++ b/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs @@ -75,13 +75,16 @@ impl ExplicitResourceManagement { definite: Default::default(), }; - try_body.push(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - declare: false, - decls: vec![using_ctx_var], - ..Default::default() - })))); + try_body.push( + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + declare: false, + decls: vec![using_ctx_var], + ..Default::default() + } + .into(), + ); for stmt in stmts.take() { match stmt.try_into_stmt() { @@ -90,7 +93,7 @@ impl ExplicitResourceManagement { } Ok(Stmt::Decl(Decl::Var(var))) => { // var.kind = VarDeclKind::Var; - try_body.push(Stmt::Decl(Decl::Var(var))); + try_body.push(var.into()); } Ok(stmt) => try_body.push(stmt), Err(stmt) => match stmt.try_into_module_decl() { @@ -105,38 +108,45 @@ impl ExplicitResourceManagement { // export { C as default } new.push( - T::try_from_module_decl(ModuleDecl::ExportNamed(NamedExport { - span: DUMMY_SP, - specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier { + T::try_from_module_decl( + NamedExport { span: DUMMY_SP, - orig: ModuleExportName::Ident(ident.clone()), - exported: Some(ModuleExportName::Ident(Ident::new_no_ctxt( - "default".into(), - DUMMY_SP, - ))), - is_type_only: Default::default(), - })], - src: None, - type_only: Default::default(), - with: None, - })) + specifiers: vec![ExportSpecifier::Named( + ExportNamedSpecifier { + span: DUMMY_SP, + orig: ModuleExportName::Ident(ident.clone()), + exported: Some(ModuleExportName::Ident( + Ident::new_no_ctxt("default".into(), DUMMY_SP), + )), + is_type_only: Default::default(), + }, + )], + src: None, + type_only: Default::default(), + with: None, + } + .into(), + ) .unwrap(), ); - try_body.push(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - decls: vec![VarDeclarator { + try_body.push( + VarDecl { span: DUMMY_SP, - name: ident.into(), - init: Some(match decl.decl { - DefaultDecl::Class(c) => Box::new(Expr::Class(c)), - DefaultDecl::Fn(f) => Box::new(Expr::Fn(f)), - DefaultDecl::TsInterfaceDecl(_) => unreachable!(), - }), - definite: Default::default(), - }], - ..Default::default() - })))); + kind: VarDeclKind::Var, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: ident.into(), + init: Some(match decl.decl { + DefaultDecl::Class(c) => Box::new(Expr::Class(c)), + DefaultDecl::Fn(f) => Box::new(Expr::Fn(f)), + DefaultDecl::TsInterfaceDecl(_) => unreachable!(), + }), + definite: Default::default(), + }], + ..Default::default() + } + .into(), + ); } Ok(ModuleDecl::ExportDefaultExpr(decl)) => { @@ -144,35 +154,42 @@ impl ExplicitResourceManagement { // export { _default as default } new.push( - T::try_from_module_decl(ModuleDecl::ExportNamed(NamedExport { - span: DUMMY_SP, - specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier { + T::try_from_module_decl( + NamedExport { span: DUMMY_SP, - orig: ModuleExportName::Ident(ident.clone()), - exported: Some(ModuleExportName::Ident(Ident::new_no_ctxt( - "default".into(), - DUMMY_SP, - ))), - is_type_only: Default::default(), - })], - src: None, - type_only: Default::default(), - with: None, - })) + specifiers: vec![ExportSpecifier::Named( + ExportNamedSpecifier { + span: DUMMY_SP, + orig: ModuleExportName::Ident(ident.clone()), + exported: Some(ModuleExportName::Ident( + Ident::new_no_ctxt("default".into(), DUMMY_SP), + )), + is_type_only: Default::default(), + }, + )], + src: None, + type_only: Default::default(), + with: None, + } + .into(), + ) .unwrap(), ); - try_body.push(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - declare: Default::default(), - decls: vec![VarDeclarator { + try_body.push( + VarDecl { span: DUMMY_SP, - name: ident.into(), - init: Some(decl.expr), - definite: Default::default(), - }], - ..Default::default() - })))); + kind: VarDeclKind::Var, + declare: Default::default(), + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: ident.into(), + init: Some(decl.expr), + definite: Default::default(), + }], + ..Default::default() + } + .into(), + ); } Ok(ModuleDecl::ExportDecl(e)) => { @@ -188,25 +205,31 @@ impl ExplicitResourceManagement { definite: Default::default(), }; - new.push(T::from_stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - declare: false, - decls: vec![var], - ..Default::default() - }))))); - - try_body.push(Stmt::Decl(e.decl)); - try_body.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: AssignExpr { + new.push(T::from( + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + declare: false, + decls: vec![var], + ..Default::default() + } + .into(), + )); + + try_body.push(e.decl.into()); + try_body.push( + ExprStmt { span: DUMMY_SP, - op: op!("="), - left: var_name.clone().into(), - right: ident.clone().into(), + expr: AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: var_name.clone().into(), + right: ident.clone().into(), + } + .into(), } .into(), - })); + ); let specifier = ExportSpecifier::Named(ExportNamedSpecifier { span: DUMMY_SP, @@ -216,13 +239,16 @@ impl ExplicitResourceManagement { }); extras.push( - T::try_from_module_decl(ModuleDecl::ExportNamed(NamedExport { - span: DUMMY_SP, - specifiers: vec![specifier], - src: None, - type_only: false, - with: None, - })) + T::try_from_module_decl( + NamedExport { + span: DUMMY_SP, + specifiers: vec![specifier], + src: None, + type_only: false, + with: None, + } + .into(), + ) .unwrap(), ); } @@ -245,33 +271,39 @@ impl ExplicitResourceManagement { }) .collect(); - new.push(T::from_stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - declare: false, - decls: var_decls, - ..Default::default() - }))))); - - try_body.push(Stmt::Decl(e.decl)); - try_body.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Expr::from_exprs( - orig_var_names - .iter() - .zip(var_names.iter()) - .map(|(orig, var_name)| { - AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: var_name.clone().into(), - right: orig.clone().into(), - } - .into() - }) - .collect(), - ), - })); + new.push(T::from( + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + declare: false, + decls: var_decls, + ..Default::default() + } + .into(), + )); + + try_body.push(e.decl.into()); + try_body.push( + ExprStmt { + span: DUMMY_SP, + expr: Expr::from_exprs( + orig_var_names + .iter() + .zip(var_names.iter()) + .map(|(orig, var_name)| { + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: var_name.clone().into(), + right: orig.clone().into(), + } + .into() + }) + .collect(), + ), + } + .into(), + ); let specifiers = orig_var_names .iter() .zip(var_names.iter()) @@ -286,20 +318,21 @@ impl ExplicitResourceManagement { .collect(); extras.push( - T::try_from_module_decl(ModuleDecl::ExportNamed(NamedExport { - span: DUMMY_SP, - specifiers, - src: None, - type_only: false, - with: None, - })) + T::try_from_module_decl( + NamedExport { + span: DUMMY_SP, + specifiers, + src: None, + type_only: false, + with: None, + } + .into(), + ) .unwrap(), ); } _ => { - new.push( - T::try_from_module_decl(ModuleDecl::ExportDecl(e)).unwrap(), - ); + new.push(T::try_from_module_decl(e.into()).unwrap()); } }; } @@ -371,7 +404,7 @@ impl ExplicitResourceManagement { }), }; - new.push(T::from_stmt(Stmt::Try(Box::new(try_stmt)))); + new.push(T::from(try_stmt.into())); new.extend(extras); *stmts = new; @@ -401,11 +434,14 @@ impl VisitMut for ExplicitResourceManagement { let mut body = vec![*n.body.take()]; self.wrap_with_try(state, &mut body); - n.body = Box::new(Stmt::Block(BlockStmt { - span: DUMMY_SP, - stmts: body, - ..Default::default() - })) + n.body = Box::new( + BlockStmt { + span: DUMMY_SP, + stmts: body, + ..Default::default() + } + .into(), + ) } } @@ -421,7 +457,7 @@ impl VisitMut for ExplicitResourceManagement { state.has_await |= decl.is_await; - *s = Stmt::Decl(Decl::Var(Box::new(VarDecl { + *s = VarDecl { span: DUMMY_SP, kind: if self.is_not_top_level { VarDeclKind::Const @@ -456,7 +492,8 @@ impl VisitMut for ExplicitResourceManagement { }) .collect(), ..Default::default() - }))); + } + .into(); } } diff --git a/crates/swc_ecma_transforms_proposal/src/export_default_from.rs b/crates/swc_ecma_transforms_proposal/src/export_default_from.rs index 9dd59be39264..2e27ee49d13a 100644 --- a/crates/swc_ecma_transforms_proposal/src/export_default_from.rs +++ b/crates/swc_ecma_transforms_proposal/src/export_default_from.rs @@ -74,26 +74,28 @@ impl VisitMut for ExportDefaultFrom { } } - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + stmts.push( NamedExport { span, specifiers: export_specifiers, src: Some(src.clone()), type_only: false, with: None, - }, - ))); + } + .into(), + ); if !origin_specifiers.is_empty() { - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( + stmts.push( NamedExport { span, specifiers: origin_specifiers, src: Some(src), type_only: false, with, - }, - ))); + } + .into(), + ); } } _ => { diff --git a/crates/swc_ecma_transforms_react/src/jsx/mod.rs b/crates/swc_ecma_transforms_react/src/jsx/mod.rs index d1577d490975..fae7124c6209 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/mod.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/mod.rs @@ -1097,7 +1097,7 @@ where prepend_stmt( stmts, - ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { + ImportDecl { span: DUMMY_SP, specifiers, src: Str { @@ -1109,7 +1109,8 @@ where type_only: Default::default(), with: Default::default(), phase: Default::default(), - })), + } + .into(), ) }); } @@ -1139,7 +1140,7 @@ where // const { createElement } = require('react') // const { jsx: jsx } = require('react/jsx-runtime') fn add_require(imports: Vec<(Ident, IdentName)>, src: &str, unresolved_mark: Mark) -> Stmt { - Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: false, @@ -1189,7 +1190,8 @@ fn add_require(imports: Vec<(Ident, IdentName)>, src: &str, unresolved_mark: Mar definite: false, }], ..Default::default() - }))) + } + .into() } impl Jsx diff --git a/crates/swc_ecma_transforms_react/src/refresh/hook.rs b/crates/swc_ecma_transforms_react/src/refresh/hook.rs index 9c5cca7ece47..19e528cb6e27 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/hook.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/hook.rs @@ -196,10 +196,13 @@ impl<'a> HookRegister<'a> { fn gen_hook_register_stmt(&mut self, ident: Ident, sig: HookSig) { self.ident.push(sig.handle.clone()); - self.extra_stmt.push(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Box::new(self.wrap_with_register(sig.handle, ident.into(), sig.hooks)), - })) + self.extra_stmt.push( + ExprStmt { + span: DUMMY_SP, + expr: Box::new(self.wrap_with_register(sig.handle, ident.into(), sig.hooks)), + } + .into(), + ) } } diff --git a/crates/swc_ecma_transforms_react/src/refresh/mod.rs b/crates/swc_ecma_transforms_react/src/refresh/mod.rs index 025da190a038..75d771d732c1 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/mod.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/mod.rs @@ -354,12 +354,11 @@ impl VisitMut for Refresh { if let Some(hook) = hook { make_hook_reg(expr.as_mut(), hook) } - item = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( - ExportDefaultExpr { - expr: Box::new(make_assign_stmt(reg[0].0.clone(), expr.take())), - span: *span, - }, - )); + item = ExportDefaultExpr { + expr: Box::new(make_assign_stmt(reg[0].0.clone(), expr.take())), + span: *span, + } + .into(); Persist::Hoc(Hoc { insert: false, reg, @@ -400,23 +399,32 @@ impl VisitMut for Refresh { refresh_regs.push((registration_handle.clone(), persistent_id.to_id())); - items.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Box::new(make_assign_stmt(registration_handle, persistent_id.into())), - }))); + items.push( + ExprStmt { + span: DUMMY_SP, + expr: Box::new(make_assign_stmt( + registration_handle, + persistent_id.into(), + )), + } + .into(), + ); } Persist::Hoc(mut hoc) => { hoc.reg = hoc.reg.into_iter().rev().collect(); if hoc.insert { let (ident, name) = hoc.reg.last().unwrap(); - items.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Box::new(make_assign_stmt( - ident.clone(), - Ident::new(name.0.clone(), DUMMY_SP, name.1).into(), - )), - }))) + items.push( + ExprStmt { + span: DUMMY_SP, + expr: Box::new(make_assign_stmt( + ident.clone(), + Ident::new(name.0.clone(), DUMMY_SP, name.1).into(), + )), + } + .into(), + ) } refresh_regs.append(&mut hoc.reg); } @@ -424,7 +432,7 @@ impl VisitMut for Refresh { } if !hook_visitor.ident.is_empty() { - items.insert(0, ModuleItem::Stmt(hook_visitor.gen_hook_handle())); + items.insert(0, hook_visitor.gen_hook_handle().into()); } // Insert @@ -459,15 +467,18 @@ impl VisitMut for Refresh { // ``` let refresh_reg = self.options.refresh_reg.as_str(); for (handle, persistent_id) in refresh_regs { - items.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: CallExpr { - callee: quote_ident!(refresh_reg).as_callee(), - args: vec![handle.as_arg(), quote_str!(persistent_id.0).as_arg()], - ..Default::default() + items.push( + ExprStmt { + span: DUMMY_SP, + expr: CallExpr { + callee: quote_ident!(refresh_reg).as_callee(), + args: vec![handle.as_arg(), quote_str!(persistent_id.0).as_arg()], + ..Default::default() + } + .into(), } .into(), - }))); + ); } *module_items = items diff --git a/crates/swc_ecma_transforms_react/src/refresh/util.rs b/crates/swc_ecma_transforms_react/src/refresh/util.rs index 68b8507b36b5..ebc93354d8de 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/util.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/util.rs @@ -52,10 +52,11 @@ pub fn make_assign_stmt(handle: Ident, expr: Box) -> Expr { } pub fn make_call_stmt(handle: Ident) -> Stmt { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: Box::new(make_call_expr(handle)), - }) + } + .into() } pub fn make_call_expr(handle: Ident) -> Expr { diff --git a/crates/swc_ecma_transforms_testing/src/lib.rs b/crates/swc_ecma_transforms_testing/src/lib.rs index 260cb6b0c168..76ca6ba2de75 100644 --- a/crates/swc_ecma_transforms_testing/src/lib.rs +++ b/crates/swc_ecma_transforms_testing/src/lib.rs @@ -236,13 +236,14 @@ impl VisitMut for RegeneratorHandler { init: Some(init), definite: Default::default(), }; - *item = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + *item = VarDecl { span: import.span, kind: VarDeclKind::Var, declare: false, decls: vec![decl], ..Default::default() - })))) + } + .into() } } } diff --git a/crates/swc_ecma_transforms_typescript/src/transform.rs b/crates/swc_ecma_transforms_typescript/src/transform.rs index e4930f694a30..4c261e4e4219 100644 --- a/crates/swc_ecma_transforms_typescript/src/transform.rs +++ b/crates/swc_ecma_transforms_typescript/src/transform.rs @@ -404,10 +404,11 @@ impl Transform { let expr = Self::wrap_enum_or_module_with_iife(&self.namespace_id, module_ident, body, is_export); - Stmt::Expr(ExprStmt { + ExprStmt { span, expr: expr.into(), - }) + } + .into() } fn transform_ts_namespace_body(id: Id, body: TsNamespaceBody) -> BlockStmt { @@ -484,7 +485,7 @@ impl Transform { var_decl.span = decl.span; - Stmt::Decl(var_decl.into()) + var_decl.into() }; stmts.push(stmt); @@ -605,10 +606,11 @@ impl Transform { is_export, ); - Stmt::Expr(ExprStmt { + ExprStmt { span, expr: expr.into(), - }) + } + .into() } fn transform_ts_enum_member( @@ -671,7 +673,7 @@ impl Transform { match decl { Decl::Fn(FnDecl { ref ident, .. }) | Decl::Class(ClassDecl { ref ident, .. }) => { let assign_stmt = Self::assign_prop(id, ident, span); - [Stmt::Decl(decl), assign_stmt].map(Option::Some) + [decl.into(), assign_stmt].map(Option::Some) } Decl::Var(var_decl) => [ Self::transform_export_var_decl_in_ts_module_block( @@ -718,7 +720,7 @@ impl Transform { .into() }; - Some(Stmt::Expr(ExprStmt { span, expr })) + Some(ExprStmt { span, expr }.into()) } } @@ -833,10 +835,11 @@ impl Transform { .clone() .make_assign_to(op!("="), id.clone().make_member(prop.clone().into()).into()); - Stmt::Expr(ExprStmt { + ExprStmt { span, expr: expr.into(), - }) + } + .into() } fn add_var_for_enum_or_module_declaration( @@ -1017,14 +1020,14 @@ impl Transform { init.into_var_decl(VarDeclKind::Const, decl.id.take().into()); let module_item = if decl.is_export { - ModuleDecl::ExportDecl(ExportDecl { + ExportDecl { span: decl.span, decl: var_decl.into(), - }) + } .into() } else { var_decl.span = decl.span; - ModuleItem::Stmt(var_decl.into()) + var_decl.into() }; n.push(module_item); } @@ -1054,7 +1057,7 @@ impl Transform { .into_var_decl(VarDeclKind::Const, decl.id.take().into()); var_decl.span = decl.span; - n.push(ModuleItem::Stmt(var_decl.into())); + n.push(var_decl.into()); } TsImportExportAssignConfig::Preserve => n.push(module_item), TsImportExportAssignConfig::NodeNext => { @@ -1066,14 +1069,14 @@ impl Transform { .into_var_decl(VarDeclKind::Const, decl.id.take().into()); let module_item = if decl.is_export { - ModuleDecl::ExportDecl(ExportDecl { + ExportDecl { span: decl.span, decl: var_decl.into(), - }) + } .into() } else { var_decl.span = decl.span; - Stmt::Decl(var_decl.into()).into() + var_decl.into() }; n.push(module_item); } @@ -1108,7 +1111,7 @@ impl Transform { if should_inject { n.inject_after_directive([ // import { createRequire } from "module"; - ModuleDecl::Import(ImportDecl { + ImportDecl { span: DUMMY_SP, specifiers: vec![ImportNamedSpecifier { span: DUMMY_SP, @@ -1121,24 +1124,21 @@ impl Transform { type_only: false, with: None, phase: Default::default(), - }) + } .into(), // const __require = _createRequire(import.meta.url); - Stmt::Decl( - create_require - .as_call( - DUMMY_SP, - vec![MetaPropExpr { - span: DUMMY_SP, - kind: MetaPropKind::ImportMeta, - } - .make_member(quote_ident!("url")) - .as_arg()], - ) - .into_var_decl(VarDeclKind::Const, require.clone().into()) - .into(), - ) - .into(), + create_require + .as_call( + DUMMY_SP, + vec![MetaPropExpr { + span: DUMMY_SP, + kind: MetaPropKind::ImportMeta, + } + .make_member(quote_ident!("url")) + .as_arg()], + ) + .into_var_decl(VarDeclKind::Const, require.clone().into()) + .into(), ]); } @@ -1148,7 +1148,7 @@ impl Transform { let TsExportAssignment { expr, span } = cjs_export_assign; n.push( - Stmt::Expr(ExprStmt { + ExprStmt { span, expr: Box::new( expr.make_assign_to( @@ -1161,12 +1161,12 @@ impl Transform { .into(), ), ), - }) + } .into(), ); } TsImportExportAssignConfig::Preserve => { - n.push(ModuleDecl::TsExportAssignment(cjs_export_assign).into()); + n.push(cjs_export_assign.into()); } TsImportExportAssignConfig::NodeNext | TsImportExportAssignConfig::EsNext => { // TS1203 diff --git a/crates/swc_ecma_transforms_typescript/src/typescript.rs b/crates/swc_ecma_transforms_typescript/src/typescript.rs index 4c4c43351858..7dadcec557e2 100644 --- a/crates/swc_ecma_transforms_typescript/src/typescript.rs +++ b/crates/swc_ecma_transforms_typescript/src/typescript.rs @@ -89,13 +89,13 @@ impl TypeScript { return; } - n.body.push(ModuleItem::ModuleDecl( + n.body.push( NamedExport { span, ..NamedExport::dummy() } .into(), - )); + ); } } diff --git a/crates/swc_ecma_utils/src/constructor.rs b/crates/swc_ecma_utils/src/constructor.rs index 3322a34ca327..25f3b5ac00a5 100644 --- a/crates/swc_ecma_utils/src/constructor.rs +++ b/crates/swc_ecma_utils/src/constructor.rs @@ -88,7 +88,7 @@ impl<'a> Fold for Injector<'a> { self.injected |= folder.injected; buf.extend(folder.injected_tmp.map(|ident| { - Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, decls: vec![VarDeclarator { @@ -98,7 +98,8 @@ impl<'a> Fold for Injector<'a> { definite: false, }], ..Default::default() - }))) + } + .into() })); buf.push(stmt); } diff --git a/crates/swc_ecma_utils/src/factory.rs b/crates/swc_ecma_utils/src/factory.rs index b62bbc7a9c11..494702b6607c 100644 --- a/crates/swc_ecma_utils/src/factory.rs +++ b/crates/swc_ecma_utils/src/factory.rs @@ -45,10 +45,11 @@ pub trait ExprFactory: Into> { /// Creates an expression statement with `self`. #[cfg_attr(not(debug_assertions), inline(always))] fn into_stmt(self) -> Stmt { - Stmt::Expr(ExprStmt { + ExprStmt { span: DUMMY_SP, expr: self.into(), - }) + } + .into() } /// Creates a statement whcih return `self`. 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 6888f681f605..4716aaa2b9a2 100644 --- a/crates/swc_ecma_utils/src/function/fn_env_hoister.rs +++ b/crates/swc_ecma_utils/src/function/fn_env_hoister.rs @@ -123,11 +123,14 @@ impl FnEnvHoister { if decls.is_empty() { None } else { - Some(Stmt::Decl(Decl::Var(Box::new(VarDecl { - kind: VarDeclKind::Var, - decls, - ..Default::default() - })))) + Some( + VarDecl { + kind: VarDeclKind::Var, + decls, + ..Default::default() + } + .into(), + ) } } @@ -180,11 +183,14 @@ impl FnEnvHoister { (None, None) } else { ( - Some(Stmt::Decl(Decl::Var(Box::new(VarDecl { - kind: VarDeclKind::Var, - decls, - ..Default::default() - })))), + Some( + VarDecl { + kind: VarDeclKind::Var, + decls, + ..Default::default() + } + .into(), + ), this, ) } @@ -291,7 +297,7 @@ impl VisitMut for FnEnvHoister { if !self.extra_ident.is_empty() { b.stmts.insert( 0, - Stmt::Decl(Decl::Var(Box::new(VarDecl { + VarDecl { kind: VarDeclKind::Var, decls: self .extra_ident @@ -305,7 +311,8 @@ impl VisitMut for FnEnvHoister { }) .collect(), ..Default::default() - }))), + } + .into(), ) } } diff --git a/crates/swc_ecma_utils/src/function/function_wrapper.rs b/crates/swc_ecma_utils/src/function/function_wrapper.rs index 827c3ffd65e1..42a883f5b8af 100644 --- a/crates/swc_ecma_utils/src/function/function_wrapper.rs +++ b/crates/swc_ecma_utils/src/function/function_wrapper.rs @@ -112,38 +112,35 @@ impl FunctionWrapper { |ident| private_ident!(ident.span, format!("_{}", ident.sym)), ); - let ref_stmt: Stmt = Stmt::Decl( - VarDecl { - kind: VarDeclKind::Var, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: Pat::Ident(ref_ident.clone().into()), - init: Some(Box::new(self.function.take())), - definite: false, - }], + let ref_stmt: Stmt = VarDecl { + kind: VarDeclKind::Var, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: Pat::Ident(ref_ident.clone().into()), + init: Some(Box::new(self.function.take())), + definite: false, + }], - ..Default::default() - } - .into(), - ); + ..Default::default() + } + .into(); let fn_decl_stmt = { let FnExpr { function, .. } = self.build_function_forward(ref_ident, None); - Stmt::Decl( - FnDecl { - ident: name_ident.clone(), - declare: false, - function, - } - .into(), - ) + FnDecl { + ident: name_ident.clone(), + declare: false, + function, + } + .into() }; - let return_stmt = Stmt::Return(ReturnStmt { + let return_stmt = ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(name_ident.into())), - }); + } + .into(); let block_stmt = BlockStmt { stmts: vec![ref_stmt, fn_decl_stmt, return_stmt], @@ -231,14 +228,15 @@ impl FunctionWrapper { /// } /// ``` fn build_function_forward(&mut self, ref_ident: Ident, name_ident: Option) -> FnExpr { - let apply = Stmt::Return(ReturnStmt { + let apply = ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(ref_ident.apply( DUMMY_SP, ThisExpr { span: DUMMY_SP }.into(), vec![quote_ident!("arguments").as_arg()], ))), - }); + } + .into(); FnExpr { ident: name_ident, diff --git a/crates/swc_ecma_utils/src/lib.rs b/crates/swc_ecma_utils/src/lib.rs index 83810b2edd72..63985f5d82b8 100644 --- a/crates/swc_ecma_utils/src/lib.rs +++ b/crates/swc_ecma_utils/src/lib.rs @@ -253,12 +253,12 @@ impl StmtOrModuleItem for ModuleItem { #[inline] fn from_stmt(stmt: Stmt) -> Self { - ModuleItem::Stmt(stmt) + stmt.into() } #[inline] fn try_from_module_decl(decl: ModuleDecl) -> Result { - Ok(ModuleItem::ModuleDecl(decl)) + Ok(decl.into()) } } @@ -271,11 +271,10 @@ pub trait ModuleItemLike: StmtLike { } } -pub trait StmtLike: Sized + 'static + Send + Sync { +pub trait StmtLike: Sized + 'static + Send + Sync + From { fn try_into_stmt(self) -> Result; fn as_stmt(&self) -> Option<&Stmt>; fn as_stmt_mut(&mut self) -> Option<&mut Stmt>; - fn from_stmt(stmt: Stmt) -> Self; } impl ModuleItemLike for Stmt {} @@ -295,11 +294,6 @@ impl StmtLike for Stmt { fn as_stmt_mut(&mut self) -> Option<&mut Stmt> { Some(self) } - - #[inline] - fn from_stmt(stmt: Stmt) -> Self { - stmt - } } impl ModuleItemLike for ModuleItem { @@ -313,7 +307,7 @@ impl ModuleItemLike for ModuleItem { #[inline] fn try_from_module_decl(decl: ModuleDecl) -> Result { - Ok(ModuleItem::ModuleDecl(decl)) + Ok(decl.into()) } } impl StmtLike for ModuleItem { @@ -340,11 +334,6 @@ impl StmtLike for ModuleItem { _ => None, } } - - #[inline] - fn from_stmt(stmt: Stmt) -> Self { - ModuleItem::Stmt(stmt) - } } pub type BoolValue = Value; diff --git a/crates/swc_estree_compat/src/swcify/stmt.rs b/crates/swc_estree_compat/src/swcify/stmt.rs index e1a8492621f6..1bc43a167157 100644 --- a/crates/swc_estree_compat/src/swcify/stmt.rs +++ b/crates/swc_estree_compat/src/swcify/stmt.rs @@ -1,13 +1,13 @@ use swc_common::DUMMY_SP; use swc_ecma_ast::{ - BlockStmt, BreakStmt, ClassDecl, ClassExpr, ContinueStmt, DebuggerStmt, Decl, DefaultDecl, + BlockStmt, BreakStmt, ClassDecl, ClassExpr, ContinueStmt, DebuggerStmt, DefaultDecl, DoWhileStmt, EmptyStmt, ExportAll, ExportDecl, ExportDefaultDecl, ExportDefaultExpr, ExportNamedSpecifier, ExprStmt, FnDecl, FnExpr, ForHead, ForInStmt, ForOfStmt, ForStmt, IfStmt, ImportDecl, ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, KeyValueProp, LabeledStmt, Lit, ModuleDecl, ModuleItem, NamedExport, ObjectLit, Pat, Prop, PropName, - PropOrSpread, ReturnStmt, Stmt, SwitchStmt, ThrowStmt, TryStmt, TsExportAssignment, - TsInterfaceDecl, TsModuleDecl, TsTypeAliasDecl, VarDecl, VarDeclKind, VarDeclOrExpr, - VarDeclarator, WhileStmt, WithStmt, + PropOrSpread, ReturnStmt, SwitchStmt, ThrowStmt, TryStmt, TsExportAssignment, TsInterfaceDecl, + TsModuleDecl, TsTypeAliasDecl, VarDecl, VarDeclKind, VarDeclOrExpr, VarDeclarator, WhileStmt, + WithStmt, }; use swc_estree_ast::{ BlockStatement, BreakStatement, ClassDeclaration, ContinueStatement, DebuggerStatement, @@ -46,7 +46,7 @@ impl Swcify for Statement { type Output = ModuleItem; fn swcify(self, ctx: &Context) -> Self::Output { - ModuleItem::Stmt(match self { + match self { Statement::Block(v) => v.swcify(ctx).into(), Statement::Break(v) => v.swcify(ctx).into(), Statement::Continue(v) => v.swcify(ctx).into(), @@ -56,7 +56,7 @@ impl Swcify for Statement { Statement::Expr(v) => v.swcify(ctx).into(), Statement::ForIn(v) => v.swcify(ctx).into(), Statement::For(v) => v.swcify(ctx).into(), - Statement::FuncDecl(v) => Decl::Fn(v.swcify(ctx)).into(), + Statement::FuncDecl(v) => v.swcify(ctx).into(), Statement::If(v) => v.swcify(ctx).into(), Statement::Labeled(v) => v.swcify(ctx).into(), Statement::Return(v) => v.swcify(ctx).into(), @@ -66,37 +66,25 @@ impl Swcify for Statement { Statement::VarDecl(v) => v.swcify(ctx).into(), Statement::While(v) => v.swcify(ctx).into(), Statement::With(v) => v.swcify(ctx).into(), - Statement::ClassDecl(v) => Decl::Class(v.swcify(ctx)).into(), - Statement::ExportAllDecl(v) => { - return ModuleItem::ModuleDecl(ModuleDecl::from(v.swcify(ctx))) - } - Statement::ExportDefaultDecl(v) => return ModuleItem::ModuleDecl(v.swcify(ctx)), - Statement::ExportNamedDecl(v) => { - return ModuleItem::ModuleDecl(ModuleDecl::from(v.swcify(ctx))) - } + Statement::ClassDecl(v) => v.swcify(ctx).into(), + Statement::ExportAllDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), + Statement::ExportDefaultDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx)), + Statement::ExportNamedDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), Statement::ForOf(v) => v.swcify(ctx).into(), - Statement::ImportDecl(v) => { - return ModuleItem::ModuleDecl(ModuleDecl::from(v.swcify(ctx))) - } - Statement::DeclClass(v) => Stmt::Decl(v.swcify(ctx).into()), - Statement::DeclFunc(v) => Stmt::Decl(v.swcify(ctx).into()), - Statement::DeclInterface(v) => Stmt::Decl(v.swcify(ctx).into()), - Statement::DeclModule(v) => Stmt::Decl(v.swcify(ctx).into()), - Statement::DeclareModuleExports(v) => { - return ModuleItem::ModuleDecl(ModuleDecl::from(v.swcify(ctx))) - } - Statement::DeclTypeAlias(v) => Stmt::Decl(Decl::from(v.swcify(ctx))), - Statement::DeclVar(v) => Stmt::Decl(Decl::from(v.swcify(ctx))), - Statement::DeclExportDeclaration(v) => { - return ModuleItem::ModuleDecl(ModuleDecl::from(v.swcify(ctx))) - } - Statement::DeclExportAllDeclaration(v) => { - return ModuleItem::ModuleDecl(ModuleDecl::from(v.swcify(ctx))) - } + Statement::ImportDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), + Statement::DeclClass(v) => v.swcify(ctx).into(), + Statement::DeclFunc(v) => v.swcify(ctx).into(), + Statement::DeclInterface(v) => v.swcify(ctx).into(), + Statement::DeclModule(v) => v.swcify(ctx).into(), + Statement::DeclareModuleExports(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), + Statement::DeclTypeAlias(v) => v.swcify(ctx).into(), + Statement::DeclVar(v) => v.swcify(ctx).into(), + Statement::DeclExportDeclaration(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), + Statement::DeclExportAllDeclaration(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), _ => { todo!("swcify: {:?}", self) } - }) + } } } diff --git a/crates/swc_node_bundler/src/loaders/json.rs b/crates/swc_node_bundler/src/loaders/json.rs index d9e6c3e0022b..9261a96bafe7 100644 --- a/crates/swc_node_bundler/src/loaders/json.rs +++ b/crates/swc_node_bundler/src/loaders/json.rs @@ -9,7 +9,7 @@ pub(super) fn load_json_as_module(fm: &Arc) -> Result let expr = parse_file_as_expr(fm, Syntax::default(), EsVersion::Es2020, None, &mut vec![]) .map_err(|err| anyhow!("failed parse json as javascript object: {:#?}", err))?; - let export = ModuleItem::Stmt(Stmt::Expr(ExprStmt { + let export = ExprStmt { span: DUMMY_SP, expr: AssignExpr { span: DUMMY_SP, @@ -23,7 +23,8 @@ pub(super) fn load_json_as_module(fm: &Arc) -> Result right: expr, } .into(), - })); + } + .into(); Ok(Module { span: DUMMY_SP, diff --git a/crates/swc_typescript/src/fast_dts/mod.rs b/crates/swc_typescript/src/fast_dts/mod.rs index 75cb8ca3bc18..ef6152bd35d6 100644 --- a/crates/swc_typescript/src/fast_dts/mod.rs +++ b/crates/swc_typescript/src/fast_dts/mod.rs @@ -128,12 +128,13 @@ impl FastDts { } if let Some(()) = self.decl_to_type_decl(decl) { - new_items.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl( + new_items.push( ExportDecl { decl: decl.take(), span: *span, - }, - ))); + } + .into(), + ); } else { self.mark_diagnostic(DtsIssue::UnableToInferType { range: self.source_range_to_range(*span), @@ -175,7 +176,7 @@ impl FastDts { .map(type_ann); if let Some(type_ann) = type_ann { - new_items.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new( + new_items.push( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, @@ -191,22 +192,25 @@ impl FastDts { definite: false, }], ..Default::default() - }, - ))))); + } + .into(), + ); - new_items.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( + new_items.push( ExportDefaultExpr { span: export.span, expr: name_ident.into(), - }, - ))) + } + .into(), + ) } else { - new_items.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( + new_items.push( ExportDefaultExpr { span: export.span, expr: export.expr.take(), - }, - ))) + } + .into(), + ) } }