Skip to content

Commit f2b043e

Browse files
committed
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`.
1 parent b5ce9b5 commit f2b043e

5 files changed

Lines changed: 118 additions & 1 deletion

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: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26106,6 +26106,83 @@ const installImprove = (modules) => {
2610626106
: undefined;
2610726107
};
2610826108

26109+
/**
26110+
* Stops a walk at a name that may be read in its dead zone: one no `var`,
26111+
* function or parameter declares.
26112+
* @param {Node} node a node walked
26113+
* @returns {WalkResult} `walk_abort` there
26114+
*/
26115+
const readsInDeadZone = (node) => {
26116+
if (!A.isSymbolRefNode(node)) return undefined;
26117+
const declared = node.definition && node.definition.identifiers[0];
26118+
return declared &&
26119+
(A.isSymbolVarNode(declared) ||
26120+
A.isSymbolDefunNode(declared) ||
26121+
A.isSymbolFunargNode(declared))
26122+
? undefined
26123+
: A.walk_abort;
26124+
};
26125+
26126+
/**
26127+
* Drops the value each `return` of a function called in place hands back,
26128+
* where nothing reads the call's value and the value runs or throws nothing:
26129+
* not of an `async` one, whose value may be a thenable it calls, nor of one
26130+
* its name or `arguments.callee` calls again.
26131+
* @param {Node} fn a function
26132+
* @param {Compressor} compressor the compressor, standing at the function
26133+
* @returns {void}
26134+
*/
26135+
const dropUnreadReturns = (fn, compressor) => {
26136+
const call = compressor.parent();
26137+
if (
26138+
!compressor.option("side_effects") ||
26139+
!(A.isFunctionNode(fn) || A.isArrowNode(fn)) ||
26140+
fn.async ||
26141+
fn.id ||
26142+
A.usesArguments(fn) ||
26143+
!A.isCallNode(call) ||
26144+
A.isNewNode(call) ||
26145+
call.callee !== fn
26146+
) {
26147+
return;
26148+
}
26149+
let child = call;
26150+
for (let level = 1; ; level++) {
26151+
const parent = compressor.parent(level);
26152+
if (A.isSimpleStatementNode(parent)) break;
26153+
if (A.isSequenceNode(parent) && A.tailNode(parent) !== child) break;
26154+
if (
26155+
!A.isSequenceNode(parent) &&
26156+
!(
26157+
A.isUnaryPrefixNode(parent) &&
26158+
(parent.operator === "!" || parent.operator === "void")
26159+
)
26160+
) {
26161+
return;
26162+
}
26163+
child = parent;
26164+
}
26165+
A.walk(/** @type {Node} */ (fn.body), (/** @type {Node} */ node) => {
26166+
if (A.isLambdaNode(node)) return true;
26167+
if (
26168+
A.isReturnNode(node) &&
26169+
node.argument &&
26170+
!A.hasSideEffects(node.argument, compressor) &&
26171+
!A.walk(node.argument, readsInDeadZone)
26172+
) {
26173+
node.argument = /** @type {Node} */ (/** @type {Node | null} */ (null));
26174+
}
26175+
});
26176+
};
26177+
26178+
// Before its body is tightened, which then folds the emptied `return`s.
26179+
for (const kind of ["Function", "Arrow"]) {
26180+
A.wrapOptimizer(kind, (optimizeLambda) => (self, compressor) => {
26181+
if (improvements.enabled) dropUnreadReturns(self, compressor);
26182+
return optimizeLambda(self, compressor);
26183+
});
26184+
}
26185+
2610926186
A.wrapOptimizer("Call", (optimizeCall) => (self, compressor) => {
2611026187
const optimized = optimizeCall(self, compressor);
2611126188
if (

‎test/helpers/swcSmaller.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ const SWC_SMALLER_BY_REASON = [
6666
[
6767
"swc drops what nothing reads or what has no effect: unused variables and destructuring, side-effect-free `new Map()` and pure calls, an empty constructor",
6868
[
69-
"swc minifier: fixture/issues/12301/input.js",
7069
"swc minifier: fixture/simple/sequences/.0001/input.js",
7170
"swc minifier: pass-1/joda/2/input.js"
7271
]

‎test/unitCases/javascript/__snapshots__/printer.unittest.js.snap‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2007,6 +2007,8 @@ exports[`syntax-printer improve phase should write less, printing the same: stor
20072007

20082008
exports[`syntax-printer improve phase should write less, printing the same: tabs in a long string, written raw, beside an escaped backslash 1`] = `"console.log(\\"row row row row row row row row row row row row row row row row row row row row row row row row row row row row row row \\",\\"a\\\\\\\\tb b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b \\",\\"c\\\\td\\\\te\\");"`;
20092009

