Skip to content

Commit b4d6769

Browse files
feat(javascript): read a copied binding in place of a var copying it in the minifier (#22574)
* feat(javascript): read a copied binding in place of a `var` copying it in the minifier The improve phase read `y` for `x` where `let x = y` or `const x = y` only copies it. A `var` does now too, the copy TypeScript's `for…of` loops make (`for (var _i = 0, array_1 = array; …)`) and terser leaves after inlining among them: `x` is dropped once nothing reads it. Neither name may be written again, `x` must be read only after it is set (terser's `fixed`), and `y` must be what its name finds at each read, looked up from the block around the read, since a `var`'s read holds its function's scope. `y` must be set once each time the `var`'s function runs (a parameter, `let` or `const` declared there or around it), or else be a `var` or function beside it no function inside the `var`'s reads, as a loop may set it again. The read made is now counted among `y`'s reads: before, `y` read once could still have its value inlined at the copy's declaration, leaving the new read reading nothing, as `let v = this.v; let m = v;` did. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * fix(javascript): leave a `var` read once copying a parameter of a call in place to terser in the minifier Reading the parameter in the copy's place counted it twice, so terser kept the argument the call passes instead of writing it in, e.g. `...(e=yield,{...e})` for `...{...yield}`. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * fix(javascript): record a copied binding as captured where its read replaces a copy in the minifier A function reading `y` in place of a copy never listed `y` among the bindings it captures, so inlining it into a function declaring that name again read the inner binding instead. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * test: retire swc's react/9 project from the cases swc minifies smaller Reading a copied `var` in place of the copy leaves react/9 no bigger than swc's output. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD
1 parent 6525560 commit b4d6769

4 files changed

