From 88a2186ba419c98c73b997ca9ea90d7a8fd128e4 Mon Sep 17 00:00:00 2001 From: Levi Date: Tue, 15 Oct 2024 12:00:39 +1300 Subject: [PATCH] feat(es/minifier): Support unary negate in `cast_to_number` (#9642) **Description:** Adds support for `-` in `cast_to_number`. Before it only worked if `arg` is `Infinity`. Now it uses a recursive call on `arg` so it works for expressions like `-5`, `-[]` etc. This change is important because negative number literals (e.g. `-5`) are a `UnaryExpr` with `op`=`-` & `arg`=`5`, unless you apply `expr_simplifier` pass or something else that uses it. --- .changeset/lazy-ladybugs-jump.md | 6 ++++++ crates/swc_ecma_utils/src/lib.rs | 15 ++++----------- 2 files changed, 10 insertions(+), 11 deletions(-) create mode 100644 .changeset/lazy-ladybugs-jump.md diff --git a/.changeset/lazy-ladybugs-jump.md b/.changeset/lazy-ladybugs-jump.md new file mode 100644 index 000000000000..9bde60378816 --- /dev/null +++ b/.changeset/lazy-ladybugs-jump.md @@ -0,0 +1,6 @@ +--- +swc_ecma_utils: patch +swc_core: patch +--- + +feat(es/minifier): Support unary negate in `cast_to_number` diff --git a/crates/swc_ecma_utils/src/lib.rs b/crates/swc_ecma_utils/src/lib.rs index a93096a861b5..3e5f07b0444d 100644 --- a/crates/swc_ecma_utils/src/lib.rs +++ b/crates/swc_ecma_utils/src/lib.rs @@ -933,17 +933,10 @@ pub trait ExprExt { op: op!(unary, "-"), arg, .. - }) if matches!( - &**arg, - Expr::Ident(Ident { - sym, - ctxt, - .. - }) if &**sym == "Infinity" && *ctxt == ctx.unresolved_ctxt - ) => - { - -f64::INFINITY - } + }) => match arg.cast_to_number(ctx) { + (Pure, Known(v)) => -v, + _ => return (MayBeImpure, Unknown), + }, Expr::Unary(UnaryExpr { op: op!("!"), ref arg,