From db932f07d3c9f2b147a79fe75a62a5c515eaec40 Mon Sep 17 00:00:00 2001 From: WofWca Date: Tue, 23 Apr 2024 13:40:12 +0000 Subject: [PATCH] object spread: also drop non-nullish constants (e.g. `{ ...true }`) (#1141) This is a follow-up to 6f04338 (#1004) --- lib/compress/index.js | 17 ++++++++--------- test/compress/expansions.js | 29 ++++++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/lib/compress/index.js b/lib/compress/index.js index 0cd730e10..d33074868 100644 --- a/lib/compress/index.js +++ b/lib/compress/index.js @@ -3758,7 +3758,7 @@ def_optimize(AST_Array, function(self, compressor) { return self; }); -function inline_object_prop_spread(props, compressor) { +function inline_object_prop_spread(props) { for (var i = 0; i < props.length; i++) { var prop = props[i]; if (prop instanceof AST_Expansion) { @@ -3770,15 +3770,14 @@ function inline_object_prop_spread(props, compressor) { props.splice(i, 1, ...expr.properties); // Step back one, as the property at i is now new. i--; - } else if (expr instanceof AST_Constant - && !(expr instanceof AST_String)) { + } else if (( + // `expr.is_constant()` returns `false` for `AST_RegExp`, so need both. + expr instanceof AST_Constant + || expr.is_constant() + ) && !(expr instanceof AST_String)) { // Unlike array-like spread, in object spread, spreading a // non-iterable value silently does nothing; it is thus safe - // to remove. AST_String is the only iterable AST_Constant. - props.splice(i, 1); - i--; - } else if (is_nullish(expr, compressor)) { - // Likewise, null and undefined can be silently removed. + // to remove. AST_String is the only iterable constant. props.splice(i, 1); i--; } @@ -3791,7 +3790,7 @@ def_optimize(AST_Object, function(self, compressor) { if (optimized !== self) { return optimized; } - inline_object_prop_spread(self.properties, compressor); + inline_object_prop_spread(self.properties); return self; }); diff --git a/test/compress/expansions.js b/test/compress/expansions.js index af90f0935..02eab0535 100644 --- a/test/compress/expansions.js +++ b/test/compress/expansions.js @@ -103,7 +103,31 @@ object_spread: { ] } -object_spread_nullish_undefined: { +object_spread_constant: { + input: { + id({ + ...null, + ...undefined, + ...true, + ...void 0, + ...!0, + ...~"foo", + .../baz/, + ...-/baz2/, + + ..."bar", + }); + } + + expect: { + id({ + ..."bar" + }) + } +} + +// https://github.com/terser/terser/pull/1071 +object_spread_inline_after_dropping_undefined: { input: { let o = { ...undefined, ...{a: true} } id(o); @@ -114,8 +138,7 @@ object_spread_nullish_undefined: { id(o) } } - -object_spread_nullish_null: { +object_spread_inline_after_dropping_null: { input: { let o = { ...null, ...{a: true} } id(o);