Skip to content

Commit

Permalink
fix(minifier): handle arrow fn expressions correctly in `is_in_boolea…
Browse files Browse the repository at this point in the history
…n_context` (#8260)

`var k = () => !!x` was incorrectly being minified to `var k = () => x`
  • Loading branch information
camc314 committed Jan 6, 2025
1 parent 7f19211 commit 62a2644
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,15 +480,24 @@ impl<'a> PeepholeMinimizeConditions {
// inside the `if` stmt, `condition` is coerced to a boolean
// whereas inside the return, it is not
fn is_in_boolean_context(ctx: &mut TraverseCtx<'_>) -> bool {
for ancestor in ctx.ancestors() {
let mut ancestors = ctx.ancestors().peekable();
while let Some(ancestor) = ancestors.next() {
match ancestor {
Ancestor::IfStatementTest(_)
| Ancestor::WhileStatementTest(_)
| Ancestor::ForStatementTest(_)
| Ancestor::DoWhileStatementTest(_)
| Ancestor::ExpressionStatementExpression(_)
| Ancestor::SequenceExpressionExpressions(_)
| Ancestor::ProgramBody(_) => return true,
// `var k = () => foo`, `foo` is not coerced to a boolean
Ancestor::ExpressionStatementExpression(_) => {
if let Some(next_ancestor) = ancestors.peek() {
match next_ancestor {
Ancestor::FunctionBodyStatements(_) => return false,
_ => return true,
}
}
}
Ancestor::CallExpressionArguments(_)
| Ancestor::AssignmentPatternRight(_)
| Ancestor::BindingRestElementArgument(_)
Expand All @@ -503,6 +512,7 @@ impl<'a> PeepholeMinimizeConditions {
_ => continue,
}
}

true
}

Expand Down Expand Up @@ -867,6 +877,8 @@ mod test {
fold("foo ? bar : bar", "foo, bar");
fold_same("foo ? bar : baz");
fold("foo() ? bar : bar", "foo(), bar");

test_same("var k = () => !!x;");
}

#[test]
Expand Down

0 comments on commit 62a2644

Please sign in to comment.