Skip to content

Commit 65c596d

Browse files
committed
fix(minifer): keep idents if not in scope when minimizing array exprs (#8551)
1 parent 7cc81ef commit 65c596d

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

crates/oxc_minifier/src/ast_passes/peephole_remove_dead_code.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -414,10 +414,11 @@ impl<'a, 'b> PeepholeRemoveDeadCode {
414414
let mut pending_spread_elements = ctx.ast.vec();
415415

416416
if array_expr.elements.len() == 0
417-
|| array_expr
418-
.elements
419-
.iter()
420-
.all(|el| matches!(el, ArrayExpressionElement::SpreadElement(_)))
417+
|| array_expr.elements.iter().all(|el| match el {
418+
ArrayExpressionElement::SpreadElement(_) => true,
419+
ArrayExpressionElement::Identifier(ident) => ctx.is_global_reference(ident),
420+
_ => false,
421+
})
421422
{
422423
return None;
423424
}
@@ -433,7 +434,7 @@ impl<'a, 'b> PeepholeRemoveDeadCode {
433434
let el = el.to_expression_mut();
434435
let el_expr = ctx.ast.move_expression(el);
435436
if !el_expr.is_literal_value(false)
436-
&& !matches!(el_expr, Expression::Identifier(_))
437+
&& !matches!(&el_expr, Expression::Identifier(ident) if !ctx.is_global_reference(ident))
437438
{
438439
if pending_spread_elements.len() > 0 {
439440
// flush pending spread elements
@@ -703,17 +704,20 @@ mod test {
703704
fn test_array_literal() {
704705
fold("([])", "");
705706
fold("([1])", "");
706-
fold("([a])", "");
707+
fold("([a])", "[a]");
708+
fold("var a; ([a])", "var a;");
707709
fold("([foo()])", "foo()");
708710
fold_same("baz.map((v) => [v])");
709711
}
710712

711713
#[test]
712714
fn test_array_literal_containing_spread() {
713715
fold_same("([...c])");
714-
fold("([4, ...c, a])", "([...c])");
716+
fold("([4, ...c, a])", "([...c], a)");
717+
fold("var a; ([4, ...c, a])", "var a; ([...c])");
715718
fold("([foo(), ...c, bar()])", "(foo(), [...c], bar())");
716-
fold("([...a, b, ...c])", "([...a, ...c])");
719+
fold("([...a, b, ...c])", "([...a, b, ...c])");
720+
fold("var b; ([...a, b, ...c])", "var b; ([...a, ...c])");
717721
fold_same("([...b, ...c])"); // It would also be fine if the spreads were split apart.
718722
}
719723

0 commit comments

Comments
 (0)