From c50fcececaac7bd1d35f613bfe8c5749a1885825 Mon Sep 17 00:00:00 2001 From: Boshen Date: Wed, 29 Nov 2023 19:31:55 +0800 Subject: [PATCH] feat(prettier): wrap return statements with parentheses (#1583) --- crates/oxc_ast/src/ast/js.rs | 4 ++++ crates/oxc_prettier/src/format/function.rs | 16 ++++++++++++++-- crates/oxc_prettier/src/macros.rs | 6 ++++++ tasks/prettier_conformance/prettier.snap.md | 5 +---- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/oxc_ast/src/ast/js.rs b/crates/oxc_ast/src/ast/js.rs index 12138f960..3b1cc4dc6 100644 --- a/crates/oxc_ast/src/ast/js.rs +++ b/crates/oxc_ast/src/ast/js.rs @@ -225,6 +225,10 @@ impl<'a> Expression<'a> { matches!(self, Expression::FunctionExpression(_) | Expression::ArrowExpression(_)) } + pub fn is_binaryish(&self) -> bool { + matches!(self, Expression::BinaryExpression(_) | Expression::LogicalExpression(_)) + } + /// Returns literal's value converted to the Boolean type /// returns `true` when node is truthy, `false` when node is falsy, `None` when it cannot be determined. pub fn get_boolean_value(&self) -> Option { diff --git a/crates/oxc_prettier/src/format/function.rs b/crates/oxc_prettier/src/format/function.rs index 440ef23d2..a1f4bd480 100644 --- a/crates/oxc_prettier/src/format/function.rs +++ b/crates/oxc_prettier/src/format/function.rs @@ -2,7 +2,7 @@ use oxc_ast::ast::*; use crate::{ doc::{Doc, DocBuilder}, - group, ss, Format, Prettier, + group, if_break, indent, softline, ss, Format, Prettier, }; pub(super) fn print_function<'a>( @@ -105,7 +105,19 @@ pub(super) fn print_return_or_throw_argument<'a>( if let Some(argument) = argument { parts.push(ss!(" ")); - parts.push(argument.format(p)); + parts.push( + if argument.is_binaryish() || matches!(argument, Expression::SequenceExpression(_)) { + group![ + p, + if_break!(p, "("), + indent!(p, softline!(), argument.format(p)), + softline!(), + if_break!(p, ")"), + ] + } else { + argument.format(p) + }, + ); } parts.push(p.str(";")); diff --git a/crates/oxc_prettier/src/macros.rs b/crates/oxc_prettier/src/macros.rs index 5510ba9bf..a6219495e 100644 --- a/crates/oxc_prettier/src/macros.rs +++ b/crates/oxc_prettier/src/macros.rs @@ -108,6 +108,12 @@ macro_rules! if_break { group_id: $group_id, }) }}; + ($p:ident, $s:expr, $flat:expr) => {{ + if_break!($p, $s, $flat, None) + }}; + ($p:ident, $s:expr) => {{ + if_break!($p, $s, "", None) + }}; } #[macro_export] diff --git a/tasks/prettier_conformance/prettier.snap.md b/tasks/prettier_conformance/prettier.snap.md index 424f73194..c75fa86d5 100644 --- a/tasks/prettier_conformance/prettier.snap.md +++ b/tasks/prettier_conformance/prettier.snap.md @@ -1,4 +1,4 @@ -Compatibility: 200/578 (34.60%) +Compatibility: 201/578 (34.78%) # Failed @@ -457,9 +457,6 @@ Compatibility: 200/578 (34.60%) * return/binaryish.js * return/comment.js -### return-outside-function -* return-outside-function/return-outside-function.js - ### sequence-break * sequence-break/break.js