@@ -4463,6 +4463,7 @@ const SCAN_END_UNIT = 1 << 11;
44634463 * @property {((compressor: EXPECTED_ANY) => boolean) | null} keepsLoopBinding whether a `for` head's lexical name nothing reads stays, its initializer having effects
44644464 * @property {((compressor: EXPECTED_ANY) => boolean) | null} keepsListPosition whether an expression dropped from an array or argument list leaves a `0` in its place
44654465 * @property {((compressor: EXPECTED_ANY) => boolean) | null} keepsImmutableWrite whether a write to a `const` or a class expression's name stays, as it throws
4466+ * @property {((assign: Node, compressor: EXPECTED_ANY) => boolean) | null} keepsConvertingWrite whether a compound write stays, as converting its sides may throw
44664467 */
44674468
44684469/**
@@ -4485,7 +4486,8 @@ const installUnused = (modules) => {
44854486 dropsCatchBinding: null,
44864487 keepsLoopBinding: null,
44874488 keepsListPosition: null,
4488- keepsImmutableWrite: null
4489+ keepsImmutableWrite: null,
4490+ keepsConvertingWrite: null
44894491 };
44904492 modules.webpackUnused = hooks;
44914493 const { ast, common, inference, utils } = modules;
@@ -4583,6 +4585,13 @@ const installUnused = (modules) => {
45834585 !node.logical &&
45844586 (node.flags & WRITE_ONLY || node.operator === "=")
45854587 ) {
4588+ if (
4589+ node.operator !== "=" &&
4590+ hooks.keepsConvertingWrite !== null &&
4591+ hooks.keepsConvertingWrite(node, compressor)
4592+ ) {
4593+ return;
4594+ }
45864595 target = node.left;
45874596 } else if (kind & UNUSED_UNARY && node.flags & WRITE_ONLY) {
45884597 target = node.argument;
@@ -5756,6 +5765,59 @@ const installReduce = (modules) => {
57565765 ["SimpleStatement", REDUCE_OPAQUE]
57575766 ]);
57585767
5768+ /**
5769+ * Whether a definition is a sloppy function declared in a block, which Annex B
5770+ * makes a `var` holding `undefined` until its statement runs.
5771+ * @param {SymbolDefinition} definition the definition
5772+ * @param {EXPECTED_ANY} compressor the compressor
5773+ * @returns {boolean} true for one terser takes as set from the scope's start
5774+ */
5775+ const isBlockFunction = (definition, compressor) => {
5776+ if (
5777+ modules.corrections === undefined ||
5778+ !modules.corrections.enabled ||
5779+ !isSymbolDefunNode(definition.identifiers[0]) ||
5780+ compressor.option("module")
5781+ ) {
5782+ return false;
5783+ }
5784+ const statements = ast.bodyOf(definition.scope.node);
5785+ if (!Array.isArray(statements) || statements.includes(definition.init)) {
5786+ return false;
5787+ }
5788+ // A module is strict, scoping the function to its block, which terser
5789+ // does for strict code it can see but not for a module it was not told of.
5790+ let top = definition.scope;
5791+ while (top.upper !== null) top = top.upper;
5792+ return !ast
5793+ .bodyOf(top.node)
5794+ .some(
5795+ (/** @type {Node} */ statement) =>
5796+ ast.isExportNode(statement) || ast.isImportNode(statement)
5797+ );
5798+ };
5799+
5800+ // The definitions `isBlockFunction` holds for, worked out once a pass.
5801+ /** @type {WeakSet<SymbolDefinition>} */
5802+ const blockFunctions = new WeakSet();
5803+
5804+ /**
5805+ * Whether a reference to a block's function reads its block's own binding,
5806+ * set on the block's entry, rather than the `var` Annex B sets later.
5807+ * @param {EXPECTED_ANY} walker the walker marking
5808+ * @param {SymbolDefinition} definition the function's definition
5809+ * @returns {boolean} true inside the block declaring it
5810+ */
5811+ const readsBlockBinding = (walker, definition) => {
5812+ const declaration = definition.init;
5813+ const scope = definition.scope.node;
5814+ for (let i = 0, node; (node = walker.parent(i)) && node !== scope; i++) {
5815+ const body = ast.bodyOf(node);
5816+ if (Array.isArray(body) && body.includes(declaration)) return true;
5817+ }
5818+ return false;
5819+ };
5820+
57595821 /**
57605822 * Clears what the analysis records on a definition.
57615823 * @param {EXPECTED_ANY} compressor the compressor
@@ -5771,6 +5833,11 @@ const installReduce = (modules) => {
57715833 definition.recursive_refs = 0;
57725834 definition.references = [];
57735835 definition.single_use = undefined;
5836+ if (isBlockFunction(definition, compressor)) {
5837+ blockFunctions.add(definition);
5838+ } else {
5839+ blockFunctions.delete(definition);
5840+ }
57745841 if (
57755842 definition.scope.isPinned() ||
57765843 (isSymbolFunargNode(definition.identifiers[0]) &&
@@ -6692,6 +6759,15 @@ const installReduce = (modules) => {
66926759 */
66936760 const reduceSymbolRef = (self, walker, descend, compressor) => {
66946761 const definition = self.definition;
6762+ // Outside its block, Annex B's `var` holds the function only once its
6763+ // statement ran, which terser takes as from the scope's start.
6764+ if (
6765+ definition.fixed &&
6766+ blockFunctions.has(definition) &&
6767+ !readsBlockBinding(walker, definition)
6768+ ) {
6769+ definition.fixed = false;
6770+ }
66956771 definition.references.push(self);
66966772 if (
66976773 definition.references.length === 1 &&
@@ -15542,6 +15618,31 @@ const installCorrect = (modules) => {
1554215618 !compressor.option("pure_conversions") &&
1554315619 convertedKind(self.key, 0) === undefined &&
1554415620 !neverKeysPrototype(self.key);
15621+ /**
15622+ * Whether a computed read converts a key that may be an object, where
15623+ * `pure_conversions` is off; terser drops the read with its conversion.
15624+ * @param {Node} self an expression
15625+ * @param {CompressorShape} compressor the compressor
15626+ * @returns {boolean} true for `a[o]`
15627+ */
15628+ const readsKeyUnknown = (self, compressor) =>
15629+ A.isSubNode(self) &&
15630+ !compressor.option("pure_conversions") &&
15631+ convertedKind(self.property, 0) === undefined;
15632+ ast.wrapDropSideEffectFree(
15633+ "MemberExpression",
15634+ (
15635+ /** @type {(self: Node, compressor: CompressorShape, firstInStatement?: boolean) => Node | null} */ original
15636+ ) =>
15637+ (
15638+ /** @type {Node} */ self,
15639+ /** @type {CompressorShape} */ compressor,
15640+ /** @type {boolean=} */ firstInStatement
15641+ ) =>
15642+ corrections.enabled && readsKeyUnknown(self, compressor)
15643+ ? self
15644+ : original(self, compressor, firstInStatement)
15645+ );
1554515646 for (const name of ["hasSideEffects", "mayThrow"]) {
1554615647 const original = ast[name];
1554715648 /**
@@ -15556,6 +15657,7 @@ const installCorrect = (modules) => {
1555615657 convertsUnknown(self) ||
1555715658 comparesUnknown(self, compressor) ||
1555815659 keysUnknown(self, compressor) ||
15660+ readsKeyUnknown(self, compressor) ||
1555915661 definesStaticPrototype(self, compressor)));
1556015662 }
1556115663 for (const type of ["ClassDeclaration", "ClassExpression"]) {
@@ -16239,6 +16341,23 @@ const installCorrect = (modules) => {
1623916341 parensByType[type] = (node, output) =>
1624016342 isPrivateInRight(node, output) || parens(node, output);
1624116343 }
16344+ // V8 reads the arguments before a bare destructuring assignment as one
16345+ // pattern and refuses `f(a += 1, [b] = c)`, which the spec allows.
16346+ const assignmentParens = parensByType.AssignmentExpression;
16347+ parensByType.AssignmentExpression = (node, output) => {
16348+ if (assignmentParens(node, output)) return true;
16349+ if (!corrections.enabled) return false;
16350+ const { left } = /** @type {PrintBinaryLike} */ (node);
16351+ if (left.type !== "ArrayPattern" && left.type !== "ObjectPattern") {
16352+ return false;
16353+ }
16354+ const parent = /** @type {PrintParent | undefined} */ (output.parent());
16355+ return (
16356+ parent !== undefined &&
16357+ (parent.type === "CallExpression" || parent.type === "NewExpression") &&
16358+ parent.arguments.indexOf(node) > 0
16359+ );
16360+ };
1624216361 const printArrow =
1624316362 /** @type {NonNullable<EstreeGenerators["ArrowFunctionExpression"]>} */ (
1624416363 estreeCodegen.ArrowFunctionExpression
@@ -16275,6 +16394,51 @@ const installCorrect = (modules) => {
1627516394 modules.printEstree(tag, output, true);
1627616395 modules.printEstree(node.quasi, output);
1627716396 };
16397+ // terser spaces a regular expression only from a word operator it is the
16398+ // left side of, so one closing a deeper operand, `!/a/ in b`, took the
16399+ // operator for its flags.
16400+ /** @type {WeakMap<OutputStream, number>} */
16401+ const regexpEnds = new WeakMap();
16402+ const printLiteralCorrected =
16403+ /** @type {NonNullable<EstreeGenerators["Literal"]>} */ (
16404+ estreeCodegen.Literal
16405+ );
16406+ estreeCodegen.Literal = (node, output) => {
16407+ printLiteralCorrected(node, output);
16408+ if (
16409+ corrections.enabled &&
16410+ node.value !== null &&
16411+ typeof node.value === "object"
16412+ ) {
16413+ regexpEnds.set(output, output.currentPosition);
16414+ }
16415+ };
16416+ const printBinaryCorrected =
16417+ /** @type {NonNullable<EstreeGenerators["BinaryExpression"]>} */ (
16418+ estreeCodegen.BinaryExpression
16419+ );
16420+ estreeCodegen.BinaryExpression = (node, output) => {
16421+ if (
16422+ !corrections.enabled ||
16423+ (node.operator !== "in" && node.operator !== "instanceof") ||
16424+ node.left.type === "PrivateIdentifier"
16425+ ) {
16426+ printBinaryCorrected(node, output);
16427+ return;
16428+ }
16429+ modules.printEstree(node.left, output);
16430+ if (
16431+ regexpEnds.get(output) === output.currentPosition &&
16432+ output.last().endsWith("/")
16433+ ) {
16434+ output.print(" ");
16435+ } else {
16436+ output.space();
16437+ }
16438+ output.print(node.operator);
16439+ output.space();
16440+ modules.printEstree(node.right, output);
16441+ };
1627816442
1627916443 /**
1628016444 * @param {PrintParent} parent a node
@@ -16875,6 +17039,26 @@ const installCorrect = (modules) => {
1687517039 : withOptionsOff(compressor, names, () => original(call, compressor));
1687617040 }
1687717041
17042+ /**
17043+ * Whether a destructuring assignment in a function writes a parameter, which
17044+ * the analysis leaves out of the parameter's assignments.
17045+ * @param {Node} lambda the function
17046+ * @param {SymbolDefinition} definition the parameter's definition
17047+ * @returns {boolean} true where one does
17048+ */
17049+ const assignsByDestructuring = (lambda, definition) =>
17050+ Boolean(
17051+ A.walk(lambda, (/** @type {Node} */ node) =>
17052+ A.isDestructuringNode(node) &&
17053+ A.walk(node, (/** @type {Node} */ inner) =>
17054+ A.isSymbolRefNode(inner) && inner.definition === definition
17055+ ? A.walk_abort
17056+ : undefined
17057+ )
17058+ ? A.walk_abort
17059+ : undefined
17060+ )
17061+ );
1687817062 // A sloppy `arguments[i]` follows its parameter only where an argument was
1687917063 // passed, so it is the parameter only while nothing reassigns that.
1688017064 wrapOptimize("Sub", (original) => (self, compressor) => {
@@ -16895,7 +17079,8 @@ const installCorrect = (modules) => {
1689517079 if (
1689617080 !compressor.option("reduce_vars") ||
1689717081 definition.assignments ||
16898- definition.identifiers.length > 1
17082+ definition.identifiers.length > 1 ||
17083+ assignsByDestructuring(expression.scope.node, definition)
1689917084 ) {
1690017085 return withOptionsOff(compressor, ["arguments"], () =>
1690117086 original(self, compressor)
@@ -17110,6 +17295,25 @@ const installCorrect = (modules) => {
1711017295 modules.webpackUnused.keepsListPosition = () => corrections.enabled;
1711117296 // terser drops a write nothing reads, though a constant's throws.
1711217297 modules.webpackUnused.keepsImmutableWrite = () => corrections.enabled;
17298+ /**
17299+ * terser drops a compound write nothing reads, though a BigInt beside
17300+ * another value throws, as may converting a parameter no write here gave.
17301+ * @param {Node} assign the compound assignment
17302+ * @param {CompressorShape} compressor the compressor
17303+ * @returns {boolean} whether it stays
17304+ */
17305+ modules.webpackUnused.keepsConvertingWrite = (assign, compressor) => {
17306+ if (!corrections.enabled) return false;
17307+ const { left, right } = assign;
17308+ const isBigInt = (/** @type {Node} */ node) =>
17309+ isBigIntLiteral(node) ||
17310+ typeof ast.evaluateNode(node, compressor, 1) === "bigint";
17311+ return (
17312+ isBigInt(left) !== isBigInt(right) ||
17313+ (A.isSymbolRefNode(left) &&
17314+ A.isSymbolFunargNode(left.definition.identifiers[0]))
17315+ );
17316+ };
1711317317 return;
1711417318 }
1711517319 // terser's own `drop_unused` trims first, so the parameter is put back.
@@ -26627,9 +26831,15 @@ const createTightenBody = (modules) => {
2662726831 * @param {CompressorShape} compressor the compressor
2662826832 * @param {Node} statement the unreachable statement
2662926833 * @param {Node[]} target where what it declares goes
26834+ * @param {boolean=} listed whether it stands in a statement list, not a clause
2663026835 * @returns {void}
2663126836 */
26632- const extractFromUnreachableCode = (compressor, statement, target) => {
26837+ const extractFromUnreachableCode = (
26838+ compressor,
26839+ statement,
26840+ target,
26841+ listed
26842+ ) => {
2663326843 walk(statement, (/** @type {Node} */ node) => {
2663426844 if (isVarNode(node)) {
2663526845 const noInitializers = removeInitializers(node);
@@ -26645,12 +26855,14 @@ const createTightenBody = (modules) => {
2664526855 ) {
2664626856 return true;
2664726857 }
26858+ // A function a clause declares is Annex B's, unset until it runs.
26859+ const hoisted = node === statement && (listed === true || !correcting());
2664826860 if (
2664926861 isDefunNode(node) &&
26650- (node === statement || !compressor.has_directive("use strict"))
26862+ (hoisted || !compressor.has_directive("use strict"))
2665126863 ) {
2665226864 target.push(
26653- node === statement
26865+ hoisted
2665426866 ? node
2665526867 : makeNode(VarNode, node, {
2665626868 declarations: [
@@ -28329,7 +28541,7 @@ const createTightenBody = (modules) => {
2832928541 state.changed = n !== length;
2833028542 if (hasQuit) {
2833128543 for (const statement of hasQuit) {
28332- extractFromUnreachableCode(compressor, statement, statements);
28544+ extractFromUnreachableCode(compressor, statement, statements, true );
2833328545 }
2833428546 }
2833528547 };
@@ -28348,6 +28560,17 @@ const createTightenBody = (modules) => {
2834828560 });
2834928561 };
2835028562
28563+ /**
28564+ * Whether a function declared in the statements being tightened is Annex B's,
28565+ * which sets its `var` where its statement runs, so it moves before nothing.
28566+ * @param {CompressorShape} compressor the compressor
28567+ * @returns {boolean} true in a sloppy block
28568+ */
28569+ const assignsBlockFunction = (compressor) =>
28570+ correcting() &&
28571+ !isScopeNode(compressor.self()) &&
28572+ !compressor.has_directive("use strict");
28573+
2835128574 /**
2835228575 * terser's `sequencesize`: joins consecutive expression statements into
2835328576 * one sequence.
@@ -28384,7 +28607,7 @@ const createTightenBody = (modules) => {
2838428607 (isVarNode(statement) ||
2838528608 modules.corrections === undefined ||
2838628609 !modules.corrections.enabled)) ||
28387- isDefunNode(statement)
28610+ ( isDefunNode(statement) && !assignsBlockFunction(compressor) )
2838828611 ) {
2838928612 statements[n++] = statement;
2839028613 } else {
@@ -35388,7 +35611,7 @@ const installHelpers = (modules) => {
3538835611 * @property {(self: Node, compressor: CompressorShape) => Node | null} unsafeUndefinedRef terser's `unsafe_undefined_ref`
3538935612 * @property {(elements: (Node | null)[]) => void} inlineArrayLikeSpread terser's `inline_array_like_spread`
3539035613 * @property {(statements: Node[], compressor: CompressorShape) => void} tightenBody terser's `tighten_body`
35391- * @property {(compressor: CompressorShape, statement: Node, target: Node[]) => void} extractFromUnreachableCode terser's `extract_from_unreachable_code`
35614+ * @property {(compressor: CompressorShape, statement: Node, target: Node[], listed?: boolean ) => void} extractFromUnreachableCode terser's `extract_from_unreachable_code`
3539235615 * @property {(self: Node, compressor: CompressorShape) => Node} inlineIntoSymbolRef terser's `inline_into_symbolref`
3539335616 * @property {(self: Node, compressor: CompressorShape) => Node} inlineIntoCall terser's `inline_into_call`
3539435617 */
0 commit comments