Skip to content

Commit 223d709

Browse files
authored
fix(javascript): keep a dropped class whose effects read its own private name (#22421)
* fix(javascript): keep a dropped class whose effects read its own private name Dropping an unused class kept its computed keys and static values but moved them outside it, where a #private name it declares is no longer declared, so class C { [o.#f] = 1; #f = 2 } became o.#f and stopped parsing, as terser's output does. The correct phase now keeps such a class, and only for a name it declares. 4 more test262 cases print in the printer's mode. * fix(javascript): read a nested class's private names as its own when keeping a dropped class A class nested in a dropped class's key that declares the same #name reads its own, so the outer class was kept where terser drops it. The check now reads such a class's body without the names it declares, and its extends with all of them. Tests cover class expressions, private methods, getters, setters, static methods and nested classes, one per branch the check takes.
1 parent e6183e8 commit 223d709

4 files changed

Lines changed: 175 additions & 5 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 class dropped for its effects where they read a private name it declares.

‎lib/javascript/syntax-printer.js‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14703,6 +14703,76 @@ const installCorrect = (modules) => {
1470314703
containsThis(self) ||
1470414704
(corrections.enabled && A.isScopeNode(self) && self.uses_eval);
1470514705

14706+
// A class dropped for its effects leaves its computed keys and static values
14707+
// outside it, where a private name it declares is no longer declared: terser's
14708+
// output no longer parses, so a class whose effects read one of its own stays.
14709+
/**
14710+
* @param {Node} classNode a class
14711+
* @returns {Set<string>} the private names it declares
14712+
*/
14713+
const privateNamesDeclaredBy = (classNode) => {
14714+
/** @type {Set<string>} */
14715+
const names = new Set();
14716+
for (const member of classNode.body.body) {
14717+
if (
14718+
A.isClassPrivatePropertyNode(member) ||
14719+
A.isPrivateMethodNode(member) ||
14720+
A.isPrivateGetterNode(member) ||
14721+
A.isPrivateSetterNode(member)
14722+
) {
14723+
names.add(member.key.name);
14724+
}
14725+
}
14726+
return names;
14727+
};
14728+
/**
14729+
* Whether a tree reads one of the private names, past a class nested in it
14730+
* that declares the same name for itself.
14731+
* @param {Node} tree the tree
14732+
* @param {Set<string>} names the names
14733+
* @returns {boolean} true where it reads one
14734+
*/
14735+
const readsPrivateName = (tree, names) =>
14736+
A.walk(tree, (/** @type {Node} */ node) => {
14737+
if (node !== tree && A.isClassNode(node)) {
14738+
const own = privateNamesDeclaredBy(node);
14739+
if (![...own].some((name) => names.has(name))) return undefined;
14740+
// Its `extends` is read where the class sits, its body past its names.
14741+
if (node.superClass && readsPrivateName(node.superClass, names)) {
14742+
return A.walk_abort;
14743+
}
14744+
const outer = new Set([...names].filter((name) => !own.has(name)));
14745+
return outer.size > 0 && readsPrivateName(node.body, outer)
14746+
? A.walk_abort
14747+
: true;
14748+
}
14749+
return (A.isDotHashNode(node) && names.has(node.property.name)) ||
14750+
(A.isPrivateInNode(node) && names.has(node.left.name))
14751+
? A.walk_abort
14752+
: undefined;
14753+
});
14754+
for (const type of ["ClassDeclaration", "ClassExpression"]) {
14755+
A.wrapDropSideEffectFree(
14756+
type,
14757+
(
14758+
/** @type {(self: Node, compressor: CompressorShape) => Node | null} */ original
14759+
) =>
14760+
(
14761+
/** @type {Node} */ self,
14762+
/** @type {CompressorShape} */ compressor
14763+
) => {
14764+
const left = original(self, compressor);
14765+
if (left === null || left === self || !corrections.enabled) {
14766+
return left;
14767+
}
14768+
const declared = privateNamesDeclaredBy(self);
14769+
return declared.size > 0 && readsPrivateName(left, declared)
14770+
? self
14771+
: left;
14772+
}
14773+
);
14774+
}
14775+
1470614776
/**
1470714777
* Whether a parameter has a default whose evaluation has effects.
1470814778
* @param {Node} parameter the parameter
@@ -19298,6 +19368,16 @@ const installDropSideEffectFree = ({
1929819368
compressor,
1929919369
firstInStatement
1930019370
);
19371+
19372+
/**
19373+
* Replaces what a node of the type is left as with one wrapping it.
19374+
* @param {string} type the nodes, by ESTree type
19375+
* @param {(original: (self: Node, compressor: CompressorShape, firstInStatement?: boolean) => Node | null) => (self: Node, compressor: CompressorShape, firstInStatement?: boolean) => Node | null} wrap builds the replacement
19376+
* @returns {void}
19377+
*/
19378+
ast.wrapDropSideEffectFree = (type, wrap) => {
19379+
DROP_SIDE_EFFECT_FREE[type] = wrap(DROP_SIDE_EFFECT_FREE[type]);
19380+
};
1930119381
};
1930219382

1930319383
/**

‎test/specCases/test262.spectest.js‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1517,14 +1517,10 @@ const MINIFIED_FAILURES = [
15171517
"global-code/return.js (strict)",
15181518
"statements/class/elements/fields-hash-constructor-is-a-valid-name.js (sloppy)",
15191519
"statements/class/elements/fields-hash-constructor-is-a-valid-name.js (strict)",
1520-
"statements/class/elements/private-field-is-visible-in-computed-properties.js (sloppy)",
1521-
"statements/class/elements/private-field-is-visible-in-computed-properties.js (strict)",
15221520
"statements/class/elements/private-field-visible-to-direct-eval-on-initializer.js (sloppy)",
15231521
"statements/class/elements/private-field-visible-to-direct-eval-on-initializer.js (strict)",
15241522
"statements/class/elements/private-field-visible-to-direct-eval.js (sloppy)",
15251523
"statements/class/elements/private-field-visible-to-direct-eval.js (strict)",
1526-
"statements/class/elements/private-field-with-initialized-id-is-visible-in-computed-properties.js (sloppy)",
1527-
"statements/class/elements/private-field-with-initialized-id-is-visible-in-computed-properties.js (strict)",
15281524
"statements/class/elements/private-getter-visible-to-direct-eval-on-initializer.js (sloppy)",
15291525
"statements/class/elements/private-getter-visible-to-direct-eval-on-initializer.js (strict)",
15301526
"statements/class/elements/private-getter-visible-to-direct-eval.js (sloppy)",
@@ -1617,6 +1613,10 @@ const MINIFIED_FAILURES = [
16171613
"expressions/dynamic-import/import-attributes/2nd-param-await-ident.js (strict)",
16181614
"expressions/function/static-init-await-reference.js (sloppy)",
16191615
"expressions/function/static-init-await-reference.js (strict)",
1616+
"statements/class/elements/private-field-is-visible-in-computed-properties.js (sloppy)",
1617+
"statements/class/elements/private-field-is-visible-in-computed-properties.js (strict)",
1618+
"statements/class/elements/private-field-with-initialized-id-is-visible-in-computed-properties.js (sloppy)",
1619+
"statements/class/elements/private-field-with-initialized-id-is-visible-in-computed-properties.js (strict)",
16201620
"statements/for-await-of/let-block-with-newline.js (sloppy)",
16211621
"statements/for-in/let-block-with-newline.js (sloppy)",
16221622
"statements/for-of/let-block-with-newline.js (sloppy)"

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

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,64 @@ const CORRECTED_CASES = [
519519
"a function naming `yield`, inlined into an async generator",
520520
"var yield; async function* g() { function h() { yield = 1; } h(); } g().next(); console.log(yield);",
521521
{ compress: { passes: 2 }, mangle: false }
522-
]
522+
],
523+
...[
524+
[
525+
"a class dropped for its effects, a computed key reading its private name",
526+
"var o = {}; try { (function () { class C { [o.#f] = 1; #f = 2; } })(); } catch (e) { console.log(e.name); }"
527+
],
528+
[
529+
"a class dropped for its effects, a computed key testing its private name with `in`",
530+
'var o = {}; (function () { class C { [#f in o ? "a" : "b"] = 1; #f = 2; } })(); console.log("ok");'
531+
],
532+
[
533+
"a class dropped for its effects, a computed key reading its private name through `?.`",
534+
"var o = {}; try { (function () { class C { [o?.#f] = 1; #f = 2; } })(); } catch (e) { console.log(e.name); }"
535+
],
536+
[
537+
"a class dropped for its effects, a static value reading its private name",
538+
"var o = {}; try { (function () { class C { static x = o.#f; #f = 2; } })(); } catch (e) { console.log(e.name); }"
539+
],
540+
[
541+
"a class dropped for its effects, a computed method key reading its private name",
542+
"var o = {}; try { (function () { class C { [o.#f]() {} #f = 2; } })(); } catch (e) { console.log(e.name); }"
543+
],
544+
[
545+
"a class expression dropped for its effects, a computed key reading its private name",
546+
"var o = {}; try { (function () { (class { [o.#f] = 1; #f = 2; }); })(); } catch (e) { console.log(e.name); }"
547+
],
548+
[
549+
"a class dropped for its effects, a computed key reading its private method",
550+
"var o = {}; try { (function () { class C { [o.#m] = 1; #m() {} } })(); } catch (e) { console.log(e.name); }"
551+
],
552+
[
553+
"a class dropped for its effects, a computed key reading its private getter",
554+
"var o = {}; try { (function () { class C { [o.#g] = 1; get #g() { return 1; } } })(); } catch (e) { console.log(e.name); }"
555+
],
556+
[
557+
"a class dropped for its effects, a computed key reading its private setter",
558+
"var o = {}; try { (function () { class C { [o.#s] = 1; set #s(v) {} } })(); } catch (e) { console.log(e.name); }"
559+
],
560+
[
561+
"a class dropped for its effects, a computed key reading its static private method",
562+
"var o = {}; try { (function () { class C { [o.#m] = 1; static #m() {} } })(); } catch (e) { console.log(e.name); }"
563+
],
564+
[
565+
"a class dropped for its effects, a class in its computed key reading its private name",
566+
'var o = {}; (function () { class C { [(class { static r(x) { return #f in x; } }).r(o)] = 1; #f = 2; } })(); console.log("ok");'
567+
],
568+
[
569+
"a class dropped for its effects, the extends of a class in its key reading its private name",
570+
"var o = {}; try { (function () { class C { [((class extends (o.#f, Object) { #f = 1; }), 1)] = 1; #f = 2; } })(); } catch (e) { console.log(e.name); }"
571+
]
572+
].map(
573+
([name, input]) =>
574+
/** @type {[string, string, import("terser").MinifyOptions]} */ ([
575+
name,
576+
input,
577+
{ compress: {}, mangle: false }
578+
])
579+
)
523580
];
524581

