Skip to content

Commit 593815b

Browse files
authored
feat(minify): drop writes to a let nothing reads from closures created after it (#22960)
* feat(minify): drop writes to a `let` nothing reads from closures created after it * fix(minify): keep a write to a `for…of` or `for…in` head from its right side * docs(changeset): shorten the closure let-writes changeset to one line * test(minify): assert the `switch` case's own write stays * fix(minify): count a `for…of` head's `let` as set once its right side has run * test(minify): snapshot the printed loop-head cases
1 parent ef640cf commit 593815b

8 files changed

Lines changed: 207 additions & 19 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Drop unread `let` writes from closures created after the declaration.

‎lib/javascript/syntax-printer.js‎

Lines changed: 63 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5437,6 +5437,7 @@ const UNUSED_LABELED = 1 << 15;
54375437
const UNUSED_BLOCK_STATEMENT = 1 << 16;
54385438
const UNUSED_SEQUENCE = 1 << 17;
54395439
const UNUSED_CATCH = 1 << 18;
5440+
const UNUSED_FOR_IN = 1 << 19;
54405441
// What the scan of `drop_unused` reads anything off; any other node it only
54415442
// descends.
54425443
const UNUSED_SCANNED =
@@ -5446,7 +5447,8 @@ const UNUSED_SCANNED_FIRST =
54465447
UNUSED_DEFUN |
54475448
UNUSED_DEF_CLASS |
54485449
UNUSED_FUNARG |
5449-
UNUSED_DEFINITIONS;
5450+
UNUSED_DEFINITIONS |
5451+
UNUSED_FOR_IN;
54505452
// What the drop of `drop_unused` changes or enters a scope at; any other node
54515453
// it only descends.
54525454
const UNUSED_DROPPED =
@@ -5631,7 +5633,8 @@ const installUnused = (modules) => {
56315633
["LabeledStatement", UNUSED_LABELED],
56325634
["BlockStatement", UNUSED_BLOCK_STATEMENT],
56335635
["Sequence", UNUSED_SEQUENCE],
5634-
["Catch", UNUSED_CATCH]
5636+
["Catch", UNUSED_CATCH],
5637+
["ForIn", UNUSED_FOR_IN]
56355638
]);
56365639

