Skip to content

Commit 8f1faf7

Browse files
committed
implement late constant-folding for && || ??
1 parent 7d50a50 commit 8f1faf7

2 files changed

Lines changed: 41 additions & 9 deletions

File tree

internal/bundler_tests/snapshots/snapshots_dce.txt

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,9 @@ console.log([
291291
7,
292292
5
293293
], [
294-
3 /* a */ && 6 /* b */,
295-
3 /* a */ || 6 /* b */,
296-
3 /* a */ ?? 6 /* b */
294+
6 /* b */,
295+
3 /* a */,
296+
3 /* a */
297297
]);
298298

299299
---------- /out/const-entry.js ----------
@@ -329,9 +329,9 @@ console.log([
329329
7,
330330
5
331331
], [
332-
3 && 6,
333-
3 || 6,
334-
3 ?? 6
332+
6,
333+
3,
334+
3
335335
]);
336336

337337
---------- /out/nested-entry.js ----------
@@ -359,9 +359,9 @@ console.log([
359359
!1,
360360
!0
361361
], [
362-
"foo" /* a */ && "bar" /* b */,
363-
"foo" /* a */ || "bar" /* b */,
364-
"foo" /* a */ ?? "bar" /* b */
362+
"bar" /* b */,
363+
"foo" /* a */,
364+
"foo" /* a */
365365
]);
366366

367367
---------- /out/const-entry.js ----------

internal/js_ast/js_ast_helpers.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,6 +1208,11 @@ func ShouldFoldBinaryOperatorWhenMinifying(binary *EBinary) bool {
12081208
resultLen := approximatePrintedIntCharCount(float64(ToUint32(left) >> (ToUint32(right) & 31)))
12091209
return resultLen <= leftLen+3+rightLen
12101210
}
1211+
1212+
case BinOpLogicalAnd, BinOpLogicalOr, BinOpNullishCoalescing:
1213+
if IsPrimitiveLiteral(binary.Left.Data) {
1214+
return true
1215+
}
12111216
}
12121217
return false
12131218
}
@@ -1326,6 +1331,33 @@ func FoldBinaryOperator(loc logger.Loc, e *EBinary) Expr {
13261331
if left, right, ok := extractStringValues(e.Left, e.Right); ok {
13271332
return Expr{Loc: loc, Data: &EBoolean{Value: stringCompareUCS2(left, right) != 0}}
13281333
}
1334+
1335+
case BinOpLogicalAnd:
1336+
if boolean, sideEffects, ok := ToBooleanWithSideEffects(e.Left.Data); ok {
1337+
if !boolean {
1338+
return e.Left
1339+
} else if sideEffects == NoSideEffects {
1340+
return e.Right
1341+
}
1342+
}
1343+
1344+
case BinOpLogicalOr:
1345+
if boolean, sideEffects, ok := ToBooleanWithSideEffects(e.Left.Data); ok {
1346+
if boolean {
1347+
return e.Left
1348+
} else if sideEffects == NoSideEffects {
1349+
return e.Right
1350+
}
1351+
}
1352+
1353+
case BinOpNullishCoalescing:
1354+
if isNullOrUndefined, sideEffects, ok := ToNullOrUndefinedWithSideEffects(e.Left.Data); ok {
1355+
if !isNullOrUndefined {
1356+
return e.Left
1357+
} else if sideEffects == NoSideEffects {
1358+
return e.Right
1359+
}
1360+
}
13291361
}
13301362

13311363
return Expr{}

0 commit comments

Comments
 (0)