Skip to content

Commit

Permalink
fix(minifier): keep side effects when folding const conditional exprs (
Browse files Browse the repository at this point in the history
  • Loading branch information
camc314 committed Jan 19, 2025
1 parent 8f5be07 commit 93d643e
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions crates/oxc_minifier/src/ast_passes/peephole_remove_dead_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,8 +495,24 @@ impl<'a, 'b> PeepholeRemoveDeadCode {
}

match ctx.get_boolean_value(&expr.test) {
Some(true) => Some(ctx.ast.move_expression(&mut expr.consequent)),
Some(false) => Some(ctx.ast.move_expression(&mut expr.alternate)),
Some(v) => {
if expr.test.may_have_side_effects() {
let mut exprs = ctx.ast.vec_with_capacity(2);
exprs.push(ctx.ast.move_expression(&mut expr.test));
exprs.push(ctx.ast.move_expression(if v {
&mut expr.consequent
} else {
&mut expr.alternate
}));
Some(ctx.ast.expression_sequence(expr.span, exprs))
} else {
Some(ctx.ast.move_expression(if v {
&mut expr.consequent
} else {
&mut expr.alternate
}))
}
}
None => None,
}
}
Expand Down Expand Up @@ -782,6 +798,14 @@ mod test {
test("if (true) {}", "");
}

#[test]
fn test_fold_conditional() {
test("true ? foo() : bar()", "foo()");
test("false ? foo() : bar()", "bar()");
test_same("foo() ? bar() : baz()");
test("foo && false ? foo() : bar()", "(foo && false, bar());");
}

#[test]
fn test_fold_iife() {
fold_same("var k = () => {}");
Expand Down

0 comments on commit 93d643e

Please sign in to comment.