Skip to content

Commit d237ab7

Browse files
feat(javascript): unwrap a function called in place whose var name is taken (#22621)
* feat(javascript): unwrap a function called in place whose var name is taken A function called in place whose one `var` shares a name with another in the function around it now runs in place there, the `var` taking a name of its own, as React's dev build calls its log toggles. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * test: update minify-corpora tables for renamed vars run in place Retire react-17.0.1.js from the swc table, and list a test262 case whose loops now run in place shorter yet a few bytes worse gzipped. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * fix(javascript): keep a function called in place whose renamed `var` shares its name with a class there Renaming the `var` collected every declaration of its name in the function, so a class in a nested block took the new name and its `.name` changed. The function is now kept where anything but a `var` declares the name. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD
1 parent fa15f02 commit d237ab7

5 files changed

Lines changed: 132 additions & 14 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 88 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18175,6 +18175,11 @@ const installImprove = (modules) => {
1817518175
const moved = new Map();
1817618176
/** @type {Set<string>} */
1817718177
const names = new Set();
18178+
// A name also met elsewhere in the scope, and every name met there.
18179+
/** @type {Set<string>} */
18180+
const clashing = new Set();
18181+
/** @type {Set<string>} */
18182+
const seen = new Set();
1817818183
for (const expression of droppedExpressions(statement)) {
1817918184
/** @type {string[]} */
1818018185
const own = [];
@@ -18183,34 +18188,107 @@ const installImprove = (modules) => {
1818318188
const ownNames = new Set(own);
1818418189
// Two functions declaring one name would share one binding there.
1818518190
for (const name of ownNames) {
18186-
if (names.has(name)) return undefined;
18191+
if (names.has(name)) clashing.add(name);
1818718192
names.add(name);
1818818193
}
1818918194
moved.set(fn, ownNames);
1819018195
}
18191-
let clash = false;
1819218196
/**
1819318197
* @param {Set<string>} allowed the names a node may read as its own
1819418198
* @returns {Walker} a walk finding a name it would read from elsewhere
1819518199
*/
1819618200
const findClash = (allowed) =>
1819718201
A.createWalker((/** @type {Node} */ node) => {
18198-
if (clash) return true;
1819918202
const own = moved.get(node);
1820018203
if (own !== undefined && own !== allowed) {
1820118204
walkNode(node, findClash(own));
1820218205
return true;
1820318206
}
18204-
if (
18205-
A.isSymbolNode(node) &&
18206-
names.has(node.name) &&
18207-
!allowed.has(node.name)
18208-
) {
18209-
clash = true;
18207+
if (!A.isSymbolNode(node)) return;
18208+
seen.add(node.name);
18209+
if (names.has(node.name) && !allowed.has(node.name)) {
18210+
clashing.add(node.name);
1821018211
}
1821118212
});
1821218213
walkNode(scope, findClash(new Set()));
18213-
return clash ? undefined : scope;
18214+
// Mangling names the tree afresh, so a `var` moving out takes a name
18215+
// the scope never spells, and binds there apart from the one it met.
18216+
// More of them than one cost longer names there than they save.
18217+
for (const [fn, own] of moved) {
18218+
for (const name of own) {
18219+
if (
18220+
clashing.has(name) &&
18221+
(own.size > 1 || declaresOtherwise(fn, name))
18222+
) {
18223+
return undefined;
18224+
}
18225+
}
18226+
}
18227+
for (const [fn, own] of moved) {
18228+
for (const name of own) {
18229+
if (clashing.has(name)) renameVar(fn, name, seen);
18230+
}
18231+
}
18232+
return scope;
18233+
};
18234+
18235+
/**
18236+
* @param {Node} fn a function called in place
18237+
* @param {string} name a name its `var` declares
18238+
* @returns {boolean} whether something else there declares the name too, as a block's class
18239+
*/
18240+
const declaresOtherwise = (fn, name) => {
18241+
let found = false;
18242+
walkNode(
18243+
fn,
18244+
A.createWalker((/** @type {Node} */ node) => {
18245+
if (found || (A.isLambdaNode(node) && node !== fn)) return true;
18246+
if (
18247+
A.isSymbolDeclarationNode(node) &&
18248+
node.name === name &&
18249+
!A.isSymbolVarNode(node)
18250+
) {
18251+
found = true;
18252+
}
18253+
})
18254+
);
18255+
return found;
18256+
};
18257+
18258+
/**
18259+
* Gives the `var` a function declares under a name another one never used.
18260+
* @param {Node} fn the function
18261+
* @param {string} name the name its `var` declares
18262+
* @param {Set<string>} seen the names already met, the new one joining them
18263+
*/
18264+
const renameVar = (fn, name, seen) => {
18265+
let fresh = name;
18266+
for (let i = 0; seen.has(fresh); i++) fresh = `${name}$${i}`;
18267+
seen.add(fresh);
18268+
/** @type {Set<SymbolDefinition>} */
18269+
const definitions = new Set();
18270+
walkNode(
18271+
fn,
18272+
A.createWalker((/** @type {Node} */ node) => {
18273+
if (A.isLambdaNode(node) && node !== fn) return true;
18274+
if (
18275+
A.isSymbolDeclarationNode(node) &&
18276+
node.name === name &&
18277+
node.definition
18278+
) {
18279+
definitions.add(node.definition);
18280+
}
18281+
})
18282+
);
18283+
walkNode(
18284+
fn,
18285+
A.createWalker((/** @type {Node} */ node) => {
18286+
if (A.isSymbolNode(node) && definitions.has(node.definition)) {
18287+
node.name = fresh;
18288+
}
18289+
})
18290+
);
18291+
for (const definition of definitions) definition.name = fresh;
1821418292
};
1821518293

1821618294
/**

‎test/helpers/swcSmaller.js‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -730,8 +730,7 @@ const SWC_SMALLER_BY_REASON = [
730730
"swc minifier: fixture/reduced/2/input.js",
731731
"swc minifier: full/vercel/ms/1/input.js",
732732
"swc minifier: pass-1/seq/1/input.js",
733-
"swc minifier: projects/files/backbone-1.1.0.js",
734-
"swc minifier: projects/files/react-17.0.1.js"
733+
"swc minifier: projects/files/backbone-1.1.0.js"
735734
]
736735
],
737736
[

‎test/specCases/minify-corpora.spectest.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1744,6 +1744,10 @@ for (const [reason, keys] of /** @type {[string, string[]][]} */ ([
17441744
"valid-rounding-increments.js (the default minimizer's options)"
17451745
]
17461746
],
1747+
[
1748+
"loops run in place, each counter taking a name of its own where the copies of one `for (var e = 0; e <` gzip matched",
1749+
["element-setting-converts-using-ToNumber.js (the default minimizer's options)"]
1750+
],
17471751
[
17481752
"a catch's `return` dropped where the function returns anyway, in a source too short for gzip to gain",
17491753
["peephole/minimize_exit_points.rs:101 (the default minimizer's options)"]

‎test/unitCases/__snapshots__/syntax-printer.unittest.js.snap‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ Array [
7474
]
7575
`;
7676

77+
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\\");"`;
78+
79+
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);"`;
80+
7781
exports[`syntax-printer improve phase should write the \`const\` declarations of a body moved up in place as one \`let\` 1`] = `"export function f(a){let b=a.x(),c=a.y();return a.z(b,c),b+c}"`;
7882

7983
exports[`syntax-printer printEstree should map as terser does: "a directive"; debugger; {} ;\\nlabel: for (;;) { break label; 1`] = `

‎test/unitCases/syntax-printer.unittest.js‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,21 @@ const IMPROVED_CASES = [
304304
"function f(x) { console.log(x); (function () { if (x) { var a = console.log.name; console.log(a, a); } })(); } f(1); f(0);",
305305
{ compress: {}, mangle: false }
306306
],
307+
[
308+
"a `var` moving to the function around the call under a name of its own, where that name is taken",
309+
"function f(x) { var a = g(); console.log(x); (function () { if (x) { var a = console.log.name; console.log(a, a); } })(); (function () { if (!x) { var a = typeof x; console.log(a, a); } })(); console.log(a); } function g() { return 'outer'; } f(1); f(0);",
310+
{ compress: {}, mangle: false }
311+
],
312+
[
313+
"a `var` moving to the function around the call under a name of its own, where that function names it elsewhere",
314+
'var a = "g"; function f(x) { (function () { if (x) { var a = console.log.name; console.log(a, a); } })(); console.log(a); } f(1);',
315+
{ compress: {}, mangle: false }
316+
],
317+
[
318+
"two functions called in place each declaring one `var` a closure keeps, or reading a name the other declares, moving under names of their own",
319+
'function h(x, r) { (function () { if (x) { var a = x.p; r.push(() => a + a); } })(); (function () { if (x) { var a = x.q; r.push(() => a + a); } })(); } function k(x) { (function () { if (x) { var b = x.q; console.log(a, b, b); } })(); (function () { if (x) { var a = x.p; console.log(a, a); } })(); } var a = "outer", r = []; h({ p: 1, q: 2 }, r); k({ p: 1, q: 2 }); console.log(r.map((f) => f()));',
320+
{ compress: {}, mangle: false }
321+
],
307322
[
308323
"a `var` moving into a function called in place, which then stays one",
309324
"function f(x) { (function () { if (x) { var a = console.log.name; console.log(a, a); } (function () { if (x) { var b = console.log.name; console.log(b, b); } })(); })(); } f(1);",
@@ -1220,8 +1235,7 @@ const KEPT_CASES = [
12201235
["a `var` copying a parameter, read in a block declaring the parameter's name, or in a class of that name", "function f(b) { var a = b; g(b); { let b = 9; g(b); return [a, b]; } } function h(b) { var a = b; g(b); return new (class b { m() { return a; } })().m(); } function g() {} console.log(f(1), h(1));"],
12211236
["a `var` copying a `var` a loop sets again, read by a function inside", "var fns = []; function f(n) { for (var i = 0; i < n; i++) { var b = i * 2; var a = b; g(b); fns.push(function () { return a; }); } } function g() {} f(2); console.log(fns.map(function (h) { return h(); }));"],
12221237
["a `var` copying a `let` a loop declares each time round, read by a function inside", "var fns = []; function f(list) { for (let b of list) { var a = b; g(b); fns.push(function () { return a; }); } } function g() {} f([1, 2]); console.log(fns.map(function (h) { return h(); }));"],
1223-
["a `var` the function around the call names elsewhere, or a call it repeats", 'var a = "g"; function f(x) { (function () { if (x) { var a = console.log.name; console.log(a, a); } })(); console.log(a); for (var i = 0; i < 2; i++) (function () { var b; if (i) b = i; console.log(b); })(); } f(1);'],
1224-
["two functions called in place declaring one `var` a closure keeps, or reading a name the other declares", 'function h(x, r) { (function () { if (x) { var a = x.p; r.push(() => a + a); } })(); (function () { if (x) { var a = x.q; r.push(() => a + a); } })(); } function k(x) { (function () { if (x) { var b = x.q; console.log(a, b, b); } })(); (function () { if (x) { var a = x.p; console.log(a, a); } })(); } var a = "outer", r = []; h({ p: 1, q: 2 }, r); k({ p: 1, q: 2 }); console.log(r.map((f) => f()));'],
1238+
["a call a loop repeats", "function f() { for (var i = 0; i < 2; i++) (function () { var b; if (i) b = i; console.log(b); })(); } f();"],
12251239
["a function called in place inside `with`, whose `var` the object could answer for", 'function f(o) { with (o) { (function () { if (o) { var a = r.length + 1; r.push(() => a + a); } })(); } return o.r.map((g) => g()); } console.log(f({ a: 2, r: [] }));'],
12261240
["a `return`", `!function () { for (let x of [1, 2]) { ${TRY} if (x) return; } console.log(2); }();`],
12271241
["`this`", `!function () { ${TRY} console.log(this); }();`],
@@ -7656,6 +7670,25 @@ describe("syntax-printer", () => {
76567670
}
76577671
});
76587672

7673+
it("should keep a function called in place whose `var`s, more than one, take names already taken", async () => {
7674+
const { minify } = await load();
7675+
const input =
7676+
"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);";
7677+
const { code } = await minify(input, { compress: {}, mangle: false });
7678+
expect(runProgram(/** @type {string} */ (code))).toBe(runProgram(input));
7679+
expect(code).toContain("function(){");
7680+
expect(code).toMatchSnapshot();
7681+
});
7682+
7683+
it("should keep a function called in place whose `var`, its name taken, a class in a block there also names", async () => {
7684+
const { minify } = await load();
7685+
const input =
7686+
"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');";
7687+
const { code } = await minify(input, { compress: {}, mangle: false });
7688+
expect(runProgram(/** @type {string} */ (code))).toBe(runProgram(input));
7689+
expect(code).toMatchSnapshot();
7690+
});
7691+
76597692
it("should keep an assignment to a `let` before the declaration in its block", async () => {
76607693
const { minify } = await load();
76617694
const input =

0 commit comments

Comments
 (0)