2010+
exports[`syntax-printer improve phase should write less, printing the same: the values a function called in place returns, where nothing reads the call's value, in a \`finally\`, a branch, an arrow or a sequence 1`] = `"function g(v){return console.log(\\"g\\",v),v}var w=8;function t(y){!function(){try{throw 1}finally{return}}(),y||g(y),g(1)||g(2),g(3),y||g(y),y||g(4)}t(0),t(1);"`;
2011+
20102012
exports[`syntax-printer improve phase should write less, printing the same: two \`var\`s declared bare and set once to one constructor, read through it inside functions called with \`new\` 1`] = `"!function(){var C=function(){this.v=1};console.log([function(){return(new C).v},function(){return(new C).v}].map(function(f){return f()}))}();"`;
20112013

20122014
exports[`syntax-printer improve phase should write less, printing the same: two calls in a sequence, one keeping a \`let\` in a block 1`] = `"{let o=console.log.name;console.log(o,o)}try{console.log(1)}catch(o){}console.log(2);"`;

‎test/unitCases/javascript/printer.unittest.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1856,6 +1856,11 @@ const IMPROVED_CASES = [
18561856
'function f(a, b, body) { if (a) return { body }; if (b) return { "body": body }; } function g(x, foo) { return x ? foo["bar"]() : foo.bar(); } console.log(JSON.stringify([f(1, 0, 2), f(0, 1, 3), f(0, 0, 4)]), g(0, { bar: () => 5 }), g(1, { bar: () => 6 }));',
18571857
{ compress: {}, mangle: false }
18581858
],
1859+
[
1860+
"the values a function called in place returns, where nothing reads the call's value, in a `finally`, a branch, an arrow or a sequence",
1861+
'function g(v) { console.log("g", v); return v; } var w = 8; function t(y) { (function () { try { throw 1; } finally { return 2; } })(); (function (x) { if (x) return 3; g(x); })(y); (() => { if (g(1)) return 4; g(2); })(); g(3), function (x) { if (x) return x; g(x); }(y); void function (x) { if (x) return w; g(4); }(y); } t(0); t(1);',
1862+
{ compress: {}, mangle: false }
1863+
],
18591864
[
18601865
"a computed `NaN` or `null` key as the name it converts to, in an object, a pattern and a class",
18611866
"class C { [NaN]() { return 1; } static [null] = 2; get [null]() { return 3; } } var { [NaN]: a, [null]: b } = { [NaN]: 4, [null]: 5 }; console.log(new C().NaN(), C.null, new C().null, a, b, Object.keys({ [NaN]: 6, [null]: 7 }).join());",
@@ -10593,6 +10598,35 @@ describe("syntax-printer", () => {
1059310598
expect(plain.code).toContain("c?{[a]:1}:{a:1}");
1059410599
});
1059510600

10601+
it("should keep what a function called in place returns where it may be read", async () => {
10602+
const { minify } = await load();
10603+
for (const input of [
10604+
"a = function (x) { if (x) return 1; g(); }(y);",
10605+
"x = (h(), function (x) { if (x) return 1; g(); }(y));",
10606+
"(async function (x) { if (x) return 1; await g(); })(y);",
10607+
"(function f(n) { if (n) return f(n - 1) + 1; g(); })(y);",
10608+
"(function (n) { if (n) return 1; arguments.length && g(); })(y);",
10609+
"new function (x) { if (x) return 1; g(); }(y);",
10610+
"(function (x) { if (x) return x.y; g(); })(y);",
10611+
"try { (function (x) { if (x) return z; g(); })(y); } catch (e) {} let z = 1;",
10612+
"(function (x) { if (x) return undeclared; g(); })(y);",
10613+
"g(function (x) { if (x) return 1; h(); });",
10614+
"(function () { g(function (x) { if (x) return 1; h(); }); })();",
10615+
'(function f(n) { if (!n) return { valueOf() { console.log("v"); } }; f(n - 1) + 1; })(1);',
10616+
"(function f(n) { if (!n) return 2; console.log(f(n - 1) * 3); })(1);",
10617+
"var a; (function (x) { if (x) return a = 1; g(); })(y); console.log(a);",
10618+
"try { (function (x) { if (x) return 1n + 1; g(); })(y); } catch (e) { console.log(e.name); }"
10619+
]) {
10620+
const { code } = await minify(input, { compress: {}, mangle: false });
10621+
expect(code).toMatch(/return[^;}]/);
10622+
}
10623+
const { code } = await minify("(function (x) { if (x) return 1; g(); })(y);", {
10624+
compress: { side_effects: false },
10625+
mangle: false
10626+
});
10627+
expect(code).toContain("return 1");
10628+
});
10629+
1059610630
it("should keep a computed `NaN` key in brackets where computed keys stay", async () => {
1059710631
const { minify } = await load();
1059810632
const { code } = await minify("console.log({ [NaN]: 1, [null]: 2 });", {

0 commit comments

Comments
 (0)