diff --git a/crates/oxc_formatter/src/print/arrow_function_expression.rs b/crates/oxc_formatter/src/print/arrow_function_expression.rs index 7ea4259065..2664f90c94 100644 --- a/crates/oxc_formatter/src/print/arrow_function_expression.rs +++ b/crates/oxc_formatter/src/print/arrow_function_expression.rs @@ -683,19 +683,10 @@ fn has_own_line_comment_before_body<'a>( } fn should_add_parens(expression: AstNode<'_, '_, Expression<'_>>) -> bool { - // Add parentheses to avoid confusion between `a => b ? c : d` and `a <= b ? c : d` - // but only if the body isn't an object/function or class expression because parentheses are always required in that - // case and added by the object expression itself - if matches!(&*expression, Expression::ConditionalExpression(_)) { - !matches!( - ExpressionLeftSide::leftmost(&expression), - Expression::ObjectExpression(_) - | Expression::FunctionExpression(_) - | Expression::ClassExpression(_) - ) - } else { - false - } + // Add parentheses to avoid confusion between `a => b ? c : d` and `a <= b ? c : d`, + // unless the body starts with an object, which always brings one (its own or an ancestor's). + matches!(&*expression, Expression::ConditionalExpression(_)) + && !matches!(ExpressionLeftSide::leftmost(&expression), Expression::ObjectExpression(_)) } fn has_rest_object_or_array_parameter(params: &FormalParameters) -> bool { diff --git a/crates/oxc_formatter/tests/fixtures/js/arrow-function/conditional-body-parens.js b/crates/oxc_formatter/tests/fixtures/js/arrow-function/conditional-body-parens.js new file mode 100644 index 0000000000..7f3465c901 --- /dev/null +++ b/crates/oxc_formatter/tests/fixtures/js/arrow-function/conditional-body-parens.js @@ -0,0 +1,2 @@ +x = () => (function () {}.a ? b : c); +x = () => () => (function () {}.a ? b : c); diff --git a/crates/oxc_formatter/tests/fixtures/js/arrow-function/conditional-body-parens.js.snap b/crates/oxc_formatter/tests/fixtures/js/arrow-function/conditional-body-parens.js.snap new file mode 100644 index 0000000000..50d8c2eb14 --- /dev/null +++ b/crates/oxc_formatter/tests/fixtures/js/arrow-function/conditional-body-parens.js.snap @@ -0,0 +1,21 @@ +--- +source: crates/oxc_formatter/tests/fixtures/mod.rs +--- +==================== Input ==================== +x = () => (function () {}.a ? b : c); +x = () => () => (function () {}.a ? b : c); + +==================== Output ==================== +------------------ +{ printWidth: 80 } +------------------ +x = () => (function () {}.a ? b : c); +x = () => () => (function () {}.a ? b : c); + +------------------- +{ printWidth: 100 } +------------------- +x = () => (function () {}.a ? b : c); +x = () => () => (function () {}.a ? b : c); + +===================== End =====================