Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ impl<'a> PeepholeOptimizations {
/// Modify `expr` if that has `target_expr` as a parent, and returns true if modified.
///
/// For `target_expr` = `a`, `expr` = `a.b`, this function changes `expr` to `a?.b` and returns true.
fn inject_optional_chaining_if_matched(
pub fn inject_optional_chaining_if_matched(
target_id_name: &str,
expr_to_inject: &mut Expression<'a>,
expr: &mut Expression<'a>,
Expand Down
49 changes: 49 additions & 0 deletions crates/oxc_minifier/src/peephole/remove_unused_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use oxc_ecmascript::{
side_effects::MayHaveSideEffects,
};
use oxc_span::GetSpan;
use oxc_syntax::es_target::ESTarget;

use crate::ctx::Ctx;

Expand Down Expand Up @@ -78,7 +79,45 @@ impl<'a> PeepholeOptimizations {
self.remove_unused_expression(&mut logical_expr.left, ctx);
*e = ctx.ast.move_expression(&mut logical_expr.left);
self.mark_current_function_as_changed();
return false;
}

if self.target >= ESTarget::ES2020 {
// "a != null && a.b()" => "a?.b()"
// "a == null || a.b()" => "a?.b()"
let LogicalExpression {
left: logical_left,
right: logical_right,
operator: logical_op,
..
} = logical_expr.as_mut();
if let Expression::BinaryExpression(binary_expr) = logical_left {
if matches!(
(logical_op, binary_expr.operator),
(LogicalOperator::And, BinaryOperator::Inequality)
| (LogicalOperator::Or, BinaryOperator::Equality)
) {
let name_and_id = if let Expression::Identifier(id) = &binary_expr.left {
(!ctx.is_global_reference(id) && binary_expr.right.is_null())
.then_some((id.name, &mut binary_expr.left))
} else if let Expression::Identifier(id) = &binary_expr.right {
(!ctx.is_global_reference(id) && binary_expr.left.is_null())
.then_some((id.name, &mut binary_expr.right))
} else {
None
};
if let Some((name, id)) = name_and_id {
if Self::inject_optional_chaining_if_matched(&name, id, logical_right, ctx)
{
*e = ctx.ast.move_expression(logical_right);
self.mark_current_function_as_changed();
return false;
}
}
}
}
}

false
}

Expand Down Expand Up @@ -594,6 +633,16 @@ mod test {
);
}

#[test]
fn test_logical_expression() {
test("var a; a != null && a.b()", "var a; a?.b()");
test("var a; a == null || a.b()", "var a; a?.b()");
test_same("a != null && a.b()"); // a may have a getter
test_same("a == null || a.b()"); // a may have a getter
test("var a; null != a && a.b()", "var a; a?.b()");
test("var a; null == a || a.b()", "var a; a?.b()");
}

#[test]
fn test_object_literal() {
test("({})", "");
Expand Down
Loading