From 951dafbc1a56b8b29fd76aaad8138e58eaadda12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Donny/=EA=B0=95=EB=8F=99=EC=9C=A4?= Date: Wed, 8 Feb 2023 11:10:44 +0900 Subject: [PATCH] fix(es/minifier): Don't break ternary with assignment in test (#6906) **Related issue:** - Closes https://github.com/swc-project/swc/issues/6903. --- .../src/compress/optimize/conditionals.rs | 9 ++- crates/swc_ecma_minifier/tests/exec.rs | 63 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs index 96380db3225c..3b108565d16f 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs @@ -4,7 +4,7 @@ use swc_common::{util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::ext::ExprRefExt; use swc_ecma_transforms_optimization::debug_assert_valid; -use swc_ecma_utils::{ExprExt, ExprFactory, StmtExt, StmtLike}; +use swc_ecma_utils::{ExprExt, ExprFactory, IdentUsageFinder, StmtExt, StmtLike}; use super::Optimizer; use crate::{ @@ -316,6 +316,10 @@ where /// Compress a conditional expression if cons and alt is simillar pub(super) fn compress_cond_expr_if_similar(&mut self, e: &mut Expr) { + if !self.options.conditionals { + return; + } + let cond = match e { Expr::Cond(expr) => expr, _ => return, @@ -368,6 +372,9 @@ where } let cons_callee = cons.callee.as_expr().and_then(|e| e.as_ident())?; + if IdentUsageFinder::find(&cons_callee.to_id(), &**test) { + return None; + } // if !cons.callee.eq_ignore_span(&alt.callee) { diff --git a/crates/swc_ecma_minifier/tests/exec.rs b/crates/swc_ecma_minifier/tests/exec.rs index f6cd217238bd..304711884b34 100644 --- a/crates/swc_ecma_minifier/tests/exec.rs +++ b/crates/swc_ecma_minifier/tests/exec.rs @@ -10758,3 +10758,66 @@ fn issue_6899_5() { false, ); } + +#[test] +fn issue_6903_1() { + run_default_exec_test( + r###" + function test(a, b) { + let wrapper = (e) => e + wrapper = (e) => (["not", e]) + if (a) { + return wrapper(b) + } + return wrapper(1) + } + console.log(test(true, "bad")) + "###, + ); +} + +#[test] +fn issue_6903_2() { + run_exec_test( + r###" + function test(a, b) { + let wrapper = (e) => e + wrapper = (e) => (["not", e]) + if (a) { + return wrapper(b) + } + return wrapper(1) + } + console.log(test(true, "bad")) + "###, + r###" + { + "if_return": true, + "join_vars": true, + "side_effects": true, + "conditionals": true + }"###, + false, + ); +} + +#[test] +fn issue_6903_3() { + run_exec_test( + r###" + function test(a, b) { + let wrapper = (e)=>e; + return ((wrapper = (e)=>[ + "not", + e + ]), a) ? wrapper(b) : wrapper(1); + } + console.log(test(true, "bad")); + "###, + r###" + { + "conditionals": true + }"###, + false, + ); +}