From f81fa6e06335745ff6ab5f7956cecc38116b1343 Mon Sep 17 00:00:00 2001 From: CPunisher <1343316114@qq.com> Date: Thu, 11 Jul 2024 22:29:51 +0800 Subject: [PATCH] fix(es/minifier): Fix case matching (#9208) **Description:** Caused by https://github.com/swc-project/swc/pull/7112 Since swc minifier evaluates expressions in a separate pass, I make a temporary patch here. **Related issue:** - Closes https://github.com/swc-project/swc/issues/9176 --- .../src/compress/optimize/switches.rs | 7 ++++++- .../tests/fixture/issues/9176/input.js | 10 ++++++++++ .../tests/fixture/issues/9176/output.js | 2 ++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 crates/swc_ecma_minifier/tests/fixture/issues/9176/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/issues/9176/output.js diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index f3730f2e84de..0e5791f89467 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -44,7 +44,12 @@ impl Optimizer<'_> { for (idx, case) in stmt.cases.iter_mut().enumerate() { if let Some(test) = case.test.as_ref() { if let Some(e) = is_primitive(&self.expr_ctx, tail_expr(test)) { - if e.eq_ignore_span(tail) { + if match (e, tail) { + (Expr::Lit(Lit::Num(e)), Expr::Lit(Lit::Num(tail))) => { + e.value == tail.value + } + _ => e.eq_ignore_span(tail), + } { cases.push(case.take()); exact = Some(idx); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/9176/input.js b/crates/swc_ecma_minifier/tests/fixture/issues/9176/input.js new file mode 100644 index 000000000000..5516a3c5436c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/issues/9176/input.js @@ -0,0 +1,10 @@ +"use strict"; +const k = (function () { + switch (-0) { + case 0: + console.log("hi"); + break; + default: + throw 0; + } +})(); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/9176/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/9176/output.js new file mode 100644 index 000000000000..5724c24c8e53 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/issues/9176/output.js @@ -0,0 +1,2 @@ +"use strict"; +console.log("hi");