From 2979771a9c361168d8672b95d1af1a45a7894d14 Mon Sep 17 00:00:00 2001 From: rishipal Date: Mon, 7 Aug 2023 14:55:17 -0700 Subject: [PATCH] Fix spread optimization on array literals with holes Do not fold if the array literal has any holes as it's a syntax error to have holes (empty arg) if we're the spread happens to be a call arg. PiperOrigin-RevId: 554601815 --- .../google/javascript/jscomp/PeepholeFoldConstants.java | 7 +++++++ .../javascript/jscomp/PeepholeFoldConstantsTest.java | 1 + 2 files changed, 8 insertions(+) diff --git a/src/com/google/javascript/jscomp/PeepholeFoldConstants.java b/src/com/google/javascript/jscomp/PeepholeFoldConstants.java index 0372af15975..956b43a89fa 100644 --- a/src/com/google/javascript/jscomp/PeepholeFoldConstants.java +++ b/src/com/google/javascript/jscomp/PeepholeFoldConstants.java @@ -1643,6 +1643,13 @@ private Node tryFoldSpread(Node spread) { Node parent = spread.getParent(); Node child = spread.getOnlyChild(); if (child.isArrayLit()) { + for (Node n = child.getFirstChild(); n != null; n = n.getNext()) { + if (n.getToken().equals(Token.EMPTY)) { + // Do not fold if the array literal has any holes as it's a syntax error to have holes + // (empty arg) if the spread happens to be a call arg + return spread; + } + } parent.addChildrenAfter(child.removeChildren(), spread); spread.detach(); reportChangeToEnclosingScope(parent); diff --git a/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java b/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java index 9675a721576..60943a31717 100644 --- a/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java +++ b/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java @@ -1412,6 +1412,7 @@ public void testFoldArraySpread() { @Test public void testFoldArrayLitSpreadInArg() { test("foo(...[0], 1)", "foo(0, 1)"); + testSame("foo(...[,,,,\"foo\"], 1)"); testSame("foo(...(false ? [0] : [1]))"); // other opts need to fold the ternery first }