Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 207 additions & 1 deletion crates/oxc_minifier/src/peephole/minimize_statements.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{iter, ops::ControlFlow};
use std::{cmp::min, iter, ops::ControlFlow};

use oxc_allocator::{Box, TakeIn, Vec};
use oxc_ast::ast::*;
Expand Down Expand Up @@ -407,6 +407,10 @@ impl<'a> PeepholeOptimizations {
ctx.state.changed = true;
}

if Self::simplify_destructuring_assignment(var_decl.kind, &mut var_decl.declarations, ctx) {
ctx.state.changed = true;
}

// If `join_vars` is off, but there are unused declarators ... just join them to make our code simpler.
if !ctx.options().join_vars
&& var_decl.declarations.iter().all(|d| !Self::should_remove_unused_declarator(d, ctx))
Expand Down Expand Up @@ -443,6 +447,169 @@ impl<'a> PeepholeOptimizations {
}
}

/// Simplifies destructuring assignments by transforming array patterns into a sequence of
/// variable declarations, whenever possible. This function modifies the input declarations
/// and returns whether any changes were made.
///
/// - iterates over the given `declarations`, identifying destructuring patterns
/// of the form `[...] = [...]` (arrays assigned to arrays).
/// - cases with `rest` parameters (e.g., `[a, b, ...rest]`) and adjusts the
/// remaining array expression accordingly.
/// - removes invalid patterns, empty assignments (e.g., `[] = []`), and
fn simplify_destructuring_assignment(
kind: VariableDeclarationKind,
declarations: &mut Vec<'a, VariableDeclarator<'a>>,
ctx: &Ctx<'a, '_>,
) -> bool {
if !declarations.iter().any(|decl| {
decl.id.kind.is_array_pattern()
&& matches!(decl.init, Some(Expression::ArrayExpression(_)))
}) {
return false;
}

let mut changed = false;
let mut new_var_decl: Vec<'a, VariableDeclarator<'a>> = ctx.ast.vec();

for mut decl in declarations.drain(..) {
// Check if declarator is array pattern `[...]`= [...]
if let BindingPatternKind::ArrayPattern(id_kind) = &mut decl.id.kind
&& let Some(Expression::ArrayExpression(init_expr)) = &mut decl.init
{
let len = id_kind.elements.len();
// uses references var [a, b, c, ...d]
let has_rest = id_kind.rest.is_some();

// if left side of assigment is empty do not process it
if len == 0 {
if !init_expr.elements.is_empty() || has_rest {
new_var_decl.push(decl);
} else {
changed = true;
}
// if [] = [] remove declarator
continue;
}

let index = if let Some(spread_index) =
init_expr.elements.iter().position(ArrayExpressionElement::is_spread)
{
if spread_index == 0 {
// if spread is at first element, `??? = [...]`
new_var_decl.push(decl);
continue;
}
min(len, spread_index)
} else {
len
};

let mut init_iter = init_expr.elements.drain(..);

for id_item in id_kind.elements.drain(0..index) {
let init_item = init_iter.next();

// check for holes [,] = ????
if let Some(id) = id_item {
if id.kind.is_assignment_pattern() {
if let Some(init) = init_item {
new_var_decl.push(ctx.ast.variable_declarator(
id.span(),
kind,
ctx.ast.binding_pattern(
ctx.ast.binding_pattern_kind_array_pattern(
decl.span,
ctx.ast.vec1(Some(id)),
None::<Box<'a, BindingRestElement<'a>>>,
),
None::<Box<'a, TSTypeAnnotation<'a>>>,
false,
),
Some(Expression::ArrayExpression(
ctx.ast.alloc_array_expression(
init.span(),
ctx.ast.vec1(init),
),
)),
decl.definite,
));
} else if let BindingPatternKind::AssignmentPattern(id_kind) = id.kind {
changed = true;
let id_kind_unbox = id_kind.unbox();
new_var_decl.push(ctx.ast.variable_declarator(
id_kind_unbox.span,
kind,
id_kind_unbox.left,
Some(id_kind_unbox.right),
decl.definite,
));
}
} else {
changed = true;
new_var_decl.push(ctx.ast.variable_declarator(
id.span(),
kind,
id,
init_item.map(ArrayExpressionElement::into_expression),
decl.definite,
));
}
} else if let Some(init_elem) = init_item {
changed = true;
// skip [,] = [,]
if !init_elem.is_elision() {
new_var_decl.push(ctx.ast.variable_declarator(
init_elem.span(),
kind,
ctx.ast.binding_pattern(
ctx.ast.binding_pattern_kind_array_pattern(
decl.span,
ctx.ast.vec(),
None::<Box<'a, BindingRestElement<'a>>>,
),
None::<Box<'a, TSTypeAnnotation<'a>>>,
false,
),
Some(Expression::ArrayExpression(ctx.ast.alloc_array_expression(
init_elem.span(),
ctx.ast.vec_from_iter(Some(init_elem)),
))),
decl.definite,
));
}
}
}

if init_iter.len() == 0 {
if !id_kind.elements.is_empty() {
changed = true;
for id in id_kind.elements.drain(..).flatten() {
new_var_decl.push(ctx.ast.variable_declarator(
id.span(),
kind,
id,
None,
decl.definite,
));
}
}
if id_kind.elements.is_empty() && !has_rest {
// do nothing if we consumed all elements and there is no rest
continue;
}
} else {
init_expr.elements = ctx.ast.vec_from_iter(init_iter);
}
}

// do nothing id is not array pattern `[...] = ????` and init is not an array expression `???? = [...]`
new_var_decl.push(decl);
}

*declarations = new_var_decl;
changed
}

