feat(minifier): complete MangleIf (#8810)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
This commit is contained in:
Boshen 2025-02-02 17:21:17 +08:00 committed by GitHub
parent 0afbc7b2bd
commit d55331815d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 244 additions and 188 deletions

View file

@ -953,13 +953,15 @@ impl Statement<'_> {
/// - `continue` => `true`
/// - `if (true) { }` => `false`
pub fn is_jump_statement(&self) -> bool {
matches!(
self,
Self::ReturnStatement(_)
| Self::ThrowStatement(_)
| Self::BreakStatement(_)
| Self::ContinueStatement(_)
)
self.get_one_child().is_some_and(|stmt| {
matches!(
stmt,
Self::ReturnStatement(_)
| Self::ThrowStatement(_)
| Self::BreakStatement(_)
| Self::ContinueStatement(_)
)
})
}
/// Returns the single statement from block statement, or self

View file

@ -4,8 +4,8 @@ use oxc_ecmascript::{
ToInt32,
};
use oxc_span::{cmp::ContentEq, GetSpan};
use oxc_syntax::es_target::ESTarget;
use oxc_traverse::Ancestor;
use oxc_syntax::{es_target::ESTarget, scope::ScopeFlags};
use oxc_traverse::{Ancestor, TraverseCtx};
use crate::ctx::Ctx;
@ -19,11 +19,7 @@ use super::PeepholeOptimizations;
///
/// <https://github.com/google/closure-compiler/blob/v20240609/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java>
impl<'a> PeepholeOptimizations {
pub fn minimize_conditions_exit_statement(
&mut self,
stmt: &mut Statement<'a>,
ctx: Ctx<'a, '_>,
) {
pub fn minimize_conditions_exit_statement(stmt: &mut Statement<'a>, ctx: Ctx<'a, '_>) {
let expr = match stmt {
Statement::IfStatement(s) => Some(&mut s.test),
Statement::WhileStatement(s) => Some(&mut s.test),
@ -43,15 +39,6 @@ impl<'a> PeepholeOptimizations {
if let Some(expr) = expr {
Self::try_fold_expr_in_boolean_context(expr, ctx);
}
if let Some(folded_stmt) = match stmt {
// If the condition is a literal, we'll let other optimizations try to remove useless code.
Statement::IfStatement(_) => self.try_minimize_if(stmt, ctx),
_ => None,
} {
*stmt = folded_stmt;
self.mark_current_function_as_changed();
};
}
pub fn minimize_conditions_exit_expression(
@ -146,125 +133,146 @@ impl<'a> PeepholeOptimizations {
}
/// `MangleIf`: <https://github.com/evanw/esbuild/blob/v0.24.2/internal/js_parser/js_parser.go#L9860>
fn try_minimize_if(&self, stmt: &mut Statement<'a>, ctx: Ctx<'a, '_>) -> Option<Statement<'a>> {
let Statement::IfStatement(if_stmt) = stmt else { unreachable!() };
// `if (x) foo()` -> `x && foo()`
if !if_stmt.test.is_literal() {
let then_branch = &if_stmt.consequent;
let else_branch = &if_stmt.alternate;
match else_branch {
None => {
if Self::is_foldable_express_block(&if_stmt.consequent) {
let right = Self::get_block_expression(&mut if_stmt.consequent, ctx);
let test = ctx.ast.move_expression(&mut if_stmt.test);
// `if(!x) foo()` -> `x || foo()`
if let Expression::UnaryExpression(unary_expr) = test {
if unary_expr.operator.is_not() {
let left = unary_expr.unbox().argument;
let logical_expr = ctx.ast.expression_logical(
if_stmt.span,
left,
LogicalOperator::Or,
right,
);
return Some(
ctx.ast.statement_expression(if_stmt.span, logical_expr),
);
}
} else {
// `if(x) foo()` -> `x && foo()`
let logical_expr = ctx.ast.expression_logical(
if_stmt.span,
test,
LogicalOperator::And,
right,
);
return Some(ctx.ast.statement_expression(if_stmt.span, logical_expr));
}
} else {
// `if (x) if (y) z` -> `if (x && y) z`
if let Some(Statement::IfStatement(then_if_stmt)) =
then_branch.get_one_child()
{
if then_if_stmt.alternate.is_none() {
let and_left = ctx.ast.move_expression(&mut if_stmt.test);
let Some(then_if_stmt) = if_stmt.consequent.get_one_child_mut()
else {
unreachable!()
};
let Statement::IfStatement(mut then_if_stmt) =
ctx.ast.move_statement(then_if_stmt)
else {
unreachable!()
};
let and_right = ctx.ast.move_expression(&mut then_if_stmt.test);
then_if_stmt.test = ctx.ast.expression_logical(
and_left.span(),
and_left,
LogicalOperator::And,
and_right,
);
return Some(Statement::IfStatement(then_if_stmt));
}
}
pub fn try_minimize_if(
&mut self,
if_stmt: &mut IfStatement<'a>,
traverse_ctx: &mut TraverseCtx<'a>,
) -> Option<Statement<'a>> {
self.wrap_to_avoid_ambiguous_else(if_stmt, traverse_ctx);
let ctx = Ctx(traverse_ctx);
if let Statement::ExpressionStatement(expr_stmt) = &mut if_stmt.consequent {
if if_stmt.alternate.is_none() {
let (op, e) = match &mut if_stmt.test {
// "if (!a) b();" => "a || b();"
Expression::UnaryExpression(unary_expr) if unary_expr.operator.is_not() => {
(LogicalOperator::Or, &mut unary_expr.argument)
}
}
Some(else_branch) => {
let then_branch_is_expression_block =
Self::is_foldable_express_block(then_branch);
let else_branch_is_expression_block =
Self::is_foldable_express_block(else_branch);
// `if(foo) bar else baz` -> `foo ? bar : baz`
if then_branch_is_expression_block && else_branch_is_expression_block {
let test = ctx.ast.move_expression(&mut if_stmt.test);
let consequent = Self::get_block_expression(&mut if_stmt.consequent, ctx);
let else_branch = if_stmt.alternate.as_mut().unwrap();
let alternate = Self::get_block_expression(else_branch, ctx);
let expr = self.minimize_conditional(
if_stmt.span,
test,
consequent,
alternate,
// "if (a) b();" => "a && b();"
e => (LogicalOperator::And, e),
};
let a = ctx.ast.move_expression(e);
let b = ctx.ast.move_expression(&mut expr_stmt.expression);
let expr = Self::join_with_left_associative_op(if_stmt.span, op, a, b, ctx);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
} else if let Some(Statement::ExpressionStatement(alternate_expr_stmt)) =
&mut if_stmt.alternate
{
// "if (a) b(); else c();" => "a ? b() : c();"
let test = ctx.ast.move_expression(&mut if_stmt.test);
let consequent = ctx.ast.move_expression(&mut expr_stmt.expression);
let alternate = ctx.ast.move_expression(&mut alternate_expr_stmt.expression);
let expr =
self.minimize_conditional(if_stmt.span, test, consequent, alternate, ctx);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
}
} else if Self::is_statement_empty(&if_stmt.consequent) {
if if_stmt.alternate.is_none()
|| if_stmt.alternate.as_ref().is_some_and(Self::is_statement_empty)
{
// "if (a) {}" => "a;"
let expr = ctx.ast.move_expression(&mut if_stmt.test);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
} else if let Some(Statement::ExpressionStatement(expr_stmt)) = &mut if_stmt.alternate {
let (op, e) = match &mut if_stmt.test {
// "if (!a) {} else b();" => "a && b();"
Expression::UnaryExpression(unary_expr) if unary_expr.operator.is_not() => {
(LogicalOperator::And, &mut unary_expr.argument)
}
// "if (a) {} else b();" => "a || b();"
e => (LogicalOperator::Or, e),
};
let a = ctx.ast.move_expression(e);
let b = ctx.ast.move_expression(&mut expr_stmt.expression);
let expr = Self::join_with_left_associative_op(if_stmt.span, op, a, b, ctx);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
} else if let Some(stmt) = &mut if_stmt.alternate {
// "yes" is missing and "no" is not missing (and is not an expression)
match &mut if_stmt.test {
// "if (!a) {} else return b;" => "if (a) return b;"
Expression::UnaryExpression(unary_expr) if unary_expr.operator.is_not() => {
if_stmt.test = ctx.ast.move_expression(&mut unary_expr.argument);
if_stmt.consequent = ctx.ast.move_statement(stmt);
if_stmt.alternate = None;
self.mark_current_function_as_changed();
}
// "if (a) {} else return b;" => "if (!a) return b;"
_ => {
if_stmt.test = Self::minimize_not(
if_stmt.test.span(),
ctx.ast.move_expression(&mut if_stmt.test),
ctx,
);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
if_stmt.consequent = ctx.ast.move_statement(stmt);
if_stmt.alternate = None;
self.mark_current_function_as_changed();
}
}
}
} else {
// "yes" is not missing (and is not an expression)
if let Some(alternate) = &mut if_stmt.alternate {
// "yes" is not missing (and is not an expression) and "no" is not missing
if let Expression::UnaryExpression(unary_expr) = &mut if_stmt.test {
if unary_expr.operator.is_not() {
// "if (!a) return b; else return c;" => "if (a) return c; else return b;"
if_stmt.test = ctx.ast.move_expression(&mut unary_expr.argument);
std::mem::swap(&mut if_stmt.consequent, alternate);
self.wrap_to_avoid_ambiguous_else(if_stmt, traverse_ctx);
self.mark_current_function_as_changed();
}
}
// "if (a) return b; else {}" => "if (a) return b;" is handled by remove_dead_code
} else {
// "no" is missing
if let Statement::IfStatement(if2_stmt) = &mut if_stmt.consequent {
if if2_stmt.alternate.is_none() {
// "if (a) if (b) return c;" => "if (a && b) return c;"
let a = ctx.ast.move_expression(&mut if_stmt.test);
let b = ctx.ast.move_expression(&mut if2_stmt.test);
if_stmt.test = Self::join_with_left_associative_op(
if_stmt.test.span(),
LogicalOperator::And,
a,
b,
ctx,
);
if_stmt.consequent = ctx.ast.move_statement(&mut if2_stmt.consequent);
self.mark_current_function_as_changed();
}
}
}
}
// `if (x) {} else foo` -> `if (!x) foo`
if match &if_stmt.consequent {
Statement::EmptyStatement(_) => true,
Statement::BlockStatement(block_stmt) => block_stmt.body.is_empty(),
_ => false,
} && if_stmt.alternate.is_some()
{
return Some(ctx.ast.statement_if(
if_stmt.span,
ctx.ast.expression_unary(
if_stmt.test.span(),
UnaryOperator::LogicalNot,
ctx.ast.move_expression(&mut if_stmt.test),
),
ctx.ast.move_statement(if_stmt.alternate.as_mut().unwrap()),
None,
));
}
None
}
fn is_foldable_express_block(stmt: &Statement<'a>) -> bool {
matches!(stmt.get_one_child(), Some(Statement::ExpressionStatement(_)))
/// Wrap to avoid ambiguous else.
/// `if (foo) if (bar) baz else quaz` -> `if (foo) { if (bar) baz else quaz }`
fn wrap_to_avoid_ambiguous_else(
&mut self,
if_stmt: &mut IfStatement<'a>,
ctx: &mut TraverseCtx<'a>,
) {
if let Statement::IfStatement(if2) = &mut if_stmt.consequent {
if if2.consequent.is_jump_statement() && if2.alternate.is_some() {
let scope_id = ctx.create_child_scope_of_current(ScopeFlags::empty());
if_stmt.consequent = Statement::BlockStatement(ctx.ast.alloc(
ctx.ast.block_statement_with_scope_id(
if_stmt.consequent.span(),
ctx.ast.vec1(ctx.ast.move_statement(&mut if_stmt.consequent)),
scope_id,
),
));
self.mark_current_function_as_changed();
}
}
}
fn get_block_expression(stmt: &mut Statement<'a>, ctx: Ctx<'a, '_>) -> Expression<'a> {
let Some(Statement::ExpressionStatement(s)) = stmt.get_one_child_mut() else {
unreachable!()
};
ctx.ast.move_expression(&mut s.expression)
fn is_statement_empty(stmt: &Statement<'a>) -> bool {
match stmt {
Statement::BlockStatement(block_stmt) if block_stmt.body.is_empty() => true,
Statement::EmptyStatement(_) => true,
_ => false,
}
}
pub fn minimize_conditional(
@ -1778,8 +1786,20 @@ mod test {
}
#[test]
fn test_no_swap_with_dangling_else() {
test_same("if(!x) {for(;;)foo(); for(;;)bar()} else if(y) for(;;) f()");
fn test_dangling_else() {
test(
"
if (!x) {
for (;;) foo();
for (;;) bar();
} else if (y) for (;;) f();",
"
if (x) {
if (y) for (; ; ) f();
} else {
for (; ; ) foo();
for (; ; ) bar();}",
);
test_same("if(!a&&!b) {for(;;)foo(); for(;;)bar()} else if(y) for(;;) f()");
}
@ -2675,4 +2695,66 @@ mod test {
run(code, None)
);
}
#[test]
fn test_minimize_if() {
test(
"function writeInteger(int) {
if (int >= 0)
if (int <= 0xffffffff) return this.u32(int);
else if (int > -0x80000000) return this.n32(int);
}",
"function writeInteger(int) {
if (int >= 0) {
if (int <= 4294967295) return this.u32(int);
if (int > -2147483648) return this.n32(int);
}
}",
);
test(
"function bar() {
if (!x) {
return null;
} else if (y) {
return foo;
} else if (z) {
return bar;
}
}",
"function bar() {
if (x) {
if (y)
return foo;
if (z)
return bar;
} else return null;
}",
);
test(
"function f() {
if (foo)
if (bar) return X;
else return Y;
return Z;
}",
"function f() {
return foo ? bar ? X : Y : Z;
}",
);
test(
"function _() {
if (currentChar === '\\n')
return pos + 1;
else if (currentChar !== ' ' && currentChar !== '\\t')
return pos + 1;
}",
"function _() {
if (currentChar === '\\n' || currentChar !== ' ' && currentChar !== '\\t')
return pos + 1;
}",
);
}
}

View file

@ -141,14 +141,19 @@ impl<'a> Traverse<'a> for PeepholeOptimizations {
self.minimize_statements(stmts, ctx);
}
fn exit_statement(&mut self, stmt: &mut Statement<'a>, ctx: &mut TraverseCtx<'a>) {
fn exit_statement(&mut self, stmt: &mut Statement<'a>, traverse_ctx: &mut TraverseCtx<'a>) {
if !self.is_prev_function_changed() {
return;
}
let ctx = Ctx(ctx);
self.minimize_conditions_exit_statement(stmt, ctx);
self.remove_dead_code_exit_statement(stmt, ctx);
self.substitute_exit_statement(stmt, ctx);
Self::minimize_conditions_exit_statement(stmt, Ctx(traverse_ctx));
self.remove_dead_code_exit_statement(stmt, Ctx(traverse_ctx));
if let Statement::IfStatement(if_stmt) = stmt {
if let Some(folded_stmt) = self.try_minimize_if(if_stmt, traverse_ctx) {
*stmt = folded_stmt;
self.mark_current_function_as_changed();
}
}
self.substitute_exit_statement(stmt, Ctx(traverse_ctx));
}
fn exit_return_statement(&mut self, stmt: &mut ReturnStatement<'a>, ctx: &mut TraverseCtx<'a>) {

View file

@ -177,19 +177,17 @@ impl<'a, 'b> PeepholeOptimizations {
_ => {}
}
// `if (test) {}` -> `test`
if if_stmt.alternate.is_none()
&& match &if_stmt.consequent {
Statement::EmptyStatement(_) => true,
Statement::BlockStatement(s) => s.body.is_empty(),
_ => false,
}
{
let expr = ctx.ast.move_expression(&mut if_stmt.test);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
}
if let Some(boolean) = ctx.get_side_free_boolean_value(&if_stmt.test) {
// Use "1" and "0" instead of "true" and "false" to be shorter.
// And also prevent swapping consequent and alternate when `!0` is encourtnered.
if let Expression::BooleanLiteral(b) = &if_stmt.test {
if_stmt.test = ctx.ast.expression_numeric_literal(
b.span,
if b.value { 1.0 } else { 0.0 },
None,
NumberBase::Decimal,
);
}
let mut keep_var = KeepVar::new(ctx.ast);
if boolean {
if let Some(alternate) = &if_stmt.alternate {

View file

@ -18,8 +18,7 @@ mod test {
#[test]
fn fold_block_into_if() {
test("a;b;c;if(x){}", "a,b,c,x");
// FIXME: remove last `!`
test("a;b;c;if(x,y){}else{}", "a, b, c, x, !y");
test("a;b;c;if(x,y){}else{}", "a, b, c, x, y");
test("a;b;c;if(x,y){}", "a, b, c, x, y");
test("a;b;c;if(x,y,z){}", "a, b, c, x, y, z");
test("a();if(a()){}a()", "a(), a(), a()");

View file

@ -60,7 +60,7 @@ fn dce_if_statement() {
);
test(
"if (xxx) { foo } else if (false) { var a; var b; } else if (false) { var c; var d; }",
"if (xxx) foo; else if (false) var a, b; else if (false) var c, d;",
"if (xxx) foo; else if (0) var a, b; else if (0) var c, d;",
);
test("if (!false) { foo }", "foo");

View file

@ -16,23 +16,6 @@ fn test_same(source_text: &str) {
#[test]
fn integration() {
// FIXME
// test(
// "function writeInteger(int) {
// if (int >= 0)
// if (int <= 0xffffffff)
// return this.u32(int);
// else if (int > -0x80000000)
// return this.n32(int);
// }",
// "function writeInteger(int) {
// if (int >= 0) {
// if (int <= 4294967295) return this.u32(int);
// if (int > -2147483648) return this.n32(int);
// }
// }",
// );
test(
"require('./index.js')(function (e, os) {
if (e) return console.log(e)
@ -76,19 +59,6 @@ fn integration() {
console.log(c, d);
",
);
test(
"function _() {
if (currentChar === '\\n')
return pos + 1;
else if (currentChar !== ' ' && currentChar !== '\\t')
return pos + 1;
}",
"function _() {
if (currentChar === '\\n' || currentChar !== ' ' && currentChar !== '\\t')
return pos + 1;
}",
);
}
#[test]

View file

@ -7,21 +7,21 @@ Original | minified | minified | gzip | gzip | Fixture
287.63 kB | 89.48 kB | 90.07 kB | 30.95 kB | 31.95 kB | jquery.js
342.15 kB | 117.68 kB | 118.14 kB | 43.57 kB | 44.37 kB | vue.js
342.15 kB | 117.68 kB | 118.14 kB | 43.56 kB | 44.37 kB | vue.js
544.10 kB | 71.43 kB | 72.48 kB | 25.87 kB | 26.20 kB | lodash.js
555.77 kB | 271.25 kB | 270.13 kB | 88.35 kB | 90.80 kB | d3.js
1.01 MB | 440.96 kB | 458.89 kB | 122.50 kB | 126.71 kB | bundle.min.js
1.01 MB | 440.97 kB | 458.89 kB | 122.50 kB | 126.71 kB | bundle.min.js
1.25 MB | 650.36 kB | 646.76 kB | 161.01 kB | 163.73 kB | three.js
2.14 MB | 718.61 kB | 724.14 kB | 162.13 kB | 181.07 kB | victory.js
2.14 MB | 718.69 kB | 724.14 kB | 162.15 kB | 181.07 kB | victory.js
3.20 MB | 1.01 MB | 1.01 MB | 324.31 kB | 331.56 kB | echarts.js
3.20 MB | 1.01 MB | 1.01 MB | 324.44 kB | 331.56 kB | echarts.js
6.69 MB | 2.30 MB | 2.31 MB | 468.52 kB | 488.28 kB | antd.js
6.69 MB | 2.30 MB | 2.31 MB | 468.54 kB | 488.28 kB | antd.js
10.95 MB | 3.36 MB | 3.49 MB | 862.11 kB | 915.50 kB | typescript.js
10.95 MB | 3.36 MB | 3.49 MB | 862.14 kB | 915.50 kB | typescript.js