diff --git a/crates/swc_bundler/src/bundler/chunk/cjs.rs b/crates/swc_bundler/src/bundler/chunk/cjs.rs index 18f4cd6072f..a4c902fe329 100644 --- a/crates/swc_bundler/src/bundler/chunk/cjs.rs +++ b/crates/swc_bundler/src/bundler/chunk/cjs.rs @@ -108,7 +108,7 @@ fn wrap_module( } // ... body of foo - let module_fn = Expr::Fn(FnExpr { + let module_fn: Expr = FnExpr { ident: None, function: Box::new(Function { params: vec![ @@ -145,7 +145,8 @@ fn wrap_module( is_async: false, ..Default::default() }), - }); + } + .into(); // var load = __swcpack_require__.bind(void 0, moduleDecl) @@ -355,15 +356,12 @@ impl VisitMut for DefaultHandler { if let Expr::Ident(i) = e { if i.sym == "default" { - *e = Expr::Member(MemberExpr { + *e = MemberExpr { span: i.span, - obj: Box::new(Expr::Ident(Ident::new( - "module".into(), - DUMMY_SP, - self.local_ctxt, - ))), + obj: Ident::new("module".into(), DUMMY_SP, self.local_ctxt).into(), prop: MemberProp::Ident(quote_ident!("exports")), - }); + } + .into(); } } } diff --git a/crates/swc_bundler/src/bundler/chunk/computed_key.rs b/crates/swc_bundler/src/bundler/chunk/computed_key.rs index 10e4b7cbb75..d7229406eb7 100644 --- a/crates/swc_bundler/src/bundler/chunk/computed_key.rs +++ b/crates/swc_bundler/src/bundler/chunk/computed_key.rs @@ -114,10 +114,13 @@ where let return_stmt = Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props: take(&mut export_visitor.return_props), - }))), + arg: Some( + ObjectLit { + span: DUMMY_SP, + props: take(&mut export_visitor.return_props), + } + .into(), + ), }); module.iter().for_each(|(_, v)| { @@ -131,7 +134,7 @@ where } }); - let module_fn = Expr::Fn(FnExpr { + let module_fn: Expr = FnExpr { function: Box::new(Function { params: Default::default(), body: Some(BlockStmt { @@ -144,20 +147,23 @@ where ..Default::default() }), ident: None, - }); + } + .into(); - let mut module_expr = Expr::Call(CallExpr { + let mut module_expr = CallExpr { span: DUMMY_SP, callee: module_fn.as_callee(), args: Default::default(), ..Default::default() - }); + } + .into(); if is_async { - module_expr = Expr::Await(AwaitExpr { + module_expr = AwaitExpr { span: DUMMY_SP, arg: Box::new(module_expr), - }); + } + .into(); } let var_decl = VarDecl { @@ -208,7 +214,7 @@ impl ExportToReturn { self.return_props .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(key.into()), - value: Box::new(Expr::Ident(value)), + value: value.into(), })))); } } diff --git a/crates/swc_bundler/src/bundler/chunk/merge.rs b/crates/swc_bundler/src/bundler/chunk/merge.rs index 169503d6695..e260df1e78a 100644 --- a/crates/swc_bundler/src/bundler/chunk/merge.rs +++ b/crates/swc_bundler/src/bundler/chunk/merge.rs @@ -693,7 +693,7 @@ where )) } None => { - let init = Expr::Class(c); + let init = c; new.push(init.assign_to(local.clone()).into_module_item( injected_ctxt, "prepare -> export default decl -> class -> without \ @@ -974,17 +974,20 @@ where vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(mod_var.clone().into()), - init: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: Ident::new( - "load".into(), - DUMMY_SP, - dep.export_ctxt(), - ) - .as_callee(), - ..Default::default() - }))), + name: mod_var.clone().into(), + init: Some( + CallExpr { + span: DUMMY_SP, + callee: Ident::new( + "load".into(), + DUMMY_SP, + dep.export_ctxt(), + ) + .as_callee(), + ..Default::default() + } + .into(), + ), definite: Default::default(), }); for s in specifiers { @@ -994,10 +997,8 @@ where ModuleExportName::Ident(name) => { vars.push(VarDeclarator { span: s.span, - name: Pat::Ident(name.clone().into()), - init: Some(Box::new(Expr::Ident( - mod_var.clone(), - ))), + name: name.clone().into(), + init: Some(mod_var.clone().into()), definite: Default::default(), }); } @@ -1011,7 +1012,7 @@ where ExportSpecifier::Default(s) => { vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(s.exported.clone().into()), + name: s.exported.clone().into(), init: Some( mod_var .clone() @@ -1042,9 +1043,7 @@ where }; vars.push(VarDeclarator { span: s.span, - name: Pat::Ident( - exported.clone().unwrap().into(), - ), + name: exported.clone().unwrap().into(), init: Some( mod_var .clone() @@ -1339,7 +1338,7 @@ impl VisitMut for ImportMetaHandler<'_, '_> { .. }) = e { - *e = Expr::Ident(self.inline_ident.clone()); + *e = self.inline_ident.clone().into(); self.occurred = true; } } diff --git a/crates/swc_bundler/src/bundler/finalize.rs b/crates/swc_bundler/src/bundler/finalize.rs index 20d8b7801bf..da14b24dae4 100644 --- a/crates/swc_bundler/src/bundler/finalize.rs +++ b/crates/swc_bundler/src/bundler/finalize.rs @@ -210,7 +210,7 @@ where "default".into(), DUMMY_SP, )), - value: Box::new(Expr::Ident(s.exported)), + value: s.exported.into(), }, )))); } @@ -225,7 +225,7 @@ where props.push(PropOrSpread::Prop(Box::new( Prop::KeyValue(KeyValueProp { key: PropName::Ident(exported.into()), - value: Box::new(Expr::Ident(orig)), + value: orig.into(), }), ))); } @@ -262,7 +262,7 @@ where "default".into(), export.span, )), - value: Box::new(Expr::Ident(ident.clone())), + value: ident.clone().into(), }, )))); @@ -283,7 +283,7 @@ where "default".into(), export.span, )), - value: Box::new(Expr::Ident(ident.clone())), + value: ident.clone().into(), }, )))); @@ -302,7 +302,7 @@ where )))); let var = VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(default_var.into()), + name: default_var.into(), init: Some(export.expr), definite: false, }; @@ -323,10 +323,13 @@ where }; body.stmts.push(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props, - }))), + arg: Some( + ObjectLit { + span: DUMMY_SP, + props, + } + .into(), + ), })); let f = Function { @@ -342,12 +345,13 @@ where function: Box::new(f), }; - let iife = Box::new(Expr::Call(CallExpr { + let iife = CallExpr { span: DUMMY_SP, callee: invoked_fn_expr.as_callee(), args: Default::default(), ..Default::default() - })); + } + .into(); Module { span: DUMMY_SP, diff --git a/crates/swc_bundler/src/bundler/import/mod.rs b/crates/swc_bundler/src/bundler/import/mod.rs index 0f964bb2178..83583fe6806 100644 --- a/crates/swc_bundler/src/bundler/import/mod.rs +++ b/crates/swc_bundler/src/bundler/import/mod.rs @@ -356,7 +356,7 @@ where }; prop.ctxt = self.imported_idents.get(&obj.to_id()).copied().unwrap(); - *e = Expr::Ident(prop); + *e = prop.into(); } } diff --git a/crates/swc_bundler/src/bundler/keywords.rs b/crates/swc_bundler/src/bundler/keywords.rs index 2e34c9fa7f9..3f1f9c1992c 100644 --- a/crates/swc_bundler/src/bundler/keywords.rs +++ b/crates/swc_bundler/src/bundler/keywords.rs @@ -91,17 +91,18 @@ impl VisitMut for KeywordRenamer { Some(default) => { *n = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(pat.key.take().into()), - value: Box::new(Pat::Assign(AssignPat { + value: AssignPat { span: pat.span, - left: Box::new(Pat::Ident(renamed.into())), + left: Box::new(renamed.into()), right: default.take(), - })), + } + .into(), }); } None => { *n = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(pat.key.take().into()), - value: Box::new(Pat::Ident(renamed.into())), + value: renamed.into(), }) } } @@ -134,7 +135,7 @@ impl VisitMut for KeywordRenamer { if let Some(renamed) = self.renamed(i) { *n = Prop::KeyValue(KeyValueProp { key: PropName::Ident(i.clone().into()), - value: Box::new(Expr::Ident(renamed)), + value: renamed.into(), }); } } diff --git a/crates/swc_bundler/src/id.rs b/crates/swc_bundler/src/id.rs index 2b105ebca64..5b4e7664c66 100644 --- a/crates/swc_bundler/src/id.rs +++ b/crates/swc_bundler/src/id.rs @@ -127,6 +127,6 @@ impl From for Ident { impl From for Expr { #[inline] fn from(id: Id) -> Self { - Expr::Ident(id.into_ident()) + id.into_ident().into() } } diff --git a/crates/swc_bundler/src/inline.rs b/crates/swc_bundler/src/inline.rs index 860d3b8cdac..62fea976be7 100644 --- a/crates/swc_bundler/src/inline.rs +++ b/crates/swc_bundler/src/inline.rs @@ -121,7 +121,7 @@ impl VisitMut for Inliner { if i.sym != orig.sym { *n = Prop::KeyValue(KeyValueProp { key: PropName::Ident(orig.into()), - value: Box::new(Expr::Ident(i.clone())), + value: i.clone().into(), }); } } diff --git a/crates/swc_bundler/src/util.rs b/crates/swc_bundler/src/util.rs index c00a55c2002..377587a0ec7 100644 --- a/crates/swc_bundler/src/util.rs +++ b/crates/swc_bundler/src/util.rs @@ -58,7 +58,7 @@ pub(crate) trait ExprExt: Into { VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(Ident::new(lhs.0, DUMMY_SP, lhs.1).into()), + name: Ident::new(lhs.0, DUMMY_SP, lhs.1).into(), init: Some(Box::new(init)), definite: false, } @@ -184,11 +184,12 @@ impl IntoParallelIterator for T where T: IntoIterator {} fn metadata(key: &str, value: &str) -> PropOrSpread { PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(IdentName::new(key.into(), DUMMY_SP)), - value: Box::new(Expr::Lit(Lit::Str(Str { + value: Lit::Str(Str { span: DUMMY_SP, value: value.into(), raw: None, - }))), + }) + .into(), }))) } diff --git a/crates/swc_ecma_ast/src/expr.rs b/crates/swc_ecma_ast/src/expr.rs index e302ac6f89a..489daa80759 100644 --- a/crates/swc_ecma_ast/src/expr.rs +++ b/crates/swc_ecma_ast/src/expr.rs @@ -302,10 +302,11 @@ impl Expr { if exprs.len() == 1 { exprs.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - })) + } + .into() } } @@ -418,7 +419,7 @@ impl Clone for Expr { impl Take for Expr { fn dummy() -> Self { - Expr::Invalid(Invalid { span: DUMMY_SP }) + Invalid { span: DUMMY_SP }.into() } } @@ -469,12 +470,14 @@ boxed_expr!(JSXEmptyExpr); boxed_expr!(Box); boxed_expr!(JSXFragment); boxed_expr!(TsTypeAssertion); +boxed_expr!(TsSatisfiesExpr); boxed_expr!(TsConstAssertion); boxed_expr!(TsNonNullExpr); boxed_expr!(TsAsExpr); boxed_expr!(TsInstantiation); boxed_expr!(PrivateName); boxed_expr!(OptChainExpr); +boxed_expr!(Invalid); #[ast_node("ThisExpression")] #[derive(Eq, Hash, Copy, EqIgnoreSpan)] @@ -567,7 +570,7 @@ impl From for ObjectLit { .map(|item| { PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(item.key), - value: Box::new(Expr::Lit(Lit::Str(item.value))), + value: Lit::Str(item.value).into(), }))) }) .collect(), @@ -1387,7 +1390,7 @@ impl TryFrom for AssignTarget { Pat::Expr(e) => match Self::try_from(e) { Ok(v) => v, - Err(e) => return Err(Pat::Expr(e)), + Err(e) => return Err(e.into()), }, _ => return Err(p), @@ -1437,9 +1440,9 @@ impl Default for AssignTargetPat { impl From for Pat { fn from(pat: AssignTargetPat) -> Self { match pat { - AssignTargetPat::Array(a) => Pat::Array(a), - AssignTargetPat::Object(o) => Pat::Object(o), - AssignTargetPat::Invalid(i) => Pat::Invalid(i), + AssignTargetPat::Array(a) => a.into(), + AssignTargetPat::Object(o) => o.into(), + AssignTargetPat::Invalid(i) => i.into(), } } } @@ -1551,17 +1554,17 @@ bridge_from!(AssignTarget, AssignTargetPat, ObjectPat); impl From for Box { fn from(s: SimpleAssignTarget) -> Self { match s { - SimpleAssignTarget::Ident(i) => Box::new(Expr::Ident(i.into())), - SimpleAssignTarget::Member(m) => Box::new(Expr::Member(m)), - SimpleAssignTarget::SuperProp(s) => Box::new(Expr::SuperProp(s)), - SimpleAssignTarget::Paren(s) => Box::new(Expr::Paren(s)), - SimpleAssignTarget::OptChain(s) => Box::new(Expr::OptChain(s)), - SimpleAssignTarget::TsAs(a) => Box::new(Expr::TsAs(a)), - SimpleAssignTarget::TsSatisfies(s) => Box::new(Expr::TsSatisfies(s)), - SimpleAssignTarget::TsNonNull(n) => Box::new(Expr::TsNonNull(n)), - SimpleAssignTarget::TsTypeAssertion(a) => Box::new(Expr::TsTypeAssertion(a)), - SimpleAssignTarget::TsInstantiation(a) => Box::new(Expr::TsInstantiation(a)), - SimpleAssignTarget::Invalid(i) => Box::new(Expr::Invalid(i)), + SimpleAssignTarget::Ident(i) => i.into(), + SimpleAssignTarget::Member(m) => m.into(), + SimpleAssignTarget::SuperProp(s) => s.into(), + SimpleAssignTarget::Paren(s) => s.into(), + SimpleAssignTarget::OptChain(s) => s.into(), + SimpleAssignTarget::TsAs(a) => a.into(), + SimpleAssignTarget::TsSatisfies(s) => s.into(), + SimpleAssignTarget::TsNonNull(n) => n.into(), + SimpleAssignTarget::TsTypeAssertion(a) => a.into(), + SimpleAssignTarget::TsInstantiation(a) => a.into(), + SimpleAssignTarget::Invalid(i) => i.into(), } } } diff --git a/crates/swc_ecma_ast/src/pat.rs b/crates/swc_ecma_ast/src/pat.rs index 993c7edc357..ab42072eb61 100644 --- a/crates/swc_ecma_ast/src/pat.rs +++ b/crates/swc_ecma_ast/src/pat.rs @@ -55,7 +55,7 @@ impl Clone for Pat { impl Default for Pat { fn default() -> Self { - Pat::Invalid(Invalid { span: DUMMY_SP }) + Invalid { span: DUMMY_SP }.into() } } impl Take for Pat { @@ -80,6 +80,7 @@ pat_to_other!(ArrayPat); pat_to_other!(ObjectPat); pat_to_other!(AssignPat); pat_to_other!(RestPat); +pat_to_other!(Box); #[ast_node("ArrayPattern")] #[derive(Eq, Hash, EqIgnoreSpan)] diff --git a/crates/swc_ecma_compat_bugfixes/src/edge_default_param.rs b/crates/swc_ecma_compat_bugfixes/src/edge_default_param.rs index 7e841a12e94..6164fa0f7b1 100644 --- a/crates/swc_ecma_compat_bugfixes/src/edge_default_param.rs +++ b/crates/swc_ecma_compat_bugfixes/src/edge_default_param.rs @@ -44,11 +44,12 @@ impl VisitMut for EdgeDefaultParam { { let prop = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(key.clone().into()), - value: Box::new(Pat::Assign(AssignPat { + value: AssignPat { span: *span, left: key.clone().into(), right: value.clone(), - })), + } + .into(), }); n.props[idx] = prop; 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 43d53667f65..ab2243a61c6 100644 --- a/crates/swc_ecma_compat_bugfixes/src/template_literal_caching.rs +++ b/crates/swc_ecma_compat_bugfixes/src/template_literal_caching.rs @@ -70,14 +70,17 @@ impl Fold for TemplateLiteralCaching { self.helper_ident = Some(helper_ident.clone()); self.create_binding( helper_ident, - Some(Expr::Arrow(ArrowExpr { - span: DUMMY_SP, - params: vec![t.clone().into()], - body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Ident(t)))), - is_async: false, - is_generator: false, - ..Default::default() - })), + Some( + ArrowExpr { + span: DUMMY_SP, + params: vec![t.clone().into()], + body: Box::new(BlockStmtOrExpr::Expr(t.into())), + is_async: false, + is_generator: false, + ..Default::default() + } + .into(), + ), ) } @@ -88,7 +91,7 @@ impl Fold for TemplateLiteralCaching { // the same shape. identity`a${0}` let template = TaggedTpl { span: DUMMY_SP, - tag: Box::new(Expr::Ident(helper_ident.clone())), + tag: helper_ident.clone().into(), tpl: Box::new(Tpl { span: DUMMY_SP, quasis: n.tpl.quasis, @@ -101,23 +104,25 @@ impl Fold for TemplateLiteralCaching { // _t || (_t = identity`a${0}`) let t = private_ident!("t"); self.create_binding(t.clone(), None); - let inline_cache = Expr::Bin(BinExpr { + let inline_cache: Expr = BinExpr { span: DUMMY_SP, op: op!("||"), - left: Box::new(Expr::Ident(t.clone())), - right: Box::new(Expr::Assign(AssignExpr { + left: t.clone().into(), + right: AssignExpr { span: DUMMY_SP, op: op!("="), left: t.into(), right: Box::new(Expr::TaggedTpl(template)), - })), - }); + } + .into(), + } + .into(); // The original tag function becomes a plain function call. // The expressions omitted from the cached Strings tag are // directly applied as arguments. // tag(_t || (_t = Object`a${0}`), 'hello') - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: n.tag.as_callee(), args: vec![inline_cache.as_arg()] @@ -125,7 +130,8 @@ impl Fold for TemplateLiteralCaching { .chain(n.tpl.exprs.into_iter().map(|expr| expr.as_arg())) .collect(), ..Default::default() - }) + } + .into() } _ => n, } 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 64429a0276d..03d93142fd5 100644 --- a/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs +++ b/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs @@ -267,10 +267,11 @@ impl BlockScoping { } if !inits.is_empty() { - call = Expr::Seq(SeqExpr { + call = SeqExpr { span: DUMMY_SP, exprs: inits.into_iter().chain(once(Box::new(call))).collect(), - }) + } + .into() } if flow_helper.has_return || flow_helper.has_break || !flow_helper.label.is_empty() { @@ -297,7 +298,7 @@ impl BlockScoping { stmts.push( IfStmt { span: DUMMY_SP, - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, op: op!("==="), left: { @@ -314,7 +315,8 @@ impl BlockScoping { }, //"object" right: "object".into(), - })), + } + .into(), cons: Box::new(Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some(ret.clone().make_member(quote_ident!("v")).into()), @@ -792,11 +794,14 @@ impl VisitMut for FlowHelper<'_> { }; *node = Stmt::Return(ReturnStmt { span, - arg: Some(Box::new(Expr::Lit(Lit::Str(Str { - span, - value, - raw: None, - })))), + arg: Some( + Lit::Str(Str { + span, + value, + raw: None, + }) + .into(), + ), }); } Stmt::Return(s) => { @@ -805,19 +810,24 @@ impl VisitMut for FlowHelper<'_> { *node = Stmt::Return(ReturnStmt { span, - arg: Some(Box::new(Expr::Object(ObjectLit { - span, - props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(IdentName::new("v".into(), DUMMY_SP)), - value: s.arg.take().unwrap_or_else(|| { - Box::new(Expr::Unary(UnaryExpr { - span: DUMMY_SP, - op: op!("void"), - arg: Expr::undefined(DUMMY_SP), - })) - }), - })))], - }))), + arg: Some( + ObjectLit { + span, + props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue( + KeyValueProp { + key: PropName::Ident(IdentName::new("v".into(), DUMMY_SP)), + value: s.arg.take().unwrap_or_else(|| { + Box::new(Expr::Unary(UnaryExpr { + span: DUMMY_SP, + op: op!("void"), + arg: Expr::undefined(DUMMY_SP), + })) + }), + }, + )))], + } + .into(), + ), }); } _ => node.visit_mut_children_with(self), @@ -869,19 +879,23 @@ impl MutationHandler<'_> { let mut exprs = Vec::with_capacity(self.map.len() + 1); for (id, ctxt) in &*self.map { - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: Ident::new(id.0.clone(), DUMMY_SP, id.1).into(), - op: op!("="), - right: Box::new(Expr::Ident(Ident::new(id.0.clone(), DUMMY_SP, *ctxt))), - }))); + exprs.push( + AssignExpr { + span: DUMMY_SP, + left: Ident::new(id.0.clone(), DUMMY_SP, id.1).into(), + op: op!("="), + right: Box::new(Ident::new(id.0.clone(), DUMMY_SP, *ctxt).into()), + } + .into(), + ); } exprs.push(orig.unwrap_or_else(|| Expr::undefined(DUMMY_SP))); - Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } } diff --git a/crates/swc_ecma_compat_es2015/src/classes/constructor.rs b/crates/swc_ecma_compat_es2015/src/classes/constructor.rs index 58c913a5033..ff6fd52bcbb 100644 --- a/crates/swc_ecma_compat_es2015/src/classes/constructor.rs +++ b/crates/swc_ecma_compat_es2015/src/classes/constructor.rs @@ -209,7 +209,7 @@ impl VisitMut for ConstructorFolder<'_> { { let right = match self.super_var.clone() { Some(super_var) => { - let call = Box::new(Expr::Call(CallExpr { + let call = CallExpr { span: DUMMY_SP, callee: if self.is_constructor_default { super_var.make_member(quote_ident!("apply")).as_callee() @@ -228,15 +228,17 @@ impl VisitMut for ConstructorFolder<'_> { call_args }, ..Default::default() - })); + } + .into(); if self.super_is_callable_constructor { - Box::new(Expr::Bin(BinExpr { + BinExpr { span: DUMMY_SP, left: call, op: op!("||"), - right: Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), - })) + right: Box::new(ThisExpr { span: DUMMY_SP }.into()), + } + .into() } else { call } @@ -249,12 +251,13 @@ impl VisitMut for ConstructorFolder<'_> { })), }; - *expr = Expr::Assign(AssignExpr { + *expr = AssignExpr { span: DUMMY_SP, left: quote_ident!(SyntaxContext::empty().apply_mark(self.mark), "_this").into(), op: op!("="), right, - }); + } + .into(); }; } @@ -284,7 +287,7 @@ impl VisitMut for ConstructorFolder<'_> { }) = &mut **expr { let expr = match self.super_var.clone() { - Some(super_var) => Box::new(Expr::Call(CallExpr { + Some(super_var) => CallExpr { span: DUMMY_SP, callee: if self.is_constructor_default { super_var.make_member(quote_ident!("apply")).as_callee() @@ -303,7 +306,8 @@ impl VisitMut for ConstructorFolder<'_> { call_args }, ..Default::default() - })), + } + .into(), None => Box::new(make_possible_return_value(ReturningMode::Prototype { is_constructor_default: self.is_constructor_default, class_name: self.class_name.clone(), @@ -378,7 +382,7 @@ pub(super) enum ReturningMode { pub(super) fn make_possible_return_value(mode: ReturningMode) -> Expr { let callee = helper!(possible_constructor_return); - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee, args: match mode { @@ -455,7 +459,8 @@ pub(super) fn make_possible_return_value(mode: ReturningMode) -> Expr { } }, ..Default::default() - }) + } + .into() } /// `mark`: Mark for `_this` @@ -481,14 +486,15 @@ pub(super) fn replace_this_in_constructor(mark: Mark, c: &mut Constructor) -> bo let this = quote_ident!(SyntaxContext::empty().apply_mark(self.mark), "_this"); if self.wrap_with_assertion { - *expr = Expr::Call(CallExpr { + *expr = CallExpr { span: DUMMY_SP, callee: helper!(assert_this_initialized), args: vec![this.as_arg()], ..Default::default() - }) + } + .into() } else { - *expr = Expr::Ident(this); + *expr = this.into(); } } diff --git a/crates/swc_ecma_compat_es2015/src/classes/mod.rs b/crates/swc_ecma_compat_es2015/src/classes/mod.rs index 8f1a109aba4..067e52a1fed 100644 --- a/crates/swc_ecma_compat_es2015/src/classes/mod.rs +++ b/crates/swc_ecma_compat_es2015/src/classes/mod.rs @@ -489,10 +489,11 @@ where prepend_stmt(&mut function.body.as_mut().unwrap().stmts, use_strict); } function.span = span; - return Expr::Fn(FnExpr { + return FnExpr { ident: Some(ident), function, - }); + } + .into(); } _ => unreachable!(), } @@ -519,7 +520,7 @@ where ..Default::default() }; - Expr::Call(call) + call.into() } /// Returned `stmts` contains `return Foo` @@ -714,7 +715,7 @@ where if is_always_initialized { body.push(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Ident(this))), + arg: Some(this.into()), })); } else { let possible_return_value = @@ -805,7 +806,7 @@ where // `return Foo` stmts.push(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Ident(class_name_sym))), + arg: Some(class_name_sym.into()), })); stmts @@ -890,17 +891,15 @@ where Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!(Default::default(), key.span(), "key").into()), value: match key { - PropName::Ident(i) => Box::new(Expr::Lit(Lit::Str(quote_str!(i.span, i.sym)))), - PropName::Str(s) => Box::new(Expr::from(s)), - PropName::Num(n) => Box::new(Expr::from(n)), - PropName::BigInt(b) => Box::new(Expr::Lit( - Str { - span: b.span, - raw: None, - value: b.value.to_string().into(), - } - .into(), - )), + PropName::Ident(i) => Lit::Str(quote_str!(i.span, i.sym)).into(), + PropName::Str(s) => s.into(), + PropName::Num(n) => n.into(), + PropName::BigInt(b) => Str { + span: b.span, + raw: None, + value: b.value.to_string().into(), + } + .into(), PropName::Computed(c) => c.expr, }, })) @@ -911,22 +910,20 @@ where PropName::Ident(i) => MemberProp::Ident(i), PropName::Str(s) => MemberProp::Computed(ComputedPropName { span: s.span, - expr: Box::new(Expr::Lit(Lit::Str(s))), + expr: Lit::Str(s).into(), }), PropName::Num(n) => MemberProp::Computed(ComputedPropName { span: n.span, - expr: Box::new(Expr::Lit(Lit::Num(n))), + expr: Lit::Num(n).into(), }), PropName::BigInt(b) => MemberProp::Computed(ComputedPropName { span: b.span, - expr: Box::new(Expr::Lit( - Str { - span: b.span, - raw: None, - value: b.value.to_string().into(), - } - .into(), - )), + expr: Str { + span: b.span, + raw: None, + value: b.value.to_string().into(), + } + .into(), }), PropName::Computed(c) => MemberProp::Computed(c), } @@ -936,7 +933,7 @@ where if props.is_empty() { return quote_expr!(DUMMY_SP, null).as_arg(); } - Expr::Array(ArrayLit { + ArrayLit { span: DUMMY_SP, elems: props .into_iter() @@ -969,7 +966,7 @@ where }) .map(Some) .collect(), - }) + } .as_arg() } @@ -1078,7 +1075,7 @@ where ); } - let value = Box::new(Expr::Fn(FnExpr { + let value = FnExpr { ident: if m.kind == MethodKind::Method && !computed { match prop_name { Expr::Ident(ident) => Some(private_ident!(ident.span, ident.sym)), @@ -1095,7 +1092,8 @@ where None }, function: m.function, - })); + } + .into(); let data = append_to.entry(key).or_insert_with(|| Data { key_prop, @@ -1153,7 +1151,7 @@ where let prop = *v.key_prop.clone(); res.push(Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span, op: op!("="), left: MemberExpr { @@ -1163,7 +1161,8 @@ where } .into(), right: escape_keywords(method), - })), + } + .into(), })); !(v.get.is_none() && v.set.is_none()) } else { @@ -1177,7 +1176,7 @@ where let prop = *v.key_prop.clone(); res.push(Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span, op: op!("="), left: MemberExpr { @@ -1187,7 +1186,8 @@ where } .into(), right: escape_keywords(method), - })), + } + .into(), })); !(v.get.is_none() && v.set.is_none()) } else { diff --git a/crates/swc_ecma_compat_es2015/src/computed_props.rs b/crates/swc_ecma_compat_es2015/src/computed_props.rs index 5bcb763d024..582c277606c 100644 --- a/crates/swc_ecma_compat_es2015/src/computed_props.rs +++ b/crates/swc_ecma_compat_es2015/src/computed_props.rs @@ -76,7 +76,7 @@ impl VisitMut for ComputedProps { let mark = Mark::fresh(Mark::root()); let obj_ident = quote_ident!(SyntaxContext::empty().apply_mark(mark), *span, "_obj"); - let mut exprs = Vec::with_capacity(props.len() + 2); + let mut exprs: Vec> = Vec::with_capacity(props.len() + 2); let mutator_map = quote_ident!( SyntaxContext::empty().apply_mark(mark), *span, @@ -98,20 +98,25 @@ impl VisitMut for ComputedProps { exprs.push( if !self.c.loose && props_cnt == 1 && !self.used_define_enum_props { - Box::new(Expr::Object(ObjectLit { + ObjectLit { span: DUMMY_SP, props: obj_props, - })) + } + .into() } else { - Box::new(Expr::Assign(AssignExpr { + AssignExpr { span: DUMMY_SP, left: obj_ident.clone().into(), op: op!("="), - right: Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props: obj_props, - })), - })) + right: Box::new( + ObjectLit { + span: DUMMY_SP, + props: obj_props, + } + .into(), + ), + } + .into() }, ); @@ -125,17 +130,18 @@ impl VisitMut for ComputedProps { Prop::Shorthand(ident) => ( ( if self.c.loose { - Expr::Ident(ident.clone()) + ident.clone().into() } else { - Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: ident.span, raw: None, value: ident.sym.clone(), - })) + }) + .into() }, false, ), - Expr::Ident(ident), + ident.into(), ), Prop::KeyValue(KeyValueProp { key, value }) => { (prop_name_to_expr(key, self.c.loose), *value) @@ -193,55 +199,71 @@ impl VisitMut for ComputedProps { .computed_member(prop_name_to_expr(key, false).0); // mutator[f] = mutator[f] || {} - exprs.push(Box::new(Expr::Assign(AssignExpr { - span, - left: mutator_elem.clone().into(), - op: op!("="), - right: Box::new(Expr::Bin(BinExpr { + exprs.push( + AssignExpr { span, left: mutator_elem.clone().into(), - op: op!("||"), - right: Box::new(Expr::Object(ObjectLit { - span, - props: vec![], - })), - })), - }))); + op: op!("="), + right: Box::new( + BinExpr { + span, + left: mutator_elem.clone().into(), + op: op!("||"), + right: Box::new(Expr::Object(ObjectLit { + span, + props: vec![], + })), + } + .into(), + ), + } + .into(), + ); // mutator[f].get = function(){} - exprs.push(Box::new(Expr::Assign(AssignExpr { - span, - left: mutator_elem - .make_member(quote_ident!(gs_prop_name.unwrap())) - .into(), - op: op!("="), - right: Box::new(Expr::Fn(FnExpr { - ident: None, - function, - })), - }))); + exprs.push( + AssignExpr { + span, + left: mutator_elem + .make_member(quote_ident!(gs_prop_name.unwrap())) + .into(), + op: op!("="), + right: Box::new( + FnExpr { + ident: None, + function, + } + .into(), + ), + } + .into(), + ); continue; // unimplemented!("getter /setter property") } Prop::Method(MethodProp { key, function }) => ( prop_name_to_expr(key, self.c.loose), - Expr::Fn(FnExpr { + FnExpr { ident: None, function, - }), + } + .into(), ), }, PropOrSpread::Spread(..) => unimplemented!("computed spread property"), }; if !self.c.loose && props_cnt == 1 { - single_cnt_prop = Some(Expr::Call(CallExpr { - span, - callee: helper!(define_property), - args: vec![exprs.pop().unwrap().as_arg(), key.as_arg(), value.as_arg()], - ..Default::default() - })); + single_cnt_prop = Some( + CallExpr { + span, + callee: helper!(define_property), + args: vec![exprs.pop().unwrap().as_arg(), key.as_arg(), value.as_arg()], + ..Default::default() + } + .into(), + ); break; } exprs.push(if self.c.loose { @@ -250,19 +272,21 @@ impl VisitMut for ComputedProps { } else { obj_ident.clone().make_member(key.ident().unwrap().into()) }; - Box::new(Expr::Assign(AssignExpr { + AssignExpr { span, op: op!("="), left: left.into(), right: value.into(), - })) + } + .into() } else { - Box::new(Expr::Call(CallExpr { + CallExpr { span, callee: helper!(define_property), args: vec![obj_ident.clone().as_arg(), key.as_arg(), value.as_arg()], ..Default::default() - })) + } + .into() }); } @@ -281,26 +305,33 @@ impl VisitMut for ComputedProps { self.vars.push(VarDeclarator { span: DUMMY_SP, name: mutator_map.clone().into(), - init: Some(Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props: vec![], - }))), + init: Some( + ObjectLit { + span: DUMMY_SP, + props: vec![], + } + .into(), + ), definite: false, }); - exprs.push(Box::new(Expr::Call(CallExpr { - span: *span, - callee: helper!(define_enumerable_properties), - args: vec![obj_ident.clone().as_arg(), mutator_map.as_arg()], - ..Default::default() - }))); + exprs.push( + CallExpr { + span: *span, + callee: helper!(define_enumerable_properties), + args: vec![obj_ident.clone().as_arg(), mutator_map.as_arg()], + ..Default::default() + } + .into(), + ); } // Last value - exprs.push(Box::new(Expr::Ident(obj_ident))); - *expr = Expr::Seq(SeqExpr { + exprs.push(obj_ident.into()); + *expr = SeqExpr { span: DUMMY_SP, exprs, - }); + } + .into(); }; } @@ -380,19 +411,20 @@ fn prop_name_to_expr(p: PropName, loose: bool) -> (Expr, bool) { match p { PropName::Ident(i) => ( if loose { - Expr::Ident(i.into()) + i.into() } else { - Expr::Lit(Lit::Str(Str { + Lit::Str(Str { raw: None, value: i.sym, span: i.span, - })) + }) + .into() }, false, ), - PropName::Str(s) => (Expr::Lit(Lit::Str(s)), true), - PropName::Num(n) => (Expr::Lit(Lit::Num(n)), true), - PropName::BigInt(b) => (Expr::Lit(Lit::BigInt(b)), true), + PropName::Str(s) => (Lit::Str(s).into(), true), + PropName::Num(n) => (Lit::Num(n).into(), true), + PropName::BigInt(b) => (Lit::BigInt(b).into(), true), PropName::Computed(c) => (*c.expr, true), } } diff --git a/crates/swc_ecma_compat_es2015/src/destructuring.rs b/crates/swc_ecma_compat_es2015/src/destructuring.rs index 6b8408cb3cc..b0a58a8492d 100644 --- a/crates/swc_ecma_compat_es2015/src/destructuring.rs +++ b/crates/swc_ecma_compat_es2015/src/destructuring.rs @@ -178,13 +178,16 @@ impl AssignFolder { VarDeclarator { span: p.span(), name: *p.arg, - init: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: arr_elems - .take() - .expect("two rest element?") - .collect(), - }))), + init: Some( + ArrayLit { + span: DUMMY_SP, + elems: arr_elems + .take() + .expect("two rest element?") + .collect(), + } + .into(), + ), definite: false, }, ); @@ -249,20 +252,23 @@ impl AssignFolder { }) => VarDeclarator { span: dot3_token, name: *arg, - init: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: ref_ident - .clone() - .make_member(quote_ident!("slice")) - .as_callee(), - args: vec![Number { - value: i as f64, - span: dot3_token, - raw: None, + init: Some( + CallExpr { + span: DUMMY_SP, + callee: ref_ident + .clone() + .make_member(quote_ident!("slice")) + .as_callee(), + args: vec![Number { + value: i as f64, + span: dot3_token, + raw: None, + } + .as_arg()], + ..Default::default() } - .as_arg()], - ..Default::default() - }))), + .into(), + ), definite: false, }, _ => VarDeclarator { @@ -339,7 +345,7 @@ impl AssignFolder { let ref_ident = make_ref_ident(self.c, ref_decls, decl.init); let ref_ident = if can_be_null { - let init = Box::new(Expr::Ident(ref_ident)); + let init = ref_ident.into(); make_ref_ident(self.c, ref_decls, Some(init)) } else { ref_ident @@ -507,7 +513,7 @@ impl Destructuring { decls.push(VarDeclarator { span, name: param.pat, - init: Some(Box::new(Expr::Ident(ref_ident))), + init: Some(ref_ident.into()), definite: false, }) } @@ -570,20 +576,22 @@ impl AssignFolder { .into(), )]; - let mut assign_cond_expr = Expr::Assign(AssignExpr { + let mut assign_cond_expr: Expr = AssignExpr { span, left: pat.left.take().try_into().unwrap(), op: op!("="), right: Box::new(make_cond_expr(ref_ident, pat.right.take())), - }); + } + .into(); assign_cond_expr.visit_mut_with(self); exprs.push(Box::new(assign_cond_expr)); - Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } } @@ -662,18 +670,24 @@ impl VisitMut for AssignFolder { let mut arr_elems = Some(arr.elems.take().into_iter()); elems.iter_mut().for_each(|p| match p { Some(Pat::Rest(p)) => { - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: p.span(), - left: p.arg.take().try_into().unwrap(), - op: op!("="), - right: Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: arr_elems - .take() - .expect("two rest element?") - .collect(), - })), - }))); + exprs.push( + AssignExpr { + span: p.span(), + left: p.arg.take().try_into().unwrap(), + op: op!("="), + right: Box::new( + ArrayLit { + span: DUMMY_SP, + elems: arr_elems + .take() + .expect("two rest element?") + .collect(), + } + .into(), + ), + } + .into(), + ); } Some(p) => { let e = arr_elems @@ -692,12 +706,13 @@ impl VisitMut for AssignFolder { let mut expr = if let Pat::Assign(pat) = p { self.handle_assign_pat(*span, pat, &mut right) } else { - Expr::Assign(AssignExpr { + AssignExpr { span: p.span(), left: p.try_into().unwrap(), op: op!("="), right, - }) + } + .into() }; self.visit_mut_expr(&mut expr); @@ -730,57 +745,68 @@ impl VisitMut for AssignFolder { elems.len() }), ); - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: ref_ident.clone().into(), - right: if self.c.loose { - right.take() - } else { - match &mut **right { - Expr::Ident(Ident { sym, .. }) if &**sym == "arguments" => { - Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: member_expr!( - Default::default(), - Default::default(), - Array.prototype.slice.call - ) - .as_callee(), - args: vec![right.take().as_arg()], - ..Default::default() - })) - } - Expr::Array(..) => right.take(), - _ => { - // if left has rest then need `_to_array` - // else `_sliced_to_array` - if elems.iter().any(|elem| matches!(elem, Some(Pat::Rest(..)))) - { - Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: helper!(to_array), - args: vec![right.take().as_arg()], - ..Default::default() - })) - } else { + exprs.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: ref_ident.clone().into(), + right: if self.c.loose { + right.take() + } else { + match &mut **right { + Expr::Ident(Ident { sym, .. }) if &**sym == "arguments" => { Box::new( CallExpr { span: DUMMY_SP, - callee: helper!(sliced_to_array), - args: vec![ - right.take().as_arg(), - elems.len().as_arg(), - ], + callee: member_expr!( + Default::default(), + Default::default(), + Array.prototype.slice.call + ) + .as_callee(), + args: vec![right.take().as_arg()], ..Default::default() } .into(), ) } + Expr::Array(..) => right.take(), + _ => { + // if left has rest then need `_to_array` + // else `_sliced_to_array` + if elems + .iter() + .any(|elem| matches!(elem, Some(Pat::Rest(..)))) + { + Box::new( + CallExpr { + span: DUMMY_SP, + callee: helper!(to_array), + args: vec![right.take().as_arg()], + ..Default::default() + } + .into(), + ) + } else { + Box::new( + CallExpr { + span: DUMMY_SP, + callee: helper!(sliced_to_array), + args: vec![ + right.take().as_arg(), + elems.len().as_arg(), + ], + ..Default::default() + } + .into(), + ) + } + } } - } - }, - }))); + }, + } + .into(), + ); for (i, elem) in elems.iter_mut().enumerate() { let elem = match elem { @@ -795,29 +821,33 @@ impl VisitMut for AssignFolder { }) => { // initialized by sequence expression. let assign_ref_ident = make_ref_ident(self.c, &mut self.vars, None); - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: assign_ref_ident.clone().into(), - op: op!("="), - right: ref_ident.clone().computed_member(i as f64).into(), - }))); + exprs.push( + AssignExpr { + span: DUMMY_SP, + left: assign_ref_ident.clone().into(), + op: op!("="), + right: ref_ident.clone().computed_member(i as f64).into(), + } + .into(), + ); - let mut assign_expr = Expr::Assign(AssignExpr { + let mut assign_expr: Expr = AssignExpr { span: *span, left: left.take().try_into().unwrap(), op: op!("="), right: Box::new(make_cond_expr(assign_ref_ident, right.take())), - }); + } + .into(); assign_expr.visit_mut_with(self); exprs.push(Box::new(assign_expr)); } Pat::Rest(RestPat { arg, .. }) => { - let mut assign_expr = Expr::Assign(AssignExpr { + let mut assign_expr: Expr = AssignExpr { span: elem_span, op: op!("="), left: arg.take().try_into().unwrap(), - right: Box::new(Expr::Call(CallExpr { + right: CallExpr { span: DUMMY_SP, callee: ref_ident .clone() @@ -825,19 +855,22 @@ impl VisitMut for AssignFolder { .as_callee(), args: vec![(i as f64).as_arg()], ..Default::default() - })), - }); + } + .into(), + } + .into(); assign_expr.visit_mut_with(self); exprs.push(Box::new(assign_expr)); } _ => { - let mut assign_expr = Expr::Assign(AssignExpr { + let mut assign_expr: Expr = AssignExpr { span: elem_span, op: op!("="), left: elem.take().try_into().unwrap(), right: make_ref_idx_expr(&ref_ident, i).into(), - }); + } + .into(); assign_expr.visit_mut_with(self); exprs.push(Box::new(assign_expr)) @@ -846,12 +879,13 @@ impl VisitMut for AssignFolder { } // last one should be `ref` - exprs.push(Box::new(Expr::Ident(ref_ident))); + exprs.push(ref_ident.into()); - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } AssignTargetPat::Object(ObjectPat { props, .. }) if props.is_empty() => { let mut right = right.take(); @@ -865,12 +899,13 @@ impl VisitMut for AssignFolder { if let ObjectPatProp::Assign(p @ AssignPatProp { value: None, .. }) = &props[0] { - *expr = Expr::Assign(AssignExpr { + *expr = AssignExpr { span: *span, op: op!("="), left: p.key.clone().into(), right: right.take().make_member(p.key.clone().into()).into(), - }); + } + .into(); return; } } @@ -900,12 +935,13 @@ impl VisitMut for AssignFolder { let mut expr = if let Pat::Assign(pat) = *value { self.handle_assign_pat(span, pat, &mut right) } else { - Expr::Assign(AssignExpr { + AssignExpr { span, left: value.try_into().unwrap(), op: op!("="), right, - }) + } + .into() }; expr.visit_mut_with(self); @@ -919,38 +955,47 @@ impl VisitMut for AssignFolder { let prop_ident = make_ref_ident(self.c, &mut self.vars, None); - exprs.push(Box::new(Expr::Assign(AssignExpr { - span, - left: prop_ident.clone().into(), - op: op!("="), - right: Box::new(make_ref_prop_expr( - &ref_ident, - key.clone().into(), - computed, - )), - }))); + exprs.push( + AssignExpr { + span, + left: prop_ident.clone().into(), + op: op!("="), + right: Box::new(make_ref_prop_expr( + &ref_ident, + key.clone().into(), + computed, + )), + } + .into(), + ); - exprs.push(Box::new(Expr::Assign(AssignExpr { - span, - left: key.clone().into(), - op: op!("="), - right: Box::new(make_cond_expr( - prop_ident, - value.take(), - )), - }))); + exprs.push( + AssignExpr { + span, + left: key.clone().into(), + op: op!("="), + right: Box::new(make_cond_expr( + prop_ident, + value.take(), + )), + } + .into(), + ); } None => { - exprs.push(Box::new(Expr::Assign(AssignExpr { - span, - left: key.clone().into(), - op: op!("="), - right: Box::new(make_ref_prop_expr( - &ref_ident, - key.clone().into(), - computed, - )), - }))); + exprs.push( + AssignExpr { + span, + left: key.clone().into(), + op: op!("="), + right: Box::new(make_ref_prop_expr( + &ref_ident, + key.clone().into(), + computed, + )), + } + .into(), + ); } } } @@ -962,12 +1007,13 @@ impl VisitMut for AssignFolder { } // Last one should be object itself. - exprs.push(Box::new(Expr::Ident(ref_ident))); + exprs.push(ref_ident.into()); - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, exprs, - }); + } + .into(); } AssignTargetPat::Invalid(..) => unreachable!(), @@ -1161,7 +1207,7 @@ fn make_ref_ident_for_array( fn make_ref_prop_expr(ref_ident: &Ident, prop: Box, mut computed: bool) -> Expr { computed |= matches!(*prop, Expr::Lit(Lit::Num(..)) | Expr::Lit(Lit::Str(..))); - Expr::Member(MemberExpr { + MemberExpr { span: DUMMY_SP, obj: Box::new(ref_ident.clone().into()), prop: if computed { @@ -1172,14 +1218,15 @@ fn make_ref_prop_expr(ref_ident: &Ident, prop: Box, mut computed: bool) -> } else { MemberProp::Ident(prop.ident().unwrap().into()) }, - }) + } + .into() } /// Creates `tmp === void 0 ? def_value : tmp` fn make_cond_expr(tmp: Ident, def_value: Box) -> Expr { - Expr::Cond(CondExpr { + CondExpr { span: DUMMY_SP, - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, left: Box::new(Expr::Ident(tmp.clone())), op: op!("==="), @@ -1188,10 +1235,12 @@ fn make_cond_expr(tmp: Ident, def_value: Box) -> Expr { op: op!("void"), arg: 0.0.into(), })), - })), + } + .into(), cons: def_value, - alt: Box::new(Expr::Ident(tmp)), - }) + alt: tmp.into(), + } + .into() } fn can_be_null(e: &Expr) -> bool { diff --git a/crates/swc_ecma_compat_es2015/src/duplicate_keys.rs b/crates/swc_ecma_compat_es2015/src/duplicate_keys.rs index 9f99cde890c..5a037bd5be3 100644 --- a/crates/swc_ecma_compat_es2015/src/duplicate_keys.rs +++ b/crates/swc_ecma_compat_es2015/src/duplicate_keys.rs @@ -59,7 +59,7 @@ impl VisitMut for PropFolder { span: ident.span, expr: quote_str!(ident.sym.clone()).into(), }), - value: Box::new(Expr::Ident(ident.clone())), + value: ident.clone().into(), }) } } @@ -102,11 +102,12 @@ impl<'a> VisitMut for PropNameFolder<'a> { if !self.props.insert(ident.sym.clone()) { *name = PropName::Computed(ComputedPropName { span, - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span, raw: None, value: ident.sym.clone(), - }))), + }) + .into(), }) } } diff --git a/crates/swc_ecma_compat_es2015/src/for_of.rs b/crates/swc_ecma_compat_es2015/src/for_of.rs index 5178deea7aa..45ce8a4a196 100644 --- a/crates/swc_ecma_compat_es2015/src/for_of.rs +++ b/crates/swc_ecma_compat_es2015/src/for_of.rs @@ -100,18 +100,24 @@ impl ForOf { let i = private_ident!("_i"); - let test = Some(Box::new(Expr::Bin(BinExpr { - span: DUMMY_SP, - left: Box::new(Expr::Ident(i.clone())), - op: op!("<"), - right: arr.clone().make_member(quote_ident!("length")).into(), - }))); - let update = Some(Box::new(Expr::Update(UpdateExpr { - span: DUMMY_SP, - prefix: false, - op: op!("++"), - arg: Box::new(Expr::Ident(i.clone())), - }))); + let test = Some( + BinExpr { + span: DUMMY_SP, + left: Box::new(i.clone().into()), + op: op!("<"), + right: arr.clone().make_member(quote_ident!("length")).into(), + } + .into(), + ); + let update = Some( + UpdateExpr { + span: DUMMY_SP, + prefix: false, + op: op!("++"), + arg: Box::new(i.clone().into()), + } + .into(), + ); let mut decls = Vec::with_capacity(2); decls.push(VarDeclarator { @@ -281,7 +287,7 @@ impl ForOf { } // !(_step = _iterator()).done; - let test = Box::new(Expr::Unary(UnaryExpr { + let test = UnaryExpr { span: DUMMY_SP, op: op!("!"), arg: AssignExpr { @@ -298,7 +304,8 @@ impl ForOf { } .make_member(quote_ident!("done")) .into(), - })); + } + .into(); let stmt = Stmt::For(ForStmt { span, @@ -393,10 +400,7 @@ impl ForOf { self.top_level_vars.push(VarDeclarator { span: DUMMY_SP, name: error_ident.clone().into(), - init: Some(Box::new(Expr::Ident(Ident::new_no_ctxt( - "undefined".into(), - DUMMY_SP, - )))), + init: Some(Ident::new_no_ctxt("undefined".into(), DUMMY_SP).into()), definite: false, }); @@ -437,40 +441,50 @@ impl ForOf { .into(), ), // !(_iteratorNormalCompletion = (_step = _iterator.next()).done) - test: Some(Box::new(Expr::Unary(UnaryExpr { - span: DUMMY_SP, - op: op!("!"), - arg: { - let step_expr = Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: step.into(), - op: op!("="), - // `_iterator.next()` - right: Box::new(Expr::Call(CallExpr { + test: Some( + UnaryExpr { + span: DUMMY_SP, + op: op!("!"), + arg: { + let step_expr: Expr = AssignExpr { span: DUMMY_SP, - // `_iterator.next` - callee: iterator.make_member(quote_ident!("next")).as_callee(), - args: vec![], - ..Default::default() - })), - })); + left: step.into(), + op: op!("="), + // `_iterator.next()` + right: Box::new(Expr::Call(CallExpr { + span: DUMMY_SP, + // `_iterator.next` + callee: iterator.make_member(quote_ident!("next")).as_callee(), + args: vec![], + ..Default::default() + })), + } + .into(); - Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: normal_completion_ident.clone().into(), - op: op!("="), - right: step_expr.make_member(quote_ident!("done")).into(), - })) - }, - }))), + Box::new( + AssignExpr { + span: DUMMY_SP, + left: normal_completion_ident.clone().into(), + op: op!("="), + right: step_expr.make_member(quote_ident!("done")).into(), + } + .into(), + ) + }, + } + .into(), + ), // `_iteratorNormalCompletion = true` - update: Some(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: normal_completion_ident.clone().into(), - op: op!("="), - right: true.into(), - }))), + update: Some( + AssignExpr { + span: DUMMY_SP, + left: normal_completion_ident.clone().into(), + op: op!("="), + right: true.into(), + } + .into(), + ), body: Box::new(Stmt::Block(body)), } .into(); diff --git a/crates/swc_ecma_compat_es2015/src/function_name.rs b/crates/swc_ecma_compat_es2015/src/function_name.rs index d331de05b12..ab313894661 100644 --- a/crates/swc_ecma_compat_es2015/src/function_name.rs +++ b/crates/swc_ecma_compat_es2015/src/function_name.rs @@ -76,12 +76,13 @@ impl VisitMut for FnName { if let Expr::Fn(expr @ FnExpr { ident: None, .. }) = &mut *p.value { // p.value = if let PropName::Ident(ref i) = p.key { - Box::new(Expr::Fn(FnExpr { + FnExpr { ident: Some(prepare(i.clone().into())), ..expr.take() - })) + } + .into() } else { - Box::new(Expr::Fn(expr.take())) + expr.take().into() }; }; } diff --git a/crates/swc_ecma_compat_es2015/src/generator.rs b/crates/swc_ecma_compat_es2015/src/generator.rs index 19e666223b8..b430f6add8c 100644 --- a/crates/swc_ecma_compat_es2015/src/generator.rs +++ b/crates/swc_ecma_compat_es2015/src/generator.rs @@ -85,7 +85,7 @@ impl VisitMut for Wrapper { is_async: false, ..Default::default() }); - let generator_object = Box::new(Expr::Call(CallExpr { + let generator_object = CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_generator), args: vec![ @@ -97,7 +97,8 @@ impl VisitMut for Wrapper { .as_arg(), ], ..Default::default() - })); + } + .into(); let mut stmts = vec![]; if !v.hoisted_vars.is_empty() { stmts.push( @@ -494,7 +495,7 @@ impl VisitMut for Generator { self.mark_label(result_label); - *e = Expr::Ident(result_local); + *e = result_local.into(); } else { node.visit_mut_with(self); } @@ -528,10 +529,11 @@ impl VisitMut for Generator { expr: if pending_expressions.len() == 1 { pending_expressions.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs: pending_expressions.take(), - })) + } + .into() }, })))), None, @@ -565,7 +567,7 @@ impl VisitMut for Generator { // .mark resumeLabel // a = _a[%sent%] - *obj = Box::new(Expr::Ident(self.cache_expression(obj.take()))); + *obj = self.cache_expression(obj.take()).into(); prop.visit_mut_with(self); return; } @@ -590,7 +592,7 @@ impl VisitMut for Generator { left.obj.visit_mut_with(self); let obj = self.cache_expression(left.obj.take()); - left.obj = Box::new(Expr::Ident(obj)); + left.obj = obj.into(); } MemberProp::Computed(prop) => { // [source] @@ -611,10 +613,10 @@ impl VisitMut for Generator { prop.visit_mut_with(self); let prop = self.cache_expression(prop.expr.take()); - left.obj = Box::new(Expr::Ident(obj)); + left.obj = obj.into(); left.prop = MemberProp::Computed(ComputedPropName { span: prop_span, - expr: Box::new(Expr::Ident(prop)), + expr: prop.into(), }); } } @@ -630,12 +632,13 @@ impl VisitMut for Generator { node.right.visit_mut_with(self); - *e = Expr::Assign(AssignExpr { + *e = AssignExpr { span: node.right.span(), op: node.op, left: left_of_right.into(), right: node.right.take(), - }); + } + .into(); } else { node.right.visit_mut_with(self); } @@ -672,7 +675,7 @@ impl VisitMut for Generator { self.emit_assignment( temp.clone().into(), - Box::new(Expr::Object(ObjectLit { + ObjectLit { span: DUMMY_SP, props: node .props @@ -680,7 +683,8 @@ impl VisitMut for Generator { .take(num_initial_properties) .map(|v| v.take()) .collect(), - })), + } + .into(), None, ); @@ -736,7 +740,7 @@ impl VisitMut for Generator { self.reduce_property(exprs, property, &mut temp) }); - expressions.push(Box::new(Expr::Ident(temp))); + expressions.push(temp.into()); *e = *Expr::from_exprs(expressions); } @@ -821,7 +825,7 @@ impl VisitMut for Generator { None }; - let apply = Expr::Ident(callee).apply( + let apply = callee.apply( node.span, this_arg, arg.take().map(|v| v.as_arg()).into_iter().collect(), @@ -863,10 +867,11 @@ impl VisitMut for Generator { Some(VarDeclOrExpr::Expr(if exprs.len() == 1 { exprs.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - })) + } + .into() })) }; node.test.visit_mut_with(self); @@ -1030,10 +1035,11 @@ impl VisitMut for Generator { expr: if exprs.len() == 1 { exprs.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - })) + } + .into() }, }); } @@ -1082,7 +1088,7 @@ impl Generator { self.emit_assignment( temp.clone().unwrap().into(), - Box::new(Expr::Array(ArrayLit { + ArrayLit { span: DUMMY_SP, elems: leading_element .take() @@ -1095,7 +1101,8 @@ impl Generator { .map(|e| e.take()), ) .collect(), - })), + } + .into(), None, ); } @@ -1109,7 +1116,7 @@ impl Generator { }); if let Some(temp) = temp { - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: temp.make_member(quote_ident!("concat")).as_callee(), args: vec![ExprOrSpread { @@ -1120,9 +1127,10 @@ impl Generator { })), }], ..Default::default() - }) + } + .into() } else { - Expr::Array(ArrayLit { + ArrayLit { span: DUMMY_SP, elems: leading_element .take() @@ -1130,7 +1138,8 @@ impl Generator { .map(Some) .chain(expressions) .collect(), - }) + } + .into() } } @@ -1150,7 +1159,7 @@ impl Generator { self.emit_assignment( temp.clone().unwrap().into(), if has_assigned_temp { - Box::new(Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: temp .clone() @@ -1163,7 +1172,8 @@ impl Generator { })) .as_arg()], ..Default::default() - })) + } + .into() } else { Box::new( ArrayLit { @@ -1209,47 +1219,50 @@ impl Generator { })); } - let mut expression = match property { + let mut expression: Expr = match property { CompiledProp::Prop(p) => match p { - Prop::Shorthand(p) => Expr::Assign(AssignExpr { + Prop::Shorthand(p) => AssignExpr { span: p.span, op: op!("="), left: MemberExpr { span: DUMMY_SP, - obj: Box::new(Expr::Ident(temp.clone())), + obj: temp.clone().into(), prop: MemberProp::Ident(p.clone().into()), } .into(), - right: Box::new(Expr::Ident(p)), - }), - Prop::KeyValue(p) => Expr::Assign(AssignExpr { + right: p.into(), + } + .into(), + Prop::KeyValue(p) => AssignExpr { span: DUMMY_SP, op: op!("="), left: MemberExpr { span: DUMMY_SP, - obj: Box::new(Expr::Ident(temp.clone())), + obj: temp.clone().into(), prop: p.key.into(), } .into(), right: p.value, - }), + } + .into(), Prop::Assign(_) => { unreachable!("assignment property be removed before generator pass") } Prop::Getter(_) | Prop::Setter(_) => { unreachable!("getter/setter property be compiled as CompiledProp::Accessor") } - Prop::Method(p) => Expr::Assign(AssignExpr { + Prop::Method(p) => AssignExpr { span: DUMMY_SP, op: op!("="), left: MemberExpr { span: DUMMY_SP, - obj: Box::new(Expr::Ident(temp.clone())), + obj: temp.clone().into(), prop: p.key.into(), } .into(), right: p.function.into(), - }), + } + .into(), }, CompiledProp::Accessor(getter, setter) => { let key = getter @@ -1293,7 +1306,7 @@ impl Generator { .collect(), }; - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: helper!(define_property), args: vec![ @@ -1302,7 +1315,8 @@ impl Generator { desc.as_arg(), ], ..Default::default() - }) + } + .into() } }; @@ -1329,7 +1343,7 @@ impl Generator { // _a + %sent% + c() node.left.visit_mut_with(self); - node.left = Box::new(Expr::Ident(self.cache_expression(node.left.take()))); + node.left = self.cache_expression(node.left.take()).into(); node.right.visit_mut_with(self); return None; } @@ -1404,7 +1418,7 @@ impl Generator { ); self.mark_label(result_label); - Expr::Ident(result_local) + result_local.into() } fn transform_and_emit_stmts(&mut self, stmts: Vec, start: usize) { @@ -1509,10 +1523,11 @@ impl Generator { expr: if pending_expressions.len() == 1 { pending_expressions.pop().unwrap() } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs: take(&mut pending_expressions), - })) + } + .into() }, })) } @@ -1748,7 +1763,7 @@ impl Generator { right: node.right.take(), body: Box::new(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span: DUMMY_SP, callee: keys_array .clone() @@ -1756,7 +1771,8 @@ impl Generator { .as_callee(), args: vec![key.as_arg()], ..Default::default() - })), + } + .into(), })), })); @@ -1797,14 +1813,15 @@ impl Generator { }; self.emit_assignment( variable.try_into().unwrap(), - Box::new(Expr::Member(MemberExpr { + MemberExpr { span: DUMMY_SP, obj: Box::new(keys_array.into()), prop: MemberProp::Computed(ComputedPropName { span: DUMMY_SP, expr: Box::new(keys_index.clone().into()), }), - })), + } + .into(), None, ); self.transform_and_emit_embedded_stmt(*node.body); @@ -1812,12 +1829,13 @@ impl Generator { self.mark_label(increment_label); self.emit_stmt(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Update(UpdateExpr { + expr: UpdateExpr { span: DUMMY_SP, prefix: false, op: op!("++"), arg: Box::new(keys_index.clone().into()), - })), + } + .into(), })); self.emit_break(condition_label, None); @@ -1966,7 +1984,7 @@ impl Generator { clauses_written += pending_clauses.len(); self.emit_stmt(Stmt::Switch(SwitchStmt { span: DUMMY_SP, - discriminant: Box::new(Expr::Ident(expression.clone())), + discriminant: expression.clone().into(), cases: take(&mut pending_clauses), })); } @@ -2302,7 +2320,7 @@ impl Generator { self.emit_assignment( name.clone().into(), - Box::new(Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: self .state @@ -2311,7 +2329,8 @@ impl Generator { .as_callee(), args: vec![], ..Default::default() - })), + } + .into(), None, ); @@ -2594,9 +2613,10 @@ impl Generator { .unwrap() .push(expr); } - return Box::new(Expr::Invalid(Invalid { + return Invalid { span: Span::new(BytePos(label.0 as _), BytePos(label.0 as _)), - })); + } + .into(); } } @@ -2631,10 +2651,13 @@ impl Generator { ]; ReturnStmt { span: span.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: args, - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: args, + } + .into(), + ), } } @@ -2645,22 +2668,25 @@ impl Generator { fn create_inline_return(&mut self, expr: Option>, loc: Option) -> ReturnStmt { ReturnStmt { span: loc.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: match expr { - Some(expr) => vec![ - Some(self.create_instruction(Instruction::Return).as_arg()), - Some(expr.as_arg()), - ], - None => vec![Some(self.create_instruction(Instruction::Return).as_arg())], - }, - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: match expr { + Some(expr) => vec![ + Some(self.create_instruction(Instruction::Return).as_arg()), + Some(expr.as_arg()), + ], + None => vec![Some(self.create_instruction(Instruction::Return).as_arg())], + }, + } + .into(), + ), } } /// Creates an expression that can be used to resume from a Yield operation. fn create_generator_resume(&mut self, loc: Option) -> Box { - Box::new(Expr::Call(CallExpr { + CallExpr { span: loc.unwrap_or(DUMMY_SP), callee: self .state @@ -2669,7 +2695,8 @@ impl Generator { .as_callee(), args: vec![], ..Default::default() - })) + } + .into() } /// Emits an empty instruction. @@ -2976,7 +3003,7 @@ impl Generator { 0, Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span: DUMMY_SP, callee: self .state @@ -2995,7 +3022,8 @@ impl Generator { } .as_arg()], ..Default::default() - })), + } + .into(), }), ); } @@ -3007,12 +3035,13 @@ impl Generator { stmts.push(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span: DUMMY_SP, op: op!("="), left: self.state.clone().make_member(quote_ident!("label")).into(), right: (self.label_number + 1).into(), - })), + } + .into(), })); } @@ -3241,12 +3270,13 @@ impl Generator { 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: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span: DUMMY_SP, op: op!("="), left, right, - })), + } + .into(), })) } @@ -3276,17 +3306,20 @@ impl Generator { let inst = self.create_instruction(Instruction::Return); self.write_stmt(Stmt::Return(ReturnStmt { span: op_loc.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: match expr { - Some(expr) => { - vec![Some(inst.as_arg()), Some(expr.as_arg())] - } - _ => { - vec![Some(inst.as_arg())] - } - }, - }))), + 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(), + ), })) } @@ -3301,10 +3334,13 @@ impl Generator { let label = self.create_label(Some(label)); self.write_stmt(Stmt::Return(ReturnStmt { span: op_loc.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: vec![Some(inst.as_arg()), Some(label.as_arg())], - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(inst.as_arg()), Some(label.as_arg())], + } + .into(), + ), })) } @@ -3321,10 +3357,13 @@ impl Generator { test: cond, cons: Box::new(Stmt::Return(ReturnStmt { span: op_loc.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: vec![Some(inst.as_arg()), Some(label.as_arg())], - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(inst.as_arg()), Some(label.as_arg())], + } + .into(), + ), })), alt: None, })) @@ -3340,17 +3379,21 @@ impl Generator { let label = self.create_label(Some(label)); self.write_stmt(Stmt::If(IfStmt { span: DUMMY_SP, - test: Box::new(Expr::Unary(UnaryExpr { + 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(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: vec![Some(inst.as_arg()), Some(label.as_arg())], - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(inst.as_arg()), Some(label.as_arg())], + } + .into(), + ), })), alt: None, })) @@ -3374,10 +3417,13 @@ impl Generator { }; self.write_stmt(Stmt::Return(ReturnStmt { span: op_loc.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems, - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems, + } + .into(), + ), })); } @@ -3391,10 +3437,13 @@ impl Generator { let arg1 = self.create_instruction(Instruction::YieldStar); self.write_stmt(Stmt::Return(ReturnStmt { span: op_loc.unwrap_or(DUMMY_SP), - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: vec![Some(arg1.as_arg()), Some(expr.as_arg())], - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(arg1.as_arg()), Some(expr.as_arg())], + } + .into(), + ), })) } @@ -3405,10 +3454,13 @@ impl Generator { let arg = self.create_instruction(Instruction::Endfinally); self.write_stmt(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: vec![Some(arg.as_arg())], - }))), + arg: Some( + ArrayLit { + span: DUMMY_SP, + elems: vec![Some(arg.as_arg())], + } + .into(), + ), })) } @@ -3472,7 +3524,7 @@ impl Generator { let this_arg = self.create_temp_variable(); *obj = Box::new(obj.take().make_assign_to(op!("="), this_arg.clone().into())); - (callee, Box::new(Expr::Ident(this_arg))) + (callee, this_arg.into()) } _ => { @@ -3481,7 +3533,7 @@ impl Generator { } else { let this_arg = self.create_temp_variable(); let target = callee.make_assign_to(op!("="), this_arg.clone().into()); - (Box::new(target), Box::new(Expr::Ident(this_arg))) + (Box::new(target), this_arg.into()) } } } diff --git a/crates/swc_ecma_compat_es2015/src/instanceof.rs b/crates/swc_ecma_compat_es2015/src/instanceof.rs index 5808501d2ca..d0b7a257383 100644 --- a/crates/swc_ecma_compat_es2015/src/instanceof.rs +++ b/crates/swc_ecma_compat_es2015/src/instanceof.rs @@ -62,12 +62,13 @@ impl VisitMut for InstanceOf { hi: right.span_lo(), }; - *expr = Expr::Call(CallExpr { + *expr = CallExpr { span: *span, callee: helper!(instanceof_span, instanceof), args: vec![left.take().as_arg(), right.take().as_arg()], ..Default::default() - }); + } + .into(); } } } diff --git a/crates/swc_ecma_compat_es2015/src/new_target.rs b/crates/swc_ecma_compat_es2015/src/new_target.rs index f27331a24f6..e2b3b323837 100644 --- a/crates/swc_ecma_compat_es2015/src/new_target.rs +++ b/crates/swc_ecma_compat_es2015/src/new_target.rs @@ -70,19 +70,21 @@ impl VisitMut for NewTarget { Ctx::Constructor => *e = this_ctor(*span), Ctx::Method => *e = *Expr::undefined(DUMMY_SP), Ctx::Function(i) => { - *e = Expr::Cond(CondExpr { + *e = CondExpr { span: *span, // this instanceof Foo - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, op: op!("instanceof"), left: Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), right: Box::new(Expr::Ident(i.clone())), - })), + } + .into(), cons: Box::new(this_ctor(DUMMY_SP)), // void 0 alt: Expr::undefined(DUMMY_SP), - }) + } + .into() } } } diff --git a/crates/swc_ecma_compat_es2015/src/object_super.rs b/crates/swc_ecma_compat_es2015/src/object_super.rs index 5bb3fddbb46..e764a77ba17 100644 --- a/crates/swc_ecma_compat_es2015/src/object_super.rs +++ b/crates/swc_ecma_compat_es2015/src/object_super.rs @@ -114,12 +114,13 @@ impl VisitMut for ObjectSuper { } } if let Some(obj) = replacer.obj { - *expr = Expr::Assign(AssignExpr { + *expr = AssignExpr { span: DUMMY_SP, op: op!("="), left: obj.clone().into(), right: Box::new(expr.take()), - }); + } + .into(); self.extra_vars.push(obj); } } @@ -176,13 +177,13 @@ impl SuperReplacer { } fn get_proto(&mut self) -> ExprOrSpread { - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: helper!(get_prototype_of), args: vec![self.get_obj_ref().as_arg()], ..Default::default() - }) + } .as_arg() } @@ -191,11 +192,12 @@ impl SuperReplacer { match prop.take() { SuperProp::Ident(IdentName { sym: value, span, .. - }) => Box::new(Expr::Lit(Lit::Str(Str { + }) => Lit::Str(Str { raw: None, value, span, - }))), + }) + .into(), SuperProp::Computed(ComputedPropName { expr, .. }) => expr, } @@ -227,7 +229,7 @@ impl SuperReplacer { SuperReplacer::super_to_get_call(self.get_proto(), *super_token, prop.as_arg()); let this = ThisExpr { span: DUMMY_SP }.as_arg(); if args.len() == 1 && is_rest_arguments(&args[0]) { - *n = Expr::Call(CallExpr { + *n = CallExpr { span: DUMMY_SP, callee: MemberExpr { span: DUMMY_SP, @@ -243,11 +245,12 @@ impl SuperReplacer { })) .collect(), ..Default::default() - }); + } + .into(); return; } - *n = Expr::Call(CallExpr { + *n = CallExpr { span: DUMMY_SP, callee: MemberExpr { span: DUMMY_SP, @@ -257,7 +260,8 @@ impl SuperReplacer { .as_callee(), args: iter::once(this).chain(args.take()).collect(), ..Default::default() - }); + } + .into(); } } } @@ -305,12 +309,13 @@ impl SuperReplacer { return; } left.visit_mut_children_with(self); - *n = Expr::Assign(AssignExpr { + *n = AssignExpr { span: *span, left: left.take(), op: *op, right: right.take(), - }); + } + .into(); } _ => {} } @@ -339,12 +344,13 @@ impl SuperReplacer { } fn super_to_get_call(proto: ExprOrSpread, super_token: Span, prop: ExprOrSpread) -> Expr { - Expr::Call(CallExpr { + CallExpr { span: super_token, callee: helper!(get), args: vec![proto, prop, ThisExpr { span: super_token }.as_arg()], ..Default::default() - }) + } + .into() } fn to_bin_expr(left: Box, op: AssignOp, rhs: Box) -> BinExpr { @@ -362,7 +368,7 @@ impl SuperReplacer { prop: ExprOrSpread, rhs: ExprOrSpread, ) -> Expr { - Expr::Call(CallExpr { + CallExpr { span: super_token, callee: helper!(set), args: vec![ @@ -374,7 +380,8 @@ impl SuperReplacer { true.as_arg(), ], ..Default::default() - }) + } + .into() } fn super_to_set_call( @@ -400,12 +407,13 @@ impl SuperReplacer { if computed { let ref_ident = alias_ident_for(&rhs, "_ref").into_private(); self.vars.push(ref_ident.clone()); - *prop = Expr::Assign(AssignExpr { + *prop = AssignExpr { span: DUMMY_SP, left: ref_ident.clone().into(), op: op!("="), right: prop.take(), - }); + } + .into(); ref_ident.as_arg() } else { prop.clone().as_arg() @@ -417,11 +425,12 @@ impl SuperReplacer { super_token, prop.as_arg(), SuperReplacer::to_bin_expr( - Box::new(Expr::Unary(UnaryExpr { + UnaryExpr { span: DUMMY_SP, op: op!(unary, "+"), arg: left, - })), + } + .into(), op, rhs, ) @@ -430,7 +439,7 @@ impl SuperReplacer { } else { let update_ident = alias_ident_for(&rhs, "_super").into_private(); self.vars.push(update_ident.clone()); - Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs: vec![ Box::new( @@ -459,7 +468,8 @@ impl SuperReplacer { ), Box::new(Expr::Ident(update_ident)), ], - }) + } + .into() } } else { self.call_set_helper( diff --git a/crates/swc_ecma_compat_es2015/src/parameters.rs b/crates/swc_ecma_compat_es2015/src/parameters.rs index 429a3752b4e..cdf19874b4c 100644 --- a/crates/swc_ecma_compat_es2015/src/parameters.rs +++ b/crates/swc_ecma_compat_es2015/src/parameters.rs @@ -114,7 +114,7 @@ impl Params { let decl = VarDeclarator { span, name: param.pat, - init: Some(Box::new(Expr::Ident(binding))), + init: Some(binding.into()), definite: false, }; if self.c.ignore_function_length { @@ -141,22 +141,28 @@ impl Params { decls.push(VarDeclarator { span, name: *left, - init: Some(Box::new(Expr::Cond(CondExpr { - span, - test: Box::new(Expr::Bin(BinExpr { - left: Box::new(check_arg_len(i)), - op: op!("&&"), - right: Box::new(Expr::Bin(BinExpr { - left: make_arg_nth(i).into(), - op: op!("!=="), - right: Expr::undefined(DUMMY_SP), - span: DUMMY_SP, - })), + init: Some( + CondExpr { span, - })), - cons: make_arg_nth(i).into(), - alt: right, - }))), + test: Box::new( + BinExpr { + left: Box::new(check_arg_len(i)), + op: op!("&&"), + right: Box::new(Expr::Bin(BinExpr { + left: make_arg_nth(i).into(), + op: op!("!=="), + right: Expr::undefined(DUMMY_SP), + span: DUMMY_SP, + })), + span, + } + .into(), + ), + cons: make_arg_nth(i).into(), + alt: right, + } + .into(), + ), definite: false, }) } else if let Pat::Ident(ident) = left.as_ref() { @@ -167,20 +173,22 @@ impl Params { }); loose_stmt.push(Stmt::If(IfStmt { span, - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, - left: Box::new(Expr::Ident(Ident::from(ident))), + left: Box::new(Ident::from(ident).into()), op: op!("==="), right: Expr::undefined(DUMMY_SP), - })), + } + .into(), cons: Box::new(Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span, left: left.try_into().unwrap(), op: op!("="), right, - })), + } + .into(), })), alt: None, })) @@ -258,37 +266,40 @@ impl Params { // `len - $i` let bin: Expr = BinExpr { span, - left: Box::new(Expr::Ident(ident.clone())), + left: ident.clone().into(), op: op!(bin, "-"), - right: Box::new(Expr::Lit(Lit::Num(Number { + right: Lit::Num(Number { span, value: i as f64, raw: None, - }))), + }) + .into(), } .into(); if !min_zero { return bin; } - Expr::Cond(CondExpr { + CondExpr { span, test: Box::new( BinExpr { span, left: Box::new(len_ident.clone().into()), op: op!(">"), - right: Box::new(Expr::Lit(Lit::Num(Number { + right: Lit::Num(Number { span, value: i as _, raw: None, - }))), + }) + .into(), } .into(), ), cons: Box::new(bin), alt: 0.into(), - }) + } + .into() } }; @@ -348,19 +359,25 @@ impl Params { .into(), ), // `_key < _len` - test: Some(Box::new(Expr::Bin(BinExpr { - span, - left: Box::new(idx_ident.clone().into()), - op: op!("<"), - right: Box::new(len_ident.clone().into()), - }))), + test: Some( + BinExpr { + span, + left: Box::new(idx_ident.clone().into()), + op: op!("<"), + right: Box::new(len_ident.clone().into()), + } + .into(), + ), // _key++ - update: Some(Box::new(Expr::Update(UpdateExpr { - span, - op: op!("++"), - prefix: false, - arg: Box::new(idx_ident.clone().into()), - }))), + 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![{ @@ -634,7 +651,7 @@ impl VisitMut for Params { } .into(); *e = match (self.in_prop, local_vars) { - (true, Some(var_decl)) => Expr::Arrow(ArrowExpr { + (true, Some(var_decl)) => ArrowExpr { span: f.span, params: Vec::new(), is_async: false, @@ -651,7 +668,7 @@ impl VisitMut for Params { ..Default::default() })), ..Default::default() - }) + } .as_iife() .into(), _ => func, @@ -675,7 +692,7 @@ impl VisitMut for Params { Box::new(BlockStmtOrExpr::BlockStmt(body)) }; - *e = Expr::Arrow(ArrowExpr { + *e = ArrowExpr { params: params.into_iter().map(|param| param.pat).collect(), body, span: f.span, @@ -684,7 +701,8 @@ impl VisitMut for Params { type_params: f.type_params.take(), return_type: f.return_type.take(), ..Default::default() - }); + } + .into(); } _ => e.visit_mut_children_with(self), } @@ -784,25 +802,27 @@ impl VisitMut for Params { } fn make_arg_nth(n: usize) -> MemberExpr { - Expr::Ident(Ident::new_no_ctxt("arguments".into(), DUMMY_SP)).computed_member(n) + Ident::new_no_ctxt("arguments".into(), DUMMY_SP).computed_member(n) } fn check_arg_len(n: usize) -> Expr { - Expr::Bin(BinExpr { + BinExpr { left: Expr::Ident(Ident::new_no_ctxt("arguments".into(), DUMMY_SP)) .make_member(IdentName::new("length".into(), DUMMY_SP)) .into(), op: op!(">"), right: n.into(), span: DUMMY_SP, - }) + } + .into() } fn check_arg_len_or_undef(n: usize) -> Expr { - Expr::Cond(CondExpr { + CondExpr { test: Box::new(check_arg_len(n)), cons: make_arg_nth(n).into(), alt: Expr::undefined(DUMMY_SP), span: DUMMY_SP, - }) + } + .into() } diff --git a/crates/swc_ecma_compat_es2015/src/shorthand_property.rs b/crates/swc_ecma_compat_es2015/src/shorthand_property.rs index ddb1caaea86..84d94ca16c9 100644 --- a/crates/swc_ecma_compat_es2015/src/shorthand_property.rs +++ b/crates/swc_ecma_compat_es2015/src/shorthand_property.rs @@ -96,10 +96,11 @@ impl VisitMut for Shorthand { }; *prop = Prop::KeyValue(KeyValueProp { key, - value: Box::new(Expr::Fn(FnExpr { + value: FnExpr { ident: None, function: function.take(), - })), + } + .into(), }) } _ => {} diff --git a/crates/swc_ecma_compat_es2015/src/spread.rs b/crates/swc_ecma_compat_es2015/src/spread.rs index 6cb6862e4d8..d65bdd06033 100644 --- a/crates/swc_ecma_compat_es2015/src/spread.rs +++ b/crates/swc_ecma_compat_es2015/src/spread.rs @@ -85,7 +85,7 @@ impl VisitMut for Spread { Expr::SuperProp(SuperPropExpr { obj: Super { span, .. }, .. - }) => (Box::new(Expr::This(ThisExpr { span: *span })), None), + }) => (ThisExpr { span: *span }.into(), None), Expr::Member(MemberExpr { obj, .. }) if obj.is_this() => (obj.clone(), None), @@ -93,7 +93,7 @@ impl VisitMut for Spread { Expr::Member(MemberExpr { obj, .. }) if obj.as_ident().is_some() && obj.as_ident().unwrap().span.is_dummy() => { - (Box::new(Expr::Ident(obj.as_ident().unwrap().clone())), None) + (obj.as_ident().unwrap().clone().into(), None) } Expr::Ident(Ident { span, .. }) => (Expr::undefined(*span), None), @@ -109,29 +109,34 @@ impl VisitMut for Spread { init: None, }); - let this = Box::new(Expr::Ident(ident.clone())); - let callee = Expr::Assign(AssignExpr { + let this = ident.clone().into(); + let callee: Expr = AssignExpr { span: DUMMY_SP, left: ident.into(), op: op!("="), right: obj.clone(), - }); + } + .into(); ( this, - Some(Box::new(Expr::Member(MemberExpr { - span: *span, - obj: callee.into(), - prop: prop.clone(), - }))), + Some( + MemberExpr { + span: *span, + obj: callee.into(), + prop: prop.clone(), + } + .into(), + ), ) } // https://github.com/swc-project/swc/issues/400 // _ => (undefined(callee.span()), callee), _ => ( - Box::new(Expr::This(ThisExpr { + ThisExpr { span: callee.span(), - })), + } + .into(), None, ), }; @@ -140,10 +145,11 @@ impl VisitMut for Spread { matches!(e, ExprOrSpread { spread: None, .. }) || matches!(e, ExprOrSpread { expr, .. } if expr.is_array()) }) { - Expr::Array(ArrayLit { + ArrayLit { span: *span, elems: expand_literal_args(args.take().into_iter().map(Some)), - }) + } + .into() } else { self.concat_args(*span, args.take().into_iter().map(Some), false) }; @@ -154,12 +160,13 @@ impl VisitMut for Spread { prop: MemberProp::Ident(IdentName::new("apply".into(), *span)), }; - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, callee: apply.as_callee(), args: vec![this.as_arg(), args_array.as_arg()], ..Default::default() - }) + } + .into() } Expr::New(NewExpr { callee, @@ -176,12 +183,13 @@ impl VisitMut for Spread { let args = self.concat_args(*span, args.take().into_iter().map(Some), true); - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, callee: helper!(construct), args: vec![callee.take().as_arg(), args.as_arg()], ..Default::default() - }); + } + .into(); } _ => {} }; @@ -291,7 +299,7 @@ impl Spread { ); } - return Expr::Call(CallExpr { + return CallExpr { span: DUMMY_SP, callee: ArrayLit { span: DUMMY_SP, @@ -301,7 +309,8 @@ impl Spread { .as_callee(), args: arg_list, ..Default::default() - }); + } + .into(); } for arg in args { @@ -338,7 +347,7 @@ impl Spread { Expr::Ident(Ident { ref sym, .. }) if &**sym == "arguments" => { if args_len == 1 { if need_array { - return Expr::Call(CallExpr { + return CallExpr { span, callee: member_expr!( Default::default(), @@ -348,7 +357,8 @@ impl Spread { .as_callee(), args: vec![expr.as_arg()], ..Default::default() - }); + } + .into(); } else { return *expr; } @@ -372,13 +382,13 @@ impl Spread { return if self.c.loose { *expr } else { - Expr::Call(to_consumable_array(expr, span)) + to_consumable_array(expr, span).into() }; } // [].concat(arr) is shorter than _to_consumable_array(arr) if args_len == 1 { return if self.c.loose { - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: ArrayLit { span: DUMMY_SP, @@ -388,9 +398,10 @@ impl Spread { .as_callee(), args: vec![expr.as_arg()], ..Default::default() - }) + } + .into() } else { - Expr::Call(to_consumable_array(expr, span)) + to_consumable_array(expr, span).into() }; } to_consumable_array(expr, span).as_arg() @@ -418,15 +429,16 @@ impl Spread { .make_member(IdentName::new("concat".into(), DUMMY_SP)) .as_callee(); - return Expr::Call(CallExpr { + return CallExpr { span, callee, args: buf, ..Default::default() - }); + } + .into(); } - Expr::Call(CallExpr { + CallExpr { // TODO span, @@ -446,7 +458,8 @@ impl Spread { args: buf, ..Default::default() - }) + } + .into() } } diff --git a/crates/swc_ecma_compat_es2015/src/sticky_regex.rs b/crates/swc_ecma_compat_es2015/src/sticky_regex.rs index 0b64d81a83e..c808f59811f 100644 --- a/crates/swc_ecma_compat_es2015/src/sticky_regex.rs +++ b/crates/swc_ecma_compat_es2015/src/sticky_regex.rs @@ -41,12 +41,13 @@ impl VisitMut for StickyRegex { if let Expr::Lit(Lit::Regex(Regex { exp, flags, span })) = e { if flags.contains('y') { - *e = Expr::New(NewExpr { + *e = NewExpr { span: *span, callee: Box::new(quote_ident!(Default::default(), *span, "RegExp").into()), args: Some(vec![exp.clone().as_arg(), flags.clone().as_arg()]), ..Default::default() - }) + } + .into() } } } diff --git a/crates/swc_ecma_compat_es2015/src/template_literal.rs b/crates/swc_ecma_compat_es2015/src/template_literal.rs index a7398af1920..3fc6dabb311 100644 --- a/crates/swc_ecma_compat_es2015/src/template_literal.rs +++ b/crates/swc_ecma_compat_es2015/src/template_literal.rs @@ -132,16 +132,16 @@ impl VisitMut for TemplateLiteral { value: r_value, .. })) => { - obj = Box::new(Expr::Lit(Lit::Str(Str { + obj = Lit::Str(Str { span: span.with_hi(r_span.hi()), raw: None, value: format!("{}{}", value, r_value).into(), - }))); + }) + .into(); continue; } _ => { - obj = - Box::new(Expr::Lit(Lit::Str(Str { span, raw, value }))); + obj = Lit::Str(Str { span, raw, value }).into(); } } } @@ -155,16 +155,17 @@ impl VisitMut for TemplateLiteral { obj = if self.c.ignore_to_primitive { let args = mem::take(&mut args); for arg in args { - obj = Box::new(Expr::Bin(BinExpr { + obj = BinExpr { span: span.with_hi(expr_span.hi() + BytePos(1)), op: op!(bin, "+"), left: obj, right: arg, - })) + } + .into() } obj } else { - Box::new(Expr::Call(CallExpr { + CallExpr { span: span.with_hi(expr_span.hi() + BytePos(1)), callee: MemberExpr { span: DUMMY_SP, @@ -180,7 +181,8 @@ impl VisitMut for TemplateLiteral { .map(|expr| expr.as_arg()) .collect(), ..Default::default() - })) + } + .into() } } } else { @@ -196,16 +198,17 @@ impl VisitMut for TemplateLiteral { continue; } } - obj = Box::new(Expr::Bin(BinExpr { + obj = BinExpr { span: span.with_hi(expr_span.hi() + BytePos(1)), op: op!(bin, "+"), left: obj, right: arg, - })) + } + .into() } obj } else { - Box::new(Expr::Call(CallExpr { + CallExpr { span: span.with_hi(expr_span.hi() + BytePos(1)), callee: MemberExpr { span: DUMMY_SP, @@ -221,7 +224,8 @@ impl VisitMut for TemplateLiteral { .map(|expr| expr.as_arg()) .collect(), ..Default::default() - })) + } + .into() }; } debug_assert!(args.is_empty()); @@ -310,8 +314,8 @@ impl VisitMut for TemplateLiteral { // _templateObject2 = function () { // return data; // }; - let assign_expr = { - Expr::Assign(AssignExpr { + let assign_expr: Expr = { + AssignExpr { span: DUMMY_SP, left: fn_ident.clone().into(), op: op!("="), @@ -331,7 +335,8 @@ impl VisitMut for TemplateLiteral { ..Default::default() } .into(), - }) + } + .into() }; Some(BlockStmt { @@ -357,7 +362,7 @@ impl VisitMut for TemplateLiteral { function: f.into(), }))); - *e = Expr::Call(CallExpr { + *e = CallExpr { span: DUMMY_SP, callee: tag.take().as_callee(), args: iter::once( @@ -372,7 +377,8 @@ impl VisitMut for TemplateLiteral { .chain(tpl.exprs.take().into_iter().map(|e| e.as_arg())) .collect(), ..Default::default() - }) + } + .into() } _ => {} diff --git a/crates/swc_ecma_compat_es2015/src/typeof_symbol.rs b/crates/swc_ecma_compat_es2015/src/typeof_symbol.rs index c90a60ab910..c792c3e21c6 100644 --- a/crates/swc_ecma_compat_es2015/src/typeof_symbol.rs +++ b/crates/swc_ecma_compat_es2015/src/typeof_symbol.rs @@ -67,39 +67,46 @@ impl VisitMut for TypeOfSymbol { Expr::Ident(..) => { let undefined_str: Box = quote_str!("undefined").into(); - let test = Box::new(Expr::Bin(BinExpr { + let test = BinExpr { span: DUMMY_SP, op: op!("==="), - left: Box::new(Expr::Unary(UnaryExpr { - span: DUMMY_SP, - op: op!("typeof"), - arg: arg.clone(), - })), + left: Box::new( + UnaryExpr { + span: DUMMY_SP, + op: op!("typeof"), + arg: arg.clone(), + } + .into(), + ), right: undefined_str.clone(), - })); + } + .into(); - let call = Expr::Call(CallExpr { + let call = CallExpr { span: *span, callee: helper!(*span, type_of), args: vec![arg.take().as_arg()], ..Default::default() - }); + } + .into(); - *expr = Expr::Cond(CondExpr { + *expr = CondExpr { span: *span, test, cons: undefined_str, alt: Box::new(call), - }); + } + .into(); } _ => { - let call = Expr::Call(CallExpr { + let call = CallExpr { span: *span, callee: helper!(*span, type_of), args: vec![arg.take().as_arg()], ..Default::default() - }); + } + .into(); *expr = call; } diff --git a/crates/swc_ecma_compat_es2016/src/exponentiation.rs b/crates/swc_ecma_compat_es2016/src/exponentiation.rs index 6d5acddfc79..5b3e1883f97 100644 --- a/crates/swc_ecma_compat_es2016/src/exponentiation.rs +++ b/crates/swc_ecma_compat_es2016/src/exponentiation.rs @@ -109,12 +109,13 @@ impl VisitMut for Exponentiation { } left => { - *e = Expr::Assign(AssignExpr { + *e = AssignExpr { span: *span, left: left.take(), op: op!("="), right: right.take(), - }); + } + .into(); return; } }; @@ -138,13 +139,14 @@ impl VisitMut for Exponentiation { #[tracing::instrument(level = "info", skip_all)] fn mk_call(span: Span, left: Box, right: Box) -> Expr { // Math.pow() - Expr::Call(CallExpr { + CallExpr { span, callee: member_expr!(Default::default(), span, Math.pow).as_callee(), args: vec![left.as_arg(), right.as_arg()], ..Default::default() - }) + } + .into() } #[cfg(test)] 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 a95b3e63839..35183be65ad 100644 --- a/crates/swc_ecma_compat_es2017/src/async_to_generator.rs +++ b/crates/swc_ecma_compat_es2017/src/async_to_generator.rs @@ -156,12 +156,15 @@ impl VisitMut for Actual { .into_iter() .chain(iter::once(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: expr.as_callee(), - args: vec![], - ..Default::default() - }))), + arg: Some( + CallExpr { + span: DUMMY_SP, + callee: expr.as_callee(), + args: vec![], + ..Default::default() + } + .into(), + ), }))) .collect(), ..Default::default() @@ -267,18 +270,15 @@ impl VisitMut for Actual { ); let fn_ref = if is_this_used { - fn_ref.apply( - DUMMY_SP, - Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), - vec![], - ) + fn_ref.apply(DUMMY_SP, ThisExpr { span: DUMMY_SP }.into(), vec![]) } else { - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: fn_ref.as_callee(), args: vec![], ..Default::default() - }) + } + .into() }; prop.function = Function { @@ -427,14 +427,13 @@ fn make_fn_ref(mut expr: FnExpr) -> Expr { let span = expr.span(); - let expr = Expr::Fn(expr); - - Expr::Call(CallExpr { + CallExpr { span, callee: helper, args: vec![expr.as_arg()], ..Default::default() - }) + } + .into() } struct AsyncFnBodyHandler { @@ -470,7 +469,7 @@ impl VisitMut for AsyncFnBodyHandler { delegate: true, }) => { let callee = helper!(async_generator_delegate); - let arg = Box::new(Expr::Call(CallExpr { + let arg = CallExpr { span: *span, callee, args: vec![ @@ -484,34 +483,39 @@ impl VisitMut for AsyncFnBodyHandler { helper_expr!(await_async_generator).as_arg(), ], ..Default::default() - })); - *expr = Expr::Yield(YieldExpr { + } + .into(); + *expr = YieldExpr { span: *span, delegate: true, arg: Some(arg), - }) + } + .into() } Expr::Await(AwaitExpr { span, arg }) => { if self.is_async_generator { let callee = helper!(await_async_generator); - let arg = Box::new(Expr::Call(CallExpr { + let arg = CallExpr { span: *span, callee, args: vec![arg.take().as_arg()], ..Default::default() - })); - *expr = Expr::Yield(YieldExpr { + } + .into(); + *expr = YieldExpr { span: *span, delegate: false, arg: Some(arg), - }) + } + .into() } else { - *expr = Expr::Yield(YieldExpr { + *expr = YieldExpr { span: *span, delegate: false, arg: Some(arg.take()), - }) + } + .into() } } _ => {} @@ -606,7 +610,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { let var_decl = VarDeclarator { span: DUMMY_SP, name: var.name, - init: Some(Box::new(Expr::Ident(value))), + init: Some(value.into()), definite: false, }; for_loop_body.push( @@ -623,12 +627,13 @@ 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: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span: DUMMY_SP, op: op!("="), left: p.try_into().unwrap(), - right: Box::new(Expr::Ident(value)), - })), + right: Box::new(value.into()), + } + .into(), })); } @@ -653,12 +658,15 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { init: { let callee = helper!(async_iterator); - Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee, - args: vec![s.right.as_arg()], - ..Default::default() - }))) + Some( + CallExpr { + span: DUMMY_SP, + callee, + args: vec![s.right.as_arg()], + ..Default::default() + } + .into(), + ) }, definite: false, }); @@ -693,49 +701,59 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { }; let yield_arg = if is_async_generator { - Box::new(Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: helper!(await_async_generator), args: vec![iter_next.as_arg()], ..Default::default() - })) + } + .into() } else { - Box::new(Expr::Call(iter_next)) + iter_next.into() }; - let assign_to_step = Expr::Assign(AssignExpr { + let assign_to_step: Expr = AssignExpr { span: DUMMY_SP, op: op!("="), left: step.into(), - right: Box::new(Expr::Yield(YieldExpr { + right: YieldExpr { span: DUMMY_SP, arg: Some(yield_arg), delegate: false, - })), - }); + } + .into(), + } + .into(); - let right = Box::new(Expr::Unary(UnaryExpr { + let right = UnaryExpr { span: DUMMY_SP, op: op!("!"), arg: assign_to_step.make_member(quote_ident!("done")).into(), - })); + } + .into(); let left = iterator_abrupt_completion.clone().into(); - Some(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left, - right, - }))) + Some( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left, + right, + } + .into(), + ) }, // _iteratorNormalCompletion = true - update: Some(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: iterator_abrupt_completion.clone().into(), - right: false.into(), - }))), + update: Some( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: iterator_abrupt_completion.clone().into(), + right: false.into(), + } + .into(), + ), body: Box::new(Stmt::Block(for_loop_body)), }); @@ -750,22 +768,24 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { // _didIteratorError = true; let mark_as_errorred = Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span: DUMMY_SP, op: op!("="), left: did_iteration_error.clone().into(), right: true.into(), - })), + } + .into(), }); // _iteratorError = err; let store_error = Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span: DUMMY_SP, op: op!("="), left: iterator_error.clone().into(), - right: Box::new(Expr::Ident(err_param.clone())), - })), + right: Box::new(err_param.clone().into()), + } + .into(), }); CatchClause { @@ -781,11 +801,11 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { let finally_block = { let throw_iterator_error = Stmt::Throw(ThrowStmt { span: DUMMY_SP, - arg: Box::new(Expr::Ident(iterator_error.clone())), + arg: iterator_error.clone().into(), }); let throw_iterator_error = Stmt::If(IfStmt { span: DUMMY_SP, - test: Box::new(Expr::Ident(did_iteration_error.clone())), + test: did_iteration_error.clone().into(), cons: Box::new(Stmt::Block(BlockStmt { span: DUMMY_SP, stmts: vec![throw_iterator_error], @@ -794,7 +814,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { alt: None, }); - let iterator_return = Box::new(Expr::Call(CallExpr { + let iterator_return: Expr = CallExpr { span: DUMMY_SP, callee: iterator .clone() @@ -802,45 +822,52 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { .as_callee(), args: vec![], ..Default::default() - })); + } + .into(); // yield _iterator.return(); // or // yield _awaitAsyncGenerator(_iterator.return()); let yield_stmt = Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Yield(YieldExpr { + expr: YieldExpr { span: DUMMY_SP, delegate: false, arg: Some(if is_async_generator { - Box::new(Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: helper!(await_async_generator), args: vec![iterator_return.as_arg()], ..Default::default() - })) + } + .into() } else { - iterator_return + iterator_return.into() }), - })), + } + .into(), }); let conditional_yield = Stmt::If(IfStmt { span: DUMMY_SP, // _iteratorAbruptCompletion && _iterator.return != null - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, op: op!("&&"), // _iteratorAbruptCompletion - left: Box::new(Expr::Ident(iterator_abrupt_completion.clone())), + left: Box::new(iterator_abrupt_completion.clone().into()), // _iterator.return != null - right: Box::new(Expr::Bin(BinExpr { - span: DUMMY_SP, - op: op!("!="), - left: iterator.make_member(quote_ident!("return")).into(), - right: Null { span: DUMMY_SP }.into(), - })), - })), + right: Box::new( + BinExpr { + span: DUMMY_SP, + op: op!("!="), + left: iterator.make_member(quote_ident!("return")).into(), + right: Null { span: DUMMY_SP }.into(), + } + .into(), + ), + } + .into(), cons: Box::new(Stmt::Block(BlockStmt { stmts: vec![yield_stmt], ..Default::default() diff --git a/crates/swc_ecma_compat_es2018/src/object_rest.rs b/crates/swc_ecma_compat_es2018/src/object_rest.rs index b9905450074..2532659e9bd 100644 --- a/crates/swc_ecma_compat_es2018/src/object_rest.rs +++ b/crates/swc_ecma_compat_es2018/src/object_rest.rs @@ -229,34 +229,41 @@ impl VisitMut for ObjectRest { definite: false, }); // println!("Expr: var_ident = right"); - self.exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: var_ident.clone().into(), - op: op!("="), - right: right.take(), - }))); + self.exprs.push( + AssignExpr { + span: DUMMY_SP, + left: var_ident.clone().into(), + op: op!("="), + right: right.take(), + } + .into(), + ); let pat = self.fold_rest( &mut 0, pat.take().into(), - Box::new(Expr::Ident(var_ident.clone())), + var_ident.clone().into(), true, true, ); match pat { Pat::Object(ObjectPat { ref props, .. }) if props.is_empty() => {} - _ => self.exprs.push(Box::new(Expr::Assign(AssignExpr { - span: *span, - left: pat.try_into().unwrap(), - op: op!("="), - right: Box::new(var_ident.clone().into()), - }))), + _ => self.exprs.push( + AssignExpr { + span: *span, + left: pat.try_into().unwrap(), + op: op!("="), + right: Box::new(var_ident.clone().into()), + } + .into(), + ), } self.exprs.push(Box::new(var_ident.into())); - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, exprs: mem::take(&mut self.exprs), - }); + } + .into(); }; } @@ -362,21 +369,24 @@ impl VisitMut for ObjectRest { self.vars.push(VarDeclarator { span: prop.span(), name: *prop.arg, - init: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: helper!(extends), - args: vec![ - ObjectLit { - span: DUMMY_SP, - props: vec![], - } - .as_arg(), - helper_expr!(object_destructuring_empty) - .as_call(DUMMY_SP, vec![init.as_arg()]) + init: Some( + CallExpr { + span: DUMMY_SP, + callee: helper!(extends), + args: vec![ + ObjectLit { + span: DUMMY_SP, + props: vec![], + } .as_arg(), - ], - ..Default::default() - }))), + helper_expr!(object_destructuring_empty) + .as_call(DUMMY_SP, vec![init.as_arg()]) + .as_arg(), + ], + ..Default::default() + } + .into(), + ), definite: false, }); continue; @@ -400,13 +410,8 @@ impl VisitMut for ObjectRest { } let mut index = self.vars.len(); - let mut pat = self.fold_rest( - &mut index, - decl.name, - Box::new(Expr::Ident(var_ident.clone())), - false, - true, - ); + let mut pat = + self.fold_rest(&mut index, decl.name, var_ident.clone().into(), false, true); match pat { // skip `{} = z` Pat::Object(ObjectPat { ref props, .. }) if props.is_empty() => {} @@ -426,7 +431,7 @@ impl VisitMut for ObjectRest { name: pat, // preserve init: if has_init { - Some(Box::new(Expr::Ident(var_ident.clone()))) + Some(var_ident.clone().into()) } else { None }, @@ -567,13 +572,8 @@ impl ObjectRest { .map(|mut param| { let var_ident = private_ident!(param.span(), "_param"); let mut index = self.vars.len(); - param.pat = self.fold_rest( - &mut index, - param.pat, - Box::new(Expr::Ident(var_ident.clone())), - false, - true, - ); + param.pat = + self.fold_rest(&mut index, param.pat, var_ident.clone().into(), false, true); match param.pat { Pat::Rest(..) | Pat::Ident(..) => param, @@ -591,18 +591,19 @@ impl ObjectRest { VarDeclarator { span, name: *left, - init: Some(Box::new(Expr::Ident(var_ident.clone()))), + init: Some(var_ident.clone().into()), definite: false, }, ); Param { span: DUMMY_SP, decorators: Default::default(), - pat: Pat::Assign(AssignPat { + pat: AssignPat { span, left: var_ident.into(), right, - }), + } + .into(), } } _ => { @@ -612,7 +613,7 @@ impl ObjectRest { VarDeclarator { span: DUMMY_SP, name: param.pat, - init: Some(Box::new(Expr::Ident(var_ident.clone()))), + init: Some(var_ident.clone().into()), definite: false, }, ); @@ -693,7 +694,7 @@ impl ObjectRest { use_expr_for_assign, use_member_for_array, )); - return Pat::Assign(AssignPat { span, left, right }); + return AssignPat { span, left, right }.into(); } Pat::Array(n) => { let ArrayPat { span, elems, .. } = n; @@ -717,7 +718,7 @@ impl ObjectRest { }) .collect(); - return Pat::Array(ArrayPat { span, elems, ..n }); + return ArrayPat { span, elems, ..n }.into(); } _ => return pat, }; @@ -760,11 +761,12 @@ impl ObjectRest { key, MemberProp::Computed(ComputedPropName { span, - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span, raw: None, value: format!("{}", value).into(), - }))), + }) + .into(), }), ), PropName::BigInt(BigInt { @@ -775,11 +777,12 @@ impl ObjectRest { key, MemberProp::Computed(ComputedPropName { span, - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span, raw: None, value: format!("{}", value).into(), - }))), + }) + .into(), }), ) } @@ -802,7 +805,7 @@ impl ObjectRest { ( PropName::Computed(ComputedPropName { span: c.span, - expr: Box::new(Expr::Ident(ident.clone())), + expr: ident.clone().into(), }), MemberProp::Computed(ComputedPropName { span: c.span, @@ -837,12 +840,13 @@ impl ObjectRest { match props.last() { Some(ObjectPatProp::Rest(..)) => {} _ => { - return Pat::Object(ObjectPat { + return ObjectPat { span, props, optional: false, type_ann, - }); + } + .into(); } } let last = match props.pop() { @@ -854,16 +858,19 @@ impl ObjectRest { if use_expr_for_assign { // println!("Expr: last.arg = objectWithoutProperties()",); - self.exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: last.arg.try_into().unwrap(), - op: op!("="), - right: Box::new(object_without_properties( - obj, - excluded_props, - self.config.no_symbol, - )), - }))); + self.exprs.push( + AssignExpr { + span: DUMMY_SP, + left: last.arg.try_into().unwrap(), + op: op!("="), + right: Box::new(object_without_properties( + obj, + excluded_props, + self.config.no_symbol, + )), + } + .into(), + ); } else { // println!("Var: rest = objectWithoutProperties()",); self.push_var_if_not_empty(VarDeclarator { @@ -878,12 +885,13 @@ impl ObjectRest { }); } - Pat::Object(ObjectPat { + ObjectPat { props, span, type_ann, optional: false, - }) + } + .into() } } @@ -894,7 +902,7 @@ fn object_without_properties( no_symbol: bool, ) -> Expr { if excluded_props.is_empty() { - return Expr::Call(CallExpr { + return CallExpr { span: DUMMY_SP, callee: helper!(extends), args: vec![ @@ -908,7 +916,8 @@ fn object_without_properties( .as_arg(), ], ..Default::default() - }); + } + .into(); } let excluded_props = excluded_props @@ -916,11 +925,12 @@ fn object_without_properties( .map(|v| { v.map(|v| match *v.expr { Expr::Lit(Lit::Num(Number { span, value, .. })) => ExprOrSpread { - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span, raw: None, value: value.to_string().into(), - }))), + }) + .into(), ..v }, _ => v, @@ -928,7 +938,7 @@ fn object_without_properties( }) .collect(); - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: if no_symbol { helper!(object_without_properties_loose) @@ -959,7 +969,8 @@ fn object_without_properties( }, ], ..Default::default() - }) + } + .into() } #[tracing::instrument(level = "info", skip_all)] diff --git a/crates/swc_ecma_compat_es2018/src/object_spread.rs b/crates/swc_ecma_compat_es2018/src/object_spread.rs index 9cb1f11bed3..9ec9891f11b 100644 --- a/crates/swc_ecma_compat_es2018/src/object_spread.rs +++ b/crates/swc_ecma_compat_es2018/src/object_spread.rs @@ -95,12 +95,13 @@ impl VisitMut for ObjectSpread { buf }; - *expr = Expr::Call(CallExpr { + *expr = CallExpr { span: *span, callee, args, ..Default::default() - }); + } + .into(); } } } diff --git a/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs b/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs index eeb0b1ee87b..6fe54e4c5c8 100644 --- a/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs +++ b/crates/swc_ecma_compat_es2020/src/nullish_coalescing.rs @@ -109,14 +109,15 @@ impl VisitMut for NullishCoalescing { } let var_expr = if aliased { - Expr::Assign(AssignExpr { + AssignExpr { span: DUMMY_SP, op: op!("="), left: l.clone().into(), right: left.take(), - }) + } + .into() } else { - Expr::Ident(l.clone()) + l.clone().into() }; *e = make_cond(self.c, *span, &l, var_expr, right.take()); @@ -125,7 +126,7 @@ impl VisitMut for NullishCoalescing { Expr::Assign(ref mut assign @ AssignExpr { op: op!("??="), .. }) => { match &mut assign.left { AssignTarget::Simple(SimpleAssignTarget::Ident(i)) => { - *e = Expr::Assign(AssignExpr { + *e = AssignExpr { span: assign.span, op: op!("="), left: i.clone().into(), @@ -136,7 +137,8 @@ impl VisitMut for NullishCoalescing { Expr::Ident(Ident::from(&*i)), assign.right.take(), )), - }); + } + .into(); } AssignTarget::Simple(left) => { @@ -149,21 +151,23 @@ impl VisitMut for NullishCoalescing { }); // TODO: Check for computed. - let right_expr = Box::new(Expr::Assign(AssignExpr { + let right_expr = AssignExpr { span: assign.span, left: left.clone().into(), op: op!("="), right: assign.right.take(), - })); + } + .into(); - let var_expr = Expr::Assign(AssignExpr { + let var_expr = AssignExpr { span: DUMMY_SP, op: op!("="), left: alias.clone().into(), right: left.take().into(), - }); + } + .into(); - *e = Expr::Assign(AssignExpr { + *e = AssignExpr { span: assign.span, op: op!("="), left: alias.clone().into(), @@ -174,7 +178,8 @@ impl VisitMut for NullishCoalescing { var_expr, right_expr, )), - }); + } + .into(); } _ => {} @@ -221,22 +226,23 @@ impl VisitMut for NullishCoalescing { #[tracing::instrument(level = "info", skip_all)] fn make_cond(c: Config, span: Span, alias: &Ident, var_expr: Expr, init: Box) -> Expr { - Expr::Cond(if c.no_document_all { + if c.no_document_all { CondExpr { span, - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, left: Box::new(var_expr), op: op!("!="), right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), - })), - cons: Box::new(Expr::Ident(alias.clone())), + } + .into(), + cons: alias.clone().into(), alt: init, } } else { CondExpr { span, - test: Box::new(Expr::Bin(BinExpr { + test: BinExpr { span: DUMMY_SP, left: Box::new(Expr::Bin(BinExpr { span: DUMMY_SP, @@ -251,9 +257,11 @@ fn make_cond(c: Config, span: Span, alias: &Ident, var_expr: Expr, init: Box unreachable!(), }; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op, left: left_expr, right, - }); + } + .into(); } } diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/class_name_tdz.rs b/crates/swc_ecma_compat_es2022/src/class_properties/class_name_tdz.rs index 61c24907feb..006a9ba579b 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/class_name_tdz.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/class_name_tdz.rs @@ -19,7 +19,7 @@ impl<'a> VisitMut for ClassNameTdzFolder<'a> { // if i.sym == self.class_name.sym { - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, exprs: vec![ Box::new(Expr::Call(CallExpr { @@ -36,7 +36,8 @@ impl<'a> VisitMut for ClassNameTdzFolder<'a> { })), Box::new(Expr::Ident(i.clone())), ], - }); + } + .into(); } } 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 5979242746e..e9f3eb43c91 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 @@ -150,7 +150,7 @@ impl MemberInitRecord { MemberInit::PubProp(PubProp { span, name, value }) => value_init.push( if self.c.set_public_fields { let this = ThisExpr { span: DUMMY_SP }; - Expr::Assign(AssignExpr { + Expr::from(AssignExpr { span, left: match name { PropName::Ident(id) => this.make_member(id).into(), @@ -160,7 +160,7 @@ impl MemberInitRecord { right: value, }) } else { - Expr::Call(CallExpr { + CallExpr { span, callee: helper!(define_property), args: vec![ @@ -169,7 +169,8 @@ impl MemberInitRecord { value.as_arg(), ], ..Default::default() - }) + } + .into() } .into(), ), @@ -193,7 +194,7 @@ impl MemberInitRecord { span, expr: (if self.c.set_public_fields { let class = class_ident.clone(); - Expr::Assign(AssignExpr { + Expr::from(AssignExpr { span, left: match name { PropName::Ident(id) => class.make_member(id).into(), @@ -203,7 +204,7 @@ impl MemberInitRecord { right: value, }) } else { - Expr::Call(CallExpr { + CallExpr { span, callee: helper!(define_property), args: vec![ @@ -212,7 +213,8 @@ impl MemberInitRecord { value.as_arg(), ], ..Default::default() - }) + } + .into() }) .into(), })) @@ -221,7 +223,7 @@ impl MemberInitRecord { value_init.push(if self.c.private_as_properties { Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span, callee: obj_def_prop(), args: vec![ @@ -230,7 +232,8 @@ impl MemberInitRecord { get_value_desc(value).as_arg(), ], ..Default::default() - })), + } + .into(), }) } else { VarDecl { @@ -255,7 +258,7 @@ impl MemberInitRecord { }) => normal_init.push(if self.c.private_as_properties { Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span, callee: obj_def_prop(), args: vec![ @@ -264,7 +267,8 @@ impl MemberInitRecord { get_accessor_desc(getter, setter).as_arg(), ], ..Default::default() - })), + } + .into(), }) } else { VarDecl { 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 7aecc77b7f2..7bff9be6764 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs @@ -195,7 +195,7 @@ impl VisitMut for ClassProperties { stmts.push(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Ident(ident))), + arg: Some(ident.into()), })); *body = BlockStmtOrExpr::BlockStmt(BlockStmt { @@ -221,10 +221,11 @@ impl VisitMut for ClassProperties { let (decl, ClassExtra { lets, vars, stmts }) = self.visit_mut_class_as_decl(ident.clone(), class.take()); - let class = Expr::Class(ClassExpr { + let class = ClassExpr { ident: orig_ident.clone(), class: decl.class, - }); + } + .into(); if vars.is_empty() && lets.is_empty() && stmts.is_empty() { *expr = class; return; @@ -319,10 +320,11 @@ impl VisitMut for ClassProperties { exprs.push(Box::new(ident.into())) } - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } else { expr.visit_mut_children_with(self); }; @@ -579,7 +581,7 @@ impl ClassProperties { // string. PropName::Computed(ComputedPropName { span: c_span, - expr: Box::new(Expr::Ident(ident)), + expr: ident.into(), }) } _ => method.key, @@ -629,7 +631,7 @@ impl ClassProperties { definite: false, }); } - *key.expr = Expr::from(ident); + *key.expr = ident.into(); } _ => (), }; @@ -658,12 +660,13 @@ impl ClassProperties { definite: false, }); let span = super_class.span(); - **super_class = Expr::Assign(AssignExpr { + **super_class = AssignExpr { span, op: op!("="), left: ident.into(), right: super_class.take(), - }) + } + .into() } } @@ -766,24 +769,30 @@ impl ClassProperties { span: DUMMY_SP, definite: false, name: ident.clone().into(), - init: Some(Box::new(Expr::from(CallExpr { - span, - callee: helper!(class_private_field_loose_key), - args: vec![ident.sym.as_arg()], - ..Default::default() - }))), + init: Some( + CallExpr { + span, + callee: helper!(class_private_field_loose_key), + args: vec![ident.sym.as_arg()], + ..Default::default() + } + .into(), + ), }); } else if !prop.is_static { vars.push(VarDeclarator { span: DUMMY_SP, definite: false, name: ident.into(), - init: Some(Box::new(Expr::from(NewExpr { - span, - callee: Box::new(Expr::Ident(quote_ident!("WeakMap").into())), - args: Some(Default::default()), - ..Default::default() - }))), + init: Some( + NewExpr { + span, + callee: Box::new(quote_ident!("WeakMap").into()), + args: Some(Default::default()), + ..Default::default() + } + .into(), + ), }); }; if prop.is_static { @@ -915,19 +924,21 @@ impl ClassProperties { definite: false, name: weak_coll_var.clone().into(), init: Some(Box::new(if self.c.private_as_properties { - Expr::from(CallExpr { + CallExpr { span, callee: helper!(class_private_field_loose_key), args: vec![weak_coll_var.sym.as_arg()], ..Default::default() - }) + } + .into() } else { - Expr::New(NewExpr { + NewExpr { span, - callee: Box::new(Expr::Ident(extra.into())), + callee: extra.into(), args: Some(Default::default()), ..Default::default() - }) + } + .into() })), }) }; diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs b/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs index 9bf35b41767..d59c9e33af1 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs @@ -102,12 +102,13 @@ impl VisitMut for BrandCheckHandler<'_> { if let Expr::Ident(right) = &**right { let curr_class = self.private.curr_class(); if curr_class.sym == right.sym && curr_class.ctxt == right.ctxt { - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op: op!("==="), - left: Box::new(Expr::Ident(curr_class.clone())), - right: Box::new(Expr::Ident(right.clone())), - }); + left: curr_class.clone().into(), + right: right.clone().into(), + } + .into(); return; } } @@ -119,12 +120,13 @@ impl VisitMut for BrandCheckHandler<'_> { } if kind.is_static { - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op: op!("==="), left: right.take(), - right: Box::new(Expr::Ident(class_name.clone())), - }); + right: class_name.clone().into(), + } + .into(); return; } @@ -134,13 +136,14 @@ impl VisitMut for BrandCheckHandler<'_> { SyntaxContext::empty().apply_mark(mark), ); - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, callee: weak_coll_ident.make_member(quote_ident!("has")).as_callee(), args: vec![right.take().as_arg()], ..Default::default() - }); + } + .into(); } _ => {} @@ -254,12 +257,12 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { SyntaxContext::empty().apply_mark(mark), ); - *e = Expr::Call(CallExpr { + *e = CallExpr { callee: helper!(class_private_field_loose_base), span: *span, args: vec![obj.take().as_arg(), ident.clone().as_arg()], ..Default::default() - }) + } .computed_member(ident) .into(); } else { @@ -290,12 +293,13 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { let n = match &left.prop { MemberProp::PrivateName(n) => n.clone(), _ => { - *e = Expr::Assign(AssignExpr { + *e = AssignExpr { span: *span, left: left.into(), op: *op, right: right.take(), - }); + } + .into(); return; } @@ -355,7 +359,7 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { }; if kind.is_static { - *e = Expr::Call(CallExpr { + *e = CallExpr { span: DUMMY_SP, callee: helper!(class_static_private_field_spec_set), args: vec![ @@ -366,7 +370,8 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { ], ..Default::default() - }); + } + .into(); } else if kind.is_readonly() { let err = CallExpr { span: DUMMY_SP, @@ -375,20 +380,22 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { ..Default::default() } .into(); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: *span, exprs: vec![this, value, err], - }); + } + .into(); } else { let set = helper!(class_private_field_set); - *e = Expr::Call(CallExpr { + *e = CallExpr { span: DUMMY_SP, callee: set, args: vec![this.as_arg(), ident.as_arg(), value.as_arg()], ..Default::default() - }); + } + .into(); } } @@ -415,24 +422,27 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { let (expr, this) = self.visit_mut_private_get(&mut tag, None); if let Some(this) = this { - *e = Expr::TaggedTpl(TaggedTpl { + *e = TaggedTpl { span: *span, - tag: Box::new(Expr::Call(CallExpr { + tag: CallExpr { span: DUMMY_SP, callee: expr.make_member(quote_ident!("bind")).as_callee(), args: vec![this.as_arg()], ..Default::default() - })), + } + .into(), tpl: tpl.take(), ..Default::default() - }); + } + .into(); } else { - *e = Expr::TaggedTpl(TaggedTpl { + *e = TaggedTpl { span: *span, tag: Box::new(expr), tpl: tpl.take(), ..Default::default() - }); + } + .into(); } } @@ -448,19 +458,21 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { let (expr, this) = self.visit_mut_private_get(&mut callee, None); if let Some(this) = this { - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, callee: expr.make_member(quote_ident!("call")).as_callee(), args: iter::once(this.as_arg()).chain(args.take()).collect(), ..Default::default() - }); + } + .into(); } else { - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, callee: expr.as_callee(), args: args.take(), ..Default::default() - }); + } + .into(); } } @@ -519,12 +531,12 @@ impl<'a> VisitMut for PrivateAccessVisitor<'a> { SyntaxContext::empty().apply_mark(mark), ); - *e = Expr::Call(CallExpr { + *e = CallExpr { callee: helper!(class_private_field_loose_base), span: *span, args: vec![obj.take().as_arg(), ident.clone().as_arg()], ..Default::default() - }) + } .computed_member(ident) .into(); } else { @@ -662,7 +674,7 @@ impl<'a> PrivateAccessVisitor<'a> { let h = helper!(class_static_private_method_get); return ( - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: h, args: vec![ @@ -671,21 +683,23 @@ impl<'a> PrivateAccessVisitor<'a> { method_name.as_arg(), ], ..Default::default() - }), - Some(Expr::Ident(class_name.clone())), + } + .into(), + Some(class_name.clone().into()), ); } let get = helper!(class_static_private_field_spec_get); ( - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: get, args: vec![obj.as_arg(), class_name.clone().as_arg(), ident.as_arg()], ..Default::default() - }), - Some(Expr::Ident(class_name.clone())), + } + .into(), + Some(class_name.clone().into()), ) } else { match self.private_access_type { @@ -821,7 +835,7 @@ impl<'a> PrivateAccessVisitor<'a> { ..Default::default() } .into(), - Some(Expr::Ident(var)), + Some(var.into()), ) } } diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/this_in_static.rs b/crates/swc_ecma_compat_es2022/src/class_properties/this_in_static.rs index 57a7c5d6bdc..5ef5df2beee 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/this_in_static.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/this_in_static.rs @@ -17,7 +17,7 @@ impl VisitMut for ThisInStaticFolder { e.visit_mut_children_with(self); if let Expr::This(..) = e { - *e = Expr::Ident(self.ident.clone()) + *e = self.ident.clone().into() } } 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 2596d63f7f4..0e706343502 100644 --- a/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs +++ b/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs @@ -116,9 +116,9 @@ impl VisitMut for OptionalChaining { arg: Some(a.right.take()), }), ]; - a.right = Box::new(Expr::Call(CallExpr { + a.right = CallExpr { span: DUMMY_SP, - callee: Expr::Arrow(ArrowExpr { + callee: ArrowExpr { span: DUMMY_SP, params: vec![], body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt { @@ -129,11 +129,12 @@ impl VisitMut for OptionalChaining { is_async: false, is_generator: false, ..Default::default() - }) + } .as_callee(), args: vec![], ..Default::default() - })); + } + .into(); } self.vars = uninit; @@ -158,7 +159,7 @@ enum Memo { impl Memo { fn into_expr(self) -> Expr { match self { - Memo::Cache(i) => Expr::Ident(i), + Memo::Cache(i) => i.into(), Memo::Raw(e) => *e, } } @@ -259,12 +260,12 @@ impl OptionalChaining { Gathering::Call(mut c) => { c.callee = current.as_callee(); ctx = None; - Expr::Call(c) + c.into() } Gathering::Member(mut m) => { m.obj = Box::new(current); ctx = None; - Expr::Member(m) + m.into() } Gathering::OptCall(mut c, memo) => { let mut call = false; @@ -278,12 +279,13 @@ impl OptionalChaining { match &this { Memo::Cache(i) => { - m.obj = Box::new(Expr::Assign(AssignExpr { + m.obj = AssignExpr { span: DUMMY_SP, op: op!("="), left: i.clone().into(), right: m.obj.take(), - })); + } + .into(); this } Memo::Raw(_) => this, @@ -316,7 +318,7 @@ impl OptionalChaining { memo.into_expr().as_callee() }; ctx = None; - Expr::Call(c) + c.into() } Gathering::OptMember(mut m, memo) => { committed_cond.push(CondExpr { @@ -331,24 +333,25 @@ impl OptionalChaining { }); ctx = Some(memo.clone()); m.obj = memo.into_expr().into(); - Expr::Member(m) + m.into() } }; } // At this point, `current` is the right-most expression `_a_b.c` in `a?.b?.c` if is_delete { - current = Expr::Unary(UnaryExpr { + current = UnaryExpr { span: DUMMY_SP, op: op!("delete"), arg: Box::new(current), - }); + } + .into(); } // We now need to reverse iterate the conditionals to construct out tree. for mut cond in committed_cond.into_iter().rev() { cond.alt = Box::new(current); - current = Expr::Cond(cond) + current = cond.into() } current } @@ -423,47 +426,52 @@ impl OptionalChaining { fn init_and_eq_null_or_undefined(i: &Memo, init: Expr, no_document_all: bool) -> Box { let lhs = match i { - Memo::Cache(i) => Box::new(Expr::Assign(AssignExpr { + Memo::Cache(i) => AssignExpr { span: DUMMY_SP, op: op!("="), left: i.clone().into(), right: Box::new(init), - })), + } + .into(), Memo::Raw(e) => e.to_owned(), }; if no_document_all { - return Box::new(Expr::Bin(BinExpr { + return BinExpr { span: DUMMY_SP, left: lhs, op: op!("=="), - right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), - })); + right: Box::new(Lit::Null(Null { span: DUMMY_SP }).into()), + } + .into(); } - let null_cmp = Box::new(Expr::Bin(BinExpr { + let null_cmp = BinExpr { span: DUMMY_SP, left: lhs, op: op!("==="), - right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), - })); + right: Box::new(Lit::Null(Null { span: DUMMY_SP }).into()), + } + .into(); let left_expr = match i { Memo::Cache(i) => Box::new(i.clone().into()), Memo::Raw(e) => e.to_owned(), }; - let void_cmp = Box::new(Expr::Bin(BinExpr { + let void_cmp = BinExpr { span: DUMMY_SP, left: left_expr, op: op!("==="), right: Expr::undefined(DUMMY_SP), - })); + } + .into(); - Box::new(Expr::Bin(BinExpr { + BinExpr { span: DUMMY_SP, left: null_cmp, op: op!("||"), right: void_cmp, - })) + } + .into() } 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 04c76643cc9..5007a935413 100644 --- a/crates/swc_ecma_compat_es2022/src/private_in_object.rs +++ b/crates/swc_ecma_compat_es2022/src/private_in_object.rs @@ -51,12 +51,15 @@ impl Mode { definite: Default::default(), }); if let Some(init) = init { - init_exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: n.into(), - right: init, - }))); + init_exprs.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: n.into(), + right: init, + } + .into(), + ); } } Mode::ClassDecl { vars } => { @@ -265,7 +268,7 @@ impl VisitMut for PrivateInObject { })); bs.visit_mut_with(self); - p.right = Box::new(Expr::Call(CallExpr { + p.right = CallExpr { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, @@ -278,7 +281,8 @@ impl VisitMut for PrivateInObject { .as_callee(), args: Default::default(), ..Default::default() - })); + } + .into(); } } } @@ -297,10 +301,11 @@ impl VisitMut for PrivateInObject { } _ => { prepend_exprs.push(Box::new(e.take())); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: DUMMY_SP, exprs: prepend_exprs, - }); + } + .into(); } } return; @@ -320,12 +325,13 @@ impl VisitMut for PrivateInObject { if let Some(cls_ident) = self.cls.ident.clone() { if is_static && is_method { - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op: op!("==="), - left: Box::new(Expr::Ident(cls_ident)), + left: cls_ident.into(), right: right.take(), - }); + } + .into(); return; } } @@ -337,18 +343,20 @@ impl VisitMut for PrivateInObject { { self.cls.vars.push_var( var_name.clone(), - Some(Box::new(Expr::New(NewExpr { - span: DUMMY_SP, - callee: Box::new(Expr::Ident(quote_ident!("WeakSet").into())), - args: Some(Default::default()), - ..Default::default() - }))), + Some( + NewExpr { + span: DUMMY_SP, + callee: Box::new(quote_ident!("WeakSet").into()), + args: Some(Default::default()), + ..Default::default() + } + .into(), + ), ); if is_method { - self.cls - .constructor_exprs - .push(Box::new(Expr::Call(CallExpr { + self.cls.constructor_exprs.push( + CallExpr { span: DUMMY_SP, callee: var_name .clone() @@ -356,16 +364,19 @@ impl VisitMut for PrivateInObject { .as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() - }))); + } + .into(), + ); } } - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, callee: var_name.make_member(quote_ident!("has")).as_callee(), args: vec![right.take().as_arg()], ..Default::default() - }); + } + .into(); } _ => {} @@ -404,36 +415,45 @@ impl VisitMut for PrivateInObject { self.cls.vars.push_var(tmp.clone(), None); - let assign = Box::new(Expr::Assign(AssignExpr { + let assign = AssignExpr { span: DUMMY_SP, op: op!("="), left: tmp.clone().into(), right: init.take(), - })); + } + .into(); - let add_to_checker = Box::new(Expr::Call(CallExpr { + let add_to_checker = CallExpr { span: DUMMY_SP, callee: var_name.make_member(quote_ident!("add")).as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() - })); + } + .into(); - *init = Box::new(Expr::Seq(SeqExpr { + *init = SeqExpr { span: init_span, exprs: vec![assign, add_to_checker, Box::new(tmp.into())], - })); + } + .into(); } None => { - n.value = Some(Box::new(Expr::Unary(UnaryExpr { - span: DUMMY_SP, - op: op!("void"), - arg: Box::new(Expr::Call(CallExpr { + n.value = Some( + UnaryExpr { span: DUMMY_SP, - callee: var_name.make_member(quote_ident!("add")).as_callee(), - args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], - ..Default::default() - })), - }))) + op: op!("void"), + arg: Box::new( + CallExpr { + span: DUMMY_SP, + callee: var_name.make_member(quote_ident!("add")).as_callee(), + args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], + ..Default::default() + } + .into(), + ), + } + .into(), + ) } } } diff --git a/crates/swc_ecma_compat_es2022/src/static_blocks.rs b/crates/swc_ecma_compat_es2022/src/static_blocks.rs index 7727ec05cfb..ebf60c3ea13 100644 --- a/crates/swc_ecma_compat_es2022/src/static_blocks.rs +++ b/crates/swc_ecma_compat_es2022/src/static_blocks.rs @@ -30,7 +30,7 @@ impl ClassStaticBlock { } else { static_block.body.stmts = stmts; - let expr = Expr::Call(CallExpr { + let expr = CallExpr { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, @@ -43,7 +43,8 @@ impl ClassStaticBlock { .as_callee(), args: Vec::new(), ..Default::default() - }); + } + .into(); Some(Box::new(expr)) }; diff --git a/crates/swc_ecma_compat_es3/src/member_expr_lits.rs b/crates/swc_ecma_compat_es3/src/member_expr_lits.rs index 533adcb53d4..ef43cce475c 100644 --- a/crates/swc_ecma_compat_es3/src/member_expr_lits.rs +++ b/crates/swc_ecma_compat_es3/src/member_expr_lits.rs @@ -42,11 +42,12 @@ impl Fold for MemberExprLit { return MemberExpr { prop: MemberProp::Computed(ComputedPropName { span: i.span, - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span: i.span, raw: None, value: i.sym, - }))), + }) + .into(), }), ..e }; diff --git a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs index 5918a46b445..cf494989b58 100644 --- a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs +++ b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs @@ -148,7 +148,7 @@ impl Hoister<'_> { var_decls.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(id.into()), + name: id.into(), init: None, definite: false, }) @@ -157,12 +157,15 @@ impl Hoister<'_> { if let Some(init) = decl.init { // - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: decl.span, - left: decl.name.try_into().unwrap(), - op: op!("="), - right: init, - }))); + exprs.push( + AssignExpr { + span: decl.span, + left: decl.name.try_into().unwrap(), + op: op!("="), + right: init, + } + .into(), + ); } } @@ -174,10 +177,11 @@ impl Hoister<'_> { expr: if exprs.len() == 1 { exprs.into_iter().next().unwrap() } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - })) + } + .into() }, }))) } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs b/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs index ae9884e4566..eec94a93ab6 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/arguments.rs @@ -135,7 +135,7 @@ impl ArgReplacer<'_> { let p = Param { span: DUMMY_SP, decorators: Default::default(), - pat: Pat::Ident(private_ident!(format!("argument_{}", start)).into()), + pat: private_ident!(format!("argument_{}", start)).into(), }; start += 1; p @@ -191,7 +191,7 @@ impl VisitMut for ArgReplacer<'_> { "arguments: Replacing access to arguments to normal \ reference" ); - *n = Expr::Ident(i.id.clone()); + *n = i.id.clone().into(); } } } @@ -213,7 +213,7 @@ impl VisitMut for ArgReplacer<'_> { reference" ); self.changed = true; - *n = Expr::Ident(i.id.clone()); + *n = i.id.clone().into(); } } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/bools.rs b/crates/swc_ecma_minifier/src/compress/optimize/bools.rs index 9251a3bab8f..342334f2e38 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/bools.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/bools.rs @@ -99,12 +99,13 @@ impl Optimizer<'_> { report_change!("conditionals: `if (foo) bar;` => `foo && bar`"); *s = Stmt::Expr(ExprStmt { span: stmt.span, - expr: Box::new(Expr::Bin(BinExpr { + expr: BinExpr { span: stmt.test.span(), op: op!("&&"), left: stmt.test.take(), right: cons.expr.take(), - })), + } + .into(), }); } } @@ -194,7 +195,7 @@ impl Optimizer<'_> { span: e.span, op: e.op, left: left.left.take(), - right: Box::new(Expr::Bin(res)), + right: res.into(), }; } } @@ -283,7 +284,7 @@ impl Optimizer<'_> { span, op: op!("=="), left: cmp.take(), - right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), + right: Lit::Null(Null { span: DUMMY_SP }).into(), }); } else { report_change!( @@ -293,7 +294,7 @@ impl Optimizer<'_> { span, op: op!("!="), left: cmp.take(), - right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), + right: Lit::Null(Null { span: DUMMY_SP }).into(), }); } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs index 80961c45d16..49fe57d3f3b 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs @@ -66,24 +66,26 @@ impl Optimizer<'_> { if !cond.cons.may_have_side_effects(&self.expr_ctx) { self.changed = true; report_change!("conditionals: `cond ? useless : alt` => `cond || alt`"); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("||"), left: cond.test.take(), right: cond.alt.take(), - }); + } + .into(); return; } if !cond.alt.may_have_side_effects(&self.expr_ctx) { self.changed = true; report_change!("conditionals: `cond ? cons : useless` => `cond && cons`"); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("&&"), left: cond.test.take(), right: cond.cons.take(), - }); + } + .into(); } } @@ -144,12 +146,13 @@ impl Optimizer<'_> { if SyntaxContext::within_ignored_ctxt(|| { cur_if.cons.eq_ignore_span(&stmt.cons) }) { - cur_if.test = Box::new(Expr::Bin(BinExpr { + cur_if.test = BinExpr { span: DUMMY_SP, left: cur_if.test.take(), op: op!("||"), right: stmt.test.take(), - })); + } + .into(); } else { new.extend(cur.take().map(Stmt::If).map(T::from_stmt)); @@ -244,31 +247,33 @@ impl Optimizer<'_> { }) => { report_change!("Optimizing `if (!foo); else bar();` as `foo && bar();`"); - let mut expr = Box::new(Expr::Bin(BinExpr { + let mut expr = BinExpr { span: DUMMY_SP, left: arg.take(), op: op!("&&"), right: Box::new(alt.take()), - })); + } + .into(); self.compress_logical_exprs_as_bang_bang(&mut expr, true); *s = Stmt::Expr(ExprStmt { span: stmt.span, - expr, + expr: expr.into(), }); } _ => { report_change!("Optimizing `if (foo); else bar();` as `foo || bar();`"); - let mut expr = Box::new(Expr::Bin(BinExpr { + let mut expr = BinExpr { span: DUMMY_SP, left: stmt.test.take(), op: op!("||"), right: Box::new(alt.take()), - })); + } + .into(); self.compress_logical_exprs_as_bang_bang(&mut expr, false); *s = Stmt::Expr(ExprStmt { span: stmt.span, - expr, + expr: expr.into(), }); } } @@ -303,12 +308,13 @@ impl Optimizer<'_> { self.changed = true; *s = Stmt::Expr(ExprStmt { span: stmt.span, - expr: Box::new(Expr::Cond(CondExpr { + expr: CondExpr { span: DUMMY_SP, test: stmt.test.take(), cons: Box::new(cons.take()), alt: Box::new(alt.take()), - })), + } + .into(), }) } } @@ -337,12 +343,13 @@ impl Optimizer<'_> { if cond.test.is_ident() && cond.test.eq_ignore_span(&cond.cons) { report_change!("Compressing `x ? x : y` as `x || y`"); self.changed = true; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("||"), left: cond.test.take(), right: cond.alt.take(), - }); + } + .into(); } } @@ -358,10 +365,13 @@ impl Optimizer<'_> { if cons.eq_ignore_span(alt) && !matches!(&*cons, Expr::Yield(..) | Expr::Fn(..)) { report_change!("conditionals: cons is same as alt"); - return Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs: vec![test.take(), Box::new(cons.take())], - })); + return Some( + SeqExpr { + span: DUMMY_SP, + exprs: vec![test.take(), Box::new(cons.take())], + } + .into(), + ); } match (cons, alt) { @@ -418,12 +428,13 @@ impl Optimizer<'_> { // Inject conditional. new_args.push(ExprOrSpread { spread: None, - expr: Box::new(Expr::Cond(CondExpr { + expr: CondExpr { span: arg.expr.span(), test: test.take(), cons: arg.expr, alt: alt.args[idx].expr.take(), - })), + } + .into(), }) } else { // @@ -431,12 +442,15 @@ impl Optimizer<'_> { } } - return Some(Expr::Call(CallExpr { - span: test.span(), - callee: cons_callee.clone().as_callee(), - args: new_args, - ..Default::default() - })); + return Some( + CallExpr { + span: test.span(), + callee: cons_callee.clone().as_callee(), + args: new_args, + ..Default::default() + } + .into(), + ); } } @@ -466,22 +480,28 @@ impl Optimizer<'_> { "Compressing if into cond as there's no side effect and the number of \ arguments is 1" ); - return Some(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: cons.callee.take(), - args, - ..Default::default() - })); + return Some( + CallExpr { + span: DUMMY_SP, + callee: cons.callee.take(), + args, + ..Default::default() + } + .into(), + ); } if !side_effect_free && is_for_if_stmt { report_change!("Compressing if into cond while preserving side effects"); - return Some(Expr::Cond(CondExpr { - span: DUMMY_SP, - test: test.take(), - cons: Box::new(Expr::Call(cons.take())), - alt: Box::new(Expr::Call(alt.take())), - })); + return Some( + CondExpr { + span: DUMMY_SP, + test: test.take(), + cons: cons.take().into(), + alt: alt.take().into(), + } + .into(), + ); } None @@ -532,12 +552,15 @@ impl Optimizer<'_> { "Compressing if statement into a conditional expression of `new` as \ there's no side effect and the number of arguments is 1" ); - return Some(Expr::New(NewExpr { - span: DUMMY_SP, - callee: cons.callee.take(), - args: Some(args), - ..Default::default() - })); + return Some( + NewExpr { + span: DUMMY_SP, + callee: cons.callee.take(), + args: Some(args), + ..Default::default() + } + .into(), + ); } None @@ -552,33 +575,41 @@ impl Optimizer<'_> { } report_change!("Merging assignments in cons and alt of if statement"); - Some(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: cons.op, - left: cons.left.take(), - right: Box::new(Expr::Cond(CondExpr { + Some( + AssignExpr { span: DUMMY_SP, - test: test.take(), - cons: cons.right.take(), - alt: alt.right.take(), - })), - })) + op: cons.op, + left: cons.left.take(), + right: CondExpr { + span: DUMMY_SP, + test: test.take(), + cons: cons.right.take(), + alt: alt.right.take(), + } + .into(), + } + .into(), + ) } // a ? b ? c() : d() : d() => a && b ? c() : d() (Expr::Cond(cons), alt) if (*cons.alt).eq_ignore_span(&*alt) => { report_change!("conditionals: a ? b ? c() : d() : d() => a && b ? c() : d()"); - Some(Expr::Cond(CondExpr { - span: DUMMY_SP, - test: Box::new(Expr::Bin(BinExpr { + Some( + CondExpr { span: DUMMY_SP, - left: test.take(), - op: op!("&&"), - right: cons.test.take(), - })), - cons: cons.cons.take(), - alt: cons.alt.take(), - })) + test: BinExpr { + span: DUMMY_SP, + left: test.take(), + op: op!("&&"), + right: cons.test.take(), + } + .into(), + cons: cons.cons.take(), + alt: cons.alt.take(), + } + .into(), + ) } // z ? "fuji" : (condition(), "fuji"); @@ -589,16 +620,20 @@ impl Optimizer<'_> { report_change!("conditionals: Reducing seq expr in alt"); // alt.exprs.pop(); - let first = Box::new(Expr::Bin(BinExpr { + let first = BinExpr { span: DUMMY_SP, left: test.take(), op: op!("||"), right: Expr::from_exprs(alt.exprs.take()), - })); - Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs: vec![first, Box::new(cons.take())], - })) + } + .into(); + Some( + SeqExpr { + span: DUMMY_SP, + exprs: vec![first, Box::new(cons.take())], + } + .into(), + ) } // z ? (condition(), "fuji") : "fuji" @@ -609,16 +644,20 @@ impl Optimizer<'_> { report_change!("conditionals: Reducing seq expr in cons"); // cons.exprs.pop(); - let first = Box::new(Expr::Bin(BinExpr { + let first = BinExpr { span: DUMMY_SP, left: test.take(), op: op!("&&"), right: Expr::from_exprs(cons.exprs.take()), - })); - Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs: vec![first, Box::new(alt.take())], - })) + } + .into(); + Some( + SeqExpr { + span: DUMMY_SP, + exprs: vec![first, Box::new(alt.take())], + } + .into(), + ) } (Expr::Seq(left), Expr::Seq(right)) => { @@ -657,10 +696,13 @@ impl Optimizer<'_> { }))]; seq.append(&mut left.exprs); - Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs: seq, - })) + Some( + SeqExpr { + span: DUMMY_SP, + exprs: seq, + } + .into(), + ) } else if idx == right_len { self.changed = true; report_change!("conditionals: Reducing similar seq expr in alt"); @@ -677,10 +719,13 @@ impl Optimizer<'_> { }))]; seq.append(&mut right.exprs); - Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs: seq, - })) + Some( + SeqExpr { + span: DUMMY_SP, + exprs: seq, + } + .into(), + ) } else { self.changed = true; report_change!("conditionals: Reducing similar seq expr"); @@ -695,10 +740,13 @@ impl Optimizer<'_> { }))]; seq.append(&mut common); - Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs: seq, - })) + Some( + SeqExpr { + span: DUMMY_SP, + exprs: seq, + } + .into(), + ) } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs b/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs index d883690e627..7fec4b5b8a0 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs @@ -87,12 +87,13 @@ impl Optimizer<'_> { ); self.changed = true; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: assign.span, op, - left: Box::new(Expr::Ident(lhs.clone().into())), + left: lhs.clone().into(), right: assign.right.take(), - }); + } + .into(); return true; } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs b/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs index 461e552d82e..f285788f043 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs @@ -49,22 +49,24 @@ impl Optimizer<'_> { "length" => { report_change!("evaluate: function.length"); - *e = Expr::Lit(Lit::Num(Number { + *e = Lit::Num(Number { span: *span, value: metadata.len as _, raw: None, - })); + }) + .into(); self.changed = true; } "name" => { report_change!("evaluate: function.name"); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: *span, value: obj.sym.clone(), raw: None, - })); + }) + .into(); self.changed = true; } @@ -113,20 +115,23 @@ impl Optimizer<'_> { Expr::Ident(Ident { span, sym, .. }) if &**sym == "Infinity" => { report_change!("evaluate: `Infinity` -> `1 / 0`"); self.changed = true; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op: op!("/"), - left: Box::new(Expr::Lit(Lit::Num(Number { + left: Lit::Num(Number { span: DUMMY_SP, value: 1.0, raw: None, - }))), - right: Box::new(Expr::Lit(Lit::Num(Number { + }) + .into(), + right: Lit::Num(Number { span: DUMMY_SP, value: 0.0, raw: None, - }))), - }); + }) + .into(), + } + .into(); } _ => {} @@ -187,11 +192,12 @@ impl Optimizer<'_> { exp.value ); - *e = Expr::Lit(Lit::Regex(Regex { + *e = Lit::Regex(Regex { span, exp: exp.value.as_ref().into(), flags: atom!(""), - })); + }) + .into(); } } _ => { @@ -205,11 +211,12 @@ impl Optimizer<'_> { flags.value ); - *e = Expr::Lit(Lit::Regex(Regex { + *e = Lit::Regex(Regex { span, exp: exp.value.as_ref().into(), flags: flags.value.as_ref().into(), - })); + }) + .into(); } } } @@ -242,11 +249,12 @@ impl Optimizer<'_> { let value = v.to_string(); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value: value.into(), - })); + }) + .into(); } } } @@ -272,28 +280,30 @@ impl Optimizer<'_> { Prop::Shorthand(p) => { keys.push(Some(ExprOrSpread { spread: None, - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span: p.span, raw: None, value: p.sym.clone(), - }))), + }) + .into(), })); } Prop::KeyValue(p) => match &p.key { PropName::Ident(key) => { keys.push(Some(ExprOrSpread { spread: None, - expr: Box::new(Expr::Lit(Lit::Str(Str { + expr: Lit::Str(Str { span: key.span, raw: None, value: key.sym.clone(), - }))), + }) + .into(), })); } PropName::Str(key) => { keys.push(Some(ExprOrSpread { spread: None, - expr: Box::new(Expr::Lit(Lit::Str(key.clone()))), + expr: Lit::Str(key.clone()).into(), })); } _ => return, @@ -303,7 +313,7 @@ impl Optimizer<'_> { } } - *e = Expr::Array(ArrayLit { span, elems: keys }) + *e = ArrayLit { span, elems: keys }.into() } } @@ -335,11 +345,12 @@ impl Optimizer<'_> { self.changed = true; report_change!("evaluate: Evaluated an expression as `{}`", value); - *e = Expr::Lit(Lit::Num(Number { + *e = Lit::Num(Number { span: e.span(), value, raw: None, - })); + }) + .into(); return; } } @@ -355,17 +366,19 @@ impl Optimizer<'_> { report_change!("evaluate: Evaluated `{:?} ** {:?}`", l, r); if l.is_nan() || r.is_nan() { - *e = Expr::Ident(Ident::new( + *e = Ident::new( "NaN".into(), bin.span, SyntaxContext::empty().apply_mark(self.marks.unresolved_mark), - )); + ) + .into(); } else { - *e = Expr::Lit(Lit::Num(Number { + *e = Lit::Num(Number { span: bin.span, value: l.powf(r), raw: None, - })); + }) + .into(); }; } } @@ -401,11 +414,12 @@ impl Optimizer<'_> { report_change!("evaluate: `0 / 0` => `NaN`"); // Sign does not matter for NaN - *e = Expr::Ident(Ident::new( + *e = Ident::new( "NaN".into(), bin.span, SyntaxContext::empty().apply_mark(self.marks.unresolved_mark), - )); + ) + .into(); } (FpCategory::Normal, FpCategory::Zero) => { self.changed = true; @@ -413,16 +427,14 @@ impl Optimizer<'_> { // Sign does not matter for NaN *e = if ln.is_sign_positive() == rn.is_sign_positive() { - Expr::Ident(Ident::new_no_ctxt("Infinity".into(), bin.span)) + Ident::new_no_ctxt("Infinity".into(), bin.span).into() } else { - Expr::Unary(UnaryExpr { + UnaryExpr { span: bin.span, op: op!(unary, "-"), - arg: Box::new(Expr::Ident(Ident::new_no_ctxt( - "Infinity".into(), - bin.span, - ))), - }) + arg: Ident::new_no_ctxt("Infinity".into(), bin.span).into(), + } + .into() }; } _ => {} 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 73c56655359..1a86d3fbbec 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs @@ -31,12 +31,13 @@ impl Optimizer<'_> { self.changed = true; report_change!("if_return: Merging nested if statements"); - s.test = Box::new(Expr::Bin(BinExpr { + s.test = BinExpr { span: s.test.span(), op: op!("&&"), left: s.test.take(), right: test.take(), - })); + } + .into(); s.cons = cons.take(); } } @@ -313,7 +314,7 @@ impl Optimizer<'_> { ) } }, - None => cur = Some(Box::new(Expr::Seq(v))), + None => cur = Some(v.into()), }, Expr::Cond(v) => match &mut cur { Some(cur) => match &mut **cur { @@ -328,26 +329,31 @@ impl Optimizer<'_> { (prev_seq.span, exprs) }; - *alt = Expr::Cond(CondExpr { + *alt = CondExpr { span: DUMMY_SP, - test: Box::new(Expr::Seq(SeqExpr { span, exprs })), + test: SeqExpr { span, exprs }.into(), cons: v.cons, alt: v.alt, - }); + } + .into(); } Expr::Seq(prev_seq) => { prev_seq.exprs.push(v.test); let exprs = prev_seq.exprs.take(); - *cur = Box::new(Expr::Cond(CondExpr { + *cur = CondExpr { span: DUMMY_SP, - test: Box::new(Expr::Seq(SeqExpr { - span: prev_seq.span, - exprs, - })), + test: Box::new( + SeqExpr { + span: prev_seq.span, + exprs, + } + .into(), + ), cons: v.cons, alt: v.alt, - })); + } + .into(); } _ => { unreachable!( @@ -356,7 +362,7 @@ impl Optimizer<'_> { ) } }, - None => cur = Some(Box::new(Expr::Cond(v))), + None => cur = Some(v.into()), }, _ => { unreachable!( @@ -432,34 +438,41 @@ impl Optimizer<'_> { exprs.push(test); - Expr::Cond(CondExpr { + CondExpr { span, - test: Box::new(Expr::Seq(SeqExpr { + test: SeqExpr { span: DUMMY_SP, exprs, - })), + } + .into(), cons, alt, - }) + } + .into() } Stmt::Expr(stmt) => { - exprs.push(Box::new(Expr::Unary(UnaryExpr { - span: DUMMY_SP, - op: op!("void"), - arg: stmt.expr, - }))); - Expr::Seq(SeqExpr { + exprs.push( + UnaryExpr { + span: DUMMY_SP, + op: op!("void"), + arg: stmt.expr, + } + .into(), + ); + SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } Stmt::Return(stmt) => { let span = stmt.span; exprs.push(stmt.arg.unwrap_or_else(|| Expr::undefined(span))); - Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } _ => unreachable!(), } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/iife.rs b/crates/swc_ecma_minifier/src/compress/optimize/iife.rs index e975ffeac3d..fb90c9d1b65 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/iife.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/iife.rs @@ -35,11 +35,12 @@ impl Optimizer<'_> { if let Expr::Fn(..) = callee { report_change!("negate_iife: Negating iife"); - *e = Expr::Unary(UnaryExpr { + *e = UnaryExpr { span: DUMMY_SP, op: op!("!"), arg: Box::new(e.take()), - }); + } + .into(); } } @@ -66,11 +67,12 @@ impl Optimizer<'_> { match callee { Expr::Fn(..) => { report_change!("negate_iife: Swapping cons and alt"); - cond.test = Box::new(Expr::Unary(UnaryExpr { + cond.test = UnaryExpr { span: DUMMY_SP, op: op!("!"), arg: cond.test.take(), - })); + } + .into(); swap(&mut cond.cons, &mut cond.alt); true } @@ -95,12 +97,13 @@ impl Optimizer<'_> { }) = &mut **arg { if let Expr::Fn(..) = &**callee { - cond.test = Box::new(Expr::Call(CallExpr { + cond.test = CallExpr { span: *call_span, callee: callee.take().as_callee(), args: args.take(), ..Default::default() - })); + } + .into(); swap(&mut cond.cons, &mut cond.alt); } } @@ -263,7 +266,7 @@ impl Optimizer<'_> { vars.insert( param_id.to_id(), - Box::new(Expr::Array(ArrayLit { + ArrayLit { span: param_id.span, elems: e .args @@ -271,7 +274,8 @@ impl Optimizer<'_> { .skip(idx) .map(|arg| Some(arg.clone())) .collect(), - })), + } + .into(), ); param.take(); } @@ -899,7 +903,7 @@ impl Optimizer<'_> { vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(param.clone().into()), + name: param.clone().into(), init: if self.ctx.executed_multiple_time && no_arg { Some(Expr::undefined(DUMMY_SP)) } else { @@ -970,12 +974,15 @@ impl Optimizer<'_> { } } - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: decl.name.clone().try_into().unwrap(), - right: decl.init.take().unwrap(), - }))) + exprs.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: decl.name.clone().try_into().unwrap(), + right: decl.init.take().unwrap(), + } + .into(), + ) } } @@ -997,7 +1004,7 @@ impl Optimizer<'_> { }; self.merge_sequences_in_seq_expr(&mut e); - let mut e = Expr::Seq(e); + let mut e = e.into(); self.normalize_expr(&mut e); return Some(e); } @@ -1006,11 +1013,12 @@ impl Optimizer<'_> { } if let Some(last) = exprs.last_mut() { - *last = Box::new(Expr::Unary(UnaryExpr { + *last = UnaryExpr { span: DUMMY_SP, op: op!("void"), arg: last.take(), - })); + } + .into(); } else { return Some(*Expr::undefined(body.span)); } @@ -1021,7 +1029,7 @@ impl Optimizer<'_> { }; self.merge_sequences_in_seq_expr(&mut e); - let mut e = Expr::Seq(e); + let mut e = e.into(); self.normalize_expr(&mut e); Some(e) } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/inline.rs b/crates/swc_ecma_minifier/src/compress/optimize/inline.rs index 6a60f292014..73e9b3a3bd8 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/inline.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/inline.rs @@ -688,10 +688,11 @@ impl Optimizer<'_> { self.vars.simple_functions.insert( i.to_id(), - Box::new(Expr::Fn(FnExpr { + FnExpr { ident: None, function: f.function.clone(), - })), + } + .into(), ); return; @@ -764,18 +765,20 @@ impl Optimizer<'_> { } let e = match decl.take() { - Decl::Class(c) => Box::new(Expr::Class(ClassExpr { + Decl::Class(c) => ClassExpr { ident: Some(c.ident), class: c.class, - })), - Decl::Fn(f) => Box::new(Expr::Fn(FnExpr { + } + .into(), + Decl::Fn(f) => FnExpr { ident: if usage.used_recursively { Some(f.ident) } else { None }, function: f.function, - })), + } + .into(), _ => { unreachable!() } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs index a1947298fe2..662b6051b03 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs @@ -641,15 +641,17 @@ impl Optimizer<'_> { if let Lit::Bool(v) = lit { self.changed = true; report_change!("Compressing boolean literal"); - *e = Expr::Unary(UnaryExpr { + *e = UnaryExpr { span: v.span, op: op!("!"), - arg: Box::new(Expr::Lit(Lit::Num(Number { + arg: Lit::Num(Number { span: v.span, value: if v.value { 0.0 } else { 1.0 }, raw: None, - }))), - }); + }) + .into(), + } + .into(); } } } @@ -716,7 +718,7 @@ impl Optimizer<'_> { .any(|m| m.as_static_block().iter().any(|s| !s.body.is_empty())) { // there's nothing we can do about it - return Some(Expr::Class(cls.take())); + return Some(cls.take().into()); } let exprs: Vec> = @@ -730,10 +732,13 @@ impl Optimizer<'_> { return None; } - return Some(Expr::Seq(SeqExpr { - span: cls.class.span, - exprs, - })); + return Some( + SeqExpr { + span: cls.class.span, + exprs, + } + .into(), + ); } Expr::Paren(e) => return self.ignore_return_value(&mut e.expr), @@ -807,10 +812,13 @@ impl Optimizer<'_> { self.changed = true; report_change!("ignore_return_value: Compressing binary as seq"); - return Some(Expr::Seq(SeqExpr { - span, - exprs: vec![Box::new(left.unwrap()), Box::new(right.unwrap())], - })); + return Some( + SeqExpr { + span, + exprs: vec![Box::new(left.unwrap()), Box::new(right.unwrap())], + } + .into(), + ); } // Pure calls can be removed @@ -890,10 +898,13 @@ impl Optimizer<'_> { return None; } - return Some(Expr::Array(ArrayLit { - span: callee.span, - elems, - })); + return Some( + ArrayLit { + span: callee.span, + elems, + } + .into(), + ); } let args = args @@ -907,10 +918,13 @@ impl Optimizer<'_> { return None; } - return Some(Expr::Seq(SeqExpr { - span: callee.span, - exprs: args, - })); + return Some( + SeqExpr { + span: callee.span, + exprs: args, + } + .into(), + ); } } } @@ -1022,25 +1036,28 @@ impl Optimizer<'_> { }) => true, _ => false, }) { - return Some(Expr::Array(ArrayLit { - elems: arr - .elems - .take() - .into_iter() - .flatten() - .filter_map(|mut e| { - if e.spread.is_some() { - return Some(e); - } + return Some( + ArrayLit { + elems: arr + .elems + .take() + .into_iter() + .flatten() + .filter_map(|mut e| { + if e.spread.is_some() { + return Some(e); + } - self.ignore_return_value(&mut e.expr) - .map(Box::new) - .map(|expr| ExprOrSpread { expr, spread: None }) - }) - .map(Some) - .collect(), - ..*arr - })); + self.ignore_return_value(&mut e.expr) + .map(Box::new) + .map(|expr| ExprOrSpread { expr, spread: None }) + }) + .map(Some) + .collect(), + ..*arr + } + .into(), + ); } let mut exprs = vec![]; @@ -1060,10 +1077,13 @@ impl Optimizer<'_> { return None; } - return Some(Expr::Seq(SeqExpr { - span: arr.span, - exprs, - })); + return Some( + SeqExpr { + span: arr.span, + exprs, + } + .into(), + ); } Expr::Object(obj) => { @@ -1120,10 +1140,13 @@ impl Optimizer<'_> { return None; } - return Some(Expr::Seq(SeqExpr { - span: obj.span, - exprs, - })); + return Some( + SeqExpr { + span: obj.span, + exprs, + } + .into(), + ); } // Preserves negated iife @@ -1174,10 +1197,11 @@ impl Optimizer<'_> { let left = self.ignore_return_value(left).map(Box::new); let right = self.ignore_return_value(right).map(Box::new); - let mut seq = Expr::Seq(SeqExpr { + let mut seq = SeqExpr { span: *span, exprs: left.into_iter().chain(right).collect(), - }); + } + .into(); return self.ignore_return_value(&mut seq); } @@ -1205,20 +1229,23 @@ impl Optimizer<'_> { // TODO: Remove if test is side effect free. - return Some(Expr::Cond(CondExpr { - span: cond.span, - test: cond.test.take(), - cons: cons.unwrap_or_else(|| { - report_change!("ignore_return_value: Dropped `cons`"); - self.changed = true; - Expr::undefined(cons_span) - }), - alt: alt.unwrap_or_else(|| { - report_change!("ignore_return_value: Dropped `alt`"); - self.changed = true; - Expr::undefined(alt_span) - }), - })); + return Some( + CondExpr { + span: cond.span, + test: cond.test.take(), + cons: cons.unwrap_or_else(|| { + report_change!("ignore_return_value: Dropped `cons`"); + self.changed = true; + Expr::undefined(cons_span) + }), + alt: alt.unwrap_or_else(|| { + report_change!("ignore_return_value: Dropped `alt`"); + self.changed = true; + Expr::undefined(alt_span) + }), + } + .into(), + ); } Expr::Seq(seq) => { @@ -1263,11 +1290,12 @@ impl Optimizer<'_> { if let Some(last) = exprs.last_mut() { report_change!("ignore_return_value: Shifting void"); self.changed = true; - *last = Box::new(Expr::Unary(UnaryExpr { + *last = UnaryExpr { span: DUMMY_SP, op: op!("void"), arg: last.take(), - })); + } + .into(); } } @@ -1276,10 +1304,13 @@ impl Optimizer<'_> { return None; } - return Some(Expr::Seq(SeqExpr { - span: seq.span, - exprs, - })); + return Some( + SeqExpr { + span: seq.span, + exprs, + } + .into(), + ); } } @@ -1626,18 +1657,20 @@ impl VisitMut for Optimizer<'_> { if is_this_undefined { if let Callee::Expr(callee) = &mut e.callee { if let Expr::Member(..) = &mut **callee { - let zero = Box::new(Expr::Lit(Lit::Num(Number { + let zero = Lit::Num(Number { span: DUMMY_SP, value: 0.0, raw: None, - }))); + }) + .into(); self.changed = true; report_change!("injecting zero to preserve `this` in call"); - *callee = Box::new(Expr::Seq(SeqExpr { + *callee = SeqExpr { span: callee.span(), exprs: vec![zero, callee.take()], - })); + } + .into(); } } } @@ -2393,12 +2426,12 @@ impl VisitMut for Optimizer<'_> { if let Prop::Shorthand(i) = n { if self.vars.has_pending_inline_for(&i.to_id()) { - let mut e = Box::new(Expr::Ident(i.clone())); + let mut e: Expr = i.clone().into(); e.visit_mut_with(self); *n = Prop::KeyValue(KeyValueProp { key: PropName::Ident(i.clone().into()), - value: e, + value: Box::new(e), }); } } @@ -3036,10 +3069,11 @@ impl VisitMut for Optimizer<'_> { expr: if side_effects.len() == 1 { side_effects.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs: side_effects.take(), - })) + } + .into() }, })); } else { @@ -3061,10 +3095,11 @@ impl VisitMut for Optimizer<'_> { expr: if side_effects.len() == 1 { side_effects.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs: side_effects, - })) + } + .into() }, })); } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/ops.rs b/crates/swc_ecma_minifier/src/compress/optimize/ops.rs index 10c84622d85..9ff07101c11 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/ops.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/ops.rs @@ -119,10 +119,13 @@ impl Optimizer<'_> { let flag = n.op == op!("!="); let mut make_lit_bool = |value: bool| { self.changed = true; - Some(Expr::Lit(Lit::Bool(Bool { - span: n.span, - value: flag ^ value, - }))) + Some( + Lit::Bool(Bool { + span: n.span, + value: flag ^ value, + }) + .into(), + ) }; match (n.left.get_type().opt()?, n.right.get_type().opt()?) { // Abort if types differ, or one of them is unknown. @@ -358,32 +361,35 @@ impl Optimizer<'_> { "Converting typeof of variable to literal as we know the value" ); self.changed = true; - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: *span, raw: None, value, - })); + }) + .into(); } } Expr::Arrow(..) | Expr::Fn(..) => { report_change!("Converting typeof to 'function' as we know the value"); self.changed = true; - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: *span, raw: None, value: "function".into(), - })); + }) + .into(); } Expr::Array(..) | Expr::Object(..) => { report_change!("Converting typeof to 'object' as we know the value"); self.changed = true; - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: *span, raw: None, value: "object".into(), - })); + }) + .into(); } _ => {} } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs index 4a28935df65..814c47a04d1 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs @@ -458,12 +458,13 @@ impl Optimizer<'_> { report_change!("sequences: Lifting Assign"); self.changed = true; if let Some(last) = seq.exprs.last_mut() { - **last = Expr::Assign(AssignExpr { + **last = AssignExpr { span: *span, op: op!("="), left: left.take(), right: last.take(), - }) + } + .into() } *e = *right.take() @@ -541,11 +542,12 @@ impl Optimizer<'_> { e.exprs.pop(); let last = e.exprs.last_mut().unwrap(); - *last = Box::new(Expr::Unary(UnaryExpr { + *last = UnaryExpr { span: DUMMY_SP, op: op!("void"), arg: last.take(), - })) + } + .into() } } } @@ -1279,7 +1281,7 @@ impl Optimizer<'_> { } } - if !self.is_skippable_for_seq(a, &Expr::Ident(left_id.id.clone())) { + if !self.is_skippable_for_seq(a, &left_id.id.clone().into()) { return false; } @@ -1315,7 +1317,7 @@ impl Optimizer<'_> { PropOrSpread::Spread(_) => return false, PropOrSpread::Prop(p) => match &**p { Prop::Shorthand(i) => { - if !self.is_skippable_for_seq(a, &Expr::Ident(i.clone())) { + if !self.is_skippable_for_seq(a, &i.clone().into()) { return false; } } @@ -1785,7 +1787,7 @@ impl Optimizer<'_> { return Ok(false); }; - if !self.is_skippable_for_seq(Some(a), &Expr::Ident(b_left.id.clone())) { + if !self.is_skippable_for_seq(Some(a), &b_left.id.clone().into()) { // Let's be safe if IdentUsageFinder::find(&b_left.to_id(), &b_assign.right) { return Ok(false); @@ -1871,17 +1873,19 @@ impl Optimizer<'_> { if self.merge_sequential_expr(a, b_callee)? { if is_this_undefined { if let Expr::Member(..) = &**b_callee { - let zero = Box::new(Expr::Lit(Lit::Num(Number { + let zero = Lit::Num(Number { span: DUMMY_SP, value: 0.0, raw: None, - }))); + }) + .into(); report_change!("injecting zero to preserve `this` in call"); - *b_callee = Box::new(Expr::Seq(SeqExpr { + *b_callee = SeqExpr { span: b_callee.span(), exprs: vec![zero, b_callee.take()], - })); + } + .into(); } } @@ -1988,7 +1992,7 @@ impl Optimizer<'_> { // We can't ignore shorthand properties // // https://github.com/swc-project/swc/issues/6914 - let mut new_b = Box::new(Expr::Ident(shorthand.clone())); + let mut new_b = shorthand.clone().into(); if self.merge_sequential_expr(a, &mut new_b)? { *prop = Box::new(Prop::KeyValue(KeyValueProp { key: Ident::new_no_ctxt( @@ -1996,7 +2000,7 @@ impl Optimizer<'_> { shorthand.span, ) .into(), - value: new_b.clone(), + value: new_b.clone().into(), })); } @@ -2123,12 +2127,13 @@ impl Optimizer<'_> { if let Expr::Ident(orig_expr) = &*e { if orig_expr.to_id() == a_id.to_id() { replaced = true; - *e = Expr::Update(UpdateExpr { + *e = UpdateExpr { span: DUMMY_SP, op: *op, prefix: true, - arg: Box::new(Expr::Ident(orig_expr.clone())), - }); + arg: orig_expr.clone().into(), + } + .into(); return; } } @@ -2197,12 +2202,13 @@ impl Optimizer<'_> { if let Expr::Ident(orig_expr) = &*e { if orig_expr.to_id() == a_id.to_id() { replaced = true; - *e = Expr::Update(UpdateExpr { + *e = UpdateExpr { span: DUMMY_SP, op: *op, prefix: true, - arg: Box::new(Expr::Ident(orig_expr.clone())), - }); + arg: orig_expr.clone().into(), + } + .into(); return; } } @@ -2421,10 +2427,11 @@ impl Optimizer<'_> { Mergable::FnDecl(a) => { // We can inline a function declaration as a function expression. - Box::new(Expr::Fn(FnExpr { + FnExpr { ident: Some(a.ident.take()), function: a.function.take(), - })) + } + .into() } Mergable::Drop => { @@ -2445,10 +2452,11 @@ impl Optimizer<'_> { let a_expr = self.ignore_return_value(&mut a_expr); if let Some(a) = a_expr { - b.right = Box::new(Expr::Seq(SeqExpr { + b.right = SeqExpr { span: DUMMY_SP, exprs: vec![Box::new(a), b.right.take()], - })); + } + .into(); } return Ok(true); } @@ -2476,12 +2484,13 @@ impl Optimizer<'_> { let to = take_a(a, true, true); - b.right = Box::new(Expr::Bin(BinExpr { + b.right = BinExpr { span: DUMMY_SP, op: bin_op, left: to, right: b.right.take(), - })); + } + .into(); return Ok(true); } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/strings.rs b/crates/swc_ecma_minifier/src/compress/optimize/strings.rs index 8ee35a50435..3143a3a9f7c 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/strings.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/strings.rs @@ -65,11 +65,12 @@ impl Optimizer<'_> { report_change!( "strings: Converted an expression into a string literal (in string context)" ); - *n = Expr::Lit(Lit::Str(Str { + *n = Lit::Str(Str { span, raw: None, value: value.into(), - })); + }) + .into(); return; } @@ -84,11 +85,12 @@ impl Optimizer<'_> { let value = format!("{:?}", v.value); - *n = Expr::Lit(Lit::Str(Str { + *n = Lit::Str(Str { span: v.span, raw: None, value: value.into(), - })); + }) + .into(); } Expr::Lit(Lit::Regex(v)) => { @@ -104,11 +106,12 @@ impl Optimizer<'_> { let value = format!("/{}/{}", v.exp, v.flags); - *n = Expr::Lit(Lit::Str(Str { + *n = Lit::Str(Str { span: v.span, raw: None, value: value.into(), - })); + }) + .into(); } Expr::Bin(BinExpr { @@ -119,11 +122,12 @@ impl Optimizer<'_> { }) => { if let (Expr::Lit(Lit::Num(l)), Expr::Lit(Lit::Num(r))) = (&**left, &**right) { if l.value == 0.0 && r.value == 0.0 { - *n = Expr::Ident(Ident::new( + *n = Ident::new( "NaN".into(), *span, SyntaxContext::empty().apply_mark(self.marks.unresolved_mark), - )); + ) + .into(); self.changed = true; report_change!("strings: Evaluated 0 / 0 => NaN in string context"); } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index 091b463316f..044f9a6e383 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -112,7 +112,7 @@ impl Optimizer<'_> { .into_iter() .map(|name| VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(name.into()), + name: name.into(), init: None, definite: Default::default(), }) @@ -369,12 +369,13 @@ impl Optimizer<'_> { let discriminant = sw.discriminant.take(); if let Some(test) = case.test { - let test = Box::new(Expr::Bin(BinExpr { + let test = BinExpr { left: discriminant, right: test, op: op!("==="), span: DUMMY_SP, - })); + } + .into(); *s = Stmt::If(IfStmt { span: sw.span, diff --git a/crates/swc_ecma_minifier/src/compress/optimize/unused.rs b/crates/swc_ecma_minifier/src/compress/optimize/unused.rs index 4d6d6f28a60..1e35e98399d 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/unused.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/unused.rs @@ -206,7 +206,7 @@ impl Optimizer<'_> { if let Some(VarDeclKind::Const | VarDeclKind::Let) = self.ctx.var_kind { *e = Null { span: DUMMY_SP }.into(); } else { - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); } } } @@ -677,10 +677,11 @@ impl Optimizer<'_> { ); self.changed = true; if self.ctx.is_this_aware_callee { - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: DUMMY_SP, exprs: vec![0.into(), assign.right.take()], - }) + } + .into() } else { *e = *assign.right.take(); } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/util.rs b/crates/swc_ecma_minifier/src/compress/optimize/util.rs index b3df1e6f908..63af8a3ef74 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/util.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/util.rs @@ -276,12 +276,13 @@ impl<'a> Finalizer<'a> { e.visit_mut_children_with(self); match &*e { - Expr::Ident(Ident { sym, .. }) if &**sym == "eval" => { - Some(Box::new(Expr::Seq(SeqExpr { + Expr::Ident(Ident { sym, .. }) if &**sym == "eval" => Some( + SeqExpr { span: DUMMY_SP, exprs: vec![0.into(), e], - }))) - } + } + .into(), + ), _ => Some(e), } } @@ -469,12 +470,13 @@ impl<'a> NormalMultiReplacer<'a> { e.visit_mut_children_with(self); match &*e { - Expr::Ident(Ident { sym, .. }) if &**sym == "eval" => { - Some(Box::new(Expr::Seq(SeqExpr { + Expr::Ident(Ident { sym, .. }) if &**sym == "eval" => Some( + SeqExpr { span: DUMMY_SP, exprs: vec![0.into(), e], - }))) - } + } + .into(), + ), _ => Some(e), } } @@ -553,12 +555,13 @@ impl ExprReplacer { let e = self.to.take()?; match &*e { - Expr::Ident(Ident { sym, .. }) if &**sym == "eval" => { - Some(Box::new(Expr::Seq(SeqExpr { + Expr::Ident(Ident { sym, .. }) if &**sym == "eval" => Some( + SeqExpr { span: DUMMY_SP, exprs: vec![0.into(), e], - }))) - } + } + .into(), + ), _ => Some(e), } } diff --git a/crates/swc_ecma_minifier/src/compress/pure/arrows.rs b/crates/swc_ecma_minifier/src/compress/pure/arrows.rs index 9c1797219ad..b1e1b9a7fd7 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/arrows.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/arrows.rs @@ -28,14 +28,15 @@ impl Pure<'_> { self.changed = true; report_change!("unsafe_arrows: Fn expr => arrow"); - *e = Expr::Arrow(ArrowExpr { + *e = ArrowExpr { span: function.span, params: function.params.take().into_iter().map(|p| p.pat).collect(), body: Box::new(BlockStmtOrExpr::BlockStmt(function.body.take().unwrap())), is_async: function.is_async, is_generator: function.is_generator, ..Default::default() - }); + } + .into(); } } @@ -94,7 +95,7 @@ impl Pure<'_> { *p = Prop::KeyValue(KeyValueProp { key: m.key.take(), - value: Box::new(Expr::Arrow(ArrowExpr { + value: ArrowExpr { span: m_span, params: m .function @@ -107,7 +108,8 @@ impl Pure<'_> { is_async: m.function.is_async, is_generator: m.function.is_generator, ..Default::default() - })), + } + .into(), }); return; } diff --git a/crates/swc_ecma_minifier/src/compress/pure/bools.rs b/crates/swc_ecma_minifier/src/compress/pure/bools.rs index a55d0583d99..964e1de68ca 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/bools.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/bools.rs @@ -233,10 +233,11 @@ impl Pure<'_> { self.changed = true; let span = delete.arg.span(); report_change!("booleans: Compressing `delete` as sequence expression"); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span, exprs: vec![delete.arg.take(), Box::new(make_bool(span, true))], - }); + } + .into(); return; } } @@ -321,11 +322,12 @@ impl Pure<'_> { report_change!("Optimizing: number => number (in bool context)"); self.changed = true; - *n = Expr::Lit(Lit::Num(Number { + *n = Lit::Num(Number { span: *span, value: if *value == 0.0 { 1.0 } else { 0.0 }, raw: None, - })) + }) + .into() } Expr::Unary(UnaryExpr { @@ -348,23 +350,26 @@ impl Pure<'_> { match &**arg { Expr::Ident(..) => { - *n = Expr::Lit(Lit::Num(Number { + *n = Lit::Num(Number { span: *span, value: 1.0, raw: None, - })) + }) + .into() } _ => { // Return value of typeof is always truthy - let true_expr = Box::new(Expr::Lit(Lit::Num(Number { + let true_expr = Lit::Num(Number { span: *span, value: 1.0, raw: None, - }))); - *n = Expr::Seq(SeqExpr { + }) + .into(); + *n = SeqExpr { span: *span, exprs: vec![arg.take(), true_expr], - }) + } + .into() } } } @@ -373,11 +378,12 @@ impl Pure<'_> { if !is_ignore { report_change!("Converting string as boolean expressions"); self.changed = true; - *n = Expr::Lit(Lit::Num(Number { + *n = Lit::Num(Number { span: s.span, value: if s.value.is_empty() { 0.0 } else { 1.0 }, raw: None, - })); + }) + .into(); } } @@ -388,11 +394,12 @@ impl Pure<'_> { if self.options.bools { report_change!("booleans: Converting number as boolean expressions"); self.changed = true; - *n = Expr::Lit(Lit::Num(Number { + *n = Lit::Num(Number { span: num.span, value: if num.value == 0.0 { 0.0 } else { 1.0 }, raw: None, - })); + }) + .into(); } } diff --git a/crates/swc_ecma_minifier/src/compress/pure/conds.rs b/crates/swc_ecma_minifier/src/compress/pure/conds.rs index 92a91d14731..4fed4ee81b0 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/conds.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/conds.rs @@ -30,12 +30,13 @@ impl Pure<'_> { self.negate_twice(&mut cond.test, false); self.changed = true; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("||"), left: cond.test.take(), right: cond.alt.take(), - }); + } + .into(); return; } @@ -46,12 +47,13 @@ impl Pure<'_> { self.changed = true; self.negate(&mut cond.test, false, false); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("&&"), left: cond.test.take(), right: cond.alt.take(), - }); + } + .into(); return; } } @@ -66,12 +68,13 @@ impl Pure<'_> { // Negate twice to convert `test` to boolean. self.negate_twice(&mut cond.test, false); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("&&"), left: cond.test.take(), right: cond.cons.take(), - }); + } + .into(); return; } @@ -81,12 +84,13 @@ impl Pure<'_> { self.negate(&mut cond.test, false, false); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("||"), left: cond.test.take(), right: cond.cons.take(), - }); + } + .into(); } } } @@ -110,17 +114,19 @@ impl Pure<'_> { report_change!("conditionals: `x ? y || z : z` => `x || y && z`"); self.changed = true; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: cond.span, op: op!("||"), - left: Box::new(Expr::Bin(BinExpr { + left: BinExpr { span: cons_span, op: op!("&&"), left: cond.test.take(), right: cons.left.take(), - })), + } + .into(), right: cons.right.take(), - }); + } + .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 a87e972101b..4ede534f8ab 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs @@ -525,7 +525,7 @@ impl Pure<'_> { .into_iter() .map(|name| VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(name.into()), + name: name.into(), init: None, definite: Default::default(), }) @@ -551,7 +551,7 @@ impl Pure<'_> { .into_iter() .map(|name| VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(name.into()), + name: name.into(), init: None, definite: Default::default(), }) diff --git a/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs b/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs index dfd783f0ee4..856c68a66c2 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/evaluate.rs @@ -88,16 +88,17 @@ impl Pure<'_> { report_change!("evaluate: Reducing array.slice({}) call", start); if start >= arr.elems.len() { - *e = Expr::Array(ArrayLit { + *e = ArrayLit { span: *span, elems: Default::default(), - }); + } + .into(); return; } let elems = arr.elems.drain(start..).collect(); - *e = Expr::Array(ArrayLit { span: *span, elems }); + *e = ArrayLit { span: *span, elems }.into(); } } _ => { @@ -129,16 +130,17 @@ impl Pure<'_> { end ); if start >= arr.elems.len() { - *e = Expr::Array(ArrayLit { + *e = ArrayLit { span: *span, elems: Default::default(), - }); + } + .into(); return; } let elems = arr.elems.drain(start..end).collect(); - *e = Expr::Array(ArrayLit { span: *span, elems }); + *e = ArrayLit { span: *span, elems }.into(); } } } @@ -282,11 +284,12 @@ impl Pure<'_> { "evaluate: Reducing a call to `Number` into an unary operation" ); - *e = Expr::Unary(UnaryExpr { + *e = UnaryExpr { span: *span, op: op!(unary, "+"), arg: args.take().into_iter().next().unwrap().expr, - }); + } + .into(); } } } @@ -369,11 +372,12 @@ impl Pure<'_> { value ); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value: value.into(), - })); + }) + .into(); } return; @@ -393,11 +397,12 @@ impl Pure<'_> { value ); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value, - })); + }) + .into(); return; } @@ -418,11 +423,12 @@ impl Pure<'_> { num, value ); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value: value.into(), - })); + }) + .into(); return; } } @@ -439,11 +445,12 @@ impl Pure<'_> { value ); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value, - })); + }) + .into(); return; } else if let Some(precision) = args .first() @@ -465,11 +472,12 @@ impl Pure<'_> { value ); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value, - })); + }) + .into(); return; } } @@ -481,11 +489,12 @@ impl Pure<'_> { { if base.trunc() == 10. { let value = num.value.to_js_string().into(); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value, - })); + }) + .into(); return; } @@ -505,11 +514,12 @@ impl Pure<'_> { } .into(); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: e.span(), raw: None, value, - })) + }) + .into() } } } @@ -570,10 +580,11 @@ impl Pure<'_> { self.changed = true; report_change!("evaluate: `foo || true` => `foo, 1`"); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: bin_expr.span, exprs: vec![bin_expr.left.clone(), bin_expr.right.clone()], - }); + } + .into(); } else { self.changed = true; report_change!("evaluate: `foo || false` => `foo` (bool ctx)"); @@ -603,10 +614,11 @@ impl Pure<'_> { self.changed = true; report_change!("evaluate: `foo && false` => `foo, false`"); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: bin_expr.span, exprs: vec![bin_expr.left.clone(), bin_expr.right.clone()], - }); + } + .into(); } return; } @@ -749,22 +761,19 @@ impl Pure<'_> { "evaluate: Evaluated `charCodeAt` of a string literal as `{}`", v ); - *e = Expr::Lit(Lit::Num(Number { + *e = Lit::Num(Number { span: call.span, value: v as usize as f64, raw: None, - })) + }) + .into() } None => { self.changed = true; report_change!( "evaluate: Evaluated `charCodeAt` of a string literal as `NaN`", ); - *e = Expr::Ident(Ident::new( - "NaN".into(), - e.span(), - SyntaxContext::empty(), - )) + *e = Ident::new("NaN".into(), e.span(), SyntaxContext::empty()).into() } } } @@ -788,22 +797,24 @@ impl Pure<'_> { "evaluate: Evaluated `codePointAt` of a string literal as `{}`", v ); - *e = Expr::Lit(Lit::Num(Number { + *e = Lit::Num(Number { span: call.span, value: v as usize as f64, raw: None, - })) + }) + .into() } None => { self.changed = true; report_change!( "evaluate: Evaluated `codePointAt` of a string literal as `NaN`", ); - *e = Expr::Ident(Ident::new( + *e = Ident::new( "NaN".into(), e.span(), SyntaxContext::empty().apply_mark(self.marks.unresolved_mark), - )) + ) + .into() } } } @@ -814,11 +825,12 @@ impl Pure<'_> { self.changed = true; report_change!("evaluate: Evaluated `{method}` of a string literal"); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { value: new_val.into(), raw: None, ..s - })); + }) + .into(); } } diff --git a/crates/swc_ecma_minifier/src/compress/pure/loops.rs b/crates/swc_ecma_minifier/src/compress/pure/loops.rs index bc24fc855b2..11e4924e049 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/loops.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/loops.rs @@ -79,12 +79,13 @@ impl Pure<'_> { match s.test.as_deref_mut() { Some(e) => { let orig_test = e.take(); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op: op!("&&"), left: Box::new(orig_test), right: test.take(), - }); + } + .into(); } None => { s.test = Some(test.take()); @@ -110,12 +111,13 @@ impl Pure<'_> { match s.test.as_deref_mut() { Some(e) => { let orig_test = e.take(); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: *span, op: op!("&&"), left: Box::new(orig_test), right: test.take(), - }); + } + .into(); } None => { s.test = Some(test.take()); @@ -173,12 +175,15 @@ impl Pure<'_> { match s.test.take() { Some(left) => { - s.test = Some(Box::new(Expr::Bin(BinExpr { - span: s.test.span(), - op: op!("&&"), - left, - right: test.take(), - }))); + s.test = Some( + BinExpr { + span: s.test.span(), + op: op!("&&"), + left, + right: test.take(), + } + .into(), + ); } None => { s.test = Some(test.take()); diff --git a/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs b/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs index 4a136ba541e..200c3ffb0a1 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs @@ -322,7 +322,7 @@ impl Pure<'_> { let mut exprs: Vec> = exprs.drain(..(exprs.len() - 1)).collect(); exprs.push(Box::new(replacement)); - Some(Expr::Seq(SeqExpr { span: *span, exprs })) + Some(SeqExpr { span: *span, exprs }.into()) } Expr::Lit(Lit::Str(Str { value, span, .. })) => { @@ -381,20 +381,20 @@ impl Pure<'_> { Some(if exprs.is_empty() { // No side effects, replacement is: // (0, void 0) - Expr::Seq(SeqExpr { + SeqExpr { span: *span, exprs: vec![0.into(), Expr::undefined(*span)] - }) + }.into() } else { // Side effects exist, replacement is: // (x(), y(), void 0) // Where `x()` and `y()` are side effects. exprs.push(Expr::undefined(*span)); - Expr::Seq(SeqExpr { + SeqExpr { span: *span, exprs - }) + }.into() }) } @@ -429,9 +429,9 @@ impl Pure<'_> { Some(if is_known_symbol { // [x(), y()].push - Expr::Member(MemberExpr { + MemberExpr { span: *span, - obj: Box::new(Expr::Array(ArrayLit { + obj: ArrayLit { span: *span, elems: exprs .into_iter() @@ -440,29 +440,30 @@ impl Pure<'_> { expr: elem, })) .collect() - })), + }.into(), prop: prop.clone(), - }) + }.into() } else { - let val = Expr::undefined(*span); + let val = Expr::undefined( + *span); if exprs.is_empty() { // No side effects, replacement is: // (0, void 0) - Expr::Seq(SeqExpr { + SeqExpr { span: val.span(), exprs: vec![0.into(), val] - }) + }.into() } else { // Side effects exist, replacement is: // (x(), y(), void 0) // Where `x()` and `y()` are side effects. exprs.push(val); - Expr::Seq(SeqExpr { + SeqExpr { span: *span, exprs - }) + }.into() } }) } @@ -522,22 +523,24 @@ impl Pure<'_> { } // Can be optimized fully or partially - Some(self.expr_ctx.preserve_effects( + Some(*self.expr_ctx.preserve_effects( *span, if is_known_symbol { // Valid key, e.g. "hasOwnProperty". Replacement: // (foo(), bar(), {}.hasOwnProperty) - Expr::Member(MemberExpr { + MemberExpr { span: *span, - obj: Box::new(Expr::Object(ObjectLit { + obj: ObjectLit { span: *span, props: vec![], - })), + } + .into(), prop: MemberProp::Ident(IdentName::new(key, *span)), - }) + } + .into() } else { // Invalid key. Replace with side effects plus `undefined`. - *Expr::undefined(*span) + Expr::undefined(*span) }, props.drain(..).map(|x| match x { PropOrSpread::Prop(prop) => match *prop { diff --git a/crates/swc_ecma_minifier/src/compress/pure/misc.rs b/crates/swc_ecma_minifier/src/compress/pure/misc.rs index ec2322d3b88..958589a00de 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/misc.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/misc.rs @@ -232,25 +232,28 @@ impl Pure<'_> { return; } - let sep = Box::new(Expr::Lit(Lit::Str(Str { + let sep: Box = Lit::Str(Str { span: DUMMY_SP, raw: None, value: separator, - }))); - let mut res = Expr::Lit(Lit::Str(Str { + }) + .into(); + let mut res = Lit::Str(Str { span: DUMMY_SP, raw: None, value: js_word!(""), - })); + }) + .into(); fn add(to: &mut Expr, right: Box) { let lhs = to.take(); - *to = Expr::Bin(BinExpr { + *to = BinExpr { span: DUMMY_SP, left: Box::new(lhs), op: op!(bin, "+"), right, - }); + } + .into(); } for (last, elem) in arr.elems.take().into_iter().identify_last() { @@ -305,11 +308,12 @@ impl Pure<'_> { report_change!("Compressing array.join()"); self.changed = true; - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: call.span, raw: None, value: res.into(), - })) + }) + .into() } pub(super) fn drop_undefined_from_return_arg(&mut self, s: &mut ReturnStmt) { @@ -398,17 +402,20 @@ impl Pure<'_> { report_change!("Optimized regex"); - Some(Expr::Lit(Lit::Regex(Regex { - span: *span, - exp: pattern, - flags: { - let flag = flag.to_string(); - let mut bytes = flag.into_bytes(); - bytes.sort_unstable(); + Some( + Lit::Regex(Regex { + span: *span, + exp: pattern, + flags: { + let flag = flag.to_string(); + let mut bytes = flag.into_bytes(); + bytes.sort_unstable(); - String::from_utf8(bytes).unwrap().into() - }, - }))) + String::from_utf8(bytes).unwrap().into() + }, + }) + .into(), + ) } /// Array() -> [] @@ -418,38 +425,50 @@ impl Pure<'_> { match &**expr { Expr::Lit(Lit::Num(num)) => { if num.value <= 5_f64 && num.value >= 0_f64 { - Some(Expr::Array(ArrayLit { - span: *span, - elems: vec![None; num.value as usize], - })) + Some( + ArrayLit { + span: *span, + elems: vec![None; num.value as usize], + } + .into(), + ) } else { None } } - Expr::Lit(_) => Some(Expr::Array(ArrayLit { - span: *span, - elems: vec![args.take().into_iter().next()], - })), + Expr::Lit(_) => Some( + ArrayLit { + span: *span, + elems: vec![args.take().into_iter().next()], + } + .into(), + ), _ => None, } } else { None } } else { - Some(Expr::Array(ArrayLit { - span: *span, - elems: args.take().into_iter().map(Some).collect(), - })) + Some( + ArrayLit { + span: *span, + elems: args.take().into_iter().map(Some).collect(), + } + .into(), + ) } } /// Object -> {} fn optimize_object(&mut self, args: &mut Vec, span: &mut Span) -> Option { if args.is_empty() { - Some(Expr::Object(ObjectLit { - span: *span, - props: Vec::new(), - })) + Some( + ObjectLit { + span: *span, + props: Vec::new(), + } + .into(), + ) } else { None } @@ -470,11 +489,12 @@ impl Pure<'_> { self.changed = true; report_change!("Optimized optional chaining expression where object is not null"); - *e = Expr::Member(MemberExpr { + *e = MemberExpr { span: opt.span, obj: base.obj.take(), prop: base.prop.take(), - }); + } + .into(); } } } @@ -534,57 +554,73 @@ impl Pure<'_> { { let new_expr = match &**callee { Expr::Ident(Ident { sym, .. }) if &**sym == "Boolean" => match &mut args[..] { - [] => Some(Expr::Lit(Lit::Bool(Bool { - span: *span, - value: false, - }))), - [ExprOrSpread { spread: None, expr }] => Some(Expr::Unary(UnaryExpr { - span: *span, - op: op!("!"), - arg: UnaryExpr { + [] => Some( + Lit::Bool(Bool { + span: *span, + value: false, + }) + .into(), + ), + [ExprOrSpread { spread: None, expr }] => Some( + UnaryExpr { span: *span, op: op!("!"), - arg: expr.take(), + arg: UnaryExpr { + span: *span, + op: op!("!"), + arg: expr.take(), + } + .into(), } .into(), - })), + ), _ => None, }, Expr::Ident(Ident { sym, .. }) if &**sym == "Number" => match &mut args[..] { - [] => Some(Expr::Lit(Lit::Num(Number { - span: *span, - value: 0.0, - raw: None, - }))), + [] => Some( + Lit::Num(Number { + span: *span, + value: 0.0, + raw: None, + }) + .into(), + ), // this is indeed very unsafe in case of BigInt - [ExprOrSpread { spread: None, expr }] if self.options.unsafe_math => { - Some(Expr::Unary(UnaryExpr { + [ExprOrSpread { spread: None, expr }] if self.options.unsafe_math => Some( + UnaryExpr { span: *span, op: op!(unary, "+"), arg: expr.take(), - })) - } + } + .into(), + ), _ => None, }, Expr::Ident(Ident { sym, .. }) if &**sym == "String" => match &mut args[..] { - [] => Some(Expr::Lit(Lit::Str(Str { - span: *span, - value: "".into(), - raw: None, - }))), + [] => Some( + Lit::Str(Str { + span: *span, + value: "".into(), + raw: None, + }) + .into(), + ), // this is also very unsafe in case of Symbol [ExprOrSpread { spread: None, expr }] if self.options.unsafe_passes => { - Some(Expr::Bin(BinExpr { - span: *span, - left: expr.take(), - op: op!(bin, "+"), - right: Lit::Str(Str { + Some( + BinExpr { span: *span, - value: "".into(), - raw: None, - }) + left: expr.take(), + op: op!(bin, "+"), + right: Lit::Str(Str { + span: *span, + value: "".into(), + raw: None, + }) + .into(), + } .into(), - })) + ) } _ => None, }, @@ -648,13 +684,14 @@ impl Pure<'_> { report_change!( "new operator: Compressing `new Array/RegExp/..` => `Array()/RegExp()/..`" ); - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, ctxt: *ctxt, callee: callee.take().as_callee(), args: args.take().unwrap_or_default(), ..Default::default() - }) + } + .into() } _ => {} } @@ -777,7 +814,7 @@ impl Pure<'_> { raw: cur_raw.into(), }); - Some(Expr::Tpl(new_tpl)) + Some(new_tpl.into()) } /// Returns true if something is modified. @@ -860,10 +897,13 @@ impl Pure<'_> { return Some(*exprs.remove(0)); } - Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs, - })) + Some( + SeqExpr { + span: DUMMY_SP, + exprs, + } + .into(), + ) } /// Calls [`Self::ignore_return_value`] on the arguments of return @@ -936,7 +976,7 @@ impl Pure<'_> { let new = self.make_ignored_expr(args.take().into_iter().map(|arg| arg.expr)); - *e = new.unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + *e = new.unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } @@ -946,7 +986,7 @@ impl Pure<'_> { let new = self.make_ignored_expr(tpl.exprs.take().into_iter()); - *e = new.unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + *e = new.unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } @@ -957,7 +997,7 @@ impl Pure<'_> { let new = self.make_ignored_expr(args.take().into_iter().flatten().map(|arg| arg.expr)); - *e = new.unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + *e = new.unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } @@ -975,7 +1015,7 @@ impl Pure<'_> { report_change!("Dropping pure call as callee is pure"); *e = self .make_ignored_expr(args.take().into_iter().map(|arg| arg.expr)) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } } @@ -988,7 +1028,7 @@ impl Pure<'_> { report_change!("Dropping pure tag tpl as callee is pure"); *e = self .make_ignored_expr(tpl.exprs.take().into_iter()) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } } @@ -1000,7 +1040,7 @@ impl Pure<'_> { // Skip 0 if n.value != 0.0 && n.value.classify() == FpCategory::Normal { self.changed = true; - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } } @@ -1014,13 +1054,13 @@ impl Pure<'_> { { if is_global_var_with_pure_property_access(&i.sym) { report_change!("Dropping a reference to a global variable"); - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } } } else { report_change!("Dropping an identifier as it's declared"); - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } } @@ -1044,7 +1084,7 @@ impl Pure<'_> { if arg.is_invalid() { report_change!("Dropping an unary expression"); - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } } @@ -1078,10 +1118,11 @@ impl Pure<'_> { if tpl.exprs.len() == 1 { *e = *tpl.exprs.remove(0); } else { - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: tpl.span, exprs: tpl.exprs.take(), - }); + } + .into(); } } @@ -1111,7 +1152,7 @@ impl Pure<'_> { Expr::Lit(Lit::Num(n)) => { if n.value == 0.0 && opts.drop_zero { self.changed = true; - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } } @@ -1121,7 +1162,7 @@ impl Pure<'_> { report_change!("Dropping an identifier as it's declared"); self.changed = true; - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } } @@ -1130,7 +1171,7 @@ impl Pure<'_> { report_change!("Dropping literals"); self.changed = true; - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } @@ -1180,7 +1221,7 @@ impl Pure<'_> { let span = bin.span; if bin.left.is_invalid() && bin.right.is_invalid() { - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } else if bin.right.is_invalid() { *e = *bin.left.take(); @@ -1193,10 +1234,11 @@ impl Pure<'_> { if matches!(*bin.left, Expr::Await(..) | Expr::Update(..)) { self.changed = true; report_change!("ignore_return_value: Compressing binary as seq"); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span, exprs: vec![bin.left.take(), bin.right.take()], - }); + } + .into(); return; } } @@ -1225,7 +1267,7 @@ impl Pure<'_> { || s.value.starts_with("@babel/helpers")) { self.changed = true; - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } @@ -1328,7 +1370,7 @@ impl Pure<'_> { self.changed = true; *e = self .make_ignored_expr(args.iter_mut().flatten().map(|arg| arg.expr.take())) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } @@ -1346,7 +1388,7 @@ impl Pure<'_> { self.changed = true; *e = self .make_ignored_expr(args.iter_mut().map(|arg| arg.expr.take())) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } @@ -1364,7 +1406,7 @@ impl Pure<'_> { if let PropOrSpread::Prop(p) = prop { match *p { Prop::Shorthand(p) => { - exprs.push(Box::new(Expr::Ident(p))); + exprs.push(p.into()); } Prop::KeyValue(p) => { if let PropName::Computed(e) = p.key { @@ -1386,7 +1428,7 @@ impl Pure<'_> { *e = self .make_ignored_expr(exprs.into_iter()) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); report_change!("Ignored an object literal"); self.changed = true; return; @@ -1400,7 +1442,7 @@ impl Pure<'_> { }) => true, _ => false, }) { - *e = Expr::Array(ArrayLit { + *e = ArrayLit { elems: arr .elems .take() @@ -1432,7 +1474,8 @@ impl Pure<'_> { .map(Some) .collect(), ..*arr - }); + } + .into(); return; } @@ -1457,7 +1500,7 @@ impl Pure<'_> { *e = self .make_ignored_expr(exprs.into_iter()) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); report_change!("Ignored an array literal"); self.changed = true; return; @@ -1485,7 +1528,7 @@ impl Pure<'_> { .make_ignored_expr( vec![obj.take(), prop.expr.take()].into_iter(), ) - .unwrap_or(Expr::Invalid(Invalid { span: DUMMY_SP })); + .unwrap_or(Invalid { span: DUMMY_SP }.into()); return; } }; @@ -1504,7 +1547,7 @@ impl Pure<'_> { if is_pure_member_access(obj, prop) { self.changed = true; report_change!("Remving pure member access to global var"); - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); } } } @@ -1534,7 +1577,7 @@ impl Pure<'_> { right, .. }) => { - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: unary.span, op: if *op == op!("==") { op!("!=") @@ -1543,7 +1586,8 @@ impl Pure<'_> { }, left: left.take(), right: right.take(), - }) + } + .into() } _ => {} } diff --git a/crates/swc_ecma_minifier/src/compress/pure/mod.rs b/crates/swc_ecma_minifier/src/compress/pure/mod.rs index b5a80efef73..a0179a24fab 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/mod.rs @@ -419,7 +419,7 @@ impl VisitMut for Pure<'_> { if let Expr::Seq(seq) = e { if seq.exprs.is_empty() { - *e = Expr::Invalid(Invalid { span: DUMMY_SP }); + *e = Invalid { span: DUMMY_SP }.into(); return; } if seq.exprs.len() == 1 { diff --git a/crates/swc_ecma_minifier/src/compress/pure/numbers.rs b/crates/swc_ecma_minifier/src/compress/pure/numbers.rs index 25440a3f6d6..fbed3349c14 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/numbers.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/numbers.rs @@ -18,11 +18,12 @@ impl Pure<'_> { self.changed = true; report_change!("numbers: Converting a string literal to {:?}", value); - *e = Expr::Lit(Lit::Num(Number { + *e = Lit::Num(Number { span: *span, value, raw: None, - })); + }) + .into(); } } @@ -47,16 +48,18 @@ impl Pure<'_> { self.changed = true; report_change!("numbers: Lifting `-`"); - *e = Expr::Unary(UnaryExpr { + *e = UnaryExpr { span: arg.span, op: op!(unary, "-"), - arg: Box::new(Expr::Bin(BinExpr { + arg: BinExpr { span: arg.span, op: arg.op, left: arg.left.take(), right: right_arg.take(), - })), - }); + } + .into(), + } + .into(); } Expr::Lit(Lit::Num(Number { span, value, .. })) => { @@ -64,10 +67,10 @@ impl Pure<'_> { self.changed = true; report_change!("numbers: Lifting `-` in a literal"); - *e = Expr::Unary(UnaryExpr { + *e = UnaryExpr { span: arg.span, op: op!(unary, "-"), - arg: Box::new(Expr::Bin(BinExpr { + arg: BinExpr { span: arg.span, op: arg.op, left: arg.left.take(), @@ -76,8 +79,10 @@ impl Pure<'_> { value: -*value, raw: None, }))), - })), - }); + } + .into(), + } + .into(); } } diff --git a/crates/swc_ecma_minifier/src/compress/pure/sequences.rs b/crates/swc_ecma_minifier/src/compress/pure/sequences.rs index ca2cce66e68..cf80181716c 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/sequences.rs @@ -52,17 +52,21 @@ impl Pure<'_> { let mut exprs = left.exprs.take(); - exprs.push(Box::new(Expr::Bin(BinExpr { - span: left.span, - op: bin.op, - left: left_last, - right: bin.right.take(), - }))); + exprs.push( + BinExpr { + span: left.span, + op: bin.op, + left: left_last, + right: bin.right.take(), + } + .into(), + ); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: bin.span, exprs, - }) + } + .into() } } @@ -99,17 +103,21 @@ impl Pure<'_> { alt: cond.alt.take(), }; - new_seq.push(Box::new(Expr::Assign(AssignExpr { - span: assign.span, - op: assign.op, - left: assign.left.take(), - right: Box::new(Expr::Cond(new_cond)), - }))); + new_seq.push( + AssignExpr { + span: assign.span, + op: assign.op, + left: assign.left.take(), + right: Box::new(new_cond.into()), + } + .into(), + ); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: assign.span, exprs: new_seq, - }); + } + .into(); } } } @@ -169,7 +177,7 @@ impl Pure<'_> { let obj = Box::new(a.take()); - let new = Expr::Call(CallExpr { + let new = CallExpr { span, callee: MemberExpr { span: DUMMY_SP, @@ -179,7 +187,8 @@ impl Pure<'_> { .as_callee(), args: args.take(), ..Default::default() - }); + } + .into(); b.take(); self.changed = true; report_change!( diff --git a/crates/swc_ecma_minifier/src/compress/pure/strings.rs b/crates/swc_ecma_minifier/src/compress/pure/strings.rs index 607de8011d0..a3273251ee8 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/strings.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/strings.rs @@ -45,12 +45,13 @@ impl Pure<'_> { report_change!("evaluate: 'foo' + ('bar' + baz) => 'foobar' + baz"); let s = lls.into_owned() + &*rls; - *e = Expr::Bin(BinExpr { + *e = BinExpr { span, op: op!(bin, "+"), left: s.into(), right: r_r.take(), - }); + } + .into(); } } @@ -82,7 +83,7 @@ impl Pure<'_> { self.changed = true; report_change!("evaluating a template to a string"); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: tpl.span, op: op!(bin, "+"), left: tpl.quasis[0] @@ -91,7 +92,8 @@ impl Pure<'_> { .unwrap_or_else(|| tpl.quasis[0].raw.clone()) .into(), right: tpl.exprs[0].take(), - }); + } + .into(); } } @@ -182,7 +184,7 @@ impl Pure<'_> { raw: s, }); - *e = Expr::Tpl(new_tpl); + *e = new_tpl.into(); } /// Converts template literals to string if `exprs` of [Tpl] is empty. @@ -198,11 +200,12 @@ impl Pure<'_> { }) { report_change!("converting a template literal to a string literal"); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: t.span, raw: None, value: value.clone(), - })); + }) + .into(); return; } } @@ -224,11 +227,12 @@ impl Pure<'_> { report_change!("converting a template literal to a string literal"); - *e = Expr::Lit(Lit::Str(Str { + *e = Lit::Str(Str { span: t.span, raw: None, value, - })); + }) + .into(); } } _ => {} @@ -496,16 +500,18 @@ impl Pure<'_> { new_str ); - *e = Expr::Bin(BinExpr { + *e = BinExpr { span: bin.span, op: op!(bin, "+"), left: left.left.take(), - right: Box::new(Expr::Lit(Lit::Str(Str { + right: Lit::Str(Str { span: left_span, raw: None, value: new_str.into(), - }))), - }); + }) + .into(), + } + .into(); } } } diff --git a/crates/swc_ecma_minifier/src/compress/util/mod.rs b/crates/swc_ecma_minifier/src/compress/util/mod.rs index b1b620f4a76..9f44110f9ba 100644 --- a/crates/swc_ecma_minifier/src/compress/util/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/util/mod.rs @@ -165,11 +165,12 @@ fn negate_inner( } else { report_change!("negate: e => !e"); - *e = Expr::Unary(UnaryExpr { + *e = UnaryExpr { span: DUMMY_SP, op: op!("!"), arg, - }); + } + .into(); dump_change_detail!("Negated `{}` as `{}`", start_str, dump(&*e, false)); diff --git a/crates/swc_ecma_minifier/src/eval.rs b/crates/swc_ecma_minifier/src/eval.rs index aa846e6b8d3..688699e2d4d 100644 --- a/crates/swc_ecma_minifier/src/eval.rs +++ b/crates/swc_ecma_minifier/src/eval.rs @@ -200,11 +200,12 @@ impl Evaluator { }) if !prop.is_computed() => { let obj = self.eval_as_expr(obj)?; - let mut e = Expr::Member(MemberExpr { + let mut e: Expr = MemberExpr { span: *span, obj, prop: prop.clone(), - }); + } + .into(); e.visit_mut_with(&mut expr_simplifier( self.marks.unresolved_mark, @@ -226,16 +227,17 @@ impl Evaluator { for expr in &q.exprs { let res = self.eval(expr)?; exprs.push(match res { - EvalResult::Lit(v) => Box::new(Expr::Lit(v)), + EvalResult::Lit(v) => v.into(), EvalResult::Undefined => Expr::undefined(DUMMY_SP), }); } - let mut e = Expr::Tpl(Tpl { + let mut e: Box = Tpl { span: q.span, exprs, quasis: q.quasis.clone(), - }); + } + .into(); { e.visit_mut_with(&mut pure_optimizer( diff --git a/crates/swc_ecma_minifier/src/option/terser.rs b/crates/swc_ecma_minifier/src/option/terser.rs index d4d5aed203b..5c8708df09f 100644 --- a/crates/swc_ecma_minifier/src/option/terser.rs +++ b/crates/swc_ecma_minifier/src/option/terser.rs @@ -456,28 +456,31 @@ impl From for Vec { fn value_to_expr(v: Value) -> Box { match v { - Value::Null => Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), - Value::Bool(value) => Box::new(Expr::Lit(Lit::Bool(Bool { + Value::Null => Lit::Null(Null { span: DUMMY_SP }).into(), + Value::Bool(value) => Lit::Bool(Bool { span: DUMMY_SP, value, - }))), + }) + .into(), Value::Number(v) => { trace_op!("Creating a numeric literal from value"); - Box::new(Expr::Lit(Lit::Num(Number { + Lit::Num(Number { span: DUMMY_SP, value: v.as_f64().unwrap(), raw: None, - }))) + }) + .into() } Value::String(v) => { let value: JsWord = v.into(); - Box::new(Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: DUMMY_SP, raw: None, value, - }))) + }) + .into() } Value::Array(arr) => { @@ -486,10 +489,11 @@ fn value_to_expr(v: Value) -> Box { .map(value_to_expr) .map(|expr| Some(ExprOrSpread { spread: None, expr })) .collect(); - Box::new(Expr::Array(ArrayLit { + ArrayLit { span: DUMMY_SP, elems, - })) + } + .into() } Value::Object(obj) => { @@ -509,10 +513,11 @@ fn value_to_expr(v: Value) -> Box { .map(PropOrSpread::Prop) .collect(); - Box::new(Expr::Object(ObjectLit { + ObjectLit { span: DUMMY_SP, props, - })) + } + .into() } } } diff --git a/crates/swc_ecma_minifier/src/pass/mangle_props.rs b/crates/swc_ecma_minifier/src/pass/mangle_props.rs index 058c88e8b3f..9e578d7625c 100644 --- a/crates/swc_ecma_minifier/src/pass/mangle_props.rs +++ b/crates/swc_ecma_minifier/src/pass/mangle_props.rs @@ -266,7 +266,7 @@ impl VisitMut for Mangler<'_> { *prop = Prop::KeyValue(KeyValueProp { key: PropName::Ident(new_ident), - value: Box::new(Expr::Ident(ident.clone())), + value: ident.clone().into(), }); } } diff --git a/crates/swc_ecma_minifier/src/util/mod.rs b/crates/swc_ecma_minifier/src/util/mod.rs index d3b141869bb..7246fc03b9a 100644 --- a/crates/swc_ecma_minifier/src/util/mod.rs +++ b/crates/swc_ecma_minifier/src/util/mod.rs @@ -16,11 +16,12 @@ pub(crate) mod unit; pub(crate) fn make_number(span: Span, value: f64) -> Expr { trace_op!("Creating a numeric literal"); - Expr::Lit(Lit::Num(Number { + Lit::Num(Number { span, value, raw: None, - })) + }) + .into() } pub trait ModuleItemExt: @@ -80,15 +81,17 @@ impl ModuleItemExt for ModuleItem { pub(crate) fn make_bool(span: Span, value: bool) -> Expr { trace_op!("Creating a boolean literal"); - Expr::Unary(UnaryExpr { + UnaryExpr { span, op: op!("!"), - arg: Box::new(Expr::Lit(Lit::Num(Number { + arg: Lit::Num(Number { span: DUMMY_SP, value: if value { 0.0 } else { 1.0 }, raw: None, - }))), - }) + }) + .into(), + } + .into() } /// Additional methods for optimizing expressions. @@ -128,10 +131,11 @@ pub(crate) trait ExprOptExt: Sized { Expr::Seq(seq) => seq, _ => { let inner = expr.take(); - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, exprs: vec![Box::new(inner)], - }); + } + .into(); expr.force_seq() } } @@ -151,10 +155,11 @@ pub(crate) trait ExprOptExt: Sized { _ => { let v = to.take(); exprs.push(Box::new(v)); - *to = Expr::Seq(SeqExpr { + *to = SeqExpr { span: DUMMY_SP, exprs, - }); + } + .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 005c02ffe73..e0db38b63f1 100644 --- a/crates/swc_ecma_parser/src/parser/class_and_fn.rs +++ b/crates/swc_ecma_parser/src/parser/class_and_fn.rs @@ -323,12 +323,13 @@ impl Parser { } let args = self.parse_args(false)?; - Ok(Box::new(Expr::Call(CallExpr { + Ok(CallExpr { span: span!(self, expr.span_lo()), callee: Callee::Expr(expr), args, ..Default::default() - }))) + } + .into()) } fn parse_class_body(&mut self) -> PResult> { @@ -1571,7 +1572,7 @@ impl OutputType for Box { ident: Option, function: Box, ) -> Result { - Ok(Box::new(Expr::Fn(FnExpr { ident, function }))) + Ok(FnExpr { ident, function }.into()) } fn finish_class( @@ -1579,7 +1580,7 @@ impl OutputType for Box { ident: Option, class: Box, ) -> Result { - Ok(Box::new(Expr::Class(ClassExpr { ident, class }))) + Ok(ClassExpr { ident, class }.into()) } } diff --git a/crates/swc_ecma_parser/src/parser/expr.rs b/crates/swc_ecma_parser/src/parser/expr.rs index 5edc405242a..918105619a6 100644 --- a/crates/swc_ecma_parser/src/parser/expr.rs +++ b/crates/swc_ecma_parser/src/parser/expr.rs @@ -24,10 +24,11 @@ impl Parser { exprs.push(self.parse_assignment_expr()?); } - return Ok(Box::new(Expr::Seq(SeqExpr { + return Ok(SeqExpr { span: span!(self, start), exprs, - }))); + } + .into()); } Ok(expr) @@ -195,13 +196,14 @@ impl Parser { bump!(self); let right = self.parse_assignment_expr()?; - Ok(Box::new(Expr::Assign(AssignExpr { + Ok(AssignExpr { span: span!(self, start), op, // TODO: left, right, - }))) + } + .into()) } _ => Ok(cond), } @@ -233,12 +235,13 @@ impl Parser { }; let alt = self.with_ctx(ctx).parse_assignment_expr()?; let span = Span::new(start, alt.span_hi()); - Ok(Box::new(Expr::Cond(CondExpr { + Ok(CondExpr { span, test, cons, alt, - }))) + } + .into()) } else { Ok(test) } @@ -262,9 +265,10 @@ impl Parser { match tok { tok!("this") => { self.input.bump(); - return Ok(Box::new(Expr::This(ThisExpr { + return Ok(ThisExpr { span: span!(self, start), - }))); + } + .into()); } tok!("async") => { @@ -282,7 +286,7 @@ impl Parser { assert_and_bump!(p, "async"); p.try_parse_ts_generic_async_arrow_fn(start) }) { - return Ok(Box::new(Expr::Arrow(res))); + return Ok(res.into()); } } @@ -320,7 +324,7 @@ impl Parser { | Token::Num { .. } | Token::BigInt { .. } | Token::Str { .. } => { - return Ok(Box::new(Expr::Lit(self.parse_lit()?))); + return Ok(self.parse_lit()?.into()); } // Regexp @@ -359,11 +363,7 @@ impl Parser { self.emit_err(span, SyntaxError::DuplicatedRegExpFlags(*flag)); } - return Ok(Box::new(Expr::Lit(Lit::Regex(Regex { - span, - exp, - flags, - })))); + return Ok(Lit::Regex(Regex { span, exp, flags }).into()); } _ => unreachable!(), } @@ -377,7 +377,7 @@ impl Parser { }; // parse template literal - return Ok(Box::new(Expr::Tpl(self.with_ctx(ctx).parse_tpl(false)?))); + return Ok(self.with_ctx(ctx).parse_tpl(false)?.into()); } tok!('(') => { @@ -428,35 +428,37 @@ impl Parser { self.emit_err(self.input.prev_span(), SyntaxError::TS1106); } - return Ok(Box::new(Expr::Ident(id))); + return Ok(id.into()); } let ident = self.parse_binding_ident()?; if self.input.syntax().typescript() && ident.sym == "as" && !is!(self, "=>") { // async as type let type_ann = self.in_type().parse_with(|p| p.parse_ts_type())?; - return Ok(Box::new(Expr::TsAs(TsAsExpr { + return Ok(TsAsExpr { span: span!(self, start), - expr: Box::new(Expr::Ident(id)), + expr: Box::new(id.into()), type_ann, - }))); + } + .into()); } // async a => body - let arg = Pat::from(ident); + let arg = ident.into(); let params = vec![arg]; expect!(self, "=>"); let body = self.parse_fn_body(true, false, true, params.is_simple_parameter_list())?; - return Ok(Box::new(Expr::Arrow(ArrowExpr { + return Ok(ArrowExpr { span: span!(self, start), body, params, is_async: true, is_generator: false, ..Default::default() - }))); + } + .into()); } else if can_be_arrow && !self.input.had_line_break_before_cur() && eat!(self, "=>") { if self.ctx().strict && id.is_reserved_in_strict_bind() { self.emit_strict_mode_err(id.span, SyntaxError::EvalAndArgumentsInStrict) @@ -465,25 +467,27 @@ impl Parser { let body = self.parse_fn_body(false, false, true, params.is_simple_parameter_list())?; - return Ok(Box::new(Expr::Arrow(ArrowExpr { + return Ok(ArrowExpr { span: span!(self, start), body, params, is_async: false, is_generator: false, ..Default::default() - }))); + } + .into()); } else { - return Ok(Box::new(Expr::Ident(id))); + return Ok(id.into()); } } if eat!(self, '#') { let id = self.parse_ident_name()?; - return Ok(Box::new(Expr::PrivateName(PrivateName { + return Ok(PrivateName { span: span!(self, start), name: id.sym, - }))); + } + .into()); } syntax_error!(self, self.input.cur_span(), SyntaxError::TS1109) @@ -522,7 +526,7 @@ impl Parser { expect!(self, ']'); let span = span!(self, start); - Ok(Box::new(Expr::Array(ArrayLit { span, elems }))) + Ok(ArrayLit { span, elems }.into()) } #[allow(dead_code)] @@ -549,10 +553,11 @@ impl Parser { if eat!(self, '.') { if eat!(self, "target") { let span = span!(self, start); - let expr = Box::new(Expr::MetaProp(MetaPropExpr { + let expr = MetaPropExpr { span, kind: MetaPropKind::NewTarget, - })); + } + .into(); let ctx = self.ctx(); if (!ctx.inside_non_arrow_function_scope) && !ctx.in_parameters && !ctx.in_class @@ -619,13 +624,16 @@ impl Parser { // Parsed with 'MemberExpression' production. let args = self.parse_args(false).map(Some)?; - let new_expr = Callee::Expr(Box::new(Expr::New(NewExpr { - span: span!(self, start), - callee, - args, - type_args, - ..Default::default() - }))); + let new_expr = Callee::Expr( + NewExpr { + span: span!(self, start), + callee, + args, + type_args, + ..Default::default() + } + .into(), + ); // We should parse subscripts for MemberExpression. // Because it's left recursive. @@ -634,13 +642,14 @@ impl Parser { // Parsed with 'NewExpression' production. - return Ok(Box::new(Expr::New(NewExpr { + return Ok(NewExpr { span: span!(self, start), callee, args: None, type_args, ..Default::default() - }))); + } + .into()); } if eat!(self, "super") { @@ -662,11 +671,12 @@ impl Parser { }; let obj = if let Some(type_args) = type_args { trace_cur!(self, parse_member_expr_or_new_expr__with_type_args); - Box::new(Expr::TsInstantiation(TsInstantiation { + TsInstantiation { expr: obj, type_args, span: span!(self, start), - })) + } + .into() } else { obj }; @@ -813,15 +823,18 @@ impl Parser { unexpected!(p, "fail") } - Ok(Some(Box::new(Expr::Arrow(ArrowExpr { - span: span!(p, expr_start), - is_async: async_span.is_some(), - is_generator: false, - params, - body, - return_type: Some(return_type), - ..Default::default() - })))) + Ok(Some( + ArrowExpr { + span: span!(p, expr_start), + is_async: async_span.is_some(), + is_generator: false, + params, + body, + return_type: Some(return_type), + ..Default::default() + } + .into(), + )) }) { return Ok(expr); } @@ -894,7 +907,7 @@ impl Parser { return Ok(errorred_expr); } } - return Ok(Box::new(Expr::Arrow(arrow_expr))); + return Ok(arrow_expr.into()); } else { // If there's no arrow function, we have to check there's no // AssignProp in lhs to check against assignment in object literals @@ -925,15 +938,15 @@ impl Parser { .collect::, _>>()?; if let Some(async_span) = async_span { // It's a call expression - return Ok(Box::new(Expr::Call(CallExpr { + return Ok(CallExpr { span: span!(self, async_span.lo()), - callee: Callee::Expr(Box::new(Expr::Ident(Ident::new_no_ctxt( - "async".into(), - async_span, - )))), + callee: Callee::Expr(Box::new( + Ident::new_no_ctxt("async".into(), async_span).into(), + )), args: expr_or_spreads, ..Default::default() - }))); + } + .into()); } // It was not head of arrow function. @@ -957,10 +970,11 @@ impl Parser { } => syntax_error!(self, expr.span(), SyntaxError::SpreadInParenExpr), ExprOrSpread { expr, .. } => expr, }; - Ok(Box::new(Expr::Paren(ParenExpr { + Ok(ParenExpr { span: span!(self, expr_start), expr, - }))) + } + .into()) } else { debug_assert!(expr_or_spreads.len() >= 2); @@ -977,17 +991,19 @@ impl Parser { debug_assert!(exprs.len() >= 2); // span of sequence expression should not include '(', ')' - let seq_expr = Box::new(Expr::Seq(SeqExpr { + let seq_expr = SeqExpr { span: Span::new( exprs.first().unwrap().span_lo(), exprs.last().unwrap().span_hi(), ), exprs, - })); - Ok(Box::new(Expr::Paren(ParenExpr { + } + .into(); + Ok(ParenExpr { span: span!(self, expr_start), expr: seq_expr, - }))) + } + .into()) } } @@ -1140,10 +1156,11 @@ impl Parser { Callee::Expr(expr) => expr, }; return Ok(( - Box::new(Expr::TsNonNull(TsNonNullExpr { + TsNonNullExpr { span: span!(self, start), expr, - })), + } + .into(), true, )); } @@ -1174,7 +1191,7 @@ impl Parser { // But it might be a call with a type argument `async();` let async_arrow_fn = p.try_parse_ts_generic_async_arrow_fn(start)?; if let Some(async_arrow_fn) = async_arrow_fn { - return Ok(Some((Box::new(Expr::Arrow(async_arrow_fn)), true))); + return Ok(Some((async_arrow_fn.into(), true))); } } @@ -1190,7 +1207,7 @@ impl Parser { if let Callee::Expr(callee) = &obj { if let Expr::OptChain(..) = &**callee { return Ok(Some(( - Box::new(Expr::OptChain(OptChainExpr { + OptChainExpr { span: span!(p, start), base: Box::new(OptChainBase::Call(OptCall { span: span!(p, start), @@ -1200,20 +1217,22 @@ impl Parser { ..Default::default() })), optional: false, - })), + } + .into(), true, ))); } } Ok(Some(( - Box::new(Expr::Call(CallExpr { + CallExpr { span: span!(p, start), callee: obj, type_args: Some(type_args), args, ..Default::default() - })), + } + .into(), true, ))) } else if is!(p, '`') { @@ -1224,18 +1243,19 @@ impl Parser { }, Some(type_args), ) - .map(|expr| (Box::new(Expr::TaggedTpl(expr)), true)) + .map(|expr| (expr.into(), true)) .map(Some) } else if is_one_of!(p, '=', "as") { Ok(Some(( - Box::new(Expr::TsInstantiation(TsInstantiation { + TsInstantiation { span: span!(p, start), expr: match mut_obj_opt { Some(Callee::Expr(obj)) => obj.take(), _ => unreachable!(), }, type_args, - })), + } + .into(), false, ))) } else if no_call { @@ -1313,11 +1333,12 @@ impl Parser { } syntax_error!(self, self.input.cur_span(), SyntaxError::InvalidSuper); } else { - Expr::SuperProp(SuperPropExpr { + SuperPropExpr { span, obj, prop: SuperProp::Computed(prop), - }) + } + .into() } } Callee::Expr(obj) => { @@ -1328,21 +1349,23 @@ impl Parser { prop: MemberProp::Computed(prop), }; let expr = if is_opt_chain || question_dot_token.is_some() { - Expr::OptChain(OptChainExpr { + OptChainExpr { span, optional: question_dot_token.is_some(), base: Box::new(OptChainBase::Member(expr)), - }) + } + .into() } else { - Expr::Member(expr) + expr.into() }; if let Some(type_args) = type_args { - Expr::TsInstantiation(TsInstantiation { + TsInstantiation { expr: Box::new(expr), type_args, span: span!(self, start), - }) + } + .into() } else { expr } @@ -1375,7 +1398,7 @@ impl Parser { syntax_error!(self, self.input.cur_span(), SyntaxError::SuperCallOptional) } Callee::Expr(callee) => Ok(( - Box::new(Expr::OptChain(OptChainExpr { + OptChainExpr { span, optional: question_dot_token.is_some(), base: Box::new(OptChainBase::Call(OptCall { @@ -1385,7 +1408,8 @@ impl Parser { type_args, ..Default::default() })), - })), + } + .into(), true, )), } @@ -1429,20 +1453,22 @@ impl Parser { self.emit_err(span, SyntaxError::ImportMetaInScript); } match &*sym { - "meta" => Expr::MetaProp(MetaPropExpr { + "meta" => MetaPropExpr { span, kind: MetaPropKind::ImportMeta, - }), + } + .into(), _ => { let args = self.parse_args(true)?; - Expr::Call(CallExpr { + CallExpr { span, callee, args, type_args: None, ..Default::default() - }) + } + .into() } } } @@ -1466,11 +1492,12 @@ impl Parser { syntax_error!(self, self.input.cur_span(), SyntaxError::InvalidSuper); } else { match prop { - MemberProp::Ident(ident) => Expr::SuperProp(SuperPropExpr { + MemberProp::Ident(ident) => SuperPropExpr { span, obj, prop: SuperProp::Ident(ident), - }), + } + .into(), MemberProp::PrivateName(..) => syntax_error!( self, self.input.cur_span(), @@ -1485,20 +1512,22 @@ impl Parser { let expr = if unwrap_ts_non_null(&expr.obj).is_opt_chain() || question_dot_token.is_some() { - Expr::OptChain(OptChainExpr { + OptChainExpr { span: span!(self, start), optional: question_dot_token.is_some(), base: Box::new(OptChainBase::Member(expr)), - }) + } + .into() } else { - Expr::Member(expr) + expr.into() }; if let Some(type_args) = type_args { - Expr::TsInstantiation(TsInstantiation { + TsInstantiation { expr: Box::new(expr), type_args, span: span!(self, start), - }) + } + .into() } else { expr } @@ -1511,11 +1540,12 @@ impl Parser { match obj { Callee::Expr(expr) => { let expr = if let Some(type_args) = type_args { - Box::new(Expr::TsInstantiation(TsInstantiation { + TsInstantiation { expr, type_args, span: span!(self, start), - })) + } + .into() } else { expr }; @@ -1528,7 +1558,7 @@ impl Parser { }; let tpl = self.with_ctx(ctx).parse_tagged_tpl(expr, None)?; - return Ok((Box::new(Expr::TaggedTpl(tpl)), true)); + return Ok((tpl.into(), true)); } Ok((expr, false)) @@ -1624,7 +1654,7 @@ impl Parser { Some(&tok!('(')), "parse_new_expr() should eat paren if it exists" ); - return Ok(Box::new(Expr::New(NewExpr { type_args, ..ne }))); + return Ok(NewExpr { type_args, ..ne }.into()); } // 'CallExpr' rule contains 'MemberExpr (...)', // and 'MemberExpr' rule contains 'new MemberExpr (...)' @@ -1645,27 +1675,27 @@ impl Parser { let args = self.parse_args(is_import)?; let call_expr = match callee { - Callee::Expr(e) if unwrap_ts_non_null(&e).is_opt_chain() => { - Box::new(Expr::OptChain(OptChainExpr { + Callee::Expr(e) if unwrap_ts_non_null(&e).is_opt_chain() => OptChainExpr { + span: span!(self, start), + base: Box::new(OptChainBase::Call(OptCall { span: span!(self, start), - base: Box::new(OptChainBase::Call(OptCall { - span: span!(self, start), - callee: e, - args, - type_args, - ..Default::default() - })), - optional: false, - })) + callee: e, + args, + type_args, + ..Default::default() + })), + optional: false, } - _ => Box::new(Expr::Call(CallExpr { + .into(), + _ => CallExpr { span: span!(self, start), callee, args, type_args, ..Default::default() - })), + } + .into(), }; return self.parse_subscripts(Callee::Expr(call_expr), false, false); @@ -1794,13 +1824,14 @@ impl Parser { arg = ExprOrSpread { spread: None, - expr: Box::new(Expr::Cond(CondExpr { + expr: CondExpr { span: Span::new(start, alt.span_hi()), test, cons, alt, - })), + } + .into(), }; false @@ -1829,12 +1860,13 @@ impl Parser { } } if let Some(span) = arg.spread { - pat = Pat::Rest(RestPat { + pat = RestPat { span: span!(self, pat_start), dot3_token: span, arg: Box::new(pat), type_ann: None, - }); + } + .into(); } match pat { Pat::Ident(BindingIdent { @@ -1876,11 +1908,12 @@ impl Parser { if eat!(self, '=') { let right = self.parse_assignment_expr()?; - pat = Pat::Assign(AssignPat { + pat = AssignPat { span: span!(self, pat_start), left: Box::new(pat), right, - }); + } + .into(); } if has_modifier { @@ -1979,11 +2012,12 @@ impl Parser { .map(|t| t.kind().starts_expr()) .unwrap_or(true)) { - Ok(Box::new(Expr::Yield(YieldExpr { + Ok(YieldExpr { span: span!(self, start), arg: None, delegate: false, - }))) + } + .into()) } else { let has_star = eat!(self, '*'); let err_span = span!(self, start); @@ -1999,11 +2033,12 @@ impl Parser { ) })?; - Ok(Box::new(Expr::Yield(YieldExpr { + Ok(YieldExpr { span: span!(self, start), arg: Some(arg), delegate: has_star, - }))) + } + .into()) } } diff --git a/crates/swc_ecma_parser/src/parser/expr/ops.rs b/crates/swc_ecma_parser/src/parser/expr/ops.rs index 3a92ac35a5d..ecedf9ee735 100644 --- a/crates/swc_ecma_parser/src/parser/expr/ops.rs +++ b/crates/swc_ecma_parser/src/parser/expr/ops.rs @@ -19,12 +19,12 @@ impl Parser { &tok!("in") if ctx.include_in_expr => { self.emit_err(self.input.cur_span(), SyntaxError::TS1109); - Box::new(Expr::Invalid(Invalid { span: err.span() })) + Invalid { span: err.span() }.into() } &tok!("instanceof") | &Token::BinOp(..) => { self.emit_err(self.input.cur_span(), SyntaxError::TS1109); - Box::new(Expr::Invalid(Invalid { span: err.span() })) + Invalid { span: err.span() }.into() } _ => return Err(err), } @@ -98,17 +98,19 @@ impl Parser { bump!(self); // as let _ = cur!(self, false); bump!(self); // const - Box::new(Expr::TsConstAssertion(TsConstAssertion { + TsConstAssertion { span: span!(self, start), expr, - })) + } + .into() } else { let type_ann = self.next_then_parse_ts_type()?; - Box::new(Expr::TsAs(TsAsExpr { + TsAsExpr { span: span!(self, start), expr, type_ann, - })) + } + .into() }; return self.parse_bin_op_recursively_inner(node, min_prec); @@ -121,11 +123,12 @@ impl Parser { let expr = left; let node = { let type_ann = self.next_then_parse_ts_type()?; - Box::new(Expr::TsSatisfies(TsSatisfiesExpr { + TsSatisfiesExpr { span: span!(self, start), expr, type_ann, - })) + } + .into() }; return self.parse_bin_op_recursively_inner(node, min_prec); @@ -227,12 +230,13 @@ impl Parser { } } - let node = Box::new(Expr::Bin(BinExpr { + let node = BinExpr { span: Span::new(left.span_lo(), right.span_hi()), op, left, right, - })); + } + .into(); Ok((node, Some(min_prec))) } @@ -248,10 +252,11 @@ impl Parser { if eat!(self, "const") { expect!(self, '>'); let expr = self.parse_unary_expr()?; - return Ok(Box::new(Expr::TsConstAssertion(TsConstAssertion { + return Ok(TsConstAssertion { span: span!(self, start), expr, - }))); + } + .into()); } return self @@ -272,12 +277,13 @@ impl Parser { let span = Span::new(start, arg.span_hi()); self.check_assign_target(&arg, false); - return Ok(Box::new(Expr::Update(UpdateExpr { + return Ok(UpdateExpr { span, prefix: true, op, arg, - }))); + } + .into()); } // Parse unary expression @@ -297,9 +303,10 @@ impl Parser { Ok(expr) => expr, Err(err) => { self.emit_error(err); - Box::new(Expr::Invalid(Invalid { + Invalid { span: Span::new(arg_start, arg_start), - })) + } + .into() } }; @@ -321,11 +328,12 @@ impl Parser { } } - return Ok(Box::new(Expr::Unary(UnaryExpr { + return Ok(UnaryExpr { span: Span::new(start, arg.span_hi()), op, arg, - }))); + } + .into()); } if is!(self, "await") { @@ -350,12 +358,13 @@ impl Parser { op!("--") }; - return Ok(Box::new(Expr::Update(UpdateExpr { + return Ok(UpdateExpr { span: span!(self, expr.span_lo()), prefix: false, op, arg: expr, - }))); + } + .into()); } Ok(expr) } @@ -383,10 +392,7 @@ impl Parser { self.emit_err(span, SyntaxError::InvalidIdentInAsync); } - return Ok(Box::new(Expr::Ident(Ident::new_no_ctxt( - "await".into(), - span, - )))); + return Ok(Ident::new_no_ctxt("await".into(), span).into()); } if ctx.in_function && !ctx.in_async { @@ -398,10 +404,11 @@ impl Parser { } let arg = self.parse_unary_expr()?; - Ok(Box::new(Expr::Await(AwaitExpr { + Ok(AwaitExpr { span: span!(self, start), arg, - }))) + } + .into()) } } diff --git a/crates/swc_ecma_parser/src/parser/expr/tests.rs b/crates/swc_ecma_parser/src/parser/expr/tests.rs index b85cf39ab68..5f211dcc82f 100644 --- a/crates/swc_ecma_parser/src/parser/expr/tests.rs +++ b/crates/swc_ecma_parser/src/parser/expr/tests.rs @@ -34,16 +34,20 @@ fn expr(s: &'static str) -> Box { }) } fn regex_expr() -> Box { - Box::new(Expr::Assign(AssignExpr { + AssignExpr { span, left: Ident::new_no_ctxt("re".into(), span).into(), op: AssignOp::Assign, - right: Box::new(Expr::Lit(Lit::Regex(Regex { - span, - exp: "w+".into(), - flags: "".into(), - }))), - })) + right: Box::new( + Lit::Regex(Regex { + span, + exp: "w+".into(), + flags: "".into(), + }) + .into(), + ), + } + .into() } #[test] fn regex_single_line_comment() { diff --git a/crates/swc_ecma_parser/src/parser/object.rs b/crates/swc_ecma_parser/src/parser/object.rs index ed9b3608f2b..5ccb22ed9f0 100644 --- a/crates/swc_ecma_parser/src/parser/object.rs +++ b/crates/swc_ecma_parser/src/parser/object.rs @@ -134,7 +134,7 @@ impl ParseObject> for Parser { if let Some(trailing_comma) = trailing_comma { self.state.trailing_commas.insert(span.lo, trailing_comma); } - Ok(Box::new(Expr::Object(ObjectLit { span, props }))) + Ok(ObjectLit { span, props }.into()) } /// spec: 'PropertyDefinition' @@ -192,9 +192,10 @@ impl ParseObject> for Parser { self.emit_err(self.input.cur_span(), SyntaxError::TS1005); return Ok(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key, - value: Box::new(Expr::Invalid(Invalid { + value: Invalid { span: span!(self, start), - })), + } + .into(), })))); } // @@ -373,7 +374,7 @@ impl ParseObject> for Parser { SyntaxError::SetterParam, ); - Pat::Invalid(Invalid { span: DUMMY_SP }) + Invalid { span: DUMMY_SP }.into() }), ); @@ -454,12 +455,13 @@ impl ParseObject for Parser { let optional = (self.input.syntax().dts() || self.ctx().in_declare) && eat!(self, '?'); - Ok(Pat::Object(ObjectPat { + Ok(ObjectPat { span, props, optional, type_ann: None, - })) + } + .into()) } /// Production 'BindingProperty' diff --git a/crates/swc_ecma_parser/src/parser/pat.rs b/crates/swc_ecma_parser/src/parser/pat.rs index 4e296431f0d..90b411a48c4 100644 --- a/crates/swc_ecma_parser/src/parser/pat.rs +++ b/crates/swc_ecma_parser/src/parser/pat.rs @@ -76,11 +76,12 @@ impl Parser { self.emit_err(span!(self, start), SyntaxError::TS2371); } - return Ok(Pat::Assign(AssignPat { + return Ok(AssignPat { span: span!(self, start), left: Box::new(left), right, - })); + } + .into()); } Ok(left) @@ -117,12 +118,13 @@ impl Parser { let pat = self.parse_binding_pat_or_ident()?; rest_span = span!(self, start); - let pat = Pat::Rest(RestPat { + let pat = RestPat { span: rest_span, dot3_token, arg: Box::new(pat), type_ann: None, - }); + } + .into(); elems.push(Some(pat)); } else { elems.push(self.parse_binding_element().map(Some)?); @@ -139,12 +141,13 @@ impl Parser { expect!(self, ']'); let optional = (self.input.syntax().dts() || self.ctx().in_declare) && eat!(self, '?'); - Ok(Pat::Array(ArrayPat { + Ok(ArrayPat { span: span!(self, start), elems, optional, type_ann: None, - })) + } + .into()) } pub(super) fn eat_any_ts_modifier(&mut self) -> PResult { @@ -260,11 +263,12 @@ impl Parser { self.emit_err(span!(self, start), SyntaxError::TS2371); } - Pat::Assign(AssignPat { + AssignPat { span: span!(self, start), left: Box::new(pat), right, - }) + } + .into() } else { pat }; @@ -304,12 +308,13 @@ impl Parser { }; rest_span = span!(self, pat_start); - let pat = Pat::Rest(RestPat { + let pat = RestPat { span: rest_span, dot3_token, arg: Box::new(pat), type_ann, - }); + } + .into(); params.push(ParamOrTsParamProp::Param(Param { span: span!(self, param_start), decorators, @@ -429,12 +434,13 @@ impl Parser { }; rest_span = span!(self, pat_start); - let pat = Pat::Rest(RestPat { + let pat = RestPat { span: rest_span, dot3_token, arg: Box::new(pat), type_ann, - }); + } + .into(); if self.syntax().typescript() && eat!(self, '?') { self.emit_err(self.input.prev_span(), SyntaxError::TS1047); @@ -493,7 +499,7 @@ impl Parser { /// rest. pub(super) fn reparse_expr_as_pat(&mut self, pat_ty: PatType, expr: Box) -> PResult { if let Expr::Invalid(i) = *expr { - return Ok(Pat::Invalid(i)); + return Ok(i.into()); } if pat_ty == PatType::AssignPat { @@ -536,11 +542,11 @@ impl Parser { // to these rules if that phrase were substituted for // LeftHandSideExpression. This rule is recursively applied. Expr::Paren(..) => { - return Ok(Pat::Expr(expr)); + return Ok(expr.into()); } Expr::Ident(i) => return Ok(i.into()), _ => { - return Ok(Pat::Expr(expr)); + return Ok(expr.into()); } }, } @@ -572,7 +578,7 @@ impl Parser { match *expr { Expr::Ident(i) => return Ok(i.into()), _ => { - return Ok(Pat::Expr(expr)); + return Ok(expr.into()); } } } @@ -587,7 +593,7 @@ impl Parser { match *expr { Expr::Paren(..) => { self.emit_err(span, SyntaxError::InvalidPat); - Ok(Pat::Invalid(Invalid { span })) + Ok(Invalid { span }.into()) } Expr::Assign( assign_expr @ AssignExpr { @@ -598,7 +604,7 @@ impl Parser { let AssignExpr { span, left, right, .. } = assign_expr; - Ok(Pat::Assign(AssignPat { + Ok(AssignPat { span, left: match left { AssignTarget::Simple(left) => { @@ -607,7 +613,8 @@ impl Parser { AssignTarget::Pat(pat) => pat.into(), }, right, - })) + } + .into()) } Expr::Object(ObjectLit { span: object_span, @@ -615,7 +622,7 @@ impl Parser { }) => { // {} let len = props.len(); - Ok(Pat::Object(ObjectPat { + Ok(ObjectPat { span: object_span, props: props .into_iter() @@ -690,19 +697,21 @@ impl Parser { .collect::>()?, optional: false, type_ann: None, - })) + } + .into()) } Expr::Ident(ident) => Ok(ident.into()), Expr::Array(ArrayLit { elems: mut exprs, .. }) => { if exprs.is_empty() { - return Ok(Pat::Array(ArrayPat { + return Ok(ArrayPat { span, elems: vec![], optional: false, type_ann: None, - })); + } + .into()); } // Trailing comma may exist. We should remove those commas. @@ -753,12 +762,13 @@ impl Parser { let expr_span = expr.span(); self.reparse_expr_as_pat(pat_ty.element(), expr) .map(|pat| { - Pat::Rest(RestPat { + RestPat { span: expr_span, dot3_token, arg: Box::new(pat), type_ann: None, - }) + } + .into() }) .map(Some)? } @@ -771,30 +781,31 @@ impl Parser { }; params.push(last); } - Ok(Pat::Array(ArrayPat { + Ok(ArrayPat { span, elems: params, optional: false, type_ann: None, - })) + } + .into()) } // Invalid patterns. // Note that assignment expression with '=' is valid, and handled above. Expr::Lit(..) | Expr::Assign(..) => { self.emit_err(span, SyntaxError::InvalidPat); - Ok(Pat::Invalid(Invalid { span })) + Ok(Invalid { span }.into()) } Expr::Yield(..) if self.ctx().in_generator => { self.emit_err(span, SyntaxError::InvalidPat); - Ok(Pat::Invalid(Invalid { span })) + Ok(Invalid { span }.into()) } _ => { self.emit_err(span, SyntaxError::InvalidPat); - Ok(Pat::Invalid(Invalid { span })) + Ok(Invalid { span }.into()) } } } @@ -845,12 +856,13 @@ impl Parser { } let expr_span = expr.span(); self.reparse_expr_as_pat(pat_ty, expr).map(|pat| { - Pat::Rest(RestPat { + RestPat { span: expr_span, dot3_token, arg: Box::new(pat), type_ann: None, - }) + } + .into() })? } AssignTargetOrSpread::ExprOrSpread(ExprOrSpread { expr, .. }) => { @@ -940,12 +952,15 @@ mod tests { } fn rest() -> Option { - Some(Pat::Rest(RestPat { - span, - dot3_token: span, - type_ann: None, - arg: Box::new(Pat::Ident(ident("tail").into())), - })) + Some( + RestPat { + span, + dot3_token: span, + type_ann: None, + arg: ident("tail").into(), + } + .into(), + ) } #[test] @@ -1153,12 +1168,13 @@ mod tests { fn prop(key: PropName, assign_name: &str, expr: Expr) -> PropOrSpread { PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key, - value: Box::new(Expr::Assign(AssignExpr { + value: AssignExpr { span, op: AssignOp::Assign, left: ident(assign_name).into(), right: Box::new(expr), - })), + } + .into(), }))) } diff --git a/crates/swc_ecma_parser/src/parser/stmt.rs b/crates/swc_ecma_parser/src/parser/stmt.rs index 90511c02954..29f1dc406ff 100644 --- a/crates/swc_ecma_parser/src/parser/stmt.rs +++ b/crates/swc_ecma_parser/src/parser/stmt.rs @@ -263,7 +263,7 @@ impl<'a, I: Tokens> Parser { return Ok(Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Invalid(Invalid { span })), + expr: Invalid { span }.into(), })); } @@ -276,7 +276,7 @@ impl<'a, I: Tokens> Parser { return Ok(Stmt::Expr(ExprStmt { span, - expr: Box::new(Expr::Invalid(Invalid { span })), + expr: Invalid { span }.into(), })); } @@ -399,7 +399,7 @@ impl<'a, I: Tokens> Parser { if eat!(self, ':') { return self.parse_labelled_stmt(ident); } - Box::new(Expr::Ident(ident)) + ident.into() } _ => self.verify_expr(expr)?, }; @@ -1327,7 +1327,7 @@ impl<'a, I: Tokens> Parser { if is_using_decl { let name = self.parse_binding_ident()?; let decl = VarDeclarator { - name: Pat::Ident(name), + name: name.into(), span: span!(self, start), init: None, definite: false, diff --git a/crates/swc_ecma_parser/src/parser/typescript.rs b/crates/swc_ecma_parser/src/parser/typescript.rs index cde1e30cbde..48d760483c7 100644 --- a/crates/swc_ecma_parser/src/parser/typescript.rs +++ b/crates/swc_ecma_parser/src/parser/typescript.rs @@ -1027,7 +1027,7 @@ impl Parser { // Note: TS uses parseLeftHandSideExpressionOrHigher, // then has grammar errors later if it's not an EntityName. - let ident = Box::new(Expr::Ident(self.parse_ident_name()?.into())); + let ident = self.parse_ident_name()?.into(); let expr = self.parse_subscripts(Callee::Expr(ident), true, true)?; if !matches!( &*expr, @@ -1390,9 +1390,9 @@ impl Parser { Either::Left(e) => { p.emit_err(e.span(), SyntaxError::PrivateNameInInterface); - Box::new(Expr::PrivateName(e)) + e.into() } - Either::Right(e) => Box::new(Expr::Ident(e.into())), + Either::Right(e) => e.into(), }), }; @@ -1736,14 +1736,15 @@ impl Parser { expect!(p, ':'); Ok(Some(if let Some(dot3_token) = rest { - Pat::Rest(RestPat { + RestPat { span: span!(p, start), dot3_token, - arg: Box::new(Pat::Ident(ident.into())), + arg: ident.into(), type_ann: None, - }) + } + .into() } else { - Pat::Ident(ident.into()) + ident.into() })) }) } diff --git a/crates/swc_ecma_parser/tests/common/mod.rs b/crates/swc_ecma_parser/tests/common/mod.rs index a4ad9700187..d1c194db26e 100644 --- a/crates/swc_ecma_parser/tests/common/mod.rs +++ b/crates/swc_ecma_parser/tests/common/mod.rs @@ -25,10 +25,11 @@ impl Fold for Normalizer { match e { Expr::Paren(ParenExpr { expr, .. }) if self.is_test262 => *expr, - Expr::New(n @ NewExpr { args: None, .. }) if self.is_test262 => Expr::New(NewExpr { + Expr::New(n @ NewExpr { args: None, .. }) if self.is_test262 => NewExpr { args: Some(vec![]), ..n - }), + } + .into(), // Flatten comma expressions. Expr::Seq(SeqExpr { mut exprs, span }) => { let need_work = exprs.iter().any(|n| matches!(**n, Expr::Seq(..))); @@ -42,7 +43,7 @@ impl Fold for Normalizer { v }); } - Expr::Seq(SeqExpr { exprs, span }) + SeqExpr { exprs, span }.into() } _ => e, } @@ -84,9 +85,9 @@ impl Fold for Normalizer { if let Pat::Expr(expr) = node { match *expr { - Expr::Ident(i) => return Pat::Ident(i.into()), + Expr::Ident(i) => return i.into(), _ => { - node = Pat::Expr(expr); + node = expr.into(); } } } diff --git a/crates/swc_ecma_parser/tests/jsx.rs b/crates/swc_ecma_parser/tests/jsx.rs index 4c31ebdd102..886e3189a8f 100644 --- a/crates/swc_ecma_parser/tests/jsx.rs +++ b/crates/swc_ecma_parser/tests/jsx.rs @@ -123,9 +123,9 @@ impl Fold for Normalizer { if let Pat::Expr(expr) = node { match *expr { - Expr::Ident(i) => return Pat::Ident(i.into()), + Expr::Ident(i) => return i.into(), _ => { - node = Pat::Expr(expr); + node = expr.into(); } } } diff --git a/crates/swc_ecma_preset_env/src/corejs2/mod.rs b/crates/swc_ecma_preset_env/src/corejs2/mod.rs index 4fd5175ef2d..46cfe3787a5 100644 --- a/crates/swc_ecma_preset_env/src/corejs2/mod.rs +++ b/crates/swc_ecma_preset_env/src/corejs2/mod.rs @@ -144,7 +144,7 @@ impl Visit for UsageVisitor { self.visit_object_pat_props(init, &o.props) } } else if let Pat::Object(ref o) = d.name { - self.visit_object_pat_props(&Expr::Ident(Ident::default()), &o.props) + self.visit_object_pat_props(&Ident::default().into(), &o.props) } } diff --git a/crates/swc_ecma_preset_env/src/corejs3/usage.rs b/crates/swc_ecma_preset_env/src/corejs3/usage.rs index 35cf1f87a6e..5a0f0a6b51e 100644 --- a/crates/swc_ecma_preset_env/src/corejs3/usage.rs +++ b/crates/swc_ecma_preset_env/src/corejs3/usage.rs @@ -254,7 +254,7 @@ impl Visit for UsageVisitor { self.visit_object_pat_props(init, &o.props) } } else if let Pat::Object(ref o) = d.name { - self.visit_object_pat_props(&Expr::Ident(Ident::default()), &o.props) + self.visit_object_pat_props(&Ident::default().into(), &o.props) } } diff --git a/crates/swc_ecma_preset_env/src/lib.rs b/crates/swc_ecma_preset_env/src/lib.rs index 7ebbe757ae2..b141ab645fd 100644 --- a/crates/swc_ecma_preset_env/src/lib.rs +++ b/crates/swc_ecma_preset_env/src/lib.rs @@ -511,11 +511,11 @@ impl VisitMut for Polyfills { span: DUMMY_SP, expr: CallExpr { span, - callee: Expr::Ident(Ident { + callee: Ident { ctxt: SyntaxContext::empty().apply_mark(self.unresolved_mark), sym: "require".into(), ..Default::default() - }) + } .as_callee(), args: vec![Str { span: DUMMY_SP, @@ -538,11 +538,11 @@ impl VisitMut for Polyfills { span: DUMMY_SP, expr: CallExpr { span, - callee: Expr::Ident(Ident { + callee: Ident { ctxt: SyntaxContext::empty().apply_mark(self.unresolved_mark), sym: "require".into(), ..Default::default() - }) + } .as_callee(), args: vec![Str { span: DUMMY_SP, diff --git a/crates/swc_ecma_transforms_base/benches/deps.rs b/crates/swc_ecma_transforms_base/benches/deps.rs index 2370e7d5fe8..a2d02559d6d 100644 --- a/crates/swc_ecma_transforms_base/benches/deps.rs +++ b/crates/swc_ecma_transforms_base/benches/deps.rs @@ -120,12 +120,13 @@ fn fold_noop_impl_vec(b: &mut Bencher) { } fn mk_expr() -> Expr { - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: Ident::new_no_ctxt("foo".into(), DUMMY_SP).as_callee(), args: vec![], ..Default::default() - }) + } + .into() } fn boxing_boxed_clone(b: &mut Bencher) { diff --git a/crates/swc_ecma_transforms_base/src/fixer.rs b/crates/swc_ecma_transforms_base/src/fixer.rs index 35ff338d792..ed0bec5a5cd 100644 --- a/crates/swc_ecma_transforms_base/src/fixer.rs +++ b/crates/swc_ecma_transforms_base/src/fixer.rs @@ -486,8 +486,8 @@ impl VisitMut for Fixer<'_> { _ => false, } => { - let expr = Expr::Ident(p.clone().expect_ident().into()); - s.left = ForHead::Pat(Box::new(Pat::Expr(Box::new(expr)))); + let expr: Pat = p.clone().expect_ident().into(); + s.left = ForHead::Pat(expr.into()); } _ => (), } @@ -878,7 +878,7 @@ impl Fixer<'_> { } } - let mut expr = Expr::Seq(SeqExpr { span: *span, exprs }); + let mut expr = SeqExpr { span: *span, exprs }.into(); if let Context::ForcedExpr = self.ctx { self.wrap(&mut expr); @@ -985,7 +985,7 @@ impl Fixer<'_> { }; let expr = Box::new(e.take()); - *e = Expr::Paren(ParenExpr { expr, span }); + *e = ParenExpr { expr, span }.into(); } /// Removes paren @@ -1071,7 +1071,7 @@ fn ignore_return_value(expr: Box, has_padding_value: &mut bool) -> Option< match exprs.len() { 0 | 1 => exprs.pop(), - _ => Some(Box::new(Expr::Seq(SeqExpr { span, exprs }))), + _ => Some(SeqExpr { span, exprs }.into()), } } Expr::Unary(UnaryExpr { diff --git a/crates/swc_ecma_transforms_base/src/helpers/mod.rs b/crates/swc_ecma_transforms_base/src/helpers/mod.rs index c383a253939..4a2e1398646 100644 --- a/crates/swc_ecma_transforms_base/src/helpers/mod.rs +++ b/crates/swc_ecma_transforms_base/src/helpers/mod.rs @@ -434,7 +434,7 @@ impl InjectHelpers { fn build_reqire(&self, name: &str, mark: Mark) -> Stmt { let c = CallExpr { span: DUMMY_SP, - callee: Expr::Ident(Ident { + callee: Expr::from(Ident { span: DUMMY_SP, ctxt: SyntaxContext::empty().apply_mark(self.global_mark), sym: "require".into(), diff --git a/crates/swc_ecma_transforms_base/src/rename/ops.rs b/crates/swc_ecma_transforms_base/src/rename/ops.rs index 49aca529b81..80158c4635a 100644 --- a/crates/swc_ecma_transforms_base/src/rename/ops.rs +++ b/crates/swc_ecma_transforms_base/src/rename/ops.rs @@ -132,7 +132,7 @@ where let var = VarDeclarator { span, name: cls.ident.clone().into(), - init: Some(Box::new(Expr::Class(expr))), + init: Some(expr.into()), definite: false, }; *decl = VarDecl { @@ -466,11 +466,12 @@ where *n = KeyValuePatProp { key: PropName::Ident(p.key.take().into()), value: match p.value.take() { - Some(default_expr) => Box::new(Pat::Assign(AssignPat { + Some(default_expr) => AssignPat { span: p.span, left: renamed.into(), right: default_expr, - })), + } + .into(), None => renamed.into(), }, } @@ -500,7 +501,7 @@ where span: i.span, sym: i.sym.clone(), }), - value: Box::new(Expr::Ident(renamed)), + value: renamed.into(), }) } } diff --git a/crates/swc_ecma_transforms_classes/src/lib.rs b/crates/swc_ecma_transforms_classes/src/lib.rs index 70b3df8a193..a39c9e97d98 100644 --- a/crates/swc_ecma_transforms_classes/src/lib.rs +++ b/crates/swc_ecma_transforms_classes/src/lib.rs @@ -15,10 +15,11 @@ pub mod super_field; /// Child.__proto__ || Object.getPrototypeOf(Child) /// ``` pub fn get_prototype_of(obj: Box) -> Box { - Box::new(Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: helper!(get_prototype_of), args: vec![obj.as_arg()], ..Default::default() - })) + } + .into() } diff --git a/crates/swc_ecma_transforms_classes/src/super_field.rs b/crates/swc_ecma_transforms_classes/src/super_field.rs index 8d1194fe91e..e0f696e03f1 100644 --- a/crates/swc_ecma_transforms_classes/src/super_field.rs +++ b/crates/swc_ecma_transforms_classes/src/super_field.rs @@ -75,7 +75,7 @@ impl<'a> VisitMut for SuperFieldAccessFolder<'a> { fn visit_mut_expr(&mut self, n: &mut Expr) { match n { Expr::This(ThisExpr { span }) if self.in_nested_scope => { - *n = Expr::Ident(quote_ident!( + *n = quote_ident!( SyntaxContext::empty().apply_mark( *self .this_alias_mark @@ -83,7 +83,8 @@ impl<'a> VisitMut for SuperFieldAccessFolder<'a> { ), *span, "_this" - )); + ) + .into(); } // We pretend method folding mode for while folding injected `_define_property` // calls. @@ -210,7 +211,7 @@ impl<'a> SuperFieldAccessFolder<'a> { let mut args = args.clone(); if args.len() == 1 && is_rest_arguments(&args[0]) { - *n = Expr::Call(CallExpr { + *n = CallExpr { span: DUMMY_SP, callee: callee.make_member(quote_ident!("apply")).as_callee(), args: iter::once(this) @@ -221,16 +222,18 @@ impl<'a> SuperFieldAccessFolder<'a> { })) .collect(), ..Default::default() - }); + } + .into(); return; } - *n = Expr::Call(CallExpr { + *n = CallExpr { span: DUMMY_SP, callee: callee.make_member(quote_ident!("call")).as_callee(), args: iter::once(this).chain(args).collect(), ..Default::default() - }); + } + .into(); } } } @@ -313,7 +316,7 @@ impl<'a> SuperFieldAccessFolder<'a> { }); // in static default super class is Function.prototype if self.is_static && self.super_class.is_some() { - Expr::Ident(name) + name.into() } else { name.make_member(quote_ident!("prototype")).into() } @@ -370,18 +373,19 @@ impl<'a> SuperFieldAccessFolder<'a> { }, }; - Expr::Assign(AssignExpr { + AssignExpr { span: super_token, left: left.into(), op, right: rhs, - }) + } + .into() } else { let proto_arg = self.proto_arg(); let prop_arg = prop_arg(prop).as_arg(); - Expr::Call(CallExpr { + CallExpr { span: super_token, callee: helper!(set), args: vec![ @@ -393,7 +397,8 @@ impl<'a> SuperFieldAccessFolder<'a> { true.as_arg(), ], ..Default::default() - }) + } + .into() } } @@ -404,7 +409,7 @@ impl<'a> SuperFieldAccessFolder<'a> { let this_arg = self.this_arg(super_token).as_arg(); - let expr = Expr::Call(CallExpr { + let expr: Expr = CallExpr { span: super_token, callee: helper!(update), args: vec![ @@ -415,7 +420,8 @@ impl<'a> SuperFieldAccessFolder<'a> { true.as_arg(), ], ..Default::default() - }); + } + .into(); expr.make_member(quote_ident!("_")) } @@ -423,7 +429,7 @@ impl<'a> SuperFieldAccessFolder<'a> { fn proto_arg(&mut self) -> Box { let expr = if self.is_static { // Foo - Box::new(Expr::Ident(self.class_name.clone())) + self.class_name.clone().into() } else { // Foo.prototype self.class_name @@ -484,11 +490,12 @@ fn prop_arg(prop: SuperProp) -> Expr { match prop { SuperProp::Ident(IdentName { sym: value, span, .. - }) => Expr::Lit(Lit::Str(Str { + }) => Lit::Str(Str { span, raw: None, value, - })), + }) + .into(), SuperProp::Computed(c) => *c.expr, } } diff --git a/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs b/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs index d893d9b3007..3ed57542f2e 100644 --- a/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs +++ b/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs @@ -276,7 +276,7 @@ impl VisitMut for ComputedFieldsHandler { if !is_literal(expr) && !is_simple_pure_expr(expr, self.pure_getters) => { let ref_key = private_ident!("prop"); - let mut computed_expr = Box::new(Expr::Ident(ref_key.clone())); + let mut computed_expr = ref_key.clone().into(); mem::swap(expr, &mut computed_expr); diff --git a/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs b/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs index 070cf6fe806..17782426c2c 100644 --- a/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs +++ b/crates/swc_ecma_transforms_compat/tests/es2017_async_to_generator.rs @@ -25,8 +25,8 @@ impl Fold for ParenRemover { match expr { Expr::Paren(ParenExpr { expr, .. }) => match *expr { - Expr::Member(e) => Expr::Member(MemberExpr { span, ..e }), - Expr::New(e) => Expr::New(NewExpr { span, ..e }), + Expr::Member(e) => MemberExpr { span, ..e }.into(), + Expr::New(e) => NewExpr { span, ..e }.into(), _ => *expr, }, _ => expr, diff --git a/crates/swc_ecma_transforms_module/src/amd.rs b/crates/swc_ecma_transforms_module/src/amd.rs index 17329dd7e00..9d4062f5ff3 100644 --- a/crates/swc_ecma_transforms_module/src/amd.rs +++ b/crates/swc_ecma_transforms_module/src/amd.rs @@ -552,13 +552,15 @@ pub(crate) fn amd_dynamic_import( fn amd_import_meta_url(span: Span, module: Ident) -> Expr { MemberExpr { span, - obj: Box::new(Expr::New(quote_ident!("URL").into_new_expr( - DUMMY_SP, - Some(vec![ - module.make_member(quote_ident!("uri")).as_arg(), - member_expr!(Default::default(), DUMMY_SP, document.baseURI).as_arg(), - ]), - ))), + obj: quote_ident!("URL") + .into_new_expr( + DUMMY_SP, + Some(vec![ + module.make_member(quote_ident!("uri")).as_arg(), + member_expr!(Default::default(), DUMMY_SP, document.baseURI).as_arg(), + ]), + ) + .into(), prop: MemberProp::Ident("href".into()), } .into() diff --git a/crates/swc_ecma_transforms_module/src/common_js.rs b/crates/swc_ecma_transforms_module/src/common_js.rs index 792071f57eb..6e510ed3421 100644 --- a/crates/swc_ecma_transforms_module/src/common_js.rs +++ b/crates/swc_ecma_transforms_module/src/common_js.rs @@ -543,8 +543,7 @@ where self.resolver .make_require_call(self.unresolved_mark, src.clone(), DUMMY_SP); - Expr::Ident(quote_ident!("__export").into()) - .as_call(DUMMY_SP, vec![import_expr.as_arg()]) + quote_ident!("__export").as_call(DUMMY_SP, vec![import_expr.as_arg()]) }) .reduce(|left, right| { BinExpr { diff --git a/crates/swc_ecma_transforms_module/src/path.rs b/crates/swc_ecma_transforms_module/src/path.rs index f35ef388168..7668ba7b326 100644 --- a/crates/swc_ecma_transforms_module/src/path.rs +++ b/crates/swc_ecma_transforms_module/src/path.rs @@ -44,7 +44,7 @@ impl Resolver { ) -> Expr { let src = self.resolve(src); - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: quote_ident!( SyntaxContext::empty().apply_mark(unresolved_mark), @@ -58,7 +58,8 @@ impl Resolver { }) .as_arg()], ..Default::default() - }) + } + .into() } } diff --git a/crates/swc_ecma_transforms_module/src/system_js.rs b/crates/swc_ecma_transforms_module/src/system_js.rs index 574b16ded3e..39beba170f0 100644 --- a/crates/swc_ecma_transforms_module/src/system_js.rs +++ b/crates/swc_ecma_transforms_module/src/system_js.rs @@ -111,7 +111,7 @@ impl SystemJs { .make_member(quote_ident!("id")) .into(); } - Expr::Ident(ident) + ident.into() } fn replace_assign_expr(&mut self, assign_expr: AssignExpr) -> Expr { @@ -120,16 +120,16 @@ impl SystemJs { SimpleAssignTarget::Ident(ident) => { for (k, v) in self.export_map.iter() { if ident.to_id() == *k { - let mut expr = Expr::Assign(assign_expr); + let mut expr = assign_expr.into(); for value in v.iter() { - expr = Expr::Call(self.export_call(value.clone(), DUMMY_SP, expr)); + expr = self.export_call(value.clone(), DUMMY_SP, expr).into(); } return expr; } } - Expr::Assign(assign_expr) + assign_expr.into() } - _ => Expr::Assign(assign_expr), + _ => assign_expr.into(), }, AssignTarget::Pat(pat) => { let mut to: Vec = vec![]; @@ -143,22 +143,26 @@ impl SystemJs { for (k, v) in self.export_map.iter() { if to == *k { for _ in v.iter() { - exprs.push(Box::new(Expr::Call(self.export_call( - to.0.clone(), - DUMMY_SP, - Ident::new(to.0.clone(), DUMMY_SP, to.1).into(), - )))); + exprs.push( + self.export_call( + to.0.clone(), + DUMMY_SP, + Ident::new(to.0.clone(), DUMMY_SP, to.1).into(), + ) + .into(), + ); } break; } } } - Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - }) + } + .into() } - _ => Expr::Assign(assign_expr), + _ => assign_expr.into(), } } } @@ -170,31 +174,34 @@ impl SystemJs { Expr::Ident(ident) => { for (k, v) in self.export_map.iter() { if ident.to_id() == *k { - let mut expr = Expr::Bin(BinExpr { + let mut expr = BinExpr { span: DUMMY_SP, op: op!(bin, "+"), - left: Box::new(Expr::Unary(UnaryExpr { + left: UnaryExpr { span: DUMMY_SP, op: op!(unary, "+"), arg: Box::new(Expr::Ident(ident.clone())), - })), + } + .into(), right: 1.0.into(), - }); - for value in v.iter() { - expr = Expr::Call(self.export_call(value.clone(), DUMMY_SP, expr)); } - return Expr::Seq(SeqExpr { + .into(); + for value in v.iter() { + expr = self.export_call(value.clone(), DUMMY_SP, expr).into(); + } + return SeqExpr { span: DUMMY_SP, exprs: vec![Box::new(expr), Box::new(Expr::Update(update_expr))], - }); + } + .into(); } } - Expr::Update(update_expr) + update_expr.into() } - _ => Expr::Update(update_expr), + _ => update_expr.into(), } } else { - Expr::Update(update_expr) + update_expr.into() } } @@ -290,7 +297,7 @@ impl SystemJs { ..Default::default() } .into(), - right: Box::new(Expr::Ident(target.clone().into())), + right: target.clone().into(), body: Box::new(Stmt::Block(BlockStmt { span: DUMMY_SP, @@ -401,20 +408,26 @@ impl SystemJs { } if let Some(init) = var_declarator.init { - exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: var_declarator.name.try_into().unwrap(), - right: init, - }))); + exprs.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: var_declarator.name.try_into().unwrap(), + right: init, + } + .into(), + ); } } match exprs.len() { 0 => None, - _ => Some(Expr::Seq(SeqExpr { - span: DUMMY_SP, - exprs, - })), + _ => Some( + SeqExpr { + span: DUMMY_SP, + exprs, + } + .into(), + ), } } @@ -552,7 +565,7 @@ impl Fold for SystemJs { } Expr::Update(update) => self.replace_update_expr(update), Expr::Call(call) => match call.callee { - Callee::Import(_) => Expr::Call(CallExpr { + Callee::Import(_) => CallExpr { args: call.args.fold_with(self), callee: self .context_ident @@ -560,8 +573,9 @@ impl Fold for SystemJs { .make_member(quote_ident!("import")) .as_callee(), ..call - }), - _ => Expr::Call(call), + } + .into(), + _ => call.into(), }, Expr::MetaProp(meta_prop_expr) => match meta_prop_expr.kind { MetaPropKind::ImportMeta => self @@ -569,14 +583,14 @@ impl Fold for SystemJs { .clone() .make_member(quote_ident!("meta")) .into(), - _ => Expr::MetaProp(meta_prop_expr), + _ => meta_prop_expr.into(), }, Expr::Await(await_expr) => { if self.enter_async_fn == 0 { self.tla = true; } - Expr::Await(await_expr) + await_expr.into() } _ => expr, } @@ -673,18 +687,19 @@ impl Fold for SystemJs { span: specifier.span, op: op!("="), left: specifier.local.clone().into(), - right: Box::new(Expr::Member(MemberExpr { + right: MemberExpr { span: DUMMY_SP, - obj: Box::new(Expr::Ident( + obj: Box::new( quote_ident!(source_alias.clone()).into(), - )), + ), prop: match specifier.imported { Some(m) => get_module_export_member_prop(&m), None => { MemberProp::Ident(specifier.local.into()) } }, - })), + } + .into(), } .into_stmt(), ); @@ -697,9 +712,7 @@ impl Fold for SystemJs { span: specifier.span, op: op!("="), left: specifier.local.into(), - right: Box::new(Expr::Ident( - quote_ident!(source_alias.clone()).into(), - )), + right: quote_ident!(source_alias.clone()).into(), } .into_stmt(), ); @@ -737,13 +750,18 @@ impl Fold for SystemJs { Some(m) => get_module_export_name(m).0, None => get_module_export_name(&specifier.orig).0, }); - export_values.push(Box::new(Expr::Member(MemberExpr { - span: DUMMY_SP, - obj: Box::new(Expr::Ident( - quote_ident!(source_alias.clone()).into(), - )), - prop: get_module_export_member_prop(&specifier.orig), - }))); + export_values.push( + MemberExpr { + span: DUMMY_SP, + obj: Box::new( + quote_ident!(source_alias.clone()).into(), + ), + prop: get_module_export_member_prop( + &specifier.orig, + ), + } + .into(), + ); } ExportSpecifier::Default(specifier) => { export_names.push(specifier.exported.sym.clone()); @@ -756,9 +774,8 @@ impl Fold for SystemJs { ExportSpecifier::Namespace(specifier) => { export_names .push(get_module_export_name(&specifier.name).0); - export_values.push(Box::new(Expr::Ident( - quote_ident!(source_alias.clone()).into(), - ))); + export_values + .push(quote_ident!(source_alias.clone()).into()); } } @@ -823,18 +840,18 @@ impl Fold for SystemJs { span: DUMMY_SP, op: op!("="), left: ident.clone().into(), - right: Box::new(Expr::Class(ClassExpr { + right: ClassExpr { ident: Some(ident.clone()), class: class_decl.class, - })), + } + .into(), } .into_stmt(), ); } Decl::Fn(fn_decl) => { self.export_names.push(fn_decl.ident.sym.clone()); - self.export_values - .push(Box::new(Expr::Ident(fn_decl.ident.clone()))); + self.export_values.push(fn_decl.ident.clone().into()); self.add_export_name( fn_decl.ident.to_id(), fn_decl.ident.sym.clone(), @@ -873,20 +890,19 @@ impl Fold for SystemJs { span: DUMMY_SP, op: op!("="), left: ident.clone().into(), - right: Box::new(Expr::Class(class_expr)), + right: class_expr.into(), } .into_stmt(), ); } else { self.export_names.push("default".into()); - self.export_values.push(Box::new(Expr::Class(class_expr))); + self.export_values.push(class_expr.into()); } } DefaultDecl::Fn(fn_expr) => { if let Some(ident) = &fn_expr.ident { self.export_names.push("default".into()); - self.export_values - .push(Box::new(Expr::Ident(ident.clone()))); + 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(), @@ -895,7 +911,7 @@ impl Fold for SystemJs { }))); } else { self.export_names.push("default".into()); - self.export_values.push(Box::new(Expr::Fn(fn_expr))); + self.export_values.push(fn_expr.into()); } } _ => {} @@ -927,10 +943,11 @@ impl Fold for SystemJs { span: DUMMY_SP, op: op!("="), left: class_decl.ident.clone().into(), - right: Box::new(Expr::Class(ClassExpr { + right: ClassExpr { ident: Some(class_decl.ident.clone()), class: class_decl.class, - })), + } + .into(), } .into_stmt(), ); @@ -1022,22 +1039,25 @@ impl Fold for SystemJs { let return_stmt = ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props: vec![ - PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: quote_ident!("setters").into(), - value: Box::new(Expr::Array(setters)), - }))), - PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: quote_ident!("execute").into(), - value: Box::new(Expr::Fn(FnExpr { - ident: None, - function: execute, - })), - }))), - ], - }))), + arg: Some( + ObjectLit { + span: DUMMY_SP, + props: vec![ + PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: quote_ident!("setters").into(), + value: Box::new(Expr::Array(setters)), + }))), + PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: quote_ident!("execute").into(), + value: Box::new(Expr::Fn(FnExpr { + ident: None, + function: execute, + })), + }))), + ], + } + .into(), + ), }; let mut function_stmts = vec![use_strict()]; @@ -1053,7 +1073,7 @@ impl Fold for SystemJs { .iter() .map(|i| VarDeclarator { span: i.span, - name: Pat::Ident(i.clone().into()), + name: i.clone().into(), init: None, definite: false, }) @@ -1124,8 +1144,8 @@ fn get_module_export_name(module_export_name: &ModuleExportName) -> Id { #[inline] fn get_module_export_expr(module_export_name: &ModuleExportName) -> Expr { match &module_export_name { - ModuleExportName::Ident(ident) => Expr::Ident(ident.clone()), - ModuleExportName::Str(s) => Expr::Lit(Lit::Str(quote_str!(s.value.clone()))), + ModuleExportName::Ident(ident) => ident.clone().into(), + ModuleExportName::Str(s) => Lit::Str(quote_str!(s.value.clone())).into(), } } @@ -1135,7 +1155,7 @@ fn get_module_export_member_prop(module_export_name: &ModuleExportName) -> Membe ModuleExportName::Ident(ident) => MemberProp::Ident(ident.clone().into()), ModuleExportName::Str(s) => MemberProp::Computed(ComputedPropName { span: s.span, - expr: Box::new(Expr::Lit(Lit::Str(quote_str!(s.value.clone())))), + expr: Lit::Str(quote_str!(s.value.clone())).into(), }), } } diff --git a/crates/swc_ecma_transforms_module/src/umd.rs b/crates/swc_ecma_transforms_module/src/umd.rs index 21aad563a2f..a5b7c073477 100644 --- a/crates/swc_ecma_transforms_module/src/umd.rs +++ b/crates/swc_ecma_transforms_module/src/umd.rs @@ -413,10 +413,10 @@ where cjs_args.push(quote_ident!("exports").as_arg()); amd_dep_list.push(Some(quote_str!("exports").as_arg())); browser_args.push( - Expr::Object(ObjectLit { + ObjectLit { span: DUMMY_SP, props: Default::default(), - }) + } .make_assign_to(op!("="), global_lib.into()) .as_arg(), ); diff --git a/crates/swc_ecma_transforms_module/src/util.rs b/crates/swc_ecma_transforms_module/src/util.rs index 43b5a7ce4e3..489329f0ace 100644 --- a/crates/swc_ecma_transforms_module/src/util.rs +++ b/crates/swc_ecma_transforms_module/src/util.rs @@ -285,7 +285,7 @@ pub(crate) fn esm_export() -> Function { let getter = KeyValueProp { key: quote_ident!("get").into(), - value: all.clone().computed_member(Expr::from(name.clone())).into(), + value: all.clone().computed_member(name.clone()).into(), }; let body = object_define_enumerable( diff --git a/crates/swc_ecma_transforms_optimization/src/inline_globals.rs b/crates/swc_ecma_transforms_optimization/src/inline_globals.rs index 49d4a2b9393..32c5c435bfe 100644 --- a/crates/swc_ecma_transforms_optimization/src/inline_globals.rs +++ b/crates/swc_ecma_transforms_optimization/src/inline_globals.rs @@ -110,11 +110,12 @@ impl VisitMut for InlineGlobals { // It's ok because we don't recurse into member expressions. if let Some(value) = self.typeofs.get(sym).cloned() { - *expr = Expr::Lit(Lit::Str(Str { + *expr = Lit::Str(Str { span: *span, raw: None, value, - })); + }) + .into(); } } } diff --git a/crates/swc_ecma_transforms_optimization/src/json_parse.rs b/crates/swc_ecma_transforms_optimization/src/json_parse.rs index 1c9765358c1..1b5522a861d 100644 --- a/crates/swc_ecma_transforms_optimization/src/json_parse.rs +++ b/crates/swc_ecma_transforms_optimization/src/json_parse.rs @@ -69,7 +69,7 @@ impl VisitMut for JsonParse { unreachable!("failed to serialize serde_json::Value as json: {}", err) }); - *expr = Expr::Call(CallExpr { + *expr = CallExpr { span: expr.span(), callee: member_expr!(Default::default(), DUMMY_SP, JSON.parse).as_callee(), args: vec![Lit::Str(Str { @@ -79,7 +79,8 @@ impl VisitMut for JsonParse { }) .as_arg()], ..Default::default() - }); + } + .into(); return; } 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 185fd7bfc56..6a37ec19a8e 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs @@ -129,7 +129,7 @@ impl VisitMut for Remover { if cfg!(feature = "debug") { debug!("Dropping assignment to the same variable"); } - *e = Expr::Ident(r.take().ident().unwrap()); + *e = r.take().ident().unwrap().into(); } Expr::Assign(AssignExpr { @@ -208,16 +208,16 @@ impl VisitMut for Remover { s.visit_mut_children_with(self); s.init = s.init.take().and_then(|e| match e { - VarDeclOrExpr::Expr(e) => ignore_result(*e, true, &self.expr_ctx) - .map(Box::new) - .map(VarDeclOrExpr::from), + VarDeclOrExpr::Expr(e) => { + ignore_result(e, true, &self.expr_ctx).map(VarDeclOrExpr::from) + } _ => Some(e), }); s.update = s .update .take() - .and_then(|e| ignore_result(*e, true, &self.expr_ctx).map(Box::new)); + .and_then(|e| ignore_result(e, true, &self.expr_ctx)); s.test = s.test.take().and_then(|e| { let span = e.span(); @@ -225,7 +225,7 @@ impl VisitMut for Remover { return if value { None } else { - Some(Box::new(Expr::Lit(Lit::Bool(Bool { span, value: false })))) + Some(Lit::Bool(Bool { span, value: false }).into()) }; } @@ -374,13 +374,13 @@ impl VisitMut for Remover { return Some(e); } - ignore_result(*e, true, &self.expr_ctx).map(Box::new) + ignore_result(e, true, &self.expr_ctx) }) .collect() } else { e.exprs .take() - .move_flat_map(|e| ignore_result(*e, false, &self.expr_ctx).map(Box::new)) + .move_flat_map(|e| ignore_result(e, false, &self.expr_ctx)) }; exprs.push(last); @@ -420,9 +420,7 @@ impl VisitMut for Remover { // Preserve effect of the test if !p.is_pure() { - if let Some(expr) = - ignore_result(*test, true, &self.expr_ctx).map(Box::new) - { + if let Some(expr) = ignore_result(test, true, &self.expr_ctx) { stmts.push(Stmt::Expr(ExprStmt { span, expr })) } } @@ -470,11 +468,8 @@ impl VisitMut for Remover { if let Stmt::Empty(..) = *cons { self.changed = true; - return if let Some(expr) = ignore_result(*test, true, &self.expr_ctx) { - Stmt::Expr(ExprStmt { - span, - expr: Box::new(expr), - }) + return if let Some(expr) = ignore_result(test, true, &self.expr_ctx) { + Stmt::Expr(ExprStmt { span, expr }) } else { Stmt::Empty(EmptyStmt { span }) }; @@ -524,12 +519,8 @@ impl VisitMut for Remover { return Stmt::Expr(ExprStmt { span, expr }); } - let expr = *expr; match ignore_result(expr, false, &self.expr_ctx) { - Some(e) => Stmt::Expr(ExprStmt { - span, - expr: Box::new(e), - }), + Some(e) => Stmt::Expr(ExprStmt { span, expr: e }), None => Stmt::Empty(EmptyStmt { span: DUMMY_SP }), } } @@ -677,11 +668,8 @@ impl VisitMut for Remover { if cfg!(feature = "debug") { 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: Box::new(expr), - }), + 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 }), }; } @@ -696,7 +684,7 @@ impl VisitMut for Remover { } let mut stmts = remove_break(s.cases.remove(0).cons); - if let Some(expr) = ignore_result(*s.discriminant, true, &self.expr_ctx) { + if let Some(expr) = ignore_result(s.discriminant, true, &self.expr_ctx) { prepend_stmt(&mut stmts, expr.into_stmt()); } @@ -766,9 +754,7 @@ impl VisitMut for Remover { if let Some(i) = selected { if !has_conditional_stopper(&s.cases[i].cons) { let mut exprs = vec![]; - exprs.extend( - ignore_result(*s.discriminant, true, &self.expr_ctx).map(Box::new), - ); + exprs.extend(ignore_result(s.discriminant, true, &self.expr_ctx)); let mut stmts = s.cases[i].cons.take(); let mut cases = s.cases.drain((i + 1)..); @@ -788,8 +774,7 @@ impl VisitMut for Remover { .flat_map(|case| { exprs.extend( case.test - .and_then(|e| ignore_result(*e, true, &self.expr_ctx)) - .map(Box::new), + .and_then(|e| ignore_result(e, true, &self.expr_ctx)), ); case.cons }) @@ -824,10 +809,11 @@ impl VisitMut for Remover { expr: if exprs.len() == 1 { exprs.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - })) + } + .into() }, }), ); @@ -982,17 +968,13 @@ impl VisitMut for Remover { && !has_conditional_stopper(&s.cases.last().unwrap().cons) { let mut exprs = vec![]; - exprs.extend( - ignore_result(*s.discriminant, true, &self.expr_ctx).map(Box::new), - ); + exprs.extend(ignore_result(s.discriminant, true, &self.expr_ctx)); exprs.extend( s.cases .iter_mut() .filter_map(|case| case.test.take()) - .filter_map(|e| { - ignore_result(*e, true, &self.expr_ctx).map(Box::new) - }), + .filter_map(|e| ignore_result(e, true, &self.expr_ctx)), ); let stmts = s.cases.pop().unwrap().cons; @@ -1006,10 +988,11 @@ impl VisitMut for Remover { expr: if exprs.len() == 1 { exprs.remove(0) } else { - Box::new(Expr::Seq(SeqExpr { + SeqExpr { span: DUMMY_SP, exprs, - })) + } + .into() }, }), ); @@ -1117,10 +1100,11 @@ impl VisitMut for Remover { if v { if purity.is_pure() { Stmt::While(WhileStmt { - test: Box::new(Expr::Lit(Lit::Bool(Bool { + test: Lit::Bool(Bool { span: s.test.span(), value: true, - }))), + }) + .into(), ..s }) } else { @@ -1164,7 +1148,7 @@ impl VisitMut for Remover { let mut body = prepare_loop_body_for_inlining(*s.body); body.visit_mut_with(self); - if let Some(test) = ignore_result(*s.test, true, &self.expr_ctx) { + if let Some(test) = ignore_result(s.test, true, &self.expr_ctx) { BlockStmt { span: s.span, stmts: vec![body, test.into_stmt()], @@ -1413,12 +1397,12 @@ impl Remover { (purity, Known(val)) => { self.changed = true; if !purity.is_pure() { - let expr = ignore_result(*test, true, &self.expr_ctx); + 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: Box::new(expr), + expr, }))); } } @@ -1472,8 +1456,8 @@ impl Remover { /// - [Some] if `e` has a side effect. /// - [None] if `e` does not have a side effect. #[inline(never)] -fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { - match e { +fn ignore_result(e: Box, drop_str_lit: bool, ctx: &ExprCtx) -> Option> { + match *e { Expr::Lit(Lit::Num(..)) | Expr::Lit(Lit::Bool(..)) | Expr::Lit(Lit::Null(..)) @@ -1481,7 +1465,7 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { Expr::Lit(Lit::Str(ref v)) if drop_str_lit || v.value.is_empty() => None, - Expr::Paren(ParenExpr { expr, .. }) => ignore_result(*expr, true, ctx), + Expr::Paren(ParenExpr { expr, .. }) => ignore_result(expr, true, ctx), Expr::Assign(AssignExpr { op: op!("="), @@ -1505,16 +1489,12 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { op, right, }) if !op.may_short_circuit() => { - let left = ignore_result(*left, true, ctx); - let right = ignore_result(*right, true, ctx); + let left = ignore_result(left, true, ctx); + let right = ignore_result(right, true, ctx); match (left, right) { (Some(l), Some(r)) => ignore_result( - ctx.preserve_effects( - span, - *Expr::undefined(span), - vec![Box::new(l), Box::new(r)], - ), + ctx.preserve_effects(span, Expr::undefined(span), vec![l, r]), true, ctx, ), @@ -1531,27 +1511,30 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { right, }) => { if op == op!("&&") { - let right = if let Some(right) = ignore_result(*right, true, ctx) { - Box::new(right) + let right = if let Some(right) = ignore_result(right, true, ctx) { + right } else { - return ignore_result(*left, true, ctx); + return ignore_result(left, true, ctx); }; let l = left.as_pure_bool(ctx); if let Known(l) = l { if l { - Some(*right) + Some(right) } else { None } } else { - Some(Expr::Bin(BinExpr { - span, - left, - op, - right, - })) + Some( + BinExpr { + span, + left, + op, + right, + } + .into(), + ) } } else { debug_assert!(op == op!("||") || op == op!("??")); @@ -1562,19 +1545,22 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { if l { None } else { - ignore_result(*right, true, ctx) + ignore_result(right, true, ctx) } } else { - let right = ignore_result(*right, true, ctx); + let right = ignore_result(right, true, ctx); if let Some(right) = right { - Some(Expr::Bin(BinExpr { - span, - left, - op, - right: Box::new(right), - })) + Some( + BinExpr { + span, + left, + op, + right, + } + .into(), + ) } else { - ignore_result(*left, true, ctx) + ignore_result(left, true, ctx) } } } @@ -1591,13 +1577,13 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { _ => false, } => { - Some(Expr::Unary(UnaryExpr { span, op, arg })) + Some(UnaryExpr { span, op, arg }.into()) } op!("void") | op!(unary, "+") | op!(unary, "-") | op!("!") | op!("~") => { - ignore_result(*arg, true, ctx) + ignore_result(arg, true, ctx) } - _ => Some(Expr::Unary(UnaryExpr { span, op, arg })), + _ => Some(UnaryExpr { span, op, arg }.into()), }, Expr::Array(ArrayLit { span, elems, .. }) => { @@ -1610,25 +1596,19 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { Some(v) } None => None, - Some(ExprOrSpread { spread: None, expr }) => { - ignore_result(*expr, true, ctx).map(|expr| { - Some(ExprOrSpread { - spread: None, - expr: Box::new(expr), - }) - }) - } + Some(ExprOrSpread { spread: None, expr }) => ignore_result(expr, true, ctx) + .map(|expr| Some(ExprOrSpread { spread: None, expr })), }); if elems.is_empty() { None } else if has_spread { - Some(Expr::Array(ArrayLit { span, elems })) + Some(ArrayLit { span, elems }.into()) } else { ignore_result( ctx.preserve_effects( span, - *Expr::undefined(span), + Expr::undefined(span), elems.into_iter().map(|v| v.unwrap().expr), ), true, @@ -1655,8 +1635,8 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { ignore_result( ctx.preserve_effects( span, - *Expr::undefined(DUMMY_SP), - once(Box::new(Expr::Object(ObjectLit { span, props }))), + Expr::undefined(DUMMY_SP), + once(ObjectLit { span, props }.into()), ), true, ctx, @@ -1670,12 +1650,13 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { args, .. }) if callee.is_pure_callee(ctx) => ignore_result( - Expr::Array(ArrayLit { + ArrayLit { span, elems: args .map(|args| args.into_iter().map(Some).collect()) .unwrap_or_else(Default::default), - }), + } + .into(), true, ctx, ), @@ -1686,23 +1667,24 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { args, .. }) if callee.is_pure_callee(ctx) => ignore_result( - Expr::Array(ArrayLit { + ArrayLit { span, elems: args.into_iter().map(Some).collect(), - }), + } + .into(), true, ctx, ), Expr::Tpl(Tpl { span, exprs, .. }) => ignore_result( - ctx.preserve_effects(span, *Expr::undefined(span), exprs), + ctx.preserve_effects(span, Expr::undefined(span), exprs), true, ctx, ), Expr::TaggedTpl(TaggedTpl { span, tag, tpl, .. }) if tag.is_pure_callee(ctx) => { ignore_result( - ctx.preserve_effects(span, *Expr::undefined(span), tpl.exprs), + ctx.preserve_effects(span, Expr::undefined(span), tpl.exprs), true, ctx, ) @@ -1723,7 +1705,7 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { return None; } - let last = ignore_result(*exprs.pop().unwrap(), true, ctx).map(Box::new); + let last = ignore_result(exprs.pop().unwrap(), true, ctx); exprs.extend(last); @@ -1732,10 +1714,10 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { } if exprs.len() == 1 { - return Some(*exprs.pop().unwrap()); + return Some(exprs.pop().unwrap()); } - Some(Expr::Seq(SeqExpr { span, exprs })) + Some(SeqExpr { span, exprs }.into()) } Expr::Cond(CondExpr { @@ -1744,42 +1726,47 @@ fn ignore_result(e: Expr, drop_str_lit: bool, ctx: &ExprCtx) -> Option { cons, alt, }) => { - let alt = if let Some(alt) = ignore_result(*alt, true, ctx) { + let alt = if let Some(alt) = ignore_result(alt, true, ctx) { alt } else { return ignore_result( - Expr::Bin(BinExpr { + BinExpr { span, left: test, op: op!("&&"), right: cons, - }), + } + .into(), true, ctx, ); }; - let cons = if let Some(cons) = ignore_result(*cons, true, ctx) { + let cons = if let Some(cons) = ignore_result(cons, true, ctx) { cons } else { return ignore_result( - Expr::Bin(BinExpr { + BinExpr { span, left: test, op: op!("||"), - right: Box::new(alt), - }), + right: alt, + } + .into(), true, ctx, ); }; - Some(Expr::Cond(CondExpr { - span, - test, - cons: Box::new(cons), - alt: Box::new(alt), - })) + Some( + CondExpr { + span, + test, + cons, + alt, + } + .into(), + ) } _ => Some(e), diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/const_propagation.rs b/crates/swc_ecma_transforms_optimization/src/simplify/const_propagation.rs index 66d6722bfdf..aff4d4200df 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/const_propagation.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/const_propagation.rs @@ -132,9 +132,7 @@ impl VisitMut for ConstPropagation<'_> { if let Some(value) = self.scope.vars.get(&init.to_id()).cloned() { self.scope.vars.insert(name.to_id(), value); } else { - self.scope - .vars - .insert(name.to_id(), Box::new(Expr::Ident(init.clone()))); + self.scope.vars.insert(name.to_id(), init.clone().into()); } } _ => {} diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs index c20083d5917..b20047df382 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs @@ -178,11 +178,12 @@ impl SimplifyExpr { KnownOp::Len => { self.changed = true; - *expr = Expr::Lit(Lit::Num(Number { + *expr = Lit::Num(Number { value: value.chars().map(|c| c.len_utf16()).sum::() as _, span: *span, raw: None, - })); + }) + .into(); } // 'foo'[1] @@ -199,11 +200,12 @@ impl SimplifyExpr { self.changed = true; - *expr = Expr::Lit(Lit::Str(Str { + *expr = Lit::Str(Str { raw: None, value: value.into(), span: *span, - })) + }) + .into() } // 'foo'[''] @@ -242,11 +244,12 @@ impl SimplifyExpr { // Prototype changes do not affect .length self.changed = true; - *expr = Expr::Lit(Lit::Num(Number { + *expr = Lit::Num(Number { value: elems.len() as _, span: *span, raw: None, - })); + }) + .into(); } KnownOp::Index(idx) => { @@ -311,16 +314,17 @@ impl SimplifyExpr { if exprs.is_empty() { // No side effects exist, replace with: // (0, val) - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: val.span(), exprs: vec![0.into(), val], - }); + } + .into(); return; } // Add value and replace with SeqExpr exprs.push(val); - *expr = Expr::Seq(SeqExpr { span: *span, exprs }); + *expr = SeqExpr { span: *span, exprs }.into(); } // Handled in compress @@ -347,13 +351,16 @@ impl SimplifyExpr { self.changed = true; - *expr = self.expr_ctx.preserve_effects( + *expr = *self.expr_ctx.preserve_effects( *span, v, - once(Box::new(Expr::Object(ObjectLit { - props: props.take(), - span: *span, - }))), + once( + ObjectLit { + props: props.take(), + span: *span, + } + .into(), + ), ); } @@ -379,7 +386,7 @@ impl SimplifyExpr { // TODO: Optimize self.changed = true; - *expr = make_bool_expr(&self.expr_ctx, *span, v, { + *expr = *make_bool_expr(&self.expr_ctx, *span, v, { iter::once(left.take()).chain(iter::once(right.take())) }); return; @@ -406,7 +413,7 @@ impl SimplifyExpr { )) }; - *expr = self.expr_ctx.preserve_effects(*span, value_expr, { + *expr = *self.expr_ctx.preserve_effects(*span, value_expr.into(), { iter::once(left.take()).chain(iter::once(right.take())) }); return; @@ -430,11 +437,12 @@ impl SimplifyExpr { self.changed = true; - *expr = Expr::Lit(Lit::Str(Str { + *expr = Lit::Str(Str { raw: None, value: l.into(), span: *span, - })); + }) + .into(); return; } } @@ -456,11 +464,12 @@ impl SimplifyExpr { let value = format!("{}{}", l, r); - *expr = Expr::Lit(Lit::Str(Str { + *expr = Lit::Str(Str { raw: None, value: value.into(), span: *span, - })); + }) + .into(); } } } @@ -480,20 +489,22 @@ impl SimplifyExpr { let span = *span; let value_expr = if !v.is_nan() { - Expr::Lit(Lit::Num(Number { + Lit::Num(Number { value: v, span, raw: None, - })) + }) + .into() } else { - Expr::Ident(Ident::new( + Ident::new( "NaN".into(), span, self.expr_ctx.unresolved_ctxt, - )) + ) + .into() }; - *expr = self.expr_ctx.preserve_effects( + *expr = *self.expr_ctx.preserve_effects( span, value_expr, iter::once(left.take()).chain(iter::once(right.take())), @@ -537,10 +548,11 @@ impl SimplifyExpr { self.changed = true; if node.directness_maters() { - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: node.span(), exprs: vec![0.into(), node.take()], - }); + } + .into(); } else { *expr = *node.take(); } @@ -554,7 +566,7 @@ impl SimplifyExpr { seq.visit_mut_with(self); - *expr = Expr::Seq(seq) + *expr = seq.into() }; } } @@ -603,14 +615,14 @@ impl SimplifyExpr { if is_non_obj(left) { self.changed = true; - *expr = make_bool_expr(&self.expr_ctx, *span, false, iter::once(right.take())); + *expr = *make_bool_expr(&self.expr_ctx, *span, false, iter::once(right.take())); return; } if is_obj(left) && right.is_global_ref_to(&self.expr_ctx, "Object") { self.changed = true; - *expr = make_bool_expr(&self.expr_ctx, *span, true, iter::once(left.take())); + *expr = *make_bool_expr(&self.expr_ctx, *span, true, iter::once(left.take())); } } @@ -698,17 +710,15 @@ impl SimplifyExpr { if *left_op == *op { if let Known(value) = self.perform_arithmetic_op(*op, left_rhs, right) { let value_expr = if !value.is_nan() { - Expr::Lit(Lit::Num(Number { + Lit::Num(Number { value, span: *span, raw: None, - })) + }) + .into() } else { - Expr::Ident(Ident::new( - "NaN".into(), - *span, - self.expr_ctx.unresolved_ctxt, - )) + Ident::new("NaN".into(), *span, self.expr_ctx.unresolved_ctxt) + .into() }; self.changed = true; @@ -776,11 +786,12 @@ impl SimplifyExpr { self.changed = true; - *expr = Expr::Lit(Lit::Str(Str { + *expr = Lit::Str(Str { span: *span, raw: None, value: val.into(), - })); + }) + .into(); } fn optimize_unary_expr(&mut self, expr: &mut Expr) { @@ -813,7 +824,7 @@ impl SimplifyExpr { if let (_, Known(val)) = arg.cast_to_bool(&self.expr_ctx) { self.changed = true; - *expr = make_bool_expr(&self.expr_ctx, *span, !val, iter::once(arg.take())); + *expr = *make_bool_expr(&self.expr_ctx, *span, !val, iter::once(arg.take())); } } op!(unary, "+") => { @@ -821,25 +832,22 @@ impl SimplifyExpr { self.changed = true; if v.is_nan() { - *expr = self.expr_ctx.preserve_effects( + *expr = *self.expr_ctx.preserve_effects( *span, - Expr::Ident(Ident::new( - "NaN".into(), - *span, - self.expr_ctx.unresolved_ctxt, - )), + Ident::new("NaN".into(), *span, self.expr_ctx.unresolved_ctxt).into(), iter::once(arg.take()), ); return; } - *expr = self.expr_ctx.preserve_effects( + *expr = *self.expr_ctx.preserve_effects( *span, - Expr::Lit(Lit::Num(Number { + Lit::Num(Number { value: v, span: *span, raw: None, - })), + }) + .into(), iter::once(arg.take()), ); } @@ -853,11 +861,12 @@ impl SimplifyExpr { } Expr::Lit(Lit::Num(Number { value: f, .. })) => { self.changed = true; - *expr = Expr::Lit(Lit::Num(Number { + *expr = Lit::Num(Number { value: -f, span: *span, raw: None, - })); + }) + .into(); } _ => { @@ -872,18 +881,19 @@ impl SimplifyExpr { } self.changed = true; - *arg = Box::new(Expr::Lit(Lit::Num(Number { + *arg = Lit::Num(Number { value: 0.0, span: arg.span(), raw: None, - }))); + }) + .into(); } op!("~") => { if let Known(value) = arg.as_pure_number(&self.expr_ctx) { if value.fract() == 0.0 { self.changed = true; - *expr = Expr::Lit(Lit::Num(Number { + *expr = Lit::Num(Number { span: *span, value: if value < 0.0 { !(value as i32 as u32) as i32 as f64 @@ -891,7 +901,8 @@ impl SimplifyExpr { !(value as u32) as i32 as f64 }, raw: None, - })); + }) + .into(); } // TODO: Report error } @@ -1133,11 +1144,12 @@ impl SimplifyExpr { self.perform_abstract_eq_cmp( span, left, - &Expr::Lit(Lit::Num(Number { + &Lit::Num(Number { value: rv, span, raw: None, - })), + }) + .into(), ) } @@ -1145,11 +1157,12 @@ impl SimplifyExpr { let lv = try_val!(left.as_pure_number(&self.expr_ctx)); self.perform_abstract_eq_cmp( span, - &Expr::Lit(Lit::Num(Number { + &Lit::Num(Number { value: lv, span, raw: None, - })), + }) + .into(), right, ) } @@ -1292,7 +1305,7 @@ impl VisitMut for SimplifyExpr { span: DUMMY_SP, exprs: vec![0.0.into(), e.take()], }; - **e = Expr::Seq(seq); + **e = seq.into(); } } } @@ -1362,18 +1375,20 @@ impl VisitMut for SimplifyExpr { let expr_value = if val { cons } else { alt }; *expr = if p.is_pure() { if expr_value.directness_maters() { - Expr::Seq(SeqExpr { + SeqExpr { span: *span, exprs: vec![0.into(), expr_value.take()], - }) + } + .into() } else { *expr_value.take() } } else { - Expr::Seq(SeqExpr { + SeqExpr { span: *span, exprs: vec![test.take(), expr_value.take()], - }) + } + .into() } } } @@ -1692,11 +1707,11 @@ impl VisitMut for SimplifyExpr { } /// make a new boolean expression preserving side effects, if any. -fn make_bool_expr(ctx: &ExprCtx, span: Span, value: bool, orig: I) -> Expr +fn make_bool_expr(ctx: &ExprCtx, span: Span, value: bool, orig: I) -> Box where I: IntoIterator>, { - ctx.preserve_effects(span, Expr::Lit(Lit::Bool(Bool { value, span })), orig) + ctx.preserve_effects(span, Lit::Bool(Bool { value, span }).into(), orig) } fn nth_char(s: &str, mut idx: usize) -> Option> { @@ -1741,7 +1756,7 @@ fn need_zero_for_this(e: &Expr) -> bool { /// Gets the value of the given key from the given object properties, if the key /// exists. If the key does exist, `Some` is returned and the property is /// removed from the given properties. -fn get_key_value(key: &str, props: &mut Vec) -> Option { +fn get_key_value(key: &str, props: &mut Vec) -> Option> { // It's impossible to know the value for certain if a spread property exists. let has_spread = props.iter().any(|prop| prop.is_spread()); @@ -1765,7 +1780,7 @@ fn get_key_value(key: &str, props: &mut Vec) -> Option { Prop::Shorthand(x) => x, _ => unreachable!(), }; - return Some(Expr::Ident(ident)); + return Some(ident.into()); } Prop::KeyValue(prop) => { @@ -1794,7 +1809,7 @@ fn get_key_value(key: &str, props: &mut Vec) -> Option { Prop::KeyValue(x) => x, _ => unreachable!(), }; - return Some(*prop.value); + return Some(prop.value); } } diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs index 6d70aa872b3..499d5178b6b 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs @@ -504,7 +504,7 @@ impl VisitMut for Inlining<'_> { PatFoldingMode::Param => { self.declare( i.to_id(), - Some(Cow::Owned(Expr::Ident(Ident::from(i)))), + Some(Cow::Owned(Ident::from(i).into())), false, VarType::Param, ); @@ -512,7 +512,7 @@ impl VisitMut for Inlining<'_> { PatFoldingMode::CatchParam => { self.declare( i.to_id(), - Some(Cow::Owned(Expr::Ident(Ident::from(i)))), + Some(Cow::Owned(Ident::from(i).into())), false, VarType::Var(VarDeclKind::Var), ); @@ -649,9 +649,7 @@ impl VisitMut for Inlining<'_> { tracing::trace!("Trying to optimize variable declaration: {:?}", id); - if self - .scope - .is_inline_prevented(&Expr::Ident(Ident::from(name))) + if self.scope.is_inline_prevented(&Ident::from(name).into()) || !self.scope.has_same_this(&id, node.init.as_deref()) { tracing::trace!("Inline is prevented for {:?}", id); @@ -666,7 +664,7 @@ impl VisitMut for Inlining<'_> { if let Expr::Ident(ri) = &**init { self.declare( name.to_id(), - Some(Cow::Owned(Expr::Ident(ri.clone()))), + Some(Cow::Owned(ri.clone().into())), false, kind, ); @@ -690,10 +688,7 @@ impl VisitMut for Inlining<'_> { Some(e) if e.is_lit() || e.is_ident() => Some(e), Some(e) => { let e = *e; - if self - .scope - .is_inline_prevented(&Expr::Ident(Ident::from(name))) - { + if self.scope.is_inline_prevented(&Ident::from(name).into()) { node.init = Some(Box::new(e)); return; } 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 385bc582ab4..7c4ee7aef27 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs @@ -76,16 +76,19 @@ impl Decorator2022_03 { let ident = private_ident!("_dec"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(ident.clone().into()), + name: ident.clone().into(), init: None, definite: false, }); - self.pre_class_inits.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: ident.clone().into(), - right: dec, - }))); + self.pre_class_inits.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: ident.clone().into(), + right: dec, + } + .into(), + ); ident.into() } @@ -116,7 +119,7 @@ impl Decorator2022_03 { if let Some(init) = self.state.init_proto.clone() { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(init.clone().into()), + name: init.clone().into(), init: None, definite: false, }); @@ -127,7 +130,7 @@ impl Decorator2022_03 { if let Some(init) = self.state.init_static.clone() { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(init.clone().into()), + name: init.clone().into(), init: None, definite: false, }); @@ -165,12 +168,13 @@ impl Decorator2022_03 { } else { Some(ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident("e".into()), - value: Box::new(Pat::Array(ArrayPat { + value: ArrayPat { span: DUMMY_SP, elems: e_lhs, type_ann: Default::default(), optional: false, - })), + } + .into(), })) }; @@ -179,16 +183,17 @@ impl Decorator2022_03 { } else { Some(ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident("c".into()), - value: Box::new(Pat::Array(ArrayPat { + value: ArrayPat { span: DUMMY_SP, elems: self.state.class_lhs.take(), type_ann: Default::default(), optional: false, - })), + } + .into(), })) }; - let expr = Box::new(Expr::Assign(AssignExpr { + let expr = AssignExpr { span: DUMMY_SP, op: op!("="), left: ObjectPat { @@ -198,13 +203,17 @@ impl Decorator2022_03 { type_ann: None, } .into(), - right: Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: helper!(apply_decs_2203_r), - args: combined_args, - ..Default::default() - })), - })); + right: Box::new( + CallExpr { + span: DUMMY_SP, + callee: helper!(apply_decs_2203_r), + args: combined_args, + ..Default::default() + } + .into(), + ), + } + .into(); self.state.extra_stmts.push(Stmt::Expr(ExprStmt { span: DUMMY_SP, @@ -214,12 +223,13 @@ impl Decorator2022_03 { if let Some(init) = self.state.init_static.take() { self.state.extra_stmts.push(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span: DUMMY_SP, callee: init.as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() - })), + } + .into(), })); } } @@ -228,11 +238,12 @@ impl Decorator2022_03 { fn initializer_name(&mut self, name: &mut PropName, prefix: &str) -> (Box, Ident) { match name { PropName::Ident(i) => ( - Box::new(Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: i.span, value: i.sym.clone(), raw: None, - }))), + }) + .into(), Ident::new( format!("_{prefix}_{}", i.sym).into(), i.span, @@ -241,7 +252,7 @@ impl Decorator2022_03 { ), PropName::Computed(c) if c.expr.is_ident() => match &*c.expr { Expr::Ident(i) => ( - Box::new(Expr::Ident(i.clone())), + i.clone().into(), Ident::new( format!("_{prefix}_{}", i.sym).into(), i.span, @@ -256,17 +267,20 @@ impl Decorator2022_03 { let key_ident = private_ident!("_computedKey"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(key_ident.clone().into()), + name: key_ident.clone().into(), init: None, definite: false, }); - self.pre_class_inits.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: key_ident.clone().into(), - right: Box::new(prop_name_to_expr_value(name.take())), - }))); + self.pre_class_inits.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: key_ident.clone().into(), + right: Box::new(prop_name_to_expr_value(name.take())), + } + .into(), + ); *name = PropName::Computed(ComputedPropName { span: DUMMY_SP, expr: key_ident.clone().into(), @@ -278,7 +292,7 @@ impl Decorator2022_03 { SyntaxContext::empty().apply_mark(Mark::new()), ); - (Box::new(Expr::Ident(key_ident)), init) + (key_ident.into(), init) } } } @@ -356,17 +370,20 @@ impl Decorator2022_03 { let id = alias_ident_for(&super_class, "_super"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(id.clone().into()), + name: id.clone().into(), init: None, definite: false, }); - class.super_class = Some(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: AssignOp::Assign, - left: id.clone().into(), - right: super_class, - }))); + class.super_class = Some( + AssignExpr { + span: DUMMY_SP, + op: AssignOp::Assign, + left: id.clone().into(), + right: super_class, + } + .into(), + ); self.state.super_class = Some(id); } @@ -382,7 +399,7 @@ impl Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(init_class.clone().into()), + name: init_class.clone().into(), init: None, definite: false, }); @@ -403,7 +420,7 @@ impl Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(new_class_name.clone().into()), + name: new_class_name.clone().into(), init: None, definite: false, }); @@ -444,7 +461,7 @@ impl Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(init_class.clone().into()), + name: init_class.clone().into(), init: None, definite: false, }); @@ -454,7 +471,7 @@ impl Decorator2022_03 { self.extra_lets.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(new_class_name.clone().into()), + name: new_class_name.clone().into(), init: None, definite: false, }); @@ -494,7 +511,7 @@ impl Decorator2022_03 { | ClassMember::PrivateProp(PrivateProp { value, .. }) => { if let Some(value) = value { if let Some(last_static_block) = last_static_block.take() { - **value = Expr::Seq(SeqExpr { + **value = SeqExpr { span: DUMMY_SP, exprs: vec![ Box::new(Expr::Call(CallExpr { @@ -519,7 +536,8 @@ impl Decorator2022_03 { })), value.take(), ], - }) + } + .into() } } } @@ -725,17 +743,20 @@ impl Decorator2022_03 { let ident = private_ident!("_computedKey"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(ident.clone().into()), + name: ident.clone().into(), init: None, definite: false, }); - self.pre_class_inits.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: ident.clone().into(), - right: Box::new(prop_name_to_expr_value(name.take())), - }))); + self.pre_class_inits.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: ident.clone().into(), + right: Box::new(prop_name_to_expr_value(name.take())), + } + .into(), + ); *name = PropName::Computed(ComputedPropName { span: DUMMY_SP, expr: ident.into(), @@ -832,7 +853,7 @@ impl VisitMut for Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: p.span, - name: Pat::Ident(init.clone().into()), + name: init.clone().into(), init: None, definite: false, }); @@ -895,7 +916,7 @@ impl VisitMut for Decorator2022_03 { MethodKind::Method => { let call_stmt = Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Ident(init))), + arg: Some(init.into()), }); p.kind = MethodKind::Getter; @@ -908,12 +929,15 @@ impl VisitMut for Decorator2022_03 { MethodKind::Getter => { let call_stmt = Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: init.as_callee(), - args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], - ..Default::default() - }))), + arg: Some( + CallExpr { + span: DUMMY_SP, + callee: init.as_callee(), + args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], + ..Default::default() + } + .into(), + ), }); p.function.body = Some(BlockStmt { @@ -925,15 +949,19 @@ impl VisitMut for Decorator2022_03 { MethodKind::Setter => { let call_stmt = Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: init.as_callee(), - args: vec![ - ThisExpr { span: DUMMY_SP }.as_arg(), - Ident::from(p.function.params[0].pat.as_ident().unwrap()).as_arg(), - ], - ..Default::default() - }))), + arg: Some( + CallExpr { + span: DUMMY_SP, + callee: init.as_callee(), + args: vec![ + ThisExpr { span: DUMMY_SP }.as_arg(), + Ident::from(p.function.params[0].pat.as_ident().unwrap()) + .as_arg(), + ], + ..Default::default() + } + .into(), + ), }); p.function.body = Some(BlockStmt { @@ -963,11 +991,12 @@ impl VisitMut for Decorator2022_03 { span: DUMMY_SP, key: match &mut accessor.key { Key::Private(k) => { - name = Box::new(Expr::Lit(Lit::Str(Str { + name = Lit::Str(Str { span: DUMMY_SP, value: k.name.clone(), raw: None, - }))); + }) + .into(); init = private_ident!(format!("_init_{}", k.name)); field_name_like = format!("__{}", k.name).into(); @@ -1011,22 +1040,26 @@ impl VisitMut for Decorator2022_03 { .get_or_insert_with(|| private_ident!("_initProto")) .clone(); - Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: init_proto.clone().as_callee(), - args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], - ..Default::default() - }))) + Some( + CallExpr { + span: DUMMY_SP, + callee: init_proto.clone().as_callee(), + args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], + ..Default::default() + } + .into(), + ) }; - let init_call = Box::new(Expr::Call(CallExpr { + let init_call = CallExpr { span: DUMMY_SP, callee: init.clone().as_callee(), args: once(ThisExpr { span: DUMMY_SP }.as_arg()) .chain(accessor.value.take().map(|v| v.as_arg())) .collect(), ..Default::default() - })); + } + .into(); Some(Expr::from_exprs( init_proto.into_iter().chain(once(init_call)).collect(), @@ -1107,7 +1140,7 @@ impl VisitMut for Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: accessor.span, - name: Pat::Ident(init.clone().into()), + name: init.clone().into(), init: None, definite: false, }); @@ -1151,13 +1184,13 @@ impl VisitMut for Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(getter_var.clone().unwrap().into()), + name: getter_var.clone().unwrap().into(), init: None, definite: false, }); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(setter_var.clone().unwrap().into()), + name: setter_var.clone().unwrap().into(), init: None, definite: false, }); @@ -1429,20 +1462,23 @@ impl VisitMut for Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: p.span, - name: Pat::Ident(init.clone().into()), + name: init.clone().into(), init: None, definite: false, }); - p.value = Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: init.clone().as_callee(), - args: once(ThisExpr { span: DUMMY_SP }.as_arg()) - .chain(p.value.take().map(|v| v.as_arg())) - .collect(), + p.value = Some( + CallExpr { + span: DUMMY_SP, + callee: init.clone().as_callee(), + args: once(ThisExpr { span: DUMMY_SP }.as_arg()) + .chain(p.value.take().map(|v| v.as_arg())) + .collect(), - ..Default::default() - }))); + ..Default::default() + } + .into(), + ); let initialize_init = { Some( @@ -1474,10 +1510,11 @@ impl VisitMut for Decorator2022_03 { c.visit_mut_with(self); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: DUMMY_SP, exprs: vec![Box::new(e.take()), Box::new(Expr::Ident(new))], - }); + } + .into(); return; } @@ -1628,24 +1665,27 @@ impl VisitMut for Decorator2022_03 { self.extra_vars.push(VarDeclarator { span: p.span, - name: Pat::Ident(init.clone().into()), + name: init.clone().into(), init: None, definite: false, }); - p.value = Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: init.clone().as_callee(), - args: once(ThisExpr { span: DUMMY_SP }.as_arg()) - .chain(p.value.take().map(|v| v.as_arg())) - .collect(), - ..Default::default() - }))); + p.value = Some( + CallExpr { + span: DUMMY_SP, + callee: init.clone().as_callee(), + args: once(ThisExpr { span: DUMMY_SP }.as_arg()) + .chain(p.value.take().map(|v| v.as_arg())) + .collect(), + ..Default::default() + } + .into(), + ); let initialize_init = { let access_expr = MemberExpr { span: DUMMY_SP, - obj: Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), + obj: ThisExpr { span: DUMMY_SP }.into(), prop: MemberProp::PrivateName(p.key.clone()), }; diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs index d13d66e776f..b0b1c9fdc46 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs @@ -69,12 +69,13 @@ impl ParamMetadata { Decorator { span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_param), args: vec![param_index.as_arg(), decorator_expr.as_arg()], ..Default::default() - })), + } + .into(), } } } @@ -266,12 +267,13 @@ impl<'a> Metadata<'a> { fn create_metadata_design_decorator(&self, design: &str, type_arg: ExprOrSpread) -> Decorator { Decorator { span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_metadata), args: vec![design.as_arg(), type_arg], ..Default::default() - })), + } + .into(), } } } @@ -281,40 +283,51 @@ fn serialize_type(class_name: Option<&Ident>, param: Option<&TsTypeAnn>) -> Expr match *expr { Expr::Member(ref member_expr) => { let obj_expr = member_expr.obj.clone(); - Box::new(Expr::Bin(BinExpr { + BinExpr { span: DUMMY_SP, left: check_object_existed(obj_expr), op: op!("||"), - right: Box::new(Expr::Bin(BinExpr { - span: DUMMY_SP, - left: Box::new(Expr::Unary(UnaryExpr { + right: Box::new( + BinExpr { span: DUMMY_SP, - op: op!("typeof"), - arg: expr, - })), - op: op!("==="), - right: Box::new(Expr::Lit(Lit::Str(Str { - span: DUMMY_SP, - value: "undefined".into(), - raw: None, - }))), - })), - })) + left: Box::new(Expr::Unary(UnaryExpr { + span: DUMMY_SP, + op: op!("typeof"), + arg: expr, + })), + op: op!("==="), + right: Box::new(Expr::Lit(Lit::Str(Str { + span: DUMMY_SP, + value: "undefined".into(), + raw: None, + }))), + } + .into(), + ), + } + .into() } - _ => Box::new(Expr::Bin(BinExpr { + _ => BinExpr { span: DUMMY_SP, - left: Box::new(Expr::Unary(UnaryExpr { - span: DUMMY_SP, - op: op!("typeof"), - arg: expr, - })), + left: Box::new( + UnaryExpr { + span: DUMMY_SP, + op: op!("typeof"), + arg: expr, + } + .into(), + ), op: op!("==="), - right: Box::new(Expr::Lit(Lit::Str(Str { - span: DUMMY_SP, - value: "undefined".into(), - raw: None, - }))), - })), + right: Box::new( + Lit::Str(Str { + span: DUMMY_SP, + value: "undefined".into(), + raw: None, + }) + .into(), + ), + } + .into(), } } @@ -336,12 +349,13 @@ fn serialize_type(class_name: Option<&Ident>, param: Option<&TsTypeAnn>) -> Expr // `typeof` operator allows us to use the expression even if it is not defined, // fallback is just `Object`. - Expr::Cond(CondExpr { + CondExpr { span: DUMMY_SP, test: check_object_existed(Box::new(member_expr.clone())), cons: Box::new(quote_ident!("Object").into()), alt: Box::new(member_expr), - }) + } + .into() } fn serialize_type_list(class_name: &str, types: &[Box]) -> Expr { @@ -469,12 +483,13 @@ fn serialize_type(class_name: Option<&Ident>, param: Option<&TsTypeAnn>) -> Expr TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsBigIntKeyword, .. - }) => Expr::Cond(CondExpr { + }) => CondExpr { span: DUMMY_SP, test: check_object_existed(quote_ident!("BigInt").into()), cons: quote_ident!("Object").into(), alt: quote_ident!("BigInt").into(), - }), + } + .into(), TsType::TsLitType(ty) => { // TODO: Proper error reporting @@ -533,13 +548,14 @@ fn ts_entity_to_member_expr(type_name: &TsEntityName) -> Expr { TsEntityName::TsQualifiedName(q) => { let obj = ts_entity_to_member_expr(&q.left); - Expr::Member(MemberExpr { + MemberExpr { span: DUMMY_SP, obj: obj.into(), prop: MemberProp::Ident(q.right.clone()), - }) + } + .into() } - TsEntityName::Ident(i) => Expr::Ident(i.clone().with_pos(BytePos::DUMMY, BytePos::DUMMY)), + TsEntityName::Ident(i) => i.clone().with_pos(BytePos::DUMMY, BytePos::DUMMY).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 1e145189564..b5b434cc3f5 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs @@ -119,29 +119,33 @@ impl TscDecorator { // Declare var self.vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(var_name.clone().into()), + name: var_name.clone().into(), init: None, definite: Default::default(), }); // Initialize var - self.prepended_exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: var_name.clone().into(), - right: k.expr.take(), - }))); + self.prepended_exprs.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: var_name.clone().into(), + right: k.expr.take(), + } + .into(), + ); - k.expr = Box::new(Expr::Ident(var_name.clone())); + k.expr = var_name.clone().into(); - return Expr::Ident(var_name); + return var_name.into(); } PropName::Ident(i) => { - return Expr::Lit(Lit::Str(Str { + return Lit::Str(Str { span: DUMMY_SP, raw: None, value: i.sym.clone(), - })) + }) + .into() } _ => {} } @@ -174,12 +178,15 @@ impl TscDecorator { remove_span(&mut target.expr); remove_span(&mut desc.expr); - self.appended_exprs.push(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: helper!(ts, ts_decorate), - args: vec![decorators, target, key, desc], - ..Default::default() - }))); + self.appended_exprs.push( + CallExpr { + span: DUMMY_SP, + callee: helper!(ts, ts_decorate), + args: vec![decorators, target, key, desc], + ..Default::default() + } + .into(), + ); } } @@ -254,7 +261,7 @@ impl VisitMut for TscDecorator { } .as_arg(); - let decorated = Box::new(Expr::Call(CallExpr { + let decorated = CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_decorate), args: vec![ @@ -265,13 +272,17 @@ impl VisitMut for TscDecorator { .as_arg(), ], ..Default::default() - })); - self.appended_exprs.push(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - op: op!("="), - left: class_name.with_pos(BytePos::DUMMY, BytePos::DUMMY).into(), - right: decorated, - }))); + } + .into(); + self.appended_exprs.push( + AssignExpr { + span: DUMMY_SP, + op: op!("="), + left: class_name.with_pos(BytePos::DUMMY, BytePos::DUMMY).into(), + right: decorated, + } + .into(), + ); } } } @@ -292,12 +303,12 @@ impl VisitMut for TscDecorator { if let Some(var_name) = self.assign_class_expr_to.take() { self.vars.push(VarDeclarator { span: DUMMY_SP, - name: Pat::Ident(var_name.clone().into()), + name: var_name.clone().into(), init: None, definite: Default::default(), }); - *e = Expr::Seq(SeqExpr { + *e = SeqExpr { span: DUMMY_SP, exprs: iter::once(AssignExpr { span: DUMMY_SP, @@ -309,7 +320,8 @@ impl VisitMut for TscDecorator { .chain(appended_exprs) .chain(iter::once(var_name.into())) .collect(), - }); + } + .into(); } } diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs index 37f296eae80..840fc80cf4f 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs @@ -130,7 +130,7 @@ impl Fold for Decorators { match expr { Expr::Class(ClassExpr { ident, class }) => { if !contains_decorator(&class) { - return Expr::Class(ClassExpr { ident, class }); + return ClassExpr { ident, class }.into(); } self.fold_class_inner( @@ -284,15 +284,16 @@ impl Decorators { .as_ref() .map(|expr| alias_ident_for(expr, "_super")); let super_class_expr = class.super_class; - class.super_class = super_class_ident.clone().map(|i| Box::new(Expr::Ident(i))); + class.super_class = super_class_ident.clone().map(|i| i.into()); let constructor = { - let initialize_call = Box::new(Expr::Call(CallExpr { + let initialize_call = CallExpr { span: DUMMY_SP, callee: initialize.clone().as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() - })); + } + .into(); // Inject initialize let pos = class.body.iter().position(|member| { @@ -449,21 +450,23 @@ impl Decorators { format!("_{}", method.key.name).into(), method.key.span, ); - let key_prop_value = Box::new(Expr::Lit(Lit::Str(Str { + let key_prop_value = Lit::Str(Str { span: method.key.span, raw: None, value: method.key.name.clone(), - }))); + }) + .into(); fold_method!(method, Some(fn_name), key_prop_value) } ClassMember::ClassProp(prop) => { let prop_span = prop.span(); let key_prop_value = match prop.key { - PropName::Ident(i) => Box::new(Expr::Lit(Lit::Str(Str { + PropName::Ident(i) => Lit::Str(Str { span: i.span, raw: None, value: i.sym, - }))), + }) + .into(), _ => prop_name_to_expr(prop.key).into(), }; // @@ -473,7 +476,7 @@ impl Decorators { props: iter::once(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("kind")), - value: Box::new(Expr::Lit(Lit::Str(quote_str!("field")))), + value: Lit::Str(quote_str!("field")).into(), }, )))) .chain(if prop.is_static { @@ -494,7 +497,7 @@ impl Decorators { Some(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("decorators")), - value: Box::new(Expr::Array(ArrayLit { + value: ArrayLit { span: DUMMY_SP, elems: prop .decorators @@ -502,7 +505,8 @@ impl Decorators { .map(|dec| dec.expr.as_arg()) .map(Some) .collect(), - })), + } + .into(), }, )))) } @@ -553,14 +557,14 @@ impl Decorators { self.vars.extend(vars); - Expr::Call(make_decorate_call( + make_decorate_call( class.decorators, iter::once({ // function(_initialize) {} Function { span: DUMMY_SP, - params: iter::once(Pat::Ident(initialize.into())) + params: iter::once(initialize.into()) .chain(super_class_ident.map(Pat::from)) .map(|pat| Param { span: DUMMY_SP, @@ -594,22 +598,29 @@ impl Decorators { })))) .chain(iter::once(Stmt::Return(ReturnStmt { span: DUMMY_SP, - arg: Some(Box::new(Expr::Object(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, - })), - }))), - ], - }))), + 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(), + ), }))) .collect(), ..Default::default() @@ -619,7 +630,8 @@ impl Decorators { .as_arg() }) .chain(super_class_expr.map(|e| e.as_arg())), - )) + ) + .into() } } 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 c6c0fd1b511..84d99915dde 100644 --- a/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs +++ b/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs @@ -338,12 +338,13 @@ impl ExplicitResourceManagement { ..Default::default() }; let dispose_stmt = if state.has_await { - Expr::Await(AwaitExpr { + AwaitExpr { span: DUMMY_SP, arg: Box::new(dispose_expr.into()), - }) + } + .into() } else { - dispose_expr.into() + Expr::from(dispose_expr) } .into_stmt(); diff --git a/crates/swc_ecma_transforms_react/src/display_name/mod.rs b/crates/swc_ecma_transforms_react/src/display_name/mod.rs index 0edd08f0f19..867b05d0eb5 100644 --- a/crates/swc_ecma_transforms_react/src/display_name/mod.rs +++ b/crates/swc_ecma_transforms_react/src/display_name/mod.rs @@ -38,21 +38,27 @@ impl VisitMut for DisplayName { ) = &expr.left { return expr.right.visit_mut_with(&mut Folder { - name: Some(Box::new(Expr::Lit(Lit::Str(Str { - span: prop.span, - raw: None, - value: prop.sym.clone(), - })))), + name: Some( + Lit::Str(Str { + span: prop.span, + raw: None, + value: prop.sym.clone(), + }) + .into(), + ), }); }; if let Some(ident) = expr.left.as_ident() { expr.right.visit_mut_with(&mut Folder { - name: Some(Box::new(Expr::Lit(Lit::Str(Str { - span: ident.span, - raw: None, - value: ident.sym.clone(), - })))), + name: Some( + Lit::Str(Str { + span: ident.span, + raw: None, + value: ident.sym.clone(), + }) + .into(), + ), }); } } @@ -62,11 +68,14 @@ impl VisitMut for DisplayName { if let ModuleDecl::ExportDefaultExpr(e) = decl { e.visit_mut_with(&mut Folder { - name: Some(Box::new(Expr::Lit(Lit::Str(Str { - span: DUMMY_SP, - raw: None, - value: "input".into(), - })))), + name: Some( + Lit::Str(Str { + span: DUMMY_SP, + raw: None, + value: "input".into(), + }) + .into(), + ), }); } } @@ -77,14 +86,15 @@ impl VisitMut for DisplayName { if let Prop::KeyValue(KeyValueProp { key, value }) = prop { value.visit_mut_with(&mut Folder { name: Some(match key { - PropName::Ident(ref i) => Box::new(Expr::Lit(Lit::Str(Str { + PropName::Ident(ref i) => Lit::Str(Str { span: i.span, raw: None, value: i.sym.clone(), - }))), - PropName::Str(ref s) => Box::new(Expr::Lit(Lit::Str(s.clone()))), - PropName::Num(ref n) => Box::new(Expr::Lit(Lit::Num(n.clone()))), - PropName::BigInt(ref b) => Box::new(Expr::Lit(Lit::BigInt(b.clone()))), + }) + .into(), + PropName::Str(ref s) => Lit::Str(s.clone()).into(), + PropName::Num(ref n) => Lit::Num(n.clone()).into(), + PropName::BigInt(ref b) => Lit::BigInt(b.clone()).into(), PropName::Computed(ref c) => c.expr.clone(), }), }); @@ -94,11 +104,14 @@ impl VisitMut for DisplayName { fn visit_mut_var_declarator(&mut self, decl: &mut VarDeclarator) { if let Pat::Ident(ref ident) = decl.name { decl.init.visit_mut_with(&mut Folder { - name: Some(Box::new(Expr::Lit(Lit::Str(Str { - span: ident.span, - value: ident.sym.clone(), - raw: None, - })))), + name: Some( + Lit::Str(Str { + span: ident.span, + value: ident.sym.clone(), + raw: None, + }) + .into(), + ), }); } } diff --git a/crates/swc_ecma_transforms_react/src/jsx/mod.rs b/crates/swc_ecma_transforms_react/src/jsx/mod.rs index 0cc64be33f0..d1577d49097 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/mod.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/mod.rs @@ -518,10 +518,11 @@ where .props .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("children")), - value: Box::new(Expr::Array(ArrayLit { + value: ArrayLit { span: DUMMY_SP, elems: children, - })), + } + .into(), })))); } } @@ -536,15 +537,16 @@ where args.collect() }; - Expr::Call(CallExpr { + CallExpr { span, callee: jsx.as_callee(), args, ..Default::default() - }) + } + .into() } Runtime::Classic => { - Expr::Call(CallExpr { + CallExpr { span, callee: (*self.pragma).clone().as_callee(), args: iter::once((*self.pragma_frag).clone().as_arg()) @@ -558,7 +560,8 @@ where }) .collect(), ..Default::default() - }) + } + .into() } } } @@ -782,10 +785,11 @@ where .props .push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("children")), - value: Box::new(Expr::Array(ArrayLit { + value: ArrayLit { span: DUMMY_SP, elems: children.take(), - })), + } + .into(), })))); } } @@ -821,15 +825,16 @@ where } else { args.chain(key).collect() }; - Expr::Call(CallExpr { + CallExpr { span, callee: jsx.as_callee(), args, ..Default::default() - }) + } + .into() } Runtime::Classic => { - Expr::Call(CallExpr { + CallExpr { span, callee: (*self.pragma).clone().as_callee(), args: iter::once(name.as_arg()) @@ -845,7 +850,8 @@ where }) .collect(), ..Default::default() - }) + } + .into() } } } @@ -888,7 +894,7 @@ where fn fold_attrs_for_classic(&mut self, attrs: Vec) -> Box { if attrs.is_empty() { - return Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))); + return Lit::Null(Null { span: DUMMY_SP }).into(); } let attr_cnt = attrs.len(); @@ -916,7 +922,7 @@ where props, }; - Box::new(Expr::Object(obj)) + obj.into() } fn attr_to_prop(&mut self, a: JSXAttr) -> Prop { @@ -927,11 +933,12 @@ where JSXAttrValue::Lit(Lit::Str(s)) => { let value = transform_jsx_attr_str(&s.value); - Box::new(Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: s.span, raw: None, value: value.into(), - }))) + }) + .into() } JSXAttrValue::JSXExprContainer(JSXExprContainer { expr: JSXExpr::Expr(e), @@ -946,10 +953,11 @@ where }) => unreachable!("attr_to_prop(JSXEmptyExpr)"), }) .unwrap_or_else(|| { - Box::new(Expr::Lit(Lit::Bool(Bool { + Lit::Bool(Bool { span: key.span(), value: true, - }))) + }) + .into() }); Prop::KeyValue(KeyValueProp { key, value }) } @@ -1193,18 +1201,19 @@ where match name { JSXElementName::Ident(i) => { if i.sym == "this" { - return Box::new(Expr::This(ThisExpr { span })); + return ThisExpr { span }.into(); } // If it starts with lowercase if i.as_ref().starts_with(|c: char| c.is_ascii_lowercase()) { - Box::new(Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span, raw: None, value: i.sym, - }))) + }) + .into() } else { - Box::new(Expr::Ident(i)) + i.into() } } JSXElementName::JSXNamespacedName(JSXNamespacedName { @@ -1226,11 +1235,12 @@ where let value = format!("{}:{}", ns.sym, name.sym); - Box::new(Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span, raw: None, value: value.into(), - }))) + }) + .into() } JSXElementName::JSXMemberExpr(JSXMemberExpr { obj, prop, .. }) => { fn convert_obj(obj: JSXObject) -> Box { @@ -1241,22 +1251,24 @@ where if i.sym == "this" { Expr::This(ThisExpr { span }) } else { - Expr::Ident(i) + i.into() } } - JSXObject::JSXMemberExpr(e) => Expr::Member(MemberExpr { + JSXObject::JSXMemberExpr(e) => MemberExpr { span, obj: convert_obj(e.obj), prop: MemberProp::Ident(e.prop), - }), + } + .into(), }) .into() } - Box::new(Expr::Member(MemberExpr { + MemberExpr { span, obj: convert_obj(obj), prop: MemberProp::Ident(prop), - })) + } + .into() } } } @@ -1325,19 +1337,20 @@ fn jsx_attr_value_to_expr(v: JSXAttrValue) -> Option> { JSXAttrValue::Lit(Lit::Str(s)) => { let value = transform_jsx_attr_str(&s.value); - Box::new(Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: s.span, raw: None, value: value.into(), - }))) + }) + .into() } JSXAttrValue::Lit(lit) => Box::new(lit.into()), JSXAttrValue::JSXExprContainer(e) => match e.expr { JSXExpr::JSXEmptyExpr(_) => None?, JSXExpr::Expr(e) => e, }, - JSXAttrValue::JSXElement(e) => Box::new(Expr::JSXElement(e)), - JSXAttrValue::JSXFragment(f) => Box::new(Expr::JSXFragment(f)), + JSXAttrValue::JSXElement(e) => e.into(), + JSXAttrValue::JSXFragment(f) => f.into(), }) } diff --git a/crates/swc_ecma_transforms_react/src/refresh/hook.rs b/crates/swc_ecma_transforms_react/src/refresh/hook.rs index 95f5af10346..9c5cca7ece4 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/hook.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/hook.rs @@ -109,11 +109,11 @@ impl<'a> HookRegister<'a> { }; args.push( - Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: DUMMY_SP, raw: None, value: sign.into(), - })) + }) .as_arg(), ); @@ -149,12 +149,13 @@ impl<'a> HookRegister<'a> { .map(|hook| { Some( match hook { - HookCall::Ident(ident) => Expr::Ident(ident), - HookCall::Member(obj, prop) => Expr::Member(MemberExpr { + HookCall::Ident(ident) => Expr::from(ident), + HookCall::Member(obj, prop) => MemberExpr { span: DUMMY_SP, obj: Box::new(obj), prop: MemberProp::Ident(prop), - }), + } + .into(), } .as_arg(), ) @@ -184,19 +185,20 @@ impl<'a> HookRegister<'a> { ); } - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: handle.as_callee(), args, ..Default::default() - }) + } + .into() } 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, Expr::Ident(ident), sig.hooks)), + expr: Box::new(self.wrap_with_register(sig.handle, ident.into(), sig.hooks)), })) } } diff --git a/crates/swc_ecma_transforms_react/src/refresh/mod.rs b/crates/swc_ecma_transforms_react/src/refresh/mod.rs index 5d4d36de3ac..025da190a03 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/mod.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/mod.rs @@ -175,12 +175,13 @@ impl Refresh { let span = first.span(); let mut args = vec![first.as_arg()]; args.extend(rest_arg.clone()); - first = Box::new(Expr::Call(CallExpr { + first = CallExpr { span, callee: callee.clone(), args, ..Default::default() - })) + } + .into() } *first_arg = Box::new(make_assign_stmt(reg_ident, first)); @@ -401,10 +402,7 @@ impl VisitMut for Refresh { items.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(make_assign_stmt( - registration_handle, - Box::new(Expr::Ident(persistent_id)), - )), + expr: Box::new(make_assign_stmt(registration_handle, persistent_id.into())), }))); } @@ -416,7 +414,7 @@ impl VisitMut for Refresh { span: DUMMY_SP, expr: Box::new(make_assign_stmt( ident.clone(), - Box::new(Expr::Ident(Ident::new(name.0.clone(), DUMMY_SP, name.1))), + Ident::new(name.0.clone(), DUMMY_SP, name.1).into(), )), }))) } @@ -463,11 +461,12 @@ impl VisitMut for Refresh { for (handle, persistent_id) in refresh_regs { items.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { + expr: CallExpr { callee: quote_ident!(refresh_reg).as_callee(), args: vec![handle.as_arg(), quote_str!(persistent_id.0).as_arg()], ..Default::default() - })), + } + .into(), }))); } @@ -481,10 +480,11 @@ fn make_hook_reg(expr: &mut Expr, mut hook: HocHook) { let span = expr.span(); let mut args = vec![expr.take().as_arg()]; args.append(&mut hook.rest_arg); - *expr = Expr::Call(CallExpr { + *expr = CallExpr { span, callee: hook.callee, args, ..Default::default() - }); + } + .into(); } diff --git a/crates/swc_ecma_transforms_react/src/refresh/util.rs b/crates/swc_ecma_transforms_react/src/refresh/util.rs index 8400e0c0e34..68b8507b36b 100644 --- a/crates/swc_ecma_transforms_react/src/refresh/util.rs +++ b/crates/swc_ecma_transforms_react/src/refresh/util.rs @@ -42,12 +42,13 @@ fn assert_hygiene(e: &Expr) { pub fn make_assign_stmt(handle: Ident, expr: Box) -> Expr { assert_hygiene(&expr); - Expr::Assign(AssignExpr { + AssignExpr { span: expr.span(), op: op!("="), left: handle.into(), right: expr, - }) + } + .into() } pub fn make_call_stmt(handle: Ident) -> Stmt { @@ -58,12 +59,13 @@ pub fn make_call_stmt(handle: Ident) -> Stmt { } pub fn make_call_expr(handle: Ident) -> Expr { - Expr::Call(CallExpr { + CallExpr { span: DUMMY_SP, callee: handle.as_callee(), args: Vec::new(), ..Default::default() - }) + } + .into() } pub fn is_import_or_require(expr: &Expr) -> bool { diff --git a/crates/swc_ecma_transforms_testing/src/lib.rs b/crates/swc_ecma_transforms_testing/src/lib.rs index 5c78ab2da47..260cb6b0c16 100644 --- a/crates/swc_ecma_transforms_testing/src/lib.rs +++ b/crates/swc_ecma_transforms_testing/src/lib.rs @@ -222,12 +222,13 @@ impl VisitMut for RegeneratorHandler { _ => return, }; - let init = Box::new(Expr::Call(CallExpr { + let init = CallExpr { span: DUMMY_SP, callee: quote_ident!("require").as_callee(), args: vec![quote_str!("regenerator-runtime").as_arg()], ..Default::default() - })); + } + .into(); let decl = VarDeclarator { span: DUMMY_SP, diff --git a/crates/swc_ecma_transforms_typescript/src/transform.rs b/crates/swc_ecma_transforms_typescript/src/transform.rs index 3df3fd6e2bc..cb4994e739a 100644 --- a/crates/swc_ecma_transforms_typescript/src/transform.rs +++ b/crates/swc_ecma_transforms_typescript/src/transform.rs @@ -162,7 +162,7 @@ impl VisitMut for Transform { let value = Ident::from(&*binding_ident).into(); ( - Pat::Ident(binding_ident.clone()), + binding_ident.clone().into(), assign_value_to_this_prop(prop_name, value), id, ) @@ -179,7 +179,7 @@ impl VisitMut for Transform { let value = binding_ident.id.clone().into(); ( - Pat::Assign(assign_pat.clone()), + assign_pat.clone().into(), assign_value_to_this_prop(prop_name, value), id, ) @@ -249,10 +249,11 @@ impl VisitMut for Transform { .map(Box::new) .collect(); - *n = Expr::Seq(SeqExpr { + *n = SeqExpr { span: DUMMY_SP, exprs, - }); + } + .into(); self.class_prop_decls.extend(decls); } @@ -762,11 +763,11 @@ impl Transform { definite: false, }); - **expr = Expr::Ident(ident.clone()); + **expr = ident.clone().into(); PropName::Computed(ComputedPropName { span: *span, - expr: Box::new(Expr::Ident(ident)), + expr: ident.into(), }) } _ => key.clone(), @@ -831,7 +832,8 @@ impl Transform { impl Transform { // Foo.x = x; fn assign_prop(id: &Id, prop: &Ident, span: Span) -> Stmt { - let expr = Expr::Ident(prop.clone()) + let expr = prop + .clone() .make_assign_to(op!("="), id.clone().make_member(prop.clone().into()).into()); Stmt::Expr(ExprStmt { @@ -1232,14 +1234,12 @@ impl VisitMut for ExportedPatRewriter { fn visit_mut_object_pat_prop(&mut self, n: &mut ObjectPatProp) { if let ObjectPatProp::Assign(AssignPatProp { key, value, .. }) = n { - let left = Box::new(Pat::Expr( - self.id.clone().make_member(key.clone().into()).into(), - )); + let left = Pat::Expr(self.id.clone().make_member(key.clone().into()).into()); let value = if let Some(right) = value.take() { AssignPat { span: DUMMY_SP, - left, + left: left.into(), right, } .into() @@ -1249,7 +1249,7 @@ impl VisitMut for ExportedPatRewriter { *n = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(key.clone().into()), - value, + value: value.into(), }); return; } diff --git a/crates/swc_ecma_transforms_typescript/src/ts_enum.rs b/crates/swc_ecma_transforms_typescript/src/ts_enum.rs index cf2be72f7f2..1e26af7ec5c 100644 --- a/crates/swc_ecma_transforms_typescript/src/ts_enum.rs +++ b/crates/swc_ecma_transforms_typescript/src/ts_enum.rs @@ -49,34 +49,38 @@ impl TsEnumRecordValue { impl From for Expr { fn from(value: TsEnumRecordValue) -> Self { match value { - TsEnumRecordValue::String(string) => Expr::Lit(Lit::Str(string.into())), - TsEnumRecordValue::Number(num) if f64::is_nan(num) => Expr::Ident(Ident { + TsEnumRecordValue::String(string) => Lit::Str(string.into()).into(), + TsEnumRecordValue::Number(num) if f64::is_nan(num) => Ident { span: DUMMY_SP, sym: "NaN".into(), ..Default::default() - }), + } + .into(), TsEnumRecordValue::Number(num) if f64::is_infinite(num) => { - let value = Expr::Ident(Ident { + let value: Expr = Ident { span: DUMMY_SP, sym: "Infinity".into(), ..Default::default() - }); + } + .into(); if f64::is_sign_negative(num) { - Expr::Unary(UnaryExpr { + UnaryExpr { span: DUMMY_SP, op: op!(unary, "-"), arg: value.into(), - }) + } + .into() } else { value } } - TsEnumRecordValue::Number(num) => Expr::Lit(Lit::Num(Number { + TsEnumRecordValue::Number(num) => Lit::Num(Number { span: DUMMY_SP, value: num, raw: None, - })), + }) + .into(), TsEnumRecordValue::Void => *Expr::undefined(DUMMY_SP), TsEnumRecordValue::Opaque(expr) => *expr, } diff --git a/crates/swc_ecma_utils/src/constructor.rs b/crates/swc_ecma_utils/src/constructor.rs index 9435ea2bfef..0b9d3a3b2eb 100644 --- a/crates/swc_ecma_utils/src/constructor.rs +++ b/crates/swc_ecma_utils/src/constructor.rs @@ -142,20 +142,24 @@ impl VisitMut for ExprInjector<'_> { self.injected = true; let e = expr.take(); - *expr = Expr::Seq(SeqExpr { + *expr = SeqExpr { span: DUMMY_SP, - exprs: iter::once(Box::new(Expr::Assign(AssignExpr { - span: DUMMY_SP, - left: self.injected_tmp.as_ref().cloned().unwrap().into(), - op: op!("="), - right: Box::new(e), - }))) + exprs: iter::once( + AssignExpr { + span: DUMMY_SP, + left: self.injected_tmp.as_ref().cloned().unwrap().into(), + op: op!("="), + right: Box::new(e), + } + .into(), + ) .chain(self.exprs.clone()) - .chain(iter::once(Box::new(Expr::Ident( - self.injected_tmp.as_ref().cloned().unwrap(), - )))) + .chain(iter::once( + self.injected_tmp.as_ref().cloned().unwrap().into(), + )) .collect(), - }) + } + .into() } } diff --git a/crates/swc_ecma_utils/src/factory.rs b/crates/swc_ecma_utils/src/factory.rs index 4658f877e25..b62bbc7a9c1 100644 --- a/crates/swc_ecma_utils/src/factory.rs +++ b/crates/swc_ecma_utils/src/factory.rs @@ -145,35 +145,38 @@ pub trait ExprFactory: Into> { fn apply(self, span: Span, this: Box, args: Vec) -> Expr { let apply = self.make_member(IdentName::new("apply".into(), span)); - Expr::Call(CallExpr { + CallExpr { span, callee: apply.as_callee(), args: iter::once(this.as_arg()).chain(args).collect(), ..Default::default() - }) + } + .into() } #[cfg_attr(not(debug_assertions), inline(always))] fn call_fn(self, span: Span, args: Vec) -> Expr { - Expr::Call(CallExpr { + CallExpr { span, args, callee: self .make_member(IdentName::new("call".into(), span)) .as_callee(), ..Default::default() - }) + } + .into() } #[cfg_attr(not(debug_assertions), inline(always))] fn as_call(self, span: Span, args: Vec) -> Expr { - Expr::Call(CallExpr { + CallExpr { span, args, callee: self.as_callee(), ..Default::default() - }) + } + .into() } #[cfg_attr(not(debug_assertions), inline(always))] @@ -210,7 +213,7 @@ pub trait ExprFactory: Into> { fn wrap_with_paren(self) -> Expr { let expr = self.into(); let span = expr.span(); - Expr::Paren(ParenExpr { expr, span }) + ParenExpr { expr, span }.into() } /// Creates a binary expr `$self === ` @@ -230,12 +233,13 @@ pub trait ExprFactory: Into> { { let right = Box::new(right.into()); - Expr::Bin(BinExpr { + BinExpr { span: DUMMY_SP, left: self.into(), op, right, - }) + } + .into() } /// Creates a assign expr `$lhs $op $self` @@ -243,12 +247,13 @@ pub trait ExprFactory: Into> { fn make_assign_to(self, op: AssignOp, left: AssignTarget) -> Expr { let right = self.into(); - Expr::Assign(AssignExpr { + AssignExpr { span: DUMMY_SP, left, op, right, - }) + } + .into() } #[cfg_attr(not(debug_assertions), inline(always))] 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 868104fc3a5..6816f5ce0c9 100644 --- a/crates/swc_ecma_utils/src/function/fn_env_hoister.rs +++ b/crates/swc_ecma_utils/src/function/fn_env_hoister.rs @@ -87,7 +87,7 @@ impl FnEnvHoister { decls.push(VarDeclarator { span: DUMMY_SP, name: this_id.into(), - init: Some(Box::new(Expr::This(ThisExpr { span: DUMMY_SP }))), + init: Some(ThisExpr { span: DUMMY_SP }.into()), definite: false, }); } @@ -95,10 +95,7 @@ impl FnEnvHoister { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), - init: Some(Box::new(Expr::Ident(Ident::new_no_ctxt( - "arguments".into(), - DUMMY_SP, - )))), + init: Some(Ident::new_no_ctxt("arguments".into(), DUMMY_SP).into()), definite: false, }); } @@ -106,10 +103,13 @@ impl FnEnvHoister { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), - init: Some(Box::new(Expr::MetaProp(MetaPropExpr { - span: DUMMY_SP, - kind: MetaPropKind::NewTarget, - }))), + init: Some( + MetaPropExpr { + span: DUMMY_SP, + kind: MetaPropKind::NewTarget, + } + .into(), + ), definite: false, }); } @@ -155,10 +155,7 @@ impl FnEnvHoister { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), - init: Some(Box::new(Expr::Ident(Ident::new_no_ctxt( - "arguments".into(), - DUMMY_SP, - )))), + init: Some(Ident::new_no_ctxt("arguments".into(), DUMMY_SP).into()), definite: false, }); } @@ -166,10 +163,13 @@ impl FnEnvHoister { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), - init: Some(Box::new(Expr::MetaProp(MetaPropExpr { - span: DUMMY_SP, - kind: MetaPropKind::NewTarget, - }))), + init: Some( + MetaPropExpr { + span: DUMMY_SP, + kind: MetaPropKind::NewTarget, + } + .into(), + ), definite: false, }); } @@ -357,11 +357,11 @@ impl VisitMut for FnEnvHoister { let arguments = self .args .get_or_insert_with(|| private_ident!("_arguments")); - *e = Expr::Ident(arguments.clone()); + *e = arguments.clone().into(); } Expr::This(..) if !self.this_disabled => { let this = self.get_this(); - *e = Expr::Ident(this); + *e = this.into(); } Expr::MetaProp(MetaPropExpr { kind: MetaPropKind::NewTarget, @@ -370,7 +370,7 @@ impl VisitMut for FnEnvHoister { let target = self .new_target .get_or_insert_with(|| private_ident!("_newtarget")); - *e = Expr::Ident(target.clone()); + *e = target.clone().into(); } // super.foo = 123 => super_get_foo = (value) => super.foo = value Expr::Assign(AssignExpr { @@ -424,16 +424,17 @@ impl VisitMut for FnEnvHoister { } else { vec![c.expr.take().as_arg(), right.take().as_arg()] }; - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, args, callee: callee.as_callee(), ..Default::default() - }); + } + .into(); } SuperProp::Ident(id) => { let callee = self.super_set(&id.sym, left_span); - *e = Expr::Call(CallExpr { + *e = CallExpr { span: *span, args: vec![(if let Some(op) = op.to_update() { Box::new(Expr::Bin(BinExpr { @@ -451,7 +452,8 @@ impl VisitMut for FnEnvHoister { .as_arg()], callee: callee.as_callee(), ..Default::default() - }); + } + .into(); } } } @@ -470,12 +472,13 @@ impl VisitMut for FnEnvHoister { match &mut super_prop.prop { SuperProp::Computed(c) => { let callee = self.super_get_computed(super_prop.span); - let call = Expr::Call(CallExpr { + let call: Expr = CallExpr { span: *span, args: vec![c.expr.take().as_arg()], callee: callee.as_callee(), ..Default::default() - }); + } + .into(); let mut new_args = args.take(); new_args.insert(0, self.get_this().as_arg()); @@ -484,12 +487,13 @@ impl VisitMut for FnEnvHoister { } SuperProp::Ident(id) => { let callee = self.super_get(&id.sym, super_prop.span); - let call = Expr::Call(CallExpr { + let call: Expr = CallExpr { span: *span, args: Vec::new(), callee: callee.as_callee(), ..Default::default() - }); + } + .into(); let mut new_args = args.take(); new_args.insert(0, self.get_this().as_arg()); @@ -514,7 +518,7 @@ impl VisitMut for FnEnvHoister { SuperProp::Computed(c) => { c.expr.visit_mut_children_with(self); *e = if self.in_pat { - Expr::Call(CallExpr { + Expr::from(CallExpr { span: *span, args: vec![c.expr.take().as_arg()], callee: self.super_update_computed(*span).as_callee(), @@ -523,12 +527,13 @@ impl VisitMut for FnEnvHoister { .make_member("_".into()) .into() } else { - Expr::Call(CallExpr { + CallExpr { span: *span, args: vec![c.expr.take().as_arg()], callee: self.super_get_computed(*span).as_callee(), ..Default::default() - }) + } + .into() }; } SuperProp::Ident(id) => { @@ -537,12 +542,13 @@ impl VisitMut for FnEnvHoister { .make_member(quote_ident!("_")) .into() } else { - Expr::Call(CallExpr { + CallExpr { span: *span, args: Vec::new(), callee: self.super_get(&id.sym, *span).as_callee(), ..Default::default() - }) + } + .into() }; } }, @@ -609,9 +615,9 @@ impl<'a> VisitMut for InitThis<'a> { ) = expr { let span = call_expr.span; - *expr = Expr::Paren(ParenExpr { + *expr = ParenExpr { span, - expr: Box::new(Expr::Seq(SeqExpr { + expr: SeqExpr { span, exprs: vec![ Box::new(Expr::Call(call_expr.take())), @@ -622,8 +628,10 @@ impl<'a> VisitMut for InitThis<'a> { right: Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), })), ], - })), - }) + } + .into(), + } + .into() } } } @@ -639,65 +647,8 @@ fn extend_super( VarDeclarator { span: DUMMY_SP, name: ident.into(), - init: Some(Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props: vec![ - Prop::Getter(GetterProp { - span: DUMMY_SP, - key: PropName::Ident("_".into()), - type_ann: None, - body: Some(BlockStmt { - stmts: vec![Expr::Ident( - get.ident - .get(&key) - .cloned() - .expect("getter not found") - .without_loc(), - ) - .as_call(DUMMY_SP, Default::default()) - .into_return_stmt() - .into()], - ..Default::default() - }), - }), - Prop::Setter(SetterProp { - span: DUMMY_SP, - key: PropName::Ident("_".into()), - this_param: None, - param: value.clone().into(), - body: Some(BlockStmt { - stmts: vec![Expr::Ident( - set.ident - .get(&key) - .cloned() - .expect("setter not found") - .without_loc(), - ) - .as_call(DUMMY_SP, vec![value.as_arg()]) - .into_stmt()], - ..Default::default() - }), - }), - ] - .into_iter() - .map(Box::new) - .map(From::from) - .collect(), - }))), - definite: false, - } - })); - if let Some(id) = update.computed { - let prop = private_ident!("_prop"); - let value = private_ident!("v"); - - decls.push(VarDeclarator { - span: DUMMY_SP, - name: id.into(), - init: Some(Box::new(Expr::Arrow(ArrowExpr { - span: DUMMY_SP, - params: vec![prop.clone().into()], - body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Object(ObjectLit { + init: Some( + ObjectLit { span: DUMMY_SP, props: vec![ Prop::Getter(GetterProp { @@ -706,12 +657,13 @@ fn extend_super( type_ann: None, body: Some(BlockStmt { stmts: vec![Expr::Ident( - get.computed - .clone() - .expect("getter computed not found") + get.ident + .get(&key) + .cloned() + .expect("getter not found") .without_loc(), ) - .as_call(DUMMY_SP, vec![prop.clone().as_arg()]) + .as_call(DUMMY_SP, Default::default()) .into_return_stmt() .into()], ..Default::default() @@ -724,14 +676,14 @@ fn extend_super( param: value.clone().into(), body: Some(BlockStmt { stmts: vec![Expr::Ident( - set.computed - .clone() - .expect("setter computed not found") + set.ident + .get(&key) + .cloned() + .expect("setter not found") .without_loc(), ) - .as_call(DUMMY_SP, vec![prop.as_arg(), value.as_arg()]) - .into_return_stmt() - .into()], + .as_call(DUMMY_SP, vec![value.as_arg()]) + .into_stmt()], ..Default::default() }), }), @@ -740,49 +692,124 @@ fn extend_super( .map(Box::new) .map(From::from) .collect(), - })))), - ..Default::default() - }))), + } + .into(), + ), + definite: false, + } + })); + if let Some(id) = update.computed { + let prop = private_ident!("_prop"); + let value = private_ident!("v"); + + decls.push(VarDeclarator { + span: DUMMY_SP, + name: id.into(), + init: Some( + ArrowExpr { + span: DUMMY_SP, + params: vec![prop.clone().into()], + body: Box::new(BlockStmtOrExpr::Expr(Box::new( + ObjectLit { + span: DUMMY_SP, + props: vec![ + Prop::Getter(GetterProp { + span: DUMMY_SP, + key: PropName::Ident("_".into()), + type_ann: None, + body: Some(BlockStmt { + stmts: vec![Expr::Ident( + get.computed + .clone() + .expect("getter computed not found") + .without_loc(), + ) + .as_call(DUMMY_SP, vec![prop.clone().as_arg()]) + .into_return_stmt() + .into()], + ..Default::default() + }), + }), + Prop::Setter(SetterProp { + span: DUMMY_SP, + key: PropName::Ident("_".into()), + this_param: None, + param: value.clone().into(), + body: Some(BlockStmt { + stmts: vec![Expr::Ident( + set.computed + .clone() + .expect("setter computed not found") + .without_loc(), + ) + .as_call(DUMMY_SP, vec![prop.as_arg(), value.as_arg()]) + .into_return_stmt() + .into()], + ..Default::default() + }), + }), + ] + .into_iter() + .map(Box::new) + .map(From::from) + .collect(), + } + .into(), + ))), + ..Default::default() + } + .into(), + ), definite: false, }); } - decls.extend(get.ident.into_iter().map(|(key, ident)| VarDeclarator { - span: DUMMY_SP, - name: ident.without_loc().into(), - init: Some(Box::new(Expr::Arrow(ArrowExpr { + decls.extend(get.ident.into_iter().map(|(key, ident)| { + VarDeclarator { span: DUMMY_SP, - params: Vec::new(), - body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::SuperProp( - SuperPropExpr { - obj: Super { span: DUMMY_SP }, - prop: SuperProp::Ident(key.into()), + name: ident.without_loc().into(), + init: Some( + ArrowExpr { span: DUMMY_SP, - }, - )))), - ..Default::default() - }))), - definite: false, + params: Vec::new(), + body: Box::new(BlockStmtOrExpr::Expr(Box::new( + SuperPropExpr { + obj: Super { span: DUMMY_SP }, + prop: SuperProp::Ident(key.into()), + span: DUMMY_SP, + } + .into(), + ))), + ..Default::default() + } + .into(), + ), + definite: false, + } })); if let Some(id) = get.computed { let param = private_ident!("_prop"); decls.push(VarDeclarator { span: DUMMY_SP, name: id.without_loc().into(), - init: Some(Box::new(Expr::Arrow(ArrowExpr { - span: DUMMY_SP, - params: vec![param.clone().into()], - body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::SuperProp( - SuperPropExpr { - obj: Super { span: DUMMY_SP }, - prop: SuperProp::Computed(ComputedPropName { + init: Some( + ArrowExpr { + span: DUMMY_SP, + params: vec![param.clone().into()], + body: Box::new(BlockStmtOrExpr::Expr(Box::new( + SuperPropExpr { + obj: Super { span: DUMMY_SP }, + prop: SuperProp::Computed(ComputedPropName { + span: DUMMY_SP, + expr: Box::new(Expr::Ident(param)), + }), span: DUMMY_SP, - expr: Box::new(Expr::Ident(param)), - }), - span: DUMMY_SP, - }, - )))), - ..Default::default() - }))), + } + .into(), + ))), + ..Default::default() + } + .into(), + ), definite: false, }); } @@ -791,22 +818,28 @@ fn extend_super( VarDeclarator { span: DUMMY_SP, name: ident.without_loc().into(), - init: Some(Box::new(Expr::Arrow(ArrowExpr { - span: DUMMY_SP, - params: vec![value.clone().into()], - body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Assign(AssignExpr { + init: Some( + ArrowExpr { span: DUMMY_SP, - left: SuperPropExpr { - obj: Super { span: DUMMY_SP }, - prop: SuperProp::Ident(key.into()), - span: DUMMY_SP, - } - .into(), - op: op!("="), - right: Box::new(Expr::Ident(value)), - })))), - ..Default::default() - }))), + params: vec![value.clone().into()], + body: Box::new(BlockStmtOrExpr::Expr(Box::new( + AssignExpr { + span: DUMMY_SP, + left: SuperPropExpr { + obj: Super { span: DUMMY_SP }, + prop: SuperProp::Ident(key.into()), + span: DUMMY_SP, + } + .into(), + op: op!("="), + right: Box::new(Expr::Ident(value)), + } + .into(), + ))), + ..Default::default() + } + .into(), + ), definite: false, } })); @@ -816,25 +849,31 @@ fn extend_super( decls.push(VarDeclarator { span: DUMMY_SP, name: id.without_loc().into(), - init: Some(Box::new(Expr::Arrow(ArrowExpr { - span: DUMMY_SP, - params: vec![prop.clone().into(), value.clone().into()], - body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Assign(AssignExpr { + init: Some( + ArrowExpr { span: DUMMY_SP, - left: SuperPropExpr { - obj: Super { span: DUMMY_SP }, - prop: SuperProp::Computed(ComputedPropName { + params: vec![prop.clone().into(), value.clone().into()], + body: Box::new(BlockStmtOrExpr::Expr(Box::new( + AssignExpr { span: DUMMY_SP, - expr: Box::new(Expr::Ident(prop)), - }), - span: DUMMY_SP, - } - .into(), - op: op!("="), - right: Box::new(Expr::Ident(value)), - })))), - ..Default::default() - }))), + left: SuperPropExpr { + obj: Super { span: DUMMY_SP }, + prop: SuperProp::Computed(ComputedPropName { + span: DUMMY_SP, + expr: Box::new(Expr::Ident(prop)), + }), + span: DUMMY_SP, + } + .into(), + op: op!("="), + right: Box::new(Expr::Ident(value)), + } + .into(), + ))), + ..Default::default() + } + .into(), + ), definite: false, }); } diff --git a/crates/swc_ecma_utils/src/function/function_wrapper.rs b/crates/swc_ecma_utils/src/function/function_wrapper.rs index 240c3784acd..827c3ffd65e 100644 --- a/crates/swc_ecma_utils/src/function/function_wrapper.rs +++ b/crates/swc_ecma_utils/src/function/function_wrapper.rs @@ -33,7 +33,7 @@ impl FunctionWrapper { Pat::Array(..) | Pat::Object(..) => Some(Param { span: param.span, decorators: param.decorators.clone(), - pat: Pat::Ident(private_ident!("_").into()), + pat: private_ident!("_").into(), }), _ => None, }) @@ -235,7 +235,7 @@ impl FunctionWrapper { span: DUMMY_SP, arg: Some(Box::new(ref_ident.apply( DUMMY_SP, - Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), + ThisExpr { span: DUMMY_SP }.into(), vec![quote_ident!("arguments").as_arg()], ))), }); diff --git a/crates/swc_ecma_utils/src/lib.rs b/crates/swc_ecma_utils/src/lib.rs index 0e9d8a1e16b..2a6c366dcaf 100644 --- a/crates/swc_ecma_utils/src/lib.rs +++ b/crates/swc_ecma_utils/src/lib.rs @@ -420,7 +420,7 @@ pub trait StmtExt { .into_iter() .map(|i| VarDeclarator { span: i.span, - name: Pat::Ident(i.into()), + name: i.into(), init: None, definite: false, }) @@ -2097,10 +2097,10 @@ pub fn alias_if_required(expr: &Expr, default: &str) -> (Ident, bool) { pub fn prop_name_to_expr(p: PropName) -> Expr { match p { - PropName::Ident(i) => Expr::Ident(i.into()), - PropName::Str(s) => Expr::Lit(Lit::Str(s)), - PropName::Num(n) => Expr::Lit(Lit::Num(n)), - PropName::BigInt(b) => Expr::Lit(Lit::BigInt(b)), + PropName::Ident(i) => i.into(), + PropName::Str(s) => Lit::Str(s).into(), + PropName::Num(n) => Lit::Num(n).into(), + PropName::BigInt(b) => Lit::BigInt(b).into(), PropName::Computed(c) => *c.expr, } } @@ -2109,14 +2109,15 @@ pub fn prop_name_to_expr(p: PropName) -> Expr { /// e.g. value from `{ key: value }` pub fn prop_name_to_expr_value(p: PropName) -> Expr { match p { - PropName::Ident(i) => Expr::Lit(Lit::Str(Str { + PropName::Ident(i) => Lit::Str(Str { span: i.span, raw: None, value: i.sym, - })), - PropName::Str(s) => Expr::Lit(Lit::Str(s)), - PropName::Num(n) => Expr::Lit(Lit::Num(n)), - PropName::BigInt(b) => Expr::Lit(Lit::BigInt(b)), + }) + .into(), + PropName::Str(s) => Lit::Str(s).into(), + PropName::Num(n) => Lit::Num(n).into(), + PropName::BigInt(b) => Lit::BigInt(b).into(), PropName::Computed(c) => *c.expr, } } @@ -2200,29 +2201,33 @@ pub fn opt_chain_test( no_document_all: bool, ) -> Expr { if no_document_all { - Expr::Bin(BinExpr { + BinExpr { span, left, op: op!("=="), - right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), - }) + right: Lit::Null(Null { span: DUMMY_SP }).into(), + } + .into() } else { - Expr::Bin(BinExpr { + BinExpr { span, - left: Box::new(Expr::Bin(BinExpr { + left: BinExpr { span: DUMMY_SP, left, op: op!("==="), right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), - })), + } + .into(), op: op!("||"), - right: Box::new(Expr::Bin(BinExpr { + right: BinExpr { span: DUMMY_SP, left: right, op: op!("==="), right: Expr::undefined(DUMMY_SP), - })), - }) + } + .into(), + } + .into() } } @@ -2450,7 +2455,7 @@ impl<'a> IdentUsageFinder<'a> { impl ExprCtx { /// make a new expression which evaluates `val` preserving side effects, if /// any. - pub fn preserve_effects(&self, span: Span, val: Expr, exprs: I) -> Expr + pub fn preserve_effects(&self, span: Span, val: Box, exprs: I) -> Box where I: IntoIterator>, { @@ -2462,9 +2467,9 @@ impl ExprCtx { if exprs.is_empty() { val } else { - exprs.push(Box::new(val)); + exprs.push(val); - Expr::Seq(SeqExpr { exprs, span }) + SeqExpr { exprs, span }.into() } } @@ -2504,7 +2509,7 @@ impl ExprCtx { } } - to.push(Box::new(Expr::New(e))) + to.push(e.into()) } Expr::Member(_) | Expr::SuperProp(_) => to.push(Box::new(expr)), @@ -2580,7 +2585,7 @@ impl ExprCtx { }); if has_spread { - to.push(Box::new(Expr::Object(ObjectLit { span, props }))) + to.push(ObjectLit { span, props }.into()) } else { props.into_iter().for_each(|prop| match prop { PropOrSpread::Prop(node) => match *node { @@ -2699,7 +2704,7 @@ impl VisitMut for IdentReplacer<'_> { if i.sym != cloned.sym || i.ctxt != cloned.ctxt { *node = Prop::KeyValue(KeyValueProp { key: PropName::Ident(IdentName::new(cloned.sym, cloned.span)), - value: Box::new(Expr::Ident(i.clone())), + value: i.clone().into(), }); } } @@ -3038,11 +3043,12 @@ impl VisitMut for IdentRenamer<'_> { Some(default) => { *i = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(orig.clone().into()), - value: Box::new(Pat::Assign(AssignPat { + value: AssignPat { span: DUMMY_SP, left: p.key.clone().into(), right: default, - })), + } + .into(), }); } None => { @@ -3068,7 +3074,7 @@ impl VisitMut for IdentRenamer<'_> { if i.sym != cloned.sym || i.ctxt != cloned.ctxt { *node = Prop::KeyValue(KeyValueProp { key: PropName::Ident(IdentName::new(cloned.sym, cloned.span)), - value: Box::new(Expr::Ident(i.clone())), + value: i.clone().into(), }); } } @@ -3148,7 +3154,7 @@ where match n { Pat::Ident(id) => { if let Some(expr) = self.query.query_lhs(&id.clone().into()) { - *n = Pat::Expr(expr); + *n = expr.into(); } } _ => n.visit_mut_children_with(self), diff --git a/crates/swc_estree_compat/src/swcify/class.rs b/crates/swc_estree_compat/src/swcify/class.rs index 5b16eec1140..746d2d5fb85 100644 --- a/crates/swc_estree_compat/src/swcify/class.rs +++ b/crates/swc_estree_compat/src/swcify/class.rs @@ -197,16 +197,17 @@ impl Swcify for TSExpressionWithTypeArguments { // if we change its conversion logic, it will break. fn swcify_expr(expr: TSEntityName, ctx: &Context) -> Box { match expr { - TSEntityName::Id(v) => Box::new(Expr::Ident(v.swcify(ctx).into())), + TSEntityName::Id(v) => v.swcify(ctx).into(), TSEntityName::Qualified(v) => swcify_qualified_name(v, ctx), } } fn swcify_qualified_name(qualified_name: TSQualifiedName, ctx: &Context) -> Box { - Box::new(Expr::Member(MemberExpr { + MemberExpr { obj: swcify_expr(*qualified_name.left, ctx), prop: MemberProp::Ident(qualified_name.right.swcify(ctx).into()), span: ctx.span(&qualified_name.base), - })) + } + .into() } TsExprWithTypeArgs { diff --git a/crates/swc_estree_compat/src/swcify/expr.rs b/crates/swc_estree_compat/src/swcify/expr.rs index 87dfd00c3f9..dc50d6c6e48 100644 --- a/crates/swc_estree_compat/src/swcify/expr.rs +++ b/crates/swc_estree_compat/src/swcify/expr.rs @@ -40,7 +40,7 @@ impl Swcify for Expression { Expression::Call(e) => e.swcify(ctx).into(), Expression::Conditional(e) => e.swcify(ctx).into(), Expression::Func(e) => e.swcify(ctx).into(), - Expression::Id(e) => Expr::Ident(e.swcify(ctx).into()), + Expression::Id(e) => e.swcify(ctx).id.into(), Expression::Literal(Literal::String(e)) => e.swcify(ctx).into(), Expression::Literal(Literal::Numeric(e)) => e.swcify(ctx).into(), Expression::Literal(Literal::Null(e)) => Lit::from(e.swcify(ctx)).into(), @@ -63,7 +63,7 @@ impl Swcify for Expression { Expression::TemplateLiteral(e) => e.swcify(ctx).into(), Expression::Yield(e) => e.swcify(ctx).into(), Expression::Await(e) => e.swcify(ctx).into(), - Expression::Literal(Literal::BigInt(e)) => Expr::Lit(e.swcify(ctx).into()), + Expression::Literal(Literal::BigInt(e)) => e.swcify(ctx).into(), Expression::OptionalMember(e) => e.swcify(ctx).into(), Expression::OptionalCall(e) => e.swcify(ctx).into(), Expression::JSXElement(e) => return e.swcify(ctx).into(), @@ -138,7 +138,7 @@ impl Swcify for BinaryExprLeft { fn swcify(self, ctx: &Context) -> Self::Output { match self { - BinaryExprLeft::Private(e) => Box::new(Expr::PrivateName(e.swcify(ctx))), + BinaryExprLeft::Private(e) => e.swcify(ctx).into(), BinaryExprLeft::Expr(e) => e.swcify(ctx), } } @@ -266,7 +266,7 @@ impl Swcify for Arg { }, Arg::JSXName(e) => ExprOrSpread { spread: None, - expr: Box::new(Expr::JSXNamespacedName(e.swcify(ctx))), + expr: e.swcify(ctx).into(), }, Arg::Placeholder(_) => return None, Arg::Expr(e) => ExprOrSpread { @@ -363,7 +363,7 @@ impl Swcify for MemberExpression { fn swcify(self, ctx: &Context) -> Self::Output { match *self.object { - Expression::Super(s) => Expr::SuperProp(SuperPropExpr { + Expression::Super(s) => SuperPropExpr { span: ctx.span(&self.base), obj: s.swcify(ctx), prop: match (*self.property, self.computed) { @@ -377,8 +377,9 @@ impl Swcify for MemberExpression { } _ => unreachable!(), }, - }), - _ => Expr::Member(MemberExpr { + } + .into(), + _ => MemberExpr { span: ctx.span(&self.base), obj: self.object.swcify(ctx), prop: match (*self.property, self.computed) { @@ -395,7 +396,8 @@ impl Swcify for MemberExpression { } _ => unreachable!(), }, - }), + } + .into(), } } } @@ -511,7 +513,7 @@ impl Swcify for ObjectProperty { key: self.key.swcify(ctx), value: match self.value { ObjectPropVal::Pattern(pat) => match pat { - PatternLike::Id(i) => Box::new(Expr::Ident(i.swcify(ctx).into())), + PatternLike::Id(i) => i.swcify(ctx).into(), _ => { panic!("swc does not support ObjectPropVal::Pattern({:?})", pat) } @@ -792,7 +794,7 @@ impl Swcify for OptionalMemberExprProp { fn swcify(self, ctx: &Context) -> Self::Output { match self { - OptionalMemberExprProp::Id(v) => Box::new(Expr::Ident(v.swcify(ctx).into())), + OptionalMemberExprProp::Id(v) => v.swcify(ctx).into(), OptionalMemberExprProp::Expr(v) => v.swcify(ctx), } } diff --git a/crates/swc_estree_compat/src/swcify/pat.rs b/crates/swc_estree_compat/src/swcify/pat.rs index e841614b707..08dce9b774d 100644 --- a/crates/swc_estree_compat/src/swcify/pat.rs +++ b/crates/swc_estree_compat/src/swcify/pat.rs @@ -13,7 +13,7 @@ impl Swcify for LVal { fn swcify(self, ctx: &Context) -> Self::Output { match self { LVal::Id(i) => i.swcify(ctx).into(), - LVal::MemberExpr(e) => Pat::Expr(Box::new(e.swcify(ctx))), + LVal::MemberExpr(e) => Box::new(e.swcify(ctx)).into(), LVal::RestEl(e) => e.swcify(ctx).into(), LVal::AssignmentPat(e) => e.swcify(ctx).into(), LVal::ArrayPat(e) => e.swcify(ctx).into(), @@ -58,7 +58,7 @@ impl Swcify for AssignmentPatternLeft { AssignmentPatternLeft::Id(v) => v.swcify(ctx).into(), AssignmentPatternLeft::Object(v) => v.swcify(ctx).into(), AssignmentPatternLeft::Array(v) => v.swcify(ctx).into(), - AssignmentPatternLeft::Member(v) => Pat::Expr(Box::new(v.swcify(ctx))), + AssignmentPatternLeft::Member(v) => Box::new(v.swcify(ctx)).into(), } } } @@ -81,11 +81,11 @@ impl Swcify for PatternLike { fn swcify(self, ctx: &Context) -> Self::Output { match self { - PatternLike::Id(v) => Pat::from(v.swcify(ctx)), - PatternLike::RestEl(v) => Pat::from(v.swcify(ctx)), - PatternLike::AssignmentPat(v) => Pat::from(v.swcify(ctx)), - PatternLike::ArrayPat(v) => Pat::from(v.swcify(ctx)), - PatternLike::ObjectPat(v) => Pat::from(v.swcify(ctx)), + PatternLike::Id(v) => v.swcify(ctx).into(), + PatternLike::RestEl(v) => v.swcify(ctx).into(), + PatternLike::AssignmentPat(v) => v.swcify(ctx).into(), + PatternLike::ArrayPat(v) => v.swcify(ctx).into(), + PatternLike::ObjectPat(v) => v.swcify(ctx).into(), } } } @@ -143,9 +143,9 @@ impl Swcify for swc_estree_ast::Pattern { fn swcify(self, ctx: &Context) -> Self::Output { match self { - swc_estree_ast::Pattern::Assignment(v) => Pat::from(v.swcify(ctx)), - swc_estree_ast::Pattern::Array(v) => Pat::from(v.swcify(ctx)), - swc_estree_ast::Pattern::Object(v) => Pat::from(v.swcify(ctx)), + swc_estree_ast::Pattern::Assignment(v) => v.swcify(ctx).into(), + swc_estree_ast::Pattern::Array(v) => v.swcify(ctx).into(), + swc_estree_ast::Pattern::Object(v) => v.swcify(ctx).into(), } } } diff --git a/crates/swc_estree_compat/src/swcify/stmt.rs b/crates/swc_estree_compat/src/swcify/stmt.rs index e273357dd27..e1a8492621f 100644 --- a/crates/swc_estree_compat/src/swcify/stmt.rs +++ b/crates/swc_estree_compat/src/swcify/stmt.rs @@ -2,8 +2,8 @@ use swc_common::DUMMY_SP; use swc_ecma_ast::{ BlockStmt, BreakStmt, ClassDecl, ClassExpr, ContinueStmt, DebuggerStmt, Decl, DefaultDecl, DoWhileStmt, EmptyStmt, ExportAll, ExportDecl, ExportDefaultDecl, ExportDefaultExpr, - ExportNamedSpecifier, Expr, ExprStmt, FnDecl, FnExpr, ForHead, ForInStmt, ForOfStmt, ForStmt, - IfStmt, ImportDecl, ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, KeyValueProp, + 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, @@ -345,9 +345,9 @@ impl Swcify for swc_estree_ast::CatchClauseParam { fn swcify(self, ctx: &Context) -> Self::Output { match self { - swc_estree_ast::CatchClauseParam::Id(v) => Pat::from(v.swcify(ctx)), - swc_estree_ast::CatchClauseParam::Array(v) => Pat::from(v.swcify(ctx)), - swc_estree_ast::CatchClauseParam::Object(v) => Pat::from(v.swcify(ctx)), + swc_estree_ast::CatchClauseParam::Id(v) => v.swcify(ctx).into(), + swc_estree_ast::CatchClauseParam::Array(v) => v.swcify(ctx).into(), + swc_estree_ast::CatchClauseParam::Object(v) => v.swcify(ctx).into(), } } } @@ -463,7 +463,7 @@ impl Swcify for ImportAttribute { fn swcify(self, ctx: &Context) -> Self::Output { KeyValueProp { key: self.key.swcify(ctx), - value: Box::new(Expr::Lit(Lit::Str(self.value.swcify(ctx)))), + value: Lit::Str(self.value.swcify(ctx)).into(), } } } diff --git a/crates/swc_node_bundler/src/loaders/json.rs b/crates/swc_node_bundler/src/loaders/json.rs index 726f6e73382..d9e6c3e0022 100644 --- a/crates/swc_node_bundler/src/loaders/json.rs +++ b/crates/swc_node_bundler/src/loaders/json.rs @@ -11,17 +11,18 @@ pub(super) fn load_json_as_module(fm: &Arc) -> Result let export = ModuleItem::Stmt(Stmt::Expr(ExprStmt { span: DUMMY_SP, - expr: Box::new(Expr::Assign(AssignExpr { + expr: AssignExpr { span: DUMMY_SP, op: op!("="), left: MemberExpr { span: DUMMY_SP, - obj: Box::new(Expr::Ident(Ident::new_no_ctxt("module".into(), DUMMY_SP))), + obj: Box::new(Ident::new_no_ctxt("module".into(), DUMMY_SP).into()), prop: MemberProp::Ident(IdentName::new("exports".into(), DUMMY_SP)), } .into(), right: expr, - })), + } + .into(), })); Ok(Module { diff --git a/crates/swc_node_bundler/src/loaders/swc.rs b/crates/swc_node_bundler/src/loaders/swc.rs index b3ed2414c8d..37653b30b7d 100644 --- a/crates/swc_node_bundler/src/loaders/swc.rs +++ b/crates/swc_node_bundler/src/loaders/swc.rs @@ -71,11 +71,12 @@ impl SwcLoader { for (k, v) in envs_map { m.insert( k, - Expr::Lit(Lit::Str(Str { + Lit::Str(Str { span: DUMMY_SP, raw: None, value: v, - })), + }) + .into(), ); } diff --git a/crates/swc_plugin_runner/tests/fixture/swc_internal_plugin/src/lib.rs b/crates/swc_plugin_runner/tests/fixture/swc_internal_plugin/src/lib.rs index 5cf021eca44..9f259f16619 100644 --- a/crates/swc_plugin_runner/tests/fixture/swc_internal_plugin/src/lib.rs +++ b/crates/swc_plugin_runner/tests/fixture/swc_internal_plugin/src/lib.rs @@ -25,11 +25,11 @@ impl VisitMut for ConsoleOutputReplacer { self.metadata.source_map.lookup_char_pos(ident.span.lo) ); if ident.sym == *"console" { - call.args[0].expr = Box::new(Expr::Lit(Lit::Str(Str { + call.args[0].expr = Lit::Str(Str { span: DUMMY_SP, value: JsWord::from("changed_via_plugin"), raw: Some(Atom::from("\"changed_via_plugin\"")), - }))); + }).into(); } } } diff --git a/crates/swc_typescript/src/fast_dts/mod.rs b/crates/swc_typescript/src/fast_dts/mod.rs index 63723aac872..75cb8ca3bc1 100644 --- a/crates/swc_typescript/src/fast_dts/mod.rs +++ b/crates/swc_typescript/src/fast_dts/mod.rs @@ -197,7 +197,7 @@ impl FastDts { new_items.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( ExportDefaultExpr { span: export.span, - expr: Box::new(Expr::Ident(name_ident)), + expr: name_ident.into(), }, ))) } else { @@ -298,12 +298,12 @@ impl FastDts { (Expr::Ident(ident.into()), false) } PropName::Str(str_prop) => { - (Expr::Lit(Lit::Str(str_prop)), false) + (Lit::Str(str_prop).into(), false) } - PropName::Num(num) => (Expr::Lit(Lit::Num(num)), true), + PropName::Num(num) => (Lit::Num(num).into(), true), PropName::Computed(computed) => (*computed.expr, true), PropName::BigInt(big_int) => { - (Expr::Lit(Lit::BigInt(big_int)), true) + (Lit::BigInt(big_int).into(), true) } }; @@ -463,7 +463,7 @@ impl FastDts { } ident.optional = true; - param.pat = Pat::Ident(ident.clone()); + param.pat = ident.clone().into(); } Pat::Array(arr_pat) => { if arr_pat.type_ann.is_none() { @@ -475,7 +475,7 @@ impl FastDts { } arr_pat.optional = true; - param.pat = Pat::Array(arr_pat.clone()); + param.pat = arr_pat.clone().into(); } Pat::Object(obj_pat) => { if obj_pat.type_ann.is_none() { @@ -487,7 +487,7 @@ impl FastDts { } obj_pat.optional = true; - param.pat = Pat::Object(obj_pat.clone()); + param.pat = obj_pat.clone().into(); } Pat::Rest(_) | Pat::Assign(_) | Pat::Expr(_) | Pat::Invalid(_) => {} }; @@ -598,7 +598,7 @@ impl FastDts { Expr::Member(member_expr) => self.valid_enum_init_expr(&member_expr.obj), Expr::OptChain(opt_expr) => match &*opt_expr.base { OptChainBase::Member(member_expr) => { - self.valid_enum_init_expr(&Expr::Member(member_expr.clone())) + self.valid_enum_init_expr(&member_expr.clone().into()) } OptChainBase::Call(_) => false, },