fn handle_expression_statement(
mut expr_stmt: Box<'a, ExpressionStatement<'a>>,
result: &mut Vec<'a, Statement<'a>>,
Expand Down Expand Up @@ -1884,4 +2051,43 @@ mod test {
test("for( a in b ){ c(); continue; }", "for ( a in b ) c();");
test("for( ; ; ){ c(); continue; }", "for ( ; ; ) c();");
}

#[test]
fn test_inline_variable_destruction() {
test("var [a] = [1]", "var a=1");
test("var [a, b, c, d] = [1, 2, 3, 4]", "var a=1,b=2,c=3,d=4");
test("var [a, b, c, d] = [1, 2, 3]", "var a=1,b=2,c=3,d");
test("var [a, b, c = 2, d] = [1]", "var a=1,b,c=2,d");
test("var [a, b, c] = [1, 2, 3, 4]", "var a=1,b=2,c=3,[]=[4]");
test("var [a, b, c = 2] = [1, 2, 3, 4]", "var a=1,b=2,[c=2]=[3],[]=[4]");
test("var [a, b, c = 3] = [1, 2]", "var a=1,b=2,c=3");
test("var [a, b] = [1, 2, 3]", "var a=1,b=2,[]=[3]");
test("var [a] = [123, 2222, 2222]", "var a=123,[]=[2222,2222];");
// spread
test("var [...a] = [...b]", "var [...a] = [...b]");
test("var [a, a, ...d] = []", "var a, a, [...d] = []");
test("var [a, ...d] = []", "var a, [...d] = []");
test("var [a, ...d] = [1, ...f]", "var a=1,[...d]=[...f]");
test("var [a, ...d] = [1, foo]", "var a=1,[...d]=[foo]");
test("var [a, b, c, ...d] = [1, 2, ...foo]", "var a=1,b=2,[c,...d]=[...foo]");
test("var [a, b, ...c] = [1, 2, 3, ...foo]", "var a=1,b=2,[...c]=[3,...foo]");
test("var [a, b] = [...c, ...d]", "var [a, b] = [...c, ...d]");
test("var [a, b] = [...c, c, d]", "var [a,b] = [...c,c,d]");
// defaults
test("var [a = 1] = [undefined]", "var [a = 1] = [void 0];");
test("var [a = 1] = [foo]", "var [a = 1] = [foo]");
test("var [a = foo] = [2]", "var [a=foo]=[2]");
// holes
test("var [] = []", "");
test("var [,,,] = [,,,]", "");
test("var [a, , c, d] = [1, 2, 3, 4]", "var a=1,[]=[2],c=3,d=4");
test("var [ , , a] = [1, 2, 3, 4]", "var []=[1],[]=[2],a=3,[]=[4]");
test("var [ , , ...t] = [1, 2, 3, 4]", "var []=[1],[]=[2],[...t]=[3,4]");
test("var [ , , ...t] = [1, ...a, 2, , 4]", "var []=[1],[,...t]=[...a,2,,4]");
// nested
test("var [a, [b, c]] = [1, [2, 3]]", "var a=1,b=2,c=3");
test("var [a, [b, [c, d]]] = [1, ...[2, 3]]", "var a=1,[[b,[c,d]]]=[...[2,3]]");
test("var [a, [b, [c,]]] = [1, [...2, 3]]", "var a=1,[b,[c]]=[...2,3]");
test("var [a, [b, [c,]]] = [1, [2, [...3]]]", "var a=1,b=2,[c]=[...3];");
}
}
4 changes: 2 additions & 2 deletions crates/oxc_minifier/src/peephole/normalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,8 @@ mod test {
test_same("{ const x = 1; eval('x = 2') }"); // keep assign error
test("{ const x = 1, y = 2 }", "{ let x = 1, y = 2 }");
test("{ const { x } = { x: 1 } }", "{ let { x } = { x: 1 } }");
test("{ const [x] = [1] }", "{ let [x] = [1] }");
test("{ const [x = 1] = [] }", "{ let [x = 1] = [] }");
test("{ const [x] = [1] }", "{ let x = 1 }");
test("{ const [x = 1] = [] }", "{ let x = 1 }");
test("for (const x in y);", "for (let x in y);");
// TypeError: Assignment to constant variable.
test_same("for (const i = 0; i < 1; i++);");
Expand Down
35 changes: 28 additions & 7 deletions crates/oxc_minifier/src/peephole/remove_unused_declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,31 @@ impl<'a> PeepholeOptimizations {
if !Self::can_remove_unused_declarators(ctx) {
return false;
}
if let BindingPatternKind::BindingIdentifier(ident) = &decl.id.kind {
// Unsafe to remove `using`, unable to statically determine usage of [Symbol.dispose].
if decl.kind.is_using() {
return false;
match &decl.id.kind {
BindingPatternKind::BindingIdentifier(ident) => {
// Unsafe to remove `using`, unable to statically determine usage of [Symbol.dispose].
if decl.kind.is_using() {
return false;
}
if let Some(symbol_id) = ident.symbol_id.get() {
return ctx.scoping().symbol_is_unused(symbol_id);
}
false
}
if let Some(symbol_id) = ident.symbol_id.get() {
return ctx.scoping().symbol_is_unused(symbol_id);
BindingPatternKind::ArrayPattern(ident) => {
if decl.kind.is_using() {
return false;
}
ident.is_empty()
}
BindingPatternKind::ObjectPattern(ident) => {
if decl.kind.is_using() {
return false;
}
ident.is_empty()
}
_ => false,
}
false
}

pub fn remove_unused_variable_declaration(
Expand Down Expand Up @@ -117,6 +132,12 @@ mod test {
test_options("var x", "", &options);
test_options("var x = 1", "", &options);
test_options("var x = foo", "foo", &options);
test_options("var [] = [1]", "", &options);
test_options("var [] = [foo]", "foo", &options);
test_options("var {} = {}", "", &options);
test_options("var {} = { a: 1 }", "", &options);
test_options("var {} = { foo }", "foo", &options);
test_options("var {} = { foo: { a } }", "a", &options);
test_same_options("var x; foo(x)", &options);
test_same_options("export var x", &options);
test_same_options("using x = foo", &options);
Expand Down