mirror of
https://github.com/danbulant/oxc
synced 2026-05-19 04:08:41 +00:00
feat(minifier): fold ambiguous if else (#8415)
This commit is contained in:
parent
fb2acd87b3
commit
5b5b8443f4
3 changed files with 43 additions and 2 deletions
|
|
@ -1,4 +1,5 @@
|
|||
use oxc_ast::ast::*;
|
||||
use oxc_span::GetSpan;
|
||||
use oxc_syntax::scope::ScopeFlags;
|
||||
use oxc_traverse::{traverse_mut_with_ctx, ReusableTraverseCtx, Traverse, TraverseCtx};
|
||||
|
||||
|
|
@ -23,8 +24,12 @@ impl<'a> CompressorPass<'a> for Normalize {
|
|||
|
||||
impl<'a> Traverse<'a> for Normalize {
|
||||
fn exit_statement(&mut self, stmt: &mut Statement<'a>, ctx: &mut TraverseCtx<'a>) {
|
||||
if matches!(stmt, Statement::WhileStatement(_)) {
|
||||
Self::convert_while_to_for(stmt, ctx);
|
||||
match stmt {
|
||||
Statement::WhileStatement(_) => {
|
||||
Self::convert_while_to_for(stmt, ctx);
|
||||
}
|
||||
Statement::IfStatement(s) => Self::wrap_to_avoid_ambiguous_else(s, ctx),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -68,6 +73,22 @@ impl<'a> Normalize {
|
|||
ctx.ast.expression_numeric_literal(ident.span, value, None, NumberBase::Decimal);
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap to avoid ambiguous else.
|
||||
// `if (foo) if (bar) baz else quaz` -> `if (foo) { if (bar) baz else quaz }`
|
||||
fn wrap_to_avoid_ambiguous_else(if_stmt: &mut IfStatement<'a>, ctx: &mut TraverseCtx<'a>) {
|
||||
if let Statement::IfStatement(if2) = &mut if_stmt.consequent {
|
||||
if if2.alternate.is_some() {
|
||||
let scope_id = ctx.create_child_scope_of_current(ScopeFlags::empty());
|
||||
if_stmt.consequent =
|
||||
Statement::BlockStatement(ctx.ast.alloc_block_statement_with_scope_id(
|
||||
if_stmt.consequent.span(),
|
||||
ctx.ast.vec1(ctx.ast.move_statement(&mut if_stmt.consequent)),
|
||||
scope_id,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -13,6 +13,25 @@ fn test_same(source_text: &str) {
|
|||
|
||||
// Oxc Integration Tests
|
||||
|
||||
#[test]
|
||||
fn integration() {
|
||||
test(
|
||||
"function writeInteger(int) {
|
||||
if (int >= 0)
|
||||
if (int <= 0xffffffff)
|
||||
return this.u32(int);
|
||||
else if (int > -0x80000000)
|
||||
return this.n32(int);
|
||||
}",
|
||||
"function writeInteger(int) {
|
||||
if (int >= 0) {
|
||||
if (int <= 4294967295) return this.u32(int);
|
||||
if (int > -2147483648) return this.n32(int);
|
||||
}
|
||||
}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test] // https://github.com/oxc-project/oxc/issues/4341
|
||||
fn tagged_template() {
|
||||
test_same("(1, o.f)()");
|
||||
|
|
|
|||
|
|
@ -98,6 +98,7 @@ pub fn run() -> Result<(), io::Error> {
|
|||
let save_path = Path::new("./target/minifier").join(marker);
|
||||
|
||||
for file in files.files() {
|
||||
println!("{}", &file.file_name);
|
||||
let minified = minify_twice(file);
|
||||
|
||||
fs::create_dir_all(&save_path).unwrap();
|
||||
|
|
|
|||
Loading…
Reference in a new issue