|
1 | 1 | use oxc_allocator::TakeIn; |
2 | 2 | use oxc_ast::{NONE, ast::*}; |
3 | | -use oxc_ecmascript::side_effects::MayHaveSideEffects; |
| 3 | +use oxc_ecmascript::{ |
| 4 | + constant_evaluation::{ConstantEvaluation, ConstantValue}, |
| 5 | + side_effects::MayHaveSideEffects, |
| 6 | +}; |
4 | 7 | use oxc_span::{ContentEq, GetSpan}; |
5 | 8 | use oxc_syntax::es_target::ESTarget; |
6 | 9 |
|
@@ -103,27 +106,6 @@ impl<'a> PeepholeOptimizations { |
103 | 106 | _ => {} |
104 | 107 | } |
105 | 108 |
|
106 | | - // "a ? true : false" => "!!a" |
107 | | - // "a ? false : true" => "!a" |
108 | | - if let (Expression::BooleanLiteral(left), Expression::BooleanLiteral(right)) = |
109 | | - (&expr.consequent, &expr.alternate) |
110 | | - { |
111 | | - match (left.value, right.value) { |
112 | | - (true, false) => { |
113 | | - let test = expr.test.take_in(ctx.ast); |
114 | | - let test = self.minimize_not(expr.span, test, ctx); |
115 | | - let test = self.minimize_not(expr.span, test, ctx); |
116 | | - return Some(test); |
117 | | - } |
118 | | - (false, true) => { |
119 | | - let test = expr.test.take_in(ctx.ast); |
120 | | - let test = self.minimize_not(expr.span, test, ctx); |
121 | | - return Some(test); |
122 | | - } |
123 | | - _ => {} |
124 | | - } |
125 | | - } |
126 | | - |
127 | 109 | // "a ? b ? c : d : d" => "a && b ? c : d" |
128 | 110 | if let Expression::ConditionalExpression(consequent) = &mut expr.consequent { |
129 | 111 | if ctx.expr_eq(&consequent.alternate, &expr.alternate) { |
@@ -389,6 +371,32 @@ impl<'a> PeepholeOptimizations { |
389 | 371 | } |
390 | 372 | } |
391 | 373 |
|
| 374 | + // "a ? true : false" => "!!a" |
| 375 | + // "a ? false : true" => "!a" |
| 376 | + match ( |
| 377 | + expr.consequent |
| 378 | + .evaluate_value(ctx) |
| 379 | + .and_then(ConstantValue::into_boolean) |
| 380 | + .filter(|_| !expr.consequent.may_have_side_effects(ctx)), |
| 381 | + expr.alternate |
| 382 | + .evaluate_value(ctx) |
| 383 | + .and_then(ConstantValue::into_boolean) |
| 384 | + .filter(|_| !expr.alternate.may_have_side_effects(ctx)), |
| 385 | + ) { |
| 386 | + (Some(true), Some(false)) => { |
| 387 | + let test = expr.test.take_in(ctx.ast); |
| 388 | + let test = self.minimize_not(expr.span, test, ctx); |
| 389 | + let test = self.minimize_not(expr.span, test, ctx); |
| 390 | + return Some(test); |
| 391 | + } |
| 392 | + (Some(false), Some(true)) => { |
| 393 | + let test = expr.test.take_in(ctx.ast); |
| 394 | + let test = self.minimize_not(expr.span, test, ctx); |
| 395 | + return Some(test); |
| 396 | + } |
| 397 | + _ => {} |
| 398 | + } |
| 399 | + |
392 | 400 | if ctx.expr_eq(&expr.alternate, &expr.consequent) { |
393 | 401 | // "/* @__PURE__ */ a() ? b : b" => "b" |
394 | 402 | if !expr.test.may_have_side_effects(ctx) { |
|
0 commit comments