Skip to content

Commit 9377120

Browse files
committed
fix(javascript): scope a parameter list apart from its body in the minifier
A name a parameter default or catch pattern reads resolved to what the body or block declares, as terser scopes it, so the mangler renamed the read onto the inner binding and the compressor dropped the outer one as unused. Such a read now skips the body's bindings. Moves 42 test262 cases off the printer's list; minifying a 1 MB bundle is within noise.
1 parent 47ace05 commit 9377120

5 files changed

Lines changed: 165 additions & 17 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+
Keep a name a parameter list or catch parameter reads from resolving to what the function body or catch block declares, which the minifier renamed or dropped as unused.

‎lib/javascript/ScopeAnalyzer.js‎

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,6 +1228,10 @@ class MinifierScope extends Scope {
12281228
this.usesWith = false;
12291229
/** @type {MinifierVariable | null} a function expression's own name */
12301230
this.functionName = null;
1231+
/** @type {number} the first name its parameter list reads, as the analysis counts them, or -1 */
1232+
this.parameterStart = -1;
1233+
/** @type {number} the name after the last its parameter list reads, or -1 */
1234+
this.parameterEnd = -1;
12311235
}
12321236

12331237
/**
@@ -1666,6 +1670,7 @@ const createCompressorScope = (type, node, upper, isVarScope) =>
16661670
* @property {boolean=} ie8 whether catch parameters belong to their function
16671671
* @property {boolean=} safari10 whether a loop's scope reads its parent's names, and catch parameters belong to their function
16681672
* @property {EXPECTED_ANY=} keep_fnames which function names survive, collecting the declarators naming one
1673+
* @property {boolean=} parameterScopes whether a name read in a parameter list or a catch parameter skips what the body declares, as the spec scopes it
16691674
*/
16701675