56375640
/**
@@ -6014,9 +6017,22 @@ const installUnused = (modules) => {
60146017
/** @type {Map<number, Node[]>} */
60156018
const initializations = new Map();
60166019
// The `let` bindings of this scope whose declaration pass 1 has walked
6017-
// past, outside a `switch` case, which a later write cannot precede.
6018-
/** @type {Set<Definition>} */
6019-
const initializedLets = new Set();
6020+
// past, outside a `switch` case, which a later write cannot precede,
6021+
// each with how many such bindings came before it.
6022+
/** @type {Map<Definition, number>} */
6023+
const initializedLets = new Map();
6024+
// How many of them a closure being walked was created after.
6025+
let letsBefore = Infinity;
6026+
/** @type {Map<Node, number>} */
6027+
const initLetsBefore = new Map();
6028+
/**
6029+
* @param {Definition} definition a binding a nested scope writes
6030+
* @returns {boolean} whether it is a `let` its closure was created after
6031+
*/
6032+
const createdAfterLet = (definition) => {
6033+
const order = initializedLets.get(definition);
6034+
return order !== undefined && order < letsBefore;
6035+
};
60206036
/**
60216037
* @param {Definition} definition a `let` whose declaration ran before
60226038
* @returns {boolean} whether a write to it may go with it: one of a block, whose
@@ -6222,6 +6238,8 @@ const installUnused = (modules) => {
62226238
}
62236239
// Past the target's reference, to the right side.
62246240
i += 2;
6241+
} else if (op & SCAN_BLOCK_NAME && createdAfterLet(definition)) {
6242+
i += 2;
62256243
} else {
62266244
i++;
62276245
}
@@ -6256,6 +6274,26 @@ const installUnused = (modules) => {
62566274
}
62576275
}
62586276
if (node === self) return;
6277+
if (kind & UNUSED_FOR_IN) {
6278+
if (
6279+
hooks.dropsLetWrite === null ||
6280+
scope !== self ||
6281+
!isLetNode(node.left) ||
6282+
!hooks.dropsLetWrite(compressor)
6283+
) {
6284+
return;
6285+
}
6286+
// The head's `let` holds its value only once the right side has run.
6287+
walkNode(node.left, tw);
6288+
walkNode(node.right, tw);
6289+
for (const definition of node.left.declarations) {
6290+
if (isSymbolLetNode(definition.id)) {
6291+
initializedLets.set(definition.id.definition, initializedLets.size);
6292+
}
6293+
}
6294+
walkNode(/** @type {Node} */ (node.body), tw);
6295+
return true;
6296+
}
62596297
if (kind & UNUSED_CLASS && ast.hasSideEffects(node, compressor)) {
62606298
if (ast.runsOnlyHeritage(node, compressor)) {
62616299
markNeeded(scope);
@@ -6288,6 +6326,15 @@ const installUnused = (modules) => {
62886326
}
62896327
if (kind & UNUSED_DEFINITIONS && inRootScope) {
62906328
const inExport = isExportNode(descending[descending.length - 2]);
6329+
const holder = descending[descending.length - 2];
6330+
// A `for…in` or `for…of` head is in its dead zone while the right
6331+
// side runs, after the walk has passed the declaration.
6332+
const initializesLets =
6333+
hooks.dropsLetWrite !== null &&
6334+
isLetNode(node) &&
6335+
!isSwitchBranchNode(holder) &&
6336+
!isForInNode(holder) &&
6337+
hooks.dropsLetWrite(compressor);
62916338
for (const definition of node.declarations) {
62926339
if (isSymbolVarNode(definition.id)) {
62936340
mapAdd(varDefsById, definition.id.definition.id, definition);
@@ -6306,6 +6353,9 @@ const installUnused = (modules) => {
63066353
if (isSymbolDeclarationNode(definition.id) && definition.init) {
63076354
const nodeDefinition = definition.id.definition;
63086355
mapAdd(initializations, nodeDefinition.id, definition.init);
6356+
if (initializedLets.size > 0) {
6357+
initLetsBefore.set(definition.init, initializedLets.size);
6358+
}
63096359
if (
63106360
!nodeDefinition.chained &&
63116361
ast.fixedValue(definition.id) === definition.init
@@ -6316,17 +6366,8 @@ const installUnused = (modules) => {
63166366
walkNode(definition.init, tw);
63176367
}
63186368
}
6319-
}
6320-
if (
6321-
hooks.dropsLetWrite !== null &&
6322-
isLetNode(node) &&
6323-
!isSwitchBranchNode(descending[descending.length - 2]) &&
6324-
hooks.dropsLetWrite(compressor)
6325-
) {
6326-
for (const definition of node.declarations) {
6327-
if (isSymbolLetNode(definition.id)) {
6328-
initializedLets.add(definition.id.definition);
6329-
}
6369+
if (initializesLets && isSymbolLetNode(definition.id)) {
6370+
initializedLets.set(definition.id.definition, initializedLets.size);
63306371
}
63316372
}
63326373
return true;
@@ -6345,6 +6386,7 @@ const installUnused = (modules) => {
63456386
if (inits) {
63466387
for (const init of inits) {
63476388
scope = defunScopes.get(init) || self;
6389+
letsBefore = initLetsBefore.get(init) || 0;
63486390
walkNode(init, tw);
63496391
}
63506392
}
@@ -6353,10 +6395,13 @@ const installUnused = (modules) => {
63536395
for (const [defun, parent] of defunScopes) {
63546396
if (!isInUse(defun.id.definition)) markNeeded(parent);
63556397
}
6356-
if (dropVariables) {
6398+
if (dropVariables || initializedLets.size > 0) {
63576399
for (let i = 0; i < nestedAssigns.length; i += 2) {
63586400
const definition = nestedAssigns[i].definition;
6359-
if (!isInUse(definition) || fixedIds.has(definition.id)) {
6401+
if (
6402+
(dropVariables || dropsWriteOf(definition)) &&
6403+
(!isInUse(definition) || fixedIds.has(definition.id))
6404+
) {
63606405
markNeeded(nestedAssigns[i + 1]);
63616406
}
63626407
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const log = [];
2+
3+
function settle(values) {
4+
let lastSeen,
5+
keep = function (value) {
6+
lastSeen = value;
7+
log.push(value);
8+
};
9+
values.forEach((value) => {
10+
lastSeen = value + 1;
11+
});
12+
values.forEach(keep);
13+
return values.length;
14+
}
15+
16+
function early(run) {
17+
const write = () => {
18+
pending = run;
19+
};
20+
try {
21+
if (run) write();
22+
} catch (err) {
23+
return err.name;
24+
}
25+
let pending;
26+
write();
27+
return "late";
28+
}
29+
30+
function remembered(values) {
31+
let seen;
32+
values.forEach((value) => {
33+
seen = value;
34+
});
35+
return () => seen;
36+
}
37+
38+
it("should drop writes to a `let` from closures created after it, which nothing reads", () => {
39+
log.length = 0;
40+
expect(settle([1, 2])).toBe(2);
41+
expect(log).toEqual([1, 2]);
42+
});
43+
44+
it("should keep a write that may run before its `let`, or one a closure reads", () => {
45+
expect(early(1)).toBe("ReferenceError");
46+
expect(early(0)).toBe("late");
47+
expect(remembered([3, 4])()).toBe(4);
48+
});
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"use strict";
2+
3+
const fs = require("fs");
4+
const path = require("path");
5+
6+
module.exports = {
7+
afterExecute(options) {
8+
const code = fs.readFileSync(
9+
path.join(options.output.path, "bundle0.js"),
10+
"utf8"
11+
);
12+
expect(code).not.toContain("lastSeen");
13+
expect(code).toContain("pending=");
14+
expect(code).toContain("seen=");
15+
}
16+
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"use strict";
2+
3+
const MinimizerPlugin = require("minimizer-webpack-plugin");
4+
const jsMinify = require("../../../../lib/javascript/jsMinify");
5+
6+
/** @type {import("../../../../").Configuration} */
7+
module.exports = {
8+
mode: "production",
9+
output: { filename: "bundle0.js" },
10+
optimization: {
11+
minimize: true,
12+
minimizer: [
13+
new MinimizerPlugin({
14+
// Keep coverage counters in the process running the tests.
15+
parallel: false,
16+
minify: jsMinify,
17+
minimizerOptions: { compress: { passes: 2 }, mangle: false }
18+
})
19+
]
20+
}
21+
};

‎test/helpers/oxcSmaller.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,13 @@ const OXC_SMALLER_BY_REASON = [
497497
"oxc's output is wrong: it renames a `#private` name a direct `eval` reads, so the `eval` throws a SyntaxError",
498498
["oxc minifier: peephole/remove_unused_private_members.rs:27"]
499499
],
500+
[
501+
"oxc's output is wrong: it drops a write in a `for…of` or `for…in` right side to the loop's own `let`, which throws a ReferenceError there, as its own test keeps it",
502+
[
503+
"oxc minifier: peephole/merge_assignments_to_declarations.rs:106",
504+
"oxc minifier: peephole/merge_assignments_to_declarations.rs:107"
505+
]
506+
],
500507
[
501508
"oxc drops an unread deferred or source-phase import, assuming its load cannot fail, where webpack keeps it as oxc's `invalid_import_side_effects` does, since it still fetches and links its module",
502509
[

‎test/unitCases/javascript/__snapshots__/printer.unittest.js.snap‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2847,6 +2847,12 @@ Array [
28472847
]
28482848
`;
28492849

2850+
exports[`syntax-printer improve phase should drop a write to a \`for…of\` head's \`let\` from its body, not its right side 1`] = `"export function f(a){let p;for(let x of a)p=()=>{};return p}"`;
2851+
2852+
exports[`syntax-printer improve phase should drop a write to a \`for…of\` head's \`let\` from its body, not its right side 2`] = `"export function f(a){for(let x of a)h(1)}"`;
2853+
2854+
exports[`syntax-printer improve phase should drop a write to a \`for…of\` head's \`let\` from its body, not its right side 3`] = `"export function f(a){let p;for(let x of a)p=()=>x;return p}"`;
2855+
28502856
exports[`syntax-printer improve phase should keep a function called in place whose \`var\`, its name taken, a class in a block there also names 1`] = `"function f(x){var a=g();!function(){var x=typeof a;{class x{}console.log(x.name)}console.log(x)}(),console.log(x,a)}function g(){return 1}f(\\"o\\");"`;
28512857

28522858
exports[`syntax-printer improve phase should keep a function called in place whose \`var\`s, more than one, take names already taken 1`] = `"function f(x){var a=g(),b=g();console.log(x),function(){if(x){var a=console.log.name,b=typeof x;console.log(a,a,b,b)}}(),console.log(a,b)}function g(){return\\"o\\"}f(1),f(0);"`;
@@ -2989,6 +2995,8 @@ exports[`syntax-printer improve phase should write less, printing the same: a \`
29892995

29902996
exports[`syntax-printer improve phase should write less, printing the same: a \`let\` before a loop assigning it first, given that value where it stands, but where the value reads it 1`] = `"function f(n){let i=0,j;for(;i<n;i++);for(j=()=>j;i<3;i++);return[i,typeof j]}console.log(f(2));"`;
29912997

2998+
exports[`syntax-printer improve phase should write less, printing the same: a \`let\` closures created after its declaration write and nothing reads 1`] = `"function f(a){return[1,2].forEach(v=>{}),a+1}console.log(f(1));[3].forEach(function(v){});"`;
2999+
29923000
exports[`syntax-printer improve phase should write less, printing the same: a \`let\` declaration beside one written from a \`const\`, joined, its names mangled 1`] = `"function f(o){let n=o.x,t=o.y;t++;for(let o of[n,t]){let c=o+t,f=[c,c];f.push(n),console.log(f)}}f({x:1,y:2});"`;
29933001

29943002
exports[`syntax-printer improve phase should write less, printing the same: a \`let\` of a \`switch\` case a later case reads, kept 1`] = `"function f(x){switch(x){case 1:let a=[x];case 2:return a}}console.log(f(1));"`;

‎test/unitCases/javascript/printer.unittest.js‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,11 @@ const IMPROVED_CASES = [
495495
"function m() { var t = typeof f; function f() { return x; } const x = 2; let r = []; try { r.push(z); } catch (e) { r.push(e.name); } let z = x + 1; r.push(t, f(), x * 3, z * z); return r; } console.log(m());",
496496
{ compress: {}, mangle: false }
497497
],
498+
[
499+
"a `let` closures created after its declaration write and nothing reads",
500+
"function f(a) { let x, k = function (v) { x = v; return v + 1; }; [1, 2].forEach((v) => { x = v; }); return k(a); } console.log(f(1)); { let y; [3].forEach(function (v) { y = v; }); }",
501+
{ compress: {}, mangle: false }
502+
],
498503
[
499504
"a `let` whose every read folds into its value, left with its write",
500505
"(function () { let x; x = 2; console.log(x); globalThis.g = function () { return x; }; })(); console.log(g());",
@@ -11421,6 +11426,22 @@ x = a ** b ** c; x = (a ** b) ** c; x = (-a) ** b; x = a < b < c; x = a < (b < c
1142111426
}
1142211427
});
1142311428

11429+
it("should drop a write to a `for…of` head's `let` from its body, not its right side", async () => {
11430+
const { minify } = await load();
11431+
for (const input of [
11432+
"export function f(a){let p;for(let x of a)p=()=>{x=3};return p}",
11433+
"export function f(a){for(let x of a)x=1,h(x)}",
11434+
"export function f(a){let p;for(const x of a)p=()=>x;return p}"
11435+
]) {
11436+
const { code } = await minify(input, {
11437+
module: true,
11438+
compress: {},
11439+
mangle: false
11440+
});
11441+
expect(code).toMatchSnapshot();
11442+
}
11443+
});
11444+
1142411445
it("should keep a write to a `let` that may run before its declaration", async () => {
1142511446
const { minify } = await load();
1142611447
for (const input of [
@@ -11429,7 +11450,14 @@ x = a ** b ** c; x = (a ** b) ** c; x = (-a) ** b; x = a < b < c; x = a < (b < c
1142911450
"export function f(){for(;;){x=1;let x}}",
1143011451
"export function f(){let x;window.h=()=>x;x=2}",
1143111452
"export function f(){g();let x;function g(){x=1}}",
11432-
"export function f(){class C{static{x=1}}let x}"
11453+
"export function f(){class C{static{x=1}}let x}",
11454+
"export function f(){h(()=>{x=1});let x}",
11455+
"export function f(){let x=h(()=>{x=1})}",
11456+
"export function f(){let x;h(()=>{x=1});h(()=>x)}",
11457+
"export function f(){for(let x of(g(()=>{x=1}),[]));}",
11458+
"export function f(){for(let x in(x=1,{}));}",
11459+
"export function f(){const w=()=>{x=1};h(w),h(w);let x}",
11460+
"export function f(){let y;const w=()=>{x=1};h(w),h(w);let x}"
1143311461
]) {
1143411462
const { code } = await minify(input, {
1143511463
module: true,
@@ -11438,6 +11466,16 @@ x = a ** b ** c; x = (a ** b) ** c; x = (-a) ** b; x = a < b < c; x = a < (b < c
1143811466
});
1143911467
expect(code).toMatch(/x=[12]/);
1144011468
}
11469+
const { code: inSwitch } = await minify(
11470+
"export function f(a){switch(a){case 0:let x;h(()=>{x=1});break;case 1:h(()=>{x=2})}}",
11471+
{ module: true, compress: {}, mangle: false }
11472+
);
11473+
expect(inSwitch).toContain("x=2");
11474+
const { code } = await minify("let x;h(()=>{x=1})", {
11475+
compress: {},
11476+
mangle: false
11477+
});
11478+
expect(code).toContain("x=1");
1144111479
});
1144211480

1144311481
it("should drop a `#__PURE__` call nothing reads rather than unwrap it", async () => {

0 commit comments

Comments
 (0)