Skip to content

Commit

Permalink
fix(minifier): do not fold if statement block with lexical declaration (
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Nov 28, 2024
1 parent 625a5ba commit 896ff86
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
11 changes: 5 additions & 6 deletions crates/oxc_allocator/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,11 @@ impl<'alloc, T> ops::Index<usize> for Vec<'alloc, T> {
}
}

// Unused right now.
// impl<'alloc, T> ops::IndexMut<usize> for Vec<'alloc, T> {
// fn index_mut(&mut self, index: usize) -> &mut Self::Output {
// self.0.index_mut(index)
// }
// }
impl<'alloc, T> ops::IndexMut<usize> for Vec<'alloc, T> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}

#[cfg(any(feature = "serialize", test))]
impl<'alloc, T> Serialize for Vec<'alloc, T>
Expand Down
21 changes: 17 additions & 4 deletions crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,19 @@ impl<'a> PeepholeMinimizeConditions {
/// Duplicate logic to DCE part.
fn try_fold_if_block_one(&mut self, if_stmt: &mut IfStatement<'a>, ctx: &mut TraverseCtx<'a>) {
if let Statement::BlockStatement(block) = &mut if_stmt.consequent {
if block.body.len() == 1 {
if block.body.len() == 1
&& !matches!(&block.body[0], Statement::VariableDeclaration(decl) if !decl.kind.is_var())
{
self.changed = true;
if_stmt.consequent = ctx.ast.move_statement(block.body.first_mut().unwrap());
if_stmt.consequent = ctx.ast.move_statement(&mut block.body[0]);
}
}
if let Some(Statement::BlockStatement(block)) = &mut if_stmt.alternate {
if block.body.len() == 1 {
if block.body.len() == 1
&& !matches!(&block.body[0], Statement::VariableDeclaration(decl) if !decl.kind.is_var())
{
self.changed = true;
if_stmt.alternate = Some(ctx.ast.move_statement(block.body.first_mut().unwrap()));
if_stmt.alternate = Some(ctx.ast.move_statement(&mut block.body[0]));
}
}
}
Expand Down Expand Up @@ -241,6 +245,15 @@ mod test {
fold_same("function f(){foo()}");
fold_same("switch(x){case y: foo()}");
fold_same("try{foo()}catch(ex){bar()}finally{baz()}");

// Dot not fold `let` and `const`.
// Lexical declaration cannot appear in a single-statement context.
fold_same("if (foo) { const bar = 1 } else { const baz = 1 }");
fold_same("if (foo) { let bar = 1 } else { let baz = 1 }");
fold(
"if (foo) { var bar = 1 } else { var baz = 1 }",
"if (foo) var bar = 1; else var baz = 1;",
);
}

/** Try to minimize returns */
Expand Down

0 comments on commit 896ff86

Please sign in to comment.