525582
// Each writes a name where terser writes it as a keyword, through the `improve`
@@ -3608,6 +3665,34 @@ describe("syntax-printer", () => {
36083665
expect(phases).toContain("correct");
36093666
});
36103667

3668+
it("should drop a class whose effects read only a nested class's own private name, as terser does", async () => {
3669+
const { minify } = await load();
3670+
const input =
3671+
'var o = {}; (function () { class C { [(class { #f = 1; static r(x) { return #f in x; } }).r(o)] = 1; #f = 2; #g = 3; } })(); console.log("ok");';
3672+
const { code } = await minify(input, { compress: {}, mangle: false });
3673+
const reference = await terserReference().minify(input, {
3674+
compress: {},
3675+
mangle: false
3676+
});
3677+
3678+
expect(code).toBe(reference.code);
3679+
expect(runProgram(/** @type {string} */ (code))).toBe(runProgram(input));
3680+
});
3681+
3682+
it("should drop a class whose effects read only an enclosing class's private name, as terser does", async () => {
3683+
const { minify } = await load();
3684+
const input =
3685+
'class D { #p = 1; m() { var t = this; (function () { class C { [t.#p] = 1; #q = 2; } })(); return "ok"; } } console.log(new D().m());';
3686+
const { code } = await minify(input, { compress: {}, mangle: false });
3687+
const reference = await terserReference().minify(input, {
3688+
compress: {},
3689+
mangle: false
3690+
});
3691+
3692+
expect(code).toBe(reference.code);
3693+
expect(code).not.toContain("class C");
3694+
});
3695+
36113696
for (const [name, input, options] of CORRECTED_CASES) {
36123697
it(`should print what the input prints: ${name}`, async () => {
36133698
const { minify, corrections } = await load();

0 commit comments

Comments
 (0)