Skip to content

Commit

Permalink
feat(es/minifier): Support unary negate in cast_to_number (#9642)
Browse files Browse the repository at this point in the history
**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.
  • Loading branch information
levi-nz authored Oct 14, 2024
1 parent 085bc19 commit 88a2186
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
6 changes: 6 additions & 0 deletions .changeset/lazy-ladybugs-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
swc_ecma_utils: patch
swc_core: patch
---

feat(es/minifier): Support unary negate in `cast_to_number`
15 changes: 4 additions & 11 deletions crates/swc_ecma_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 88a2186

Please sign in to comment.