Skip to content

Commit

Permalink
implement late constant-folding for && || ??
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed May 24, 2024
1 parent 7d50a50 commit 8f1faf7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 9 deletions.
18 changes: 9 additions & 9 deletions internal/bundler_tests/snapshots/snapshots_dce.txt
Original file line number Diff line number Diff line change
Expand Up @@ -291,9 +291,9 @@ console.log([
7,
5
], [
3 /* a */ && 6 /* b */,
3 /* a */ || 6 /* b */,
3 /* a */ ?? 6 /* b */
6 /* b */,
3 /* a */,
3 /* a */
]);

---------- /out/const-entry.js ----------
Expand Down Expand Up @@ -329,9 +329,9 @@ console.log([
7,
5
], [
3 && 6,
3 || 6,
3 ?? 6
6,
3,
3
]);

---------- /out/nested-entry.js ----------
Expand Down Expand Up @@ -359,9 +359,9 @@ console.log([
!1,
!0
], [
"foo" /* a */ && "bar" /* b */,
"foo" /* a */ || "bar" /* b */,
"foo" /* a */ ?? "bar" /* b */
"bar" /* b */,
"foo" /* a */,
"foo" /* a */
]);

---------- /out/const-entry.js ----------
Expand Down
32 changes: 32 additions & 0 deletions internal/js_ast/js_ast_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -1208,6 +1208,11 @@ func ShouldFoldBinaryOperatorWhenMinifying(binary *EBinary) bool {
resultLen := approximatePrintedIntCharCount(float64(ToUint32(left) >> (ToUint32(right) & 31)))
return resultLen <= leftLen+3+rightLen
}

case BinOpLogicalAnd, BinOpLogicalOr, BinOpNullishCoalescing:
if IsPrimitiveLiteral(binary.Left.Data) {
return true
}
}
return false
}
Expand Down Expand Up @@ -1326,6 +1331,33 @@ func FoldBinaryOperator(loc logger.Loc, e *EBinary) Expr {
if left, right, ok := extractStringValues(e.Left, e.Right); ok {
return Expr{Loc: loc, Data: &EBoolean{Value: stringCompareUCS2(left, right) != 0}}
}

case BinOpLogicalAnd:
if boolean, sideEffects, ok := ToBooleanWithSideEffects(e.Left.Data); ok {
if !boolean {
return e.Left
} else if sideEffects == NoSideEffects {
return e.Right
}
}

case BinOpLogicalOr:
if boolean, sideEffects, ok := ToBooleanWithSideEffects(e.Left.Data); ok {
if boolean {
return e.Left
} else if sideEffects == NoSideEffects {
return e.Right
}
}

case BinOpNullishCoalescing:
if isNullOrUndefined, sideEffects, ok := ToNullOrUndefinedWithSideEffects(e.Left.Data); ok {
if !isNullOrUndefined {
return e.Left
} else if sideEffects == NoSideEffects {
return e.Right
}
}
}

return Expr{}
Expand Down

0 comments on commit 8f1faf7

Please sign in to comment.