Lines changed: 116 additions & 17 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 85 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20772,8 +20772,53 @@ const installImprove = (modules) => {
2077220772
node.definition.assignments === 0;
2077320773

2077420774
/**
20775-
* `y` read in place of `x` where `let x = y` only copies it: neither name
20776-
* is written again, `x` is read only after it is set, and `y` is found there.
20775+
* Whether a scope is another or one around it.
20776+
* @param {Scope} outer the scope that may be around
20777+
* @param {Scope} inner the scope it may be around
20778+
* @returns {boolean} true when it is
20779+
*/
20780+
const isScopeOrAround = (outer, inner) => {
20781+
for (
20782+
let scope = /** @type {Scope | null} */ (inner);
20783+
scope;
20784+
scope = scope.upper
20785+
) {
20786+
if (scope === outer) return true;
20787+
}
20788+
return false;
20789+
};
20790+
20791+
/**
20792+
* Whether every read of a `var` copying a binding finds the value it was set
20793+
* from: a parameter, `let` or `const` set once each time the `var`'s function
20794+
* runs, or a `var` or function beside it no function inside reads, as a loop
20795+
* may set it again.
20796+
* @param {Definition} definition the `var`
20797+
* @param {Definition} target the binding it copies
20798+
* @returns {boolean} true when every read does
20799+
*/
20800+
const copiesForEveryRead = (definition, target) => {
20801+
const declaration = target.identifiers[0];
20802+
if (
20803+
A.isSymbolFunargNode(declaration) ||
20804+
A.isSymbolLetNode(declaration) ||
20805+
A.isSymbolConstNode(declaration)
20806+
) {
20807+
return isScopeOrAround(target.scope, definition.scope);
20808+
}
20809+
return (
20810+
target.scope === definition.scope &&
20811+
definition.references.every(
20812+
(/** @type {Node} */ reference) =>
20813+
reference.scope.getDefunScope() === definition.scope
20814+
)
20815+
);
20816+
};
20817+
20818+
/**
20819+
* `y` read in place of `x` where `let x = y`, or `const` or `var`, only
20820+
* copies it: neither name is written again, `x` is read only after it is
20821+
* set, and `y` is found there.
2077720822
* @param {Node} ref a read terser has optimized
2077820823
* @param {CompressorShape} compressor the compressor
2077920824
* @returns {Node | undefined} the read of `y`, or undefined
@@ -20788,7 +20833,11 @@ const installImprove = (modules) => {
2078820833
copiedThroughout(/** @type {Definition} */ (definition))
2078920834
) ||
2079020835
definition.identifiers.length !== 1 ||
20791-
!(A.isSymbolLetNode(declaration) || A.isSymbolConstNode(declaration)) ||
20836+
!(
20837+
A.isSymbolLetNode(declaration) ||
20838+
A.isSymbolConstNode(declaration) ||
20839+
(A.isSymbolVarNode(declaration) && !A.isSymbolFunargNode(declaration))
20840+
) ||
2079220841
compressor.exposed(definition) ||
2079320842
!staysPut(ref, compressor)
2079420843
) {
@@ -20823,18 +20872,46 @@ const installImprove = (modules) => {
2082320872
) {
2082420873
return undefined;
2082520874
}
20875+
let scope = /** @type {Scope} */ (/** @type {unknown} */ (ref.scope));
20876+
if (A.isSymbolVarNode(declaration)) {
20877+
// A read of a `var` holds its function's scope, not the block's around it.
20878+
const nearest = /** @type {Scope | undefined} */ (
20879+
compressor.find_scope()
20880+
);
20881+
// A `var` read once copying a parameter of a call in place is terser's to
20882+
// collapse: read twice, that parameter's argument stays where it is.
20883+
if (
20884+
(definition.references.length < 2 &&
20885+
A.isSymbolFunargNode(targetDeclaration) &&
20886+
target.fixed) ||
20887+
!nearest ||
20888+
nearest.findVariable(value.name) !== target ||
20889+
!copiesForEveryRead(
20890+
/** @type {Definition} */ (definition),
20891+
/** @type {Definition} */ (target)
20892+
)
20893+
) {
20894+
return undefined;
20895+
}
20896+
if (
20897+
A.isSymbolLetNode(targetDeclaration) ||
20898+
A.isSymbolConstNode(targetDeclaration)
20899+
) {
20900+
scope = nearest;
20901+
}
20902+
}
2082620903
const read = makeNode(A.SymbolRefNode, ref, {
2082720904
name: value.name,
2082820905
definition: target,
20829-
scope: ref.scope
20906+
scope
2083020907
});
2083120908
// A function reading `y` now captures it: inlining one into a scope that
2083220909
// declares the name again must see the clash.
20833-
/** @type {Scope} */ (/** @type {unknown} */ (ref.scope)).markEnclosed(
20834-
/** @type {Definition} */ (target)
20835-
);
20836-
// Counted, the read keeps `collapse_vars` from moving `y`'s value away.
20910+
scope.markEnclosed(/** @type {Definition} */ (target));
20911+
// Counted, the read keeps `collapse_vars` from moving `y`'s value away;
20912+
// read again, `y` is no longer read once for inlining at the copy.
2083720913
target.references.push(read);
20914+
target.single_use = false;
2083820915
return read;
2083920916
};
2084020917

‎test/helpers/oxcSmaller.js‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,6 @@ const OXC_SMALLER_BY_REASON = [
200200
"terser compress: class-properties/mangle_class_properties_keep_quoted",
201201
"terser compress: collapse_vars/collapse_rhs_conditional_2",
202202
"terser compress: collapse_vars/collapse_vars_side_effects_2",
203-
"terser compress: collapse_vars/collapse_vars_while",
204203
"terser compress: concat-strings/concat_1",
205204
"terser compress: conditionals/cond_9",
206205
"terser compress: conditionals/ifs_6",
@@ -660,13 +659,11 @@ const OXC_SMALLER_BY_REASON = [
660659
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/no-ssr-custom-loading-7f61b2e27708ca1854e0/input.js",
661660
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/ssr-994266264fb6ff57d32c/input.js",
662661
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/ssr-true-6d4aa8fc503b9d073aef/input.js",
663-
"swc minifier: fixture/projects/react/.6/input.js",
664662
"swc minifier: fixture/projects/wmr/archive-1/chunks/hoofd.module.6c5395cb/input.js",
665663
"swc minifier: projects/files/backbone-1.1.0.js",
666664
"swc minifier: projects/files/jquery-1.9.1.js",
667665
"swc minifier: projects/files/jquery.mobile-1.4.2.js",
668666
"swc minifier: projects/files/mootools-1.4.5.js",
669-
"swc minifier: projects/files/react-17.0.1.js",
670667
"swc minifier: projects/files/underscore-1.5.2.js"
671668
]
672669
],

