mirror of
https://github.com/danbulant/oxc
synced 2026-05-19 12:19:15 +00:00
refactor(minifier): clean up try_optimize_block (#8139)
This commit is contained in:
parent
2b2a37347c
commit
75264ed7d6
1 changed files with 21 additions and 22 deletions
|
|
@ -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) => {
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
Loading…
Reference in a new issue