Skip to content

Commit e7adf94

Browse files
feat(javascript): write !!(a&b)&&c as a&b?c:!1 in the minifier where it prints shorter (#22543)
* feat(javascript): write `!!(a&b)||c` as `a&b?!0:c` in the minifier A `&&` or `||` whose left operand negates, once or twice, what `!` has to parenthesize (`!!(a&b)&&c`, `!(a+b)||c`, `!(!a||!b)&&c`) becomes the conditional choosing a boolean that terser rewrote it from (`a&b?c:!1`, `a+b?c:!0`, `a&&b?c:!1`), its test negated where that prints shorter, when the conditional prints shorter where it sits. Both convert the test to a boolean once. Boolean contexts are left as terser writes them. Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * test(javascript): drop the jQuery Mobile entry main no longer prints bigger Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * fix(javascript): count a conditional test's parentheses before writing `!!(a)&&b` as a conditional Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD
1 parent 01ee7b7 commit e7adf94

5 files changed

Lines changed: 168 additions & 3 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20287,6 +20287,141 @@ const installImprove = (modules) => {
2028720287
: undefined;
2028820288
};
2028920289

20290+
const { PRECEDENCE } = /** @type {{ PRECEDENCE: Record<string, number> }} */ (
20291+
modules.parse
20292+
);
20293+
20294+
/**
20295+
* Whether an expression prints in parentheses as the test of a conditional.
20296+
* @param {Node} node the expression
20297+
* @returns {boolean} true when it does
20298+
*/
20299+
const parenthesizedAsTest = (node) =>
20300+
A.isConditionalNode(node) ||
20301+
A.isAssignNode(node) ||
20302+
A.isSequenceNode(node) ||
20303+
A.isArrowNode(node) ||
20304+
A.isYieldNode(node);
20305+
20306+
/**
20307+
* Whether an expression prints in parentheses as the operand of `!`.
20308+
* @param {Node} node the expression
20309+
* @returns {boolean} true when it does
20310+
*/
20311+
const parenthesizedAsOperand = (node) =>
20312+
parenthesizedAsTest(node) ||
20313+
A.isBinaryNode(node) ||
20314+
A.isPrivateInNode(node);
20315+
20316+
/**
20317+
* Whether an expression prints in parentheses as an operand of a binary
20318+
* operator other than an assignment.
20319+
* @param {Node} node the operand
20320+
* @param {string} operator the operator
20321+
* @param {boolean} right whether it is the right operand
20322+
* @returns {boolean} true when it does
20323+
*/
20324+
const parenthesizedInBinary = (node, operator, right) => {
20325+
if (parenthesizedAsTest(node)) return true;
20326+
if (!A.isBinaryNode(node)) return false;
20327+
// `??` mixed with `||` or `&&` is a syntax error without parens.
20328+
if (
20329+
(node.operator === "??" && (operator === "||" || operator === "&&")) ||
20330+
(operator === "??" && (node.operator === "||" || node.operator === "&&"))
20331+
) {
20332+
return true;
20333+
}
20334+
const precedence = PRECEDENCE[node.operator];
20335+
return (
20336+
PRECEDENCE[operator] > precedence ||
20337+
(PRECEDENCE[operator] === precedence && right)
20338+
);
20339+
};
20340+
20341+
/**
20342+
* `!!(a) && b` as `a ? b : !1` and `!(a) && b` as `a ? !1 : b`, `||` alike,
20343+
* where it prints shorter: both convert `a`, which `!` parenthesizes, once.
20344+
* @param {Node} node a logical expression
20345+
* @param {Node} self the node optimized into it
20346+
* @param {CompressorShape} compressor the compressor
20347+
* @returns {Node | undefined} the conditional, or undefined
20348+
*/
20349+
const booleanConditional = (node, self, compressor) => {
20350+
const { operator, left, right } = node;
20351+
if (
20352+
(operator !== "&&" && operator !== "||") ||
20353+
!A.isUnaryPrefixNode(left) ||
20354+
left.operator !== "!" ||
20355+
// The context read is the visited node's, which a node built since is not.
20356+
compressor.self() !== self
20357+
) {
20358+
return undefined;
20359+
}
20360+
const double =
20361+
A.isUnaryPrefixNode(left.argument) && left.argument.operator === "!";
20362+
/** @type {Node} */
20363+
let test = double ? left.argument.argument : left.argument;
20364+
if (!parenthesizedAsOperand(test) || compressor.in_boolean_context()) {
20365+
return undefined;
20366+
}
20367+
const parent = compressor.parent();
20368+
const logicalCost =
20369+
(double ? 4 : 3) + (parenthesizedInBinary(right, operator, true) ? 2 : 0);
20370+
let conditionalCost = A.isSequenceNode(right) ? 4 : 2;
20371+
// Any binary operator or a conditional's test parenthesizes the
20372+
// conditional, not always the logical.
20373+
if (
20374+
(A.isBinaryNode(parent) &&
20375+
!A.isAssignNode(parent) &&
20376+
!A.isDefaultAssignNode(parent) &&
20377+
!parenthesizedInBinary(node, parent.operator, parent.right === self)) ||
20378+
(A.isConditionalNode(parent) && parent.test === self)
20379+
) {
20380+
conditionalCost += 2;
20381+
}
20382+
// `!a` decides `&&` and `!!a` decides `||` where `a` is truthy.
20383+
let decidedByTruthy = double === (operator === "||");
20384+
let text = "";
20385+
// `!(!a || !b)` tests `a && b` with the branches swapped.
20386+
if (
20387+
A.isBinaryNode(test) &&
20388+
(test.operator === "&&" || test.operator === "||")
20389+
) {
20390+
text = modules.printToString(test);
20391+
const negated = A.negate(test, compressor);
20392+
const negatedText = modules.printToString(negated);
20393+
if (negatedText.length < text.length) {
20394+
conditionalCost += negatedText.length - text.length;
20395+
test = negated;
20396+
text = negatedText;
20397+
decidedByTruthy = !decidedByTruthy;
20398+
}
20399+
}
20400+
if (parenthesizedAsTest(test)) {
20401+
conditionalCost += 2;
20402+
} else if (
20403+
A.isExitNode(parent) ||
20404+
A.isYieldNode(parent) ||
20405+
A.isCaseNode(parent)
20406+
) {
20407+
// A keyword before the test keeps a space apart from a name it opens with.
20408+
if (text === "") text = modules.printToString(test);
20409+
if (/^[\w$\\\u0080-\uFFFF]/.test(text)) conditionalCost++;
20410+
}
20411+
if (conditionalCost >= logicalCost) return undefined;
20412+
const literal = makeNode(A.UnaryPrefixNode, node, {
20413+
operator: "!",
20414+
argument: makeNode(A.NumberNode, node, {
20415+
value: operator === "||" ? 0 : 1
20416+
})
20417+
});
20418+
return makeNode(A.ConditionalNode, node, {
20419+
test,
20420+
consequent: decidedByTruthy ? literal : right,
20421+
alternate: decidedByTruthy ? right : literal
20422+
});
20423+
};
20424+
2029020425
/**
2029120426
* `(a = b) === null || a === void 0` as `(a = b) == null`, and `!==` with
2029220427
* `&&` alike, where `a` holds what the first comparison stored.
@@ -21564,6 +21699,19 @@ const installImprove = (modules) => {
2156421699
);
2156521700
});
2156621701

21702+
// terser writes `c ? !0 : x` as `!!c || x` even where that prints longer.
21703+
for (const kind of ["Binary", "Conditional"]) {
21704+
A.wrapOptimizer(kind, (optimize) => (self, compressor) => {
21705+
const optimized = optimize(self, compressor);
21706+
return (
21707+
(improvements.enabled &&
21708+
A.isBinaryNode(optimized) &&
21709+
booleanConditional(optimized, self, compressor)) ||
21710+
optimized
21711+
);
21712+
});
21713+
}
21714+
2156721715
/**
2156821716
* The names a function's parameters bind, with `arguments` where it has its own.
2156921717
* @param {Node} lambda the function

‎test/helpers/oxcSmaller.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,6 @@ const OXC_SMALLER_BY_REASON = [
171171
"swc minifier: fixture/pr/11381/input.js",
172172
"swc minifier: fixture/pr/6272/input.js",
173173
"swc minifier: fixture/projects/backbone/16/input.js",
174-
"swc minifier: fixture/projects/backbone/20/input.js",
175174
"swc minifier: fixture/projects/backbone/6/input.js",
176175
"swc minifier: fixture/projects/jquery/26/input.js",
177176
"swc minifier: fixture/projects/jquery/27/input.js",
@@ -1009,7 +1008,6 @@ const OXC_SMALLER_BY_REASON = [
10091008
"swc minifier: fixture/projects/backbone/5/input.js",
10101009
"swc minifier: fixture/projects/jquery/.17/input.js",
10111010
"swc minifier: fixture/projects/react/16/input.js",
1012-
"swc minifier: fixture/projects/yui/2/input.js",
10131011
"terser compress: arrow/ternary_precedence",
10141012
"terser compress: collapse_vars/issue_2873_1",
10151013
"terser compress: conditionals/issue_1674_false_equivalency_of_props",

‎test/helpers/swcSmaller.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,6 @@ const SWC_SMALLER_BY_REASON = [
632632
"swc minifier: fixture/issues/12186/signed-shift/input.js",
633633
"swc minifier: fixture/issues/12307/input.js",
634634
"swc minifier: fixture/issues/array-constructor-length/input.js",
635-
"swc minifier: fixture/projects/yui/2/input.js",
636635
"terser compress: collapse_vars/collapse_vars_properties",
637636
"terser compress: pure_funcs/assign"
638637
]

‎test/specCases/minify-corpora.spectest.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,6 +1306,8 @@ const IMPROVED_YET_BIGGER = {
13061306
"12 bytes fewer, 1 more gzipped: `{x();return}` breaks the `return void` runs of the branches around it",
13071307
"fixture/issues/d3-color/1/input.js (the default minimizer's options)":
13081308
"2 bytes fewer, 1 more gzipped: `p*e*h` breaks the `h*(` runs of the products beside it gzip reused",
1309+
"fixture/next/31077/static/chunks/1606726a.10299989c08cb523/input.js (the default minimizer's options)":
1310+
"117 bytes fewer, 15 more gzipped: `c?x:!1` in place of `!!(c)&&x` breaks the `return!!(` runs gzip reused",
13091311
"projects/files/react-17.0.1.js (its own options)":
13101312
"33 bytes fewer, 3 more gzipped: `!!x` in place of `null!==x` breaks the runs of `null!==` gzip reused",
13111313
"evaluate/string_case (the default minimizer's options)":

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,12 @@ const IMPROVED_CASES = [
355355
"function f(a, b) { var x = a ? 1 : 0, y = a ? 0 : 1; return [x, y, a < b ? 1 : 0, !a ? 1 : 0, b + (a ? 1 : 0), b - (a ? 0 : 1), (a ? 1 : 0).toFixed(1), -(a ? 1 : 0), typeof (a ? 1 : 0)]; } for (var v of [0, 1, \"\", \"x\", NaN, null, {}, 0n, 2n]) console.log(f(v, 1), f(v, \"s\"));",
356356
{ compress: {}, mangle: false }
357357
],
358+
[
359+
"a conditional choosing a boolean, kept where `!` would parenthesize its test",
360+
"function f(a, b, c, d, e) { var r = [a & b ? true : c, a & b ? c : false, a + b ? false : c, a | b ? e() : true, a && b ? c : false, a || b ? c : false, a < b && c ? false : d, (a & b ? true : c) + 1, -(a & b ? c : false), (a & b ? c : false) ?? d, a & b ? (e(), c) : false, a & b ? true : c ? 1 : 2, a & b ? false : c ?? d, a & b ? c && d : false, a & b ? c || d : true]; return [r, a ^ b ? c : false]; } function* g(a, b) { yield a & b ? true : b; } function h(a, b, c) { switch (c) { case a & b ? c : false: return -a & b ? c : false; case 2: return 2; } } function k() { return 5; } for (var v of [0, 1, 2, NaN, \"\", \"x\", null]) console.log(f(v, 3, \"c\", 4, k), f(v, 0, null, 4, k), [...g(v, 1)], h(v, 1, 1), h(v, 2, false));",
361+
{ compress: {}, mangle: false },
362+
'function f(a,b,c,d,e){return[[a&b?!0:c,a&b?c:!1,a+b?!1:c,a|b?e():!0,a&&b?c:!1,a||b?c:!1,a<b&&c?!1:d,(a&b?!0:c)+1,-(a&b?c:!1),(a&b?c:!1)??d,a&b?(e(),c):!1,a&b?!0:c?1:2,a&b?!1:c??d,a&b?c&&d:!1,a&b?c||d:!0],a^b?c:!1]}function*g(a,b){yield a&b?!0:b}function h(a,b,c){switch(c){case a&b?c:!1:return-a&b?c:!1;case 2:return 2}}function k(){return 5}for(var v of[0,1,2,NaN,"","x",null])console.log(f(v,3,"c",4,k),f(v,0,null,4,k),[...g(v,1)],h(v,1,1),h(v,2,!1));'
363+
],
358364
[
359365
"a nested function reading its own `this`",
360366
`!function () { ${TRY} console.log([1].map(function () { return typeof this; })[0]); }();`,
@@ -886,6 +892,7 @@ const KEPT_CASES = [
886892
["consecutive `if`s alike whose branch does not always leave", 'function f(a, b) { for (var i = 0; i < 3; i++) { if (a === i) try { g(i); } finally { console.log(i); } if (b === i) try { g(i); } finally { console.log(i); } console.log(i); } } function g(i) { console.log("g", i); } f(0, 1); f(1, 1);'],
887893
["an array literal joining to a string longer than it", 'console.log([!0, !0, !0] + "");'],
888894
["a conditional choosing `1` or `0` that a number conversion writes no shorter, or choosing `-0`", "function f(a, b) { return [a < b ? 0 : 1, a + b ? 1 : 0, a in b ? 0 : 1, a ? 1 : -0, a ? 2 : 0, a ? -1 : 0]; } console.log(f(1, {}), f(0, { 0: 1 }));"],
895+
["a logical expression negating what needs no parentheses, in a condition, or no shorter as a conditional", "var r; function f(a, b, c, d, e) { if (!(a & b) && c) e(); while (!(a & b) && c) c = e(); return [!!a && b, !a || b, (!(a & b) && c) || d, (r = a) ? true : c]; } function g(a, b, c) { return a & b ? false : c; } function k() { return 0; } console.log(f(1, 2, 0, 4, k), f(0, 1, 2, 4, k), g(1, 2, 3), r);"],
889896
["`+` and `~` of what a literal does not give", "function f(a) { return [+[a], ~a !== 0 ? 1 : 2]; } console.log(f(1), f(1n));"],
890897
["a string literal indexed past its end, by no constant or as a target", 'function f(i) { var s = "abc"; "abc"[0] = 1; return ["abc"[5], "abc"[i], "abc"[1.5], "abc"[-1]]; } console.log(f(1));'],
891898
["a `new` whose constructor reads `arguments` or a rest, extends a class, or is rebound", 'function f(h) { function Z(a) { this.n = arguments.length; } function R(...a) { this.n = a.length; } class B { constructor(a) { this.n = arguments.length; } } class C extends B {} var V = function (a) { this.n = 1; }; if (h) V = function () { this.n = arguments.length; }; return [new Z(1, 2).n, new R(1, 2).n, new C(1, 2).n, new V(1, 2).n]; } console.log(f(0), f(1));'],
@@ -6228,6 +6235,17 @@ describe("syntax-printer", () => {
62286235
});
62296236
}
62306237

6238+
it("should keep a logical expression negating its test as the test of a conditional where `booleans` is off", async () => {
6239+
const { minify } = await load();
6240+
const { code } = await minify(
6241+
"function f(a, b, c, x, y) { return [(!!(a & b) && c) ? x : y, (!(a & b) || c) ? x : y]; }",
6242+
{ compress: { booleans: false }, mangle: false }
6243+
);
6244+
expect(code).toBe(
6245+
"function f(a,b,c,x,y){return[!!(a&b)&&c?x:y,a&b&&!c?y:x]}"
6246+
);
6247+
});
6248+
62316249
it("should split a `return` of `undefined` outside a function", async () => {
62326250
const { minify } = await load();
62336251
const { code } = await minify("if (a()) { b(); return; } c();", {

0 commit comments

Comments
 (0)