From f000596edf39d0aa2b1c5ec37e5bf56f745fb632 Mon Sep 17 00:00:00 2001 From: camc314 <18101008+camc314@users.noreply.github.com> Date: Mon, 6 Jan 2025 02:21:28 +0000 Subject: [PATCH] feat(minifier): minify call expressionsto `Number` (#8267) --- crates/oxc_ecmascript/src/to_number.rs | 4 ++++ .../peephole_substitute_alternate_syntax.rs | 23 ++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/oxc_ecmascript/src/to_number.rs b/crates/oxc_ecmascript/src/to_number.rs index 927f90693cb86..34bfa90863cb9 100644 --- a/crates/oxc_ecmascript/src/to_number.rs +++ b/crates/oxc_ecmascript/src/to_number.rs @@ -28,6 +28,10 @@ impl<'a> ToNumber<'a> for Expression<'a> { use crate::StringToNumber; Some(lit.value.as_str().string_to_number()) } + Expression::UnaryExpression(unary) if unary.operator.is_not() => { + let number = unary.argument.to_number()?; + Some(if number == 0.0 { 1.0 } else { 0.0 }) + } _ => None, } } diff --git a/crates/oxc_minifier/src/ast_passes/peephole_substitute_alternate_syntax.rs b/crates/oxc_minifier/src/ast_passes/peephole_substitute_alternate_syntax.rs index 328fb0609bcf2..dba1cde889e25 100644 --- a/crates/oxc_minifier/src/ast_passes/peephole_substitute_alternate_syntax.rs +++ b/crates/oxc_minifier/src/ast_passes/peephole_substitute_alternate_syntax.rs @@ -1,6 +1,6 @@ use oxc_allocator::Vec; use oxc_ast::{ast::*, NONE}; -use oxc_ecmascript::{constant_evaluation::ConstantEvaluation, ToInt32, ToJsString}; +use oxc_ecmascript::{constant_evaluation::ConstantEvaluation, ToInt32, ToJsString, ToNumber}; use oxc_semantic::IsGlobalReference; use oxc_span::{GetSpan, SPAN}; use oxc_syntax::{ @@ -671,6 +671,19 @@ impl<'a, 'b> PeepholeSubstituteAlternateSyntax { BinaryOperator::Addition, ctx.ast.move_expression(arg), )) + } else if call_expr.callee.is_global_reference_name("Number", ctx.symbols()) { + let number = call_expr + .arguments + .get_mut(0) + .and_then(|arg| arg.as_expression_mut())? + .to_number()?; + + Some(ctx.ast.expression_numeric_literal( + call_expr.span, + number, + None, + NumberBase::Decimal, + )) } else { None } @@ -1373,4 +1386,12 @@ mod test { test("f(...[1,,,3])", "f(1, void 0, void 0, 3)"); test("f(a, ...[])", "f(a)"); } + + #[test] + fn test_fold_number_call() { + test("Number(0)", "0"); + test("Number(true)", "1"); + test("Number(false)", "0"); + test("Number('foo')", "NaN"); + } }