Skip to content

Commit 11a1ebd

Browse files
authored
feat(minify): close more oxc and swc gaps: quoted keys, unread returns, NaN keys (#22914)
* feat(minify): drop `new` before `RegExp` of a BigInt `new RegExp(10n)` builds what `RegExp(10n)` does: a BigInt pattern, negated or not, is no regular expression to hand back, so the call is written as for a number. Retires `normalize.rs:221`. * feat(minify): write computed `NaN` and `null` keys as names `{[NaN]: 1, [null]: 2}` as `{NaN: 1, null: 2}`, in objects, patterns and classes, where `computed_props` is on; no property mangler renames either name. oxc keeps `[null]`. Retires `convert_computed_props_to_regular_ones`. * feat(minify): read `a["b"]` as `a.b` when merging branches Branches spelling a key with and without quotes merge where the run keeps no quote: not under `mangle.properties.keep_quoted: "strict"` or `format.keep_quoted_props`, since plain `keep_quoted` reserves each quoted name everywhere. Retires `minimize_statements.rs:188` and `issue_1674_false_equivalency_of_props`. * feat(minify): drop the values an unread function called in place returns Where nothing reads the call, a pure `return` value goes before the body is tightened, so the call unwraps: not of an `async`, named or `arguments`-reading function, nor a value that may read a `let` in its dead zone. Behind `side_effects`. Retires swc `12301`. * test(minify): build the oxc and swc gaps through webpack A config case runs each rewrite through a real production build, with and without mangling, keeping quoted keys and with `side_effects` off, checking what each bundle prints and runs. The minimizer runs in the process so the coverage counts.
1 parent 9acffe7 commit 11a1ebd

10 files changed

Lines changed: 476 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": minor
3+
---
4+
5+
Merge branches spelling a key with and without quotes, drop the values an unread function called in place returns, write computed `NaN` and `null` keys as names, and drop `new` before `RegExp` of a BigInt when minifying.

‎lib/javascript/syntax-printer.js‎

Lines changed: 138 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ const {
7878
* @property {(files: MinifySources, options?: MinifyOptions) => MinifyOutput} minifySync terser's `minify_sync`
7979
* @property {Corrections} corrections the switch the corrections read, once the correct phase installs it
8080
* @property {Improvements} improvements the switch the improvements read, once the improve phase installs it
81+
* @property {boolean} quotesKept whether the run keeps a quoted key apart from the same key bare: a property mangler keeping quoted names strictly, or the output keeping quotes
8182
* @property {(compressor: Walker) => string[] | undefined} reservedAround the names reserved around what a walker visits
8283
* @property {(lambda: Node, reserved: string[]) => boolean} namesInOwnContext whether a function's names stay apart from the reserved ones
8384
* @property {(stream: OutputStream<PrintNode | number>, text: string, print: () => void) => void} printWithLineBreaksOf prints with the line breaks a text holds
@@ -9881,6 +9882,14 @@ const installMinify = (modules) => {
98819882

98829883
// Compress.
98839884
if (timings) timings.compress = Date.now();
9885+
// Without `"strict"`, a quoted key is reserved everywhere above.
9886+
modules.quotesKept =
9887+
Boolean(options.format.keep_quoted_props) ||
9888+
Boolean(
9889+
options.mangle &&
9890+
options.mangle.properties &&
9891+
options.mangle.properties.keep_quoted === "strict"
9892+
);
98849893
if (options.compress) {
98859894
const compressor = createCompressor(
98869895
/** @type {Partial<CompressOptions>} */ (options.compress),
@@ -26217,6 +26226,83 @@ const installImprove = (modules) => {
2621726226
: undefined;
2621826227
};
2621926228

26229+
/**
26230+
* Stops a walk at a name that may be read in its dead zone: one no `var`,
26231+
* function or parameter declares.
26232+
* @param {Node} node a node walked
26233+
* @returns {WalkResult} `walk_abort` there
26234+
*/
26235+
const readsInDeadZone = (node) => {
26236+
if (!A.isSymbolRefNode(node)) return undefined;
26237+
const declared = node.definition && node.definition.identifiers[0];
26238+
return declared &&
26239+
(A.isSymbolVarNode(declared) ||
26240+
A.isSymbolDefunNode(declared) ||
26241+
A.isSymbolFunargNode(declared))
26242+
? undefined
26243+
: A.walk_abort;
26244+
};
26245+
26246+
/**
26247+
* Drops the value each `return` of a function called in place hands back,
26248+
* where nothing reads the call's value and the value runs or throws nothing:
26249+
* not of an `async` one, whose value may be a thenable it calls, nor of one
26250+
* its name or `arguments.callee` calls again.
26251+
* @param {Node} fn a function
26252+
* @param {Compressor} compressor the compressor, standing at the function
26253+
* @returns {void}
26254+
*/
26255+
const dropUnreadReturns = (fn, compressor) => {
26256+
const call = compressor.parent();
26257+
if (
26258+
!compressor.option("side_effects") ||
26259+
!(A.isFunctionNode(fn) || A.isArrowNode(fn)) ||
26260+
fn.async ||
26261+
fn.id ||
26262+
A.usesArguments(fn) ||
26263+
!A.isCallNode(call) ||
26264+
A.isNewNode(call) ||
26265+
call.callee !== fn
26266+
) {
26267+
return;
26268+
}
26269+
let child = call;
26270+
for (let level = 1; ; level++) {
26271+
const parent = compressor.parent(level);
26272+
if (A.isSimpleStatementNode(parent)) break;
26273+
if (A.isSequenceNode(parent) && A.tailNode(parent) !== child) break;
26274+
if (
26275+
!A.isSequenceNode(parent) &&
26276+
!(
26277+
A.isUnaryPrefixNode(parent) &&
26278+
(parent.operator === "!" || parent.operator === "void")
26279+
)
26280+
) {
26281+
return;
26282+
}
26283+
child = parent;
26284+
}
26285+
A.walk(/** @type {Node} */ (fn.body), (/** @type {Node} */ node) => {
26286+
if (A.isLambdaNode(node)) return true;
26287+
if (
26288+
A.isReturnNode(node) &&
26289+
node.argument &&
26290+
!A.hasSideEffects(node.argument, compressor) &&
26291+
!A.walk(node.argument, readsInDeadZone)
26292+
) {
26293+
node.argument = /** @type {Node} */ (/** @type {Node | null} */ (null));
26294+
}
26295+
});
26296+
};
26297+
26298+
// Before its body is tightened, which then folds the emptied `return`s.
26299+
for (const kind of ["Function", "Arrow"]) {
26300+
A.wrapOptimizer(kind, (optimizeLambda) => (self, compressor) => {
26301+
if (improvements.enabled) dropUnreadReturns(self, compressor);
26302+
return optimizeLambda(self, compressor);
26303+
});
26304+
}
26305+
2622026306
A.wrapOptimizer("Call", (optimizeCall) => (self, compressor) => {
2622126307
const optimized = optimizeCall(self, compressor);
2622226308
if (
@@ -29773,8 +29859,8 @@ const installImprove = (modules) => {
2977329859
/**
2977429860
* Whether a `new` of a built-in the program never assigns constructs as its
2977529861
* call does: always but for `RegExp`, which hands back a regular expression
29776-
* passed without flags, so it needs a constant or string pattern, or flags
29777-
* that are a string.
29862+
* passed without flags, so it needs a constant, BigInt or string pattern, or
29863+
* flags that are a string.
2977829864
* @param {Node} node a `new` expression
2977929865
* @param {Compressor} compressor the compressor
2978029866
* @returns {boolean} true when the call constructs the same
@@ -29794,6 +29880,8 @@ const installImprove = (modules) => {
2979429880
return (
2979529881
!args.some((/** @type {Node} */ arg) => A.isExpansionNode(arg)) &&
2979629882
(constantOf(pattern) !== NOT_CONSTANT ||
29883+
A.isBigIntNode(pattern) ||
29884+
(A.isUnaryPrefixNode(pattern) && A.isBigIntNode(pattern.argument)) ||
2979729885
A.isString(pattern, compressor) ||
2979829886
(flags !== undefined && A.isString(flags, compressor)))
2979929887
);
@@ -35767,15 +35855,58 @@ const installImprove = (modules) => {
3576735855
return node;
3576835856
};
3576935857

35858+
/**
35859+
* A computed `NaN` or `null` key written as the name it converts to, which
35860+
* terser keeps in brackets; no property mangler renames either name.
35861+
* @param {Node} node an object or class member terser has optimized
35862+
* @param {Compressor} compressor the compressor
35863+
* @returns {Node} the member
35864+
*/
35865+
const liftLiteralKey = (node, compressor) => {
35866+
if (
35867+
!(A.isNaNNode(node.key) || A.isNullNode(node.key)) ||
35868+
!compressor.option("computed_props")
35869+
) {
35870+
return node;
35871+
}
35872+
const name = A.isNullNode(node.key) ? "null" : "NaN";
35873+
node.computed = false;
35874+
node.key = A.isObjectKeyValNode(node)
35875+
? makeNode(A.SymbolPropertyNode, node.key, { name })
35876+
: A.isClassPropertyNode(node)
35877+
? makeNode(A.SymbolClassPropertyNode, node.key, { name })
35878+
: makeNode(A.SymbolMethodNode, node.key, { name });
35879+
return node;
35880+
};
35881+
3577035882
for (const kind of ["ObjectProperty", "ConciseMethod"]) {
3577135883
A.wrapOptimizer(kind, (optimizeMember) => (self, compressor) => {
3577235884
const optimized = optimizeMember(self, compressor);
3577335885
return improvements.enabled
35774-
? liftSpecialKey(optimized, compressor)
35886+
? liftLiteralKey(liftSpecialKey(optimized, compressor), compressor)
3577535887
: optimized;
3577635888
});
3577735889
}
3577835890

35891+
// `a["b"]` reads what `a.b` does, and `"b": x` writes what `b: x` does, so
35892+
// two branches spelling them apart are one where the run keeps no quote.
35893+
A.wrapShallowEquivalent(
35894+
"Dot",
35895+
(/** @type {(self: Node, other: Node) => boolean} */ original) =>
35896+
(/** @type {Node} */ self, /** @type {Node} */ other) =>
35897+
improvements.enabled && !modules.quotesKept
35898+
? self.property.name === other.property.name
35899+
: original(self, other)
35900+
);
35901+
A.wrapShallowEquivalent(
35902+
"ObjectKeyVal",
35903+
(/** @type {(self: Node, other: Node) => boolean} */ original) =>
35904+
(/** @type {Node} */ self, /** @type {Node} */ other) =>
35905+
improvements.enabled && !modules.quotesKept
35906+
? self.key.name === other.key.name
35907+
: original(self, other)
35908+
);
35909+
3577935910
// In a pattern `__proto__: x` reads the property, as `["__proto__"]: x` does.
3578035911
A.wrapOptimizer("ObjectKeyVal", (optimizeKeyVal) => (self, compressor) => {
3578135912
const optimized = optimizeKeyVal(self, compressor);
@@ -35791,7 +35922,9 @@ const installImprove = (modules) => {
3579135922
optimized.quote = optimized.key.quote;
3579235923
optimized.key = A.SymbolPropertyNode({ name: "__proto__" });
3579335924
}
35794-
return optimized;
35925+
return improvements.enabled
35926+
? liftLiteralKey(optimized, compressor)
35927+
: optimized;
3579535928
});
3579635929

3579735930
const { isBasicIdentifier: isPlainKey } = createUnicode();
@@ -62343,6 +62476,7 @@ const createModules = () => {
6234362476
modules.domprops = {
6234462477
domprops: require("./syntax-printer-data").domProperties()
6234562478
};
62479+
modules.quotesKept = true;
6234662480
return /** @type {MinifierModules} */ (
6234762481
/** @type {MinifierModules | TerserModules} */ (modules)
6234862482
);
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
const log = [];
2+
3+
function record(value) {
4+
log.push(value);
5+
return value;
6+
}
7+
8+
function bigIntPatterns() {
9+
return [String(new RegExp(10n)), String(new RegExp(-10n))];
10+
}
11+
12+
class Keys {
13+
[NaN]() {
14+
return 1;
15+
}
16+
17+
get [null]() {
18+
return 2;
19+
}
20+
21+
static [NaN]() {
22+
return 3;
23+
}
24+
}
25+
26+
class Fields {
27+
[null] = 4;
28+
}
29+
30+
function keyed(o) {
31+
const { [NaN]: a, [null]: b } = o;
32+
return [a, b, Object.keys({ [NaN]: 5, [null]: 6 }).join()];
33+
}
34+
35+
function quoted(x, o) {
36+
return x ? o["read"]() : o.read();
37+
}
38+
39+
function quotedKeys(a, b, value) {
40+
if (a) return { kept: value };
41+
if (b) return { "kept": value };
42+
}
43+
44+
function unreadReturns(y) {
45+
(function () {
46+
try {
47+
throw 1;
48+
} finally {
49+
return 2;
50+
}
51+
})();
52+
(function (x) {
53+
if (x) return 3;
54+
record(x);
55+
})(y);
56+
(() => {
57+
if (record(1)) return 4;
58+
record(2);
59+
})();
60+
record(5),
61+
(function (x) {
62+
if (x) return x;
63+
record(x);
64+
})(y);
65+
void (function (x) {
66+
if (x) return record;
67+
record(6);
68+
})(y);
69+
}
70+
71+
function readReturns(y) {
72+
const assigned = (function (x) {
73+
if (x) return 7;
74+
record(x);
75+
})(y);
76+
const named = (function count(n) {
77+
if (!n) return 2;
78+
return count(n - 1) * 3;
79+
})(1);
80+
const passed = [1].map(function (x) {
81+
if (x) return 8;
82+
record(x);
83+
});
84+
(function (x) {
85+
if (x) return arguments.length;
86+
record(x);
87+
})(y);
88+
const constructed = new (function (x) {
89+
if (x) return { built: 9 };
90+
this.built = 0;
91+
})(y);
92+
let written;
93+
(function (x) {
94+
if (x) return (written = 10);
95+
record(x);
96+
})(y);
97+
return [assigned, named, passed[0], constructed.built, written];
98+
}
99+
100+
function deadZone(y) {
101+
try {
102+
(function (x) {
103+
if (x) return later;
104+
record(x);
105+
})(y);
106+
} catch (err) {
107+
return err.name;
108+
}
109+
let later = 1;
110+
return later;
111+
}
112+
113+
async function asyncReturn(y) {
114+
return (async function (x) {
115+
if (x) return { then: (resolve) => resolve(11) };
116+
await record(x);
117+
})(y);
118+
}
119+
120+
it("should drop `new` before `RegExp` of a BigInt", () => {
121+
expect(bigIntPatterns()).toEqual(["/10/", "/-10/"]);
122+
});
123+
124+
it("should read computed `NaN` and `null` keys as the names they convert to", () => {
125+
expect(new Keys().NaN()).toBe(1);
126+
expect(new Keys().null).toBe(2);
127+
expect(Keys.NaN()).toBe(3);
128+
expect(new Fields().null).toBe(4);
129+
expect(keyed({ NaN: "a", null: "b" })).toEqual(["a", "b", "NaN,null"]);
130+
});
131+
132+
it("should read `a[\"b\"]` as `a.b`", () => {
133+
const o = { read: () => "r" };
134+
expect([quoted(0, o), quoted(1, o)]).toEqual(["r", "r"]);
135+
expect([quotedKeys(1, 0, 1), quotedKeys(0, 1, 2), quotedKeys(0, 0, 3)]).toEqual([
136+
{ kept: 1 },
137+
{ kept: 2 },
138+
undefined
139+
]);
140+
});
141+
142+
it("should run what an unread function called in place runs", () => {
143+
log.length = 0;
144+
unreadReturns(0);
145+
expect(log).toEqual([0, 1, 5, 0, 6]);
146+
log.length = 0;
147+
unreadReturns(1);
148+
expect(log).toEqual([1, 5]);
149+
});
150+
151+
it("should keep what a function called in place returns where it is read", async () => {
152+
expect(readReturns(1)).toEqual([7, 6, 8, 9, 10]);
153+
expect(deadZone(1)).toBe("ReferenceError");
154+
expect(deadZone(0)).toBe(1);
155+
expect(await asyncReturn(1)).toBe(11);
156+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"use strict";
2+
3+
const fs = require("fs");
4+
const path = require("path");
5+
6+
// The config keeping quoted keys apart, and the one leaving `side_effects` off.
7+
const KEEPS_QUOTES = 2;
8+
const KEEPS_EFFECTS = 3;
9+
10+
module.exports = {
11+
afterExecute(options) {
12+
for (const [index, config] of options.entries()) {
13+
const code = fs.readFileSync(
14+
path.join(config.output.path, `bundle${index}.js`),
15+
"utf8"
16+
);
17+
expect(code).toContain("RegExp(10n)");
18+
expect(code).not.toContain("new RegExp");
19+
expect(code).toContain("NaN(){");
20+
expect(code).toContain("get null(");
21+
const merged = !/\?\w\.read\(\):\w\.read\(\)/.test(code);
22+
expect(merged).toBe(index !== KEEPS_QUOTES);
23+
expect(code).toContain(
24+
index === KEEPS_EFFECTS ? "finally{return 2}" : "finally{return}"
25+
);
26+
}
27+
}
28+
};

0 commit comments

Comments
 (0)