Skip to content

Commit a2906d8

Browse files
committed
feat(minifier): enhance merge similar if stmts
1 parent 934c75c commit a2906d8

2 files changed

Lines changed: 29 additions & 6 deletions

File tree

crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -258,9 +258,35 @@ impl<'a> PeepholeMinimizeConditions {
258258
if_stmt.test = test;
259259
stmts[i] = Statement::IfStatement(if_stmt);
260260
self.changed = true;
261+
} else if next_if
262+
.alternate
263+
.as_ref()
264+
.is_some_and(|alternate| alternate.content_eq(then_branch))
265+
{
266+
// `if (x) return 1; if (y) foo() else return 1;` -> `if (!x&&y) foo() else return 1;`
267+
let Statement::IfStatement(mut if_stmt) = ctx.ast.move_statement(current_node)
268+
else {
269+
unreachable!()
270+
};
271+
let Statement::IfStatement(mut next) = ctx.ast.move_statement(next_node) else {
272+
unreachable!()
273+
};
274+
let test = ctx.ast.expression_logical(
275+
next.test.span(),
276+
ctx.ast.expression_unary(
277+
if_stmt.test.span(),
278+
UnaryOperator::LogicalNot,
279+
ctx.ast.move_expression(&mut if_stmt.test),
280+
),
281+
LogicalOperator::And,
282+
ctx.ast.move_expression(&mut next.test),
283+
);
284+
if_stmt.test = test;
285+
if_stmt.consequent = ctx.ast.move_statement(&mut next.consequent);
286+
if_stmt.alternate = next.alternate.take();
287+
stmts[i] = Statement::IfStatement(if_stmt);
288+
self.changed = true;
261289
}
262-
263-
// TODO: `if (x) return 1; if (y) foo() else return 1;` -> `if (!x&&y) foo() else return 1;`
264290
} else if next_node.as_deref().is_some_and(Self::is_return_expression)
265291
&& else_branch.is_none()
266292
&& Self::is_return_block(then_branch)
@@ -994,7 +1020,6 @@ mod test {
9941020
}
9951021

9961022
#[test]
997-
#[ignore]
9981023
fn test_combine_ifs1() {
9991024
fold(
10001025
"function f() {if (x) return 1; if (y) foo(); else return 1}",
@@ -1003,7 +1028,6 @@ mod test {
10031028
}
10041029

10051030
#[test]
1006-
#[ignore]
10071031
fn test_combine_ifs2() {
10081032
fold(
10091033
"function f() {if (x) throw 1; if (y) throw 1}",
@@ -1020,7 +1044,6 @@ mod test {
10201044
}
10211045

10221046
#[test]
1023-
#[ignore]
10241047
fn test_combine_ifs3() {
10251048
fold_same("function f() {if (x) return 1; if (y) {g();f()}}");
10261049
}

tasks/minsize/minsize.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Original | minified | minified | gzip | gzip | Fixture
1717

1818
1.25 MB | 652.73 kB | 646.76 kB | 163.55 kB | 163.73 kB | three.js
1919

20-
2.14 MB | 725.66 kB | 724.14 kB | 180.08 kB | 181.07 kB | victory.js
20+
2.14 MB | 725.63 kB | 724.14 kB | 180.07 kB | 181.07 kB | victory.js
2121

2222
3.20 MB | 1.01 MB | 1.01 MB | 331.78 kB | 331.56 kB | echarts.js
2323

0 commit comments

Comments
 (0)