Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(minifier): fold void 1 -> void 0 #5670

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion crates/oxc_ast/src/ast_builder_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,16 @@ impl<'a> AstBuilder<'a> {

/* ---------- Constructors ---------- */

/// `0`
#[inline]
pub fn number_0(self) -> Expression<'a> {
self.expression_numeric_literal(Span::default(), 0.0, "0", NumberBase::Decimal)
}

/// `void 0`
#[inline]
pub fn void_0(self) -> Expression<'a> {
let num = self.expression_numeric_literal(Span::default(), 0.0, "0", NumberBase::Decimal);
let num = self.number_0();
Expression::UnaryExpression(self.alloc(self.unary_expression(
Span::default(),
UnaryOperator::Void,
Expand Down
16 changes: 15 additions & 1 deletion crates/oxc_minifier/src/ast_passes/fold_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! <https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/PeepholeFoldConstants.java>

use std::cmp::Ordering;
use std::{cmp::Ordering, mem};

use num_bigint::BigInt;
use oxc_ast::{ast::*, AstBuilder, Visit};
Expand Down Expand Up @@ -166,6 +166,7 @@ impl<'a> FoldConstants<'a> {
ctx: &mut TraverseCtx<'a>,
) -> Option<Expression<'a>> {
match expr.operator {
UnaryOperator::Void => Self::try_reduce_void(expr, ctx),
UnaryOperator::Typeof => self.try_fold_type_of(expr, ctx),
UnaryOperator::LogicalNot => {
expr.argument.to_boolean().map(|b| self.ast.expression_boolean_literal(SPAN, !b))
Expand All @@ -182,6 +183,19 @@ impl<'a> FoldConstants<'a> {
}
}

/// `void 1` -> `void 0`
fn try_reduce_void(
expr: &mut UnaryExpression<'a>,
ctx: &mut TraverseCtx<'a>,
) -> Option<Expression<'a>> {
if (!expr.argument.is_number() || !expr.argument.is_number_0())
&& !expr.may_have_side_effects()
{
let _ = mem::replace(&mut expr.argument, ctx.ast.number_0());
}
None
}

/// Folds 'typeof(foo)' if foo is a literal, e.g.
/// `typeof("bar") --> "string"`
/// `typeof(6) --> "number"`
Expand Down
1 change: 0 additions & 1 deletion crates/oxc_minifier/tests/ast_passes/fold_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,6 @@ fn test_fold_logical_op2() {
}

#[test]
#[ignore]
fn test_fold_void() {
test_same("void 0");
test("void 1", "void 0");
Expand Down