‎test/helpers/swcSmaller.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -217,16 +217,12 @@ const SWC_SMALLER_BY_REASON = [
217217
"swc minifier: fixture/issues/react/hooks/1/input.js",
218218
"swc minifier: fixture/next/feedback-1/reduced/1/input.js",
219219
"swc minifier: fixture/pr/11446/input.js",
220-
"swc minifier: fixture/projects/react/10/input.js",
221220
"swc minifier: fixture/projects/react/11/input.js",
222-
"swc minifier: fixture/projects/react/9/input.js",
223221
"swc minifier: fixture/projects/yui/11/input.js",
224222
"swc minifier: fixture/reduced/3/input.js",
225223
"terser compress: classes/class_duplication_2",
226224
"terser compress: collapse_vars/collapse_vars_array",
227-
"terser compress: collapse_vars/collapse_vars_closures",
228225
"terser compress: collapse_vars/collapse_vars_side_effects_2",
229-
"terser compress: collapse_vars/collapse_vars_while",
230226
"terser compress: collapse_vars/issue_1537_destructuring_1",
231227
"terser compress: collapse_vars/issue_2436_9",
232228
"terser compress: collapse_vars/var_defs",
@@ -744,7 +740,6 @@ const SWC_SMALLER_BY_REASON = [
744740
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/no-ssr-custom-loading-7f61b2e27708ca1854e0/input.js",
745741
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/ssr-994266264fb6ff57d32c/input.js",
746742
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/ssr-true-6d4aa8fc503b9d073aef/input.js",
747-
"swc minifier: fixture/projects/react/.6/input.js",
748743
"swc minifier: fixture/projects/react/14/input.js",
749744
"swc minifier: fixture/projects/wmr/archive-1/chunks/.compat.2f7d9500/input.js",
750745
"swc minifier: fixture/projects/wmr/archive-1/chunks/hoofd.module.6c5395cb/input.js",

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

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,18 @@ const IMPROVED_CASES = [
844844
"var h = (function () { const t = [0, 0]; return function (o) { const s = t; s[0]++; { let t = o; t.v = s[0]; } return o; }; })(); console.log(h({}).v, h({}).v);",
845845
{ compress: { passes: 2 }, mangle: false }
846846
],
847+
[
848+
"a `var` only copying a parameter read as the parameter, the copy a TypeScript `for…of` loop makes among them",
849+
"function contains(array, value) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; if (v === value) return true; } return false; } function f(b) { var a = b; g(); return [a.x, a.y]; } function g() {} console.log(contains([1, 2], 2), contains([], 1), f({ x: 1, y: 2 }));",
850+
{ compress: {}, mangle: false },
851+
"function contains(array,value){for(var _i=0;_i<array.length;_i++){if(array[_i]===value)return!0}return!1}function f(b){return g(),[b.x,b.y]}function g(){}console.log(contains([1,2],2),contains([],1),f({x:1,y:2}));"
852+
],
853+
[
854+
"a `var` copying a parameter, read inside a class whose name the parameter's was",
855+
"function f(b) { var a = b; g(b); return new (class b { m() { return [a, a]; } })().m(); } function g() {} console.log(f(1));",
856+
{ compress: { passes: 2 }, mangle: false },
857+
"function f(b){return g(b),(new class{m(){return[b,b]}}).m()}function g(){}console.log(f(1));"
858+
],
847859
[
848860
"a function written in place passed the names of its parameters, which it reads instead, its value called, tagged, typed or read past a chain",
849861
'function f(o, k) { var a = (function (o, k) { return o.k ? o.m : o[k]; })(o, k)(), c = typeof (function (o, k) { return o[k] || o.p; })(o, k), d = (function (o, k) { return o?.[o.k]?.[k]; })(o, k).length, e = (function (o, k) { return o[k] ? o.u : o.t; })(o, k)`x`; return [a === o, c, d, e]; } console.log(f({ k: "p", p: { q: "ab" }, m() { return this; }, t(s) { return s[0]; } }, "q"));',
@@ -1119,6 +1131,10 @@ const KEPT_CASES = [
11191131
["a `let` copying a parameter a `var`, a pattern or a loop head writes later", "function g(...a) { return a.join(); } function f(a) { let x = a; var a = 2; return g(x); } function h(a) { let x = a; [a] = [2]; return g(x); } function k(a) { let x = a; for (a of [2]); return g(x, a); } console.log(f(1), h(1), k(1));"],
11201132
["a `let` copying a binding declared after it", "function f() { let b = c; let c = 1; return b; } try { console.log(f()); } catch (e) { console.log(e.name); }"],
11211133
["a `let` copying a longer name read more than once, where names keep their length", "function f(longBinding) { let x = longBinding; g(); return x + x + x; } function g() {} console.log(f(1));"],
1134+
["a `var` read once copying a parameter of a function called in place, whose argument terser writes in its place", "function* gen() { yield { ...(function (arg) { var y = arg; return { ...y }; })(yield) }; } var it = gen(); it.next(); console.log(it.next({ a: 1 }).value);"],
1135+
["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));"],
1136+
["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(); }));"],
1137+
["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(); }));"],
11221138
["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);'],
11231139
["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()));'],
11241140
["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: [] }));'],
@@ -6890,7 +6906,7 @@ describe("syntax-printer", () => {
68906906
it("should keep a binding read in place of its copy captured where a function declaring its name inlines the reader", async () => {
68916907
const { minify } = await load();
68926908
const input =
6893-
"function inner(b) { let a = b; g(b); var f = function () { return a + a; }; return function (b) { return [f(), b]; }; } function g() {} console.log(inner(1)(2));";
6909+
"function outer(b) { var a = b; g(b); var f = function () { return [a, a]; }; return function (b) { return f().concat(b); }; } function inner(b) { let a = b; g(b); var f = function () { return a + a; }; return function (b) { return [f(), b]; }; } function g() {} console.log(outer(1)(2), inner(1)(2));";
68946910
for (const options of [
68956911
{ compress: { passes: 2 }, mangle: false },
68966912
{ compress: { passes: 3 } }
@@ -6902,6 +6918,20 @@ describe("syntax-printer", () => {
69026918
}
69036919
});
69046920

6921+
it("should keep the value of a binding read again in place of its copy", async () => {
6922+
const { minify } = await load();
6923+
const input =
6924+
"function f() { var v = this.v; var m = v; return g(m) ? m : [m]; } function h() { let v = this.v; let m = v; return g(m) ? m : [m]; } function g(x) { return void 0 === x; } console.log(f.call({ v: 1 }), h.call({ v: 2 }));";
6925+
const { code } = await minify(input, {
6926+
compress: { passes: 2 },
6927+
mangle: false
6928+
});
6929+
expect(runProgram(/** @type {string} */ (code))).toBe(runProgram(input));
6930+
expect(code).toBe(
6931+
"function f(){var v=this.v;return g(v)?v:[v]}function h(){let v=this.v;return g(v)?v:[v]}function g(x){return void 0===x}console.log(f.call({v:1}),h.call({v:2}));"
6932+
);
6933+
});
6934+
69056935
it("should split a `return` of `undefined` outside a function", async () => {
69066936
const { minify } = await load();
69076937
const { code } = await minify("if (a()) { b(); return; } c();", {

0 commit comments

Comments
 (0)