Skip to content

Commit ad1d016

Browse files
feat(javascript): move a value past a read of a built-in in the minifier (#22499)
* feat(javascript): move a value past a read of a built-in in the minifier On the last pass, `collapse_vars` no longer stops at a read of `console`, a built-in global or one of its standard methods, which no value moved past it can change, where the declaration it moves goes away entirely. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * test(javascript): retire an swc exclusion `main` no longer needs `fixture/issues/11684/class-decl` is no bigger than swc's output since the latest minifier changes on `main`. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD
1 parent f9524b3 commit ad1d016

5 files changed

Lines changed: 107 additions & 24 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 92 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18138,6 +18138,39 @@ const installImprove = (modules) => {
1813818138
unusedHooks.dropsCatchBinding = (compressor) =>
1813918139
improvements.enabled && compressor.option("ecma") >= 2019;
1814018140

18141+
/**
18142+
* A global `collapse_vars` may move a value past: a built-in, or `console`,
18143+
* which every host defines and nothing in a bundle is expected to replace.
18144+
* @param {Node} node a name
18145+
* @param {CompressorShape} compressor the compressor
18146+
* @returns {boolean} true for such a global
18147+
*/
18148+
const isBuiltInRead = (node, compressor) =>
18149+
A.isSymbolRefNode(node) &&
18150+
(pureGlobals.has(node.name) || node.name === "console") &&
18151+
isUndeclaredRef(node) &&
18152+
!globalMayBeRebound(compressor);
18153+
18154+
/** @type {CollapseHooks} */
18155+
const collapseHooks = modules.webpackCollapse;
18156+
collapseHooks.readsBuiltIn = (node, compressor, movesEffects) => {
18157+
if (!improvements.enabled) return false;
18158+
// Code a moved value runs may patch `console`, which bundles do.
18159+
if (A.isSymbolRefNode(node)) {
18160+
return (
18161+
isBuiltInRead(node, compressor) &&
18162+
!(movesEffects && node.name === "console")
18163+
);
18164+
}
18165+
if (!A.isDotNode(node) || node.optional) return false;
18166+
const { object } = node;
18167+
if (!isBuiltInRead(object, compressor)) return false;
18168+
// A console's members are its methods; a built-in's, the standard ones.
18169+
if (object.name === "console") return !movesEffects;
18170+
const statics = callableStatics.get(object.name);
18171+
return statics !== undefined && statics.has(node.property.name);
18172+
};
18173+
1814118174
const constructedWhenCalled = new Set(foldedTables.constructedWhenCalled);
1814218175

1814318176
/**
@@ -23295,6 +23328,12 @@ const installDropSideEffectFree = ({
2329523328
};
2329623329
};
2329723330

23331+
/**
23332+
* @typedef {object} CollapseHooks what later phases add to `collapse_vars`
23333+
* @property {((node: Node, compressor: CompressorShape, movesEffects: boolean) => boolean) | null} readsBuiltIn whether a node only reads a built-in global or one of its members, which no value moved past it can change, given whether that value has effects
23334+
* @property {boolean} finalPass whether the pass running is the last one asked for
23335+
*/
23336+
2329823337
/**
2329923338
* Creates terser's `tighten_body`, which joins, reorders and drops the
2330023339
* statements of a block and folds assignments into their first use.
@@ -23304,6 +23343,10 @@ const installDropSideEffectFree = ({
2330423343
const createTightenBody = (modules) => {
2330523344
const { transformNode, walkNode } = modules.ast;
2330623345
const { ast, common, flags, inference, nativeObjects, utils } = modules;
23346+
// What a later phase lets `collapse_vars` move a value past.
23347+
/** @type {CollapseHooks} */
23348+
const collapseHooks = { readsBuiltIn: null, finalPass: true };
23349+
modules.webpackCollapse = collapseHooks;
2330723350
const {
2330823351
ArrayNode,
2330923352
isArrowNode,
@@ -24293,7 +24336,8 @@ const createTightenBody = (modules) => {
2429324336
isSymbolRefNode(node) &&
2429424337
!ast.isDeclared(node, compressor) &&
2429524338
// Likely a terser bug: a set of names asked for a node is never true.
24296-
!purePropertyAccessGlobals.has(node)) ||
24339+
!purePropertyAccessGlobals.has(node) &&
24340+
!readsBuiltIn(state, node)) ||
2429724341
(isSymbolRefNode(node) &&
2429824342
isCallNode(parent) &&
2429924343
hasAnnotation(parent, _NOINLINE)) ||
@@ -24384,13 +24428,16 @@ const createTightenBody = (modules) => {
2438424428
isPropAccessNode(lhs) ||
2438524429
mayModify(state, lhs))) ||
2438624430
(isPropAccessNode(node) &&
24387-
(state.sideEffects || ast.mayThrowOnAccess(node.object, compressor))) ||
24431+
(state.sideEffects || ast.mayThrowOnAccess(node.object, compressor)) &&
24432+
!readsBuiltIn(state, node)) ||
2438824433
(isSymbolRefNode(node) &&
2438924434
((hasLeftValue(state, node.name) &&
2439024435
/** @type {{ modified: boolean }} */ (
2439124436
leftValues(state).get(node.name)
2439224437
).modified) ||
24393-
(state.sideEffects && mayModify(state, node)))) ||
24438+
(state.sideEffects &&
24439+
mayModify(state, node) &&
24440+
!readsBuiltIn(state, node)))) ||
2439424441
(isVarDefNode(node) &&
2439524442
node.init &&
2439624443
(hasLeftValue(state, node.id.name) ||
@@ -24928,6 +24975,44 @@ const createTightenBody = (modules) => {
2492824975
return false;
2492924976
};
2493024977

24978+
/**
24979+
* Whether a node only reads a built-in global or one of its members.
24980+
* @param {CollapseState} state the run's state
24981+
* @param {Node} node a node
24982+
* @returns {boolean} true where a later phase reads it so
24983+
*/
24984+
const readsBuiltIn = (state, node) =>
24985+
// Moved earlier, a value would hide from later passes what they fold.
24986+
collapseHooks.finalPass &&
24987+
collapseHooks.readsBuiltIn !== null &&
24988+
dropsCandidate(state) &&
24989+
collapseHooks.readsBuiltIn(node, state.compressor, state.sideEffects);
24990+
24991+
/**
24992+
* Whether collapsing the candidate leaves nothing of it behind.
24993+
* @param {CollapseState} state the run's state
24994+
* @returns {boolean} true for a declaration of a name read once and written nowhere else
24995+
*/
24996+
const dropsCandidate = (state) => {
24997+
const { candidate, compressor } = state;
24998+
if (!isVarDefNode(candidate) || isSymbolFunargNode(candidate.id)) {
24999+
return false;
25000+
}
25001+
const candidateDefinition = candidate.id.definition;
25002+
return (
25003+
candidateDefinition.references.length - candidateDefinition.replaced ===
25004+
1 &&
25005+
candidateDefinition.identifiers.length === 1 &&
25006+
!candidateDefinition.assignments &&
25007+
!compressor.exposed(candidateDefinition) &&
25008+
!(
25009+
candidateDefinition.global &&
25010+
compressor.top_retain &&
25011+
compressor.top_retain(candidateDefinition)
25012+
)
25013+
);
25014+
};
25015+
2493125016
/**
2493225017
* terser's `may_modify`.
2493325018
* @param {CollapseState} state the run's state
@@ -26790,7 +26875,10 @@ const installStatementOptimizers = (modules, helpers) => {
2679026875
let minimumCount = Infinity;
2679126876
let stopping = false;
2679226877
const mangle = this.mangle_options();
26878+
/** @type {CollapseHooks} */
26879+
const collapseHooks = modules.webpackCollapse;
2679326880
for (let pass = 0; pass < passes; pass++) {
26881+
collapseHooks.finalPass = pass + 1 === passes;
2679426882
ast.figureOutScope(this._toplevel, mangle);
2679526883
if (pass === 0 && this.option("drop_console")) {
2679626884
// Before `reduce_vars` and the pass itself.
@@ -26829,6 +26917,7 @@ const installStatementOptimizers = (modules, helpers) => {
2682926917
}
2683026918
}
2683126919
}
26920+
collapseHooks.finalPass = true;
2683226921
if (this.option("expression")) {
2683326922
ast.processExpression(this._toplevel, false);
2683426923
}

‎test/helpers/oxcSmaller.js‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,6 @@ const OXC_SMALLER_BY_REASON = [
172172
"swc minifier: fixture/issues/vercel/002/input.js",
173173
"swc minifier: fixture/issues/vercel/004/input.js",
174174
"swc minifier: fixture/next/46887-2/input.js",
175-
"swc minifier: fixture/next/46887/input.js",
176175
"swc minifier: fixture/pr/11381/input.js",
177176
"swc minifier: fixture/pr/6272/input.js",
178177
"swc minifier: fixture/projects/backbone/16/input.js",
@@ -657,10 +656,8 @@ const OXC_SMALLER_BY_REASON = [
657656
"swc minifier: fixture/issues/emotion/react/2/input.js",
658657
"swc minifier: fixture/issues/firebase-core/1/input.js",
659658
"swc minifier: fixture/issues/firebase/dist/1/input.js",
660-
"swc minifier: fixture/issues/react-autosuggest/1/input.js",
661659
"swc minifier: fixture/issues/react-instancesearch/004/input.js",
662660
"swc minifier: fixture/issues/react/hooks/3/input.js",
663-
"swc minifier: fixture/issues/vercel/005/input.js",
664661
"swc minifier: fixture/next/31077/static/chunks/1606726a.10299989c08cb523/input.js",
665662
"swc minifier: fixture/next/33265/static/chunks/pages/index-cb36c1bf7f830e3c/input.js",
666663
"swc minifier: fixture/next/36127/2/3/input.js",
@@ -692,7 +689,6 @@ const OXC_SMALLER_BY_REASON = [
692689
"swc minifier: fixture/projects/next/archive-3/pages/dynamic/ssr-true-6d4aa8fc503b9d073aef/input.js",
693690
"swc minifier: fixture/projects/react/.6/input.js",
694691
"swc minifier: fixture/projects/wmr/archive-1/chunks/hoofd.module.6c5395cb/input.js",
695-
"swc minifier: full/vercel/ms/1/input.js",
696692
"swc minifier: projects/files/backbone-1.1.0.js",
697693
"swc minifier: projects/files/jquery-1.9.1.js",
698694
"swc minifier: projects/files/jquery.mobile-1.4.2.js",
@@ -778,7 +774,6 @@ const OXC_SMALLER_BY_REASON = [
778774
[
779775
"oxc minifier: peephole/dead_code_elimination.rs:241",
780776
"oxc minifier: peephole/dead_code_elimination.rs:346",
781-
"oxc minifier: peephole/dead_code_elimination.rs:393",
782777
"oxc minifier: peephole/dead_code_elimination.rs:600",
783778
"oxc minifier: peephole/dead_code_elimination.rs:605",
784779
"oxc minifier: peephole/dead_code_elimination.rs:610",
@@ -998,14 +993,11 @@ const OXC_SMALLER_BY_REASON = [
998993
"swc exec: terser_issue_1466_same_variable_in_multiple_for_of",
999994
"swc exec: terser_issue_1466_same_variable_in_multiple_for_of_sequences_const",
1000995
"swc exec: terser_issue_1466_same_variable_in_multiple_for_of_sequences_let",
1001-
"swc exec: terser_reduce_vars_issue_3110_3",
1002-
"swc minifier: fixture/issues/5280/input.js",
1003996
"swc minifier: fixture/issues/5846/input.js",
1004997
"swc minifier: fixture/issues/7228/1/input.js",
1005998
"swc minifier: fixture/issues/7770/2/input.js",
1006999
"swc minifier: fixture/issues/next-97517/input.js",
10071000
"swc minifier: fixture/member_expr/callee/input.js",
1008-
"swc minifier: mangle/issue-5766/2/input.js",
10091001
"swc minifier: mangle/issue-5766/for-in/2/input.js",
10101002
"terser compress: block-scope/issue_508",
10111003
"terser compress: collapse_vars/collapse_vars_object",
@@ -1025,9 +1017,6 @@ const OXC_SMALLER_BY_REASON = [
10251017
"terser compress: issue-1466/same_variable_in_multiple_forOf_sequences_const",
10261018
"terser compress: issue-1466/same_variable_in_multiple_forOf_sequences_let",
10271019
"terser compress: issue-1466/same_variable_in_multiple_for_loop",
1028-
"terser compress: reduce_vars/issue_1107",
1029-
"terser compress: reduce_vars/issue_3110_2",
1030-
"terser compress: reduce_vars/issue_3110_3",
10311020
"terser compress: reduce_vars/unsafe_evaluate_side_effect_free_2",
10321021
"terser compress: try-catch/issue_452"
10331022
]
@@ -1198,7 +1187,6 @@ const OXC_SMALLER_BY_REASON = [
11981187
"oxc minifier: peephole/inline_single_use_variable.rs:412",
11991188
"oxc minifier: peephole/inline_single_use_variable.rs:47",
12001189
"oxc minifier: peephole/inline_single_use_variable.rs:533",
1201-
"oxc minifier: peephole/inline_single_use_variable.rs:573",
12021190
"oxc minifier: peephole/inline_single_use_variable.rs:80"
12031191
]
12041192
],

‎test/helpers/swcSmaller.js‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,6 @@ const SWC_SMALLER_BY_REASON = [
235235
"terser compress: collapse_vars/collapse_vars_side_effects_2",
236236
"terser compress: collapse_vars/collapse_vars_while",
237237
"terser compress: collapse_vars/issue_1537_destructuring_1",
238-
"terser compress: collapse_vars/issue_2187_1",
239238
"terser compress: collapse_vars/issue_2436_9",
240239
"terser compress: collapse_vars/var_defs",
241240
"terser compress: collapse_vars/var_side_effects_2",
@@ -588,9 +587,7 @@ const SWC_SMALLER_BY_REASON = [
588587
"swc minifier: fixture/member_expr/callee/input.js",
589588
"swc minifier: fixture/projects/wmr/archive-1/chunks/index.bf24abaa/input.js",
590589
"swc minifier: fixture/projects/wmr/archive-1/chunks/index.ddc4110d/input.js",
591-
"swc minifier: pass-1/issue-6788/1/input.js",
592-
"terser compress: hoist_props/direct_access_2",
593-
"terser compress: template-string/tagged_call_with_invalid_escape_2"
590+
"terser compress: hoist_props/direct_access_2"
594591
]
595592
],
596593
[

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

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,8 +1287,6 @@ const IMPROVED_YET_BIGGER = {
12871287
"214 bytes fewer, 6 more gzipped: `!!x` in place of `null!==x` breaks the runs of `null!==` gzip reused",
12881288
"projects/files/react-17.0.1.js (its own options)":
12891289
"33 bytes fewer, 3 more gzipped: `!!x` in place of `null!==x` breaks the runs of `null!==` gzip reused",
1290-
"benches-full/vue.js (the default minimizer's options)":
1291-
"9 bytes fewer, 6 more gzipped: the shorter `typeof x<\"u\"` and constructor calls break runs gzip reused",
12921290
"fixture/projects/next/.archive-4/framework-054ead69ea8124b4cb27/input.js (its own options)":
12931291
"83 bytes fewer, 8 more gzipped: the shorter `typeof x<\"u\"` breaks the `\"…\"!=typeof` runs gzip reused",
12941292
"fixture/projects/next/.archive-4/framework-054ead69ea8124b4cb27/input.js (the default minimizer's options)":
@@ -1317,8 +1315,6 @@ const IMPROVED_YET_BIGGER = {
13171315
"10 bytes fewer, 7 more gzipped: the folded `[3,2,1].join(\"-\")` matched the one left after it",
13181316
"harmony/issue_2345 (reminify 8 {\"compress\":{\"reduce_funcs\":false}})":
13191317
"10 bytes fewer, 7 more gzipped: the folded `[3,2,1].join(\"-\")` matched the one left after it",
1320-
"fixture/issues/12215/input.js (its own options)":
1321-
"20 bytes fewer, 5 more gzipped: the folded global call matched a shadowed one beside it",
13221318
"issue_8864_1 (its own options)":
13231319
"19 bytes fewer, 1 more gzipped: the folded `toUpperCase()` matched the one left in the template",
13241320
"S15.1.3.3_A4_T2.js (the default minimizer's options)":
@@ -1615,6 +1611,13 @@ for (const [reason, keys] of /** @type {[string, string[]][]} */ ([
16151611
"fixture/issues/string-index-utf16/input.js (the default minimizer's options)"
16161612
]
16171613
],
1614+
[
1615+
"a value read where a built-in read stood between, where the source repeats the declaration gzip matched",
1616+
[
1617+
"regress-1383630.js (the default minimizer's options)",
1618+
"reviver-forward-modifies-object.js (the default minimizer's options)"
1619+
]
1620+
],
16181621
[
16191622
"a pattern's unused names dropped where the source repeats the pattern gzip matched",
16201623
[

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,10 @@ const IMPROVED_CASES = [
605605
"an array of strings split beside long arrays holding a number or a hole, left alone",
606606
`var a = ${stringArray(100)}, b = ${stringArray(100).slice(0, -1)}, 1], c = ${stringArray(100).slice(0, -1)}, , "z"]; console.log(a.length, typeof b[100], 100 in c, c.length);`
607607
],
608+
[
609+
"a value moved past a read of `console`, a built-in or one of its methods",
610+
"function f(x) { var r = x + 1, a = r * r - r; console.log(a + 7); var v = g(); console.log(Math.max(v, 1)); var c; c = 2; console.log(c); } function g() { return 3; } f(1);"
611+
],
608612
[
609613
"an array of empty strings",
610614
`var a = ${stringArray(100, () => "")}; console.log(a.length, a.every((s) => s === ""));`
@@ -715,6 +719,8 @@ const KEPT_CASES = [
715719
["`new.target`", `!function () { ${TRY} console.log(new.target); }();`],
716720
["an arrow reading `this`", `!function () { ${TRY} [1].map(() => this); }();`],
717721
["an arrow calling `eval`", `!function () { ${TRY} [1].map(() => eval("this")); }();`],
722+
["a value with effects kept before a read of `console`, which it may patch", 'var log = console.log; function g() { console.log = function (x) { log("patched", x); }; return 1; } function f() { var v = g(); console.log(v); console.log = log; } f(); f();'],
723+
["a value kept before a global no built-in names, a member a built-in computes, a shadowed built-in, or a built-in the value writes", 'function f(Math) { var v = g(); h(v); var w = g(); console.log(RegExp.$1, w); var x = g(); console.log(Math.max(x)); } function k() { var o = console; var u = (console = { log: function () { o.log("new"); } }, 1); console.log(u); console = o; } var h = console.log; function g() { return 2; } f({ max: String }); k();'],
718724
["a parameter given an argument", `!function (a) { ${TRY} console.log(a); }(Math.random());`],
719725
["a parameter given nothing", `!function (a) { ${TRY} console.log(a, a = Math.random()); }();`],
720726
["a name", `!function f() { ${TRY} console.log(f); }();`],
@@ -5697,7 +5703,7 @@ describe("syntax-printer", () => {
56975703
["function f(c) { return null == c ? void 0 : c?.a; } console.log(f(null), f({ a: 1 }));", target(2021)],
56985704
["var o = { p: 0, q: 1 }; function f(k) { o[k + 1] || (o[k + 1] = 2); return o; } console.log(f(\"p\"), f(\"q\"));", target(2021)],
56995705
["var g = function f() { \"use strict\"; try { f = f || 1; } catch (e) { return e.name; } return typeof f; }; console.log(g());", target(2021)],
5700-
["x = x || 1; var x; console.log(x);", target(2021)],
5706+
["x = x || 1; var x; print(x); function print(v) { console.log(v); }", target(2021)],
57015707
["console.log(function () { var other = {}, o = { get p() { o = other; return 0; }, set p(v) {} }, first = o; o.p || (o.p = 1); return [first === o, other.p]; }());", target(2021)],
57025708
["var n = 0; Object.defineProperty(globalThis, \"a\", { get: function () { return n++ ? null : { p: 1 }; }, configurable: true }); function f() { return null == a ? void 0 : a.p; } try { console.log(f()); } catch (e) { console.log(e.name); }", target(2021)],
57035709
["function f(o, c) { with (o) { return null == c ? void 0 : c.p; } } console.log(f({}, null), f({ c: { p: 2 } }, { p: 1 }));", target(2021)],

0 commit comments

Comments
 (0)