From 2dfa997911b64dc7da2e064cbd9a11524f9017ed Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Mon, 6 Jun 2022 11:41:03 -0300 Subject: [PATCH 01/16] feat(rome_js_formatter): call arguments --- .../rome_formatter/src/format_extensions.rs | 1 + crates/rome_formatter/src/printer/mod.rs | 1 - crates/rome_js_formatter/src/builders.rs | 133 +++++-- .../src/js/expressions/call_arguments.rs | 372 +++++++++++++++++- .../src/js/expressions/object_expression.rs | 4 +- .../src/js/lists/call_argument_list.rs | 17 +- .../src/js/module/export_named_from_clause.rs | 4 +- crates/rome_js_formatter/src/lib.rs | 10 +- crates/rome_js_formatter/src/separated.rs | 9 +- .../src/ts/lists/enum_member_list.rs | 4 +- .../src/ts/types/object_type.rs | 4 +- crates/rome_js_formatter/src/utils/mod.rs | 29 +- .../tests/specs/js/module/call_expression.js | 17 + .../specs/js/module/call_expression.js.snap | 48 +++ .../js/first-argument-expansion/test.js.snap | 6 +- .../js/method-chain/issue-4125.js.snap | 3 +- .../js/preserve-line/argument-list.js.snap | 4 +- crates/rome_js_syntax/src/lib.rs | 1 + crates/rome_js_syntax/src/parameters_ext.rs | 11 + crates/rome_rowan/src/syntax/node.rs | 20 + 20 files changed, 626 insertions(+), 72 deletions(-) create mode 100644 crates/rome_js_formatter/tests/specs/js/module/call_expression.js create mode 100644 crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap create mode 100644 crates/rome_js_syntax/src/parameters_ext.rs diff --git a/crates/rome_formatter/src/format_extensions.rs b/crates/rome_formatter/src/format_extensions.rs index 73b4128e79a..42af623a3f7 100644 --- a/crates/rome_formatter/src/format_extensions.rs +++ b/crates/rome_formatter/src/format_extensions.rs @@ -141,6 +141,7 @@ pub trait MemoizeFormat { impl MemoizeFormat for T where T: Format {} /// Memoizes the output of its inner [Format] to avoid re-formatting a potential expensive object. +#[derive(Debug)] pub struct Memoized { inner: F, memory: RefCell>>>, diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index 7fda04ee003..5ed4845d6d9 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -282,7 +282,6 @@ impl<'a> Printer<'a> { if fits_on_line(&[variant], args.with_print_mode(mode), queue, self) { self.state.measured_group_fits = true; - queue.enqueue(PrintElementCall::new( variant, args.with_print_mode(mode), diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs index f99790f76a2..d7bfbf6793b 100644 --- a/crates/rome_js_formatter/src/builders.rs +++ b/crates/rome_js_formatter/src/builders.rs @@ -410,38 +410,17 @@ impl Format for FormatDelimited<'_, '_> { mode, } = self; - f.state_mut().track_token(open_token); - f.state_mut().track_token(close_token); + let open_delimiter = format_open_delimiter(open_token); + let close_delimiter = format_close_delimiter(close_token); - format_leading_trivia(open_token).fmt(f)?; + open_delimiter.as_leading_trivia_fmt().fmt(f)?; - let open_token_trailing_trivia = format_with(|f| { - // Not really interested in the pre-amble, but want to know if it was written - let mut buffer = VecBuffer::new(f.state_mut()); - - write!(buffer, [format_trailing_trivia(open_token)])?; - - let trivia = buffer.into_vec(); - - if !trivia.is_empty() { - f.write_elements(trivia)?; - soft_line_break().fmt(f)?; - } + let open_token_trailing_trivia = open_delimiter.as_trailing_trivia_fmt(); - Ok(()) - }); - - let close_token_leading_trivia = format_with(|f| { - let mut buffer = PreambleBuffer::new(f, soft_line_break()); - - write!( - buffer, - [format_leading_trivia(close_token).with_trim_mode(TriviaPrintMode::Trim)] - ) - }); + let close_token_leading_trivia = close_delimiter.as_leading_trivia_fmt(); let delimited = format_with(|f| { - format_trimmed_token(open_token).fmt(f)?; + open_delimiter.as_token_fmt().fmt(f)?; let format_content = format_with(|f| f.write_fmt(Arguments::from(content))); @@ -484,7 +463,7 @@ impl Format for FormatDelimited<'_, '_> { } }; - format_trimmed_token(close_token).fmt(f) + close_delimiter.as_token_fmt().fmt(f) }); let _grouped = match mode { @@ -511,3 +490,101 @@ enum DelimitedMode { SoftBlockIndent(Option), SoftBlockSpaces(Option), } + +/// Use this function to create an open delimiter, where you can extract the formatting of +/// trivias and token, separately. +/// +/// This function assumes that you will use the token to replicate [format_delimited], which means +/// that it will add possible line breaks +pub(crate) fn format_open_delimiter(open_token: &JsSyntaxToken) -> OpenDelimiter { + OpenDelimiter::new(open_token) +} + +/// Use this function to create an close delimiter, where you can extract the formatting of +/// trivias and token, separately. +/// +/// This function assumes that you will use the token to replicate [format_delimited], which means +/// that it will add possible line breaks +pub(crate) fn format_close_delimiter(close_token: &JsSyntaxToken) -> CloseDelimiter { + CloseDelimiter::new(close_token) +} + +pub(crate) struct OpenDelimiter<'t> { + open_token: &'t JsSyntaxToken, +} + +impl<'t> OpenDelimiter<'t> { + pub(crate) fn new(open_token: &'t JsSyntaxToken) -> Self { + Self { open_token } + } + + /// It extracts the formatted leading trivia of the token, without writing it in the buffer + pub(crate) fn as_leading_trivia_fmt(&self) -> impl Format + 't { + format_leading_trivia(self.open_token, TriviaPrintMode::Full) + } + + /// It extracts the formatted trailing trivia of the token, without writing it in the buffer + pub(crate) fn as_trailing_trivia_fmt(&self) -> impl Format + 't { + format_with(|f| { + // Not really interested in the pre-amble, but want to know if it was written + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [format_trailing_trivia(self.open_token)])?; + + let trivia = buffer.into_element(); + + if !trivia.is_empty() { + f.write_element(trivia)?; + soft_line_break_or_space().fmt(f)?; + } + + Ok(()) + }) + } + + /// It extracts the formatted token, without writing it in the buffer + pub(crate) fn as_token_fmt(&self) -> impl Format + 't { + format_with(|f| { + f.state_mut().track_token(self.open_token); + write!(f, [format_trimmed_token(self.open_token)]) + }) + } +} + +pub(crate) struct CloseDelimiter<'t> { + close_token: &'t JsSyntaxToken, +} + +impl<'t> CloseDelimiter<'t> { + pub(crate) fn new(close_token: &'t JsSyntaxToken) -> Self { + Self { close_token } + } + + /// It extracts the formatted leading trivia of the token, without writing it in the buffer + pub(crate) fn as_trailing_trivia_fmt(&self) -> impl Format + 't { + format_trailing_trivia(self.close_token) + } + + /// It extracts the formatted trailing trivia of the token, without writing it in the buffer + pub(crate) fn as_leading_trivia_fmt(&self) -> impl Format + 't { + format_with(|f| { + let mut buffer = PreambleBuffer::new(f, soft_line_break_or_space()); + + write!( + buffer, + [format_leading_trivia( + self.close_token, + TriviaPrintMode::Trim + )] + ) + }) + } + + /// It extracts the formatted token, without writing it in the buffer + pub(crate) fn as_token_fmt(&self) -> impl Format + 't { + format_with(|f| { + f.state_mut().track_token(self.close_token); + write!(f, [format_trimmed_token(self.close_token)]) + }) + } +} diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 3c814dce3b8..261055c8b0f 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,9 +1,14 @@ +use crate::builders::{format_close_delimiter, format_open_delimiter}; use crate::prelude::*; -use crate::utils::{is_simple_expression, token_has_comments}; +use crate::utils::{format_separated_for_call_arguments, is_simple_expression, token_has_comments}; use crate::FormatNodeFields; -use rome_formatter::write; -use rome_js_syntax::JsCallArgumentsFields; -use rome_js_syntax::{JsAnyCallArgument, JsCallArguments}; +use rome_formatter::{format_args, write}; +use rome_js_syntax::{ + JsAnyCallArgument, JsAnyExpression, JsAnyFunctionBody, JsArrayExpression, + JsArrowFunctionExpression, JsCallArgumentList, JsCallArguments, JsCallArgumentsFields, + JsFunctionExpression, JsObjectExpression, JsSyntaxNode, TsAsExpression, + TsTypeAssertionExpression, +}; use rome_rowan::{AstSeparatedList, SyntaxResult}; impl FormatNodeFields for FormatNodeRule { @@ -14,24 +19,230 @@ impl FormatNodeFields for FormatNodeRule { r_paren_token, } = node.as_fields(); - if is_simple_function_arguments(node)? { - return write![ + let l_paren_token = l_paren_token?; + let r_paren_token = r_paren_token?; + + // we create open a close delimiters + let open_delimiter = format_open_delimiter(&l_paren_token); + let close_delimiter = format_close_delimiter(&r_paren_token); + + // we now extracts the formatted version of trivias and tokens of the delimiters and + // we cache them. This is needed because `[rome_formatter::best_fitting]` will try to + // print each version first + + // tokens on the left + let l_leading_trivia = open_delimiter.as_leading_trivia_fmt().memoized(); + let l_paren = open_delimiter.as_token_fmt().memoized(); + let l_trailing_trivia = open_delimiter.as_trailing_trivia_fmt().memoized(); + + // tokens on the right + let r_leading_trivia = close_delimiter.as_leading_trivia_fmt().memoized(); + let r_paren = close_delimiter.as_token_fmt().memoized(); + let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt().memoized(); + + // particular formatting for hooks + if is_react_hook_with_deps_array(&args)? { + let mut list = args.elements(); + // SAFETY: the function `is_react_hook_with_deps_array` already checks the presence of the + // first two arguments, so it's safe un unwrap them + let first_argument = list.next().unwrap(); + let second_argument = list.next().unwrap(); + + // SAFETY: function is_react_hook_with_deps_array checks if there aren't any + // comments. If there are comments, we don't fall in this branch of the condition, + // so it's safe to not print them + write!( f, [ - l_paren_token.format(), - group_elements(&args.format()), - r_paren_token.format(), + &l_paren, + first_argument.node().format(), + first_argument.trailing_separator().format(), + space_token(), + second_argument.node().format(), + format_with(|f| { + // we don't want to print the trailing separator, so if it's present, we replace it + // with an empty element + if let Some(separator) = second_argument.trailing_separator()? { + return write!(f, [format_replaced(separator, &empty_element())]); + } + + Ok(()) + }), + &r_paren ] - ]; + )?; + return Ok(()); } - write!( - f, - [ - format_delimited(&l_paren_token?, &args.format(), &r_paren_token?,) - .soft_block_indent() - ] - ) + // We finished the "simple cases", we now need to use `best_fitting`. + // We now need to allocate a new vector with cached nodes, this is needed because + // we can't attempt to print the same node twice without incur in "printed token twice" errors. + // We also disallow the trailing separator, we are interested in doing it manually. + let separated: Vec<_> = args + .format_separated(token(",")) + .with_options( + FormatSeparatedOptions::default().with_trailing_separator(TrailingSeparator::Elide), + ) + .map(|e| e.memoized()) + .collect(); + + let should_group_first_argument = should_group_first_argument(&args)?; + let should_group_last_argument = should_group_last_argument(&args)?; + + dbg!(should_group_last_argument, should_group_first_argument); + // if the first or last groups needs grouping, then we prepare some special formatting + if should_group_first_argument || should_group_last_argument { + let formatted = format_with(|f| { + // `should_group_first_argument` and `should_group_last_argument` are mutually exclusive + // which means that if one is `false`, then the other is `true`. + // This means that in this branch we format the case where `should_group_first_argument`, + // in the else branch we format the case where `should_group_last_argument` is `true`. + if should_group_first_argument { + write!( + f, + [ + l_leading_trivia, + l_paren, + l_trailing_trivia, + format_with(|f| { + // special formatting of the first element + let mut iter = separated.iter(); + // SAFETY: check on the existence of at least one argument are done before + let first = iter.next().unwrap(); + f.join_with(&space_token()) + .entry(&format_with(|f| { + write!( + f, + [group_elements(&format_args![first, expand_parent()])] + ) + })) + .entries(iter) + .finish() + }), + r_leading_trivia, + r_paren, + r_trailing_trivia + ] + ) + } else { + write!( + f, + [ + l_leading_trivia, + l_paren, + l_trailing_trivia, + format_with(|f| { + // special formatting of the last element + let mut iter = separated.iter(); + // SAFETY: check on the existence of at least one argument are done before + let last = iter.next_back().unwrap(); + + f.join_with(&space_token()) + .entries(iter) + .entry(&format_with(|f| { + write!( + f, + [group_elements(&format_args![last, expand_parent()])] + ) + })) + .finish() + }), + r_leading_trivia, + r_paren, + r_trailing_trivia + ] + ) + } + }); + + // This is the version of where all the arguments are broken out + let all_arguments_expanded = format_with(|f| { + // this formatting structure replicates what we have inside the `format_delimited` + // function, but here we use a different way to print the trailing separator + write!( + f, + [ + &l_leading_trivia, + &l_paren, + &group_elements(&format_args![format_with(|f| { + write!( + f, + [ + &soft_block_indent(&format_args![ + &l_trailing_trivia, + format_with(|f| { + format_separated_for_call_arguments( + separated.iter(), + separated.len(), + f, + ) + }), + r_leading_trivia, + soft_line_break() + ]), + &r_paren + ] + ) + })]), + &r_trailing_trivia + ] + ) + }) + .memoized(); + + write!( + f, + [best_fitting![ + format_args![ + l_leading_trivia, + l_paren, + l_trailing_trivia, + group_elements(&format_args![format_with(|f| { + format_separated_for_call_arguments( + separated.iter(), + separated.len(), + f, + ) + })]), + r_leading_trivia, + r_paren, + r_trailing_trivia + ], + format_args![formatted], + format_args![all_arguments_expanded] + ]] + ) + } else { + write!( + f, + [group_elements(&format_args![ + l_leading_trivia, + l_paren, + l_trailing_trivia, + &if_group_breaks(&format_args![ + indent(&format_args![ + soft_line_break(), + &format_with(|f| { + format_separated_for_call_arguments( + separated.iter(), + separated.len(), + f, + ) + }), + ]), + soft_line_break(), + ]), + &if_group_fits_on_line(&format_args![&format_with(|f| { + f.join_with(&space_token()) + .entries(separated.iter()) + .finish() + }),]), + r_leading_trivia, + r_paren, + r_trailing_trivia + ]),] + ) + } } } @@ -71,3 +282,130 @@ fn is_simple_function_arguments(node: &JsCallArguments) -> SyntaxResult { Ok(true) } + +/// Checks if the the first argument requires grouping +fn should_group_first_argument(list: &JsCallArgumentList) -> SyntaxResult { + if list.len() != 2 { + return Ok(false); + } + let mut iter = list.iter(); + // SAFETY: checked at the beginning of the function + let first = iter.next().unwrap()?; + let second = iter.next().unwrap()?; + + let has_comments = first.syntax().has_comments_direct(); + + let is_function_like = if let JsAnyCallArgument::JsAnyExpression(expression) = first { + match expression { + JsAnyExpression::JsFunctionExpression(_) => true, + JsAnyExpression::JsArrowFunctionExpression(arrow) => { + let body = arrow.body()?; + matches!(body, JsAnyFunctionBody::JsFunctionBody(_)) + } + _ => false, + } + } else { + false + }; + + let second_arg_is_function_like = + if let JsAnyCallArgument::JsAnyExpression(ref expression) = second { + matches!( + expression, + JsAnyExpression::JsFunctionExpression(_) + | JsAnyExpression::JsArrowFunctionExpression(_) + | JsAnyExpression::JsConditionalExpression(_) + ) + } else { + false + }; + + Ok(!has_comments + && is_function_like + && !second_arg_is_function_like + && !can_group_argument(second.syntax())?) +} + +/// Checks if the last group requires grouping +fn should_group_last_argument(list: &JsCallArgumentList) -> SyntaxResult { + let mut iter = list.iter().rev(); + // SAFETY: checked at the beginning of the function + let last = iter.next(); + let penultimate = iter.next(); + + if let Some(last) = last { + // SAFETY: guaranteed by the syntax factory + let last = last.unwrap(); + let check_with_penultimate = if let Some(penultimate) = penultimate { + // SAFETY: guaranteed by the syntax factory + let penultimate = penultimate.unwrap(); + (last.syntax().kind() != penultimate.syntax().kind()) + && !JsArrayExpression::can_cast(penultimate.syntax().kind()) + || !JsArrowFunctionExpression::can_cast(last.syntax().kind()) + } else { + true + }; + + Ok(!last.syntax().has_comments_at_the_edges() + && can_group_argument(last.syntax())? + && check_with_penultimate) + } else { + Ok(false) + } +} + +/// Checks if the current argument requires grouping. +fn can_group_argument(argument: &JsSyntaxNode) -> SyntaxResult { + let result = if let Some(object_expression) = JsObjectExpression::cast(argument.clone()) { + object_expression.members().len() > 0 + || object_expression.syntax().has_comments_at_the_edges() + } else if let Some(array_expression) = JsArrayExpression::cast(argument.clone()) { + array_expression.elements().len() > 0 + || array_expression.syntax().has_comments_at_the_edges() + } else if let Some(assertion_expression) = TsTypeAssertionExpression::cast(argument.clone()) { + can_group_argument(assertion_expression.expression()?.syntax())? + } else if let Some(as_expression) = TsAsExpression::cast(argument.clone()) { + can_group_argument(as_expression.expression()?.syntax())? + } else { + JsFunctionExpression::can_cast(argument.kind()) + }; + + Ok(result) +} + +/// This function is used to check if the code is a hook-like code: +/// +/// ```js +/// useMemo(() => {}, []) +/// ``` +fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult { + let enough_arguments = node.len() == 2; + let result = if enough_arguments { + let mut iter = node.elements(); + // SAFETY: covered by enough_arguments + let first = iter.next().unwrap().into_node()?; + let second = iter.next().unwrap().into_node()?; + let first_node_matches = if let JsAnyCallArgument::JsAnyExpression( + JsAnyExpression::JsArrowFunctionExpression(arrow_function), + ) = first + { + let no_parameters = arrow_function.parameters()?.len() == 0; + let body = arrow_function.body()?; + let is_block = matches!(body, JsAnyFunctionBody::JsFunctionBody(_)); + + no_parameters && is_block + } else { + false + }; + + let second_node_matches = JsArrayExpression::can_cast(second.syntax().kind()); + + let no_comments = !node.syntax().has_comments_at_the_edges(); + + first_node_matches && second_node_matches && no_comments + } else { + false + }; + + Ok(result) +} diff --git a/crates/rome_js_formatter/src/js/expressions/object_expression.rs b/crates/rome_js_formatter/src/js/expressions/object_expression.rs index 505973857a0..b11abf12eae 100644 --- a/crates/rome_js_formatter/src/js/expressions/object_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/object_expression.rs @@ -1,5 +1,5 @@ use crate::prelude::*; -use crate::utils::has_leading_newline; +use crate::utils::node_has_leading_newline; use crate::FormatNodeFields; use rome_formatter::write; use rome_js_syntax::JsObjectExpression; @@ -13,7 +13,7 @@ impl FormatNodeFields for FormatNodeRule r_curly_token, } = node.as_fields(); - let has_newline = has_leading_newline(members.syntax()); + let has_newline = node_has_leading_newline(members.syntax()); if members.is_empty() { write!( diff --git a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs index 31c14a900d2..7ecf434735b 100644 --- a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs +++ b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs @@ -1,13 +1,24 @@ use crate::generated::FormatJsCallArgumentList; use crate::prelude::*; +use crate::utils::format_separated_for_call_arguments; +use rome_formatter::write; use rome_js_syntax::{JsCallArgumentList, JsSyntaxKind}; impl FormatRule for FormatJsCallArgumentList { type Context = JsFormatContext; fn fmt(node: &JsCallArgumentList, f: &mut JsFormatter) -> FormatResult<()> { - f.join_with(&soft_line_break_or_space()) - .entries(node.format_separated(JsSyntaxKind::COMMA)) - .finish() + let args = format_with(|f| { + let separated = node + .format_separated(JsSyntaxKind::COMMA) + .with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ) + .map(|e| e.memoized()); + format_separated_for_call_arguments(separated, node.len(), f) + }); + + dbg_write!(f, [&group_elements(&soft_block_indent(&args))]) } } diff --git a/crates/rome_js_formatter/src/js/module/export_named_from_clause.rs b/crates/rome_js_formatter/src/js/module/export_named_from_clause.rs index 0aae763c557..d919c260fa2 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_from_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_from_clause.rs @@ -1,5 +1,5 @@ use crate::prelude::*; -use crate::utils::{has_leading_newline, FormatWithSemicolon}; +use crate::utils::{node_has_leading_newline, FormatWithSemicolon}; use rome_formatter::write; use crate::FormatNodeFields; @@ -25,7 +25,7 @@ impl FormatNodeFields for FormatNodeRule { hey; }, [1, 4])"#; + + let syntax = SourceType::tsx(); let tree = parse(src, 0, syntax); let result = format_node(JsFormatContext::default(), &tree.syntax()) .unwrap() diff --git a/crates/rome_js_formatter/src/separated.rs b/crates/rome_js_formatter/src/separated.rs index e12309dc0bf..6921961038b 100644 --- a/crates/rome_js_formatter/src/separated.rs +++ b/crates/rome_js_formatter/src/separated.rs @@ -47,6 +47,9 @@ where // A trailing separator was present where it wasn't allowed, opt out of formatting return Err(FormatError::SyntaxError); } + TrailingSeparator::Elide => { + write!(f, [format_replaced(separator, &empty_element())])?; + } } } else { write!(f, [separator.format()])?; @@ -63,7 +66,7 @@ where TrailingSeparator::Mandatory => { format_inserted(self.separator).fmt(f)?; } - TrailingSeparator::Disallowed => { /* no op */ } + TrailingSeparator::Elide | TrailingSeparator::Disallowed => { /* no op */ } } } else { unreachable!( @@ -169,6 +172,10 @@ pub enum TrailingSeparator { /// A trailing separator is mandatory for the syntax to be correct Mandatory, + + /// A trailing separator might be present, but the consumer + /// decided to remove it with an [rome_formatter::empty_element] + Elide, } impl Default for TrailingSeparator { diff --git a/crates/rome_js_formatter/src/ts/lists/enum_member_list.rs b/crates/rome_js_formatter/src/ts/lists/enum_member_list.rs index 287634046fd..d3c02e53f38 100644 --- a/crates/rome_js_formatter/src/ts/lists/enum_member_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/enum_member_list.rs @@ -1,13 +1,13 @@ use crate::generated::FormatTsEnumMemberList; use crate::prelude::*; -use crate::utils::has_leading_newline; +use crate::utils::node_has_leading_newline; use rome_js_syntax::{JsSyntaxKind, TsEnumMemberList}; impl FormatRule for FormatTsEnumMemberList { type Context = JsFormatContext; fn fmt(node: &TsEnumMemberList, f: &mut JsFormatter) -> FormatResult<()> { - let has_newline = has_leading_newline(node.syntax()); + let has_newline = node_has_leading_newline(node.syntax()); f.join_with(&if has_newline { hard_line_break() diff --git a/crates/rome_js_formatter/src/ts/types/object_type.rs b/crates/rome_js_formatter/src/ts/types/object_type.rs index c7a09f8c8e1..2c5ac9b7ab6 100644 --- a/crates/rome_js_formatter/src/ts/types/object_type.rs +++ b/crates/rome_js_formatter/src/ts/types/object_type.rs @@ -1,5 +1,5 @@ use crate::prelude::*; -use crate::utils::has_leading_newline; +use crate::utils::node_has_leading_newline; use crate::FormatNodeFields; use rome_formatter::write; use rome_js_syntax::{TsObjectType, TsObjectTypeFields}; @@ -12,7 +12,7 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - if has_leading_newline(members.syntax()) { + if node_has_leading_newline(members.syntax()) { write!( f, [ diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 594c1645ff6..a6c4c977bdc 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -17,7 +17,7 @@ pub(crate) use object::{ is_break_after_colon, property_object_member_layout, write_member_name, PropertyObjectMemberLayout, }; -use rome_formatter::{normalize_newlines, write, Buffer, VecBuffer}; +use rome_formatter::{format_args, normalize_newlines, write, Buffer, VecBuffer}; use rome_js_syntax::suppression::{has_suppressions_category, SuppressionCategory}; use rome_js_syntax::JsSyntaxKind::JS_STRING_LITERAL; use rome_js_syntax::{ @@ -27,6 +27,7 @@ use rome_js_syntax::{ }; use rome_js_syntax::{JsSyntaxKind, JsSyntaxNode, JsSyntaxToken}; use rome_rowan::{AstNode, AstNodeList, Direction, SyntaxResult}; +use std::fmt::Debug; pub(crate) use simple::*; pub(crate) use string_utils::*; @@ -137,7 +138,7 @@ pub(crate) fn has_formatter_trivia(node: &JsSyntaxNode) -> bool { } /// Returns true if this node contains newlines in trivias. -pub(crate) fn has_leading_newline(node: &JsSyntaxNode) -> bool { +pub(crate) fn node_has_leading_newline(node: &JsSyntaxNode) -> bool { if let Some(leading_trivia) = node.first_leading_trivia() { for piece in leading_trivia.pieces() { if piece.is_newline() { @@ -523,3 +524,27 @@ impl Format for FormatMemberName { } } } + +/// This function is in charge to format the call arguments. +/// This function must be used on a vector of memoized nodes. +pub(crate) fn format_separated_for_call_arguments, I>( + separated: I, + number_of_elements: usize, + f: &mut JsFormatter, +) -> FormatResult<()> +where + I: Iterator, + S: std::fmt::Debug, +{ + let mut iterator = separated.enumerate(); + let mut join_with = f.join_with(soft_line_break_or_space()); + for (index, element) in iterator.by_ref() { + if index == number_of_elements - 1 { + join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); + } else { + join_with.entry(&element); + } + } + + join_with.finish() +} diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js new file mode 100644 index 00000000000..5d9444924dd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js @@ -0,0 +1,17 @@ + +useEffect(() => { + +}, [a, b]) + +useMemo(() => { + return { + d, e + } +}, [a, b]) + +useMemo(() => { + + } // some comment + , + [a, b] +) \ No newline at end of file diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap new file mode 100644 index 00000000000..42e2bf81565 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap @@ -0,0 +1,48 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: call_expression.js +--- +# Input + +useEffect(() => { + +}, [a, b]) + +useMemo(() => { + return { + d, e + } +}, [a, b]) + +useMemo(() => { + + } // some comment + , + [a, b] +) +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +useEffect(() => {}, [a, b]); + +useMemo( + () => { + return { + d, + e, + }; + }, + [a, b], +); + +useMemo( + () => {}, // some comment + [a, b], +); + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap index fd7e9f15dc2..03ec813da40 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap @@ -238,8 +238,7 @@ compose( somthing.reduce( function (item, thing) { return thing.blah = item; - }, - {}, + }, {}, ); somthing.reduce( @@ -269,8 +268,7 @@ func( func( () => { thing(); - }, - { yes: true, cats: 5 }, + }, { yes: true, cats: 5 }, ); compose( diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap index f0d3fc5f445..f9aca588665 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap @@ -215,8 +215,7 @@ Object.keys(props) (a, key) => { a[key] = props[key]; return a; - }, - {}, + }, {}, ); point().x(4).y(3).z(6).plot(); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap index 7dc1065212c..c3434470a6e 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: argument-list.js --- # Input @@ -333,8 +334,7 @@ doThing( func( () => { thing(); - }, - { yes: true, no: 5 }, + }, { yes: true, no: 5 }, ); doSomething( diff --git a/crates/rome_js_syntax/src/lib.rs b/crates/rome_js_syntax/src/lib.rs index 4848fe4d00a..9b2b01b8227 100644 --- a/crates/rome_js_syntax/src/lib.rs +++ b/crates/rome_js_syntax/src/lib.rs @@ -7,6 +7,7 @@ mod generated; pub mod expr_ext; pub mod modifier_ext; pub mod numbers; +mod parameters_ext; pub mod source_type; pub mod stmt_ext; pub mod suppression; diff --git a/crates/rome_js_syntax/src/parameters_ext.rs b/crates/rome_js_syntax/src/parameters_ext.rs new file mode 100644 index 00000000000..ae4a47ce6d2 --- /dev/null +++ b/crates/rome_js_syntax/src/parameters_ext.rs @@ -0,0 +1,11 @@ +use crate::JsAnyArrowFunctionParameters; +use rome_rowan::AstSeparatedList; + +impl JsAnyArrowFunctionParameters { + pub fn len(&self) -> usize { + match self { + JsAnyArrowFunctionParameters::JsAnyBinding(_) => 1, + JsAnyArrowFunctionParameters::JsParameters(parameters) => parameters.items().len(), + } + } +} diff --git a/crates/rome_rowan/src/syntax/node.rs b/crates/rome_rowan/src/syntax/node.rs index c987dd63f36..83dc39d2357 100644 --- a/crates/rome_rowan/src/syntax/node.rs +++ b/crates/rome_rowan/src/syntax/node.rs @@ -472,12 +472,32 @@ impl SyntaxNode { self.has_trailing_comments() || self.has_leading_comments() } + /// It checks if the current node has comments at the edges: + /// if first or last tokens contain comments (leading or trailing) + pub fn has_comments_at_the_edges(&self) -> bool { + self.first_token_has_comments() || self.last_token_has_comments() + } + /// Whether the node contains trailing comments. pub fn has_trailing_comments(&self) -> bool { self.last_token() .map_or(false, |tok| tok.has_trailing_comments()) } + /// Whether the last token of a node has comments (leading or trailing) + pub fn last_token_has_comments(&self) -> bool { + self.last_token().map_or(false, |tok| { + tok.has_trailing_comments() || tok.has_leading_comments() + }) + } + + /// Whether the first token of a node has comments (leading or trailing) + pub fn first_token_has_comments(&self) -> bool { + self.first_token().map_or(false, |tok| { + tok.has_trailing_comments() || tok.has_leading_comments() + }) + } + /// Whether the node contains leading comments. pub fn has_leading_comments(&self) -> bool { self.first_token() From 1574c8f11da146b629f89c894f5276aedf1ff5d6 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Tue, 14 Jun 2022 14:07:14 -0300 Subject: [PATCH 02/16] chore: temp changes --- crates/rome_cli/examples/input.js | 60 ++++++++++++- .../src/js/expressions/call_arguments.rs | 65 +++++++++----- .../src/js/lists/call_argument_list.rs | 4 +- crates/rome_js_formatter/src/lib.rs | 89 ++++++++++++++++++- crates/rome_js_formatter/src/utils/mod.rs | 32 +++++-- 5 files changed, 213 insertions(+), 37 deletions(-) diff --git a/crates/rome_cli/examples/input.js b/crates/rome_cli/examples/input.js index 4e5b6b5ead9..c6e10ad12c0 100644 --- a/crates/rome_cli/examples/input.js +++ b/crates/rome_cli/examples/input.js @@ -1,4 +1,56 @@ -function foo() { let var1 = [true, false] - let broken = [ 45, 54] - let var2 = (var1, var2) => {} -} +tap.test( + "RecordImport.advance", + (t) => { + mockFS( + (callback) => { + batch.setResults( + [fs.createReadStream(dataFile)], + (err) => { + getBatches( + (err, batches) => { + checkStates(batches, ["started"]); + + RecordImport.advance( + (err) => { + t.error(err, "Error should be empty."); + + getBatches( + (err, batches) => { + checkStates(batches, ["process.completed"]); + + // Need to manually move to the next step + batch.importRecords( + (err) => { + t.error(err, "Error should be empty."); + + getBatches( + (err, batches) => { + checkStates(batches, ["import.completed"]); + + RecordImport.advance( + (err) => { + t.error(err, "Error should be empty."); + }, + ); + + t.ok(batch.getCurState().name(i18n)); + }, + ); + }, + ); + + t.ok(batch.getCurState().name(i18n)); + }, + ); + }, + ); + + t.ok(batch.getCurState().name(i18n)); + }, + ); + }, + ); + }, + ); + }, +); diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 261055c8b0f..f53e2265161 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -40,6 +40,23 @@ impl FormatNodeFields for FormatNodeRule { let r_paren = close_delimiter.as_token_fmt().memoized(); let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt().memoized(); + // if the function has simple arguments, don't do any particular formatting and delegate/ + // the formatting of the arguments to the list itself + // if is_simple_function_arguments(node)? { + // return write!( + // f, + // [ + // l_leading_trivia, + // l_paren, + // l_trailing_trivia, + // &args.format(), + // r_leading_trivia, + // r_paren, + // r_trailing_trivia, + // ] + // ); + // } + // particular formatting for hooks if is_react_hook_with_deps_array(&args)? { let mut list = args.elements(); @@ -51,7 +68,7 @@ impl FormatNodeFields for FormatNodeRule { // SAFETY: function is_react_hook_with_deps_array checks if there aren't any // comments. If there are comments, we don't fall in this branch of the condition, // so it's safe to not print them - write!( + return write!( f, [ &l_paren, @@ -70,28 +87,27 @@ impl FormatNodeFields for FormatNodeRule { }), &r_paren ] - )?; - return Ok(()); + ); } - // We finished the "simple cases", we now need to use `best_fitting`. - // We now need to allocate a new vector with cached nodes, this is needed because - // we can't attempt to print the same node twice without incur in "printed token twice" errors. - // We also disallow the trailing separator, we are interested in doing it manually. - let separated: Vec<_> = args - .format_separated(token(",")) - .with_options( - FormatSeparatedOptions::default().with_trailing_separator(TrailingSeparator::Elide), - ) - .map(|e| e.memoized()) - .collect(); - let should_group_first_argument = should_group_first_argument(&args)?; let should_group_last_argument = should_group_last_argument(&args)?; - dbg!(should_group_last_argument, should_group_first_argument); // if the first or last groups needs grouping, then we prepare some special formatting if should_group_first_argument || should_group_last_argument { + // We finished the "simple cases", we now need to use `best_fitting`. + // We now need to allocate a new vector with cached nodes, this is needed because + // we can't attempt to print the same node twice without incur in "printed token twice" errors. + // We also disallow the trailing separator, we are interested in doing it manually. + let separated: Vec<_> = args + .format_separated(token(",")) + .with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ) + .map(|e| e.memoized()) + .collect(); + let formatted = format_with(|f| { // `should_group_first_argument` and `should_group_last_argument` are mutually exclusive // which means that if one is `false`, then the other is `true`. @@ -175,6 +191,7 @@ impl FormatNodeFields for FormatNodeRule { separated.iter(), separated.len(), f, + false, ) }), r_leading_trivia, @@ -202,6 +219,7 @@ impl FormatNodeFields for FormatNodeRule { separated.iter(), separated.len(), f, + false, ) })]), r_leading_trivia, @@ -213,6 +231,14 @@ impl FormatNodeFields for FormatNodeRule { ]] ) } else { + let separated: Vec<_> = args + .format_separated(token(",")) + .with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ) + .map(|e| e.memoized()) + .collect(); write!( f, [group_elements(&format_args![ @@ -225,17 +251,16 @@ impl FormatNodeFields for FormatNodeRule { &format_with(|f| { format_separated_for_call_arguments( separated.iter(), - separated.len(), + args.len(), f, + false, ) }), ]), soft_line_break(), ]), &if_group_fits_on_line(&format_args![&format_with(|f| { - f.join_with(&space_token()) - .entries(separated.iter()) - .finish() + format_separated_for_call_arguments(separated.iter(), args.len(), f, true) }),]), r_leading_trivia, r_paren, diff --git a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs index 7ecf434735b..c145df66166 100644 --- a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs +++ b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs @@ -16,9 +16,9 @@ impl FormatRule for FormatJsCallArgumentList { .with_trailing_separator(TrailingSeparator::Elide), ) .map(|e| e.memoized()); - format_separated_for_call_arguments(separated, node.len(), f) + format_separated_for_call_arguments(separated, node.len(), f, false) }); - dbg_write!(f, [&group_elements(&soft_block_indent(&args))]) + write!(f, [&group_elements(&soft_block_indent(&args))]) } } diff --git a/crates/rome_js_formatter/src/lib.rs b/crates/rome_js_formatter/src/lib.rs index b5e78d3dc07..a363a5d3b3c 100644 --- a/crates/rome_js_formatter/src/lib.rs +++ b/crates/rome_js_formatter/src/lib.rs @@ -525,9 +525,92 @@ mod test { #[test] // use this test check if your snippet prints as you wish, without using a snapshot fn quick_test() { - let src = r#"expect.toTriggerReadyStateChanges([ - // Nothing. -],);"#; + let src = r#" + tap.test("RecordImport.advance", (t) => { + const checkStates = (batches, states) => { + t.equal(batches.length, states.length); + for (const batch of batches) { + t.equal(batch.state, states.shift()); + t.ok(batch.getCurState().name(i18n)); + } + }; + + const batch = init.getRecordBatch(); + const dataFile = path.resolve(process.cwd(), "testData", "default.json"); + + const getBatches = (callback) => { + RecordImport.find({}, "", {}, (err, batches) => { + callback(null, batches.filter((batch) => (batch.state !== "error" && + batch.state !== "completed"))); + }); + }; + + mockFS((callback) => { + batch.setResults([fs.createReadStream(dataFile)], (err) => { + t.error(err, "Error should be empty."); + t.equal(batch.results.length, 6, "Check number of results"); + for (const result of batch.results) { + t.equal(result.result, "unknown"); + t.ok(result.data); + t.equal(result.data.lang, "en"); + } + + getBatches((err, batches) => { + checkStates(batches, ["started"]); + + RecordImport.advance((err) => { + t.error(err, "Error should be empty."); + + getBatches((err, batches) => { + checkStates(batches, ["process.completed"]); + + // Need to manually move to the next step + batch.importRecords((err) => { + t.error(err, "Error should be empty."); + + getBatches((err, batches) => { + checkStates(batches, ["import.completed"]); + + RecordImport.advance((err) => { + t.error(err, "Error should be empty."); + + getBatches((err, batches) => { + checkStates(batches, + ["similarity.sync.completed"]); + + RecordImport.advance((err) => { + t.error(err, + "Error should be empty."); + + t.ok(batch.getCurState() + .name(i18n)); + + getBatches((err, batches) => { + checkStates(batches, []); + t.end(); + callback(); + }); + }); + + t.ok(batch.getCurState().name(i18n)); + }); + }); + + t.ok(batch.getCurState().name(i18n)); + }); + }); + + t.ok(batch.getCurState().name(i18n)); + }); + }); + + t.ok(batch.getCurState().name(i18n)); + }); + }); + }); +}); + + "#; // let src = r#"useEffect(() => { hey; }, [1, 4])"#; let syntax = SourceType::tsx(); diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index a6c4c977bdc..2d969b37d53 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -531,20 +531,36 @@ pub(crate) fn format_separated_for_call_arguments, I> separated: I, number_of_elements: usize, f: &mut JsFormatter, + join_with_space: bool, ) -> FormatResult<()> where I: Iterator, S: std::fmt::Debug, { let mut iterator = separated.enumerate(); - let mut join_with = f.join_with(soft_line_break_or_space()); - for (index, element) in iterator.by_ref() { - if index == number_of_elements - 1 { - join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); - } else { - join_with.entry(&element); + if join_with_space { + let mut join_with = f.join_with(soft_line_break_or_space()); + + for (index, element) in iterator.by_ref() { + if index == number_of_elements - 1 { + join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); + } else { + join_with.entry(&element); + } } - } - join_with.finish() + join_with.finish() + } else { + let mut join_with = f.join_with(space_token()); + + for (index, element) in iterator.by_ref() { + if index == number_of_elements - 1 { + join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); + } else { + join_with.entry(&element); + } + } + + join_with.finish() + } } From e4740b87740a69343c46349f952a44b328b7dcc3 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Wed, 8 Jun 2022 13:42:02 +0200 Subject: [PATCH 03/16] refactor(rome_formatter): Add `Rc` `FormatElement` Introduces a new reference counted `FormatElement`. Useful for situation where the same content is part of the resulting IR twice but with different parent formatting. --- crates/rome_formatter/src/format_element.rs | 8 ++++++ .../rome_formatter/src/format_extensions.rs | 25 ++++++++----------- crates/rome_formatter/src/printer/mod.rs | 2 ++ 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/crates/rome_formatter/src/format_element.rs b/crates/rome_formatter/src/format_element.rs index bb4565d1010..6d9013e6324 100644 --- a/crates/rome_formatter/src/format_element.rs +++ b/crates/rome_formatter/src/format_element.rs @@ -5,6 +5,7 @@ use rome_rowan::SyntaxTokenText; use std::borrow::Cow; use std::fmt::{self, Debug, Formatter}; use std::ops::Deref; +use std::rc::Rc; type Content = Box; @@ -65,6 +66,10 @@ pub enum FormatElement { /// A list of different variants representing the same content. The printer picks the best fitting content. /// Line breaks inside of a best fitting don't propagate to parent groups. BestFitting(BestFitting), + + /// Reference counted format element content. Useful when the same content must be emitted twice + /// because it avoids deep cloning of the inner content and instead only requires bumping a ref counter. + Rc(Rc), } #[derive(Clone, Copy, Eq, PartialEq, Debug)] @@ -144,6 +149,7 @@ impl Debug for FormatElement { best_fitting.fmt(fmt) } FormatElement::ExpandParent => write!(fmt, "ExpandParent"), + FormatElement::Rc(inner) => inner.fmt(fmt), } } } @@ -464,6 +470,7 @@ impl FormatElement { pub fn is_empty(&self) -> bool { match self { FormatElement::List(list) => list.is_empty(), + FormatElement::Rc(inner) => inner.is_empty(), _ => false, } } @@ -491,6 +498,7 @@ impl FormatElement { FormatElement::BestFitting(_) => false, FormatElement::LineSuffixBoundary => false, FormatElement::ExpandParent => true, + FormatElement::Rc(inner) => inner.will_break(), } } diff --git a/crates/rome_formatter/src/format_extensions.rs b/crates/rome_formatter/src/format_extensions.rs index 42af623a3f7..b61fb585694 100644 --- a/crates/rome_formatter/src/format_extensions.rs +++ b/crates/rome_formatter/src/format_extensions.rs @@ -1,6 +1,7 @@ use crate::prelude::*; use std::cell::RefCell; use std::marker::PhantomData; +use std::rc::Rc; use crate::{write, Buffer, VecBuffer}; @@ -118,15 +119,15 @@ pub trait MemoizeFormat { /// /// // Calls `format` for everytime the object gets formatted /// assert_eq!( - /// format!(SimpleFormatContext::default(), [token("Formatted 1 times."), token("Formatted 2 times.")]), - /// format!(SimpleFormatContext::default(), [normal, normal]) + /// "Formatted 1 times. Formatted 2 times.", + /// format!(SimpleFormatContext::default(), [normal, space_token(), normal]).unwrap().print().as_code() /// ); /// /// // Memoized memoizes the result and calls `format` only once. /// let memoized = normal.memoized(); /// assert_eq!( - /// format!(SimpleFormatContext::default(), [token("Formatted 3 times."), token("Formatted 3 times.")]), - /// format![SimpleFormatContext::default(), [memoized, memoized]] + /// "Formatted 3 times. Formatted 3 times.", + /// format![SimpleFormatContext::default(), [memoized, space_token(), memoized]].unwrap().print().as_code() /// ); /// ``` /// @@ -144,7 +145,7 @@ impl MemoizeFormat for T where T: Format {} #[derive(Debug)] pub struct Memoized { inner: F, - memory: RefCell>>>, + memory: RefCell>>>, options: PhantomData, } @@ -170,9 +171,7 @@ where if let Some(memory) = self.memory.borrow().as_ref() { return match memory { Ok(elements) => { - for element in elements { - f.write_element(element.clone())?; - } + f.write_element(FormatElement::Rc(elements.clone()))?; Ok(()) } @@ -185,12 +184,10 @@ where match result { Ok(_) => { - let elements = buffer.into_vec(); - for element in &elements { - f.write_element(element.clone())?; - } - - *self.memory.borrow_mut() = Some(Ok(elements)); + let elements = buffer.into_element(); + let reference = Rc::new(elements); + f.write_element(FormatElement::Rc(reference.clone()))?; + *self.memory.borrow_mut() = Some(Ok(reference)); Ok(()) } diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index 5ed4845d6d9..32f04d0e881 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -293,6 +293,7 @@ impl<'a> Printer<'a> { } } } + FormatElement::Rc(content) => queue.enqueue(PrintElementCall::new(content, args)), } } @@ -799,6 +800,7 @@ fn fits_element_on_line<'a, 'rest>( return Fits::No; } } + FormatElement::Rc(content) => queue.enqueue(PrintElementCall::new(content, args)), } Fits::Maybe From 55d1252542def912e33777fc227c3315b7e16271 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Tue, 14 Jun 2022 14:53:10 -0300 Subject: [PATCH 04/16] chore: temp changes --- crates/rome_cli/examples/input.js | 6 +- .../src/js/expressions/call_arguments.rs | 19 +--- crates/rome_js_formatter/src/lib.rs | 90 ++----------------- 3 files changed, 8 insertions(+), 107 deletions(-) diff --git a/crates/rome_cli/examples/input.js b/crates/rome_cli/examples/input.js index c6e10ad12c0..e91bdf2e8f4 100644 --- a/crates/rome_cli/examples/input.js +++ b/crates/rome_cli/examples/input.js @@ -1,11 +1,9 @@ tap.test( - "RecordImport.advance", - (t) => { + "RecordImport.advance", (t) => { mockFS( (callback) => { batch.setResults( - [fs.createReadStream(dataFile)], - (err) => { + [fs.createReadStream(dataFile)], (err) => { getBatches( (err, batches) => { checkStates(batches, ["started"]); diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index f53e2265161..894e0b9028a 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -40,23 +40,6 @@ impl FormatNodeFields for FormatNodeRule { let r_paren = close_delimiter.as_token_fmt().memoized(); let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt().memoized(); - // if the function has simple arguments, don't do any particular formatting and delegate/ - // the formatting of the arguments to the list itself - // if is_simple_function_arguments(node)? { - // return write!( - // f, - // [ - // l_leading_trivia, - // l_paren, - // l_trailing_trivia, - // &args.format(), - // r_leading_trivia, - // r_paren, - // r_trailing_trivia, - // ] - // ); - // } - // particular formatting for hooks if is_react_hook_with_deps_array(&args)? { let mut list = args.elements(); @@ -371,7 +354,7 @@ fn should_group_last_argument(list: &JsCallArgumentList) -> SyntaxResult { true }; - Ok(!last.syntax().has_comments_at_the_edges() + Ok(!last.syntax().has_comments_direct() && can_group_argument(last.syntax())? && check_with_penultimate) } else { diff --git a/crates/rome_js_formatter/src/lib.rs b/crates/rome_js_formatter/src/lib.rs index a363a5d3b3c..30663477671 100644 --- a/crates/rome_js_formatter/src/lib.rs +++ b/crates/rome_js_formatter/src/lib.rs @@ -183,7 +183,7 @@ where if has_formatter_suppressions(syntax) { write!(f, [format_suppressed_node(syntax)])?; } else { - Self::fmt_fields(node, f)?; + dbg_write!(f, [format_with(|f| { Self::fmt_fields(node, f) })])?; }; Ok(()) @@ -526,91 +526,11 @@ mod test { // use this test check if your snippet prints as you wish, without using a snapshot fn quick_test() { let src = r#" - tap.test("RecordImport.advance", (t) => { - const checkStates = (batches, states) => { - t.equal(batches.length, states.length); - for (const batch of batches) { - t.equal(batch.state, states.shift()); - t.ok(batch.getCurState().name(i18n)); - } - }; - - const batch = init.getRecordBatch(); - const dataFile = path.resolve(process.cwd(), "testData", "default.json"); - - const getBatches = (callback) => { - RecordImport.find({}, "", {}, (err, batches) => { - callback(null, batches.filter((batch) => (batch.state !== "error" && - batch.state !== "completed"))); - }); - }; - - mockFS((callback) => { - batch.setResults([fs.createReadStream(dataFile)], (err) => { - t.error(err, "Error should be empty."); - t.equal(batch.results.length, 6, "Check number of results"); - for (const result of batch.results) { - t.equal(result.result, "unknown"); - t.ok(result.data); - t.equal(result.data.lang, "en"); - } - - getBatches((err, batches) => { - checkStates(batches, ["started"]); - - RecordImport.advance((err) => { - t.error(err, "Error should be empty."); - - getBatches((err, batches) => { - checkStates(batches, ["process.completed"]); - - // Need to manually move to the next step - batch.importRecords((err) => { - t.error(err, "Error should be empty."); - - getBatches((err, batches) => { - checkStates(batches, ["import.completed"]); - - RecordImport.advance((err) => { - t.error(err, "Error should be empty."); - - getBatches((err, batches) => { - checkStates(batches, - ["similarity.sync.completed"]); - - RecordImport.advance((err) => { - t.error(err, - "Error should be empty."); - - t.ok(batch.getCurState() - .name(i18n)); - - getBatches((err, batches) => { - checkStates(batches, []); - t.end(); - callback(); - }); - }); - - t.ok(batch.getCurState().name(i18n)); - }); - }); - - t.ok(batch.getCurState().name(i18n)); - }); - }); - - t.ok(batch.getCurState().name(i18n)); - }); - }); - - t.ok(batch.getCurState().name(i18n)); - }); - }); - }); -}); - "#; + Observable.timer(800) // debounce + + +"#; // let src = r#"useEffect(() => { hey; }, [1, 4])"#; let syntax = SourceType::tsx(); From 543b44cace69676d9580ef0bcc6340a697c9e150 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Tue, 14 Jun 2022 14:55:06 -0300 Subject: [PATCH 05/16] chore: conflict from rebase --- crates/rome_js_formatter/src/builders.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs index d7bfbf6793b..1bee77f7332 100644 --- a/crates/rome_js_formatter/src/builders.rs +++ b/crates/rome_js_formatter/src/builders.rs @@ -531,10 +531,10 @@ impl<'t> OpenDelimiter<'t> { write!(buffer, [format_trailing_trivia(self.open_token)])?; - let trivia = buffer.into_element(); + let trivia = buffer.into_vec(); if !trivia.is_empty() { - f.write_element(trivia)?; + f.write_elements(trivia)?; soft_line_break_or_space().fmt(f)?; } From a7f2dbb0847c63129b3be6c2be7c9dd7e151d325 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Tue, 14 Jun 2022 15:12:38 -0300 Subject: [PATCH 06/16] chore: move trivias outside the group --- .../src/js/expressions/call_arguments.rs | 70 +++++++++++-------- .../src/js/lists/call_argument_list.rs | 17 +++-- crates/rome_js_formatter/src/lib.rs | 8 ++- crates/rome_js_formatter/src/utils/mod.rs | 54 ++++++++------ 4 files changed, 85 insertions(+), 64 deletions(-) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 894e0b9028a..bc1294d3d99 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,6 +1,8 @@ use crate::builders::{format_close_delimiter, format_open_delimiter}; use crate::prelude::*; -use crate::utils::{format_separated_for_call_arguments, is_simple_expression, token_has_comments}; +use crate::utils::{ + fmt_arguments_multi_line, fmt_arguments_one_line, is_simple_expression, token_has_comments, +}; use crate::FormatNodeFields; use rome_formatter::{format_args, write}; use rome_js_syntax::{ @@ -40,6 +42,23 @@ impl FormatNodeFields for FormatNodeRule { let r_paren = close_delimiter.as_token_fmt().memoized(); let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt().memoized(); + if args.len() == 0 { + return write!( + f, + [ + l_leading_trivia, + l_paren, + group_elements(&format_args![ + l_trailing_trivia, + args.format(), + r_leading_trivia, + ]), + r_paren, + r_trailing_trivia + ] + ); + } + // particular formatting for hooks if is_react_hook_with_deps_array(&args)? { let mut list = args.elements(); @@ -170,11 +189,10 @@ impl FormatNodeFields for FormatNodeRule { &soft_block_indent(&format_args![ &l_trailing_trivia, format_with(|f| { - format_separated_for_call_arguments( + fmt_arguments_multi_line( separated.iter(), separated.len(), f, - false, ) }), r_leading_trivia, @@ -198,12 +216,7 @@ impl FormatNodeFields for FormatNodeRule { l_paren, l_trailing_trivia, group_elements(&format_args![format_with(|f| { - format_separated_for_call_arguments( - separated.iter(), - separated.len(), - f, - false, - ) + fmt_arguments_multi_line(separated.iter(), separated.len(), f) })]), r_leading_trivia, r_paren, @@ -224,31 +237,28 @@ impl FormatNodeFields for FormatNodeRule { .collect(); write!( f, - [group_elements(&format_args![ + [ l_leading_trivia, - l_paren, - l_trailing_trivia, - &if_group_breaks(&format_args![ - indent(&format_args![ + &group_elements(&format_args![ + l_paren, + l_trailing_trivia, + &if_group_breaks(&format_args![ + indent(&format_args![ + soft_line_break(), + &format_with(|f| { + fmt_arguments_multi_line(separated.iter(), args.len(), f) + }), + ]), soft_line_break(), - &format_with(|f| { - format_separated_for_call_arguments( - separated.iter(), - args.len(), - f, - false, - ) - }), ]), - soft_line_break(), - ]), - &if_group_fits_on_line(&format_args![&format_with(|f| { - format_separated_for_call_arguments(separated.iter(), args.len(), f, true) - }),]), - r_leading_trivia, - r_paren, + &if_group_fits_on_line(&format_args![&format_with(|f| { + fmt_arguments_one_line(separated.iter(), args.len(), f) + }),]), + r_leading_trivia, + r_paren, + ],), r_trailing_trivia - ]),] + ] ) } } diff --git a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs index c145df66166..2c84672cbc0 100644 --- a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs +++ b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs @@ -1,6 +1,6 @@ use crate::generated::FormatJsCallArgumentList; use crate::prelude::*; -use crate::utils::format_separated_for_call_arguments; +use crate::utils::fmt_arguments_multi_line; use rome_formatter::write; use rome_js_syntax::{JsCallArgumentList, JsSyntaxKind}; @@ -8,15 +8,14 @@ impl FormatRule for FormatJsCallArgumentList { type Context = JsFormatContext; fn fmt(node: &JsCallArgumentList, f: &mut JsFormatter) -> FormatResult<()> { + if node.len() == 0 { + return write!(f, [empty_element()]); + } let args = format_with(|f| { - let separated = node - .format_separated(JsSyntaxKind::COMMA) - .with_options( - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), - ) - .map(|e| e.memoized()); - format_separated_for_call_arguments(separated, node.len(), f, false) + let separated = node.format_separated(JsSyntaxKind::COMMA).with_options( + FormatSeparatedOptions::default().with_trailing_separator(TrailingSeparator::Elide), + ); + fmt_arguments_multi_line(separated, node.len(), f) }); write!(f, [&group_elements(&soft_block_indent(&args))]) diff --git a/crates/rome_js_formatter/src/lib.rs b/crates/rome_js_formatter/src/lib.rs index 30663477671..d80a7808a7a 100644 --- a/crates/rome_js_formatter/src/lib.rs +++ b/crates/rome_js_formatter/src/lib.rs @@ -183,7 +183,7 @@ where if has_formatter_suppressions(syntax) { write!(f, [format_suppressed_node(syntax)])?; } else { - dbg_write!(f, [format_with(|f| { Self::fmt_fields(node, f) })])?; + Self::fmt_fields(node, f)?; }; Ok(()) @@ -526,8 +526,12 @@ mod test { // use this test check if your snippet prints as you wish, without using a snapshot fn quick_test() { let src = r#" +export class Thing implements OtherThing { + do: (type: Type) => Provider = memoize( + (type: ObjectType): Provider => {}, + ); +} - Observable.timer(800) // debounce "#; diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 2d969b37d53..d06e31d4bd2 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -526,41 +526,49 @@ impl Format for FormatMemberName { } /// This function is in charge to format the call arguments. -/// This function must be used on a vector of memoized nodes. -pub(crate) fn format_separated_for_call_arguments, I>( +pub(crate) fn fmt_arguments_multi_line, I>( separated: I, number_of_elements: usize, f: &mut JsFormatter, - join_with_space: bool, ) -> FormatResult<()> where I: Iterator, S: std::fmt::Debug, { let mut iterator = separated.enumerate(); - if join_with_space { - let mut join_with = f.join_with(soft_line_break_or_space()); - - for (index, element) in iterator.by_ref() { - if index == number_of_elements - 1 { - join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); - } else { - join_with.entry(&element); - } + let mut join_with = f.join_with(soft_line_break_or_space()); + + for (index, element) in iterator.by_ref() { + if index == number_of_elements - 1 { + join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); + } else { + join_with.entry(&element); } + } - join_with.finish() - } else { - let mut join_with = f.join_with(space_token()); + join_with.finish() +} - for (index, element) in iterator.by_ref() { - if index == number_of_elements - 1 { - join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); - } else { - join_with.entry(&element); - } - } +/// This function is in charge to format the call arguments. +pub(crate) fn fmt_arguments_one_line, I>( + separated: I, + number_of_elements: usize, + f: &mut JsFormatter, +) -> FormatResult<()> +where + I: Iterator, + S: std::fmt::Debug, +{ + let mut iterator = separated.enumerate(); + let mut join_with = f.join_with(space_token()); - join_with.finish() + for (index, element) in iterator.by_ref() { + if index == number_of_elements - 1 { + join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); + } else { + join_with.entry(&element); + } } + + join_with.finish() } From 1be509af642f2d25ace11b79bc4188223fc55e2d Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Wed, 15 Jun 2022 14:03:18 -0300 Subject: [PATCH 07/16] chore: handle edge cases --- .../src/js/expressions/call_arguments.rs | 316 +++++++++--------- crates/rome_js_formatter/src/lib.rs | 14 +- 2 files changed, 163 insertions(+), 167 deletions(-) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index bc1294d3d99..bc4b17708da 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,15 +1,14 @@ use crate::builders::{format_close_delimiter, format_open_delimiter}; use crate::prelude::*; -use crate::utils::{ - fmt_arguments_multi_line, fmt_arguments_one_line, is_simple_expression, token_has_comments, -}; +use crate::utils::{fmt_arguments_multi_line, fmt_arguments_one_line, is_call_like_expression}; use crate::FormatNodeFields; use rome_formatter::{format_args, write}; +use rome_js_syntax::JsSyntaxKind::JS_EMPTY_STATEMENT; use rome_js_syntax::{ JsAnyCallArgument, JsAnyExpression, JsAnyFunctionBody, JsArrayExpression, JsArrowFunctionExpression, JsCallArgumentList, JsCallArguments, JsCallArgumentsFields, - JsFunctionExpression, JsObjectExpression, JsSyntaxNode, TsAsExpression, - TsTypeAssertionExpression, + JsConditionalExpression, JsFunctionBody, JsFunctionExpression, JsObjectExpression, + JsSyntaxNode, TsAsExpression, TsReferenceType, TsTypeAssertionExpression, }; use rome_rowan::{AstSeparatedList, SyntaxResult}; @@ -28,33 +27,15 @@ impl FormatNodeFields for FormatNodeRule { let open_delimiter = format_open_delimiter(&l_paren_token); let close_delimiter = format_close_delimiter(&r_paren_token); - // we now extracts the formatted version of trivias and tokens of the delimiters and - // we cache them. This is needed because `[rome_formatter::best_fitting]` will try to - // print each version first - - // tokens on the left - let l_leading_trivia = open_delimiter.as_leading_trivia_fmt().memoized(); - let l_paren = open_delimiter.as_token_fmt().memoized(); - let l_trailing_trivia = open_delimiter.as_trailing_trivia_fmt().memoized(); - - // tokens on the right - let r_leading_trivia = close_delimiter.as_leading_trivia_fmt().memoized(); - let r_paren = close_delimiter.as_token_fmt().memoized(); - let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt().memoized(); + // we now extracts the formatted version of trivias and tokens of the delimiters if args.len() == 0 { return write!( f, [ - l_leading_trivia, - l_paren, - group_elements(&format_args![ - l_trailing_trivia, - args.format(), - r_leading_trivia, - ]), - r_paren, - r_trailing_trivia + l_paren_token.format(), + args.format(), + r_paren_token.format() ] ); } @@ -67,13 +48,10 @@ impl FormatNodeFields for FormatNodeRule { let first_argument = list.next().unwrap(); let second_argument = list.next().unwrap(); - // SAFETY: function is_react_hook_with_deps_array checks if there aren't any - // comments. If there are comments, we don't fall in this branch of the condition, - // so it's safe to not print them return write!( f, [ - &l_paren, + l_paren_token.format(), first_argument.node().format(), first_argument.trailing_separator().format(), space_token(), @@ -87,90 +65,99 @@ impl FormatNodeFields for FormatNodeRule { Ok(()) }), - &r_paren + r_paren_token.format() ] ); } + // tokens on the left + let l_leading_trivia = open_delimiter.as_leading_trivia_fmt(); + let l_paren = open_delimiter.as_token_fmt(); + let l_trailing_trivia = open_delimiter.as_trailing_trivia_fmt(); + + // tokens on the right + let r_leading_trivia = close_delimiter.as_leading_trivia_fmt(); + let r_paren = close_delimiter.as_token_fmt(); + let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt(); + let should_group_first_argument = should_group_first_argument(&args)?; let should_group_last_argument = should_group_last_argument(&args)?; + // We finished the "simple cases", we now need to use `best_fitting`. + // We now need to allocate a new vector with cached nodes, this is needed because + // we can't attempt to print the same node twice without incur in "printed token twice" errors. + // We also disallow the trailing separator, we are interested in doing it manually. + let separated: Vec<_> = args + .format_separated(token(",")) + .with_options( + FormatSeparatedOptions::default().with_trailing_separator(TrailingSeparator::Elide), + ) + .map(|e| e.memoized()) + .collect(); + // if the first or last groups needs grouping, then we prepare some special formatting if should_group_first_argument || should_group_last_argument { - // We finished the "simple cases", we now need to use `best_fitting`. - // We now need to allocate a new vector with cached nodes, this is needed because - // we can't attempt to print the same node twice without incur in "printed token twice" errors. - // We also disallow the trailing separator, we are interested in doing it manually. - let separated: Vec<_> = args - .format_separated(token(",")) - .with_options( - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), - ) - .map(|e| e.memoized()) - .collect(); - - let formatted = format_with(|f| { + // We now cache them the delimiters tokens. This is needed because `[rome_formatter::best_fitting]` will try to + // print each version first + // tokens on the left + let l_leading_trivia = l_leading_trivia.memoized(); + let l_paren = l_paren.memoized(); + let l_trailing_trivia = l_trailing_trivia.memoized(); + + // tokens on the right + let r_leading_trivia = r_leading_trivia.memoized(); + let r_paren = r_paren.memoized(); + let r_trailing_trivia = r_trailing_trivia.memoized(); + + let edge_arguments_not_grouped = format_with(|f| { // `should_group_first_argument` and `should_group_last_argument` are mutually exclusive // which means that if one is `false`, then the other is `true`. // This means that in this branch we format the case where `should_group_first_argument`, // in the else branch we format the case where `should_group_last_argument` is `true`. + + write!(f, [l_leading_trivia, l_paren, l_trailing_trivia,])?; if should_group_first_argument { write!( f, - [ - l_leading_trivia, - l_paren, - l_trailing_trivia, - format_with(|f| { - // special formatting of the first element - let mut iter = separated.iter(); - // SAFETY: check on the existence of at least one argument are done before - let first = iter.next().unwrap(); - f.join_with(&space_token()) - .entry(&format_with(|f| { - write!( - f, - [group_elements(&format_args![first, expand_parent()])] - ) - })) - .entries(iter) - .finish() - }), - r_leading_trivia, - r_paren, - r_trailing_trivia - ] - ) + [format_with(|f| { + // special formatting of the first element + let mut iter = separated.iter(); + // SAFETY: check on the existence of at least one argument are done before + let first = iter.next().unwrap(); + f.join_with(&space_token()) + .entry(&format_with(|f| { + write!( + f, + [group_elements(&format_args![first, expand_parent()])] + ) + })) + .entries(iter) + .finish() + }),] + )?; } else { write!( f, - [ - l_leading_trivia, - l_paren, - l_trailing_trivia, - format_with(|f| { - // special formatting of the last element - let mut iter = separated.iter(); - // SAFETY: check on the existence of at least one argument are done before - let last = iter.next_back().unwrap(); - - f.join_with(&space_token()) - .entries(iter) - .entry(&format_with(|f| { - write!( - f, - [group_elements(&format_args![last, expand_parent()])] - ) - })) - .finish() - }), - r_leading_trivia, - r_paren, - r_trailing_trivia - ] - ) + [format_with(|f| { + // special formatting of the last element + let mut iter = separated.iter(); + // SAFETY: check on the existence of at least one argument are done before + let last = iter.next_back().unwrap(); + + f.join_with(&space_token()) + .entries(iter) + .entry(&format_with(|f| { + write!( + f, + [group_elements(&format_args![last, expand_parent()])] + ) + })) + .finish() + }),] + )?; } + + write!(f, [r_leading_trivia, r_paren, r_trailing_trivia]) }); // This is the version of where all the arguments are broken out @@ -182,7 +169,7 @@ impl FormatNodeFields for FormatNodeRule { [ &l_leading_trivia, &l_paren, - &group_elements(&format_args![format_with(|f| { + &group_elements(&format_with(|f| { write!( f, [ @@ -195,18 +182,17 @@ impl FormatNodeFields for FormatNodeRule { f, ) }), - r_leading_trivia, + &r_leading_trivia, soft_line_break() ]), &r_paren ] ) - })]), + })), &r_trailing_trivia ] ) - }) - .memoized(); + }); write!( f, @@ -222,19 +208,11 @@ impl FormatNodeFields for FormatNodeRule { r_paren, r_trailing_trivia ], - format_args![formatted], - format_args![all_arguments_expanded] + edge_arguments_not_grouped, + all_arguments_expanded ]] ) } else { - let separated: Vec<_> = args - .format_separated(token(",")) - .with_options( - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), - ) - .map(|e| e.memoized()) - .collect(); write!( f, [ @@ -242,6 +220,7 @@ impl FormatNodeFields for FormatNodeRule { &group_elements(&format_args![ l_paren, l_trailing_trivia, + // TODO: check if soft_line_block works here &if_group_breaks(&format_args![ indent(&format_args![ soft_line_break(), @@ -264,43 +243,6 @@ impl FormatNodeFields for FormatNodeRule { } } -/// Returns true if the passed [JsCallArguments] has a single argument -/// that is a simple function expression, array expression or object expression -fn is_simple_function_arguments(node: &JsCallArguments) -> SyntaxResult { - let JsCallArgumentsFields { - l_paren_token, - args, - r_paren_token, - } = node.as_fields(); - - if token_has_comments(&l_paren_token?) || token_has_comments(&r_paren_token?) { - return Ok(false); - } - - if args.len() > 1 { - return Ok(false); - } - - for item in args.elements() { - if let Some(separator) = item.trailing_separator()? { - if token_has_comments(separator) { - return Ok(false); - } - } - - match item.node() { - Ok(JsAnyCallArgument::JsAnyExpression(expr)) => { - if !is_simple_expression(expr)? { - return Ok(false); - } - } - _ => return Ok(false), - } - } - - Ok(true) -} - /// Checks if the the first argument requires grouping fn should_group_first_argument(list: &JsCallArgumentList) -> SyntaxResult { if list.len() != 2 { @@ -317,8 +259,7 @@ fn should_group_first_argument(list: &JsCallArgumentList) -> SyntaxResult match expression { JsAnyExpression::JsFunctionExpression(_) => true, JsAnyExpression::JsArrowFunctionExpression(arrow) => { - let body = arrow.body()?; - matches!(body, JsAnyFunctionBody::JsFunctionBody(_)) + matches!(arrow.body()?, JsAnyFunctionBody::JsFunctionBody(_)) } _ => false, } @@ -341,7 +282,7 @@ fn should_group_first_argument(list: &JsCallArgumentList) -> SyntaxResult Ok(!has_comments && is_function_like && !second_arg_is_function_like - && !can_group_argument(second.syntax())?) + && !could_group_argument(second.syntax(), false)?) } /// Checks if the last group requires grouping @@ -365,15 +306,15 @@ fn should_group_last_argument(list: &JsCallArgumentList) -> SyntaxResult { }; Ok(!last.syntax().has_comments_direct() - && can_group_argument(last.syntax())? + && could_group_argument(last.syntax(), false)? && check_with_penultimate) } else { Ok(false) } } -/// Checks if the current argument requires grouping. -fn can_group_argument(argument: &JsSyntaxNode) -> SyntaxResult { +/// Checks if the current argument could be grouped +fn could_group_argument(argument: &JsSyntaxNode, is_arrow_recursion: bool) -> SyntaxResult { let result = if let Some(object_expression) = JsObjectExpression::cast(argument.clone()) { object_expression.members().len() > 0 || object_expression.syntax().has_comments_at_the_edges() @@ -381,9 +322,67 @@ fn can_group_argument(argument: &JsSyntaxNode) -> SyntaxResult { array_expression.elements().len() > 0 || array_expression.syntax().has_comments_at_the_edges() } else if let Some(assertion_expression) = TsTypeAssertionExpression::cast(argument.clone()) { - can_group_argument(assertion_expression.expression()?.syntax())? + could_group_argument(assertion_expression.expression()?.syntax(), false)? } else if let Some(as_expression) = TsAsExpression::cast(argument.clone()) { - can_group_argument(as_expression.expression()?.syntax())? + could_group_argument(as_expression.expression()?.syntax(), false)? + } else if let Some(arrow_function) = JsArrowFunctionExpression::cast(argument.clone()) { + let body = arrow_function.body()?; + let return_type_annotation = arrow_function.return_type_annotation(); + + // Handles cases like: + // + // app.get("/", (req, res): void => { + // res.send("Hello World!"); + // }); + // + // export class Thing implements OtherThing { + // do: (type: Type) => Provider = memoize( + // (type: ObjectType): Provider => {} + // ); + // } + let can_group_type = + !return_type_annotation + .and_then(|rty| rty.ty().ok()) + .map_or(false, |any_type| { + TsReferenceType::can_cast(any_type.syntax().kind()) + || JsFunctionBody::cast(body.syntax().clone()).map_or( + true, + |function_body| { + function_body + .statements() + .iter() + .any(|st| st.syntax().kind() == JS_EMPTY_STATEMENT) + }, + ) + }); + + let body_is_delimited = matches!( + body, + JsAnyFunctionBody::JsFunctionBody(_) + | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsObjectExpression(_)) + | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsArrayExpression(_)) + ); + + if let JsAnyFunctionBody::JsAnyExpression(any_expression) = body.clone() { + let is_nested_arrow_function = + JsArrowFunctionExpression::cast(any_expression.syntax().clone()) + .and_then(|arrow_function_expression| { + arrow_function_expression + .body() + .ok() + .and_then(|body| could_group_argument(body.syntax(), true).ok()) + }) + .unwrap_or(false); + + body_is_delimited + && is_nested_arrow_function + && can_group_type + && (!is_arrow_recursion + && (is_call_like_expression(&any_expression) + || JsConditionalExpression::can_cast(body.syntax().kind()))) + } else { + body_is_delimited && can_group_type + } } else { JsFunctionExpression::can_cast(argument.kind()) }; @@ -397,10 +396,9 @@ fn can_group_argument(argument: &JsSyntaxNode) -> SyntaxResult { /// useMemo(() => {}, []) /// ``` fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult { - let enough_arguments = node.len() == 2; - let result = if enough_arguments { + let result = if node.len() == 2 { let mut iter = node.elements(); - // SAFETY: covered by enough_arguments + // SAFETY: covered by the previous if check let first = iter.next().unwrap().into_node()?; let second = iter.next().unwrap().into_node()?; let first_node_matches = if let JsAnyCallArgument::JsAnyExpression( @@ -417,9 +415,7 @@ fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult Provider = memoize( - (type: ObjectType): Provider => {}, - ); -} - - + + export class Thing implements OtherThing { + do: (type: Type) => Provider = memoize( + (type: ObjectType): Provider => {} + ); + } + "#; // let src = r#"useEffect(() => { hey; }, [1, 4])"#; From aafe413f12720b455bc4bc5a51d6bb7fc9fbfcd2 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Wed, 15 Jun 2022 14:05:14 -0300 Subject: [PATCH 08/16] chore: snapshots --- .../js/module/arrow/arrow_nested.js.snap | 30 ++--- .../tests/specs/js/module/arrow/call.js.snap | 15 +-- .../specs/js/module/arrow/params.js.snap | 69 +++++------ .../specs/js/module/call_expression.js.snap | 22 ++-- .../tests/specs/js/module/comments.js.snap | 9 +- .../expression/member-chain/computed.js.snap | 10 +- .../member-chain/inline-merge.js.snap | 5 +- .../specs/js/module/function/function.js.snap | 3 +- .../object/property_object_member.js.snap | 13 +- .../tests/specs/jsx/attributes.jsx.snap | 20 ++- .../prettier/js/arrow-call/arrow_call.js.snap | 16 ++- .../prettier/js/break-calls/parent.js.snap | 18 +-- .../function_expression.js.snap | 15 +-- .../array.js.snap | 20 +-- .../gobject_connect.js.snap | 12 +- .../mongo_connect.js.snap | 12 +- ...dangling-comment-in-arrow-function.js.snap | 9 +- .../js/method-chain/issue-4125.js.snap | 11 +- .../js/preserve-line/argument-list.js.snap | 9 +- .../js/template-literals/expressions.js.snap | 18 ++- .../js/test-declarations/jest-each.js.snap | 72 +++++------ .../test_declarations.js.snap | 116 ++++++++---------- .../js/trailing-comma/function-calls.js.snap | 10 +- .../typescript/arrow/arrow_regression.ts.snap | 10 +- .../typescript/as/assignment2.ts.snap | 20 ++- .../custom/typeParameters/variables.ts.snap | 9 +- .../pipe-function-calls-with-comments.ts.snap | 23 ++-- .../pipe-function-calls.ts.snap | 15 ++- .../last-argument-expansion/break.ts.snap | 27 ++-- .../typescript/method-chain/comment.ts.snap | 23 ++-- 30 files changed, 288 insertions(+), 373 deletions(-) diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap b/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap index cf5c162de4c..5a6371d92a9 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap @@ -44,13 +44,10 @@ Seq(typeDef.interface.groups).forEach( (group) => Seq(group.members).forEach( (member, memberName) => - markdownDoc( - member.doc, - { - typePath: typePath.concat(memberName.slice(1)), - signatures: member.signatures, - }, - ), + markdownDoc(member.doc, { + typePath: typePath.concat(memberName.slice(1)), + signatures: member.signatures, + }), ), ); @@ -62,16 +59,15 @@ const promiseFromCallback = (fn) => return reject(err); } return resolve(result); - },), + }), ); -runtimeAgent.getProperties( - objectId, - false, // ownProperties - false, // accessorPropertiesOnly - false, // generatePreview - (error, properties, internalProperties) => { - return 1; - }, -); +runtimeAgent.getProperties(objectId, false, false, false, ( + // ownProperties // accessorPropertiesOnly // generatePreview + error, + properties, + internalProperties, +) => { + return 1; +}); diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap b/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap index 13c6570bd65..d25aab91e36 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap @@ -61,14 +61,11 @@ const testResults = results.testResults.map( (testResult) => formatResult(testResult, formatter, reporter), ); -it( - "mocks regexp instances", - () => { - expect( - // () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), - ).not.toThrow(); - }, -); +it("mocks regexp instances", () => { + expect( + // () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), + ).not.toThrow(); +}); expect(() => asyncRequest({ url: "/test-endpoint" })); // .toThrowError(/Required parameter/); @@ -116,5 +113,5 @@ romise.then( ## Lines exceeding width of 80 characters - 54: result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", + 51: result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap b/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap index e6a0a5c0f9f..9720d5d8eb1 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: params.js --- # Input @@ -367,21 +368,19 @@ foo(([{ a: { b: { c: { d, e } } } }]) => {}); foo(([...{ a: { b: { c: { d, e } } } }]) => {}); -foo( - ( - n = { - a: { - b: { - c: { - d, - - e, - }, +foo(( + n = { + a: { + b: { + c: { + d, + + e, }, }, }, - ) => {}, -); + }, +) => {}); foo(({ x: [{ a, b }] }) => {}); @@ -407,39 +406,33 @@ foo((...[{ a, b }]) => {}); foo(([...[{ a, b }]]) => {}); -foo( - ( - a = [ - { - a, +foo(( + a = [ + { + a, - b, - }, - ], - ) => {}, -); + b, + }, + ], +) => {}); foo((a = (({ a, b }) => {})()) => {}); -foo( - ( - a = f({ - a, +foo(( + a = f({ + a, - b, - },), - ) => {}, -); + b, + }), +) => {}); foo((a = ({ a, b }) => {}) => {}); -foo( - ( - a = 1 + f({ - a, +foo(( + a = 1 + f({ + a, - b, - },), - ) => {}, -); + b, + }), +) => {}); diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap index 42e2bf81565..369e0792a65 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap @@ -31,18 +31,12 @@ Quote style: Double Quotes ----- useEffect(() => {}, [a, b]); -useMemo( - () => { - return { - d, - e, - }; - }, - [a, b], -); - -useMemo( - () => {}, // some comment - [a, b], -); +useMemo(() => { + return { + d, + e, + }; +}, [a, b]); + +useMemo(() => {}, [a, b]); // some comment diff --git a/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap b/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap index 2e15076a728..74e0e98b62e 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: comments.js --- # Input @@ -97,15 +98,13 @@ import { expression(/* block comment */); expression( - /* block comment */ +/* block comment */ ); -expression( - // line comment -); +expression(); // line comment expression( - // line comment +// line comment ); expression( diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/computed.js.snap b/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/computed.js.snap index f029b3e708e..8b38e84fb74 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/computed.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/computed.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: computed.js --- # Input @@ -19,10 +20,7 @@ Quote style: Double Quotes ----- nock(/test/) .matchHeader("Accept", "application/json")[httpMethodNock(method)]("/foo") - .reply( - 200, - { - foo: "bar", - }, - ); + .reply(200, { + foo: "bar", + }); diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap b/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap index 63e138938cb..05259d257eb 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: inline-merge.js --- # Input @@ -31,8 +32,8 @@ _.flatMap(this.visibilityHandlers, (fn) => fn()) Object.keys( availableLocales({ test: true, - },), + }), ).forEach((locale) => { // ... -},); +}); diff --git a/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap b/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap index efd7cfd1779..d7cb070eb9f 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: function.js --- # Input @@ -66,7 +67,7 @@ function foo() { useEffect(() => { setRef(); - },); + }); return ref; } diff --git a/crates/rome_js_formatter/tests/specs/js/module/object/property_object_member.js.snap b/crates/rome_js_formatter/tests/specs/js/module/object/property_object_member.js.snap index 46667b7563b..d94be9d4026 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/object/property_object_member.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/object/property_object_member.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: property_object_member.js --- # Input @@ -218,12 +219,12 @@ const fluidObject = { created: "09/01/2017 17:25", }, ], - render: withGraphQLQuery( - "node(1234567890){image{uri}}", - function (container, data) { - return "image"; - }, - ), + render: withGraphQLQuery("node(1234567890){image{uri}}", function ( + container, + data, + ) { + return "image"; + }), loadNext: (stateIsOK && hasNext) || { skipNext: true, }, diff --git a/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap b/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap index 6b58cd3ea2d..acbc729b24d 100644 --- a/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap +++ b/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 expression: attributes.jsx --- # Input @@ -71,16 +72,13 @@ Quote style: Double Quotes />; formatResult(testResult, formatter, reporter), ); -it( - "mocks regexp instances", - () => { - expect( - () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), - ).not.toThrow(); - }, -); +it("mocks regexp instances", () => { + expect( + () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), + ).not.toThrow(); +}); expect(() => asyncRequest({ url: "/test-endpoint" })).toThrowError( /Required parameter/, @@ -106,6 +104,6 @@ promise.then( # Lines exceeding max width of 80 characters ``` - 52: result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", + 49: result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/parent.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/parent.js.snap index 84acd94f2d0..d504cd97ca7 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/parent.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/parent.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: parent.js --- # Input @@ -18,15 +19,14 @@ runtimeAgent.getProperties( # Output ```js -runtimeAgent.getProperties( - objectId, - false, // ownProperties - false, // accessorPropertiesOnly - false, // generatePreview - (error, properties, internalProperties) => { - return 1; - }, -); +runtimeAgent.getProperties(objectId, false, false, false, ( + // ownProperties // accessorPropertiesOnly // generatePreview + error, + properties, + internalProperties, +) => { + return 1; +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap index 1d63a77c60b..f24029d1de5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap @@ -34,18 +34,13 @@ db.collection('indexOptionDefault').createIndex({ a: 1 }, { # Output ```js //https://github.com/prettier/prettier/issues/3002 -beep.boop().baz( - "foo", - { - some: { - thing: { - nested: true, - }, +beep.boop().baz("foo", { + some: { + thing: { + nested: true, }, }, - { another: { thing: true } }, - () => {}, -); +}, { another: { thing: true } }, () => {}); //https://github.com/prettier/prettier/issues/2984 db.collection("indexOptionDefault").createIndex( diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap index 7e9692509ce..e42a54de330 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: array.js --- # Input @@ -73,20 +74,11 @@ class A { } } -promise.then( - ( - [ - firstResult, - secondResult, - thirdResult, - fourthResult, - fifthResult, - ...rest - ], - ) => { - return rest; - }, -); +promise.then(( + [firstResult, secondResult, thirdResult, fourthResult, fifthResult, ...rest], +) => { + return rest; +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/gobject_connect.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/gobject_connect.js.snap index 1566de90161..56b0257987b 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/gobject_connect.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/gobject_connect.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: gobject_connect.js --- # Input @@ -21,13 +22,10 @@ app.connect( # Output ```js button.connect("clicked", () => doSomething()); -app.connect( - "activate", - async () => { - await data.load(); - win.show_all(); - }, -); +app.connect("activate", async () => { + await data.load(); + win.show_all(); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/mongo_connect.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/mongo_connect.js.snap index 52e8c378ff5..331004ef667 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/mongo_connect.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/mongo_connect.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: mongo_connect.js --- # Input @@ -16,13 +17,10 @@ MongoClient.connect( # Output ```js -MongoClient.connect( - "mongodb://localhost:27017/posts", - (err, db) => { - assert.equal(null, err); - db.close(); - }, -); +MongoClient.connect("mongodb://localhost:27017/posts", (err, db) => { + assert.equal(null, err); + db.close(); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/dangling-comment-in-arrow-function.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/dangling-comment-in-arrow-function.js.snap index 704f78fb703..42017259d56 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/dangling-comment-in-arrow-function.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/dangling-comment-in-arrow-function.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: dangling-comment-in-arrow-function.js --- # Input @@ -14,11 +15,9 @@ foo( # Output ```js -foo( - ( - // foo - ) => {}, -); +foo(( + // foo +) => {}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap index f9aca588665..513f43d0622 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap @@ -296,13 +296,10 @@ window.FooClient.setVars({ authorizationToken: data.token, },).initVerify("foo_container"); -it( - "gets triggered by mouseenter", - () => { - const wrapper = shallow(); - wrapper.dive().find(Button).prop(); - }, -); +it("gets triggered by mouseenter", () => { + const wrapper = shallow(); + wrapper.dive().find(Button).prop(); +}); const a1 = x.a(true).b(null).c(123); const a2 = x.d("").e(``).f(g); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap index c3434470a6e..0fc7f6a0e40 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap @@ -284,12 +284,9 @@ foo.apply( [1, 2], ); -bar.on( - "readable", - () => { - doStuff(); - }, -); +bar.on("readable", () => { + doStuff(); +}); foo( ["A, B"], diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/template-literals/expressions.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/template-literals/expressions.js.snap index 593329529bb..ec8694a331d 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/template-literals/expressions.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/template-literals/expressions.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: expressions.js --- # Input @@ -109,15 +110,12 @@ console.log( `\nApparently jetbrains changed the release artifact for ${app.name}@${app.jetbrains.version}.\n`, ); -descirbe( - "something", - () => { - test( - `{pass: false} expect(${small}).toBeGreaterThanOrEqual(${big})`, - () => {}, - ); - }, -); +descirbe("something", () => { + test( + `{pass: false} expect(${small}).toBeGreaterThanOrEqual(${big})`, + () => {}, + ); +}); throw new Error( `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`, @@ -137,6 +135,6 @@ throw new Error( 34: return `${process.env.OPENID_URL}/something/something/something?${Object.keys( 44: `Trying update appcast for ${app.name} (${app.cask.appcast}) -> (${app.cask.appcastGenerated})`, 52: `\nApparently jetbrains changed the release artifact for ${app.name}@${app.jetbrains.version}.\n`, - 66: `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`, + 63: `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`, ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/jest-each.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/jest-each.js.snap index 23cd5435328..7a82d8d40b8 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/jest-each.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/jest-each.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: jest-each.js --- # Input @@ -76,31 +77,19 @@ a|b|expected ${11} | ${1}|${222} ${1 - 1}|${2 + 2}|${3333} ${2 + 1 + 2}|${1111}|${3} -`( - "$a + $b", - ({ a, b, expected }) => { - test( - `returns ${expected}`, - () => { - expect(a + b).toBe(expected); - }, - ); - - test( - `returned value not be greater than ${expected}`, - () => { - expect(a + b).not.toBeGreaterThan(expected); - }, - ); - - test( - `returned value not be less than ${expected}`, - () => { - expect(a + b).not.toBeLessThan(expected); - }, - ); - }, -); +`("$a + $b", ({ a, b, expected }) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test(`returned value not be greater than ${expected}`, () => { + expect(a + b).not.toBeGreaterThan(expected); + }); + + test(`returned value not be less than ${expected}`, () => { + expect(a + b).not.toBeLessThan(expected); + }); +}); describe.only.each` a|b|expected @@ -130,26 +119,23 @@ ${11111111111} | ${a() ${1} | ${2} | ${3} ${2} | ${1} | ${3}`; -describe.each([1, 2, 3])( - "test", - (a) => { - expect(a).toBe(a); - }, -); +describe.each([1, 2, 3])("test", (a) => { + expect(a).toBe(a); +}); -test.only.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( - ".add(%i, %i)", - (a, b, expected) => { - expect(a + b).toBe(expected); - }, -); +test.only.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])(".add(%i, %i)", ( + a, + b, + expected, +) => { + expect(a + b).toBe(expected); +}); -test.each([{ a: "1", b: 1 }, { a: "2", b: 2 }, { a: "3", b: 3 }])( - "test", - ({ a, b }) => { - expect(Number(a)).toBe(b); - }, -); +test.each([{ a: "1", b: 1 }, { a: "2", b: 2 }, { a: "3", b: 3 }])("test", ( + { a, b }, +) => { + expect(Number(a)).toBe(b); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/test_declarations.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/test_declarations.js.snap index d5c8efc56a1..b5bf6118e3e 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/test_declarations.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/test_declarations.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: test_declarations.js --- # Input @@ -215,15 +216,12 @@ it( }, ); -it( - `handles +it(`handles some newlines - does something really long and complicated so I have to write a very long name for the test`, - () => { - console.log("hello!"); - }, -); + does something really long and complicated so I have to write a very long name for the test`, () => { + console.log("hello!"); +}); test( "does something really long and complicated so I have to write a very long name for the test", @@ -242,24 +240,18 @@ test( describe( "does something really long and complicated so I have to write a very long name for the describe block", () => { - it( - "an example test", - (done) => { - console.log("hello!"); - }, - ); + it("an example test", (done) => { + console.log("hello!"); + }); }, ); describe( `does something really long and complicated so I have to write a very long name for the describe block`, () => { - it( - `an example test`, - (done) => { - console.log("hello!"); - }, - ); + it(`an example test`, (done) => { + console.log("hello!"); + }); }, ); @@ -503,48 +495,48 @@ it( 25: "does something really long and complicated so I have to write a very long name for the test", 32: `does something really long and complicated so I have to write a very long name for the test`, 39: `{foo + bar} does something really long and complicated so I have to write a very long name for the test`, - 49: does something really long and complicated so I have to write a very long name for the test`, - 56: "does something really long and complicated so I have to write a very long name for the test", - 63: `does something really long and complicated so I have to write a very long name for the test`, - 70: "does something really long and complicated so I have to write a very long name for the describe block", - 82: `does something really long and complicated so I have to write a very long name for the describe block`, - 94: "does something really long and complicated so I have to write a very long name for the describe block", - 99: "does something really long and complicated so I have to write a very long name for the describe block", - 104: `does something really long and complicated so I have to write a very long name for the test`, - 109: `does something really long and complicated so I have to write a very long name for the test`, - 114: "does something really long and complicated so I have to write a very long name for the describe block", - 119: "does something really long and complicated so I have to write a very long name for the describe block", - 124: "does something really long and complicated so I have to write a very long name for the test", - 131: `does something really long and complicated so I have to write a very long name for the test`, - 138: `does something really long and complicated so I have to write a very long name for the test`, - 143: `does something really long and complicated so I have to write a very long name for the test`, - 148: `does something really long and complicated so I have to write a very long name for the test`, - 153: "does something really long and complicated so I have to write a very long name for the describe block", - 158: "does something really long and complicated so I have to write a very long name for the describe block", - 163: `does something really long and complicated so I have to write a very long name for the test`, - 168: "does something really long and complicated so I have to write a very long name for the test", - 173: "does something really long and complicated so I have to write a very long name for the test", - 178: `does something really long and complicated so I have to write a very long name for the test`, - 183: "does something really long and complicated so I have to write a very long name for the test", - 188: `does something really long and complicated so I have to write a very long name for the test`, - 193: "does something really long and complicated so I have to write a very long name for the test", - 198: `does something really long and complicated so I have to write a very long name for the test`, - 203: "does something really long and complicated so I have to write a very long name for the test", - 208: `does something really long and complicated so I have to write a very long name for the test`, - 213: "does something really long and complicated so I have to write a very long name for the testThis is a very", - 218: `does something really long and complicated so I have to write a very long name for the testThis is a very`, - 223: "does something really long and complicated so I have to write a very long name for the test", - 228: `does something really long and complicated so I have to write a very long name for the test`, - 233: "does something really long and complicated so I have to write a very long name for the test", - 238: `does something really long and complicated so I have to write a very long name for the test`, - 245: "does something really long and complicated so I have to write a very long name for the test", - 253: "does something really long and complicated so I have to write a very long name for the test", - 260: "does something really long and complicated so I have to write a very long name for the test", - 267: "does something really long and complicated so I have to write a very long name for the test", - 272: "does something really long and complicated so I have to write a very long name for the test", - 277: "does something really long and complicated so I have to write a very long name for the testThis is a very", - 282: "does something really long and complicated so I have to write a very long name for the test", - 287: "does something really long and complicated so I have to write a very long name for the test", - 297: does something really long and complicated so I have to write a very long name for the test`, + 48: does something really long and complicated so I have to write a very long name for the test`, () => { + 53: "does something really long and complicated so I have to write a very long name for the test", + 60: `does something really long and complicated so I have to write a very long name for the test`, + 67: "does something really long and complicated so I have to write a very long name for the describe block", + 76: `does something really long and complicated so I have to write a very long name for the describe block`, + 85: "does something really long and complicated so I have to write a very long name for the describe block", + 90: "does something really long and complicated so I have to write a very long name for the describe block", + 95: `does something really long and complicated so I have to write a very long name for the test`, + 100: `does something really long and complicated so I have to write a very long name for the test`, + 105: "does something really long and complicated so I have to write a very long name for the describe block", + 110: "does something really long and complicated so I have to write a very long name for the describe block", + 115: "does something really long and complicated so I have to write a very long name for the test", + 122: `does something really long and complicated so I have to write a very long name for the test`, + 129: `does something really long and complicated so I have to write a very long name for the test`, + 134: `does something really long and complicated so I have to write a very long name for the test`, + 139: `does something really long and complicated so I have to write a very long name for the test`, + 144: "does something really long and complicated so I have to write a very long name for the describe block", + 149: "does something really long and complicated so I have to write a very long name for the describe block", + 154: `does something really long and complicated so I have to write a very long name for the test`, + 159: "does something really long and complicated so I have to write a very long name for the test", + 164: "does something really long and complicated so I have to write a very long name for the test", + 169: `does something really long and complicated so I have to write a very long name for the test`, + 174: "does something really long and complicated so I have to write a very long name for the test", + 179: `does something really long and complicated so I have to write a very long name for the test`, + 184: "does something really long and complicated so I have to write a very long name for the test", + 189: `does something really long and complicated so I have to write a very long name for the test`, + 194: "does something really long and complicated so I have to write a very long name for the test", + 199: `does something really long and complicated so I have to write a very long name for the test`, + 204: "does something really long and complicated so I have to write a very long name for the testThis is a very", + 209: `does something really long and complicated so I have to write a very long name for the testThis is a very`, + 214: "does something really long and complicated so I have to write a very long name for the test", + 219: `does something really long and complicated so I have to write a very long name for the test`, + 224: "does something really long and complicated so I have to write a very long name for the test", + 229: `does something really long and complicated so I have to write a very long name for the test`, + 236: "does something really long and complicated so I have to write a very long name for the test", + 244: "does something really long and complicated so I have to write a very long name for the test", + 251: "does something really long and complicated so I have to write a very long name for the test", + 258: "does something really long and complicated so I have to write a very long name for the test", + 263: "does something really long and complicated so I have to write a very long name for the test", + 268: "does something really long and complicated so I have to write a very long name for the testThis is a very", + 273: "does something really long and complicated so I have to write a very long name for the test", + 278: "does something really long and complicated so I have to write a very long name for the test", + 288: does something really long and complicated so I have to write a very long name for the test`, ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/function-calls.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/function-calls.js.snap index 1d07dd5e965..fa6af11eda8 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/function-calls.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/function-calls.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: function-calls.js --- # Input @@ -43,12 +44,9 @@ a( a("long-nested-value", "long-nested-value2", "long-nested-value3"), ); -a.b().c( - { - d, - }, - () => {}, -); +a.b().c({ + d, +}, () => {}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/arrow_regression.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/arrow_regression.ts.snap index e7c500654fb..8ceca727ed5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/arrow_regression.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/arrow_regression.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: arrow_regression.ts --- # Input @@ -30,12 +31,9 @@ const bar = (...varargs: any[]) => { const foo = (x: string): void => (bar(x, () => {}, () => {})); -app.get( - "/", - (req, res): void => { - res.send("Hello world"); - }, -); +app.get("/", (req, res): void => { + res.send("Hello world"); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment2.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment2.ts.snap index 4f6446c0d57..c03ed1255b3 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment2.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment2.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: assignment2.ts --- # Input @@ -44,17 +45,14 @@ const defaultMaskGetter = $parse(attrs[directiveName]) as ( (this.configuration as any) = (this.editor as any) = (this.editorBody as any) = undefined; -angular.module("foo").directive( - "formIsolator", - () => { - return { - name: "form", - controller: class FormIsolatorController { - $addControl = angular.noop; - } as ng.IControllerConstructor, - }; - }, -); +angular.module("foo").directive("formIsolator", () => { + return { + name: "form", + controller: class FormIsolatorController { + $addControl = angular.noop; + } as ng.IControllerConstructor, + }; +}); (this.selectorElem as any) = this.multiselectWidget = this.initialValues = undefined; diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/custom/typeParameters/variables.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/custom/typeParameters/variables.ts.snap index 472f8da7539..a929ed9539e 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/custom/typeParameters/variables.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/custom/typeParameters/variables.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: variables.ts --- # Input @@ -54,11 +55,9 @@ const baaaaaaaaaaaaaaaar: SomeThing< const isAnySuccessfulAttempt$: Observable< boolean > = this._quizService.isAnySuccessfulAttempt$().pipe( - tap( - (isAnySuccessfulAttempt: boolean) => { - this.isAnySuccessfulAttempt = isAnySuccessfulAttempt; - }, - ), + tap((isAnySuccessfulAttempt: boolean) => { + this.isAnySuccessfulAttempt = isAnySuccessfulAttempt; + }), ); const isAnySuccessfulAttempt2$: Observable< boolean diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls-with-comments.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls-with-comments.ts.snap index 14bfbe6882e..0c32c65401b 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls-with-comments.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls-with-comments.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: pipe-function-calls-with-comments.ts --- # Input @@ -81,18 +82,16 @@ expression: pipe-function-calls-with-comments.ts ), )() .then(messageResponse(logger, msg)) - .catch( - (err: Error) => { - logger.error( - pipe( - // add a descriptive comment here - O.fromNullable(err.stack), - O.getOrElse(constant(err.message)), - ), - ); - process.exit(1); - }, - ); + .catch((err: Error) => { + logger.error( + pipe( + // add a descriptive comment here + O.fromNullable(err.stack), + O.getOrElse(constant(err.message)), + ), + ); + process.exit(1); + }); pipe( // add a descriptive comment here diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls.ts.snap index 53ce5dc5f8b..1df135ef1d5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: pipe-function-calls.ts --- # Input @@ -37,14 +38,12 @@ expression: pipe-function-calls.ts TE.chain(flow(publishServiceEvent(analytics), TE.mapLeft(nackFromError))), )() .then(messageResponse(logger, msg)) - .catch( - (err: Error) => { - logger.error( - pipe(O.fromNullable(err.stack), O.getOrElse(constant(err.message))), - ); - process.exit(1); - }, - ); + .catch((err: Error) => { + logger.error( + pipe(O.fromNullable(err.stack), O.getOrElse(constant(err.message))), + ); + process.exit(1); + }); })(); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/break.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/break.ts.snap index 58f9ee5ddf4..dfc73dcbce5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/break.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/break.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: break.ts --- # Input @@ -20,22 +21,18 @@ export default class AddAssetHtmlPlugin { ```js export default class AddAssetHtmlPlugin { apply(compiler: WebpackCompilerType) { - compiler.plugin( - "compilation", - (compilation: WebpackCompilationType) => { - compilation.plugin( - "html-webpack-plugin-before-html", - (callback: Callback) => { - addAllAssetsToCompilation( - this.assets, - compilation, - htmlPluginData, - callback, - ); - }, + compiler.plugin("compilation", (compilation: WebpackCompilationType) => { + compilation.plugin("html-webpack-plugin-before-html", ( + callback: Callback, + ) => { + addAllAssetsToCompilation( + this.assets, + compilation, + htmlPluginData, + callback, ); - }, - ); + }); + }); } } diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/method-chain/comment.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/method-chain/comment.ts.snap index a99f21f46fa..a09177d4015 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/method-chain/comment.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/method-chain/comment.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: comment.ts --- # Input @@ -20,18 +21,16 @@ this.firebase.object(`/shops/${shopLocation.shop}`) ```js this.firebase.object(`/shops/${shopLocation.shop}`) // keep distance info -.first( - ( - shop: ShopQueryResult, - index: number, - source: Observable, - ): any => { - // add distance to result - const s = shop; - s.distance = shopLocation.distance; - return s; - }, -); +.first(( + shop: ShopQueryResult, + index: number, + source: Observable, +): any => { + // add distance to result + const s = shop; + s.distance = shopLocation.distance; + return s; +}); ``` From 8df0fbf8319251225c98228629015f834eed48e8 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Tue, 14 Jun 2022 17:21:57 -0300 Subject: [PATCH 09/16] chore: snapshots --- .../js/arrays/numbers-in-args.js.snap | 5 +- .../js/assignment/call-with-template.js.snap | 5 +- .../prettier/js/assignment/issue-6922.js.snap | 8 +- .../prettier/js/assignment/lone-arg.js.snap | 3 +- .../js/binary-expressions/short-right.js.snap | 3 +- .../prettier/js/break-calls/break.js.snap | 41 ++--- .../prettier/js/break-calls/react.js.snap | 174 +++++++++--------- .../prettier/js/break-calls/reduce.js.snap | 19 +- .../non-casts.js.snap | 7 +- .../prettier/js/comments/call_comment.js.snap | 10 +- .../js/comments/dangling_array.js.snap | 3 +- .../js/comments/dynamic_imports.js.snap | 4 +- .../specs/prettier/js/comments/issues.js.snap | 7 +- .../js/first-argument-expansion/test.js.snap | 131 +++++-------- .../function_expression.js.snap | 25 ++- .../pipe-function-calls-with-comments.js.snap | 3 +- .../pipe-function-calls.js.snap | 3 +- .../break-parent.js.snap | 14 +- .../last-argument-expansion/edge_case.js.snap | 83 ++++----- .../empty-lines.js.snap | 3 +- .../empty-object.js.snap | 5 +- .../function-expression-issue-2239.js.snap | 12 +- .../function-expression.js.snap | 29 ++- .../number-only-array.js.snap | 18 +- .../specs/prettier/js/member/expand.js.snap | 11 +- .../js/method-chain/bracket_0.js.snap | 3 +- .../js/method-chain/break-last-call.js.snap | 128 +++++++------ .../prettier/js/method-chain/comment.js.snap | 5 +- .../js/method-chain/computed-merge.js.snap | 5 +- .../prettier/js/method-chain/computed.js.snap | 10 +- .../js/method-chain/first_long.js.snap | 9 +- .../js/method-chain/inline_merge.js.snap | 5 +- .../js/method-chain/issue-4125.js.snap | 17 +- .../js/method-chain/multiple-members.js.snap | 47 +++-- .../js/method-chain/object-literal.js.snap | 5 +- .../multiparser-graphql/graphql-tag.js.snap | 3 +- .../with-member-expression.js.snap | 3 +- .../js/object-prop-break-in/test.js.snap | 15 +- .../specs/prettier/js/objects/range.js.snap | 21 +-- .../js/performance/nested-real.js.snap | 155 ++++++++-------- .../prettier/js/performance/nested.js.snap | 29 +-- .../js/preserve-line/argument-list.js.snap | 46 ++--- .../js/require-amd/named-amd-module.js.snap | 11 +- .../prettier/js/require-amd/require.js.snap | 91 +++++---- .../specs/prettier/js/return/comment.js.snap | 3 +- .../prettier/js/template/graphql.js.snap | 9 +- .../specs/prettier/js/template/indent.js.snap | 3 +- .../prettier/js/ternaries/indent.js.snap | 7 +- .../test-declarations/angular_async.js.snap | 9 +- .../angular_fakeAsync.js.snap | 9 +- .../angular_waitForAsync.js.snap | 9 +- .../angularjs_inject.js.snap | 11 +- .../js/throw_statement/comment.js.snap | 3 +- .../prettier/js/trailing-comma/jsx.js.snap | 3 +- .../trailing_whitespace.js.snap | 21 +-- .../js/variable_declarator/multiple.js.snap | 10 +- .../argument_expansion.ts.snap | 87 ++++----- .../specs/prettier/typescript/as/as.ts.snap | 17 +- .../prettier/typescript/as/assignment.ts.snap | 25 +-- .../assignment/issue-10848.tsx.snap | 9 +- .../prettier/typescript/cast/hug-args.ts.snap | 31 ++-- .../prettier/typescript/classes/break.ts.snap | 3 +- .../last-argument-expansion/edge_case.ts.snap | 9 +- .../typeparams/class-method.ts.snap | 115 ++++++------ 64 files changed, 761 insertions(+), 866 deletions(-) diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap index d164de7cdd8..99215dc22e8 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: numbers-in-args.js --- # Input @@ -24,7 +25,7 @@ expect(bifornCringerMoshedPerplexSawder.getLongArrayOfNumbers()).toEqual( ```js expect(bifornCringerMoshedPerplexSawder.getArrayOfNumbers()).toEqual([ 1, 2, 3, 4, 5, -],); +]); expect(bifornCringerMoshedPerplexSawder.getLongArrayOfNumbers()).toEqual([ 66, 57, 45, 47, 33, 53, 82, 81, 76, 78, 10, 78, 15, 98, 24, 29, 32, 27, 28, @@ -33,7 +34,7 @@ expect(bifornCringerMoshedPerplexSawder.getLongArrayOfNumbers()).toEqual([ 83, 26, 34, 93, 29, 66, 88, 49, 33, 49, 73, 9, 81, 4, 36, 5, 14, 43, 31, 86, 27, 39, 75, 98, 99, 55, 19, 39, 21, 85, 86, 46, 82, 11, 44, 48, 77, 35, 48, 78, 97, -],); +]); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap index 14befb74650..d659544eb15 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: call-with-template.js --- # Input @@ -25,11 +26,11 @@ const result = template( `, )({ SOME_VAR: value, -},); +}); const output = template(`function f() %%A%%`)({ A: t.blockStatement([]), -},); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap index 1963aa1488b..31d488638c2 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: issue-6922.js --- # Input @@ -44,10 +45,9 @@ async function f() { return { data, status }; } -const data1 = request.delete( - "----------------------------------------------", - { validateStatus: () => true }, -); +const data1 = request.delete("----------------------------------------------", { + validateStatus: () => true, +}); const data2 = request.delete( "----------------------------------------------x", diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap index a39c032c38b..102f6546bb2 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: lone-arg.js --- # Input @@ -33,7 +34,7 @@ let vgChannel = pointPositionDefaultRef({ model, defaultPos, channel, -},)(); +})(); let vgChannel2 = pointPositionDefaultRef({ model, defaultPos, channel })(); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap index 32acb9aec41..79e53cfe781 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: short-right.js --- # Input @@ -44,7 +45,7 @@ const isPartOfPackageJSON = dependenciesArray.indexOf( defaultContent.filter((defaultLocale) => { // ... -},)[0] || null; +})[0] || null; ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap index 4f63097794e..bd172cf0d4b 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: break.js --- # Input @@ -56,26 +57,24 @@ h( f( g(() => { a; - },), + }), ), ); -deepCopyAndAsyncMapLeavesA( - { source: sourceValue, destination: destination[sourceKey] }, - { valueMapper, overwriteExistingKeys }, -); +deepCopyAndAsyncMapLeavesA({ + source: sourceValue, + destination: destination[sourceKey], +}, { valueMapper, overwriteExistingKeys }); -deepCopyAndAsyncMapLeavesB( - 1337, - { source: sourceValue, destination: destination[sourceKey] }, - { valueMapper, overwriteExistingKeys }, -); +deepCopyAndAsyncMapLeavesB(1337, { + source: sourceValue, + destination: destination[sourceKey], +}, { valueMapper, overwriteExistingKeys }); -deepCopyAndAsyncMapLeavesC( - { source: sourceValue, destination: destination[sourceKey] }, - 1337, - { valueMapper, overwriteExistingKeys }, -); +deepCopyAndAsyncMapLeavesC({ + source: sourceValue, + destination: destination[sourceKey], +}, 1337, { valueMapper, overwriteExistingKeys }); function someFunction(url) { return get(url).then( @@ -93,12 +92,12 @@ expect( new LongLongLongLongLongRange([0, 0], [0, 0]), ).toEqualAtomLongLongLongLongRange(new LongLongLongRange([0, 0], [0, 0])); -["red", "white", "blue", "black", "hotpink", "rebeccapurple"].reduce( - (allColors, color) => { - return allColors.concat(color); - }, - [], -); +["red", "white", "blue", "black", "hotpink", "rebeccapurple"].reduce(( + allColors, + color, +) => { + return allColors.concat(color); +}, []); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/react.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/react.js.snap index 3545b0b627b..db948133c5a 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/react.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/react.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: react.js --- # Input @@ -74,117 +75,108 @@ function Comp5() { # Output ```js function helloWorld() { - useEffect( - () => { - // do something - }, - [props.value], - ); - useEffect( - () => { - // do something - }, - [ - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - ], - ); + useEffect(() => { + // do something + }, [props.value]); + useEffect(() => { + // do something + }, [ + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + ]); } function helloWorldWithReact() { - React.useEffect( - () => { - // do something - }, - [props.value], - ); - React.useEffect( - () => { - // do something - }, - [ - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - ], - ); + React.useEffect(() => { + // do something + }, [props.value]); + React.useEffect(() => { + // do something + }, [ + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + ]); } function MyComponent(props) { - useEffect( - () => { - console.log("some code", props.foo); - }, - // We need to disable the eslint warning here, - // because of some complicated reason. - // eslint-disable line react-hooks/exhaustive-deps - [], - ); + useEffect(() => { + console.log("some code", props.foo); + }, + // We need to disable the eslint warning here, + // because of some complicated reason. + // eslint-disable line react-hooks/exhaustive-deps + []); return null; } function Comp1() { - const { firstName, lastName } = useMemo( - () => parseFullName(fullName), - [fullName], - ); + const { firstName, lastName } = useMemo(() => parseFullName(fullName), [ + fullName, + ]); } function Comp2() { - const { firstName, lastName } = useMemo( - () => func(), - [ - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - props.value, - ], - ); + const { firstName, lastName } = useMemo(() => func(), [ + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + props.value, + ]); } function Comp3() { - const { firstName, lastName } = useMemo( - (aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii, jjj, kkk) => - func(aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii, jjj, kkk), - [foo, bar, baz], - ); + const { firstName, lastName } = useMemo(( + aaa, + bbb, + ccc, + ddd, + eee, + fff, + ggg, + hhh, + iii, + jjj, + kkk, + ) => func(aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii, jjj, kkk), [ + foo, + bar, + baz, + ]); } function Comp4() { - const { firstName, lastName } = useMemo( - () => - (foo && bar && baz) || - baz || - (foo && baz(foo) + bar(foo) + foo && bar && baz) || - baz || - (foo && baz(foo) + bar(foo)), - [foo, bar, baz], - ); + const { firstName, lastName } = useMemo(() => + (foo && bar && baz) || + baz || + (foo && baz(foo) + bar(foo) + foo && bar && baz) || + baz || + (foo && baz(foo) + bar(foo)), [foo, bar, baz]); } function Comp5() { diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap index 5577f5127e8..3cdca9f62ed 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: reduce.js --- # Input @@ -18,15 +19,17 @@ const [ first2 ] = array.reduce( # Output ```js -const [first1] = array.reduce( - () => [accumulator, element, accumulator, element], - [fullName], -); +const [first1] = array.reduce(() => [ + accumulator, + element, + accumulator, + element, +], [fullName]); -const [first2] = array.reduce( - (accumulator, element) => [accumulator, element], - [fullName], -); +const [first2] = array.reduce((accumulator, element) => [ + accumulator, + element, +], [fullName]); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap index 01cf7ca9491..a988a1d708c 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: non-casts.js --- # Input @@ -31,18 +32,18 @@ const w1 = /** @typefoo Foo */ (value); z((x) => { (foo)((bar)(2 + (3))); return (1); -},); +}); /** @type { } */ z((x) => { (foo)((bar)(2 + (3))); return (1); -},); +}); /** @type {number} */ let q = z((x) => { return (1); -},); +}); const w1 = /** @typefoo Foo */ (value); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap index 36e6b6315d2..2676bfd9b80 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: call_comment.js --- # Input @@ -23,20 +24,17 @@ render?.( // Warm any cache # Output ```js -render( - // Warm any cache +render( // Warm any cache , container, ); -React.render( - // Warm any cache +React.render( // Warm any cache , container, ); -render?.( - // Warm any cache +render?.( // Warm any cache , container, ); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap index ea6d5e95df7..4c39bf66506 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: dangling_array.js --- # Input @@ -16,7 +17,7 @@ expect(() => {}).toTriggerReadyStateChanges([ ```js expect(() => {}).toTriggerReadyStateChanges([ // Nothing. -],); +]); [1 /* first comment */, 2 /* second comment */, 3]; diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap index 77aedf41d84..c46bcb08988 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: dynamic_imports.js --- # Input @@ -39,8 +40,7 @@ import("something" /* Hello */ + "else"); import( /* Hello */ "something", - /* Hello */ -); +/* Hello */ ); wrap(import(/* Hello */ "something")); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/issues.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/issues.js.snap index 43a044328c0..8df29ece356 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/issues.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/issues.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: issues.js --- # Input @@ -88,7 +89,7 @@ this.call(a, /* comment */ b); throw new ProcessSystemError({ code: acc.error.code, // Alias of errno originalError: acc.error, // Just in case. -},); +}); // Missing one level of indentation because of the comment const rootEpic = (actions, store) => ( @@ -97,7 +98,7 @@ const rootEpic = (actions, store) => ( .catch((err, stream) => { getLogger().error(err); return stream; - },) + }) ); // optional trailing comma gets moved all the way to the beginning @@ -149,7 +150,7 @@ const result = asyncExecute("non_existing_command", /* args */ []); // The closing paren is printed on the same line as the comment foo( {}, - // Hi +// Hi ); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap index 03ec813da40..3cd4a50a6d7 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: test.js --- # Input @@ -122,68 +123,41 @@ func((args) => { # Output ```js -setTimeout( - function () { - thing(); - }, - 500, -); +setTimeout(function () { + thing(); +}, 500); -["a", "b", "c"].reduce( - function (item, thing) { - return thing + " " + item; - }, - "letters:", -); +["a", "b", "c"].reduce(function (item, thing) { + return thing + " " + item; +}, "letters:"); -func( - () => { - thing(); - }, - identifier, -); +func(() => { + thing(); +}, identifier); -func( - function () { - thing(); - }, - this.props.timeout * 1000, -); +func(function () { + thing(); +}, this.props.timeout * 1000); -func( - (that) => { - thing(); - }, - this.props.getTimeout(), -); +func((that) => { + thing(); +}, this.props.getTimeout()); -func( - () => { - thing(); - }, - true, -); +func(() => { + thing(); +}, true); -func( - () => { - thing(); - }, - null, -); +func(() => { + thing(); +}, null); -func( - () => { - thing(); - }, - undefined, -); +func(() => { + thing(); +}, undefined); -func( - () => { - thing(); - }, - /regex.*?/, -); +func(() => { + thing(); +}, /regex.*?/); func( () => { @@ -235,25 +209,21 @@ compose( (b) => b * b, ); -somthing.reduce( - function (item, thing) { - return thing.blah = item; - }, {}, -); +somthing.reduce(function (item, thing) { + return thing.blah = item; +}, {}); -somthing.reduce( - function (item, thing) { - return thing.push(item); - }, - [], -); +somthing.reduce(function (item, thing) { + return thing.push(item); +}, []); -reallyLongLongLongLongLongLongLongLongLongLongLongLongLongLongMethod( - (f, g, h) => { - return f.pop(); - }, - true, -); +reallyLongLongLongLongLongLongLongLongLongLongLongLongLongLongMethod(( + f, + g, + h, +) => { + return f.pop(); +}, true); // Don't do the rest of these @@ -265,11 +235,9 @@ func( false, ); -func( - () => { - thing(); - }, { yes: true, cats: 5 }, -); +func(() => { + thing(); +}, { yes: true, cats: 5 }); compose( (a) => { @@ -300,13 +268,10 @@ setTimeout( 500, ); -setTimeout( - /* blip */ - function () { - thing(); - }, - 500, -); +setTimeout( /* blip */ +function () { + thing(); +}, 500); func( (args) => { diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap index f24029d1de5..e38fae452ae 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: function_expression.js --- # Input @@ -43,21 +44,17 @@ beep.boop().baz("foo", { }, { another: { thing: true } }, () => {}); //https://github.com/prettier/prettier/issues/2984 -db.collection("indexOptionDefault").createIndex( - { a: 1 }, - { - indexOptionDefaults: true, - w: 2, - wtimeout: 1000, - }, - function (err) { - test.equal(null, err); - test.deepEqual({ w: 2, wtimeout: 1000 }, commandResult.writeConcern); +db.collection("indexOptionDefault").createIndex({ a: 1 }, { + indexOptionDefaults: true, + w: 2, + wtimeout: 1000, +}, function (err) { + test.equal(null, err); + test.deepEqual({ w: 2, wtimeout: 1000 }, commandResult.writeConcern); - client.close(); - done(); - }, -); + client.close(); + done(); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap index 600fd71b6ec..74a5439291f 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: pipe-function-calls-with-comments.js --- # Input @@ -90,7 +91,7 @@ expression: pipe-function-calls-with-comments.js ), ); process.exit(1); - },); + }); pipe( // add a descriptive comment here diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap index 72604e08f2d..c8b1b6983e5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: pipe-function-calls.js --- # Input @@ -63,7 +64,7 @@ expression: pipe-function-calls.js pipe(O.fromNullable(err.stack), O.getOrElse(constant(err.message))), ); process.exit(1); - },); + }); pipe(Changelog.timestampOfFirstCommit([[commit]]), O.toUndefined); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap index 628ce1a01a2..a2374914523 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: break-parent.js --- # Input @@ -36,22 +37,19 @@ true ```js ({ processors: [ - require( - "autoprefixer", - { - browsers: ["> 1%", "last 2 versions", "ie >= 11", "Firefox ESR"], - }, - ), + require("autoprefixer", { + browsers: ["> 1%", "last 2 versions", "ie >= 11", "Firefox ESR"], + }), require("postcss-url")({ url: (url) => url.startsWith("/") || /^[a-z]+:/.test(url) ? url : `/static/${url}`, - },), + }), ], }); true ? test({ a: 1, -},) :
+ render: withGraphQLQuery("node(1234567890){image{uri}}", function ( + container, + data, + ) { + return ( +
- ); - }, - ), + ); + }), }, ]; -someReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReally.a([ - [], - // comment - [], -],); - -(function webpackUniversalModuleDefinition() {})( - this, - function (__WEBPACK_EXTERNAL_MODULE_85__, __WEBPACK_EXTERNAL_MODULE_115__) { - return /******/ (function (modules) { - // webpackBootstrap - /******/ - }) - /************************************************************************/ - /******/ ( - [ - /* 0 */ - /***/ function (module, exports, __webpack_require__) { - /***/ - }, - /* 1 */ - /***/ function (module, exports, __webpack_require__) { - /***/ - }, - /* 2 */ - /***/ function (module, exports, __webpack_require__) { - /***/ - }, - /******/ - ], - ); - }, +someReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReally.a( + [ + [], + // comment + [], + ], ); +(function webpackUniversalModuleDefinition() {})(this, function ( + __WEBPACK_EXTERNAL_MODULE_85__, + __WEBPACK_EXTERNAL_MODULE_115__, +) { + return /******/ (function (modules) { + // webpackBootstrap + /******/ + }) + /************************************************************************/ + /******/ ([ + /* 0 */ + /***/ function (module, exports, __webpack_require__) { + /***/ + }, + /* 1 */ + /***/ function (module, exports, __webpack_require__) { + /***/ + }, + /* 2 */ + /***/ function (module, exports, __webpack_require__) { + /***/ + }, + /******/ + ]); +}); + ``` # Lines exceeding max width of 80 characters ``` 2: SomethingVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLong, 5: SomethingVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLong: 1, - 31: someReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReally.a([ + 31: someReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReally.a( ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-lines.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-lines.js.snap index 1af01abb62e..35846405a3a 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-lines.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-lines.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: empty-lines.js --- # Input @@ -18,7 +19,7 @@ all_verylongcall_verylongcall_verylongcall_verylongcall_verylongcall( ```js all_verylongcall_verylongcall_verylongcall_verylongcall_verylongcall((a, b) => { console.log(); -},); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap index 87875c5c26c..71085470ccd 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: empty-object.js --- # Input @@ -44,7 +45,7 @@ func( func({ // comment -},); +}); func( {}, // comment @@ -52,7 +53,7 @@ func( func( {}, - // comment +// comment ); func( diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression-issue-2239.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression-issue-2239.js.snap index 1f081cc5b80..ca8989e0f0d 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression-issue-2239.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression-issue-2239.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: function-expression-issue-2239.js --- # Input @@ -12,12 +13,11 @@ someFunctionCallWithBigArgumentsAndACallback(thisArgumentIsQuiteLong, function(c # Output ```js -someFunctionCallWithBigArgumentsAndACallback( - thisArgumentIsQuiteLong, - function (cool) { - return cool; - }, -); +someFunctionCallWithBigArgumentsAndACallback(thisArgumentIsQuiteLong, function ( + cool, +) { + return cool; +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap index 443b4eb6bfd..077a29a63ec 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: function-expression.js --- # Input @@ -30,24 +31,22 @@ function mySagas2() { # Output ```js function* mySagas() { - yield effects.takeEvery( - rexpress.actionTypes.REQUEST_START, - function* ({ id }) { - console.log(id); - yield rexpress.actions(store).writeHead(id, 400); - yield rexpress.actions(store).end(id, "pong"); - console.log("pong"); - }, - ); + yield effects.takeEvery(rexpress.actionTypes.REQUEST_START, function* ( + { id }, + ) { + console.log(id); + yield rexpress.actions(store).writeHead(id, 400); + yield rexpress.actions(store).end(id, "pong"); + console.log("pong"); + }); } function mySagas2() { - return effects.takeEvery( - rexpress.actionTypes.REQUEST_START, - function ({ id }) { - console.log(id); - }, - ); + return effects.takeEvery(rexpress.actionTypes.REQUEST_START, function ( + { id }, + ) { + console.log(id); + }); } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/number-only-array.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/number-only-array.js.snap index d21d391bd87..afbc5d2f92d 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/number-only-array.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/number-only-array.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: number-only-array.js --- # Input @@ -13,17 +14,12 @@ instantiate(game, [ # Output ```js -instantiate( - game, - [ - transform([-0.7, 0.5, 0]), - render_colored_diffuse( - game.MaterialDiffuse, - game.Meshes["monkey_flat"], - [1, 1, 0.3, 1], - ), - ], -); +instantiate(game, [ + transform([-0.7, 0.5, 0]), + render_colored_diffuse(game.MaterialDiffuse, game.Meshes["monkey_flat"], [ + 1, 1, 0.3, 1, + ]), +]); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap index 4d0ed0155a8..de812e2ee08 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: expand.js --- # Input @@ -56,7 +57,7 @@ const promises = [ .catch((err) => { console.log(err); return null; - },), + }), redis.fetch(), other.fetch(), ]; @@ -70,7 +71,7 @@ const promises2 = [ .catch((err) => { console.log(err); return null; - },), + }), redis.fetch(), other.fetch(), ]; @@ -78,17 +79,17 @@ const promises2 = [ window.FooClient.setVars({ locale: getFooLocale({ page }), authorizationToken: data.token, -},).initVerify("foo_container"); +}).initVerify("foo_container"); window.something.FooClient.setVars({ locale: getFooLocale({ page }), authorizationToken: data.token, -},).initVerify("foo_container"); +}).initVerify("foo_container"); window.FooClient.something.setVars({ locale: getFooLocale({ page }), authorizationToken: data.token, -},).initVerify("foo_container"); +}).initVerify("foo_container"); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/bracket_0.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/bracket_0.js.snap index c5d1dde81cd..7788bf4ebf2 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/bracket_0.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/bracket_0.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: bracket_0.js --- # Input @@ -23,7 +24,7 @@ function a() { queryThenMutateDOM(() => { title = SomeThing.call(root, "someLongStringThatPushesThisTextReallyFar")[0]; - },); + }); } } diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap index 9b462eed91b..6c37a85cb30 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: break-last-call.js --- # Input @@ -51,81 +52,78 @@ export default (store) => { actionWith({ response, type: successType, - },), + }), ), (error) => next( actionWith({ type: failureType, error: error.message || "Something bad happened", - },), + }), ), ); }; -it( - "should group messages with same created time", - () => { - expect(groupMessages(messages).toJS()).toEqual({ - "11/01/2017 13:36": [ - { - message: "test", - messageType: "SMS", - status: "Unknown", - created: "11/01/2017 13:36", - }, - { - message: "test", - messageType: "Email", - status: "Unknown", - created: "11/01/2017 13:36", - }, - ], - "09/01/2017 17:25": [ - { - message: "te", - messageType: "SMS", - status: "Unknown", - created: "09/01/2017 17:25", - }, - { - message: "te", - messageType: "Email", - status: "Unknown", - created: "09/01/2017 17:25", - }, - ], - "11/01/2017 13:33": [ - { - message: "test", - messageType: "SMS", - status: "Unknown", - created: "11/01/2017 13:33", - }, - { - message: "test", - messageType: "Email", - status: "Unknown", - created: "11/01/2017 13:33", - }, - ], - "11/01/2017 13:37": [ - { - message: "test", - messageType: "SMS", - status: "Unknown", - created: "11/01/2017 13:37", - }, - { - message: "test", - messageType: "Email", - status: "Unknown", - created: "11/01/2017 13:37", - }, - ], - },); - }, -); +it("should group messages with same created time", () => { + expect(groupMessages(messages).toJS()).toEqual({ + "11/01/2017 13:36": [ + { + message: "test", + messageType: "SMS", + status: "Unknown", + created: "11/01/2017 13:36", + }, + { + message: "test", + messageType: "Email", + status: "Unknown", + created: "11/01/2017 13:36", + }, + ], + "09/01/2017 17:25": [ + { + message: "te", + messageType: "SMS", + status: "Unknown", + created: "09/01/2017 17:25", + }, + { + message: "te", + messageType: "Email", + status: "Unknown", + created: "09/01/2017 17:25", + }, + ], + "11/01/2017 13:33": [ + { + message: "test", + messageType: "SMS", + status: "Unknown", + created: "11/01/2017 13:33", + }, + { + message: "test", + messageType: "Email", + status: "Unknown", + created: "11/01/2017 13:33", + }, + ], + "11/01/2017 13:37": [ + { + message: "test", + messageType: "SMS", + status: "Unknown", + created: "11/01/2017 13:37", + }, + { + message: "test", + messageType: "Email", + status: "Unknown", + created: "11/01/2017 13:37", + }, + ], + }); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap index 6d988bbb7c6..894890d9364 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: comment.js --- # Input @@ -88,12 +89,12 @@ Something // Warm-up first measure().then(() => { SomethingLong(); -},); +}); measure() // Warm-up first .then(() => { SomethingLong(); -},); +}); const configModel = this.baseConfigurationService.getCache().consolidated.merge( // global/default values (do NOT modify) diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap index 7a0016367c7..99b7f4b6173 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: computed-merge.js --- # Input @@ -29,13 +30,13 @@ window.Data[key]("foo") data[key]("foo") .then(() => console.log("bar")) .catch(() => console.log("baz")); -},); +}); [].forEach((key) => { data("foo")[key]("bar") .then(() => console.log("bar")) .catch(() => console.log("baz")); -},); +}); window.Data[key]("foo") .then(() => a) diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed.js.snap index 27f9b0153c7..ecd06e8391b 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: computed.js --- # Input @@ -17,12 +18,9 @@ nock(/test/) ```js nock(/test/) .matchHeader("Accept", "application/json")[httpMethodNock(method)]("/foo") - .reply( - 200, - { - foo: "bar", - }, - ); + .reply(200, { + foo: "bar", + }); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap index 1af6fba8439..2003cb40d36 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: first_long.js --- # Input @@ -53,8 +54,8 @@ export default function theFunction(action$, store) { value1: true, value2: false, value3: false, - },), - },) + }), + }) .filter((data) => theFilter(data)) .map(({ theType, ...data }) => theMap(theType, data)) .retryWhen((errors) => errors), @@ -65,7 +66,7 @@ function f() { return this._getWorker(workerOptions)({ filePath, hasteImplModulePath: this._options.hasteImplModulePath, - },) + }) .then((metadata) => { // `1` for truthy values instead of `true` to save cache space. fileMetadata[H.VISITED] = 1; @@ -76,7 +77,7 @@ function f() { setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies || []; - },); + }); } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap index 15922c4c1f9..fe230d707f6 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: inline_merge.js --- # Input @@ -30,10 +31,10 @@ var jqxhr = $.ajax("example.php") Object.keys( availableLocales({ test: true, - },), + }), ).forEach((locale) => { // ... -},); +}); this.layoutPartsToHide = this.utils.hashset( diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap index 513f43d0622..0d03bd47e65 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: issue-4125.js --- # Input @@ -211,12 +212,10 @@ d3 Object.keys(props) .filter((key) => (key in own) === false) - .reduce( - (a, key) => { - a[key] = props[key]; - return a; - }, {}, - ); + .reduce((a, key) => { + a[key] = props[key]; + return a; + }, {}); point().x(4).y(3).z(6).plot(); @@ -253,12 +252,12 @@ function HelloWorld() { window.FooClient.setVars({ locale: getFooLocale({ page }), authorizationToken: data.token, - },).initVerify("foo_container"); + }).initVerify("foo_container"); fejax.ajax({ url: "/verification/", dataType: "json", - },).then( + }).then( (data) => { this.setState({ isLoading: false }); this.initWidget(data); @@ -294,7 +293,7 @@ action$ window.FooClient.setVars({ locale: getFooLocale({ page }), authorizationToken: data.token, -},).initVerify("foo_container"); +}).initVerify("foo_container"); it("gets triggered by mouseenter", () => { const wrapper = shallow(); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap index 04b6b195554..02b5b649c2f 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: multiple-members.js --- # Input @@ -42,28 +43,22 @@ wrapper.find('SomewhatLongNodeName').prop('longPropFunctionName')('argument', 's # Output ```js if (testConfig.ENABLE_ONLINE_TESTS === "true") { - describe( - "POST /users/me/pet", - function () { - it( - "saves pet", - function () { - function assert(pet) { - expect(pet).to.have - .property("OwnerAddress") - .that.deep.equals({ - AddressLine1: "Alexanderstrasse", - AddressLine2: "", - PostalCode: "10999", - Region: "Berlin", - City: "Berlin", - Country: "DE", - },); - } - }, - ); - }, - ); + describe("POST /users/me/pet", function () { + it("saves pet", function () { + function assert(pet) { + expect(pet).to.have + .property("OwnerAddress") + .that.deep.equals({ + AddressLine1: "Alexanderstrasse", + AddressLine2: "", + PostalCode: "10999", + Region: "Berlin", + City: "Berlin", + Country: "DE", + }); + } + }); + }); } wrapper @@ -71,14 +66,14 @@ wrapper .prop("longPropFunctionName")() .then(function () { doSomething(); - },); + }); wrapper .find("SomewhatLongNodeName") .prop("longPropFunctionName")("argument") .then(function () { doSomething(); - },); + }); wrapper .find("SomewhatLongNodeName") @@ -88,7 +83,7 @@ wrapper )("argument") .then(function () { doSomething(); - },); + }); wrapper .find("SomewhatLongNodeName") @@ -98,7 +93,7 @@ wrapper ) .then(function () { doSomething(); - },); + }); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap index 4449210e0ce..ae0c3240c35 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: object-literal.js --- # Input @@ -30,7 +31,7 @@ of("test") error(err) { thrown = err; }, - },); + }); of("test") .pipe(throwIfEmpty()) @@ -38,7 +39,7 @@ of("test") get foo() { bar(); }, - },); + }); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/graphql-tag.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/graphql-tag.js.snap index 36dbbee657a..1f67c082319 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/graphql-tag.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/graphql-tag.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: graphql-tag.js --- # Input @@ -307,7 +308,7 @@ ${USER_DETAILS_FRAGMENT} ${FRIENDS_FRAGMENT} ${generateFragment({ totally: "a good idea", -},)} +})} ${fragment}#comment diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/new-expression/with-member-expression.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/new-expression/with-member-expression.js.snap index 1ee942c3fbe..5bd1380a68a 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/new-expression/with-member-expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/new-expression/with-member-expression.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: with-member-expression.js --- # Input @@ -25,7 +26,7 @@ function functionName() { this._aVeryLongVariableNameToForceLineBreak = new this.Promise((resolve, reject) => { // do something - },); + }); } } diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/object-prop-break-in/test.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/object-prop-break-in/test.js.snap index f5aea980470..b72cf15ba93 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/object-prop-break-in/test.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/object-prop-break-in/test.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: test.js --- # Input @@ -41,33 +42,33 @@ ipsum` } ```js const a = classnames({ "some-prop": this.state.longLongLongLongLongLongLongLongLongTooLongProp, -},); +}); const b = classnames({ "some-prop": this.state.longLongLongLongLongLongLongLongLongTooLongProp === true, -},); +}); const c = classnames({ "some-prop": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo"], -},); +}); const d = classnames({ "some-prop": () => {}, -},); +}); const e = classnames({ "some-prop": function bar() {}, -},); +}); const f = classnames({ "some-prop": { foo: "bar", bar: "foo", foo: "bar", bar: "foo", foo: "bar" }, -},); +}); const g = classnames({ "some-prop": longLongLongLongLongLongLongLongLongLongLongLongLongTooLongVar || 1337, -},); +}); const h = { foo: "bar", diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/objects/range.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/objects/range.js.snap index 257b0da9eb7..a886300e441 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/objects/range.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/objects/range.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: range.js --- # Input @@ -22,19 +23,13 @@ group( # Output ```js -group( - concat([ - "(", - indent( - options.tabWidth, - concat([line, join(concat([",", line]), printed)]), - ), - options.trailingComma ? "," : "", - line, - ")", - ],), - { shouldBreak: true }, -); +group(concat([ + "(", + indent(options.tabWidth, concat([line, join(concat([",", line]), printed)])), + options.trailingComma ? "," : "", + line, + ")", +]), { shouldBreak: true }); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested-real.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested-real.js.snap index cb3cb324014..43855d0c089 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested-real.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested-real.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: nested-real.js --- # Input @@ -92,103 +93,93 @@ tap.test("RecordImport.advance", (t) => { # Output ```js -tap.test( - "RecordImport.advance", - (t) => { - const checkStates = (batches, states) => { - t.equal(batches.length, states.length); - for (const batch of batches) { - t.equal(batch.state, states.shift()); - t.ok(batch.getCurState().name(i18n)); - } - }; - - const batch = init.getRecordBatch(); - const dataFile = path.resolve(process.cwd(), "testData", "default.json"); - - const getBatches = (callback) => { - RecordImport.find( - {}, - "", - {}, - (err, batches) => { - callback( - null, - batches.filter( - (batch) => ( - batch.state !== "error" && batch.state !== "completed" - ), - ), - ); - }, +tap.test("RecordImport.advance", (t) => { + const checkStates = (batches, states) => { + t.equal(batches.length, states.length); + for (const batch of batches) { + t.equal(batch.state, states.shift()); + t.ok(batch.getCurState().name(i18n)); + } + }; + + const batch = init.getRecordBatch(); + const dataFile = path.resolve(process.cwd(), "testData", "default.json"); + + const getBatches = (callback) => { + RecordImport.find({}, "", {}, (err, batches) => { + callback( + null, + batches.filter( + (batch) => (batch.state !== "error" && batch.state !== "completed"), + ), ); - }; - - mockFS((callback) => { - batch.setResults( - [fs.createReadStream(dataFile)], - (err) => { - t.error(err, "Error should be empty."); - t.equal(batch.results.length, 6, "Check number of results"); - for (const result of batch.results) { - t.equal(result.result, "unknown"); - t.ok(result.data); - t.equal(result.data.lang, "en"); - } + }); + }; + + mockFS((callback) => { + batch.setResults( + [fs.createReadStream(dataFile)], + (err) => { + t.error(err, "Error should be empty."); + t.equal(batch.results.length, 6, "Check number of results"); + for (const result of batch.results) { + t.equal(result.result, "unknown"); + t.ok(result.data); + t.equal(result.data.lang, "en"); + } - getBatches((err, batches) => { - checkStates(batches, ["started"]); + getBatches((err, batches) => { + checkStates(batches, ["started"]); - RecordImport.advance((err) => { - t.error(err, "Error should be empty."); + RecordImport.advance((err) => { + t.error(err, "Error should be empty."); - getBatches((err, batches) => { - checkStates(batches, ["process.completed"]); + getBatches((err, batches) => { + checkStates(batches, ["process.completed"]); - // Need to manually move to the next step - batch.importRecords((err) => { - t.error(err, "Error should be empty."); + // Need to manually move to the next step + batch.importRecords((err) => { + t.error(err, "Error should be empty."); - getBatches((err, batches) => { - checkStates(batches, ["import.completed"]); + getBatches((err, batches) => { + checkStates(batches, ["import.completed"]); - RecordImport.advance((err) => { - t.error(err, "Error should be empty."); + RecordImport.advance((err) => { + t.error(err, "Error should be empty."); - getBatches((err, batches) => { - checkStates(batches, ["similarity.sync.completed"]); + getBatches((err, batches) => { + checkStates(batches, ["similarity.sync.completed"]); - RecordImport.advance((err) => { - t.error(err, "Error should be empty."); + RecordImport.advance((err) => { + t.error(err, "Error should be empty."); - t.ok(batch.getCurState().name(i18n)); + t.ok(batch.getCurState().name(i18n)); - getBatches((err, batches) => { - checkStates(batches, []); - t.end(); - callback(); - },); - },); + getBatches((err, batches) => { + checkStates(batches, []); + t.end(); + callback(); + }); + }); - t.ok(batch.getCurState().name(i18n)); - },); - },); + t.ok(batch.getCurState().name(i18n)); + }); + }); - t.ok(batch.getCurState().name(i18n)); - },); - },); + t.ok(batch.getCurState().name(i18n)); + }); + }); - t.ok(batch.getCurState().name(i18n)); - },); - },); + t.ok(batch.getCurState().name(i18n)); + }); + }); - t.ok(batch.getCurState().name(i18n)); - },); - }, - ); - },); - }, -); + t.ok(batch.getCurState().name(i18n)); + }); + }, + ); + }); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested.js.snap index 889c17e4d4c..4fbcc99d35d 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/performance/nested.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: nested.js --- # Input @@ -53,20 +54,20 @@ someObject.someFunction().then(function () { return someObject.someFunction().then(function () { return someObject.someFunction().then(function () { anotherFunction(); - },); - },); - },); - },); - },); - },); - },); - },); - },); - },); - },); - },); - },); -},); + }); + }); + }); + }); + }); + }); + }); + }); + }); + }); + }); + }); + }); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap index 0fc7f6a0e40..48f4ff48643 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap @@ -245,7 +245,7 @@ comments( // Long Long Long Long Long Comment short3, - // More comments +// More comments ); differentArgTypes( @@ -267,7 +267,7 @@ moreArgTypes( // Hello world again { name: "Hello World", age: 34 }, oneThing + anotherThing, - // Comment + // Comment ), ); @@ -303,36 +303,24 @@ doSomething.apply( ["Hello world 1", "Hello world 2", "Hello world 3"], ); -doAnotherThing( - "node", - { - solution_type, - time_frame, - }, -); +doAnotherThing("node", { + solution_type, + time_frame, +}); -stuff.doThing( - someStuff, - -1, - { - accept: (node) => doSomething(node), - }, -); +stuff.doThing(someStuff, -1, { + accept: (node) => doSomething(node), +}); -doThing( - someOtherStuff, - // This is important - true, - { - decline: (creditCard) => takeMoney(creditCard), - }, -); +doThing(someOtherStuff, +// This is important +true, { + decline: (creditCard) => takeMoney(creditCard), +}); -func( - () => { - thing(); - }, { yes: true, no: 5 }, -); +func(() => { + thing(); +}, { yes: true, no: 5 }); doSomething( { tomorrow: maybe, today: never[always] }, diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/named-amd-module.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/named-amd-module.js.snap index 04ef08bad69..f9452a83b93 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/named-amd-module.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/named-amd-module.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: named-amd-module.js --- # Input @@ -15,13 +16,9 @@ define("foo/title", # Output ```js -define( - "foo/title", - ["my/cart", "my/inventory"], - function (cart, inventory) { - //Define foo/title object in here. - }, -); +define("foo/title", ["my/cart", "my/inventory"], function (cart, inventory) { + //Define foo/title object in here. +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/require.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/require.js.snap index 5665ec16bcf..9ef59eafe1f 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/require.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/require-amd/require.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: require.js --- # Input @@ -42,55 +43,49 @@ define( # Output ```js -require( - [ - "jquery", - "common/global.context", - "common/log.event", - "some_project/square", - "some_project/rectangle", - "some_project/triangle", - "some_project/circle", - "some_project/star", - ], - function ( - $, - Context, - EventLogger, - Square, - Rectangle, - Triangle, - Circle, - Star, - ) { - console.log("some code"); - }, -); +require([ + "jquery", + "common/global.context", + "common/log.event", + "some_project/square", + "some_project/rectangle", + "some_project/triangle", + "some_project/circle", + "some_project/star", +], function ( + $, + Context, + EventLogger, + Square, + Rectangle, + Triangle, + Circle, + Star, +) { + console.log("some code"); +}); -define( - [ - "jquery", - "common/global.context", - "common/log.event", - "some_project/square", - "some_project/rectangle", - "some_project/triangle", - "some_project/circle", - "some_project/star", - ], - function ( - $, - Context, - EventLogger, - Square, - Rectangle, - Triangle, - Circle, - Star, - ) { - console.log("some code"); - }, -); +define([ + "jquery", + "common/global.context", + "common/log.event", + "some_project/square", + "some_project/rectangle", + "some_project/triangle", + "some_project/circle", + "some_project/star", +], function ( + $, + Context, + EventLogger, + Square, + Rectangle, + Triangle, + Circle, + Star, +) { + console.log("some code"); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/return/comment.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/return/comment.js.snap index 090ecd76c96..a7fca1a276b 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/return/comment.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/return/comment.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: comment.js --- # Input @@ -89,7 +90,7 @@ fn(function f() { // comment .bar() ); -},); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/template/graphql.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/template/graphql.js.snap index b0e16121208..c76825a8eed 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/template/graphql.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/template/graphql.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: graphql.js --- # Input @@ -36,10 +37,10 @@ module.exports = Relay.QL` fragment on RelatedNode @relay(plural: true) { __typename - ${OptimalSolutionsSection.getFragment( - "node", - { solution_type, time_frame }, - )} + ${OptimalSolutionsSection.getFragment("node", { + solution_type, + time_frame, + })} } `, }, diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/template/indent.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/template/indent.js.snap index 4cd1f0783f4..7cc24c81cc3 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/template/indent.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/template/indent.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: indent.js --- # Input @@ -41,7 +42,7 @@ line n ${foo({ many: keys, many: keys, - },)} + })} line n + 1 line n + 2 line n + n diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ternaries/indent.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/ternaries/indent.js.snap index eca52954e8a..1da157d4d91 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/ternaries/indent.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ternaries/indent.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: indent.js --- # Input @@ -243,7 +244,7 @@ a ? { a ? { a: a({ a: 0, - },), + }), } : [ 0, a(), @@ -254,7 +255,7 @@ a ? { }, a ? a() : a({ a: 0, - },), + }), ), a() ? { a: a(), @@ -277,7 +278,7 @@ a ? { { a: 0, }, - ],); + ]); })( a ? function (a) { return function () { diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_async.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_async.js.snap index 6e543542e28..e20c6e21235 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_async.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_async.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: angular_async.js --- # Input @@ -46,7 +47,7 @@ function x() { async(() => {}) } beforeEach( async(() => { // code - },), + }), ); beforeEach((done) => foo().bar().bar()); @@ -54,7 +55,7 @@ beforeEach((done) => foo().bar().bar()); afterAll( async(() => { console.log("Hello"); - },), + }), ); afterAll((done) => foo().bar().bar()); @@ -63,14 +64,14 @@ it( "should create the app", async(() => { //code - },), + }), ); it( "does something really long and complicated so I have to write a very long name for the test", async(() => { // code - },), + }), ); /* diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_fakeAsync.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_fakeAsync.js.snap index 35c00121d6d..ae4ece92245 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_fakeAsync.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_fakeAsync.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: angular_fakeAsync.js --- # Input @@ -36,27 +37,27 @@ function x() { fakeAsync(() => {}) } beforeEach( fakeAsync(() => { // code - },), + }), ); afterAll( fakeAsync(() => { console.log("Hello"); - },), + }), ); it( "should create the app", fakeAsync(() => { //code - },), + }), ); it( "does something really long and complicated so I have to write a very long name for the test", fakeAsync(() => { // code - },), + }), ); it( diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_waitForAsync.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_waitForAsync.js.snap index fa4adbdafe0..b0d21872109 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_waitForAsync.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_waitForAsync.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: angular_waitForAsync.js --- # Input @@ -36,27 +37,27 @@ function x() { waitForAsync(() => {}) } beforeEach( waitForAsync(() => { // code - },), + }), ); afterAll( waitForAsync(() => { console.log("Hello"); - },), + }), ); it( "should create the app", waitForAsync(() => { //code - },), + }), ); it( "does something really long and complicated so I have to write a very long name for the test", waitForAsync(() => { // code - },), + }), ); it( diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angularjs_inject.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angularjs_inject.js.snap index f32f2887133..32f5f6a0b31 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angularjs_inject.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angularjs_inject.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: angularjs_inject.js --- # Input @@ -38,34 +39,34 @@ function x() { inject(() => {}) } beforeEach( inject(($fooService, $barService) => { // code - },), + }), ); afterAll( inject(($fooService, $barService) => { console.log("Hello"); - },), + }), ); it( "should create the app", inject(($fooService, $barService) => { //code - },), + }), ); it( "does something really long and complicated so I have to write a very long name for the test", inject(() => { // code - },), + }), ); it( "does something really long and complicated so I have to write a very long name for the test", inject(($fooServiceLongName, $barServiceLongName) => { // code - },), + }), ); /* diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/comment.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/comment.js.snap index ebd82401525..1040cce7b8a 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/comment.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/comment.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: comment.js --- # Input @@ -50,7 +51,7 @@ fn(function f() { // comment .bar() ); -},); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/jsx.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/jsx.js.snap index 910967d8658..c941b01a2d6 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/jsx.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/jsx.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: jsx.js --- # Input @@ -21,7 +22,7 @@ expression: jsx.js () => doSomething({ foo: bar, - },) + }) } />; diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/trailing_whitespace.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/trailing_whitespace.js.snap index fb4c375a2c1..d786f3102f6 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/trailing_whitespace.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/trailing_whitespace.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: trailing_whitespace.js --- # Input @@ -59,7 +60,7 @@ let example = [ foo( {}, - // Comment +// Comment ); o = @@ -89,17 +90,13 @@ function supersupersupersuperLongF( a; } -this.getAttribute( - function (s) - /*string*/ { - console.log(); - }, -); -this.getAttribute( - function (s) /*string*/ { - console.log(); - }, -); +this.getAttribute(function (s) +/*string*/ { + console.log(); +}); +this.getAttribute(function (s) /*string*/ { + console.log(); +}); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/variable_declarator/multiple.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/variable_declarator/multiple.js.snap index e91c3e9ab5c..65e37830ac4 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/variable_declarator/multiple.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/variable_declarator/multiple.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: multiple.js --- # Input @@ -51,12 +52,9 @@ var templateTagsMapping = { "%{itemContentMetaTextViews}": "views", }, separator = '', - templateTagsList = $.map( - templateTagsMapping, - function (value, key) { - return key; - }, - ), + templateTagsList = $.map(templateTagsMapping, function (value, key) { + return key; + }), data; ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/argument-expansion/argument_expansion.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/argument-expansion/argument_expansion.ts.snap index b91fc1e3fa3..2c44ea8f9b3 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/argument-expansion/argument_expansion.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/argument-expansion/argument_expansion.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: argument_expansion.ts --- # Input @@ -40,61 +41,37 @@ const bar8 = [1,2,3].reduce((carry, value) => { # Output ```js -const bar1 = [1, 2, 3].reduce( - (carry, value) => { - return [...carry, value]; - }, - ([] as unknown) as number[], -); - -const bar2 = [1, 2, 3].reduce( - (carry, value) => { - return [...carry, value]; - }, - >[], -); - -const bar3 = [1, 2, 3].reduce( - (carry, value) => { - return [...carry, value]; - }, - ([1, 2, 3] as unknown) as number[], -); - -const bar4 = [1, 2, 3].reduce( - (carry, value) => { - return [...carry, value]; - }, - >[1, 2, 3], -); - -const bar5 = [1, 2, 3].reduce( - (carry, value) => { - return { ...carry, [value]: true }; - }, - ({} as unknown) as { [key: number]: boolean }, -); - -const bar6 = [1, 2, 3].reduce( - (carry, value) => { - return { ...carry, [value]: true }; - }, - <{ [key: number]: boolean }>{}, -); - -const bar7 = [1, 2, 3].reduce( - (carry, value) => { - return { ...carry, [value]: true }; - }, - ({ 1: true } as unknown) as { [key: number]: boolean }, -); - -const bar8 = [1, 2, 3].reduce( - (carry, value) => { - return { ...carry, [value]: true }; - }, - <{ [key: number]: boolean }>{ 1: true }, -); +const bar1 = [1, 2, 3].reduce((carry, value) => { + return [...carry, value]; +}, ([] as unknown) as number[]); + +const bar2 = [1, 2, 3].reduce((carry, value) => { + return [...carry, value]; +}, >[]); + +const bar3 = [1, 2, 3].reduce((carry, value) => { + return [...carry, value]; +}, ([1, 2, 3] as unknown) as number[]); + +const bar4 = [1, 2, 3].reduce((carry, value) => { + return [...carry, value]; +}, >[1, 2, 3]); + +const bar5 = [1, 2, 3].reduce((carry, value) => { + return { ...carry, [value]: true }; +}, ({} as unknown) as { [key: number]: boolean }); + +const bar6 = [1, 2, 3].reduce((carry, value) => { + return { ...carry, [value]: true }; +}, <{ [key: number]: boolean }>{}); + +const bar7 = [1, 2, 3].reduce((carry, value) => { + return { ...carry, [value]: true }; +}, ({ 1: true } as unknown) as { [key: number]: boolean }); + +const bar8 = [1, 2, 3].reduce((carry, value) => { + return { ...carry, [value]: true }; +}, <{ [key: number]: boolean }>{ 1: true }); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/as/as.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/as/as.ts.snap index c57f474a4dd..84e34ead9aa 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/as/as.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/as/as.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: as.ts --- # Input @@ -79,12 +80,10 @@ async function g1() { } ({}) as X; () => ({}) as X; -const state = JSON.stringify( - { - next: window.location.href, - nonce, - } as State, -); +const state = JSON.stringify({ + next: window.location.href, + nonce, +} as State); (foo.bar as Baz) = [bar]; (foo.bar as any)++; @@ -122,8 +121,8 @@ const iter2 = createIterator( # Lines exceeding max width of 80 characters ``` - 44: const value1 = thisIsAReallyReallyReallyReallyReallyLongIdentifier as SomeInterface; - 45: const value2 = thisIsAnIdentifier as thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongInterface; - 54: const value5 = thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyLongIdentifier as [ + 42: const value1 = thisIsAReallyReallyReallyReallyReallyLongIdentifier as SomeInterface; + 43: const value2 = thisIsAnIdentifier as thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongInterface; + 52: const value5 = thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyLongIdentifier as [ ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment.ts.snap index b271d90ce23..74ef8070173 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: assignment.ts --- # Input @@ -61,25 +62,19 @@ const TYPE_MAP = { this.previewPlayerHandle = ( - setInterval( - async () => { - if (this.previewIsPlaying) { - await this.fetchNextPreviews(); - this.currentPreviewIndex++; - } - }, - this.refreshDelay, - ) as unknown + setInterval(async () => { + if (this.previewIsPlaying) { + await this.fetchNextPreviews(); + this.currentPreviewIndex++; + } + }, this.refreshDelay) as unknown ) as number; this.intervalID = ( - setInterval( - () => { - self.step(); - }, - 30, - ) as unknown + setInterval(() => { + self.step(); + }, 30) as unknown ) as number; ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-10848.tsx.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-10848.tsx.snap index a1f7e2b3a37..ddf138d2302 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-10848.tsx.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-10848.tsx.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: issue-10848.tsx --- # Input @@ -121,10 +122,10 @@ const Query: FunctionComponent = ( }, ) => children( - useQuery( - { type, resource, payload }, - { ...options, withDeclarativeSideEffectsSupport: true }, - ), + useQuery({ type, resource, payload }, { + ...options, + withDeclarativeSideEffectsSupport: true, + }), ); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/cast/hug-args.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/cast/hug-args.ts.snap index 7c150801afa..8bb6332d9cd 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/cast/hug-args.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/cast/hug-args.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: hug-args.ts --- # Input @@ -31,28 +32,22 @@ postMessages( # Output ```js -postMessage( - { - context: item.context, - topic: item.topic, - }, -); +postMessage({ + context: item.context, + topic: item.topic, +}); -window.postMessage( +window.postMessage({ + context: item.context, + topic: item.topic, +} as IActionMessage); + +postMessages([ { context: item.context, topic: item.topic, - } as IActionMessage, -); - -postMessages( - [ - { - context: item.context, - topic: item.topic, - }, - ], -); + }, +]); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/classes/break.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/classes/break.ts.snap index 6591f8f2f2d..613bb43793c 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/classes/break.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/classes/break.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: break.ts --- # Input @@ -81,7 +82,7 @@ class InMemoryAppender extends log4javascript.Appender class Foo extends Immutable.Record({ ipaddress: "", -},) { +}) { ipaddress: string; } diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/edge_case.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/edge_case.ts.snap index bfb3e6e8dd3..4413e470f95 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/edge_case.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/last-argument-expansion/edge_case.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: edge_case.ts --- # Input @@ -24,10 +25,10 @@ var listener = DOM.listen( "click", sigil, (event: JavelinEvent): void => - BanzaiLogger.log( - config, - { ...logData, ...DataStore.get(event.getNode(sigil)) }, - ), + BanzaiLogger.log(config, { + ...logData, + ...DataStore.get(event.getNode(sigil)), + }), ); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/typeparams/class-method.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/typeparams/class-method.ts.snap index 21adc167dc8..5dcd7dca42d 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/typeparams/class-method.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/typeparams/class-method.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: class-method.ts --- # Input @@ -132,7 +133,7 @@ export class Thing3 implements OtherThing { return someVar.method(); } return false; - },); + }); } export class Thing4 implements OtherThing { @@ -194,23 +195,23 @@ export class Thing11 implements OtherThing { // regular non-arrow functions export class Thing12 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType): Provider { - return type; - }, - ); + do: (type: Type) => Provider = memoize(function ( + type: ObjectType, + ): Provider { + return type; + }); } export class Thing13 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType): Provider { - const someVar = doSomething(type); - if (someVar) { - return someVar.method(); - } - return false; - }, - ); + do: (type: Type) => Provider = memoize(function ( + type: ObjectType, + ): Provider { + const someVar = doSomething(type); + if (someVar) { + return someVar.method(); + } + return false; + }); } export class Thing14 implements OtherThing { @@ -220,75 +221,69 @@ export class Thing14 implements OtherThing { return someVar.method(); } return false; - },); + }); } export class Thing15 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType): Provider { - return type.doSomething(); - }, - ); + do: (type: Type) => Provider = memoize(function ( + type: ObjectType, + ): Provider { + return type.doSomething(); + }); } export class Thing16 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType): Provider { - return type.doSomething(); - }, - ); + do: (type: Type) => Provider = memoize(function ( + type: ObjectType, + ): Provider { + return type.doSomething(); + }); } export class Thing17 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType): Provider { - return >type.doSomething(); - }, - ); + do: (type: Type) => Provider = memoize(function ( + type: ObjectType, + ): Provider { + return >type.doSomething(); + }); } export class Thing18 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType) { - return >type.doSomething(); - }, - ); + do: (type: Type) => Provider = memoize(function (type: ObjectType) { + return >type.doSomething(); + }); } export class Thing19 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType) { - return >type.doSomething( - withArgs, - soIt, - does, - not, - fit, - ).extraCall(); - }, - ); + do: (type: Type) => Provider = memoize(function (type: ObjectType) { + return >type.doSomething( + withArgs, + soIt, + does, + not, + fit, + ).extraCall(); + }); } export class Thing20 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType) { - return type.doSomething(); - }, - ); + do: (type: Type) => Provider = memoize(function (type: ObjectType) { + return type.doSomething(); + }); } export class Thing21 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (veryLongArgName: ObjectType): Provider { - return veryLongArgName; - }, - ); + do: (type: Type) => Provider = memoize(function ( + veryLongArgName: ObjectType, + ): Provider { + return veryLongArgName; + }); } export class Thing22 implements OtherThing { - do: (type: Type) => Provider = memoize( - function (type: ObjectType): Provider {}, - ); + do: (type: Type) => Provider = memoize(function ( + type: ObjectType, + ): Provider {}); } // case from https://github.com/prettier/prettier/issues/2581 From 2e74bac5660fc749e9fe8b4b1f2a6095ad81afcc Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Wed, 15 Jun 2022 14:16:56 -0300 Subject: [PATCH 10/16] chore: optimisations --- .../src/js/expressions/call_arguments.rs | 55 +++++++++---------- crates/rome_js_formatter/src/utils/mod.rs | 24 -------- 2 files changed, 25 insertions(+), 54 deletions(-) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index bc4b17708da..e0e8bd37651 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,6 +1,6 @@ use crate::builders::{format_close_delimiter, format_open_delimiter}; use crate::prelude::*; -use crate::utils::{fmt_arguments_multi_line, fmt_arguments_one_line, is_call_like_expression}; +use crate::utils::{fmt_arguments_multi_line, is_call_like_expression}; use crate::FormatNodeFields; use rome_formatter::{format_args, write}; use rome_js_syntax::JsSyntaxKind::JS_EMPTY_STATEMENT; @@ -23,10 +23,6 @@ impl FormatNodeFields for FormatNodeRule { let l_paren_token = l_paren_token?; let r_paren_token = r_paren_token?; - // we create open a close delimiters - let open_delimiter = format_open_delimiter(&l_paren_token); - let close_delimiter = format_close_delimiter(&r_paren_token); - // we now extracts the formatted version of trivias and tokens of the delimiters if args.len() == 0 { @@ -70,6 +66,10 @@ impl FormatNodeFields for FormatNodeRule { ); } + // we create open a close delimiters + let open_delimiter = format_open_delimiter(&l_paren_token); + let close_delimiter = format_close_delimiter(&r_paren_token); + // tokens on the left let l_leading_trivia = open_delimiter.as_leading_trivia_fmt(); let l_paren = open_delimiter.as_token_fmt(); @@ -83,20 +83,21 @@ impl FormatNodeFields for FormatNodeRule { let should_group_first_argument = should_group_first_argument(&args)?; let should_group_last_argument = should_group_last_argument(&args)?; - // We finished the "simple cases", we now need to use `best_fitting`. - // We now need to allocate a new vector with cached nodes, this is needed because - // we can't attempt to print the same node twice without incur in "printed token twice" errors. - // We also disallow the trailing separator, we are interested in doing it manually. - let separated: Vec<_> = args - .format_separated(token(",")) - .with_options( - FormatSeparatedOptions::default().with_trailing_separator(TrailingSeparator::Elide), - ) - .map(|e| e.memoized()) - .collect(); - // if the first or last groups needs grouping, then we prepare some special formatting if should_group_first_argument || should_group_last_argument { + // We finished the "simple cases", we now need to use `best_fitting`. + // We now need to allocate a new vector with cached nodes, this is needed because + // we can't attempt to print the same node twice without incur in "printed token twice" errors. + // We also disallow the trailing separator, we are interested in doing it manually. + let separated: Vec<_> = args + .format_separated(token(",")) + .with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ) + .map(|e| e.memoized()) + .collect(); + // We now cache them the delimiters tokens. This is needed because `[rome_formatter::best_fitting]` will try to // print each version first // tokens on the left @@ -220,19 +221,13 @@ impl FormatNodeFields for FormatNodeRule { &group_elements(&format_args![ l_paren, l_trailing_trivia, - // TODO: check if soft_line_block works here - &if_group_breaks(&format_args![ - indent(&format_args![ - soft_line_break(), - &format_with(|f| { - fmt_arguments_multi_line(separated.iter(), args.len(), f) - }), - ]), - soft_line_break(), - ]), - &if_group_fits_on_line(&format_args![&format_with(|f| { - fmt_arguments_one_line(separated.iter(), args.len(), f) - }),]), + &soft_block_indent(&format_with(|f| { + let separated = args.format_separated(token(",")).with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ); + fmt_arguments_multi_line(separated, args.len(), f) + }),), r_leading_trivia, r_paren, ],), diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index d06e31d4bd2..45493a3175a 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -548,27 +548,3 @@ where join_with.finish() } - -/// This function is in charge to format the call arguments. -pub(crate) fn fmt_arguments_one_line, I>( - separated: I, - number_of_elements: usize, - f: &mut JsFormatter, -) -> FormatResult<()> -where - I: Iterator, - S: std::fmt::Debug, -{ - let mut iterator = separated.enumerate(); - let mut join_with = f.join_with(space_token()); - - for (index, element) in iterator.by_ref() { - if index == number_of_elements - 1 { - join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); - } else { - join_with.entry(&element); - } - } - - join_with.finish() -} From 89f9c3325d0d752d48bee23ff25ff5f594174fbe Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Wed, 15 Jun 2022 14:29:19 -0300 Subject: [PATCH 11/16] chore: code review --- .../src/js/expressions/call_arguments.rs | 34 +++++++------------ .../src/js/lists/call_argument_list.rs | 19 ++++++----- crates/rome_js_formatter/src/lib.rs | 4 ++- crates/rome_js_formatter/src/utils/mod.rs | 9 ++--- .../tests/specs/js/module/call_expression.js | 16 ++++++++- .../specs/js/module/call_expression.js.snap | 31 +++++++++++++++++ .../tests/specs/ts/call_expression.ts | 10 ++++++ .../tests/specs/ts/call_expression.ts.snap | 34 +++++++++++++++++++ 8 files changed, 122 insertions(+), 35 deletions(-) create mode 100644 crates/rome_js_formatter/tests/specs/ts/call_expression.ts create mode 100644 crates/rome_js_formatter/tests/specs/ts/call_expression.ts.snap diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index e0e8bd37651..d2998f9c172 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -110,7 +110,7 @@ impl FormatNodeFields for FormatNodeRule { let r_paren = r_paren.memoized(); let r_trailing_trivia = r_trailing_trivia.memoized(); - let edge_arguments_not_grouped = format_with(|f| { + let edge_arguments_do_not_break = format_with(|f| { // `should_group_first_argument` and `should_group_last_argument` are mutually exclusive // which means that if one is `false`, then the other is `true`. // This means that in this branch we format the case where `should_group_first_argument`, @@ -177,11 +177,7 @@ impl FormatNodeFields for FormatNodeRule { &soft_block_indent(&format_args![ &l_trailing_trivia, format_with(|f| { - fmt_arguments_multi_line( - separated.iter(), - separated.len(), - f, - ) + fmt_arguments_multi_line(separated.iter(), f) }), &r_leading_trivia, soft_line_break() @@ -203,13 +199,13 @@ impl FormatNodeFields for FormatNodeRule { l_paren, l_trailing_trivia, group_elements(&format_args![format_with(|f| { - fmt_arguments_multi_line(separated.iter(), separated.len(), f) + fmt_arguments_multi_line(separated.iter(), f) })]), r_leading_trivia, r_paren, r_trailing_trivia ], - edge_arguments_not_grouped, + edge_arguments_do_not_break, all_arguments_expanded ]] ) @@ -226,7 +222,7 @@ impl FormatNodeFields for FormatNodeRule { FormatSeparatedOptions::default() .with_trailing_separator(TrailingSeparator::Elide), ); - fmt_arguments_multi_line(separated, args.len(), f) + fmt_arguments_multi_line(separated, f) }),), r_leading_trivia, r_paren, @@ -262,18 +258,14 @@ fn should_group_first_argument(list: &JsCallArgumentList) -> SyntaxResult false }; - let second_arg_is_function_like = - if let JsAnyCallArgument::JsAnyExpression(ref expression) = second { - matches!( - expression, - JsAnyExpression::JsFunctionExpression(_) - | JsAnyExpression::JsArrowFunctionExpression(_) - | JsAnyExpression::JsConditionalExpression(_) - ) - } else { - false - }; - + let second_arg_is_function_like = matches!( + second, + JsAnyCallArgument::JsAnyExpression( + JsAnyExpression::JsFunctionExpression(_) + | JsAnyExpression::JsArrowFunctionExpression(_) + | JsAnyExpression::JsConditionalExpression(_) + ) + ); Ok(!has_comments && is_function_like && !second_arg_is_function_like diff --git a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs index 2c84672cbc0..7f73c745978 100644 --- a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs +++ b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs @@ -9,15 +9,18 @@ impl FormatRule for FormatJsCallArgumentList { fn fmt(node: &JsCallArgumentList, f: &mut JsFormatter) -> FormatResult<()> { if node.len() == 0 { - return write!(f, [empty_element()]); + return Ok(()); } - let args = format_with(|f| { - let separated = node.format_separated(JsSyntaxKind::COMMA).with_options( - FormatSeparatedOptions::default().with_trailing_separator(TrailingSeparator::Elide), - ); - fmt_arguments_multi_line(separated, node.len(), f) - }); - write!(f, [&group_elements(&soft_block_indent(&args))]) + write!( + f, + [&group_elements(&soft_block_indent(&format_with(|f| { + let separated = node.format_separated(JsSyntaxKind::COMMA).with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ); + fmt_arguments_multi_line(separated, f) + })))] + ) } } diff --git a/crates/rome_js_formatter/src/lib.rs b/crates/rome_js_formatter/src/lib.rs index 3e764c67518..7e03a595c92 100644 --- a/crates/rome_js_formatter/src/lib.rs +++ b/crates/rome_js_formatter/src/lib.rs @@ -526,7 +526,9 @@ mod test { // use this test check if your snippet prints as you wish, without using a snapshot fn quick_test() { let src = r#" - + app.get("/", (req, res): void => { + res.send("Hello World!"); + }); export class Thing implements OtherThing { do: (type: Type) => Provider = memoize( diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 45493a3175a..66c277cd778 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -528,18 +528,19 @@ impl Format for FormatMemberName { /// This function is in charge to format the call arguments. pub(crate) fn fmt_arguments_multi_line, I>( separated: I, - number_of_elements: usize, f: &mut JsFormatter, ) -> FormatResult<()> where I: Iterator, S: std::fmt::Debug, { - let mut iterator = separated.enumerate(); + let mut iterator = separated.peekable(); let mut join_with = f.join_with(soft_line_break_or_space()); - for (index, element) in iterator.by_ref() { - if index == number_of_elements - 1 { + while let Some(element) = iterator.by_ref().next() { + let last = iterator.peek().is_none(); + + if last { join_with.entry(&format_args![&element, &if_group_breaks(&token(","))]); } else { join_with.entry(&element); diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js index 5d9444924dd..b71bb6a3a01 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js @@ -14,4 +14,18 @@ useMemo(() => { } // some comment , [a, b] -) \ No newline at end of file +) + +test.expect(t => { + t.true(a) +}) + +test.expect(t => { + t.true(a) +}, false) + +test.something(t => { + t.true() +}, context => { + context.flush() +}) \ No newline at end of file diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap index 369e0792a65..ce911cd0a39 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap @@ -21,6 +21,20 @@ useMemo(() => { , [a, b] ) + +test.expect(t => { + t.true(a) +}) + +test.expect(t => { + t.true(a) +}, false) + +test.something(t => { + t.true() +}, context => { + context.flush() +}) ============================= # Outputs ## Output 1 @@ -40,3 +54,20 @@ useMemo(() => { useMemo(() => {}, [a, b]); // some comment +test.expect((t) => { + t.true(a); +}); + +test.expect((t) => { + t.true(a); +}, false); + +test.something( + (t) => { + t.true(); + }, + (context) => { + context.flush(); + }, +); + diff --git a/crates/rome_js_formatter/tests/specs/ts/call_expression.ts b/crates/rome_js_formatter/tests/specs/ts/call_expression.ts new file mode 100644 index 00000000000..9fe943873d2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/ts/call_expression.ts @@ -0,0 +1,10 @@ +app.get("/", (req, res): void => { + res.send("Hello World!"); +}) + + +export class Thing implements OtherThing { + do: (type: Type) => Provider = memoize( + (type: ObjectType): Provider => {} + ); +} \ No newline at end of file diff --git a/crates/rome_js_formatter/tests/specs/ts/call_expression.ts.snap b/crates/rome_js_formatter/tests/specs/ts/call_expression.ts.snap new file mode 100644 index 00000000000..16db0f0daaf --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/ts/call_expression.ts.snap @@ -0,0 +1,34 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: call_expression.ts +--- +# Input +app.get("/", (req, res): void => { + res.send("Hello World!"); +}) + + +export class Thing implements OtherThing { + do: (type: Type) => Provider = memoize( + (type: ObjectType): Provider => {} + ); +} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +app.get("/", (req, res): void => { + res.send("Hello World!"); +}); + +export class Thing implements OtherThing { + do: (type: Type) => Provider = memoize( + (type: ObjectType): Provider => {}, + ); +} + From 23c343cfd31204d92a63604862ebd5d4a0bad4cd Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Wed, 15 Jun 2022 15:05:09 -0300 Subject: [PATCH 12/16] chore: rebase and clippy --- crates/rome_js_formatter/src/builders.rs | 12 +++--------- .../src/js/expressions/call_arguments.rs | 17 +++++++++-------- crates/rome_js_formatter/src/separated.rs | 2 +- .../tests/specs/js/module/comments.js.snap | 6 +++--- .../specs/js/module/statement/if_else.js.snap | 4 ++-- .../specs/prettier/js/comments/arrow.js.snap | 5 +++-- .../prettier/js/comments/dangling.js.snap | 5 +++-- .../js/comments/dynamic_imports.js.snap | 3 ++- .../js/comments/function-declaration.js.snap | 19 ++++++++++--------- .../class-property.js.snap | 13 +++++++------ .../empty_paren_comment.js.snap | 15 ++++++++------- .../js/first-argument-expansion/test.js.snap | 2 +- .../specs/prettier/js/ignore/ignore-2.js.snap | 3 ++- .../js/preserve-line/argument-list.js.snap | 2 ++ .../class/empty-method-body.ts.snap | 3 ++- .../typescript/comments/method_types.ts.snap | 17 +++++++++-------- .../typescript/comments/methods.ts.snap | 3 ++- crates/rome_js_syntax/src/parameters_ext.rs | 4 ++++ 18 files changed, 73 insertions(+), 62 deletions(-) diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs index 1bee77f7332..cb9d8dcf482 100644 --- a/crates/rome_js_formatter/src/builders.rs +++ b/crates/rome_js_formatter/src/builders.rs @@ -3,7 +3,7 @@ use crate::{AsFormat, JsCommentStyle}; use rome_formatter::token::{ format_token_trailing_trivia, FormatInserted, FormatInsertedCloseParen, FormatInsertedOpenParen, FormatLeadingTrivia, FormatOnlyIfBreaks, FormatRemoved, - FormatReplaced, TriviaPrintMode, + FormatReplaced, }; use rome_formatter::{format_args, write, Argument, Arguments, GroupId, PreambleBuffer, VecBuffer}; use rome_js_syntax::{JsLanguage, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken}; @@ -520,7 +520,7 @@ impl<'t> OpenDelimiter<'t> { /// It extracts the formatted leading trivia of the token, without writing it in the buffer pub(crate) fn as_leading_trivia_fmt(&self) -> impl Format + 't { - format_leading_trivia(self.open_token, TriviaPrintMode::Full) + format_leading_trivia(self.open_token) } /// It extracts the formatted trailing trivia of the token, without writing it in the buffer @@ -570,13 +570,7 @@ impl<'t> CloseDelimiter<'t> { format_with(|f| { let mut buffer = PreambleBuffer::new(f, soft_line_break_or_space()); - write!( - buffer, - [format_leading_trivia( - self.close_token, - TriviaPrintMode::Trim - )] - ) + write!(buffer, [format_leading_trivia(self.close_token,)]) }) } diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index d2998f9c172..95539ab8545 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -8,7 +8,7 @@ use rome_js_syntax::{ JsAnyCallArgument, JsAnyExpression, JsAnyFunctionBody, JsArrayExpression, JsArrowFunctionExpression, JsCallArgumentList, JsCallArguments, JsCallArgumentsFields, JsConditionalExpression, JsFunctionBody, JsFunctionExpression, JsObjectExpression, - JsSyntaxNode, TsAsExpression, TsReferenceType, TsTypeAssertionExpression, + JsSyntaxKind, JsSyntaxNode, TsAsExpression, TsReferenceType, TsTypeAssertionExpression, }; use rome_rowan::{AstSeparatedList, SyntaxResult}; @@ -56,7 +56,7 @@ impl FormatNodeFields for FormatNodeRule { // we don't want to print the trailing separator, so if it's present, we replace it // with an empty element if let Some(separator) = second_argument.trailing_separator()? { - return write!(f, [format_replaced(separator, &empty_element())]); + return write!(f, [format_removed(separator)]); } Ok(()) @@ -90,7 +90,7 @@ impl FormatNodeFields for FormatNodeRule { // we can't attempt to print the same node twice without incur in "printed token twice" errors. // We also disallow the trailing separator, we are interested in doing it manually. let separated: Vec<_> = args - .format_separated(token(",")) + .format_separated(JsSyntaxKind::COMMA) .with_options( FormatSeparatedOptions::default() .with_trailing_separator(TrailingSeparator::Elide), @@ -218,10 +218,11 @@ impl FormatNodeFields for FormatNodeRule { l_paren, l_trailing_trivia, &soft_block_indent(&format_with(|f| { - let separated = args.format_separated(token(",")).with_options( - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), - ); + let separated = + args.format_separated(JsSyntaxKind::COMMA).with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Elide), + ); fmt_arguments_multi_line(separated, f) }),), r_leading_trivia, @@ -392,7 +393,7 @@ fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult { - write!(f, [format_replaced(separator, &empty_element())])?; + write!(f, [format_removed(separator)])?; } } } else { diff --git a/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap b/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap index 74e0e98b62e..eeaca33d598 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap @@ -120,9 +120,9 @@ expression( "something", ); -const array0 = [/*0*/]; -const array1 = [/*0*/, /*1*/]; -const array2 = [/*0*/, /*1*/ , /*2*/]; +const array0 = [/*0*/ ]; +const array1 = [/*0*/ , /*1*/]; +const array2 = [/*0*/ , /*1*/ , /*2*/]; /* block comment */ statement(); diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap b/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap index 0e8f34c4238..dc0ecb630c0 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap @@ -1,8 +1,7 @@ --- source: crates/rome_js_formatter/tests/spec_test.rs -assertion_line: 242 +assertion_line: 257 expression: if_else.js - --- # Input if(a); @@ -125,6 +124,7 @@ if (true) { if (true) { // trailing + } else { // trailing } diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap index 6aefbe7e822..a99351cbe0f 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: arrow.js --- # Input @@ -12,9 +13,9 @@ const fn2 = (/*event, data*/) => doSomething(anything); # Output ```js -const fn = (/*event, data*/) => doSomething(); +const fn = (/*event, data*/ ) => doSomething(); -const fn2 = (/*event, data*/) => doSomething(anything); +const fn2 = (/*event, data*/ ) => doSomething(anything); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap index 4a875afdfc5..bc0fa442b88 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: dangling.js --- # Input @@ -20,11 +21,11 @@ export /* dangling */{}; # Output ```js -var a = {/* dangling */}; +var a = {/* dangling */ }; var b = { // dangling }; -var b = [/* dangling */]; +var b = [/* dangling */ ]; function d() { /* dangling */ } diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap index c46bcb08988..ed7b8bc3ef9 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap @@ -40,7 +40,8 @@ import("something" /* Hello */ + "else"); import( /* Hello */ "something", -/* Hello */ ); +/* Hello */ +); wrap(import(/* Hello */ "something")); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap index 052371461e3..3d7ebe3eeaf 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: function-declaration.js --- # Input @@ -70,7 +71,7 @@ function foo4() { # Output ```js -function a(/* comment */) {} // comment +function a(/* comment */ ) {} // comment function b() {} // comment function c(/* comment */ argA, argB, argC) {} // comment call((/*object*/ row) => {}); @@ -82,9 +83,9 @@ KEYPAD_NUMBERS.map( ); function f1 /* f */ () {} -function f2(/* args */) {} +function f2(/* args */ ) {} function f3() /* returns */ {} -function f4 /* f */ (/* args */) /* returns */ {} +function f4 /* f */ (/* args */ ) /* returns */ {} function f5 /* f */ (/* a */ a) {} function f6 /* f */ (a /* a */) {} @@ -92,27 +93,27 @@ function f7 /* f */ (/* a */ a) /* returns */ {} const obj = { f1 /* f */ () {}, - f2(/* args */) {}, + f2(/* args */ ) {}, f3() /* returns */ {}, - f4 /* f */ (/* args */) /* returns */ {}, + f4 /* f */ (/* args */ ) /* returns */ {}, }; (function f /* f */ () {})(); -(function f(/* args */) {})(); +(function f(/* args */ ) {})(); (function f() /* returns */ {})(); -(function f /* f */ (/* args */) /* returns */ {})(); +(function f /* f */ (/* args */ ) /* returns */ {})(); class C1 { f /* f */ () {} } class C2 { - f(/* args */) {} + f(/* args */ ) {} } class C3 { f() /* returns */ {} } class C4 { - f /* f */ (/* args */) /* returns */ {} + f /* f */ (/* args */ ) /* returns */ {} } function foo1() diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap index 0736611e4e4..38505fa513b 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: class-property.js --- # Input @@ -19,13 +20,13 @@ class Foo { # Output ```js class Foo { - f(/* ... */) {} + f(/* ... */ ) {} f() /* ... */ {} - f = (/* ... */) => {}; - static f(/* ... */) {} - static f = (/* ... */) => {}; - static f = function (/* ... */) {}; - static f = function f(/* ... */) {}; + f = (/* ... */ ) => {}; + static f(/* ... */ ) {} + static f = (/* ... */ ) => {}; + static f = function (/* ... */ ) {}; + static f = function f(/* ... */ ) {}; } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap index e4832492d40..dfce1d107f4 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: empty_paren_comment.js --- # Input @@ -27,15 +28,15 @@ let f4 = () => doThing(a, /* ... */ b); # Output ```js -let f1 = (/* ... */) => {}; -(function (/* ... */) {})(/* ... */); -function f2(/* ... */) {} +let f1 = (/* ... */ ) => {}; +(function (/* ... */ ) {})(/* ... */); +function f2(/* ... */ ) {} const obj = { - f(/* ... */) {}, - f: (/* ... */) => {}, - f: function (/* ... */) {}, - f: function f(/* ... */) {}, + f(/* ... */ ) {}, + f: (/* ... */ ) => {}, + f: function (/* ... */ ) {}, + f: function f(/* ... */ ) {}, }; f(/* ... */); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap index 3cd4a50a6d7..f8861c89b5a 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap @@ -268,7 +268,7 @@ setTimeout( 500, ); -setTimeout( /* blip */ +setTimeout(/* blip */ function () { thing(); }, 500); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap index 113c2501f11..b6eba177710 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: ignore-2.js --- # Input @@ -45,7 +46,7 @@ function HelloWorld() { a =
; a =
; a =
; -a =
; +a =
; a =
; ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap index 48f4ff48643..4cb0b78c4dc 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap @@ -246,6 +246,7 @@ comments( short3, // More comments + ); differentArgTypes( @@ -268,6 +269,7 @@ moreArgTypes( { name: "Hello World", age: 34 }, oneThing + anotherThing, // Comment + ), ); diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap index c8772dc780f..fc6d844df08 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: empty-method-body.ts --- # Input @@ -27,7 +28,7 @@ class foo1 { // #9367 class Test { - foo(/* 2 */) /* 3 */; + foo(/* 2 */ ) /* 3 */; } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap index e0d481959e7..089e1376c79 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: method_types.ts --- # Input @@ -49,9 +50,9 @@ abstract class Test { # Output ```js interface foo1 { - bar3 /* foo */ (/* baz */); // bat - bar /* foo */ ? /* bar */ (/* baz */) /* bat */; - bar2 /* foo */ (/* baz */) /* bat */; + bar3 /* foo */ (/* baz */ ); // bat + bar /* foo */ ? /* bar */ (/* baz */ ) /* bat */; + bar2 /* foo */ (/* baz */ ) /* bat */; } interface foo2 { @@ -59,7 +60,7 @@ interface foo2 { } interface foo3 { - /* foo */ (/* bar */): /* baz */ string; + /* foo */ (/* bar */ ): /* baz */ string; } interface foo4 { @@ -71,21 +72,21 @@ interface foo5 { } interface foo6 { - /* foo */ new /* bar */ (/* baz */): /* bat */ string; + /* foo */ new /* bar */ (/* baz */ ): /* bat */ string; } -type foo7 = /* foo */ (/* bar */) /* baz */ => void; +type foo7 = /* foo */ (/* bar */ ) /* baz */ => void; type foo8 = /* foo */ (a: /* bar */ string) /* baz */ => void; -let foo9: new /* foo */ (/* bar */) /* baz */ => string; +let foo9: new /* foo */ (/* bar */ ) /* baz */ => string; let foo10: new /* foo */ (a: /* bar */ string) /* baz */ => string; abstract class Test { abstract foo12 /* foo */ (a: /* bar */ string): /* baz */ void; - abstract foo13 /* foo */ (/* bar */) /* baz */; + abstract foo13 /* foo */ (/* bar */ ) /* baz */; } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap index 3ac1a3bd151..9c583d57ddb 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap @@ -1,5 +1,6 @@ --- source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 expression: methods.ts --- # Input @@ -103,7 +104,7 @@ export class Point { */ mismatchedIndentation() {} - inline /* foo*/ (/* bar */) /* baz */ {} + inline /* foo*/ (/* bar */ ) /* baz */ {} noBody(/* comment */ arg); } diff --git a/crates/rome_js_syntax/src/parameters_ext.rs b/crates/rome_js_syntax/src/parameters_ext.rs index ae4a47ce6d2..a6e0f30b457 100644 --- a/crates/rome_js_syntax/src/parameters_ext.rs +++ b/crates/rome_js_syntax/src/parameters_ext.rs @@ -8,4 +8,8 @@ impl JsAnyArrowFunctionParameters { JsAnyArrowFunctionParameters::JsParameters(parameters) => parameters.items().len(), } } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } From 11a205a7ff919bf8847b514f91f8f78384afed00 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 16 Jun 2022 11:05:59 -0300 Subject: [PATCH 13/16] chore: code review and fix regressions --- crates/rome_formatter/src/printed_tokens.rs | 4 +- crates/rome_js_formatter/src/builders.rs | 2 +- .../src/js/expressions/call_arguments.rs | 301 +++++++++--------- .../src/js/lists/call_argument_list.rs | 4 +- crates/rome_js_formatter/src/utils/mod.rs | 3 +- .../tests/specs/js/module/comments.js.snap | 6 +- .../specs/prettier/js/comments/arrow.js.snap | 4 +- .../prettier/js/comments/dangling.js.snap | 4 +- .../js/comments/function-declaration.js.snap | 18 +- .../class-property.js.snap | 12 +- .../empty_paren_comment.js.snap | 14 +- .../js/first-argument-expansion/test.js.snap | 52 ++- .../specs/prettier/js/ignore/ignore-2.js.snap | 2 +- .../js/preserve-line/argument-list.js.snap | 9 +- .../class/empty-method-body.ts.snap | 2 +- .../typescript/comments/method_types.ts.snap | 16 +- .../typescript/comments/methods.ts.snap | 2 +- crates/rome_js_syntax/src/lib.rs | 1 - crates/rome_js_syntax/src/parameters_ext.rs | 15 - crates/rome_js_syntax/src/union_ext.rs | 15 +- crates/rome_rowan/src/syntax/node.rs | 2 +- 21 files changed, 242 insertions(+), 246 deletions(-) delete mode 100644 crates/rome_js_syntax/src/parameters_ext.rs diff --git a/crates/rome_formatter/src/printed_tokens.rs b/crates/rome_formatter/src/printed_tokens.rs index 92b64df6267..bcd8e001546 100644 --- a/crates/rome_formatter/src/printed_tokens.rs +++ b/crates/rome_formatter/src/printed_tokens.rs @@ -36,7 +36,9 @@ impl PrintedTokens { match (descendants.next(), offsets.next()) { (Some(descendant), Some(offset)) => match descendant.text_trimmed_range().start() { descendant_offset if descendant_offset < *offset => { - panic!("token has not been seen by the formatter: {descendant:#?}.\nUse `formatter.format_replaced` if you intentionally remove or replace a token from the formatted output.") + panic!("token has not been seen by the formatter: {descendant:#?}.\ + \nUse `format_replaced` if you want to replace a token from the formatted output.\ + \nUse `format_removed` if you to remove a token from the formatted output") } descendant_offset if descendant_offset > *offset => { panic!("tracked offset {offset:?} doesn't match any token of {root:#?}. Have you passed a token from another tree?"); diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs index cb9d8dcf482..a5fe95404f7 100644 --- a/crates/rome_js_formatter/src/builders.rs +++ b/crates/rome_js_formatter/src/builders.rs @@ -535,7 +535,7 @@ impl<'t> OpenDelimiter<'t> { if !trivia.is_empty() { f.write_elements(trivia)?; - soft_line_break_or_space().fmt(f)?; + soft_line_break().fmt(f)?; } Ok(()) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 95539ab8545..65f7eab7d74 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,16 +1,14 @@ use crate::builders::{format_close_delimiter, format_open_delimiter}; use crate::prelude::*; -use crate::utils::{fmt_arguments_multi_line, is_call_like_expression}; +use crate::utils::{format_arguments_multi_line, is_call_like_expression}; use crate::FormatNodeFields; use rome_formatter::{format_args, write}; -use rome_js_syntax::JsSyntaxKind::JS_EMPTY_STATEMENT; use rome_js_syntax::{ - JsAnyCallArgument, JsAnyExpression, JsAnyFunctionBody, JsArrayExpression, + JsAnyCallArgument, JsAnyExpression, JsAnyFunctionBody, JsAnyStatement, JsArrayExpression, JsArrowFunctionExpression, JsCallArgumentList, JsCallArguments, JsCallArgumentsFields, - JsConditionalExpression, JsFunctionBody, JsFunctionExpression, JsObjectExpression, - JsSyntaxKind, JsSyntaxNode, TsAsExpression, TsReferenceType, TsTypeAssertionExpression, + JsLanguage, JsSyntaxKind, TsReferenceType, }; -use rome_rowan::{AstSeparatedList, SyntaxResult}; +use rome_rowan::{AstSeparatedElement, AstSeparatedList, SyntaxResult}; impl FormatNodeFields for FormatNodeRule { fn fmt_fields(node: &JsCallArguments, f: &mut JsFormatter) -> FormatResult<()> { @@ -23,8 +21,6 @@ impl FormatNodeFields for FormatNodeRule { let l_paren_token = l_paren_token?; let r_paren_token = r_paren_token?; - // we now extracts the formatted version of trivias and tokens of the delimiters - if args.len() == 0 { return write!( f, @@ -37,14 +33,8 @@ impl FormatNodeFields for FormatNodeRule { } // particular formatting for hooks - if is_react_hook_with_deps_array(&args)? { - let mut list = args.elements(); - // SAFETY: the function `is_react_hook_with_deps_array` already checks the presence of the - // first two arguments, so it's safe un unwrap them - let first_argument = list.next().unwrap(); - let second_argument = list.next().unwrap(); - - return write!( + if let Some((first_argument, second_argument)) = is_react_hook_with_deps_array(&args)? { + write!( f, [ l_paren_token.format(), @@ -52,24 +42,22 @@ impl FormatNodeFields for FormatNodeRule { first_argument.trailing_separator().format(), space_token(), second_argument.node().format(), - format_with(|f| { - // we don't want to print the trailing separator, so if it's present, we replace it - // with an empty element - if let Some(separator) = second_argument.trailing_separator()? { - return write!(f, [format_removed(separator)]); - } - - Ok(()) - }), - r_paren_token.format() ] - ); + )?; + + // we don't want to print the trailing separator, so if it's present, we remove it + if let Some(separator) = second_argument.trailing_separator()? { + write!(f, [format_removed(separator)])?; + } + + return write!(f, [r_paren_token.format()]); } // we create open a close delimiters let open_delimiter = format_open_delimiter(&l_paren_token); let close_delimiter = format_close_delimiter(&r_paren_token); + // we now extracts the formatted version of trivias and tokens of the delimiters // tokens on the left let l_leading_trivia = open_delimiter.as_leading_trivia_fmt(); let l_paren = open_delimiter.as_token_fmt(); @@ -118,44 +106,28 @@ impl FormatNodeFields for FormatNodeRule { write!(f, [l_leading_trivia, l_paren, l_trailing_trivia,])?; if should_group_first_argument { - write!( - f, - [format_with(|f| { - // special formatting of the first element - let mut iter = separated.iter(); - // SAFETY: check on the existence of at least one argument are done before - let first = iter.next().unwrap(); - f.join_with(&space_token()) - .entry(&format_with(|f| { - write!( - f, - [group_elements(&format_args![first, expand_parent()])] - ) - })) - .entries(iter) - .finish() - }),] - )?; + // special formatting of the first element + let mut iter = separated.iter(); + // SAFETY: check on the existence of at least one argument are done before + let first = iter.next().unwrap(); + f.join_with(&space_token()) + .entry(&format_with(|f| { + write!(f, [group_elements(&format_args![first, expand_parent()])]) + })) + .entries(iter) + .finish()?; } else { - write!( - f, - [format_with(|f| { - // special formatting of the last element - let mut iter = separated.iter(); - // SAFETY: check on the existence of at least one argument are done before - let last = iter.next_back().unwrap(); - - f.join_with(&space_token()) - .entries(iter) - .entry(&format_with(|f| { - write!( - f, - [group_elements(&format_args![last, expand_parent()])] - ) - })) - .finish() - }),] - )?; + // special formatting of the last element + let mut iter = separated.iter(); + // SAFETY: check on the existence of at least one argument are done before + let last = iter.next_back().unwrap(); + + f.join_with(&space_token()) + .entries(iter) + .entry(&format_with(|f| { + write!(f, [group_elements(&format_args![last, expand_parent()])]) + })) + .finish()?; } write!(f, [r_leading_trivia, r_paren, r_trailing_trivia]) @@ -177,7 +149,7 @@ impl FormatNodeFields for FormatNodeRule { &soft_block_indent(&format_args![ &l_trailing_trivia, format_with(|f| { - fmt_arguments_multi_line(separated.iter(), f) + format_arguments_multi_line(separated.iter(), f) }), &r_leading_trivia, soft_line_break() @@ -199,7 +171,7 @@ impl FormatNodeFields for FormatNodeRule { l_paren, l_trailing_trivia, group_elements(&format_args![format_with(|f| { - fmt_arguments_multi_line(separated.iter(), f) + format_arguments_multi_line(separated.iter(), f) })]), r_leading_trivia, r_paren, @@ -223,7 +195,7 @@ impl FormatNodeFields for FormatNodeRule { FormatSeparatedOptions::default() .with_trailing_separator(TrailingSeparator::Elide), ); - fmt_arguments_multi_line(separated, f) + format_arguments_multi_line(separated, f) }),), r_leading_trivia, r_paren, @@ -270,22 +242,19 @@ fn should_group_first_argument(list: &JsCallArgumentList) -> SyntaxResult Ok(!has_comments && is_function_like && !second_arg_is_function_like - && !could_group_argument(second.syntax(), false)?) + && !could_group_argument(&second, false)?) } /// Checks if the last group requires grouping fn should_group_last_argument(list: &JsCallArgumentList) -> SyntaxResult { let mut iter = list.iter().rev(); - // SAFETY: checked at the beginning of the function let last = iter.next(); let penultimate = iter.next(); if let Some(last) = last { - // SAFETY: guaranteed by the syntax factory - let last = last.unwrap(); + let last = last?; let check_with_penultimate = if let Some(penultimate) = penultimate { - // SAFETY: guaranteed by the syntax factory - let penultimate = penultimate.unwrap(); + let penultimate = penultimate?; (last.syntax().kind() != penultimate.syntax().kind()) && !JsArrayExpression::can_cast(penultimate.syntax().kind()) || !JsArrowFunctionExpression::can_cast(last.syntax().kind()) @@ -294,7 +263,7 @@ fn should_group_last_argument(list: &JsCallArgumentList) -> SyntaxResult { }; Ok(!last.syntax().has_comments_direct() - && could_group_argument(last.syntax(), false)? + && could_group_argument(&last, false)? && check_with_penultimate) } else { Ok(false) @@ -302,77 +271,108 @@ fn should_group_last_argument(list: &JsCallArgumentList) -> SyntaxResult { } /// Checks if the current argument could be grouped -fn could_group_argument(argument: &JsSyntaxNode, is_arrow_recursion: bool) -> SyntaxResult { - let result = if let Some(object_expression) = JsObjectExpression::cast(argument.clone()) { - object_expression.members().len() > 0 - || object_expression.syntax().has_comments_at_the_edges() - } else if let Some(array_expression) = JsArrayExpression::cast(argument.clone()) { - array_expression.elements().len() > 0 - || array_expression.syntax().has_comments_at_the_edges() - } else if let Some(assertion_expression) = TsTypeAssertionExpression::cast(argument.clone()) { - could_group_argument(assertion_expression.expression()?.syntax(), false)? - } else if let Some(as_expression) = TsAsExpression::cast(argument.clone()) { - could_group_argument(as_expression.expression()?.syntax(), false)? - } else if let Some(arrow_function) = JsArrowFunctionExpression::cast(argument.clone()) { - let body = arrow_function.body()?; - let return_type_annotation = arrow_function.return_type_annotation(); - - // Handles cases like: - // - // app.get("/", (req, res): void => { - // res.send("Hello World!"); - // }); - // - // export class Thing implements OtherThing { - // do: (type: Type) => Provider = memoize( - // (type: ObjectType): Provider => {} - // ); - // } - let can_group_type = - !return_type_annotation - .and_then(|rty| rty.ty().ok()) - .map_or(false, |any_type| { - TsReferenceType::can_cast(any_type.syntax().kind()) - || JsFunctionBody::cast(body.syntax().clone()).map_or( - true, - |function_body| { +fn could_group_argument( + argument: &JsAnyCallArgument, + is_arrow_recursion: bool, +) -> SyntaxResult { + let result = if let JsAnyCallArgument::JsAnyExpression(argument) = argument { + if let JsAnyExpression::JsObjectExpression(object_expression) = argument { + object_expression.members().len() > 0 + || object_expression + .syntax() + .first_or_last_token_have_comments() + } else if let JsAnyExpression::JsArrayExpression(array_expression) = argument { + array_expression.elements().len() > 0 + || array_expression + .syntax() + .first_or_last_token_have_comments() + } else if let JsAnyExpression::TsTypeAssertionExpression(assertion_expression) = argument { + could_group_argument( + &JsAnyCallArgument::JsAnyExpression(assertion_expression.expression()?), + false, + )? + } else if let JsAnyExpression::TsAsExpression(as_expression) = argument { + could_group_argument( + &JsAnyCallArgument::JsAnyExpression(as_expression.expression()?), + false, + )? + } else if let JsAnyExpression::JsArrowFunctionExpression(arrow_function) = argument { + let body = arrow_function.body()?; + let return_type_annotation = arrow_function.return_type_annotation(); + + // Handles cases like: + // + // app.get("/", (req, res): void => { + // res.send("Hello World!"); + // }); + // + // export class Thing implements OtherThing { + // do: (type: Type) => Provider = memoize( + // (type: ObjectType): Provider => {} + // ); + // } + let can_group_type = + !return_type_annotation + .and_then(|rty| rty.ty().ok()) + .map_or(false, |any_type| { + TsReferenceType::can_cast(any_type.syntax().kind()) + || if let JsAnyFunctionBody::JsFunctionBody(function_body) = &body { function_body .statements() .iter() - .any(|st| st.syntax().kind() == JS_EMPTY_STATEMENT) - }, - ) - }); - - let body_is_delimited = matches!( - body, - JsAnyFunctionBody::JsFunctionBody(_) - | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsObjectExpression(_)) - | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsArrayExpression(_)) - ); - - if let JsAnyFunctionBody::JsAnyExpression(any_expression) = body.clone() { - let is_nested_arrow_function = - JsArrowFunctionExpression::cast(any_expression.syntax().clone()) - .and_then(|arrow_function_expression| { + .any(|st| matches!(st, JsAnyStatement::JsEmptyStatement(_))) + } else { + true + } + }); + + let body_is_delimited = matches!( + body, + JsAnyFunctionBody::JsFunctionBody(_) + | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsObjectExpression(_)) + | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsArrayExpression(_)) + ); + + if let JsAnyFunctionBody::JsAnyExpression(any_expression) = body.clone() { + let is_nested_arrow_function = + if let JsAnyExpression::JsArrowFunctionExpression(arrow_function_expression) = + &any_expression + { arrow_function_expression .body() .ok() - .and_then(|body| could_group_argument(body.syntax(), true).ok()) - }) - .unwrap_or(false); - - body_is_delimited - && is_nested_arrow_function - && can_group_type - && (!is_arrow_recursion - && (is_call_like_expression(&any_expression) - || JsConditionalExpression::can_cast(body.syntax().kind()))) + .and_then(|body| body.as_js_any_expression().cloned()) + .and_then(|body| { + could_group_argument( + &JsAnyCallArgument::JsAnyExpression(body.clone()), + true, + ) + .ok() + }) + .unwrap_or(false) + } else { + false + }; + + body_is_delimited + && is_nested_arrow_function + && can_group_type + && (!is_arrow_recursion + && (is_call_like_expression(&any_expression) + || matches!( + body, + JsAnyFunctionBody::JsAnyExpression( + JsAnyExpression::JsConditionalExpression(_) + ) + ))) + } else { + body_is_delimited && can_group_type + } } else { - body_is_delimited && can_group_type + matches!(argument, JsAnyExpression::JsFunctionExpression(_)) } } else { - JsFunctionExpression::can_cast(argument.kind()) + false }; Ok(result) @@ -383,15 +383,24 @@ fn could_group_argument(argument: &JsSyntaxNode, is_arrow_recursion: bool) -> Sy /// ```js /// useMemo(() => {}, []) /// ``` -fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult { +fn is_react_hook_with_deps_array( + node: &JsCallArgumentList, +) -> SyntaxResult< + Option<( + AstSeparatedElement, + AstSeparatedElement, + )>, +> { let result = if node.len() == 2 { let mut iter = node.elements(); + let first_element = iter.next().unwrap(); + let second_element = iter.next().unwrap(); // SAFETY: covered by the previous if check - let first = iter.next().unwrap().into_node()?; - let second = iter.next().unwrap().into_node()?; + let first_node = first_element.node()?; + let second_node = second_element.node()?; let first_node_matches = if let JsAnyCallArgument::JsAnyExpression( JsAnyExpression::JsArrowFunctionExpression(arrow_function), - ) = first + ) = first_node { let no_parameters = arrow_function.parameters()?.is_empty(); let body = arrow_function.body()?; @@ -402,11 +411,15 @@ fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult for FormatJsCallArgumentList { FormatSeparatedOptions::default() .with_trailing_separator(TrailingSeparator::Elide), ); - fmt_arguments_multi_line(separated, f) + format_arguments_multi_line(separated, f) })))] ) } diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 66c277cd778..cbb28b2b080 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -526,13 +526,12 @@ impl Format for FormatMemberName { } /// This function is in charge to format the call arguments. -pub(crate) fn fmt_arguments_multi_line, I>( +pub(crate) fn format_arguments_multi_line, I>( separated: I, f: &mut JsFormatter, ) -> FormatResult<()> where I: Iterator, - S: std::fmt::Debug, { let mut iterator = separated.peekable(); let mut join_with = f.join_with(soft_line_break_or_space()); diff --git a/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap b/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap index eeaca33d598..74e0e98b62e 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/comments.js.snap @@ -120,9 +120,9 @@ expression( "something", ); -const array0 = [/*0*/ ]; -const array1 = [/*0*/ , /*1*/]; -const array2 = [/*0*/ , /*1*/ , /*2*/]; +const array0 = [/*0*/]; +const array1 = [/*0*/, /*1*/]; +const array2 = [/*0*/, /*1*/ , /*2*/]; /* block comment */ statement(); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap index a99351cbe0f..e3959dd29aa 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap @@ -13,9 +13,9 @@ const fn2 = (/*event, data*/) => doSomething(anything); # Output ```js -const fn = (/*event, data*/ ) => doSomething(); +const fn = (/*event, data*/) => doSomething(); -const fn2 = (/*event, data*/ ) => doSomething(anything); +const fn2 = (/*event, data*/) => doSomething(anything); ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap index bc0fa442b88..798915cffe5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap @@ -21,11 +21,11 @@ export /* dangling */{}; # Output ```js -var a = {/* dangling */ }; +var a = {/* dangling */}; var b = { // dangling }; -var b = [/* dangling */ ]; +var b = [/* dangling */]; function d() { /* dangling */ } diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap index 3d7ebe3eeaf..a88357459ca 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap @@ -71,7 +71,7 @@ function foo4() { # Output ```js -function a(/* comment */ ) {} // comment +function a(/* comment */) {} // comment function b() {} // comment function c(/* comment */ argA, argB, argC) {} // comment call((/*object*/ row) => {}); @@ -83,9 +83,9 @@ KEYPAD_NUMBERS.map( ); function f1 /* f */ () {} -function f2(/* args */ ) {} +function f2(/* args */) {} function f3() /* returns */ {} -function f4 /* f */ (/* args */ ) /* returns */ {} +function f4 /* f */ (/* args */) /* returns */ {} function f5 /* f */ (/* a */ a) {} function f6 /* f */ (a /* a */) {} @@ -93,27 +93,27 @@ function f7 /* f */ (/* a */ a) /* returns */ {} const obj = { f1 /* f */ () {}, - f2(/* args */ ) {}, + f2(/* args */) {}, f3() /* returns */ {}, - f4 /* f */ (/* args */ ) /* returns */ {}, + f4 /* f */ (/* args */) /* returns */ {}, }; (function f /* f */ () {})(); -(function f(/* args */ ) {})(); +(function f(/* args */) {})(); (function f() /* returns */ {})(); -(function f /* f */ (/* args */ ) /* returns */ {})(); +(function f /* f */ (/* args */) /* returns */ {})(); class C1 { f /* f */ () {} } class C2 { - f(/* args */ ) {} + f(/* args */) {} } class C3 { f() /* returns */ {} } class C4 { - f /* f */ (/* args */ ) /* returns */ {} + f /* f */ (/* args */) /* returns */ {} } function foo1() diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap index 38505fa513b..163f9b5df7f 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/class-property.js.snap @@ -20,13 +20,13 @@ class Foo { # Output ```js class Foo { - f(/* ... */ ) {} + f(/* ... */) {} f() /* ... */ {} - f = (/* ... */ ) => {}; - static f(/* ... */ ) {} - static f = (/* ... */ ) => {}; - static f = function (/* ... */ ) {}; - static f = function f(/* ... */ ) {}; + f = (/* ... */) => {}; + static f(/* ... */) {} + static f = (/* ... */) => {}; + static f = function (/* ... */) {}; + static f = function f(/* ... */) {}; } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap index dfce1d107f4..c0d78d2e6fd 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap @@ -28,15 +28,15 @@ let f4 = () => doThing(a, /* ... */ b); # Output ```js -let f1 = (/* ... */ ) => {}; -(function (/* ... */ ) {})(/* ... */); -function f2(/* ... */ ) {} +let f1 = (/* ... */) => {}; +(function (/* ... */) {})(/* ... */); +function f2(/* ... */) {} const obj = { - f(/* ... */ ) {}, - f: (/* ... */ ) => {}, - f: function (/* ... */ ) {}, - f: function f(/* ... */ ) {}, + f(/* ... */) {}, + f: (/* ... */) => {}, + f: function (/* ... */) {}, + f: function f(/* ... */) {}, }; f(/* ... */); diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap index f8861c89b5a..b00c3cf1d56 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap @@ -159,12 +159,9 @@ func(() => { thing(); }, /regex.*?/); -func( - () => { - thing(); - }, - 1 ? 2 : 3, -); +func(() => { + thing(); +}, 1 ? 2 : 3); func( function () { @@ -173,34 +170,25 @@ func( 1 ? 2 : 3, ); -func( - () => { - thing(); - }, - something() ? someOtherThing() : somethingElse(true, 0), -); +func(() => { + thing(); +}, something() ? someOtherThing() : somethingElse(true, 0)); -func( - () => { - thing(); - }, - something( - longArgumentName, - anotherLongArgumentName, - ) ? someOtherThing() : somethingElse(true, 0), -); +func(() => { + thing(); +}, something( + longArgumentName, + anotherLongArgumentName, +) ? someOtherThing() : somethingElse(true, 0)); -func( - () => { - thing(); - }, - something( - longArgumentName, - anotherLongArgumentName, - anotherLongArgumentName, - anotherLongArgumentName, - ) ? someOtherThing() : somethingElse(true, 0), -); +func(() => { + thing(); +}, something( + longArgumentName, + anotherLongArgumentName, + anotherLongArgumentName, + anotherLongArgumentName, +) ? someOtherThing() : somethingElse(true, 0)); compose( (a) => { diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap index b6eba177710..732fce92dfb 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap @@ -46,7 +46,7 @@ function HelloWorld() { a =
; a =
; a =
; -a =
; +a =
; a =
; ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap index 4cb0b78c4dc..beb8cbce014 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/argument-list.js.snap @@ -249,12 +249,9 @@ comments( ); -differentArgTypes( - () => { - return true; - }, - isTrue ? doSomething() : 12, -); +differentArgTypes(() => { + return true; +}, isTrue ? doSomething() : 12); moreArgTypes( [1, 2, 3], diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap index fc6d844df08..eeb65571a75 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap @@ -28,7 +28,7 @@ class foo1 { // #9367 class Test { - foo(/* 2 */ ) /* 3 */; + foo(/* 2 */) /* 3 */; } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap index 089e1376c79..59dec9b5db6 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap @@ -50,9 +50,9 @@ abstract class Test { # Output ```js interface foo1 { - bar3 /* foo */ (/* baz */ ); // bat - bar /* foo */ ? /* bar */ (/* baz */ ) /* bat */; - bar2 /* foo */ (/* baz */ ) /* bat */; + bar3 /* foo */ (/* baz */); // bat + bar /* foo */ ? /* bar */ (/* baz */) /* bat */; + bar2 /* foo */ (/* baz */) /* bat */; } interface foo2 { @@ -60,7 +60,7 @@ interface foo2 { } interface foo3 { - /* foo */ (/* bar */ ): /* baz */ string; + /* foo */ (/* bar */): /* baz */ string; } interface foo4 { @@ -72,21 +72,21 @@ interface foo5 { } interface foo6 { - /* foo */ new /* bar */ (/* baz */ ): /* bat */ string; + /* foo */ new /* bar */ (/* baz */): /* bat */ string; } -type foo7 = /* foo */ (/* bar */ ) /* baz */ => void; +type foo7 = /* foo */ (/* bar */) /* baz */ => void; type foo8 = /* foo */ (a: /* bar */ string) /* baz */ => void; -let foo9: new /* foo */ (/* bar */ ) /* baz */ => string; +let foo9: new /* foo */ (/* bar */) /* baz */ => string; let foo10: new /* foo */ (a: /* bar */ string) /* baz */ => string; abstract class Test { abstract foo12 /* foo */ (a: /* bar */ string): /* baz */ void; - abstract foo13 /* foo */ (/* bar */ ) /* baz */; + abstract foo13 /* foo */ (/* bar */) /* baz */; } ``` diff --git a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap index 9c583d57ddb..a43c17d76c5 100644 --- a/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap +++ b/crates/rome_js_formatter/tests/specs/prettier/typescript/comments/methods.ts.snap @@ -104,7 +104,7 @@ export class Point { */ mismatchedIndentation() {} - inline /* foo*/ (/* bar */ ) /* baz */ {} + inline /* foo*/ (/* bar */) /* baz */ {} noBody(/* comment */ arg); } diff --git a/crates/rome_js_syntax/src/lib.rs b/crates/rome_js_syntax/src/lib.rs index 9b2b01b8227..4848fe4d00a 100644 --- a/crates/rome_js_syntax/src/lib.rs +++ b/crates/rome_js_syntax/src/lib.rs @@ -7,7 +7,6 @@ mod generated; pub mod expr_ext; pub mod modifier_ext; pub mod numbers; -mod parameters_ext; pub mod source_type; pub mod stmt_ext; pub mod suppression; diff --git a/crates/rome_js_syntax/src/parameters_ext.rs b/crates/rome_js_syntax/src/parameters_ext.rs deleted file mode 100644 index a6e0f30b457..00000000000 --- a/crates/rome_js_syntax/src/parameters_ext.rs +++ /dev/null @@ -1,15 +0,0 @@ -use crate::JsAnyArrowFunctionParameters; -use rome_rowan::AstSeparatedList; - -impl JsAnyArrowFunctionParameters { - pub fn len(&self) -> usize { - match self { - JsAnyArrowFunctionParameters::JsAnyBinding(_) => 1, - JsAnyArrowFunctionParameters::JsParameters(parameters) => parameters.items().len(), - } - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } -} diff --git a/crates/rome_js_syntax/src/union_ext.rs b/crates/rome_js_syntax/src/union_ext.rs index 8868b901cfc..7cf1a7867bc 100644 --- a/crates/rome_js_syntax/src/union_ext.rs +++ b/crates/rome_js_syntax/src/union_ext.rs @@ -4,7 +4,7 @@ use crate::{ TsAnyVariableAnnotation, TsImplementsClause, TsReturnTypeAnnotation, TsTypeAnnotation, TsTypeParameters, }; -use rome_rowan::SyntaxResult; +use rome_rowan::{AstSeparatedList, SyntaxResult}; impl JsAnyClass { pub fn abstract_token(&self) -> Option { @@ -220,3 +220,16 @@ impl TsAnyPropertyAnnotation { } } } + +impl JsAnyArrowFunctionParameters { + pub fn len(&self) -> usize { + match self { + JsAnyArrowFunctionParameters::JsAnyBinding(_) => 1, + JsAnyArrowFunctionParameters::JsParameters(parameters) => parameters.items().len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} diff --git a/crates/rome_rowan/src/syntax/node.rs b/crates/rome_rowan/src/syntax/node.rs index 83dc39d2357..471d00f0200 100644 --- a/crates/rome_rowan/src/syntax/node.rs +++ b/crates/rome_rowan/src/syntax/node.rs @@ -474,7 +474,7 @@ impl SyntaxNode { /// It checks if the current node has comments at the edges: /// if first or last tokens contain comments (leading or trailing) - pub fn has_comments_at_the_edges(&self) -> bool { + pub fn first_or_last_token_have_comments(&self) -> bool { self.first_token_has_comments() || self.last_token_has_comments() } From 4d0e0fb61985d5fcaab0ae56e6e299c8dc3c3239 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 16 Jun 2022 11:11:38 -0300 Subject: [PATCH 14/16] chore: renaming functions --- crates/rome_js_formatter/src/builders.rs | 22 +++++++++---------- .../src/js/expressions/call_arguments.rs | 12 +++++----- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs index a5fe95404f7..3d8019a396f 100644 --- a/crates/rome_js_formatter/src/builders.rs +++ b/crates/rome_js_formatter/src/builders.rs @@ -413,14 +413,14 @@ impl Format for FormatDelimited<'_, '_> { let open_delimiter = format_open_delimiter(open_token); let close_delimiter = format_close_delimiter(close_token); - open_delimiter.as_leading_trivia_fmt().fmt(f)?; + open_delimiter.format_leading_trivia().fmt(f)?; - let open_token_trailing_trivia = open_delimiter.as_trailing_trivia_fmt(); + let open_token_trailing_trivia = open_delimiter.format_trailing_trivia(); - let close_token_leading_trivia = close_delimiter.as_leading_trivia_fmt(); + let close_token_leading_trivia = close_delimiter.format_leading_trivia(); let delimited = format_with(|f| { - open_delimiter.as_token_fmt().fmt(f)?; + open_delimiter.format_token().fmt(f)?; let format_content = format_with(|f| f.write_fmt(Arguments::from(content))); @@ -463,7 +463,7 @@ impl Format for FormatDelimited<'_, '_> { } }; - close_delimiter.as_token_fmt().fmt(f) + close_delimiter.format_token().fmt(f) }); let _grouped = match mode { @@ -519,12 +519,12 @@ impl<'t> OpenDelimiter<'t> { } /// It extracts the formatted leading trivia of the token, without writing it in the buffer - pub(crate) fn as_leading_trivia_fmt(&self) -> impl Format + 't { + pub(crate) fn format_leading_trivia(&self) -> impl Format + 't { format_leading_trivia(self.open_token) } /// It extracts the formatted trailing trivia of the token, without writing it in the buffer - pub(crate) fn as_trailing_trivia_fmt(&self) -> impl Format + 't { + pub(crate) fn format_trailing_trivia(&self) -> impl Format + 't { format_with(|f| { // Not really interested in the pre-amble, but want to know if it was written let mut buffer = VecBuffer::new(f.state_mut()); @@ -543,7 +543,7 @@ impl<'t> OpenDelimiter<'t> { } /// It extracts the formatted token, without writing it in the buffer - pub(crate) fn as_token_fmt(&self) -> impl Format + 't { + pub(crate) fn format_token(&self) -> impl Format + 't { format_with(|f| { f.state_mut().track_token(self.open_token); write!(f, [format_trimmed_token(self.open_token)]) @@ -561,12 +561,12 @@ impl<'t> CloseDelimiter<'t> { } /// It extracts the formatted leading trivia of the token, without writing it in the buffer - pub(crate) fn as_trailing_trivia_fmt(&self) -> impl Format + 't { + pub(crate) fn format_trailing_trivia(&self) -> impl Format + 't { format_trailing_trivia(self.close_token) } /// It extracts the formatted trailing trivia of the token, without writing it in the buffer - pub(crate) fn as_leading_trivia_fmt(&self) -> impl Format + 't { + pub(crate) fn format_leading_trivia(&self) -> impl Format + 't { format_with(|f| { let mut buffer = PreambleBuffer::new(f, soft_line_break_or_space()); @@ -575,7 +575,7 @@ impl<'t> CloseDelimiter<'t> { } /// It extracts the formatted token, without writing it in the buffer - pub(crate) fn as_token_fmt(&self) -> impl Format + 't { + pub(crate) fn format_token(&self) -> impl Format + 't { format_with(|f| { f.state_mut().track_token(self.close_token); write!(f, [format_trimmed_token(self.close_token)]) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 65f7eab7d74..5a47f991313 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -59,14 +59,14 @@ impl FormatNodeFields for FormatNodeRule { // we now extracts the formatted version of trivias and tokens of the delimiters // tokens on the left - let l_leading_trivia = open_delimiter.as_leading_trivia_fmt(); - let l_paren = open_delimiter.as_token_fmt(); - let l_trailing_trivia = open_delimiter.as_trailing_trivia_fmt(); + let l_leading_trivia = open_delimiter.format_leading_trivia(); + let l_paren = open_delimiter.format_token(); + let l_trailing_trivia = open_delimiter.format_trailing_trivia(); // tokens on the right - let r_leading_trivia = close_delimiter.as_leading_trivia_fmt(); - let r_paren = close_delimiter.as_token_fmt(); - let r_trailing_trivia = close_delimiter.as_trailing_trivia_fmt(); + let r_leading_trivia = close_delimiter.format_leading_trivia(); + let r_paren = close_delimiter.format_token(); + let r_trailing_trivia = close_delimiter.format_trailing_trivia(); let should_group_first_argument = should_group_first_argument(&args)?; let should_group_last_argument = should_group_last_argument(&args)?; From 23be09498eae3bf712f2c2e91039e9252d173f3b Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 16 Jun 2022 11:15:24 -0300 Subject: [PATCH 15/16] chore: clippy --- .../src/js/expressions/call_arguments.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 5a47f991313..6118b42948b 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -344,7 +344,7 @@ fn could_group_argument( .and_then(|body| body.as_js_any_expression().cloned()) .and_then(|body| { could_group_argument( - &JsAnyCallArgument::JsAnyExpression(body.clone()), + &JsAnyCallArgument::JsAnyExpression(body), true, ) .ok() @@ -378,19 +378,16 @@ fn could_group_argument( Ok(result) } +type HookArgs = ( + AstSeparatedElement, + AstSeparatedElement, +); /// This function is used to check if the code is a hook-like code: /// /// ```js /// useMemo(() => {}, []) /// ``` -fn is_react_hook_with_deps_array( - node: &JsCallArgumentList, -) -> SyntaxResult< - Option<( - AstSeparatedElement, - AstSeparatedElement, - )>, -> { +fn is_react_hook_with_deps_array(node: &JsCallArgumentList) -> SyntaxResult> { let result = if node.len() == 2 { let mut iter = node.elements(); let first_element = iter.next().unwrap(); From 9657acb2ca32da422eed06a2f59073a5cdd686fa Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 16 Jun 2022 12:20:22 -0300 Subject: [PATCH 16/16] chore: code review --- crates/rome_js_formatter/src/builders.rs | 2 +- .../src/js/expressions/call_arguments.rs | 188 +++++++++--------- .../src/js/lists/call_argument_list.rs | 6 +- crates/rome_js_formatter/src/separated.rs | 8 +- crates/rome_js_formatter/src/utils/mod.rs | 2 +- .../tests/specs/js/module/call_expression.js | 11 +- .../specs/js/module/call_expression.js.snap | 18 ++ 7 files changed, 136 insertions(+), 99 deletions(-) diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs index 3d8019a396f..b4c979a6d51 100644 --- a/crates/rome_js_formatter/src/builders.rs +++ b/crates/rome_js_formatter/src/builders.rs @@ -568,7 +568,7 @@ impl<'t> CloseDelimiter<'t> { /// It extracts the formatted trailing trivia of the token, without writing it in the buffer pub(crate) fn format_leading_trivia(&self) -> impl Format + 't { format_with(|f| { - let mut buffer = PreambleBuffer::new(f, soft_line_break_or_space()); + let mut buffer = PreambleBuffer::new(f, soft_line_break()); write!(buffer, [format_leading_trivia(self.close_token,)]) }) diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index 6118b42948b..a6bb65bbed4 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,6 +1,6 @@ use crate::builders::{format_close_delimiter, format_open_delimiter}; use crate::prelude::*; -use crate::utils::{format_arguments_multi_line, is_call_like_expression}; +use crate::utils::{is_call_like_expression, write_arguments_multi_line}; use crate::FormatNodeFields; use rome_formatter::{format_args, write}; use rome_js_syntax::{ @@ -81,7 +81,7 @@ impl FormatNodeFields for FormatNodeRule { .format_separated(JsSyntaxKind::COMMA) .with_options( FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), + .with_trailing_separator(TrailingSeparator::Omit), ) .map(|e| e.memoized()) .collect(); @@ -112,7 +112,7 @@ impl FormatNodeFields for FormatNodeRule { let first = iter.next().unwrap(); f.join_with(&space_token()) .entry(&format_with(|f| { - write!(f, [group_elements(&format_args![first, expand_parent()])]) + write!(f, [&format_args![first, expand_parent()]]) })) .entries(iter) .finish()?; @@ -125,7 +125,7 @@ impl FormatNodeFields for FormatNodeRule { f.join_with(&space_token()) .entries(iter) .entry(&format_with(|f| { - write!(f, [group_elements(&format_args![last, expand_parent()])]) + write!(f, [&format_args![last, expand_parent()]]) })) .finish()?; } @@ -149,7 +149,7 @@ impl FormatNodeFields for FormatNodeRule { &soft_block_indent(&format_args![ &l_trailing_trivia, format_with(|f| { - format_arguments_multi_line(separated.iter(), f) + write_arguments_multi_line(separated.iter(), f) }), &r_leading_trivia, soft_line_break() @@ -171,7 +171,7 @@ impl FormatNodeFields for FormatNodeRule { l_paren, l_trailing_trivia, group_elements(&format_args![format_with(|f| { - format_arguments_multi_line(separated.iter(), f) + write_arguments_multi_line(separated.iter(), f) })]), r_leading_trivia, r_paren, @@ -193,9 +193,9 @@ impl FormatNodeFields for FormatNodeRule { let separated = args.format_separated(JsSyntaxKind::COMMA).with_options( FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), + .with_trailing_separator(TrailingSeparator::Omit), ); - format_arguments_multi_line(separated, f) + write_arguments_multi_line(separated, f) }),), r_leading_trivia, r_paren, @@ -276,45 +276,49 @@ fn could_group_argument( is_arrow_recursion: bool, ) -> SyntaxResult { let result = if let JsAnyCallArgument::JsAnyExpression(argument) = argument { - if let JsAnyExpression::JsObjectExpression(object_expression) = argument { - object_expression.members().len() > 0 - || object_expression - .syntax() - .first_or_last_token_have_comments() - } else if let JsAnyExpression::JsArrayExpression(array_expression) = argument { - array_expression.elements().len() > 0 - || array_expression - .syntax() - .first_or_last_token_have_comments() - } else if let JsAnyExpression::TsTypeAssertionExpression(assertion_expression) = argument { - could_group_argument( - &JsAnyCallArgument::JsAnyExpression(assertion_expression.expression()?), - false, - )? - } else if let JsAnyExpression::TsAsExpression(as_expression) = argument { - could_group_argument( + match argument { + JsAnyExpression::JsObjectExpression(object_expression) => { + object_expression.members().len() > 0 + || object_expression + .syntax() + .first_or_last_token_have_comments() + } + + JsAnyExpression::JsArrayExpression(array_expression) => { + array_expression.elements().len() > 0 + || array_expression + .syntax() + .first_or_last_token_have_comments() + } + JsAnyExpression::TsTypeAssertionExpression(assertion_expression) => { + could_group_argument( + &JsAnyCallArgument::JsAnyExpression(assertion_expression.expression()?), + false, + )? + } + + JsAnyExpression::TsAsExpression(as_expression) => could_group_argument( &JsAnyCallArgument::JsAnyExpression(as_expression.expression()?), false, - )? - } else if let JsAnyExpression::JsArrowFunctionExpression(arrow_function) = argument { - let body = arrow_function.body()?; - let return_type_annotation = arrow_function.return_type_annotation(); - - // Handles cases like: - // - // app.get("/", (req, res): void => { - // res.send("Hello World!"); - // }); - // - // export class Thing implements OtherThing { - // do: (type: Type) => Provider = memoize( - // (type: ObjectType): Provider => {} - // ); - // } - let can_group_type = - !return_type_annotation - .and_then(|rty| rty.ty().ok()) - .map_or(false, |any_type| { + )?, + JsAnyExpression::JsArrowFunctionExpression(arrow_function) => { + let body = arrow_function.body()?; + let return_type_annotation = arrow_function.return_type_annotation(); + + // Handles cases like: + // + // app.get("/", (req, res): void => { + // res.send("Hello World!"); + // }); + // + // export class Thing implements OtherThing { + // do: (type: Type) => Provider = memoize( + // (type: ObjectType): Provider => {} + // ); + // } + let can_group_type = !return_type_annotation.and_then(|rty| rty.ty().ok()).map_or( + false, + |any_type| { TsReferenceType::can_cast(any_type.syntax().kind()) || if let JsAnyFunctionBody::JsFunctionBody(function_body) = &body { function_body @@ -324,52 +328,58 @@ fn could_group_argument( } else { true } - }); - - let body_is_delimited = matches!( - body, - JsAnyFunctionBody::JsFunctionBody(_) - | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsObjectExpression(_)) - | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsArrayExpression(_)) - ); - - if let JsAnyFunctionBody::JsAnyExpression(any_expression) = body.clone() { - let is_nested_arrow_function = - if let JsAnyExpression::JsArrowFunctionExpression(arrow_function_expression) = - &any_expression - { - arrow_function_expression - .body() - .ok() - .and_then(|body| body.as_js_any_expression().cloned()) - .and_then(|body| { - could_group_argument( - &JsAnyCallArgument::JsAnyExpression(body), - true, - ) + }, + ); + + let body_is_delimited = matches!( + body, + JsAnyFunctionBody::JsFunctionBody(_) + | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsObjectExpression( + _ + )) + | JsAnyFunctionBody::JsAnyExpression(JsAnyExpression::JsArrayExpression(_)) + ); + + if let JsAnyFunctionBody::JsAnyExpression(any_expression) = body.clone() { + let is_nested_arrow_function = + if let JsAnyExpression::JsArrowFunctionExpression( + arrow_function_expression, + ) = &any_expression + { + arrow_function_expression + .body() .ok() - }) - .unwrap_or(false) - } else { - false - }; - - body_is_delimited - && is_nested_arrow_function - && can_group_type - && (!is_arrow_recursion - && (is_call_like_expression(&any_expression) - || matches!( - body, - JsAnyFunctionBody::JsAnyExpression( - JsAnyExpression::JsConditionalExpression(_) - ) - ))) - } else { - body_is_delimited && can_group_type + .and_then(|body| body.as_js_any_expression().cloned()) + .and_then(|body| { + could_group_argument( + &JsAnyCallArgument::JsAnyExpression(body), + true, + ) + .ok() + }) + .unwrap_or(false) + } else { + false + }; + + body_is_delimited + && is_nested_arrow_function + && can_group_type + && (!is_arrow_recursion + && (is_call_like_expression(&any_expression) + || matches!( + body, + JsAnyFunctionBody::JsAnyExpression( + JsAnyExpression::JsConditionalExpression(_) + ) + ))) + } else { + body_is_delimited && can_group_type + } } - } else { - matches!(argument, JsAnyExpression::JsFunctionExpression(_)) + + JsAnyExpression::JsFunctionExpression(_) => true, + _ => false, } } else { false diff --git a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs index ee09fc5c014..718cf211855 100644 --- a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs +++ b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs @@ -1,6 +1,6 @@ use crate::generated::FormatJsCallArgumentList; use crate::prelude::*; -use crate::utils::format_arguments_multi_line; +use crate::utils::write_arguments_multi_line; use rome_formatter::write; use rome_js_syntax::{JsCallArgumentList, JsSyntaxKind}; @@ -17,9 +17,9 @@ impl FormatRule for FormatJsCallArgumentList { [&group_elements(&soft_block_indent(&format_with(|f| { let separated = node.format_separated(JsSyntaxKind::COMMA).with_options( FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Elide), + .with_trailing_separator(TrailingSeparator::Omit), ); - format_arguments_multi_line(separated, f) + write_arguments_multi_line(separated, f) })))] ) } diff --git a/crates/rome_js_formatter/src/separated.rs b/crates/rome_js_formatter/src/separated.rs index 424b32399b5..b8de05eed04 100644 --- a/crates/rome_js_formatter/src/separated.rs +++ b/crates/rome_js_formatter/src/separated.rs @@ -47,7 +47,7 @@ where // A trailing separator was present where it wasn't allowed, opt out of formatting return Err(FormatError::SyntaxError); } - TrailingSeparator::Elide => { + TrailingSeparator::Omit => { write!(f, [format_removed(separator)])?; } } @@ -66,7 +66,7 @@ where TrailingSeparator::Mandatory => { format_inserted(self.separator).fmt(f)?; } - TrailingSeparator::Elide | TrailingSeparator::Disallowed => { /* no op */ } + TrailingSeparator::Omit | TrailingSeparator::Disallowed => { /* no op */ } } } else { unreachable!( @@ -174,8 +174,8 @@ pub enum TrailingSeparator { Mandatory, /// A trailing separator might be present, but the consumer - /// decided to remove it with an [rome_formatter::empty_element] - Elide, + /// decides to remove it + Omit, } impl Default for TrailingSeparator { diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index cbb28b2b080..04bea9d6a36 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -526,7 +526,7 @@ impl Format for FormatMemberName { } /// This function is in charge to format the call arguments. -pub(crate) fn format_arguments_multi_line, I>( +pub(crate) fn write_arguments_multi_line, I>( separated: I, f: &mut JsFormatter, ) -> FormatResult<()> diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js index b71bb6a3a01..80ae11d0e8b 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js @@ -28,4 +28,13 @@ test.something(t => { t.true() }, context => { context.flush() -}) \ No newline at end of file +}) + +// trailing separator omitted +test.expect(t => { + t.true(a) +}, false,) + +test.expect(t => { + t.true(a) +}, false, /* something */) \ No newline at end of file diff --git a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap index ce911cd0a39..63eb33ad4a1 100644 --- a/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap +++ b/crates/rome_js_formatter/tests/specs/js/module/call_expression.js.snap @@ -35,6 +35,15 @@ test.something(t => { }, context => { context.flush() }) + +// trailing separator omitted +test.expect(t => { + t.true(a) +}, false,) + +test.expect(t => { + t.true(a) +}, false, /* something */) ============================= # Outputs ## Output 1 @@ -71,3 +80,12 @@ test.something( }, ); +// trailing separator omitted +test.expect((t) => { + t.true(a); +}, false); + +test.expect((t) => { + t.true(a); +}, false /* something */); +