16711676
/**
@@ -1699,28 +1704,52 @@ const isExport = (node) =>
16991704
node.type === "ExportDefaultDeclaration" ||
17001705
node.type === "ExportAllDeclaration";
17011706

1707+
/**
1708+
* @param {MinifierScope} scope the scope declaring it
1709+
* @param {MinifierVariable} variable a definition
1710+
* @param {number} read the read's place in the analysis's count
1711+
* @returns {boolean} whether the read sits in the scope's parameter list and the definition in its body, which the list cannot see
1712+
*/
1713+
const isHiddenFromParameters = (scope, variable, read) =>
1714+
read < scope.parameterEnd &&
1715+
read >= scope.parameterStart &&
1716+
variable.kind !== DECLARES_FUNARG &&
1717+
variable.kind !== DECLARES_LAMBDA &&
1718+
variable.kind !== DECLARES_CATCH;
1719+
17021720
/**
17031721
* @param {MinifierScope} from the scope a name is read in
17041722
* @param {string} name the name
1723+
* @param {number=} read the read's place in the analysis's count, under `parameterScopes`
17051724
* @returns {MinifierVariable | undefined} what it resolves to from there
17061725
*/
1707-
const findMinifierVariable = (from, name) => {
1726+
const findMinifierVariable = (from, name, read = -1) => {
17081727
for (let scope = /** @type {Scope | null} */ (from); scope !== null;) {
17091728
// `getBinding`, inlined: the interpreter pays a call per scope climbed
17101729
const index = scope._index;
1730+
/** @type {MinifierVariable | undefined} */
1731+
let variable;
17111732
if (index !== undefined) {
1712-
const variable = index.get(name);
1713-
if (variable !== undefined) {
1714-
return /** @type {MinifierVariable} */ (variable);
1715-
}
1733+
variable = /** @type {MinifierVariable | undefined} */ (index.get(name));
17161734
} else {
17171735
const variables = scope.variables;
17181736
for (let i = 0; i < variables.length; i++) {
17191737
if (variables[i].name === name) {
1720-
return /** @type {MinifierVariable} */ (variables[i]);
1738+
variable = /** @type {MinifierVariable} */ (variables[i]);
1739+
break;
17211740
}
17221741
}
17231742
}
1743+
if (
1744+
variable !== undefined &&
1745+
!isHiddenFromParameters(
1746+
/** @type {MinifierScope} */ (scope),
1747+
variable,
1748+
read
1749+
)
1750+
) {
1751+
return variable;
1752+
}
17241753
scope = scope.upper;
17251754
}
17261755
return undefined;
@@ -1763,6 +1792,8 @@ class MinifierScopeAnalyzer extends ScopeAnalyzer {
17631792
this.legacyCatch = Boolean(options.ie8 || options.safari10);
17641793
/** @type {boolean} */
17651794
this.safari10 = Boolean(options.safari10);
1795+
/** @type {boolean} */
1796+
this.parameterScopes = Boolean(options.parameterScopes);
17661797
/** @type {MinifierScope} */
17671798
this.toplevel = new MinifierScope("global", program, null, true);
17681799
this.scope = this.toplevel;
@@ -2129,9 +2160,13 @@ class MinifierScopeAnalyzer extends ScopeAnalyzer {
21292160
lambda.functionName = /** @type {MinifierVariable} */ (id.definition);
21302161
}
21312162
const { params } = node;
2163+
if (this.parameterScopes) {
2164+
lambda.parameterStart = this.referenceNodes.length;
2165+
}
21322166
for (let i = 0; i < params.length; i++) {
21332167
this._visitBinding(params[i], DECLARES_FUNARG);
21342168
}
2169+
if (this.parameterScopes) lambda.parameterEnd = this.referenceNodes.length;
21352170
if (this.release !== undefined) this.release(node.body);
21362171
this._visitList(node.body.body);
21372172
this.scope = outer;
@@ -2391,7 +2426,14 @@ class MinifierScopeAnalyzer extends ScopeAnalyzer {
23912426
case "CatchClause": {
23922427
stack.push(current);
23932428
const outer = this._enterBlock("catch", current);
2429+
const catchScope = /** @type {MinifierScope} */ (this.scope);
2430+
if (this.parameterScopes) {
2431+
catchScope.parameterStart = this.referenceNodes.length;
2432+
}
23942433
if (current.param) this._visitBinding(current.param, DECLARES_CATCH);
2434+
if (this.parameterScopes) {
2435+
catchScope.parameterEnd = this.referenceNodes.length;
2436+
}
23952437
if (this.release !== undefined) this.release(current.body);
23962438
this._visitList(current.body.body);
23972439
this.scope = outer;
@@ -2604,7 +2646,7 @@ class MinifierScopeAnalyzer extends ScopeAnalyzer {
26042646
let variable =
26052647
flags & REFERENCE_FROM_MODULE
26062648
? undefined
2607-
: findMinifierVariable(from, name);
2649+
: findMinifierVariable(from, name, i);
26082650
if (variable === undefined) {
26092651
variable = globals.get(name);
26102652
if (variable === undefined) {
@@ -2738,7 +2780,12 @@ class CompressorScopeAnalyzer extends MinifierScopeAnalyzer {
27382780
constructor(root, options, raise, dialect, parentScope, toplevel) {
27392781
super(
27402782
/** @type {PrintProgram} */ (/** @type {unknown} */ (root)),
2741-
{ ie8: options.ie8, safari10: options.safari10, module: options.module },
2783+
{
2784+
ie8: options.ie8,
2785+
safari10: options.safari10,
2786+
module: options.module,
2787+
parameterScopes: options.parameterScopes
2788+
},
27422789
raise,
27432790
undefined
27442791
);
@@ -3098,7 +3145,7 @@ class CompressorScopeAnalyzer extends MinifierScopeAnalyzer {
30983145
/** @type {unknown} */ (
30993146
flags & REFERENCE_FROM_MODULE
31003147
? undefined
3101-
: findMinifierVariable(from, name)
3148+
: findMinifierVariable(from, name, i)
31023149
)
31033150
);
31043151
if (definition === undefined) {

‎lib/javascript/syntax-printer.js‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4175,9 +4175,13 @@ const installScope = (modules) => {
41754175
if (!isToplevelNode(toplevel)) {
41764176
throw new Error("Invalid toplevel scope");
41774177
}
4178+
const { corrections } = modules;
41784179
analyzeCompressorScope(
41794180
self,
4180-
options,
4181+
// The correct phase scopes a parameter list apart from its body.
4182+
corrections !== undefined && corrections.enabled
4183+
? { ...options, parameterScopes: true }
4184+
: options,
41814185
raise,
41824186
dialect,
41834187
parentScope || null,
@@ -30096,13 +30100,18 @@ const installEstreeMangle = (modules) => {
3009630100
* @param {boolean=} releases whether nobody keeps the tree, so each node read drops what only the compressor read
3009730101
* @returns {MinifierScopeAnalysis} the scopes
3009830102
*/
30099-
const analyzeManglingScopes = (program, options, releases) =>
30100-
analyzeMinifierScope(
30103+
const analyzeManglingScopes = (program, options, releases) => {
30104+
const { corrections } = modules;
30105+
return analyzeMinifierScope(
3010130106
program,
30102-
options,
30107+
// The correct phase scopes a parameter list apart from its body.
30108+
corrections !== undefined && corrections.enabled
30109+
? { ...options, parameterScopes: true }
30110+
: options,
3010330111
raise,
3010430112
releases === true ? releaseCompressorFields : undefined
3010530113
);
30114+
};
3010630115
modules.analyzeManglingScopes = analyzeManglingScopes;
3010730116
modules.isUnmangleable = isUnmangleable;
3010830117

‎test/specCases/test262.spectest.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1409,7 +1409,7 @@ const MINIFIED_FAILURES = [
14091409
{
14101410
reason:
14111411
"terser writes a program that reads a binding outside its scope",
1412-
minifiers: ["terser", "printer"],
1412+
minifiers: ["terser"],
14131413
tests: [
14141414
"expressions/arrow-function/scope-paramsbody-var-open.js (sloppy)",
14151415
"expressions/arrow-function/scope-paramsbody-var-open.js (strict)",

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

Lines changed: 90 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,62 @@ const CORRECTED_CASES = [
629629
input,
630630
{ compress: false, mangle: false }
631631
])
632-
)
632+
),
633+
[
634+
"a parameter default's closure reading a name its body declares with `var`",
635+
"var x = 'out'; var a, b; function f(_ = a = () => x) { var x = 'in'; b = () => x; } f(); console.log(a(), b());",
636+
{ compress: false, mangle: true }
637+
],
638+
[
639+
"a parameter default reading a name its body redeclares",
640+
"var x = 1; function f(a = x, b = a) { var x = 2, a; return x + a + b; } console.log(f());",
641+
{ compress: false, mangle: true }
642+
],
643+
[
644+
"a parameter default's closure reading a name its body declares, compressed",
645+
"function g() { var x = 'out'; var a, b; function f(_ = a = () => x) { var x = 'in'; b = () => x; } f(); console.log(a(), b()); } g();",
646+
{ compress: {}, mangle: false }
647+
],
648+
[
649+
"a parameter default's closure reading a name its body declares as a function",
650+
"var h = 'out'; var a; function f(_ = a = () => h) { function h() {} } f(); console.log(a());",
651+
{ compress: false, mangle: true }
652+
],
653+
[
654+
"a parameter default's closure reading a name its body declares with `let`",
655+
"var x = 'out'; var a; function f(_ = a = () => x) { let x = 'in'; } f(); console.log(a());",
656+
{ compress: false, mangle: true }
657+
],
658+
[
659+
"a destructured parameter default's closure reading a name its body declares",
660+
"var x = 'out'; var a; function f({ y = a = () => x } = {}) { var x = 'in'; } f(); console.log(a());",
661+
{ compress: false, mangle: true }
662+
],
663+
[
664+
"an arrow's parameter default reading a name its body declares",
665+
"var x = 'out'; var a, b; var f = (_ = a = () => x) => { var x = 'in'; b = () => x; }; f(); console.log(a(), b());",
666+
{ compress: false, mangle: true }
667+
],
668+
[
669+
"a method's parameter default reading a name its body declares",
670+
"var x = 'out'; var a; class C { static m(_ = a = () => x) { var x = 'in'; } } C.m(); console.log(a());",
671+
{ compress: false, mangle: true }
672+
],
673+
[
674+
"a nested function's parameter default reading a name its body declares",
675+
"var x = 'out'; var a; function f(_ = function () { return function (__ = a = () => x) { var x = 'deep'; }; }) { var x = 'in'; _()(); } f(); console.log(a());",
676+
{ compress: false, mangle: true }
677+
],
678+
[
679+
"a catch parameter default's closure reading a name its block declares",
680+
"var a, b; let x = 'out'; try { throw []; } catch ([_ = a = () => x]) { b = () => x; let x = 'in'; } console.log(a(), b());",
681+
{ compress: false, mangle: true }
682+
],
683+
[
684+
"a catch parameter default's closure reading a name its block declares, compressed",
685+
"function g() { var a, b; let x = 'out'; try { throw []; } catch ([_ = a = () => x]) { b = () => x; let x = 'in'; } console.log(a(), b()); } g();",
686+
{ compress: {}, mangle: false }
687+
]
633688
];
634689

635690
// terser's parser refuses `let` as a name, so with corrections off the print
@@ -1637,7 +1692,8 @@ describe("syntax-printer", () => {
16371692

16381693
for (const [name, source, options] of SCOPE_CASES) {
16391694
it(`should analyse scopes as terser does: ${name}`, async () => {
1640-
const { minify } = await load();
1695+
const { minify, corrections } = await load();
1696+
if (!corrections) throw new Error("the correct phase is not installed");
16411697
const reference = terserReference();
16421698
/**
16431699
* @param {EXPECTED_ANY} run a minify, webpack's or terser's
@@ -1655,9 +1711,17 @@ describe("syntax-printer", () => {
16551711
/** @returns {EXPECTED_OBJECT} the options */
16561712
const settings = () => ({ compress, mangle: true, ...JSON.parse(JSON.stringify(options)) });
16571713
const theirs = await outcome(reference.minify, settings());
1714+
// The correct phase scopes a parameter list apart from its body.
1715+
corrections.enabled = false;
1716+
let ours;
1717+
try {
1718+
ours = await outcome(minify, settings());
1719+
} finally {
1720+
corrections.enabled = true;
1721+
}
16581722
// webpack's parser refuses what the spec makes an early error, in its
16591723
// own words, before any scope is read.
1660-
expect(await outcome(minify, settings())).toEqual(
1724+
expect(ours).toEqual(
16611725
theirs.error === undefined ? theirs : { error: expect.any(String) }
16621726
);
16631727
}
@@ -3930,6 +3994,29 @@ describe("syntax-printer", () => {
39303994
}
39313995
});
39323996

3997+
describe("a parameter list's scope", () => {
3998+
it("should still read in a parameter list what the list and its function name declare", async () => {
3999+
const { minify } = await load();
4000+
for (const input of [
4001+
"var a; function f(p = 'p', q = a = () => p) { var r = 1; } f(); console.log(a());",
4002+
"var a; var f = function self(_ = a = () => typeof self) { var z; }; f(); console.log(a());",
4003+
"var a; function f(_ = a = () => arguments.length) { var y; } f(1, 2); console.log(a());",
4004+
"var a; try { throw ['e']; } catch ([e, _ = a = () => e]) { let z; } console.log(a());",
4005+
"var x = 'out'; function f(y = x) { var x = 'in'; return y; } console.log(f());"
4006+
]) {
4007+
for (const options of [
4008+
{ compress: false, mangle: true },
4009+
{ compress: { passes: 2 }, mangle: true }
4010+
]) {
4011+
const { code } = await minify(`function g() { ${input} } g();`, options);
4012+
expect(runProgram(/** @type {string} */ (code))).toBe(
4013+
runProgram(input)
4014+
);
4015+
}
4016+
}
4017+
});
4018+
});
4019+
39334020
describe("a `let` heading a statement or loop", () => {
39344021
it("should not parenthesize a `let` or `async` nothing misreads", async () => {
39354022
const { minify } = await load();

0 commit comments

Comments
 (0)