From 4868c73d5bc5eb3ffbbc2fd31c485e3e22795550 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Donny/=EA=B0=95=EB=8F=99=EC=9C=A4?= Date: Sat, 9 Apr 2022 03:08:31 +0900 Subject: [PATCH] fix(es/optimization): Don't create invalid sequence expressions (#4285) --- .../src/simplify/branch/mod.rs | 25 ++++++++++++++++++- .../tests/simplify.rs | 18 +++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) 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 aaa6c948430..73d0a7187f8 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs @@ -82,6 +82,12 @@ impl VisitMut for Remover { e.visit_mut_children_with(self); match e { + Expr::Seq(s) => { + if s.exprs.is_empty() { + *e = Expr::dummy(); + } + } + Expr::Assign(AssignExpr { op: op!("="), left: PatOrExpr::Pat(l), @@ -154,6 +160,19 @@ impl VisitMut for Remover { *e = *cond.cons.take(); } + Expr::Bin(be) => match (be.left.is_invalid(), be.right.is_invalid()) { + (true, true) => { + *e = Expr::dummy(); + } + (true, false) => { + *e = *be.right.take(); + } + (false, true) => { + *e = *be.left.take(); + } + _ => {} + }, + _ => {} } } @@ -189,7 +208,7 @@ impl VisitMut for Remover { if cfg!(feature = "debug") { debug!("Removing dead branches"); } - self.fold_stmt_like(n) + self.fold_stmt_like(n); } fn visit_mut_object_pat(&mut self, p: &mut ObjectPat) { @@ -1483,6 +1502,10 @@ fn ignore_result(e: Expr) -> Option { exprs.extend(last); + if exprs.is_empty() { + return None; + } + Some(Expr::Seq(SeqExpr { span, exprs })) } diff --git a/crates/swc_ecma_transforms_optimization/tests/simplify.rs b/crates/swc_ecma_transforms_optimization/tests/simplify.rs index 17e85ca00c2..c3c782397c6 100644 --- a/crates/swc_ecma_transforms_optimization/tests/simplify.rs +++ b/crates/swc_ecma_transforms_optimization/tests/simplify.rs @@ -631,6 +631,24 @@ test!( " ); +test!( + Syntax::default(), + |_| dead_branch_remover(), + issue_4272, + " + function oe() { + var e, t; + return t !== i && (e, t = t), e = t; + } + ", + " + function oe() { + var e, t; + return e = t; + } + " +); + test!( Syntax::default(), |_| chain!(