Skip to content

Commit b640357

Browse files
feat(minify): drop unread call arguments and fold Object.keys, .length and Array(-0)
Trim arguments past a known function's or constructor's parameters, and write `0` for one an unused parameter takes, where terser leaves them; fold `Object.keys` without `reduce_vars` once the probe finds no write of `Object`, `Math` calls of another's result, and a known function's `length` under `unsafe`. Closes eleven of swc's gaps and two of oxc's. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD
1 parent 3e0056b commit b640357

7 files changed

Lines changed: 317 additions & 55 deletions

File tree

‎.changeset/060-minify-swc-gaps.md‎

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+
Drop unread call arguments and fold `Object.keys` and `.length` when minifying.

‎lib/javascript/syntax-printer.js‎

Lines changed: 214 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -23574,9 +23574,10 @@ const installImprove = (modules) => {
2357423574
*/
2357523575
const readsUnassignedGlobal = (node, compressor) =>
2357623576
isUndeclaredRef(node) &&
23577-
compressor.option("reduce_vars") &&
23578-
node.definition.assignments === 0 &&
23579-
node.definition.patternWrites === 0 &&
23577+
// Without `reduce_vars` counting writes, the probe's own find them.
23578+
(!compressor.option("reduce_vars") ||
23579+
(node.definition.assignments === 0 &&
23580+
node.definition.patternWrites === 0)) &&
2358023581
!isReboundGlobal(node.name) &&
2358123582
!globalMayBeRebound(compressor);
2358223583

@@ -23641,8 +23642,17 @@ const installImprove = (modules) => {
2364123642
const limit = modules.printToString(call).length;
2364223643
/** @type {EvaluatedArray} */
2364323644
const args = [];
23645+
// A `Math` function takes another's result, `Math.ceil(Math.sqrt(2))`.
23646+
const ofMath =
23647+
A.isDotNode(call.callee) &&
23648+
A.isSymbolRefNode(call.callee.object) &&
23649+
call.callee.object.name === "Math";
2364423650
for (const arg of call.arguments) {
23645-
const value = valueOf(arg);
23651+
let value = valueOf(arg);
23652+
if (value === NOT_CONSTANT && ofMath && A.isCallNode(arg)) {
23653+
const result = builtInCallValue(arg, compressor);
23654+
if (typeof result === "number") value = result;
23655+
}
2364623656
if (value === NOT_CONSTANT) return call;
2364723657
// A count or length past the call's own size, as in `"a".repeat(1e9)`,
2364823658
// answers nothing shorter, so the method is never run.
@@ -24175,14 +24185,25 @@ const installImprove = (modules) => {
2417524185
const argument = args[0];
2417624186
if (A.isObjectNode(argument)) {
2417724187
for (const property of argument.properties) {
24178-
if (!A.isObjectKeyValNode(property) || property.computed) {
24179-
return undefined;
24180-
}
24181-
const key = A.terserKey(property.key);
24188+
if (!A.isObjectKeyValNode(property)) return undefined;
24189+
const key = property.computed
24190+
? constantOf(property.key)
24191+
: A.terserKey(property.key);
2418224192
const { value } = property;
24193+
// `__proto__: v` sets the prototype, no own key; `{ __proto__ }`
24194+
// and `["__proto__"]: v` define one.
24195+
if (
24196+
!property.computed &&
24197+
key === "__proto__" &&
24198+
!(property.startToken && property.startToken === property.endToken)
24199+
) {
24200+
if (A.hasSideEffects(/** @type {Node} */ (value), compressor)) {
24201+
return undefined;
24202+
}
24203+
continue;
24204+
}
2418324205
if (
2418424206
(typeof key !== "string" && typeof key !== "number") ||
24185-
key === "__proto__" ||
2418624207
// Engines once disagreed on where an integer key past 2 ** 32 - 2 sorts.
2418724208
/^\d{10}/.test(String(key)) ||
2418824209
A.hasSideEffects(/** @type {Node} */ (value), compressor) ||
@@ -25479,24 +25500,32 @@ const installImprove = (modules) => {
2547925500
isPatternTarget(node, walker, A)
2548025501
);
2548125502
};
25503+
// The functions a name declared once holds, and the names written again,
25504+
// by declaring symbol, which stays as passes analyze scope anew.
25505+
/** @type {Map<Node, Node>} */
25506+
const localFunctions = new Map();
25507+
/** @type {Set<Node>} */
25508+
const writtenNames = new Set();
2548225509
/**
2548325510
* The function a call runs where the program defines it: a function written
25484-
* in place, or one a name declared once holds.
25511+
* in place, or one a name declared once, never written again, holds.
2548525512
* @param {Node} callee the call's callee
25486-
* @param {Map<Definition, Node>} localFunctions the functions names hold
25487-
* @param {Set<Definition>} writtenNames the names written again
2548825513
* @returns {Node | undefined} the function, or undefined where not known
2548925514
*/
25490-
const calledFunction = (callee, localFunctions, writtenNames) => {
25515+
const calledFunction = (callee) => {
2549125516
if (A.isLambdaNode(callee)) return callee;
25492-
if (!A.isSymbolRefNode(callee) || isUndeclaredRef(callee)) {
25517+
if (
25518+
!A.isSymbolRefNode(callee) ||
25519+
!callee.definition ||
25520+
isUndeclaredRef(callee) ||
25521+
callee.definition.identifiers.length !== 1
25522+
) {
2549325523
return undefined;
2549425524
}
25495-
const { definition } = callee;
25496-
const lambda = localFunctions.get(definition);
25497-
return definition.identifiers.length === 1 && !writtenNames.has(definition)
25498-
? lambda
25499-
: undefined;
25525+
const [declaration] = callee.definition.identifiers;
25526+
return writtenNames.has(declaration)
25527+
? undefined
25528+
: localFunctions.get(declaration);
2550025529
};
2550125530
/**
2550225531
* Records what a function the program defines but cannot be read may do
@@ -25531,13 +25560,10 @@ const installImprove = (modules) => {
2553125560
// Runs once scope is known, so a local named `self` is told from the global.
2553225561
collapseHooks.probeProgram = (toplevel) => {
2553325562
parameterAliases.clear();
25563+
localFunctions.clear();
25564+
writtenNames.clear();
2553425565
if (improvements.enabled) {
2553525566
let depth = 0;
25536-
// The functions a name holds, declared once and never written again.
25537-
/** @type {Map<Definition, Node>} */
25538-
const localFunctions = new Map();
25539-
/** @type {Set<Definition>} */
25540-
const writtenNames = new Set();
2554125567
/** @type {{ call: Node, argument: Node, name: string }[]} */
2554225568
const handOffs = [];
2554325569
/**
@@ -25593,17 +25619,26 @@ const installImprove = (modules) => {
2559325619
handOff(node, "globalThis");
2559425620
}
2559525621
}
25596-
if (A.isDefunNode(node) && node.id) {
25597-
localFunctions.set(node.id.definition, node);
25622+
if ((A.isDefunNode(node) || A.isDefClassNode(node)) && node.id) {
25623+
localFunctions.set(node.id.definition.identifiers[0], node);
2559825624
} else if (
2559925625
A.isVarDefNode(node) &&
2560025626
A.isSymbolDeclarationNode(node.id) &&
2560125627
node.init &&
2560225628
A.isLambdaNode(node.init)
2560325629
) {
25604-
localFunctions.set(node.id.definition, node.init);
25605-
} else if (A.isSymbolRefNode(node) && isWrittenName(node, walker)) {
25606-
writtenNames.add(node.definition);
25630+
localFunctions.set(node.id.definition.identifiers[0], node.init);
25631+
} else if (
25632+
A.isSymbolRefNode(node) &&
25633+
(isWrittenName(node, walker) ||
25634+
(A.isUnaryPrefixNode(walker.parent(0)) &&
25635+
walker.parent(0).operator === "delete"))
25636+
) {
25637+
if (isUndeclaredRef(node)) {
25638+
reboundGlobals.add(node.name);
25639+
} else {
25640+
writtenNames.add(node.definition.identifiers[0]);
25641+
}
2560725642
}
2560825643
if (depth > 0 && A.isSymbolRefNode(node)) {
2560925644
probedReads.add(node);
@@ -25623,12 +25658,8 @@ const installImprove = (modules) => {
2562325658
// it, until no call hands one on.
2562425659
for (let i = 0; i < handOffs.length; i++) {
2562525660
const { call, argument, name } = handOffs[i];
25626-
const lambda = calledFunction(
25627-
call.callee,
25628-
localFunctions,
25629-
writtenNames
25630-
);
25631-
if (lambda === undefined) continue;
25661+
const lambda = calledFunction(call.callee);
25662+
if (lambda === undefined || !A.isLambdaNode(lambda)) continue;
2563225663
const index = call.arguments.indexOf(argument);
2563325664
const parameter = lambda.params[index];
2563425665
if (
@@ -25650,6 +25681,154 @@ const installImprove = (modules) => {
2565025681
}
2565125682
};
2565225683

25684+
/**
25685+
* Drops the arguments past a function's parameters that do nothing, and
25686+
* writes `0` for one an unused parameter takes, where terser leaves them:
25687+
* a callee named without `reduce_vars`, or arguments spread after them.
25688+
* @param {Node} self a call
25689+
* @param {Compressor} compressor the compressor
25690+
* @returns {void}
25691+
*/
25692+
const trimArguments = (self, compressor) => {
25693+
const fn = A.isNewNode(self)
25694+
? constructorOf(self.callee)
25695+
: calledFunction(self.callee);
25696+
if (
25697+
!fn ||
25698+
!A.isLambdaNode(fn) ||
25699+
A.isPinned(fn) ||
25700+
A.usesArguments(fn) ||
25701+
// terser trims a call's own, short of a spread, but no `new`'s.
25702+
(!A.isNewNode(self) &&
25703+
(fn === self.callee || compressor.option("reduce_vars")) &&
25704+
!self.arguments.some(A.isExpansionNode))
25705+
) {
25706+
return;
25707+
}
25708+
const { params } = fn;
25709+
const args = self.arguments;
25710+
const { has_flag: hasFlag, UNUSED } = modules.flags;
25711+
for (let i = 0; i < args.length; i++) {
25712+
const parameter = params[i];
25713+
// Past a spread or into a rest parameter, no argument has a place.
25714+
if (A.isExpansionNode(args[i])) return;
25715+
if (A.isExpansionNode(parameter)) {
25716+
// An unused rest parameter takes what is left: only effects stay.
25717+
if (!hasFlag(parameter.argument, UNUSED)) return;
25718+
let kept = i;
25719+
for (let j = i; j < args.length; j++) {
25720+
if (A.isExpansionNode(args[j])) return;
25721+
const node = A.dropSideEffectFree(args[j], compressor);
25722+
if (node) args[kept++] = node;
25723+
}
25724+
args.length = kept;
25725+
return;
25726+
}
25727+
// A default runs where its argument is `undefined`, which `0` is not.
25728+
if (
25729+
parameter &&
25730+
A.isSymbolFunargNode(parameter) &&
25731+
hasFlag(parameter, UNUSED)
25732+
) {
25733+
const kept = A.dropSideEffectFree(args[i], compressor);
25734+
if (kept) {
25735+
args[i] = kept;
25736+
} else if (A.nodeSize(args[i], compressor) > 1) {
25737+
// `0` in place of a name or a digit writes nothing shorter.
25738+
args[i] = makeNode(A.NumberNode, args[i], { value: 0 });
25739+
}
25740+
}
25741+
}
25742+
let end = args.length;
25743+
while (end > params.length) {
25744+
const kept = A.dropSideEffectFree(args[end - 1], compressor);
25745+
if (kept) break;
25746+
end--;
25747+
}
25748+
args.length = end;
25749+
};
25750+
/**
25751+
* The constructor `new` runs on a class the program defines, written in its
25752+
* body: a class without one, derived, passes every argument on.
25753+
* @param {Node} callee the `new`'s callee
25754+
* @returns {Node | undefined} the constructor's function, or undefined
25755+
*/
25756+
const constructorOf = (callee) => {
25757+
const value = A.isClassNode(callee) ? callee : calledFunction(callee);
25758+
if (!value) return undefined;
25759+
// `new` of an arrow, a generator or an async function throws.
25760+
if (!A.isClassNode(value)) {
25761+
return A.isArrowNode(value) || value.generator || value.async
25762+
? undefined
25763+
: value;
25764+
}
25765+
const member = /** @type {Node[]} */ (
25766+
/** @type {Node} */ (value.body).body
25767+
).find(
25768+
(/** @type {Node} */ node) =>
25769+
A.isConciseMethodNode(node) &&
25770+
!node.static &&
25771+
!node.computed &&
25772+
(node.key.name === "constructor" || node.key.value === "constructor")
25773+
);
25774+
return member && /** @type {Node} */ (member.value);
25775+
};
25776+
// `f.length` counts the parameters before the first default or rest, which
25777+
// only `unsafe` takes as left alone: `Object.defineProperty` may set it.
25778+
A.wrapOptimizer("Dot", (optimizeDot) => (self, compressor) => {
25779+
if (
25780+
!improvements.enabled ||
25781+
self.optional ||
25782+
self.property.name !== "length" ||
25783+
!compressor.option("unsafe") ||
25784+
!compressor.option("evaluate")
25785+
) {
25786+
return optimizeDot(self, compressor);
25787+
}
25788+
const fn = calledFunction(self.object);
25789+
const parent = compressor.parent();
25790+
if (
25791+
!fn ||
25792+
!A.isLambdaNode(fn) ||
25793+
isLhs(self, parent) ||
25794+
(A.isUnaryPrefixNode(parent) && parent.operator === "delete")
25795+
) {
25796+
return optimizeDot(self, compressor);
25797+
}
25798+
let length = 0;
25799+
while (
25800+
length < fn.params.length &&
25801+
!A.isDefaultAssignNode(fn.params[length]) &&
25802+
!A.isExpansionNode(fn.params[length])
25803+
) {
25804+
length++;
25805+
}
25806+
return makeNode(A.NumberNode, self, { value: length });
25807+
});
25808+
for (const kind of ["Call", "New"]) {
25809+
A.wrapOptimizer(kind, (optimizeCall) => (self, compressor) => {
25810+
if (improvements.enabled && compressor.option("unused")) {
25811+
trimArguments(self, compressor);
25812+
}
25813+
// `Array(-0)` is `Array(0)`: a length is converted, losing the sign.
25814+
const [length] = self.arguments;
25815+
if (
25816+
improvements.enabled &&
25817+
self.arguments.length === 1 &&
25818+
A.isSymbolRefNode(self.callee) &&
25819+
self.callee.name === "Array" &&
25820+
isUndeclaredRef(self.callee) &&
25821+
A.isUnaryPrefixNode(length) &&
25822+
length.operator === "-" &&
25823+
A.isNumberNode(length.argument) &&
25824+
length.argument.value === 0
25825+
) {
25826+
self.arguments[0] = makeNode(A.NumberNode, length, { value: 0 });
25827+
}
25828+
return optimizeCall(self, compressor);
25829+
});
25830+
}
25831+
2565325832
/**
2565425833
* Whether a read sits in a `try` block, where a global's read may be there to
2565525834
* throw: `try { x } catch {}` probes for `x`.

‎test/helpers/oxcSmaller.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,6 @@ const OXC_SMALLER_BY_REASON = [
253253
"swc minifier: fixture/issues/10885/input.js",
254254
"swc minifier: fixture/issues/11368/input.js",
255255
"swc minifier: fixture/issues/11684/identifier-preserved/input.js",
256-
"swc minifier: fixture/issues/11684/identifier-side-effects/input.js",
257256
"swc minifier: fixture/issues/11684/scopes-and-mutations/input.js",
258257
"swc minifier: fixture/issues/12206/preserve-nonmatching-test-before-dynamic-case/input.js",
259258
"swc minifier: fixture/issues/12228/disabled/input.js",
@@ -473,7 +472,6 @@ const OXC_SMALLER_BY_REASON = [
473472
"oxc picks shorter spellings for comparisons, coercions and literals",
474473
[
475474
"swc minifier: fixture/issues/11082/input.js",
476-
"swc minifier: fixture/issues/array-constructor-length/input.js",
477475
"swc minifier: fixture/projects/backbone/2/input.js",
478476
"swc minifier: fixture/issues/10720/input.js",
479477
"swc minifier: fixture/issues/12194/input.js"

0 commit comments

Comments
 (0)