Skip to content

Commit

Permalink
refactor(minifier): clean up try_optimize_block (#8139)
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Dec 27, 2024
1 parent 2b2a373 commit 75264ed
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions crates/oxc_minifier/src/ast_passes/peephole_remove_dead_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ impl<'a> CompressorPass<'a> for PeepholeRemoveDeadCode {

impl<'a> Traverse<'a> for PeepholeRemoveDeadCode {
fn exit_statement(&mut self, stmt: &mut Statement<'a>, ctx: &mut TraverseCtx<'a>) {
self.compress_block(stmt, Ctx(ctx));
let ctx = Ctx(ctx);
if let Some(new_stmt) = match stmt {
Statement::BlockStatement(block_stmt) => Self::try_optimize_block(block_stmt, ctx),
Statement::IfStatement(if_stmt) => self.try_fold_if(if_stmt, ctx),
Statement::ForStatement(for_stmt) => self.try_fold_for(for_stmt, ctx),
Statement::ExpressionStatement(expr_stmt) => {
Expand Down Expand Up @@ -126,28 +126,27 @@ impl<'a, 'b> PeepholeRemoveDeadCode {

/// Remove block from single line blocks
/// `{ block } -> block`
fn compress_block(&mut self, stmt: &mut Statement<'a>, ctx: Ctx<'a, 'b>) {
if let Statement::BlockStatement(block) = stmt {
// Avoid compressing `if (x) { var x = 1 }` to `if (x) var x = 1` due to different
// semantics according to AnnexB, which lead to different semantics.
if block.body.len() == 1 && !block.body[0].is_declaration() {
*stmt = block.body.remove(0);
self.compress_block(stmt, ctx);
self.changed = true;
return;
}
if block.body.len() == 0
&& (ctx.parent().is_while_statement()
|| ctx.parent().is_for_statement()
|| ctx.parent().is_for_in_statement()
|| ctx.parent().is_for_of_statement()
|| ctx.parent().is_block_statement()
|| ctx.parent().is_program())
{
// Remove the block if it is empty and the parent is a block statement.
*stmt = ctx.ast.statement_empty(SPAN);
}
fn try_optimize_block(
stmt: &mut BlockStatement<'a>,
ctx: Ctx<'a, 'b>,
) -> Option<Statement<'a>> {
// Avoid compressing `if (x) { var x = 1 }` to `if (x) var x = 1` due to different
// semantics according to AnnexB, which lead to different semantics.
if stmt.body.len() == 1 && !stmt.body[0].is_declaration() {
return Some(stmt.body.remove(0));
}
if stmt.body.len() == 0
&& (ctx.parent().is_while_statement()
|| ctx.parent().is_for_statement()
|| ctx.parent().is_for_in_statement()
|| ctx.parent().is_for_of_statement()
|| ctx.parent().is_block_statement()
|| ctx.parent().is_program())
{
// Remove the block if it is empty and the parent is a block statement.
return Some(ctx.ast.statement_empty(stmt.span));
}
None
}

fn try_fold_if(
Expand Down

0 comments on commit 75264ed

Please sign in to comment.