From 5a3e8df1fc00ed6e4f90091193f64d847e5bb937 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Mon, 30 May 2022 07:53:02 +0200 Subject: [PATCH 01/35] refactor(formatter): `format` and `write` macros --- crates/rome_formatter/src/arguments.rs | 108 ++ crates/rome_formatter/src/buffer.rs | 233 +++ crates/rome_formatter/src/builders.rs | 1413 +++++++++++++++- crates/rome_formatter/src/format_element.rs | 1484 +++-------------- .../rome_formatter/src/format_extensions.rs | 290 ++-- crates/rome_formatter/src/formatter.rs | 205 ++- crates/rome_formatter/src/lib.rs | 211 ++- crates/rome_formatter/src/macros.rs | 219 +-- crates/rome_formatter/src/prelude.rs | 5 +- crates/rome_formatter/src/printer/mod.rs | 257 +-- crates/rome_js_formatter/src/formatter.rs | 4 +- .../src/js/auxiliary/static_modifier.rs | 7 +- .../expressions/regex_literal_expression.rs | 3 +- .../export_named_shorthand_specifier.rs | 10 +- .../src/js/objects/method_object_member.rs | 16 +- .../src/js/statements/empty_statement.rs | 8 +- .../attribute/attribute_initializer_clause.rs | 7 +- .../src/jsx/auxiliary/text.rs | 7 +- crates/rome_js_formatter/src/lib.rs | 43 +- .../ts/auxiliary/accessibility_modifier.rs | 7 +- .../auxiliary/optional_tuple_type_element.rs | 7 +- .../src/utils/member_chain/flatten_item.rs | 13 +- .../src/utils/member_chain/groups.rs | 2 +- crates/rome_js_formatter/src/utils/mod.rs | 20 +- .../src/utils/string_utils.rs | 2 +- 25 files changed, 2642 insertions(+), 1939 deletions(-) create mode 100644 crates/rome_formatter/src/arguments.rs create mode 100644 crates/rome_formatter/src/buffer.rs diff --git a/crates/rome_formatter/src/arguments.rs b/crates/rome_formatter/src/arguments.rs new file mode 100644 index 00000000000..20d2e76bc5a --- /dev/null +++ b/crates/rome_formatter/src/arguments.rs @@ -0,0 +1,108 @@ +use super::{Buffer, Format, Formatter}; + +// Ideally, a extern "C" { type Opaque } but the opaque features isn't stabilized. +// Use an empty enum as an opaque type instead. +enum Opaque {} + +/// Stack allocated element that is pending for formatting +/// +/// This struct is similar to dynamic dispatch (using `dyn Format`) by it stores a pointer to the value. +/// However, it doesn't store the pointer to `dyn Format`'s vtable, instead it statically resolves the function +/// pointer of `Format::format` and stores it in `formatter. +pub struct Argument<'fmt, O> { + /// The value to format. + value: &'fmt Opaque, + /// The function pointer to `value`'s `Format::format` method + formatter: fn(&'fmt Opaque, &mut Formatter<'_, O>) -> super::FormatResult<()>, +} + +impl<'fmt, O> Argument<'fmt, O> { + #[doc(hidden)] + #[inline] + pub fn new>(value: &'fmt F) -> Self { + let formatter: fn(&F, &mut Formatter<'_, O>) -> super::FormatResult<()> = F::format; + + unsafe { + Self { + // SAFETY: `mem::transmute` is safe because + // 1. `&'fmt F` keeps the lifetime it originated with `'fmt` + // 2. `&'fmt F` and `&'fmt Opaque` have the same memory layout + value: std::mem::transmute(value), + // SAFETY: `mem::transmute` is safe because `fn(&F, &mut Formatter<'_>) -> Result` + // and `fn(&Opaque, &mut Formatter<'_> -> Result` have the same ABI + formatter: std::mem::transmute(formatter), + } + } + } + + /// Formats the value stored by this argument using the given formatter. + pub(crate) fn format(&self, formatter: &mut Formatter) -> super::FormatResult<()> { + (self.formatter)(self.value, formatter) + } +} + +/// Stack allocated collection of items that should be formatted. +#[derive(Copy, Clone)] +pub struct Arguments<'fmt, O>(pub &'fmt [Argument<'fmt, O>]); + +impl<'fmt, O> Arguments<'fmt, O> { + #[doc(hidden)] + #[inline] + pub fn new(arguments: &'fmt [Argument<'fmt, O>]) -> Self { + Self(arguments) + } + + /// Returns the arguments + pub(crate) fn items(&self) -> &'fmt [Argument<'fmt, O>] { + &self.0 + } +} + +impl Format for Arguments<'_, Context> { + type Context = Context; + + fn format(&self, formatter: &mut Formatter) -> super::FormatResult<()> { + formatter.write_fmt(self) + } +} + +#[cfg(test)] +mod tests { + use crate::buffer::Document; + use crate::prelude::*; + use crate::{format_args, write, FormatState, VecBuffer}; + + #[test] + fn test_nesting() { + // Format_arguments not very useful, but I guess the same as normal format_args + + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); + + write!( + &mut buffer, + [ + token("function"), + space_token(), + token("a"), + space_token(), + group_elements(&format_args!(token("("), token(")"))) + ] + ) + .unwrap(); + + assert_eq!( + buffer.into_document(), + Document::from_iter([ + FormatElement::Token(Token::Static { text: "function" }), + FormatElement::Space, + FormatElement::Token(Token::Static { text: "a" }), + FormatElement::Space, + FormatElement::Group(Group::new(FormatElement::List(List::new(vec![ + FormatElement::Token(Token::Static { text: "(" }), + FormatElement::Token(Token::Static { text: ")" }), + ])))) + ]) + ); + } +} diff --git a/crates/rome_formatter/src/buffer.rs b/crates/rome_formatter/src/buffer.rs new file mode 100644 index 00000000000..c0f0047e66a --- /dev/null +++ b/crates/rome_formatter/src/buffer.rs @@ -0,0 +1,233 @@ +use super::{write, Arguments, FormatElement}; +use crate::format_element::List; +use crate::group_id::UniqueGroupIdBuilder; +#[cfg(debug_assertions)] +use crate::printed_tokens::PrintedTokens; +use crate::{FormatResult, GroupId}; +use rome_rowan::{Language, SyntaxNode, SyntaxToken}; +use std::fmt; +use std::fmt::Debug; +use std::ops::{Deref, DerefMut}; + +pub trait Buffer { + type Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()>; + + fn write_fmt(mut self: &mut Self, arguments: &Arguments) -> FormatResult<()> { + write(&mut self, arguments) + } + + fn state(&self) -> &FormatState; + + fn state_mut(&mut self) -> &mut FormatState; +} + +#[derive(Default)] +pub struct FormatState { + context: Context, + group_id_builder: UniqueGroupIdBuilder, + // This is using a RefCell as it only exists in debug mode, + // the Formatter is still completely immutable in release builds + #[cfg(debug_assertions)] + pub printed_tokens: PrintedTokens, +} + +impl fmt::Debug for FormatState +where + Context: Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("FormatContext") + .field("options", &self.context) + .finish() + } +} + +impl FormatState { + pub fn new(context: Context) -> Self { + Self { + context, + group_id_builder: Default::default(), + #[cfg(debug_assertions)] + printed_tokens: Default::default(), + } + } + + /// Returns the [FormatContext] specifying how to format the current CST + pub fn context(&self) -> &Context { + &self.context + } + + /// Creates a new group id that is unique to this document. The passed debug name is used in the + /// [std::fmt::Debug] of the document if this is a debug build. + /// The name is unused for production builds and has no meaning on the equality of two group ids. + pub fn group_id(&self, debug_name: &'static str) -> GroupId { + self.group_id_builder.group_id(debug_name) + } + + /// Tracks the given token as formatted + #[inline] + pub fn track_token(&mut self, #[allow(unused_variables)] token: &SyntaxToken) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.printed_tokens.track_token(token); + } + } + } + + #[inline] + pub fn assert_formatted_all_tokens( + &self, + #[allow(unused_variables)] root: &SyntaxNode, + ) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.printed_tokens.assert_all_tracked(root); + } + } + } +} + +impl + ?Sized, Context> Buffer for &mut W { + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + (**self).write_element(element) + } + + fn write_fmt(&mut self, args: &Arguments) -> FormatResult<()> { + (**self).write_fmt(args) + } + + fn state(&self) -> &FormatState { + (**self).state() + } + + fn state_mut(&mut self) -> &mut FormatState { + (**self).state_mut() + } +} + +// TODO use Smallvec internally +#[derive(Debug)] +pub struct VecBuffer<'a, Context> { + context: &'a mut FormatState, + elements: Vec, +} + +impl<'a, Context> VecBuffer<'a, Context> { + pub fn new(context: &'a mut FormatState) -> Self { + Self { + context, + elements: vec![], + } + } + + pub fn with_capacity(capacity: usize, context: &'a mut FormatState) -> Self { + Self { + context, + elements: Vec::with_capacity(capacity), + } + } + + /// Writes the elements from this buffer into the passed buffer + pub fn write_into( + &mut self, + buffer: &mut dyn Buffer, + ) -> super::FormatResult<()> { + for element in self.drain(..) { + buffer.write_element(element)?; + } + + Ok(()) + } + + pub fn into_document(self) -> Document { + Document(self.elements) + } + + pub fn into_vec(self) -> Vec { + self.elements + } +} + +impl Deref for VecBuffer<'_, Context> { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.elements + } +} + +impl DerefMut for VecBuffer<'_, Context> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.elements + } +} + +impl Buffer for VecBuffer<'_, Context> { + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + match element { + FormatElement::List(list) => { + if self.elements.is_empty() { + self.elements = list.into_vec() + } else { + self.elements.extend(list.into_vec()) + } + } + FormatElement::Empty => {} + element => self.elements.push(element), + } + Ok(()) + } + + fn state(&self) -> &FormatState { + self.context + } + + fn state_mut(&mut self) -> &mut FormatState { + &mut self.context + } +} + +#[derive(Clone, Eq, PartialEq)] +pub struct Document(Vec); + +impl Document { + pub fn into_vec(self) -> Vec { + self.0 + } + + pub fn into_element(mut self) -> FormatElement { + if self.is_empty() { + FormatElement::Empty + } else if self.0.len() == 1 { + self.0.pop().unwrap() + } else { + FormatElement::List(List::new(self.0)) + } + } +} + +impl FromIterator for Document { + fn from_iter>(iter: T) -> Self { + Document(Vec::from_iter(iter)) + } +} + +impl fmt::Debug for Document { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_list().entries(&self.0).finish() + } +} + +impl Deref for Document { + type Target = [FormatElement]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/crates/rome_formatter/src/builders.rs b/crates/rome_formatter/src/builders.rs index ee65ebe4cca..f119c188c0b 100644 --- a/crates/rome_formatter/src/builders.rs +++ b/crates/rome_formatter/src/builders.rs @@ -1,4 +1,1415 @@ use crate::prelude::*; +use crate::{write, GroupId, TextRange, TextSize}; +use crate::{Buffer, VecBuffer}; +use rome_rowan::{Language, SyntaxToken, SyntaxTokenText, TextLen}; +use std::borrow::Cow; +use std::marker::PhantomData; + +/// Format element that doesn't represent any content. +/// +/// Can be helpful if you need to return a `FormatElement` (e.g. in an else branch) but don't want +/// to show any content. +#[deprecated] +pub const fn empty_element() -> Empty { + Empty { + options: PhantomData, + } +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Empty { + options: PhantomData, +} + +impl Format for Empty { + type Context = O; + + fn format(&self, _: &mut Formatter) -> FormatResult<()> { + Ok(()) + } +} + +/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line. +/// It's omitted if the enclosing `Group` fits on a single line. +/// A soft line break is identical to a hard line break when not enclosed inside of a `Group`. +/// +/// ## Examples +/// +/// Soft line breaks are omitted if the enclosing `Group` fits on a single line +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![token("a,"), soft_line_break(), token("b")]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a,b", +/// elements.print().as_code() +/// ); +/// ``` +/// See [soft_line_break_or_space] if you want to insert a space between the elements if the enclosing +/// `Group` fits on a single line. +/// +/// Soft line breaks are emitted if the enclosing `Group` doesn't fit on a single line +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(options, [ +/// group_elements(&format_args![ +/// token("a long word,"), +/// soft_line_break(), +/// token("so that the group doesn't fit on a single line"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a long word,\nso that the group doesn't fit on a single line", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn soft_line_break() -> Line { + Line::new(LineMode::Soft) +} + +/// A forced line break that are always printed. A hard line break forces any enclosing `Group` +/// to be printed over multiple lines. +/// +/// ## Examples +/// +/// It forces a line break, even if the enclosing `Group` would otherwise fit on a single line. +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a,"), +/// hard_line_break(), +/// token("b"), +/// hard_line_break() +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a,\nb\n", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn hard_line_break() -> Line { + Line::new(LineMode::Hard) +} + +/// A forced empty line. An empty line inserts enough line breaks in the output for +/// the previous and next element to be separated by an empty line. +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!( +/// SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a,"), +/// empty_line(), +/// token("b"), +/// empty_line() +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a,\n\nb\n\n", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn empty_line() -> Line { + Line::new(LineMode::Empty) +} + +/// A line break if the enclosing `Group` doesn't fit on a single line, a space otherwise. +/// +/// ## Examples +/// +/// The line breaks are emitted as spaces if the enclosing `Group` fits on a a single line: +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a,"), +/// soft_line_break_or_space(), +/// token("b"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a, b", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// The printer breaks the lines if the enclosing `Group` doesn't fit on a single line: +/// ``` +/// use rome_formatter::{format_args, format, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(options, [ +/// group_elements(&format_args![ +/// token("a long word,"), +/// soft_line_break_or_space(), +/// token("so that the group doesn't fit on a single line"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a long word,\nso that the group doesn't fit on a single line", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn soft_line_break_or_space() -> Line { + Line::new(LineMode::SoftOrSpace) +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Line { + mode: LineMode, + options: PhantomData, +} + +impl Line { + const fn new(mode: LineMode) -> Self { + Self { + mode, + options: PhantomData, + } + } +} + +impl Format for Line { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Line(self.mode)) + } +} + +/// Creates a token that gets written as is to the output. Make sure to properly escape the text if +/// it's user generated (e.g. a string and not a language keyword). +/// +/// ## Line feeds +/// Tokens may contain line breaks but they must use the line feeds (`\n`). +/// The [crate::Printer] converts the line feed characters to the character specified in the [crate::PrinterOptions]. +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [token("Hello World")]).unwrap(); +/// +/// assert_eq!( +/// "Hello World", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Printing a string literal as a literal requires that the string literal is properly escaped and +/// enclosed in quotes (depending on the target language). +/// +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") +/// let elements = format!(SimpleFormatContext::default(), [token("\"Hello\\tWorld\"")]).unwrap(); +/// +/// assert_eq!(r#""Hello\tWorld""#, elements.print().as_code()); +/// ``` +#[inline] +pub fn token(text: &'static str) -> StaticToken { + debug_assert_no_newlines(text); + + StaticToken { + text, + options: PhantomData, + } +} + +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct StaticToken { + text: &'static str, + options: PhantomData, +} + +impl Format for StaticToken { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Token(Token::Static { text: self.text })) + } +} + +/// Create a token from a dynamic string and a range of the input source +pub fn dynamic_token(text: &str, position: TextSize) -> DynamicToken { + debug_assert_no_newlines(text); + + DynamicToken { + text, + position, + options: PhantomData, + } +} + +#[derive(Debug, Eq, PartialEq)] +pub struct DynamicToken<'a, O> { + text: &'a str, + position: TextSize, + options: PhantomData, +} + +impl Format for DynamicToken<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Token(Token::Dynamic { + text: self.text.to_string().into_boxed_str(), + source_position: self.position, + })) + } +} + +pub fn syntax_token_cow_slice<'a, L: Language, O>( + text: Cow<'a, str>, + token: &'a SyntaxToken, + start: TextSize, +) -> SyntaxTokenCowSlice<'a, L, O> { + debug_assert_no_newlines(&text); + + SyntaxTokenCowSlice { + text, + token, + start, + options: PhantomData, + } +} + +pub struct SyntaxTokenCowSlice<'a, L: Language, O> { + text: Cow<'a, str>, + token: &'a SyntaxToken, + start: TextSize, + options: PhantomData, +} + +impl Format for SyntaxTokenCowSlice<'_, L, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + match &self.text { + Cow::Borrowed(text) => { + let range = TextRange::at(self.start, text.text_len()); + debug_assert_eq!( + *text, + &self.token.text()[range - self.token.text_range().start()], + "The borrowed string doesn't match the specified token substring. Does the borrowed string belong to this token and range?" + ); + + let relative_range = range - self.token.text_range().start(); + let slice = self.token.token_text().slice(relative_range); + + f.write_element(FormatElement::Token(Token::SyntaxTokenSlice { + slice, + source_position: self.start, + })) + } + Cow::Owned(text) => f.write_element(FormatElement::Token(Token::Dynamic { + text: text.to_string().into_boxed_str(), + source_position: self.start, + })), + } + } +} + +pub fn syntax_token_text_slice( + token: &SyntaxToken, + range: TextRange, +) -> SyntaxTokenTextSlice { + let relative_range = range - token.text_range().start(); + let slice = token.token_text().slice(relative_range); + + debug_assert_no_newlines(&slice); + + SyntaxTokenTextSlice { + text: slice, + source_position: range.start(), + options: PhantomData, + } +} + +pub struct SyntaxTokenTextSlice { + text: SyntaxTokenText, + source_position: TextSize, + options: PhantomData, +} + +impl Format for SyntaxTokenTextSlice { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Token(Token::SyntaxTokenSlice { + slice: self.text.clone(), + source_position: self.source_position, + })) + } +} + +fn debug_assert_no_newlines(text: &str) { + debug_assert!(!text.contains('\r'), "The content '{}' contains an unsupported '\\r' line terminator character but string tokens must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.", text); +} + +/// Push a [FormatElement] to the end of the current line +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// token("a"), +/// line_suffix(&token("c")), +/// token("b") +/// ]).unwrap(); +/// +/// assert_eq!( +/// "abc", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn line_suffix(inner: &dyn Format) -> LineSuffix { + LineSuffix { content: inner } +} + +#[derive(Copy, Clone)] +pub struct LineSuffix<'a, O> { + content: &'a dyn Format, +} + +impl Format for LineSuffix<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [self.content])?; + + let content = buffer.into_document().into_element(); + f.write_element(FormatElement::LineSuffix(Box::new(content))) + } +} + +/// Inserts a boundary for line suffixes that forces to print all pending line suffixes. Helpful +/// if a line sufix shouldn't pass a certain point. +/// +/// ## Examples +/// +/// Forces the line suffix "c" to be printed before the token `d`. +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// token("a"), +/// line_suffix(&token("c")), +/// token("b"), +/// line_suffix_boundary(), +/// token("d") +/// ]).unwrap(); +/// +/// assert_eq!( +/// "abc\nd", +/// elements.print().as_code() +/// ); +/// ``` +pub const fn line_suffix_boundary() -> LineSuffixBoundary { + LineSuffixBoundary { + options: PhantomData, + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct LineSuffixBoundary { + options: PhantomData, +} + +impl Format for LineSuffixBoundary { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::LineSuffixBoundary) + } +} + +/// Mark a [FormatElement] as being a piece of trivia +/// +/// This does not directly influence how this content will be printed, but some +/// parts of the formatter may chose to handle this element in a specific way +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!( +/// SimpleFormatContext::default(), +/// [ +/// group_elements(&format_args![ +/// comment(&empty_line()), +/// token("a"), +/// soft_line_break_or_space(), +/// token("b") +/// ]) +/// ] +/// ).unwrap(); +/// +/// assert_eq!( +/// "\na b", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn comment(content: &dyn Format) -> Comment { + Comment { content } +} + +#[derive(Copy, Clone)] +pub struct Comment<'a, O> { + content: &'a dyn Format, +} + +impl Format for Comment<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.content])?; + let content = buffer.into_document().into_element(); + + f.write_element(FormatElement::Comment(Box::new(content))) + } +} + +/// Inserts a single space. Allows to separate different tokens. +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") +/// let elements = format!(SimpleFormatContext::default(), [token("a"), space_token(), token("b")]).unwrap(); +/// +/// assert_eq!("a b", elements.print().as_code()); +/// ``` +#[inline] +pub const fn space_token() -> Space { + Space { + options: PhantomData, + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct Space { + options: PhantomData, +} + +impl Format for Space { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Space) + } +} + +/// It adds a level of indentation to the given content +/// +/// It doesn't add any line breaks at the edges of the content, meaning that +/// the line breaks have to be manually added. +/// +/// This helper should be used only in rare cases, instead you should rely more on +/// [block_indent] and [soft_block_indent] +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let block = format!(SimpleFormatContext::default(), [ +/// token("switch {"), +/// block_indent(&format_args![ +/// token("default:"), +/// indent(&format_args![ +/// // this is where we want to use a +/// hard_line_break(), +/// token("break;"), +/// ]) +/// ]), +/// token("}"), +/// ]).unwrap(); +/// +/// assert_eq!( +/// "switch {\n\tdefault:\n\t\tbreak;\n}", +/// block.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn indent(content: &dyn Format) -> Indent { + Indent { content } +} + +pub struct Indent<'a, O> { + content: &'a dyn Format, +} + +impl Format for Indent<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.content])?; + + if buffer.is_empty() { + return Ok(()); + } + + let content = buffer.into_document().into_element(); + f.write_element(FormatElement::Indent(Box::new(content))) + } +} + +/// Inserts a hard line break before and after the content and increases the indention level for the content by one. +/// +/// Block indents indent a block of code, such as in a function body, and therefore insert a line +/// break before and after the content. +/// +/// Doesn't create an indention if the passed in content is [FormatElement.is_empty]. +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let block = format![ +/// SimpleFormatContext::default(), +/// [ +/// token("{"), +/// block_indent(&format_args![ +/// token("let a = 10;"), +/// hard_line_break(), +/// token("let c = a + 5;"), +/// ]), +/// token("}"), +/// ] +/// ].unwrap(); +/// +/// assert_eq!( +/// "{\n\tlet a = 10;\n\tlet c = a + 5;\n}", +/// block.print().as_code() +/// ); +/// ``` +#[inline] +pub fn block_indent(content: &dyn Format) -> BlockIndent { + BlockIndent { + content, + mode: IndentMode::Block, + } +} + +/// Indents the content by inserting a line break before and after the content and increasing +/// the indention level for the content by one if the enclosing group doesn't fit on a single line. +/// Doesn't change the formatting if the enclosing group fits on a single line. +/// +/// ## Examples +/// +/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't fit on a single line +/// +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(options, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'First string',"), +/// soft_line_break_or_space(), +/// token("'second string',"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'First string',\n\t'second string',\n]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Doesn't change the formatting if the enclosing `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("5,"), +/// soft_line_break_or_space(), +/// token("10"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[5, 10]", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn soft_block_indent(content: &dyn Format) -> BlockIndent { + BlockIndent { + content, + mode: IndentMode::Soft, + } +} + +/// If the enclosing `Group` doesn't fit on a single line, inserts a line break and indent. +/// Otherwise, just inserts a space. +/// +/// Line indents are used to break a single line of code, and therefore only insert a line +/// break before the content and not after the content. +/// +/// ## Examples +/// +/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't +/// fit on a single line. Otherwise, just inserts a space. +/// +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(options, [ +/// group_elements(&format_args![ +/// token("name"), +/// space_token(), +/// token("="), +/// soft_line_indent_or_space(&format_args![ +/// token("firstName"), +/// space_token(), +/// token("+"), +/// space_token(), +/// token("lastName"), +/// ]), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "name =\n\tfirstName + lastName", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Only adds a space if the enclosing `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a"), +/// space_token(), +/// token("="), +/// soft_line_indent_or_space(&token("10")), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a = 10", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn soft_line_indent_or_space(content: &dyn Format) -> BlockIndent { + BlockIndent { + content, + mode: IndentMode::SoftLineOrSpace, + } +} + +#[derive(Copy, Clone)] +pub struct BlockIndent<'a, O> { + content: &'a dyn Format, + mode: IndentMode, +} + +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +enum IndentMode { + Soft, + Block, + SoftLineOrSpace, +} + +impl Format for BlockIndent<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + match self.mode { + IndentMode::Soft => write!(buffer, [soft_line_break()])?, + IndentMode::Block => write!(buffer, [hard_line_break()])?, + IndentMode::SoftLineOrSpace => write!(buffer, [soft_line_break_or_space()])?, + }; + + write!(buffer, [self.content])?; + + // Don't create an indent if the content is empty + if buffer.len() == 1 { + return Ok(()); + } + + let content = buffer.into_document().into_element(); + + f.write_element(FormatElement::Indent(Box::new(content)))?; + + match self.mode { + IndentMode::Soft => write!(f, [soft_line_break()])?, + IndentMode::Block => write!(f, [hard_line_break()])?, + IndentMode::SoftLineOrSpace => {} + } + + Ok(()) + } +} + +/// Creates a logical `Group` around the content that should either consistently be printed on a single line +/// or broken across multiple lines. +/// +/// The printer will try to print the content of the `Group` on a single line, ignoring all soft line breaks and +/// emitting spaces for soft line breaks or spaces. The printer tracks back if it isn't successful either +/// because it encountered a hard line break, or because printing the `Group` on a single line exceeds +/// the configured line width, and thus it must print all its content on multiple lines, +/// emitting line breaks for all line break kinds. +/// +/// ## Examples +/// +/// `Group` that fits on a single line +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[1, 2, 3]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// The printer breaks the `Group` over multiple lines if its content doesn't fit on a single line +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(options, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'Good morning! How are you today?',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn group_elements(content: &dyn Format) -> GroupElements { + GroupElements { + content, + options: GroupElementsOptions { group_id: None }, + } +} + +#[derive(Default, Clone, Copy, Debug)] +pub struct GroupElementsOptions { + pub group_id: Option, +} + +/// Creates a group with a specific id. Useful for cases where `if_group_breaks` and `if_group_fits_on_line` +/// shouldn't refer to the direct parent group. +pub const fn group_elements_with_options( + content: &dyn Format, + options: GroupElementsOptions, +) -> GroupElements { + GroupElements { content, options } +} + +#[derive(Copy, Clone)] +pub struct GroupElements<'a, O> { + content: &'a dyn Format, + options: GroupElementsOptions, +} + +impl Format for GroupElements<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.content])?; + + let content = buffer.into_document().into_element(); + + let (leading, content, trailing) = content.split_trivia(); + let group = Group::new(content).with_id(self.options.group_id); + + if !leading.is_empty() { + f.write_element(leading)?; + } + f.write_element(FormatElement::Group(group))?; + + if !trailing.is_empty() { + f.write_element(trailing)?; + } + + Ok(()) + } +} + +/// IR element that forces the parent group to print in expanded mode. +/// +/// Has no effect if used outside of a group or element that introduce implicit groups (fill element). +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'Good morning! How are you today?',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// expand_parent(), // Forces the parent to expand +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// ## Prettier +/// Equivalent to Prettier's `break_parent` IR element +pub const fn expand_parent() -> ExpandParent { + ExpandParent { + options: PhantomData, + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct ExpandParent { + options: PhantomData, +} + +impl Format for ExpandParent { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::ExpandParent) + } +} + +/// Adds a conditional content that is emitted only if it isn't inside an enclosing `Group` that +/// is printed on a single line. The element allows, for example, to insert a trailing comma after the last +/// array element only if the array doesn't fit on a single line. +/// +/// The element has no special meaning if used outside of a `Group`. In that case, the content is always emitted. +/// +/// If you're looking for a way to only print something if the `Group` fits on a single line see [if_group_fits_on_single_line]. +/// +/// ## Examples +/// +/// Omits the trailing comma for the last array element if the `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_breaks(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[1, 2, 3]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Prints the trailing comma for the last array element if the `Group` doesn't fit on a single line +/// ``` +/// use rome_formatter::{format_args, format, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(options, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'A somewhat longer string to force a line break',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_breaks(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// let options = PrinterOptions { +/// print_width: LineWidth::try_from(20).unwrap(), +/// ..PrinterOptions::default() +/// }; +/// assert_eq!( +/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3,\n]", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn if_group_breaks(content: &dyn Format) -> IfGroupBreaks { + IfGroupBreaks { + content, + group_id: None, + mode: PrintMode::Expanded, + } +} + +/// Inserts some content that the printer only prints if the group with the specified `group_id` +/// is printed in multiline mode. The referred group must appear before this element in the document +/// but doesn't have to one of its ancestors. +/// +/// ## Examples +/// +/// Prints the trailing comma if the array group doesn't fit. The `group_id` is necessary +/// because `fill` creates an implicit group around each item and tries to print the item in flat mode. +/// The item `[4]` in this example fits on a single line but the trailing comma should still be printed +/// +/// ``` +/// use rome_formatter::{format, format_args, write, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let formatted = format!(options, [format_with(|f| { +/// let group_id = f.group_id("array"); +/// +/// write!(f, [ +/// group_elements_with_options( +/// &format_args![ +/// token("["), +/// soft_block_indent(&format_with(|f| { +/// f.fill(&soft_line_break_or_space()) +/// .entry(&token("1,")) +/// .entry(&token("234568789,")) +/// .entry(&token("3456789,")) +/// .entry(&format_args!( +/// token("["), +/// soft_block_indent(&token("4")), +/// token("]"), +/// if_group_with_id_breaks(&token(","), group_id) +/// )) +/// .finish() +/// })), +/// token("]") +/// ], +/// GroupElementsOptions { group_id: Some(group_id) } +/// ) +/// ]) +/// })]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t1, 234568789,\n\t3456789, [4],\n]", +/// formatted.print().as_code() +/// ); +/// ``` +pub const fn if_group_with_id_breaks( + content: &dyn Format, + group_id: GroupId, +) -> IfGroupBreaks { + IfGroupBreaks { + content, + group_id: Some(group_id), + mode: PrintMode::Expanded, + } +} + +/// Adds a conditional content specific for `Group`s that fit on a single line. The content isn't +/// emitted for `Group`s spanning multiple lines. +/// +/// See [if_group_breaks] if you're looking for a way to print content only for groups spanning multiple lines. +/// +/// ## Examples +/// +/// Adds the trailing comma for the last array element if the `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let formatted = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_fits_on_single_line(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[1, 2, 3,]", +/// formatted.print().as_code() +/// ); +/// ``` +/// +/// Omits the trailing comma for the last array element if the `Group` doesn't fit on a single line +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let options = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let formatted = format!(options, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'A somewhat longer string to force a line break',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_fits_on_single_line(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3\n]", +/// formatted.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn if_group_fits_on_single_line( + flat_content: &dyn Format, +) -> IfGroupBreaks { + IfGroupBreaks { + mode: PrintMode::Flat, + group_id: None, + content: flat_content, + } +} + +/// Inserts some content that the printer only prints if the group with the specified `group_id` +/// is printed in flat mode. +/// +#[inline] +pub const fn if_group_with_id_fits_on_line( + flat_content: &dyn Format, + id: GroupId, +) -> IfGroupBreaks { + IfGroupBreaks { + mode: PrintMode::Flat, + group_id: Some(id), + content: flat_content, + } +} + +#[derive(Copy, Clone)] +pub struct IfGroupBreaks<'a, O> { + content: &'a dyn Format, + group_id: Option, + mode: PrintMode, +} + +impl Format for IfGroupBreaks<'_, O> { + type Context = O; + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.content])?; + + if buffer.is_empty() { + return Ok(()); + } + + let content = buffer.into_document().into_element(); + f.write_element(FormatElement::ConditionalGroupContent( + ConditionalGroupContent::new(content, self.mode).with_group_id(self.group_id), + )) + } +} + +pub struct JoinBuilder<'fmt, 'joiner, 'buf, O> { + result: super::FormatResult<()>, + fmt: &'fmt mut Formatter<'buf, O>, + with: Option<&'joiner dyn Format>, + has_elements: bool, +} + +impl<'fmt, 'joiner, 'buf, O> JoinBuilder<'fmt, 'joiner, 'buf, O> { + pub(crate) fn new(fmt: &'fmt mut Formatter<'buf, O>) -> Self { + Self { + result: Ok(()), + fmt, + has_elements: false, + with: None, + } + } + + pub(crate) fn with( + fmt: &'fmt mut Formatter<'buf, O>, + with: &'joiner dyn Format, + ) -> Self { + Self { + result: Ok(()), + fmt, + has_elements: false, + with: Some(with), + } + } + + pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { + self.result = self.result.and_then(|_| { + if let Some(with) = &self.with { + if self.has_elements { + with.format(self.fmt)?; + } + } + self.has_elements = true; + + entry.format(self.fmt) + }); + + self + } + + pub fn entries(&mut self, entries: I) -> &mut Self + where + F: Format, + I: IntoIterator, + { + for entry in entries { + self.entry(&entry); + } + + self + } + + pub fn finish(&mut self) -> super::FormatResult<()> { + self.result + } +} + +pub struct FillBuilder<'fmt, 'separator, 'buf, O> { + result: FormatResult<()>, + fmt: &'fmt mut Formatter<'buf, O>, + separator: &'separator dyn Format, + items: Vec, +} + +impl<'a, 'separator, 'buf, O> FillBuilder<'a, 'separator, 'buf, O> { + pub(crate) fn new( + fmt: &'a mut Formatter<'buf, O>, + separator: &'separator dyn Format, + ) -> Self { + Self { + result: Ok(()), + fmt, + separator, + items: vec![], + } + } + + pub fn entries(&mut self, entries: I) -> &mut Self + where + F: Format, + I: IntoIterator, + { + for entry in entries { + self.entry(&entry); + } + + self + } + + pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { + self.result = self.result.and_then(|_| { + let mut buffer = VecBuffer::new(self.fmt.state_mut()); + write!(buffer, [entry])?; + + let item = buffer.into_document().into_element(); + + if !item.is_empty() { + self.items.push(item); + } + + Ok(()) + }); + + self + } + + pub fn finish(&mut self) -> super::FormatResult<()> { + self.result.and_then(|_| { + let mut items = std::mem::take(&mut self.items); + + match items.len() { + 0 => Ok(()), + 1 => self.fmt.write_element(items.pop().unwrap()), + _ => self + .fmt + .write_element(FormatElement::Fill(List::new(items))), + } + }) + } +} + +pub struct FormatWith +where + T: Fn(&mut Formatter) -> FormatResult<()>, +{ + closure: T, + options: PhantomData, +} + +impl Format for FormatWith +where + T: Fn(&mut Formatter) -> FormatResult<()>, +{ + type Context = O; + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + (self.closure)(f) + } +} + +pub const fn format_with(closure: T) -> FormatWith +where + T: Fn(&mut Formatter) -> FormatResult<()>, +{ + FormatWith { + closure, + options: PhantomData, + } +} #[derive(Default)] pub struct ConcatBuilder { @@ -58,7 +1469,7 @@ impl ConcatBuilder { #[inline] pub fn finish(mut self) -> FormatElement { if self.elements.is_empty() { - empty_element() + FormatElement::Empty } else if self.elements.len() == 1 { // Safety: Guaranteed to succeed by the length check above self.elements.pop().unwrap() diff --git a/crates/rome_formatter/src/format_element.rs b/crates/rome_formatter/src/format_element.rs index fa8530ee891..bb13e17ed15 100644 --- a/crates/rome_formatter/src/format_element.rs +++ b/crates/rome_formatter/src/format_element.rs @@ -1,339 +1,14 @@ use crate::builders::ConcatBuilder; -use crate::intersperse::{Intersperse, IntersperseFn}; -use crate::{format_elements, GroupId, TextRange, TextSize}; +use crate::{Format, FormatResult, GroupId, TextRange, TextSize}; #[cfg(target_pointer_width = "64")] use rome_rowan::static_assert; -use rome_rowan::{ - Language, SyntaxNode, SyntaxToken, SyntaxTokenText, SyntaxTriviaPieceComments, TextLen, -}; +use rome_rowan::{Language, SyntaxToken, SyntaxTokenText, SyntaxTriviaPieceComments, TextLen}; use std::borrow::Cow; use std::fmt::{self, Debug, Formatter}; use std::ops::Deref; type Content = Box; -/// Format element that doesn't represent any content. -/// -/// Can be helpful if you need to return a `FormatElement` (e.g. in an else branch) but don't want -/// to show any content. -pub fn empty_element() -> FormatElement { - FormatElement::Empty -} - -/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line. -/// It's omitted if the enclosing `Group` fits on a single line. -/// A soft line break is identical to a hard line break when not enclosed inside of a `Group`. -/// -/// ## Examples -/// -/// Soft line breaks are omitted if the enclosing `Group` fits on a single line -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![token("a,"), soft_line_break(), token("b"),]); -/// -/// assert_eq!( -/// "a,b", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// See [soft_line_break_or_space] if you want to insert a space between the elements if the enclosing -/// `Group` fits on a single line. -/// -/// Soft line breaks are emitted if the enclosing `Group` doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a long word,"), -/// soft_line_break(), -/// token("so that the group doesn't fit on a single line"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "a long word,\nso that the group doesn't fit on a single line", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub const fn soft_line_break() -> FormatElement { - FormatElement::Line(Line::new(LineMode::Soft)) -} - -/// A forced line break that are always printed. A hard line break forces any enclosing `Group` -/// to be printed over multiple lines. -/// -/// ## Examples -/// -/// It forces a line break, even if the enclosing `Group` would otherwise fit on a single line. -/// ``` -/// use rome_formatter::*; -/// use rome_formatter::prelude::PrinterOptions; -/// -/// let elements = group_elements(format_elements![ -/// token("a,"), -/// hard_line_break(), -/// token("b"), -/// hard_line_break() -/// ]); -/// -/// assert_eq!( -/// "a,\nb\n", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub const fn hard_line_break() -> FormatElement { - FormatElement::Line(Line::new(LineMode::Hard)) -} - -/// A forced empty line. An empty line inserts enough line breaks in the output for -/// the previous and next element to be separated by an empty line. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a,"), -/// empty_line(), -/// token("b"), -/// empty_line() -/// ]); -/// -/// assert_eq!( -/// "a,\n\nb\n\n", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub const fn empty_line() -> FormatElement { - FormatElement::Line(Line::new(LineMode::Empty)) -} - -/// A line break if the enclosing `Group` doesn't fit on a single line, a space otherwise. -/// -/// ## Examples -/// -/// The line breaks are emitted as spaces if the enclosing `Group` fits on a a single line: -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a,"), -/// soft_line_break_or_space(), -/// token("b"), -/// ]); -/// -/// assert_eq!( -/// "a, b", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// The printer breaks the lines if the enclosing `Group` doesn't fit on a single line: -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a long word,"), -/// soft_line_break_or_space(), -/// token("so that the group doesn't fit on a single line"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "a long word,\nso that the group doesn't fit on a single line", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub const fn soft_line_break_or_space() -> FormatElement { - FormatElement::Line(Line::new(LineMode::SoftOrSpace)) -} - -/// Creates a token that gets written as is to the output. Make sure to properly escape the text if -/// it's user generated (e.g. a string and not a language keyword). -/// -/// ## Line feeds -/// Tokens may contain line breaks but they must use the line feeds (`\n`). -/// The [crate::Printer] converts the line feed characters to the character specified in the [crate::PrinterOptions]. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// let elements = token("Hello World"); -/// -/// assert_eq!( -/// "Hello World", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// Printing a string literal as a literal requires that the string literal is properly escaped and -/// enclosed in quotes (depending on the target language). -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") -/// let elements = token("\"Hello\\tWorld\""); -/// -/// assert_eq!(r#""Hello\tWorld""#, Formatted::new(elements, PrinterOptions::default()).print().as_code()); -/// ``` -#[inline] -pub const fn token(text: &'static str) -> FormatElement { - if text.is_empty() { - FormatElement::Empty - } else { - FormatElement::Token(Token::new_static(text)) - } -} - -/// Push a [FormatElement] to the end of the current line -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = format_elements![token("a"), line_suffix(token("c")), token("b")]; -/// -/// assert_eq!( -/// "abc", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn line_suffix(element: impl Into) -> FormatElement { - FormatElement::LineSuffix(Box::new(element.into())) -} - -/// Inserts a boundary for line suffixes that forces to print all pending line suffixes. Helpful -/// if a line sufix shouldn't pass a certain point. -/// -/// ## Examples -/// -/// Forces the line suffix "c" to be printed before the token `d`. -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = format_elements![token("a"), line_suffix(token("c")), token("b"), line_suffix_boundary(), token("d")]; -/// -/// assert_eq!( -/// "abc\nd", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -pub const fn line_suffix_boundary() -> FormatElement { - FormatElement::LineSuffixBoundary -} - -/// Mark a [FormatElement] as being a piece of trivia -/// -/// This does not directly influence how this content will be printed, but some -/// parts of the formatter may chose to handle this element in a specific way -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// comment(empty_line()), -/// token("a"), -/// soft_line_break_or_space(), -/// token("b") -/// ]); -/// -/// assert_eq!( -/// "\na b", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn comment(element: impl Into) -> FormatElement { - FormatElement::Comment(Box::new(element.into())) -} - -/// Inserts a single space. Allows to separate different tokens. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") -/// let elements = format_elements![token("a"), space_token(), token("b")]; -/// -/// assert_eq!("a b", Formatted::new(elements, PrinterOptions::default()).print().as_code()); -/// ``` -#[inline] -pub const fn space_token() -> FormatElement { - FormatElement::Space -} - -/// Concatenates the content of multiple [FormatElement]s. -/// -/// ## Examples -/// -/// ```rust -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// let expr = concat_elements(vec![ -/// token("a"), -/// space_token(), -/// token("+"), -/// space_token(), -/// token("b"), -/// ]); -/// -/// assert_eq!( -/// "a + b", -/// Formatted::new(expr, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ) -/// ``` pub fn concat_elements(elements: I) -> FormatElement where I: IntoIterator, @@ -349,709 +24,74 @@ where builder.finish() } - -/// Concatenates a list of [FormatElement]s with spaces and line breaks to fit -/// them on as few lines as possible. Each element introduces a conceptual group. The printer -/// first tries to print the item in flat mode but then prints it in expanded mode if it doesn't fit. -/// -/// ## Examples -/// -/// ```rust -/// use rome_formatter::prelude::*; -/// use rome_formatter::Formatted; -/// use std::str::from_utf8; -/// -/// let a = from_utf8(&[b'a'; 30]).unwrap(); -/// let b = from_utf8(&[b'b'; 30]).unwrap(); -/// let c = from_utf8(&[b'c'; 30]).unwrap(); -/// let d = from_utf8(&[b'd'; 30]).unwrap(); -/// let expr = fill_elements([token(a), token(b), token(c), token(d)]); -/// -/// assert_eq!( -/// format!("{a} {b}\n{c} {d}"), -/// Formatted::new(expr, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ) -/// ``` -pub fn fill_elements(elements: impl IntoIterator) -> FormatElement { - let mut list: Vec<_> = elements.into_iter().collect(); - match list.len() { - 0 => empty_element(), - 1 => list.pop().unwrap(), - _ => FormatElement::Fill(List::new(list)), - } -} - -/// Joins the elements by placing a given separator between elements. -/// -/// ## Examples -/// -/// Joining different tokens by separating them with a comma and a space. -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let separator = concat_elements(vec![token(","), space_token()]); -/// let elements = join_elements( -/// separator, -/// vec![token("1"), token("2"), token("3"), token("4")], -/// ); -/// -/// assert_eq!( -/// "1, 2, 3, 4", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn join_elements(separator: TSep, elements: I) -> FormatElement -where - TSep: Into, - I: IntoIterator, -{ - concat_elements(Intersperse::new( - elements.into_iter().filter(|e| !e.is_empty()), - separator.into(), - )) -} - -/// It adds a level of indentation to the given content -/// -/// It doesn't add any line breaks at the edges of the content, meaning that -/// the line breaks have to be manually added. -/// -/// This helper should be used only in rare cases, instead you should rely more on -/// [block_indent] and [soft_block_indent] -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let block = (format_elements![ -/// token("switch {"), -/// block_indent(format_elements![ -/// token("default:"), -/// indent(format_elements![ -/// // this is where we want to use a -/// hard_line_break(), -/// token("break;"), -/// ]) -/// ]), -/// token("}"), -/// ]); -/// -/// assert_eq!( -/// "switch {\n\tdefault:\n\t\tbreak;\n}", -/// Formatted::new(block, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn indent>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![Indent::new(format_elements![content])] - } -} - -/// Inserts a hard line break before and after the content and increases the indention level for the content by one. -/// -/// Block indents indent a block of code, such as in a function body, and therefore insert a line -/// break before and after the content. -/// -/// Doesn't create an indention if the passed in content is [FormatElement.is_empty]. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let block = (format_elements![ -/// token("{"), -/// block_indent(format_elements![ -/// token("let a = 10;"), -/// hard_line_break(), -/// token("let c = a + 5;"), -/// ]), -/// token("}"), -/// ]); -/// -/// assert_eq!( -/// "{\n\tlet a = 10;\n\tlet c = a + 5;\n}", -/// Formatted::new(block, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn block_indent>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![ - Indent::new(format_elements![hard_line_break(), content]), - hard_line_break(), - ] - } -} - -/// Indents the content by inserting a line break before and after the content and increasing -/// the indention level for the content by one if the enclosing group doesn't fit on a single line. -/// Doesn't change the formatting if the enclosing group fits on a single line. -/// -/// ## Examples -/// -/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't fit on a single line -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'First string',"), -/// soft_line_break_or_space(), -/// token("'second string',"), -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "[\n\t'First string',\n\t'second string',\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -/// -/// Doesn't change the formatting if the enclosing `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("5,"), -/// soft_line_break_or_space(), -/// token("10"), -/// ]), -/// token("]"), -/// ]); -/// -/// assert_eq!( -/// "[5, 10]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn soft_block_indent>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![ - Indent::new(format_elements![soft_line_break(), content]), - soft_line_break(), - ] - } -} - -/// If the enclosing `Group` doesn't fit on a single line, inserts a line break and indent. -/// Otherwise, just inserts a space. -/// -/// Line indents are used to break a single line of code, and therefore only insert a line -/// break before the content and not after the content. -/// -/// ## Examples -/// -/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't -/// fit on a single line. Otherwise, just inserts a space. -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("name"), -/// space_token(), -/// token("="), -/// soft_line_indent_or_space(format_elements![ -/// token("firstName"), -/// space_token(), -/// token("+"), -/// space_token(), -/// token("lastName"), -/// ]), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "name =\n\tfirstName + lastName", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -/// -/// Only adds a space if the enclosing `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a"), -/// space_token(), -/// token("="), -/// soft_line_indent_or_space(format_elements![token("10")]), -/// ]); -/// -/// assert_eq!( -/// "a = 10", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn soft_line_indent_or_space>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![Indent::new(format_elements![ - soft_line_break_or_space(), - content - ])] - } -} - -/// Creates a logical `Group` around the content that should either consistently be printed on a single line -/// or broken across multiple lines. -/// -/// The printer will try to print the content of the `Group` on a single line, ignoring all soft line breaks and -/// emitting spaces for soft line breaks or spaces. The printer tracks back if it isn't successful either -/// because it encountered a hard line break, or because printing the `Group` on a single line exceeds -/// the configured line width, and thus it must print all its content on multiple lines, -/// emitting line breaks for all line break kinds. -/// -/// ## Examples -/// -/// `Group` that fits on a single line -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]"), -/// ]); -/// -/// assert_eq!( -/// "[1, 2, 3]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// The printer breaks the `Group` over multiple lines if its content doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'Good morning! How are you today?',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub fn group_elements>(content: T) -> FormatElement { - group_elements_with_options(content.into(), GroupElementsOptions::default()) -} - -#[derive(Default, Clone, Debug)] -pub struct GroupElementsOptions { - pub group_id: Option, -} - -/// Creates a group with a specific id. Useful for cases where `if_group_breaks` and `if_group_fits_on_line` -/// shouldn't refer to the direct parent group. -pub fn group_elements_with_options( - content: FormatElement, - options: GroupElementsOptions, -) -> FormatElement { - if content.is_empty() { - content - } else { - let (leading, content, trailing) = content.split_trivia(); - - let group = Group::new(content).with_id(options.group_id); - - format_elements![leading, group, trailing] - } -} - -/// IR element that forces the parent group to print in expanded mode. -/// -/// Has no effect if used outside of a group or element that introduce implicit groups (fill element). -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'Good morning! How are you today?',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// expand_parent(), // Forces the parent to expand -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]"), -/// ]); -/// -/// assert_eq!( -/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", -/// Formatted::new(elements, PrinterOptions::default()).print().as_code() -/// ); -/// ``` -/// -/// ## Prettier -/// Equivalent to Prettier's `break_parent` IR element -pub const fn expand_parent() -> FormatElement { - FormatElement::ExpandParent -} - -/// Adds a conditional content that is emitted only if it isn't inside an enclosing `Group` that -/// is printed on a single line. The element allows, for example, to insert a trailing comma after the last -/// array element only if the array doesn't fit on a single line. -/// -/// The element has no special meaning if used outside of a `Group`. In that case, the content is always emitted. -/// -/// If you're looking for a way to only print something if the `Group` fits on a single line see [if_group_fits_on_single_line]. -/// -/// ## Examples -/// -/// Omits the trailing comma for the last array element if the `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_breaks(token(",")) -/// ]), -/// token("]"), -/// ]); -/// assert_eq!( -/// "[1, 2, 3]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// Prints the trailing comma for the last array element if the `Group` doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'A somewhat longer string to force a line break',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_breaks(token(",")) -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// assert_eq!( -/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3,\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub fn if_group_breaks>(content: T) -> FormatElement { - if_group_breaks_impl(content.into(), None) -} - -/// Inserts some content that the printer only prints if the group with the specified `group_id` -/// is printed in multiline mode. The referred group must appear before this element in the document -/// but doesn't have to one of its ancestors. -/// -/// ## Examples -/// -/// Prints the trailing comma if the array group doesn't fit. The `group_id` is necessary -/// because `fill` creates an implicit group around each item and tries to print the item in flat mode. -/// The item `[4]` in this example fits on a single line but the trailing comma should still be printed -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let formatter = Formatter::<()>::default(); -/// let group_id = formatter.group_id("array"); -/// -/// let elements = group_elements_with_options(format_elements![ -/// token("["), -/// soft_block_indent(fill_elements(vec![ -/// format_elements![token("1,")], -/// format_elements![token("234568789,")], -/// format_elements![token("3456789,")], -/// format_elements![ -/// token("["), -/// soft_block_indent(token("4")), -/// token("]"), -/// if_group_with_id_breaks(token(","), group_id) -/// ], -/// ])), -/// token("]"), -/// ], GroupElementsOptions { group_id: Some(group_id) }); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// assert_eq!( -/// "[\n\t1, 234568789,\n\t3456789, [4],\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -pub fn if_group_with_id_breaks(content: FormatElement, group_id: GroupId) -> FormatElement { - if_group_breaks_impl(content, Some(group_id)) -} - -fn if_group_breaks_impl(content: FormatElement, group_id: Option) -> FormatElement { - if content.is_empty() { - content - } else { - FormatElement::from( - ConditionalGroupContent::new(content, PrintMode::Expanded).with_group_id(group_id), - ) - } -} - -/// Adds a conditional content specific for `Group`s that fit on a single line. The content isn't -/// emitted for `Group`s spanning multiple lines. -/// -/// See [if_group_breaks] if you're looking for a way to print content only for groups spanning multiple lines. -/// -/// ## Examples -/// -/// Adds the trailing comma for the last array element if the `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_fits_on_single_line(token(",")) -/// ]), -/// token("]"), -/// ]); -/// assert_eq!( -/// "[1, 2, 3,]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// Omits the trailing comma for the last array element if the `Group` doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'A somewhat longer string to force a line break',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_fits_on_single_line(token(",")) -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// assert_eq!( -/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub fn if_group_fits_on_single_line(flat_content: TFlat) -> FormatElement -where - TFlat: Into, -{ - if_group_fits_on_line_impl(flat_content.into(), None) -} - -/// Inserts some content that the printer only prints if the group with the specified `group_id` -/// is printed in flat mode. -/// -#[inline] -pub fn if_group_with_id_fits_on_line(flat_content: FormatElement, id: GroupId) -> FormatElement { - if_group_fits_on_line_impl(flat_content, Some(id)) -} - -fn if_group_fits_on_line_impl( - flat_content: FormatElement, - group_id: Option, -) -> FormatElement { - if flat_content.is_empty() { - flat_content - } else { - FormatElement::from( - ConditionalGroupContent::new(flat_content, PrintMode::Flat).with_group_id(group_id), - ) - } -} - -/// Specialized version of [join_elements] for joining SyntaxNodes separated by a space, soft -/// line break or empty line depending on the input file. -/// -/// This functions inspects the input source and separates consecutive elements with either -/// a [soft_line_break_or_space] or [empty_line] depending on how many line breaks were -/// separating the elements in the original file. -#[inline] -pub fn join_elements_soft_line(elements: I) -> FormatElement -where - I: IntoIterator, FormatElement)>, - L: Language, -{ - join_elements_with(elements, soft_line_break_or_space) -} - -/// Specialized version of [join_elements] for joining SyntaxNodes separated by one or more -/// line breaks depending on the input file. -/// -/// This functions inspects the input source and separates consecutive elements with either -/// a [hard_line_break] or [empty_line] depending on how many line breaks were separating the -/// elements in the original file. -#[inline] -pub fn join_elements_hard_line(elements: I) -> FormatElement -where - I: IntoIterator, FormatElement)>, - L: Language, -{ - join_elements_with(elements, hard_line_break) -} - -/// Get the number of line breaks between two consecutive SyntaxNodes in the tree -pub fn get_lines_before(next_node: &SyntaxNode) -> usize { - // Count the newlines in the leading trivia of the next node - if let Some(leading_trivia) = next_node.first_leading_trivia() { - leading_trivia - .pieces() - .take_while(|piece| { - // Stop at the first comment piece, the comment printer - // will handle newlines between the comment and the node - !piece.is_comments() - }) - .filter(|piece| piece.is_newline()) - .count() - } else { - 0 - } -} - -#[inline] -pub fn join_elements_with(elements: I, separator: fn() -> FormatElement) -> FormatElement -where - I: IntoIterator, FormatElement)>, - L: Language, -{ - concat_elements(IntersperseFn::new( - elements.into_iter(), - |_, next_node, next_elem| { - if next_elem.is_empty() { - empty_element() - } else if get_lines_before(next_node) > 1 { - empty_line() - } else { - separator() - } - }, - )) -} +// +// /// Specialized version of [join_elements] for joining SyntaxNodes separated by a space, soft +// /// line break or empty line depending on the input file. +// /// +// /// This functions inspects the input source and separates consecutive elements with either +// /// a [soft_line_break_or_space] or [empty_line] depending on how many line breaks were +// /// separating the elements in the original file. +// #[inline] +// pub fn join_elements_soft_line(elements: I) -> FormatElement +// where +// I: IntoIterator, FormatElement)>, +// L: Language, +// { +// join_elements_with(elements, soft_line_break_or_space) +// } +// +// /// Specialized version of [join_elements] for joining SyntaxNodes separated by one or more +// /// line breaks depending on the input file. +// /// +// /// This functions inspects the input source and separates consecutive elements with either +// /// a [hard_line_break] or [empty_line] depending on how many line breaks were separating the +// /// elements in the original file. +// #[inline] +// pub fn join_elements_hard_line(elements: I) -> FormatElement +// where +// I: IntoIterator, FormatElement)>, +// L: Language, +// { +// join_elements_with(elements, hard_line_break) +// } +// +// /// Get the number of line breaks between two consecutive SyntaxNodes in the tree +// pub fn get_lines_before(next_node: &SyntaxNode) -> usize { +// // Count the newlines in the leading trivia of the next node +// if let Some(leading_trivia) = next_node.first_leading_trivia() { +// leading_trivia +// .pieces() +// .take_while(|piece| { +// // Stop at the first comment piece, the comment printer +// // will handle newlines between the comment and the node +// !piece.is_comments() +// }) +// .filter(|piece| piece.is_newline()) +// .count() +// } else { +// 0 +// } +// } +// +// #[inline] +// pub fn join_elements_with(elements: I, separator: fn() -> FormatElement) -> FormatElement +// where +// I: IntoIterator, FormatElement)>, +// L: Language, +// { +// concat_elements(IntersperseFn::new( +// elements.into_iter(), +// |_, next_node, next_elem| { +// if next_elem.is_empty() { +// empty_element() +// } else if get_lines_before(next_node) > 1 { +// empty_line() +// } else { +// separator() +// } +// }, +// )) +// } /// Language agnostic IR for formatting source code. /// @@ -1064,10 +104,10 @@ pub enum FormatElement { Space, /// A new line, see [crate::soft_line_break], [crate::hard_line_break], and [crate::soft_line_break_or_space] for documentation. - Line(Line), + Line(LineMode), /// Indents the content one level deeper, see [crate::indent] for documentation and examples. - Indent(Indent), + Indent(Content), /// Creates a logical group where its content is either consistently printed: /// * on a single line: Omitting `LineMode::Soft` line breaks and printing spaces for `LineMode::SoftOrSpace` @@ -1165,7 +205,7 @@ impl Debug for FormatElement { FormatElement::Empty => write!(fmt, "Empty"), FormatElement::Space => write!(fmt, "Space"), FormatElement::Line(content) => content.fmt(fmt), - FormatElement::Indent(content) => content.fmt(fmt), + FormatElement::Indent(content) => fmt.debug_tuple("Indent").field(content).finish(), FormatElement::Group(content) => { write!(fmt, "Group")?; content.fmt(fmt) @@ -1198,24 +238,6 @@ impl Debug for FormatElement { } } -/// Inserts a new line -#[derive(Clone, Eq, PartialEq)] -pub struct Line { - pub mode: LineMode, -} - -impl Debug for Line { - fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { - write!(fmt, "Line({:?})", self.mode) - } -} - -impl Line { - pub const fn new(mode: LineMode) -> Self { - Self { mode } - } -} - #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum LineMode { /// See [soft_line_break_or_space] for documentation. @@ -1228,26 +250,6 @@ pub enum LineMode { Empty, } -/// Increases the indention by one; see [indented_with_soft_break] and [indented_with_hard_break]. -#[derive(Clone, Eq, PartialEq)] -pub struct Indent { - pub(crate) content: Content, -} - -impl Debug for Indent { - fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { - fmt.debug_tuple("Indent").field(&self.content).finish() - } -} - -impl Indent { - pub fn new(content: FormatElement) -> Self { - Self { - content: Box::new(content), - } - } -} - /// A token used to gather a list of elements; see [concat_elements] and [join_elements]. #[derive(Clone, Eq, PartialEq)] pub struct List { @@ -1460,60 +462,6 @@ impl Debug for Token { } impl Token { - /// Create a token from a static string - const fn new_static(text: &'static str) -> Self { - Self::Static { text } - } - - /// Create a token from a dynamic string and a range of the input source - pub fn new_dynamic(text: String, position: TextSize) -> Self { - debug_assert_no_newlines(&text); - - Self::Dynamic { - text: text.into_boxed_str(), - source_position: position, - } - } - - /// Creates a token from a [Cow] that is a sub-slice over the text of a token. - /// - /// The `start` is the absolute start of the token in the source text. - /// - /// ## Returns - /// * [Token::Dynamic] if `text` is a [Cow::Owned] (text doesn't match syntax token text) - /// * [Token::SyntaxTokenSlice] if `text` is borrowed. Avoids allocating a new string. - pub fn from_syntax_token_cow_slice( - text: Cow, - token: &SyntaxToken, - start: TextSize, - ) -> Self { - match text { - Cow::Owned(text) => Self::new_dynamic(text, start), - Cow::Borrowed(text) => { - let range = TextRange::at(start, text.text_len()); - debug_assert_eq!( - text, - &token.text()[range - token.text_range().start()], - "The borrowed string doesn't match the specified token substring. Does the borrowed string belong to this token and range?" - ); - Token::new_syntax_token_slice(token, range) - } - } - } - - /// Creates a new [Token] with a text backed by the string of [SyntaxToken] - pub fn new_syntax_token_slice(token: &SyntaxToken, range: TextRange) -> Self { - let relative_range = range - token.text_range().start(); - let slice = token.token_text().slice(relative_range); - - debug_assert_no_newlines(&slice); - - Self::SyntaxTokenSlice { - slice, - source_position: range.start(), - } - } - /// Get the range of the input source covered by this token, /// or None if the token was synthesized by the formatter pub fn source_position(&self) -> Option<&TextSize> { @@ -1529,10 +477,6 @@ impl Token { } } -fn debug_assert_no_newlines(text: &str) { - debug_assert!(!text.contains('\r'), "The content '{}' contains an unsupported '\\r' line terminator character but string tokens must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.", text); -} - // Token equality only compares the text content impl PartialEq for Token { fn eq(&self, other: &Self) -> bool { @@ -1540,20 +484,6 @@ impl PartialEq for Token { } } -impl From> for Token { - fn from(token: SyntaxToken) -> Self { - Self::from(&token) - } -} - -impl<'a, L: Language> From<&'a SyntaxToken> for Token { - fn from(token: &'a SyntaxToken) -> Self { - let trimmed_range = token.text_trimmed_range(); - - Self::new_syntax_token_slice(token, trimmed_range) - } -} - const LINE_SEPARATOR: char = '\u{2028}'; const PARAGRAPH_SEPARATOR: char = '\u{2029}'; pub const LINE_TERMINATORS: [char; 3] = ['\r', LINE_SEPARATOR, PARAGRAPH_SEPARATOR]; @@ -1586,16 +516,18 @@ pub fn normalize_newlines(text: &str, terminators: [char; N]) -> } } -impl From> for Token { - fn from(trivia: SyntaxTriviaPieceComments) -> Self { - let range = trivia.text_range(); - Token::from_syntax_token_cow_slice( - normalize_newlines(trivia.text().trim(), LINE_TERMINATORS), - &trivia.as_piece().token(), - range.start(), - ) - } -} +// TODO +// Consider making `Format` `Options` not an associated type? +// impl From> for Token { +// fn from(trivia: SyntaxTriviaPieceComments) -> Self { +// let range = trivia.text_range(); +// Token::from_syntax_token_cow_slice( +// normalize_newlines(trivia.text().trim(), LINE_TERMINATORS), +// &trivia.as_piece().token(), +// range.start(), +// ) +// } +// } impl Deref for Token { type Target = str; @@ -1627,8 +559,8 @@ impl FormatElement { match self { FormatElement::Empty => false, FormatElement::Space => false, - FormatElement::Line(line) => matches!(line.mode, LineMode::Hard | LineMode::Empty), - FormatElement::Indent(indent) => indent.content.will_break(), + FormatElement::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty), + FormatElement::Indent(content) => content.will_break(), FormatElement::Group(group) => group.content.will_break(), FormatElement::ConditionalGroupContent(group) => group.content.will_break(), FormatElement::List(list) | FormatElement::Fill(list) => { @@ -1665,7 +597,7 @@ impl FormatElement { (FormatElement::List(list), content) } else { // No leading trivia - (empty_element(), list.content) + (FormatElement::Empty, list.content) }; let content_end = content @@ -1677,17 +609,21 @@ impl FormatElement { let trailing = if trailing_start < content.len() { FormatElement::List(List::new(content.split_off(trailing_start))) } else { - empty_element() + FormatElement::Empty }; (leading, FormatElement::List(List::new(content)), trailing) } else { // All leading trivia - (FormatElement::List(list), empty_element(), empty_element()) + ( + FormatElement::List(list), + FormatElement::Empty, + FormatElement::Empty, + ) } } // Non-list elements are returned directly - _ => (empty_element(), self, empty_element()), + _ => (FormatElement::Empty, self, FormatElement::Empty), } } @@ -1702,7 +638,7 @@ impl FormatElement { FormatElement::Empty | FormatElement::Line(_) | FormatElement::Comment(_) => None, - FormatElement::Indent(indent) => indent.content.last_element(), + FormatElement::Indent(indent) => indent.last_element(), FormatElement::Group(group) => group.content.last_element(), _ => Some(self), @@ -1734,137 +670,123 @@ impl From for FormatElement { } } -impl From for FormatElement { - fn from(token: Line) -> Self { - FormatElement::Line(token) - } -} - -impl From for FormatElement { - fn from(token: Indent) -> Self { - FormatElement::Indent(token) - } -} - impl From> for FormatElement { fn from(element: Option) -> Self { - element.unwrap_or_else(empty_element) + element.unwrap_or_else(|| FormatElement::Empty) } } #[cfg(test)] mod tests { - use crate::format_element::{ - empty_element, join_elements, normalize_newlines, List, LINE_TERMINATORS, - }; + use crate::format_element::{normalize_newlines, LINE_TERMINATORS}; use crate::{concat_elements, space_token, token, FormatElement}; - #[test] - fn concat_elements_returns_a_list_token_containing_the_passed_in_elements() { - let concatenated = concat_elements(vec![token("a"), space_token(), token("b")]); - - assert_eq!( - concatenated, - FormatElement::List(List::new(vec![token("a"), space_token(), token("b")])) - ); - } - - #[test] - fn concat_elements_returns_the_passed_in_element_if_the_content_is_a_list_with_a_single_element( - ) { - let concatenated = concat_elements(vec![token("a")]); - - assert_eq!(concatenated, token("a")); - } - - #[test] - fn concat_elements_the_empty_element_if_the_passed_vector_is_empty() { - let concatenated = concat_elements(vec![]); - - assert_eq!(concatenated, empty_element()); - } - - #[test] - fn concat_elements_flattens_sub_lists_and_skips_empty_elements() { - let concatenated = concat_elements(vec![ - token("a"), - space_token(), - empty_element(), - concat_elements(vec![token("1"), space_token(), token("2")]), - space_token(), - token("b"), - ]); - - assert_eq!( - concatenated, - FormatElement::List(List::new(vec![ - token("a"), - space_token(), - token("1"), - space_token(), - token("2"), - space_token(), - token("b") - ])) - ); - } - - #[test] - fn join_elements_inserts_the_separator_between_elements() { - let joined = join_elements(space_token(), vec![token("a"), token("b"), token("c")]); - - assert_eq!( - joined, - concat_elements(vec![ - token("a"), - space_token(), - token("b"), - space_token(), - token("c") - ]) - ); - } - - #[test] - fn join_returns_the_content_element_if_the_content_contains_a_single_element() { - let joined = join_elements(space_token(), vec![token("a")]); - - assert_eq!(joined, token("a")); - } - - #[test] - fn join_returns_the_empty_element_if_the_passed_vec_is_empty() { - let joined = join_elements(space_token(), vec![]); - - assert_eq!(joined, empty_element()); - } - - #[test] - fn join_flattens_sub_lists_and_skips_empty_elements_without_inserting_separators() { - let joined = join_elements( - space_token(), - vec![ - token("a"), - empty_element(), - concat_elements(vec![token("1"), token("+"), token("2")]), - token("b"), - ], - ); - - assert_eq!( - joined, - FormatElement::List(List::new(vec![ - token("a"), - space_token(), - token("1"), - token("+"), - token("2"), - space_token(), - token("b") - ])) - ); - } + // #[test] + // fn concat_elements_returns_a_list_token_containing_the_passed_in_elements() { + // let concatenated = concat_elements(vec![token("a"), space_token(), token("b")]); + // + // assert_eq!( + // concatenated, + // FormatElement::List(List::new(vec![token("a"), space_token(), token("b")])) + // ); + // } + + // #[test] + // fn concat_elements_returns_the_passed_in_element_if_the_content_is_a_list_with_a_single_element( + // ) { + // let concatenated = concat_elements(vec![token("a")]); + // + // assert_eq!(concatenated, token("a")); + // } + // + // #[test] + // fn concat_elements_the_empty_element_if_the_passed_vector_is_empty() { + // let concatenated = concat_elements(vec![]); + // + // assert_eq!(concatenated, FormatElement::Empty); + // } + // + // #[test] + // fn concat_elements_flattens_sub_lists_and_skips_empty_elements() { + // let concatenated = concat_elements(vec![ + // token("a"), + // space_token(), + // FormatElement::Empty, + // concat_elements(vec![token("1"), space_token(), token("2")]), + // space_token(), + // token("b"), + // ]); + // + // assert_eq!( + // concatenated, + // FormatElement::List(List::new(vec![ + // token("a"), + // space_token(), + // token("1"), + // space_token(), + // token("2"), + // space_token(), + // token("b") + // ])) + // ); + // } + + // #[test] + // fn join_elements_inserts_the_separator_between_elements() { + // let joined = join_elements(space_token(), vec![token("a"), token("b"), token("c")]); + // + // assert_eq!( + // joined, + // concat_elements(vec![ + // token("a"), + // space_token(), + // token("b"), + // space_token(), + // token("c") + // ]) + // ); + // } + // + // #[test] + // fn join_returns_the_content_element_if_the_content_contains_a_single_element() { + // let joined = join_elements(space_token(), vec![token("a")]); + // + // assert_eq!(joined, token("a")); + // } + // + // #[test] + // fn join_returns_the_empty_element_if_the_passed_vec_is_empty() { + // let joined = join_elements(space_token(), vec![]); + // + // assert_eq!(joined, empty_element()); + // } + // + // #[test] + // fn join_flattens_sub_lists_and_skips_empty_elements_without_inserting_separators() { + // let joined = join_elements( + // space_token(), + // vec![ + // token("a"), + // empty_element(), + // concat_elements(vec![token("1"), token("+"), token("2")]), + // token("b"), + // ], + // ); + // + // assert_eq!( + // joined, + // FormatElement::List(List::new(vec![ + // token("a"), + // space_token(), + // token("1"), + // token("+"), + // token("2"), + // space_token(), + // token("b") + // ])) + // ); + // } #[test] fn test_normalize_newlines() { diff --git a/crates/rome_formatter/src/format_extensions.rs b/crates/rome_formatter/src/format_extensions.rs index bda64ddfc4a..4dc37906d28 100644 --- a/crates/rome_formatter/src/format_extensions.rs +++ b/crates/rome_formatter/src/format_extensions.rs @@ -1,7 +1,7 @@ use crate::prelude::*; use std::cell::RefCell; -use crate::IntoFormatElement; +use crate::{write, Buffer, VecBuffer}; use rome_rowan::SyntaxResult; /// Utility trait used to simplify the formatting of optional objects that are formattable. @@ -18,40 +18,50 @@ pub trait FormatOptional { /// ## Examples /// /// ``` + /// use rome_formatter::{FormatContext, write, format}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// /// struct MyFormat; /// /// impl Format for MyFormat { - /// type Context = (); + /// type Context = SimpleFormatContext; /// - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// write!(f, [token("MyToken")]) /// } /// } /// - /// let formatter = Formatter::default(); - /// /// let none_token: Option = None; /// // Returns `empty_element()` for a `None` value - /// let none_result = none_token.with_or_empty(|token| token); - /// assert_eq!(Ok(empty_element()), formatted![&formatter, [none_result]]); + /// let none_formatted = format!(SimpleFormatContext::default(), [ + /// none_token.with_or_empty(|token, f| write!(f, [token])) + /// ]).unwrap(); + /// + /// assert_eq!(FormatElement::Empty, none_formatted.into_format_element()); /// /// let some_token = Some(MyFormat); - /// let some_result = some_token.with_or_empty(|token| { - /// formatted![&formatter, [space_token(), token]] - /// }); - /// assert_eq!(formatted![&formatter, [space_token(), token("MyToken")]], formatted![&formatter, [some_result]]); - fn with_or_empty( + /// assert_eq!( + /// format![SimpleFormatContext::default(), [space_token(), token("MyToken")]], + /// format!( + /// SimpleFormatContext::default(), [ + /// some_token.with_or_empty(|token, f| { + /// write!(f, [space_token(), token]) + /// }) + /// ] + /// ) + /// ); + fn with_or_empty( &self, with: With, - ) -> FormatWithOr FormatElement, WithResult, FormatElement, Self::Context> + ) -> FormatWithOr) -> FormatResult<()>, Self::Context> where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, + With: Fn( + &dyn Format, + &mut Formatter, + ) -> FormatResult<()>, { - self.with_or(with, empty_element) + self.with_or(with, |_| Ok(())) } /// This function tries to format an optional formattable object as is. If the object is [None], @@ -61,28 +71,32 @@ pub trait FormatOptional { /// /// ``` /// use rome_formatter::prelude::*; + /// use rome_formatter::{write, format}; /// use rome_rowan::TextSize; /// /// struct MyFormat; /// /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) + /// type Context = SimpleFormatContext; + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// write!(f, [token("MyToken")]) /// } /// } /// - /// let formatter = Formatter::default(); /// let none_token: Option = None; - /// let result = none_token.or_format(|| token(" other result")); /// - /// assert_eq!(Ok(token(" other result")), formatted![&formatter, [result]]); - fn or_format(&self, op: Or) -> OrFormat + /// assert_eq!( + /// format!(SimpleFormatContext::default(), [token(" other result")]), + /// format!( + /// SimpleFormatContext::default(), + /// [none_token.or_format(|f| write!(f, [token(" other result")]))] + /// ) + /// ); + fn or_format(&self, op: Or) -> OrFormat where - Or: Fn() -> OrResult, - OrResult: IntoFormatElement, + Or: Fn(&mut Formatter) -> FormatResult<()>, { - self.with_or(|token| token, op) + self.with_or(|token, f| token.format(f), op) } /// If the object isn't [None], it will call the first closure which will accept formatted element. @@ -95,42 +109,51 @@ pub trait FormatOptional { /// /// ``` /// use rome_formatter::prelude::*; + /// use rome_formatter::{format, write}; /// use rome_rowan::TextSize; /// /// struct MyFormat; /// /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) + /// type Context = SimpleFormatContext; + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// write!(f, [token("MyToken")]) /// } /// } /// - /// let formatter = Formatter::default(); /// let none_token: Option = None; /// - /// // It returns the `or` result if called on `None` - /// let none_result = none_token.with_or(|token| token, || { - /// token("empty") - /// }); - /// assert_eq!(Ok(token("empty")), formatted![&formatter, [none_result]]); - /// - /// // Returns the result of the first callback when called with `Some(value)` - /// let some_result = Some(MyFormat).with_or(|token| { - /// formatted![&formatter, [space_token(), token]] - /// }, || empty_element()); + /// assert_eq!( + /// format!(SimpleFormatContext::default(), [token("empty")]), + /// format!( + /// SimpleFormatContext::default(), + /// [ + /// // It writes the `or` result if called on `None` + /// none_token.with_or( + /// |token, f| write!(f, [token]), + /// |f| write!(f, [token("empty")]) + /// ) + /// ] + /// ) + /// ); /// - /// assert_eq!(formatted![&formatter, [space_token(), token("MyToken")]], formatted![&formatter, [some_result]]); - fn with_or( - &self, - with: With, - op: Or, - ) -> FormatWithOr + /// assert_eq!( + /// format!(SimpleFormatContext::default(), [space_token(), token("MyToken")]), + /// format!(SimpleFormatContext::default(), [ + /// // Writes the first callback if called with `Some(value)` + /// Some(MyFormat).with_or( + /// |token, f| { write![f, [space_token(), token]]}, + /// |f| { write!(f, [token("empty")])} + /// ) + /// ]) + /// ); + fn with_or(&self, with: With, op: Or) -> FormatWithOr where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - Or: Fn() -> OrResult, - OrResult: IntoFormatElement; + With: Fn( + &dyn Format, + &mut Formatter, + ) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>; } /// Utility trait for formatting a formattable object with some additional content. @@ -146,58 +169,57 @@ pub trait FormatWith: Format { /// /// ``` /// use rome_formatter::prelude::*; + /// use rome_formatter::{write, format}; /// use rome_rowan::TextSize; /// /// struct MyFormat; /// /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) + /// type Context = SimpleFormatContext; + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// write!(f, [token("MyToken")]) /// } /// } /// - /// let formatter = Formatter::default(); - /// - /// let result = MyFormat.with(|string_literal| { - /// formatted![&formatter, [string_literal, space_token(), token("+")]] - /// }); - /// - /// assert_eq!(formatted![&formatter, [token("MyToken"), space_token(), token("+")]], formatted![&formatter, [result]]) - fn with(&self, with: With) -> FormatItemWith + /// assert_eq!( + /// format!(SimpleFormatContext::default(), [token("MyToken"), space_token(), token("+")]), + /// format!(SimpleFormatContext::default(), [ + /// MyFormat.with(|string_literal, f| { + /// write!(f, [string_literal, space_token(), token("+")]) + /// }) + /// ]) + /// ) + fn with(&self, with: With) -> FormatItemWith where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement; + With: Fn( + &dyn Format, + &mut Formatter, + ) -> FormatResult<()>; } -pub struct FormatItemWith<'a, With, WithResult, Context> +pub struct FormatItemWith<'a, With, Context> where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { with: With, inner: &'a dyn Format, } -impl<'a, With, WithResult, Context> Format for FormatItemWith<'a, With, WithResult, Context> +impl<'a, With, Context> Format for FormatItemWith<'a, With, Context> where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { type Context = Context; - fn format(&self, formatter: &Formatter) -> FormatResult { - let element = self.inner.format(formatter)?; - - (self.with)(element).into_format_element(formatter) + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + (self.with)(self.inner, f) } } impl FormatWith for F { - fn with(&self, with: With) -> FormatItemWith + fn with(&self, with: With) -> FormatItemWith where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { FormatItemWith { with, inner: self } } @@ -206,16 +228,10 @@ impl FormatWith for F { impl FormatOptional for SyntaxResult> { type Context = F::Context; - fn with_or( - &self, - with: With, - op: Or, - ) -> FormatWithOr + fn with_or(&self, with: With, op: Or) -> FormatWithOr where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - Or: Fn() -> OrResult, - OrResult: IntoFormatElement, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { match self { Err(_) => FormatWithOr::With { inner: self, with }, @@ -228,16 +244,13 @@ impl FormatOptional for SyntaxResult> { impl FormatOptional for Option { type Context = F::Context; - fn with_or( - &self, - with: With, - op: Or, - ) -> FormatWithOr + fn with_or(&self, with: With, op: Or) -> FormatWithOr where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - Or: Fn() -> OrResult, - OrResult: IntoFormatElement, + With: Fn( + &dyn Format, + &mut Formatter, + ) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { match self { None => FormatWithOr::Or(op), @@ -246,15 +259,17 @@ impl FormatOptional for Option { } } -pub type OrFormat<'a, Or, OrResult, Context> = - FormatWithOr<'a, fn(FormatElement) -> FormatElement, Or, FormatElement, OrResult, Context>; +pub type OrFormat<'a, Or, Context> = FormatWithOr< + 'a, + fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or, + Context, +>; -pub enum FormatWithOr<'a, With, Or, WithResult, OrResult, Context> +pub enum FormatWithOr<'a, With, Or, Context> where - With: Fn(FormatElement) -> WithResult, - Or: Fn() -> OrResult, - WithResult: IntoFormatElement, - OrResult: IntoFormatElement, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { With { inner: &'a dyn Format, @@ -263,23 +278,18 @@ where Or(Or), } -impl<'a, With, Or, WithResult, OrResult, Context> Format - for FormatWithOr<'a, With, Or, WithResult, OrResult, Context> +impl<'a, With, Or, Context> Format for FormatWithOr<'a, With, Or, Context> where - With: Fn(FormatElement) -> WithResult, - Or: Fn() -> OrResult, - WithResult: IntoFormatElement, - OrResult: IntoFormatElement, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { type Context = Context; #[inline] - fn format(&self, formatter: &Formatter) -> FormatResult { + fn format(&self, formatter: &mut Formatter) -> FormatResult<()> { match self { - FormatWithOr::Or(op) => op().into_format_element(formatter), - FormatWithOr::With { inner, with } => { - with(inner.format(formatter)?).into_format_element(formatter) - } + FormatWithOr::Or(op) => op(formatter), + FormatWithOr::With { inner, with } => with(inner, formatter), } } } @@ -293,7 +303,7 @@ pub trait MemoizeFormat { /// /// ``` /// use std::cell::Cell; - /// use rome_formatter::FormatContext; + /// use rome_formatter::{format, write}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// @@ -308,29 +318,28 @@ pub trait MemoizeFormat { /// } /// /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { + /// type Context = SimpleFormatContext; + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// let value = self.value.get(); /// self.value.set(value + 1); /// - /// Ok(FormatElement::from(Token::new_dynamic(format!("Formatted {value} times."), TextSize::from(0)))) + /// write!(f, [dynamic_token(&std::format!("Formatted {value} times."), TextSize::from(0))]) /// } /// } /// - /// let formatter = Formatter::default(); /// let normal = MyFormat::new(); /// /// // Calls `format` for everytime the object gets formatted /// assert_eq!( - /// Ok(format_elements![token("Formatted 1 times."), token("Formatted 2 times.")]), - /// formatted![&formatter, [&normal, &normal]] + /// format!(SimpleFormatContext::default(), [token("Formatted 1 times."), token("Formatted 2 times.")]), + /// format!(SimpleFormatContext::default(), [normal, normal]) /// ); /// /// // Memoized memoizes the result and calls `format` only once. /// let memoized = normal.memoized(); /// assert_eq!( - /// Ok(format_elements![token("Formatted 3 times."), token("Formatted 3 times.")]), - /// formatted![&formatter, [&memoized, &memoized]] + /// format!(SimpleFormatContext::default(), [token("Formatted 3 times."), token("Formatted 3 times.")]), + /// format![SimpleFormatContext::default(), [memoized, memoized]] /// ); /// ``` /// @@ -347,7 +356,7 @@ impl MemoizeFormat for F where F: Format {} /// Memoizes the output of its inner [Format] to avoid re-formatting a potential expensive object. pub struct Memoized { inner: F, - memory: RefCell>>, + memory: RefCell>>>, } impl Memoized { @@ -365,14 +374,39 @@ where { type Context = F::Context; - fn format(&self, formatter: &Formatter) -> FormatResult { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + // Cached if let Some(memory) = self.memory.borrow().as_ref() { - return memory.clone(); + return match memory { + Ok(elements) => { + for element in elements { + f.write_element(element.clone())?; + } + + Ok(()) + } + Err(err) => Err(*err), + }; } + let mut buffer = VecBuffer::new(f.state_mut()); + + let result = write!(buffer, [self.inner]); + + match result { + Ok(_) => { + let elements = buffer.into_vec(); + for element in &elements { + f.write_element(element.clone())?; + } - let formatted = self.inner.format(formatter); - *self.memory.borrow_mut() = Some(formatted.clone()); + *self.memory.borrow_mut() = Some(Ok(elements)); - formatted + Ok(()) + } + Err(err) => { + *self.memory.borrow_mut() = Some(Err(err)); + Err(err) + } + } } } diff --git a/crates/rome_formatter/src/formatter.rs b/crates/rome_formatter/src/formatter.rs index 78de68b631e..74204bd1770 100644 --- a/crates/rome_formatter/src/formatter.rs +++ b/crates/rome_formatter/src/formatter.rs @@ -1,113 +1,168 @@ -use crate::group_id::UniqueGroupIdBuilder; +use crate::builders::{FillBuilder, JoinBuilder}; use crate::prelude::*; #[cfg(debug_assertions)] use crate::printed_tokens::PrintedTokens; -use crate::GroupId; +use crate::{Arguments, Buffer, FormatContext, FormatState, GroupId}; use rome_rowan::{Language, SyntaxNode, SyntaxToken}; -#[cfg(debug_assertions)] -use std::cell::RefCell; /// Handles the formatting of a CST and stores the options how the CST should be formatted (user preferences). /// The formatter is passed to the [Format] implementation of every node in the CST so that they /// can use it to format their children. -#[derive(Default)] -pub struct Formatter { - /// Yields various information that belong to the current instance of the formatter - context: Context, - group_id_builder: UniqueGroupIdBuilder, - // This is using a RefCell as it only exists in debug mode, - // the Formatter is still completely immutable in release builds - #[cfg(debug_assertions)] - pub printed_tokens: RefCell, +pub struct Formatter<'buf, Options> { + buffer: &'buf mut dyn Buffer, } -impl Formatter { +impl<'buf, Context> Formatter<'buf, Context> { /// Creates a new context that uses the given formatter options - pub fn new(options: Context) -> Self { - Self { - context: options, - group_id_builder: Default::default(), - #[cfg(debug_assertions)] - printed_tokens: Default::default(), - } + pub fn new(buffer: &'buf mut (dyn Buffer + 'buf)) -> Self { + Self { buffer } } /// Returns the [FormatOptions] specifying how to format the current CST pub fn context(&self) -> &Context { - &self.context + &self.state().context() } /// Creates a new group id that is unique to this document. The passed debug name is used in the /// [std::fmt::Debug] of the document if this is a debug build. /// The name is unused for production builds and has no meaning on the equality of two group ids. pub fn group_id(&self, debug_name: &'static str) -> GroupId { - self.group_id_builder.group_id(debug_name) + self.state().group_id(debug_name) } - /// Tracks the given token as formatted - #[inline] - pub fn track_token(&self, #[allow(unused_variables)] token: &SyntaxToken) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - self.printed_tokens.borrow_mut().track_token(token); - } - } + /// Concatenates multiple [Format]. + /// + /// ## Examples + /// + /// ```rust + /// use rome_formatter::format; + /// use rome_formatter::prelude::*; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.join() + /// .entry(&token("a")) + /// .entry(&space_token()) + /// .entry(&token("+")) + /// .entry(&space_token()) + /// .entry(&token("b")) + /// .finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// "a + b", + /// formatted.print().as_code() + /// ) + /// ``` + pub fn join<'a>(&'a mut self) -> JoinBuilder<'a, '_, 'buf, Context> { + JoinBuilder::new(self) } - #[inline] - pub fn assert_formatted_all_tokens( - &self, - #[allow(unused_variables)] root: &SyntaxNode, - ) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - let printed_tokens = self.printed_tokens.borrow(); - printed_tokens.assert_all_tracked(root); - } - } + /// Joins the elements by placing a given separator between elements. + /// + /// ## Examples + /// + /// Joining different tokens by separating them with a comma and a space. + /// + /// ``` + /// use rome_formatter::{format, format_args}; + /// use rome_formatter::prelude::*; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.join_with(&format_args!(token(","), space_token())) + /// .entry(&token("1")) + /// .entry(&token("2")) + /// .entry(&token("3")) + /// .entry(&token("4")) + /// .finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// "1, 2, 3, 4", + /// formatted.print().as_code() + /// ); + /// ``` + pub fn join_with<'a, 'joiner>( + &'a mut self, + joiner: &'joiner dyn Format, + ) -> JoinBuilder<'a, 'joiner, 'buf, Context> { + JoinBuilder::with(self, joiner) } - /// Formats all items of the iterator and returns the formatted result + /// Concatenates a list of [FormatElement]s with spaces and line breaks to fit + /// them on as few lines as possible. Each element introduces a conceptual group. The printer + /// first tries to print the item in flat mode but then prints it in expanded mode if it doesn't fit. /// - /// Returns the [Err] of the first item that failed to format. - #[inline] - pub fn format_all>( - &self, - nodes: impl IntoIterator, - ) -> FormatResult> { - let mut result = Vec::new(); + /// ## Examples + /// + /// ```rust + /// use rome_formatter::prelude::*; + /// use rome_formatter::{format, format_args}; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.fill(&soft_line_break_or_space()) + /// .entry(&token("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) + /// .entry(&token("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) + /// .entry(&token("cccccccccccccccccccccccccccccc")) + /// .entry(&token("dddddddddddddddddddddddddddddd")) + /// .finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\ncccccccccccccccccccccccccccccc dddddddddddddddddddddddddddddd", + /// formatted.print().as_code() + /// ) + /// ``` + pub fn fill<'a, 'with>( + &'a mut self, + separator: &'with dyn Format, + ) -> FillBuilder<'a, 'with, 'buf, Context> { + FillBuilder::new(self, separator) + } +} - for node in nodes { - match node.format(self) { - Ok(formatted) => { - result.push(formatted); - } - Err(err) => return Err(err), - } - } +impl Formatter<'_, Options> { + // TODO - Ok(result.into_iter()) - } + // /// Take a snapshot of the state of the formatter + // #[inline] + // pub fn snapshot(&self) -> FormatterSnapshot { + // FormatterSnapshot { + // #[cfg(debug_assertions)] + // printed_tokens: self.printed_tokens.borrow().clone(), + // } + // } + // + // #[inline] + // /// Restore the state of the formatter to a previous snapshot + // pub fn restore(&self, #[allow(unused)] snapshot: FormatterSnapshot) { + // cfg_if::cfg_if! { + // if #[cfg(debug_assertions)] { + // *self.printed_tokens.borrow_mut() = snapshot.printed_tokens; + // } + // } + // } } -impl Formatter { - /// Take a snapshot of the state of the formatter - #[inline] - pub fn snapshot(&self) -> FormatterSnapshot { - FormatterSnapshot { - #[cfg(debug_assertions)] - printed_tokens: self.printed_tokens.borrow().clone(), - } +impl Buffer for Formatter<'_, O> { + type Context = O; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + self.buffer.write_element(element) } - #[inline] - /// Restore the state of the formatter to a previous snapshot - pub fn restore(&self, #[allow(unused)] snapshot: FormatterSnapshot) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - *self.printed_tokens.borrow_mut() = snapshot.printed_tokens; - } + fn write_fmt(self: &mut Self, arguments: &Arguments) -> FormatResult<()> { + for argument in arguments.items() { + argument.format(self)?; } + Ok(()) + } + + fn state(&self) -> &FormatState { + self.buffer.state() + } + + fn state_mut(&mut self) -> &mut FormatState { + self.buffer.state_mut() } } diff --git a/crates/rome_formatter/src/lib.rs b/crates/rome_formatter/src/lib.rs index 6fae7ffdc34..644cdca1e6d 100644 --- a/crates/rome_formatter/src/lib.rs +++ b/crates/rome_formatter/src/lib.rs @@ -23,6 +23,8 @@ extern crate core; +mod arguments; +mod buffer; mod builders; pub mod format_element; mod format_extensions; @@ -37,14 +39,16 @@ pub mod printer; use crate::formatter::Formatter; use crate::printer::{Printer, PrinterOptions}; -pub use builders::ConcatBuilder; +pub use arguments::{Argument, Arguments}; +pub use buffer::{Buffer, FormatState, VecBuffer}; +pub use builders::{ + block_indent, comment, empty_element, empty_line, group_elements, group_elements_with_options, + hard_line_break, if_group_breaks, if_group_fits_on_single_line, if_group_with_id_breaks, + indent, line_suffix, soft_block_indent, soft_line_break, soft_line_break_or_space, + soft_line_indent_or_space, space_token, token, ConcatBuilder, +}; pub use format_element::{ - block_indent, comment, concat_elements, empty_element, empty_line, fill_elements, - group_elements, hard_line_break, if_group_breaks, if_group_fits_on_single_line, indent, - join_elements, join_elements_hard_line, join_elements_soft_line, join_elements_with, - line_suffix, normalize_newlines, soft_block_indent, soft_line_break, soft_line_break_or_space, - soft_line_indent_or_space, space_token, token, FormatElement, Token, Verbatim, - LINE_TERMINATORS, + concat_elements, normalize_newlines, FormatElement, Token, Verbatim, LINE_TERMINATORS, }; pub use group_id::GroupId; use rome_rowan::{ @@ -91,8 +95,8 @@ impl FromStr for IndentStyle { impl fmt::Display for IndentStyle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - IndentStyle::Tab => write!(f, "Tab"), - IndentStyle::Space(size) => write!(f, "Spaces, size: {}", size), + IndentStyle::Tab => std::write!(f, "Tab"), + IndentStyle::Space(size) => std::write!(f, "Spaces, size: {}", size), } } } @@ -130,7 +134,7 @@ pub enum ParseLineWidthError { impl fmt::Display for ParseLineWidthError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(fmt, "{self:?}") + std::write!(fmt, "{self:?}") } } @@ -175,12 +179,34 @@ pub trait FormatContext { fn indent_style(&self) -> IndentStyle; /// What's the max width of a line. Defaults to 80. - fn line_with(&self) -> LineWidth; + fn line_width(&self) -> LineWidth; /// Derives the print options from the these format options fn as_print_options(&self) -> PrinterOptions; } +#[derive(Debug, Default)] +pub struct SimpleFormatContext { + pub indent_style: IndentStyle, + pub line_width: LineWidth, +} + +impl FormatContext for SimpleFormatContext { + fn indent_style(&self) -> IndentStyle { + self.indent_style + } + + fn line_width(&self) -> LineWidth { + self.line_width + } + + fn as_print_options(&self) -> PrinterOptions { + PrinterOptions::default() + .with_indent(self.indent_style) + .with_print_width(self.line_width) + } +} + /// Lightweight sourcemap marker between source and output tokens #[derive(Debug, Clone, Eq, PartialEq)] pub struct SourceMarker { @@ -190,7 +216,7 @@ pub struct SourceMarker { pub dest: TextSize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Eq, PartialEq)] pub struct Formatted { root: FormatElement, options: PrinterOptions, @@ -337,54 +363,35 @@ impl From<&SyntaxError> for FormatError { /// Implementing `Format` for a custom struct /// /// ``` -/// use rome_formatter::{format, FormatContext, IndentStyle, LineWidth}; +/// use rome_formatter::{format, write, IndentStyle, LineWidth}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// /// struct Paragraph(String); /// /// impl Format for Paragraph { -/// type Context = Context; -/// -/// fn format(&self, formatter: &Formatter) -> FormatResult { -/// formatted![ -/// formatter, -/// [ -/// hard_line_break(), -/// FormatElement::from(Token::new_dynamic(self.0.clone(), TextSize::from(0))), -/// hard_line_break(), -/// ] -/// ] -/// } -/// } -/// -/// struct Context; -/// -/// impl FormatContext for Context { -/// fn indent_style(&self) -> IndentStyle { -/// IndentStyle::Tab -/// } +/// type Context = SimpleFormatContext; /// -/// fn line_with(&self) -> LineWidth { -/// LineWidth::default() -/// } -/// -/// fn as_print_options(&self) -> PrinterOptions { -/// PrinterOptions::default() +/// fn format(&self, f: &mut Formatter) -> FormatResult<()> { +/// write!(f, [ +/// hard_line_break(), +/// dynamic_token(&self.0, TextSize::from(0)), +/// hard_line_break(), +/// ]) /// } /// } /// /// let paragraph = Paragraph(String::from("test")); -/// let printed = format(Context, ¶graph).unwrap().print(); +/// let formatted = format!(SimpleFormatContext::default(), [paragraph]).unwrap(); /// -/// assert_eq!("test\n", printed.as_code()) +/// assert_eq!("test\n", formatted.print().as_code()) /// ``` pub trait Format { /// Type of the formatter options. type Context; /// Formats the object - fn format(&self, formatter: &Formatter) -> FormatResult; + fn format(&self, f: &mut Formatter) -> FormatResult<()>; } impl Format for &T @@ -393,8 +400,8 @@ where { type Context = T::Context; - fn format(&self, formatter: &Formatter) -> FormatResult { - Format::format(&**self, formatter) + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + Format::format(&**self, f) } } @@ -404,8 +411,8 @@ where { type Context = T::Context; - fn format(&self, formatter: &Formatter) -> FormatResult { - Format::format(&**self, formatter) + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + Format::format(&**self, f) } } @@ -415,10 +422,10 @@ where { type Context = T::Context; - fn format(&self, formatter: &Formatter) -> FormatResult { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { match self { - Some(value) => value.format(formatter), - None => Ok(empty_element()), + Some(value) => value.format(f), + None => Ok(()), } } } @@ -429,46 +436,14 @@ where { type Context = T::Context; - fn format(&self, formatter: &Formatter) -> FormatResult { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { match self { - Ok(value) => value.format(formatter), + Ok(value) => value.format(f), Err(err) => Err(err.into()), } } } -/// Implemented by traits that can be converted to a `FormatElement`. -/// -/// This is similar to [Format] but with the difference that it consumes `self`, allowing it to also -/// be implemented on [FormatElement].format_elements.rs -pub trait IntoFormatElement { - fn into_format_element(self, formatter: &Formatter) -> FormatResult; -} - -impl IntoFormatElement for FormatElement { - #[inline] - fn into_format_element(self, _: &Formatter) -> FormatResult { - Ok(self) - } -} - -impl IntoFormatElement for FormatResult { - #[inline] - fn into_format_element(self, _: &Formatter) -> FormatResult { - self - } -} - -impl IntoFormatElement for T -where - T: Format, -{ - #[inline] - fn into_format_element(self, formatter: &Formatter) -> FormatResult { - self.format(formatter) - } -} - /// Rule that knows how to format an object of type [T]. /// /// Implementing [Format] on the object itself is preferred over implementing [FormatRule] but @@ -482,7 +457,7 @@ where pub trait FormatRule { type Context; - fn format(item: &T, formatter: &Formatter) -> FormatResult; + fn format(item: &T, f: &mut Formatter) -> FormatResult<()>; } /// Trait for an object that formats an object with a specified rule. @@ -500,12 +475,10 @@ pub trait FormatRule { /// /// ``` /// use rome_formatter::prelude::*; -/// use rome_formatter::{FormatContext, FormatWithRule}; +/// use rome_formatter::{format, Formatted, FormatWithRule}; /// use rome_rowan::{Language, SyntaxNode}; -/// fn format_node, Context=()>>(node: F) -> FormatResult { -/// let formatter = Formatter::default(); -/// -/// let formatted = node.format(&formatter); +/// fn format_node, Context=SimpleFormatContext>>(node: F) -> FormatResult { +/// let formatted = format!(SimpleFormatContext::default(), [node]); /// let _syntax = node.item(); /// /// // Do something with syntax @@ -558,8 +531,8 @@ where type Context = R::Context; #[inline] - fn format(&self, formatter: &Formatter) -> FormatResult { - R::format(self.item, formatter) + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + R::format(self.item, f) } } @@ -600,8 +573,8 @@ where type Context = R::Context; #[inline] - fn format(&self, formatter: &Formatter) -> FormatResult { - R::format(&self.item, formatter) + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + R::format(&self.item, f) } } @@ -616,18 +589,30 @@ where } } -/// Formats any value that implements [Format]. -/// -/// Please note that [format_node] is preferred to format a [JsSyntaxNode] -pub fn format( - options: C, - root: &dyn Format, -) -> FormatResult { - tracing::trace_span!("format").in_scope(move || { - let printer_options = options.as_print_options(); - let formatter = Formatter::new(options); - let element = root.format(&formatter)?; - Ok(Formatted::new(element, printer_options)) +pub fn write( + output: &mut dyn Buffer, + args: &Arguments, +) -> FormatResult<()> { + let mut f = Formatter::new(output); + + f.write_fmt(args) +} + +/// Creates the formatter IR for the passed in item +/// Or use `format!` marco instead? +pub fn format(context: Context, arguments: &Arguments) -> FormatResult +where + Context: FormatContext, +{ + let print_options = context.as_print_options(); + let mut state = FormatState::new(context); + let mut buffer = VecBuffer::new(&mut state); + + buffer.write_fmt(arguments)?; + + Ok(Formatted { + root: buffer.into_document().into_element(), + options: print_options, }) } @@ -639,17 +624,21 @@ pub fn format_node< L: Language, N: FormatWithRule, Context = C>, >( - options: C, + context: C, root: &N, ) -> FormatResult { tracing::trace_span!("format_node").in_scope(move || { - let printer_options = options.as_print_options(); - let formatter = Formatter::new(options); - let element = formatted![&formatter, [root]]?; + let print_options = context.as_print_options(); + let mut context = FormatState::new(context); + let mut buffer = VecBuffer::new(&mut context); + + write!(&mut buffer, [root])?; + + let document = buffer.into_document().into_element(); - formatter.assert_formatted_all_tokens(root.item()); + context.assert_formatted_all_tokens(root.item()); - Ok(Formatted::new(element, printer_options)) + Ok(Formatted::new(document, print_options)) }) } diff --git a/crates/rome_formatter/src/macros.rs b/crates/rome_formatter/src/macros.rs index 58396bdc39b..f1097b29647 100644 --- a/crates/rome_formatter/src/macros.rs +++ b/crates/rome_formatter/src/macros.rs @@ -1,6 +1,52 @@ -use crate::prelude::*; -use crate::{ConcatBuilder, IntoFormatElement}; -use std::marker::PhantomData; +/// TODO consider adding JSX kind of support: `{} +#[macro_export] +macro_rules! format_args { + ($($value:expr),+ $(,)?) => { + &$crate::Arguments::new(&[ + $( + $crate::Argument::new(&$value) + ),+ + ]) + } +} + +#[macro_export] +macro_rules! write { + ($dst:expr, [$($arg:expr),+ $(,)?]) => {{ + use $crate::Buffer; + $dst.write_fmt($crate::format_args!($($arg),+)) + }} +} + +/// Creates the Format IR for a value. +/// +/// The first argument `format!` receives is the [FormatContext] that specify how elements must be formatted. +/// Additional parameters passed get formatted by using their [Format] implementation. +/// +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::format; +/// +/// let formatted = format!(SimpleFormatContext::default(), [token("("), token("a"), token(")")]).unwrap(); +/// +/// assert_eq!( +/// formatted.into_format_element(), +/// format_elements![ +/// FormatElement::Token(Token::Static { text: "(" }), +/// FormatElement::Token(Token::Static { text: "a" }), +/// FormatElement::Token(Token::Static { text: ")" }), +/// ] +/// ); +/// ``` +#[macro_export] +macro_rules! format { + ($context:expr, [$($arg:expr),+ $(,)?]) => {{ + ($crate::format($context, $crate::format_args!($($arg),+))) + }} +} /// The macro `format_elements` is a convenience macro to /// use when writing a list of tokens that should be at the same level @@ -72,98 +118,6 @@ macro_rules! format_elements { }}; } -/// The macro `formatted` is a convenience macro to chain a list of [FormatElement] or objects -/// that implement [IntoFormatElement] (which is implemented by all object implementing [Format]). -/// -/// # Examples -/// -/// Let's suppose you need to create tokens for the string `"foo": "bar"`, -/// you would write: -/// -/// ```rust -/// use rome_formatter::FormatContext; -/// use rome_formatter::prelude::*; -/// -/// struct TestFormat; -/// -/// impl Format for TestFormat { -/// type Context = (); -/// fn format(&self, _: &Formatter) -> FormatResult { -/// Ok(token("test")) -/// } -/// } -/// -/// let formatter = Formatter::default(); -/// -/// let formatted = formatted![ -/// &formatter, -/// [ -/// token("a"), -/// space_token(), -/// token("simple"), -/// space_token(), -/// TestFormat -/// ] -/// ] -/// .unwrap(); -/// -/// assert_eq!( -/// formatted, -/// concat_elements([ -/// token("a"), -/// space_token(), -/// token("simple"), -/// space_token(), -/// token("test") -/// ]) -/// ); -/// ``` -/// -/// Or you can also create single element: -/// ``` -/// use rome_formatter::prelude::*; -/// use rome_formatter::FormatContext; -/// -/// let formatter = Formatter::<()>::default(); -/// -/// let formatted = formatted![&formatter, [token("test")]].unwrap(); -/// -/// assert_eq!(formatted, token("test")); -/// ``` -#[macro_export] -macro_rules! formatted { - - // called for things like formatted![formatter, [token("test")]] - ($formatter:expr, [$element:expr]) => { - { - $crate::IntoFormatElement::into_format_element($element, $formatter) - } - }; - - ($formatter:expr, [$($element:expr),+ $(,)?]) => {{ - use $crate::macros::FormatBuilder; - - const SIZE: usize = $crate::__count_elements!($($element),*); - - let mut builder = FormatBuilder::new(SIZE); - - $( - builder.entry($element, $formatter); - )+ - - builder.finish() - }}; -} - -// Helper macro that counts the count of elements passed -#[doc(hidden)] -#[macro_export] -macro_rules! __count_elements { - () => {0usize}; - ($ex:expr) => {1usize}; - ($_head:expr, $($tail:expr),* $(,)?) => {1usize + $crate::__count_elements!($($tail),*)}; -} - /// Provides multiple different alternatives and the printer picks the first one that fits. /// Use this as last resort because it requires that the printer must try all variants in the worst case. /// The passed variants must be in the following order: @@ -271,71 +225,40 @@ macro_rules! best_fitting { }} } -#[doc(hidden)] -pub struct FormatBuilder { - builder: ConcatBuilder, - result: Result<(), FormatError>, - options: PhantomData, -} - -impl FormatBuilder { - #[inline] - pub fn new(size: usize) -> Self { - let mut builder = ConcatBuilder::new(); - builder.size_hint((size, Some(size))); - - Self { - builder, - result: Ok(()), - options: PhantomData, - } - } - - #[inline] - pub fn entry(&mut self, element: T, formatter: &Formatter) - where - T: IntoFormatElement, - { - self.result = self.result.and_then(|_| { - self.builder.entry(element.into_format_element(formatter)?); - Ok(()) - }); - } - - #[inline] - pub fn finish(self) -> FormatResult { - self.result.map(|_| self.builder.finish()) - } -} - #[cfg(test)] mod tests { use crate::prelude::*; + use crate::{write, FormatContext, FormatState, VecBuffer}; struct TestFormat; impl Format for TestFormat { type Context = (); - fn format(&self, _: &Formatter) -> FormatResult { - Ok(token("test")) + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + write!(f, [token("test")]) } } #[test] fn test_single_element() { - let formatter = Formatter::new(()); + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); - let formatted = formatted![&formatter, [TestFormat]].unwrap(); + write![&mut buffer, [TestFormat]].unwrap(); - assert_eq!(formatted, token("test")); + assert_eq!( + buffer.into_document().into_element(), + FormatElement::Token(Token::Static { text: "test" }) + ); } #[test] fn test_multiple_elements() { - let formatter = Formatter::new(()); + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); - let formatted = formatted![ - &formatter, + write![ + &mut buffer, [ token("a"), space_token(), @@ -347,14 +270,14 @@ mod tests { .unwrap(); assert_eq!( - formatted, - concat_elements([ - token("a"), - space_token(), - token("simple"), - space_token(), - token("test") - ]) + buffer.into_document().into_element(), + FormatElement::List(List::new(vec![ + FormatElement::Token(Token::Static { text: "a" }), + FormatElement::Space, + FormatElement::Token(Token::Static { text: "simple" }), + FormatElement::Space, + FormatElement::Token(Token::Static { text: "test" }) + ])) ); } } diff --git a/crates/rome_formatter/src/prelude.rs b/crates/rome_formatter/src/prelude.rs index 8358c997dfe..691675ebb7c 100644 --- a/crates/rome_formatter/src/prelude.rs +++ b/crates/rome_formatter/src/prelude.rs @@ -1,9 +1,10 @@ +pub use crate::builders::*; pub use crate::format_element::*; pub use crate::format_extensions::{FormatOptional as _, FormatWith as _, MemoizeFormat}; pub use crate::formatter::Formatter; pub use crate::printer::PrinterOptions; pub use crate::{ - best_fitting, format_elements, formatted, Format, Format as _, FormatError, FormatResult, - FormatRule, FormatWithRule as _, IntoFormatElement as _, + best_fitting, format, format_args, format_elements, write, Format, Format as _, FormatError, + FormatResult, FormatRule, FormatWithRule as _, SimpleFormatContext, }; diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index 31c10fefc55..4d16b4dfb1e 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -6,9 +6,8 @@ use crate::format_element::{ ConditionalGroupContent, Group, LineMode, List, PrintMode, VerbatimKind, }; use crate::intersperse::Intersperse; -use crate::{hard_line_break, FormatElement, GroupId, Printed, SourceMarker, TextRange}; +use crate::{FormatElement, GroupId, Printed, SourceMarker, TextRange}; -use crate::prelude::Line; use rome_rowan::TextSize; use std::iter::{once, Rev}; @@ -168,9 +167,9 @@ impl<'a> Printer<'a> { queue.extend(list.iter().map(|t| PrintElementCall::new(t, args))); } - FormatElement::Indent(indent) => { + FormatElement::Indent(content) => { queue.enqueue(PrintElementCall::new( - &indent.content, + &content, args.with_incremented_indent(), )); } @@ -194,11 +193,11 @@ impl<'a> Printer<'a> { } } - FormatElement::Line(line) => { + FormatElement::Line(line_mode) => { if args.mode.is_flat() - && matches!(line.mode, LineMode::Soft | LineMode::SoftOrSpace) + && matches!(line_mode, LineMode::Soft | LineMode::SoftOrSpace) { - if line.mode == LineMode::SoftOrSpace && self.state.line_width > 0 { + if line_mode == &LineMode::SoftOrSpace && self.state.line_width > 0 { self.state.pending_space = true; } } else if !self.state.line_suffixes.is_empty() { @@ -210,7 +209,7 @@ impl<'a> Printer<'a> { } // Print a second line break if this is an empty line - if line.mode == LineMode::Empty && !self.state.has_empty_line { + if line_mode == &LineMode::Empty && !self.state.has_empty_line { self.print_str("\n"); self.state.has_empty_line = true; } @@ -230,7 +229,7 @@ impl<'a> Printer<'a> { .push(PrintElementCall::new(&**suffix, args)); } FormatElement::LineSuffixBoundary => { - const HARD_BREAK: &FormatElement = &hard_line_break(); + const HARD_BREAK: &FormatElement = &FormatElement::Line(LineMode::Hard); self.queue_line_suffixes(HARD_BREAK, args, queue); } @@ -348,7 +347,7 @@ impl<'a> Printer<'a> { args: PrintElementArgs, ) { const SPACE: &FormatElement = &FormatElement::Space; - const HARD_LINE_BREAK: &FormatElement = &FormatElement::Line(Line::new(LineMode::Hard)); + const HARD_LINE_BREAK: &FormatElement = &FormatElement::Line(LineMode::Hard); let empty_rest = ElementCallQueue::default(); let mut items = content.iter(); @@ -703,9 +702,9 @@ fn fits_element_on_line<'a, 'rest>( } } - FormatElement::Line(line) => { + FormatElement::Line(line_mode) => { if args.mode.is_flat() { - match line.mode { + match line_mode { LineMode::SoftOrSpace => { state.pending_space = true; } @@ -723,8 +722,8 @@ fn fits_element_on_line<'a, 'rest>( } } - FormatElement::Indent(indent) => queue.enqueue(PrintElementCall::new( - &indent.content, + FormatElement::Indent(content) => queue.enqueue(PrintElementCall::new( + &content, args.with_incremented_indent(), )), @@ -906,46 +905,56 @@ impl<'a, 'rest> MeasureQueue<'a, 'rest> { mod tests { use crate::prelude::*; use crate::printer::{LineEnding, Printer, PrinterOptions}; - use crate::FormatElement::LineSuffix; - use crate::{LineWidth, Printed}; + use crate::{format_args, write, FormatContext, FormatState, LineWidth, Printed, VecBuffer}; + + fn format(root: &dyn Format) -> Printed { + format_with_options( + root, + PrinterOptions { + indent_string: String::from(" "), + ..PrinterOptions::default() + }, + ) + } - /// Prints the given element with the default printer options - fn print_element>(element: T) -> Printed { - let options = PrinterOptions { - indent_string: String::from(" "), - ..PrinterOptions::default() - }; + fn format_with_options(root: &dyn Format, options: PrinterOptions) -> Printed { + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); + + write!(&mut buffer, [root]).unwrap(); - Printer::new(options).print(&element.into()) + Printer::new(options).print(&buffer.into_document().into_element()) } #[test] fn it_prints_a_group_on_a_single_line_if_it_fits() { - let result = print_element(create_array_element(vec![ - token("\"a\""), - token("\"b\""), - token("\"c\""), - token("\"d\""), - ])); + let result = format(&FormatArrayElements { + items: vec![ + &token("\"a\""), + &token("\"b\""), + &token("\"c\""), + &token("\"d\""), + ], + }); assert_eq!(r#"["a", "b", "c", "d"]"#, result.as_code()) } #[test] fn it_tracks_the_indent_for_each_token() { - let element = format_elements![ + let formatted = format(&format_args!( token("a"), - soft_block_indent(format_elements![ + soft_block_indent(&format_args!( token("b"), - soft_block_indent(format_elements![ + soft_block_indent(&format_args!( token("c"), - soft_block_indent(format_elements![token("d"), soft_line_break(), token("d"),],), + soft_block_indent(&format_args!(token("d"), soft_line_break(), token("d"),)), token("c"), - ],), + )), token("b"), - ],), - token("a"), - ]; + )), + token("a") + )); assert_eq!( r#"a @@ -956,7 +965,7 @@ mod tests { c b a"#, - print_element(element).as_code() + formatted.as_code() ) } @@ -967,14 +976,15 @@ a"#, ..PrinterOptions::default() }; - let program = format_elements![ - token("function main() {"), - block_indent(token("let x = `This is a multiline\nstring`;"),), - token("}"), - hard_line_break(), - ]; - - let result = Printer::new(options).print(&program); + let result = format_with_options( + &format_args![ + token("function main() {"), + block_indent(&token("let x = `This is a multiline\nstring`;")), + token("}"), + hard_line_break() + ], + options, + ); assert_eq!( "function main() {\r\n\tlet x = `This is a multiline\r\nstring`;\r\n}\r\n", @@ -984,10 +994,12 @@ a"#, #[test] fn it_breaks_a_group_if_a_string_contains_a_newline() { - let result = print_element(create_array_element(vec![ - token("`This is a string spanning\ntwo lines`"), - token("\"b\""), - ])); + let result = format(&FormatArrayElements { + items: vec![ + &token("`This is a string spanning\ntwo lines`"), + &token("\"b\""), + ], + }); assert_eq!( r#"[ @@ -998,12 +1010,11 @@ two lines`, result.as_code() ) } - #[test] fn it_breaks_a_group_if_it_contains_a_hard_line_break() { - let result = print_element(group_elements(format_elements![ + let result = format(&group_elements(&format_args![ token("a"), - block_indent(token("b")) + block_indent(&token("b")) ])); assert_eq!("a\n b\n", result.as_code()) @@ -1011,19 +1022,23 @@ two lines`, #[test] fn it_breaks_parent_groups_if_they_dont_fit_on_a_single_line() { - let result = print_element(create_array_element(vec![ - token("\"a\""), - token("\"b\""), - token("\"c\""), - token("\"d\""), - create_array_element(vec![ - token("\"0123456789\""), - token("\"0123456789\""), - token("\"0123456789\""), - token("\"0123456789\""), - token("\"0123456789\""), - ]), - ])); + let result = format(&FormatArrayElements { + items: vec![ + &token("\"a\""), + &token("\"b\""), + &token("\"c\""), + &token("\"d\""), + &FormatArrayElements { + items: vec![ + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + ], + }, + ], + }); assert_eq!( r#"[ @@ -1039,24 +1054,26 @@ two lines`, #[test] fn it_use_the_indent_character_specified_in_the_options() { - let printer = Printer::new(PrinterOptions { + let options = PrinterOptions { indent_string: String::from("\t"), tab_width: 4, print_width: LineWidth::try_from(19).unwrap(), ..PrinterOptions::default() - }); - - let element = - create_array_element(vec![token("'a'"), token("'b'"), token("'c'"), token("'d'")]); + }; - let result = printer.print(&element); + let result = format_with_options( + &FormatArrayElements { + items: vec![&token("'a'"), &token("'b'"), &token("'c'"), &token("'d'")], + }, + options, + ); assert_eq!("[\n\t'a',\n\t\'b',\n\t\'c',\n\t'd',\n]", result.as_code()); } #[test] fn it_prints_consecutive_hard_lines_as_one() { - let result = print_element(format_elements![ + let result = format(&format_args![ token("a"), hard_line_break(), hard_line_break(), @@ -1069,7 +1086,7 @@ two lines`, #[test] fn it_prints_consecutive_empty_lines_as_one() { - let result = print_element(format_elements![ + let result = format(&format_args![ token("a"), empty_line(), empty_line(), @@ -1082,7 +1099,7 @@ two lines`, #[test] fn it_prints_consecutive_mixed_lines_as_one() { - let result = print_element(format_elements![ + let result = format(&format_args![ token("a"), empty_line(), hard_line_break(), @@ -1096,26 +1113,34 @@ two lines`, #[test] fn test_fill_breaks() { - let document = fill_elements(vec![ + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); + let mut formatter = Formatter::new(&mut buffer); + + formatter + .fill(&soft_line_break_or_space()) // These all fit on the same line together - format_elements![token("1"), token(",")], - format_elements![token("2"), token(",")], - format_elements![token("3"), token(",")], + .entry(&format_args!(token("1"), token(","))) + .entry(&format_args!(token("2"), token(","))) + .entry(&format_args!(token("3"), token(","))) // This one fits on a line by itself, - format_elements![token("723493294"), token(",")], + .entry(&format_args!(token("723493294"), token(","))) // fits without breaking - format_elements![group_elements(format_elements![ + .entry(&group_elements(&format_args!( token("["), - soft_block_indent(token("5")), + soft_block_indent(&token("5")), token("],") - ])], + ))) // this one must be printed in expanded mode to fit - group_elements(format_elements![ + .entry(&group_elements(&format_args!( token("["), - soft_block_indent(token("123456789")), + soft_block_indent(&token("123456789")), token("]"), - ]), - ]); + ))) + .finish() + .unwrap(); + + let document = buffer.into_document().into_element(); let printed = Printer::new(PrinterOptions::default().with_print_width(LineWidth(10))) .print(&document); @@ -1127,40 +1152,52 @@ two lines`, } #[test] - fn line_suffix() { - let document = format_elements![ - group_elements(format_elements![ + fn line_suffix_printed_at_end() { + let printed = format(&format_args![ + group_elements(&format_args![ token("["), - soft_block_indent(format_elements![fill_elements(vec![ - format_elements![token("1"), token(",")], - format_elements![token("2"), token(",")], - format_elements![token("3"), if_group_breaks(token(","))] - ])]), + soft_block_indent(&format_with(|f| { + f.fill(&soft_line_break_or_space()) + .entry(&format_args!(token("1"), token(","))) + .entry(&format_args!(token("2"), token(","))) + .entry(&format_args!(token("3"), if_group_breaks(&token(",")))) + .finish() + })), token("]") ]), token(";"), - comment(LineSuffix(Box::new(format_elements![ + comment(&line_suffix(&format_args![ space_token(), token("// trailing"), space_token() - ]))) - ]; - - let printed = print_element(document); + ])) + ]); assert_eq!(printed.as_code(), "[1, 2, 3]; // trailing") } - fn create_array_element(items: Vec) -> FormatElement { - let separator = format_elements![token(","), soft_line_break_or_space(),]; - - let elements = - format_elements![join_elements(separator, items), if_group_breaks(token(","))]; + struct FormatArrayElements<'a> { + items: Vec<&'a dyn Format>, + } - group_elements(format_elements![ - token("["), - soft_block_indent(elements), - token("]"), - ]) + impl Format for FormatArrayElements<'_> { + type Context = (); + + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + write!( + f, + [group_elements(&format_args!( + token("["), + soft_block_indent(&format_args!( + format_with(|f| f + .join_with(&format_args!(token(","), soft_line_break_or_space())) + .entries(&self.items) + .finish()), + if_group_breaks(&token(",")), + )), + token("]") + ))] + ) + } } } diff --git a/crates/rome_js_formatter/src/formatter.rs b/crates/rome_js_formatter/src/formatter.rs index 07b0c3c0b2e..b76d50493c0 100644 --- a/crates/rome_js_formatter/src/formatter.rs +++ b/crates/rome_js_formatter/src/formatter.rs @@ -442,9 +442,9 @@ pub(crate) trait JsFormatterExt { current_token: &JsSyntaxToken, content_to_replace_with: FormatElement, ) -> FormatElement { - let formatter = self.as_formatter(); + let f = self.as_formatter(); - formatter.track_token(current_token); + f.track_token(current_token); format_elements![ format_leading_trivia(current_token, TriviaPrintMode::Full), diff --git a/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs index dfe577a78fc..3ec7f421f92 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs @@ -5,12 +5,9 @@ use rome_js_syntax::JsStaticModifier; use rome_js_syntax::JsStaticModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStaticModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsStaticModifier, f: &mut JsFormatter) -> FormatResult<()> { let JsStaticModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs index 6b9d03c69b9..86695c38511 100644 --- a/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use std::fmt; use crate::FormatNodeFields; use rome_formatter::Token; @@ -29,7 +30,7 @@ impl FormatNodeFields for FormatNodeRule(); let sorted_regex_literal = Token::from_syntax_token_cow_slice( - std::borrow::Cow::Owned(format!( + std::borrow::Cow::Owned(std::format!( "{}{}", &trimmed_raw_string[0..end_slash_pos + 1], sorted_flag_string diff --git a/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs index 6e8d6bcf7b6..7fcdfb3d91b 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs @@ -9,16 +9,16 @@ impl FormatNodeFields { fn format_fields( node: &JsExportNamedShorthandSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsExportNamedShorthandSpecifierFields { type_token, name } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ type_token .format() - .with_or_empty(|type_token| formatted![formatter, [type_token, space_token()]]), + .with_or_empty(|type_token, f| write![f, [type_token, space_token()]]), name.format() ] ] diff --git a/crates/rome_js_formatter/src/js/objects/method_object_member.rs b/crates/rome_js_formatter/src/js/objects/method_object_member.rs index efa52bd869f..97db3eb2281 100644 --- a/crates/rome_js_formatter/src/js/objects/method_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/method_object_member.rs @@ -5,10 +5,7 @@ use rome_js_syntax::JsMethodObjectMember; use rome_js_syntax::JsMethodObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsMethodObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsMethodObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsMethodObjectMemberFields { async_token, star_token, @@ -19,13 +16,12 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsEmptyStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsEmptyStatement, formatter: &JsFormatter) -> FormatResult<()> { let JsEmptyStatementFields { semicolon_token } = node.as_fields(); let parent_kind = node.syntax().parent().map(|p| p.kind()); + if matches!( parent_kind, Some(JsSyntaxKind::JS_DO_WHILE_STATEMENT) | Some(JsSyntaxKind::JS_IF_STATEMENT) | Some(JsSyntaxKind::JS_ELSE_CLAUSE) ) { - formatted![formatter, [semicolon_token.format()]] + write!(f, [semicolon_token]) } else { Ok(formatter.format_replaced(&semicolon_token?, empty_element())) } diff --git a/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs index 85023d5e416..93bbd8a9360 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs @@ -5,12 +5,9 @@ use rome_js_syntax::{JsxAttributeInitializerClause, JsxAttributeInitializerClaus impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxAttributeInitializerClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxAttributeInitializerClause, f: &JsFormatter) -> FormatResult<()> { let JsxAttributeInitializerClauseFields { eq_token, value } = node.as_fields(); - formatted![formatter, [eq_token.format(), value.format()]] + write![f, [eq_token.format(), value.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/text.rs b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs index eee848d0c70..2087e17f910 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/text.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs @@ -2,6 +2,7 @@ use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::{JsxText, JsxTextFields}; use std::borrow::Cow; +use std::fmt; use std::ops::Range; use std::str::CharIndices; @@ -175,10 +176,10 @@ fn get_trimmed_text( (Some(WhitespaceType::HasNewline), None) => Cow::Borrowed(text.trim_start()), (None, Some(WhitespaceType::HasNewline)) => Cow::Borrowed(text.trim_end()), (Some(WhitespaceType::NoNewline), Some(WhitespaceType::NoNewline)) => { - Cow::Owned(format!(" {} ", text.trim())) + Cow::Owned(std::format!(" {} ", text.trim())) } - (Some(WhitespaceType::NoNewline), _) => Cow::Owned(format!(" {}", text.trim())), - (_, Some(WhitespaceType::NoNewline)) => Cow::Owned(format!("{} ", text.trim())), + (Some(WhitespaceType::NoNewline), _) => Cow::Owned(std::format!(" {}", text.trim())), + (_, Some(WhitespaceType::NoNewline)) => Cow::Owned(std::format!("{} ", text.trim())), } } diff --git a/crates/rome_js_formatter/src/lib.rs b/crates/rome_js_formatter/src/lib.rs index 5e55e438650..6193e0198ac 100644 --- a/crates/rome_js_formatter/src/lib.rs +++ b/crates/rome_js_formatter/src/lib.rs @@ -14,7 +14,7 @@ pub(crate) use formatter::{ format_leading_trivia, format_trailing_trivia, JsFormatter, JsFormatterExt, }; use rome_formatter::prelude::*; -use rome_formatter::{FormatOwnedWithRule, FormatRefWithRule, Formatted, Printed}; +use rome_formatter::{Buffer, FormatOwnedWithRule, FormatRefWithRule, Formatted, Printed}; use rome_js_syntax::{ JsAnyDeclaration, JsAnyStatement, JsLanguage, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, }; @@ -175,15 +175,15 @@ where { type Context = JsFormatContext; - fn format(node: &N, formatter: &Formatter) -> FormatResult { + fn format(node: &N, f: &JsFormatter) -> FormatResult<()> { let syntax = node.syntax(); - let element = if has_formatter_suppressions(syntax) { - suppressed_node(syntax).format(formatter)? + if has_formatter_suppressions(syntax) { + write!(f, [suppressed_node(syntax)])?; } else { - Self::format_fields(node, formatter)? + Self::format_fields(node, f)?; }; - Ok(element) + Ok(()) } } @@ -192,10 +192,7 @@ where T: AstNode, { /// Formats the node's fields. - fn format_fields( - item: &T, - formatter: &Formatter, - ) -> FormatResult; + fn format_fields(item: &T, formatter: &mut JsFormatter) -> FormatResult; } /// Format implementation specific to JavaScript tokens. @@ -204,17 +201,17 @@ pub struct FormatJsSyntaxToken; impl FormatRule for FormatJsSyntaxToken { type Context = JsFormatContext; - fn format( - token: &JsSyntaxToken, - formatter: &Formatter, - ) -> FormatResult { - formatter.track_token(token); - - Ok(format_elements![ - format_leading_trivia(token, formatter::TriviaPrintMode::Full), - Token::from(token), - format_trailing_trivia(token), - ]) + fn format(token: &JsSyntaxToken, f: &mut JsFormatter) -> FormatResult<()> { + f.state_mut().track_token(token); + + write!( + f, + [ + format_leading_trivia(token, formatter::TriviaPrintMode::Full), + Token::from(token), + format_trailing_trivia(token), + ] + ) } } @@ -237,7 +234,7 @@ impl IntoFormat for JsSyntaxToken { /// Formats a range within a file, supported by Rome /// /// This runs a simple heuristic to determine the initial indentation -/// level of the node based on the provided [FormatOptions], which +/// level of the node based on the provided [FormatContext], which /// must match currently the current initial of the file. Additionally, /// because the reformatting happens only locally the resulting code /// will be indented with the same level as the original selection, @@ -284,7 +281,7 @@ pub fn format_node(context: JsFormatContext, root: &JsSyntaxNode) -> FormatResul /// Formats a single node within a file, supported by Rome. /// /// This runs a simple heuristic to determine the initial indentation -/// level of the node based on the provided [FormatOptions], which +/// level of the node based on the provided [FormatContext], which /// must match currently the current initial of the file. Additionally, /// because the reformatting happens only locally the resulting code /// will be indented with the same level as the original selection, diff --git a/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs index 5f1d20b41ec..8e2b1e70ffb 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs @@ -4,12 +4,9 @@ use rome_js_syntax::TsAccessibilityModifier; use rome_js_syntax::TsAccessibilityModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAccessibilityModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsAccessibilityModifier, f: &JsFormatter) -> FormatResult<()> { let TsAccessibilityModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs index 19ce191d39b..204dd05dc29 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs @@ -3,16 +3,13 @@ use crate::FormatNodeFields; use rome_js_syntax::{TsOptionalTupleTypeElement, TsOptionalTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsOptionalTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsOptionalTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { let TsOptionalTupleTypeElementFields { ty, question_mark_token, } = node.as_fields(); let ty = ty.format(); let question_mark = question_mark_token.format(); - formatted![formatter, [ty, question_mark]] + write![f, [ty, question_mark]] } } diff --git a/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs b/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs index fb8efa8ef13..025985745fd 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs @@ -5,6 +5,7 @@ use rome_js_syntax::{ JsThisExpression, }; use rome_rowan::{AstNode, SyntaxResult}; +use std::fmt; use std::fmt::Debug; #[derive(Clone)] @@ -141,14 +142,18 @@ impl FlattenItem { impl Debug for FlattenItem { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - FlattenItem::StaticMember(_, formatted) => write!(f, "StaticMember: {:?}", formatted), + FlattenItem::StaticMember(_, formatted) => { + std::write!(f, "StaticMember: {:?}", formatted) + } FlattenItem::CallExpression(_, formatted) => { - write!(f, "CallExpression: {:?}", formatted) + std::write!(f, "CallExpression: {:?}", formatted) } FlattenItem::ComputedExpression(_, formatted) => { - write!(f, "ComputedExpression: {:?}", formatted) + std::write!(f, "ComputedExpression: {:?}", formatted) + } + FlattenItem::Node(node, formatted) => { + std::write!(f, "{:?} {:?}", node.kind(), formatted) } - FlattenItem::Node(node, formatted) => write!(f, "{:?} {:?}", node.kind(), formatted), } } } diff --git a/crates/rome_js_formatter/src/utils/member_chain/groups.rs b/crates/rome_js_formatter/src/utils/member_chain/groups.rs index bb3032216ec..bc15dd53345 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/groups.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/groups.rs @@ -146,7 +146,7 @@ impl<'f> Groups<'f> { /// This is an heuristic needed to check when the first element of the group /// Should be part of the "head" or the "tail". fn should_not_wrap(&self, first_group: &HeadGroup) -> SyntaxResult { - let tab_with = self.formatter.context().tab_width(); + let tab_with = self.formatter.state().tab_width(); let has_computed_property = if self.groups.len() > 1 { // SAFETY: guarded by the previous check let group = &self.groups[0]; diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 3a8edd3da35..f3a6b9ef524 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -21,6 +21,10 @@ use rome_js_syntax::{ }; use rome_js_syntax::{JsSyntaxKind, JsSyntaxNode, JsSyntaxToken}; use rome_rowan::{AstNode, AstNodeList}; +use std::borrow::Cow; +use std::fmt; + +use crate::options::{JsFormatOptions, QuoteStyle}; pub(crate) use simple::*; pub(crate) use string_utils::*; @@ -221,10 +225,10 @@ impl TemplateElement { let middle = format_elements![middle, line_suffix_boundary()]; if should_hard_group { - formatted![ + write!( formatter, [dollar_curly_token.format(), middle, r_curly_token.format()] - ] + )?; } else { formatter .delimited(&dollar_curly_token, middle, &r_curly_token) @@ -359,26 +363,26 @@ impl FormatPrecedence { /// semicolon insertion if it was missing in the input source and the /// preceeding element wasn't an unknown node pub(crate) fn format_with_semicolon( - formatter: &JsFormatter, + formatter: &mut JsFormatter, content: FormatElement, semicolon: Option, -) -> FormatResult { +) -> FormatResult<()> { let is_unknown = match content.last_element() { Some(FormatElement::Verbatim(elem)) => elem.is_unknown(), _ => false, }; - formatted![ + write!( formatter, [ content, semicolon.format().or_format(if is_unknown { - empty_element + |f| Ok(()) } else { - || token(";") + |f| write!(f, [token(";")]) }) ] - ] + ) } /// A call like expression is one of: diff --git a/crates/rome_js_formatter/src/utils/string_utils.rs b/crates/rome_js_formatter/src/utils/string_utils.rs index 5e84fea3f41..39b1c36e7f5 100644 --- a/crates/rome_js_formatter/src/utils/string_utils.rs +++ b/crates/rome_js_formatter/src/utils/string_utils.rs @@ -65,7 +65,7 @@ impl Format for FormatLiteralStringToken<'_> { type Context = JsFormatContext; fn format(&self, formatter: &JsFormatter) -> FormatResult { - let chosen_quote_style = formatter.context().quote_style(); + let chosen_quote_style = formatter.state().quote_style(); let token = self.token(); let mut string_cleaner = LiteralStringNormaliser::new(self, chosen_quote_style); From 1efbafb6b73d6ac3eaaa8f9dac7e39a49c6d9514 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Mon, 30 May 2022 08:20:59 +0200 Subject: [PATCH 02/35] refactor(formatter): Make Format `Options` a type parameter To allow types that implement `Format` for all option types. --- crates/rome_formatter/src/arguments.rs | 8 +- crates/rome_formatter/src/builders.rs | 251 +++++++----------- .../rome_formatter/src/format_extensions.rs | 152 +++++------ crates/rome_formatter/src/formatter.rs | 4 +- crates/rome_formatter/src/lib.rs | 77 ++---- crates/rome_formatter/src/macros.rs | 31 ++- crates/rome_formatter/src/printer/mod.rs | 12 +- 7 files changed, 208 insertions(+), 327 deletions(-) diff --git a/crates/rome_formatter/src/arguments.rs b/crates/rome_formatter/src/arguments.rs index 20d2e76bc5a..2c03177a6b9 100644 --- a/crates/rome_formatter/src/arguments.rs +++ b/crates/rome_formatter/src/arguments.rs @@ -19,7 +19,7 @@ pub struct Argument<'fmt, O> { impl<'fmt, O> Argument<'fmt, O> { #[doc(hidden)] #[inline] - pub fn new>(value: &'fmt F) -> Self { + pub fn new>(value: &'fmt F) -> Self { let formatter: fn(&F, &mut Formatter<'_, O>) -> super::FormatResult<()> = F::format; unsafe { @@ -58,10 +58,8 @@ impl<'fmt, O> Arguments<'fmt, O> { } } -impl Format for Arguments<'_, Context> { - type Context = Context; - - fn format(&self, formatter: &mut Formatter) -> super::FormatResult<()> { +impl Format for Arguments<'_, O> { + fn format(&self, formatter: &mut Formatter) -> super::FormatResult<()> { formatter.write_fmt(self) } } diff --git a/crates/rome_formatter/src/builders.rs b/crates/rome_formatter/src/builders.rs index f119c188c0b..9bbf86c0ab4 100644 --- a/crates/rome_formatter/src/builders.rs +++ b/crates/rome_formatter/src/builders.rs @@ -10,21 +10,15 @@ use std::marker::PhantomData; /// Can be helpful if you need to return a `FormatElement` (e.g. in an else branch) but don't want /// to show any content. #[deprecated] -pub const fn empty_element() -> Empty { - Empty { - options: PhantomData, - } +pub const fn empty_element() -> Empty { + Empty } #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub struct Empty { - options: PhantomData, -} +pub struct Empty; -impl Format for Empty { - type Context = O; - - fn format(&self, _: &mut Formatter) -> FormatResult<()> { +impl Format for Empty { + fn format(&self, _: &mut Formatter) -> FormatResult<()> { Ok(()) } } @@ -77,7 +71,7 @@ impl Format for Empty { /// ); /// ``` #[inline] -pub const fn soft_line_break() -> Line { +pub const fn soft_line_break() -> Line { Line::new(LineMode::Soft) } @@ -106,7 +100,7 @@ pub const fn soft_line_break() -> Line { /// ); /// ``` #[inline] -pub const fn hard_line_break() -> Line { +pub const fn hard_line_break() -> Line { Line::new(LineMode::Hard) } @@ -135,7 +129,7 @@ pub const fn hard_line_break() -> Line { /// ); /// ``` #[inline] -pub const fn empty_line() -> Line { +pub const fn empty_line() -> Line { Line::new(LineMode::Empty) } @@ -186,29 +180,23 @@ pub const fn empty_line() -> Line { /// ); /// ``` #[inline] -pub const fn soft_line_break_or_space() -> Line { +pub const fn soft_line_break_or_space() -> Line { Line::new(LineMode::SoftOrSpace) } #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub struct Line { +pub struct Line { mode: LineMode, - options: PhantomData, } -impl Line { +impl Line { const fn new(mode: LineMode) -> Self { - Self { - mode, - options: PhantomData, - } + Self { mode } } } -impl Format for Line { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for Line { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::Line(self.mode)) } } @@ -247,51 +235,38 @@ impl Format for Line { /// assert_eq!(r#""Hello\tWorld""#, elements.print().as_code()); /// ``` #[inline] -pub fn token(text: &'static str) -> StaticToken { +pub fn token(text: &'static str) -> StaticToken { debug_assert_no_newlines(text); - StaticToken { - text, - options: PhantomData, - } + StaticToken { text } } #[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub struct StaticToken { +pub struct StaticToken { text: &'static str, - options: PhantomData, } -impl Format for StaticToken { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for StaticToken { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::Token(Token::Static { text: self.text })) } } /// Create a token from a dynamic string and a range of the input source -pub fn dynamic_token(text: &str, position: TextSize) -> DynamicToken { +pub fn dynamic_token(text: &str, position: TextSize) -> DynamicToken { debug_assert_no_newlines(text); - DynamicToken { - text, - position, - options: PhantomData, - } + DynamicToken { text, position } } #[derive(Debug, Eq, PartialEq)] -pub struct DynamicToken<'a, O> { +pub struct DynamicToken<'a> { text: &'a str, position: TextSize, - options: PhantomData, } -impl Format for DynamicToken<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for DynamicToken<'_> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::Token(Token::Dynamic { text: self.text.to_string().into_boxed_str(), source_position: self.position, @@ -299,32 +274,24 @@ impl Format for DynamicToken<'_, O> { } } -pub fn syntax_token_cow_slice<'a, L: Language, O>( +pub fn syntax_token_cow_slice<'a, L: Language>( text: Cow<'a, str>, token: &'a SyntaxToken, start: TextSize, -) -> SyntaxTokenCowSlice<'a, L, O> { +) -> SyntaxTokenCowSlice<'a, L> { debug_assert_no_newlines(&text); - SyntaxTokenCowSlice { - text, - token, - start, - options: PhantomData, - } + SyntaxTokenCowSlice { text, token, start } } -pub struct SyntaxTokenCowSlice<'a, L: Language, O> { +pub struct SyntaxTokenCowSlice<'a, L: Language> { text: Cow<'a, str>, token: &'a SyntaxToken, start: TextSize, - options: PhantomData, } -impl Format for SyntaxTokenCowSlice<'_, L, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for SyntaxTokenCowSlice<'_, L> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { match &self.text { Cow::Borrowed(text) => { let range = TextRange::at(self.start, text.text_len()); @@ -350,10 +317,10 @@ impl Format for SyntaxTokenCowSlice<'_, L, O> { } } -pub fn syntax_token_text_slice( +pub fn syntax_token_text_slice( token: &SyntaxToken, range: TextRange, -) -> SyntaxTokenTextSlice { +) -> SyntaxTokenTextSlice { let relative_range = range - token.text_range().start(); let slice = token.token_text().slice(relative_range); @@ -362,20 +329,16 @@ pub fn syntax_token_text_slice( SyntaxTokenTextSlice { text: slice, source_position: range.start(), - options: PhantomData, } } -pub struct SyntaxTokenTextSlice { +pub struct SyntaxTokenTextSlice { text: SyntaxTokenText, source_position: TextSize, - options: PhantomData, } -impl Format for SyntaxTokenTextSlice { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for SyntaxTokenTextSlice { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::Token(Token::SyntaxTokenSlice { slice: self.text.clone(), source_position: self.source_position, @@ -407,19 +370,17 @@ fn debug_assert_no_newlines(text: &str) { /// ); /// ``` #[inline] -pub const fn line_suffix(inner: &dyn Format) -> LineSuffix { +pub const fn line_suffix(inner: &dyn Format) -> LineSuffix { LineSuffix { content: inner } } #[derive(Copy, Clone)] pub struct LineSuffix<'a, O> { - content: &'a dyn Format, + content: &'a dyn Format, } -impl Format for LineSuffix<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for LineSuffix<'_, O> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { let mut buffer = VecBuffer::new(f.state_mut()); write!(buffer, [self.content])?; @@ -451,21 +412,15 @@ impl Format for LineSuffix<'_, O> { /// elements.print().as_code() /// ); /// ``` -pub const fn line_suffix_boundary() -> LineSuffixBoundary { - LineSuffixBoundary { - options: PhantomData, - } +pub const fn line_suffix_boundary() -> LineSuffixBoundary { + LineSuffixBoundary } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct LineSuffixBoundary { - options: PhantomData, -} +pub struct LineSuffixBoundary; -impl Format for LineSuffixBoundary { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for LineSuffixBoundary { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::LineSuffixBoundary) } } @@ -499,19 +454,17 @@ impl Format for LineSuffixBoundary { /// ); /// ``` #[inline] -pub fn comment(content: &dyn Format) -> Comment { +pub fn comment(content: &dyn Format) -> Comment { Comment { content } } #[derive(Copy, Clone)] pub struct Comment<'a, O> { - content: &'a dyn Format, + content: &'a dyn Format, } -impl Format for Comment<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for Comment<'_, O> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { let mut buffer = VecBuffer::new(f.state_mut()); write!(buffer, [self.content])?; @@ -535,21 +488,15 @@ impl Format for Comment<'_, O> { /// assert_eq!("a b", elements.print().as_code()); /// ``` #[inline] -pub const fn space_token() -> Space { - Space { - options: PhantomData, - } +pub const fn space_token() -> Space { + Space } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct Space { - options: PhantomData, -} +pub struct Space; -impl Format for Space { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for Space { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::Space) } } @@ -587,18 +534,16 @@ impl Format for Space { /// ); /// ``` #[inline] -pub const fn indent(content: &dyn Format) -> Indent { +pub const fn indent(content: &dyn Format) -> Indent { Indent { content } } pub struct Indent<'a, O> { - content: &'a dyn Format, + content: &'a dyn Format, } -impl Format for Indent<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for Indent<'_, O> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { let mut buffer = VecBuffer::new(f.state_mut()); write!(buffer, [self.content])?; @@ -644,7 +589,7 @@ impl Format for Indent<'_, O> { /// ); /// ``` #[inline] -pub fn block_indent(content: &dyn Format) -> BlockIndent { +pub fn block_indent(content: &dyn Format) -> BlockIndent { BlockIndent { content, mode: IndentMode::Block, @@ -709,7 +654,7 @@ pub fn block_indent(content: &dyn Format) -> BlockIndent { /// ); /// ``` #[inline] -pub fn soft_block_indent(content: &dyn Format) -> BlockIndent { +pub fn soft_block_indent(content: &dyn Format) -> BlockIndent { BlockIndent { content, mode: IndentMode::Soft, @@ -777,7 +722,7 @@ pub fn soft_block_indent(content: &dyn Format) -> BlockIndent /// ); /// ``` #[inline] -pub fn soft_line_indent_or_space(content: &dyn Format) -> BlockIndent { +pub fn soft_line_indent_or_space(content: &dyn Format) -> BlockIndent { BlockIndent { content, mode: IndentMode::SoftLineOrSpace, @@ -786,7 +731,7 @@ pub fn soft_line_indent_or_space(content: &dyn Format) -> BlockI #[derive(Copy, Clone)] pub struct BlockIndent<'a, O> { - content: &'a dyn Format, + content: &'a dyn Format, mode: IndentMode, } @@ -797,10 +742,8 @@ enum IndentMode { SoftLineOrSpace, } -impl Format for BlockIndent<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for BlockIndent<'_, O> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { let mut buffer = VecBuffer::new(f.state_mut()); match self.mode { @@ -897,7 +840,7 @@ impl Format for BlockIndent<'_, O> { /// ); /// ``` #[inline] -pub const fn group_elements(content: &dyn Format) -> GroupElements { +pub const fn group_elements(content: &dyn Format) -> GroupElements { GroupElements { content, options: GroupElementsOptions { group_id: None }, @@ -912,7 +855,7 @@ pub struct GroupElementsOptions { /// Creates a group with a specific id. Useful for cases where `if_group_breaks` and `if_group_fits_on_line` /// shouldn't refer to the direct parent group. pub const fn group_elements_with_options( - content: &dyn Format, + content: &dyn Format, options: GroupElementsOptions, ) -> GroupElements { GroupElements { content, options } @@ -920,14 +863,12 @@ pub const fn group_elements_with_options( #[derive(Copy, Clone)] pub struct GroupElements<'a, O> { - content: &'a dyn Format, + content: &'a dyn Format, options: GroupElementsOptions, } -impl Format for GroupElements<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for GroupElements<'_, O> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { let mut buffer = VecBuffer::new(f.state_mut()); write!(buffer, [self.content])?; @@ -983,21 +924,15 @@ impl Format for GroupElements<'_, O> { /// /// ## Prettier /// Equivalent to Prettier's `break_parent` IR element -pub const fn expand_parent() -> ExpandParent { - ExpandParent { - options: PhantomData, - } +pub const fn expand_parent() -> ExpandParent { + ExpandParent } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct ExpandParent { - options: PhantomData, -} - -impl Format for ExpandParent { - type Context = O; +pub struct ExpandParent; - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for ExpandParent { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { f.write_element(FormatElement::ExpandParent) } } @@ -1073,7 +1008,7 @@ impl Format for ExpandParent { /// ); /// ``` #[inline] -pub fn if_group_breaks(content: &dyn Format) -> IfGroupBreaks { +pub fn if_group_breaks(content: &dyn Format) -> IfGroupBreaks { IfGroupBreaks { content, group_id: None, @@ -1133,7 +1068,7 @@ pub fn if_group_breaks(content: &dyn Format) -> IfGroupBreaks /// ); /// ``` pub const fn if_group_with_id_breaks( - content: &dyn Format, + content: &dyn Format, group_id: GroupId, ) -> IfGroupBreaks { IfGroupBreaks { @@ -1207,9 +1142,7 @@ pub const fn if_group_with_id_breaks( /// ); /// ``` #[inline] -pub const fn if_group_fits_on_single_line( - flat_content: &dyn Format, -) -> IfGroupBreaks { +pub const fn if_group_fits_on_single_line(flat_content: &dyn Format) -> IfGroupBreaks { IfGroupBreaks { mode: PrintMode::Flat, group_id: None, @@ -1222,7 +1155,7 @@ pub const fn if_group_fits_on_single_line( /// #[inline] pub const fn if_group_with_id_fits_on_line( - flat_content: &dyn Format, + flat_content: &dyn Format, id: GroupId, ) -> IfGroupBreaks { IfGroupBreaks { @@ -1234,15 +1167,13 @@ pub const fn if_group_with_id_fits_on_line( #[derive(Copy, Clone)] pub struct IfGroupBreaks<'a, O> { - content: &'a dyn Format, + content: &'a dyn Format, group_id: Option, mode: PrintMode, } -impl Format for IfGroupBreaks<'_, O> { - type Context = O; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { +impl Format for IfGroupBreaks<'_, O> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { let mut buffer = VecBuffer::new(f.state_mut()); write!(buffer, [self.content])?; @@ -1261,7 +1192,7 @@ impl Format for IfGroupBreaks<'_, O> { pub struct JoinBuilder<'fmt, 'joiner, 'buf, O> { result: super::FormatResult<()>, fmt: &'fmt mut Formatter<'buf, O>, - with: Option<&'joiner dyn Format>, + with: Option<&'joiner dyn Format>, has_elements: bool, } @@ -1275,10 +1206,7 @@ impl<'fmt, 'joiner, 'buf, O> JoinBuilder<'fmt, 'joiner, 'buf, O> { } } - pub(crate) fn with( - fmt: &'fmt mut Formatter<'buf, O>, - with: &'joiner dyn Format, - ) -> Self { + pub(crate) fn with(fmt: &'fmt mut Formatter<'buf, O>, with: &'joiner dyn Format) -> Self { Self { result: Ok(()), fmt, @@ -1287,7 +1215,7 @@ impl<'fmt, 'joiner, 'buf, O> JoinBuilder<'fmt, 'joiner, 'buf, O> { } } - pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { + pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { self.result = self.result.and_then(|_| { if let Some(with) = &self.with { if self.has_elements { @@ -1304,7 +1232,7 @@ impl<'fmt, 'joiner, 'buf, O> JoinBuilder<'fmt, 'joiner, 'buf, O> { pub fn entries(&mut self, entries: I) -> &mut Self where - F: Format, + F: Format, I: IntoIterator, { for entry in entries { @@ -1322,14 +1250,14 @@ impl<'fmt, 'joiner, 'buf, O> JoinBuilder<'fmt, 'joiner, 'buf, O> { pub struct FillBuilder<'fmt, 'separator, 'buf, O> { result: FormatResult<()>, fmt: &'fmt mut Formatter<'buf, O>, - separator: &'separator dyn Format, + separator: &'separator dyn Format, items: Vec, } impl<'a, 'separator, 'buf, O> FillBuilder<'a, 'separator, 'buf, O> { pub(crate) fn new( fmt: &'a mut Formatter<'buf, O>, - separator: &'separator dyn Format, + separator: &'separator dyn Format, ) -> Self { Self { result: Ok(()), @@ -1341,7 +1269,7 @@ impl<'a, 'separator, 'buf, O> FillBuilder<'a, 'separator, 'buf, O> { pub fn entries(&mut self, entries: I) -> &mut Self where - F: Format, + F: Format, I: IntoIterator, { for entry in entries { @@ -1351,7 +1279,7 @@ impl<'a, 'separator, 'buf, O> FillBuilder<'a, 'separator, 'buf, O> { self } - pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { + pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { self.result = self.result.and_then(|_| { let mut buffer = VecBuffer::new(self.fmt.state_mut()); write!(buffer, [entry])?; @@ -1391,11 +1319,10 @@ where options: PhantomData, } -impl Format for FormatWith +impl Format for FormatWith where T: Fn(&mut Formatter) -> FormatResult<()>, { - type Context = O; fn format(&self, f: &mut Formatter) -> FormatResult<()> { (self.closure)(f) } diff --git a/crates/rome_formatter/src/format_extensions.rs b/crates/rome_formatter/src/format_extensions.rs index 4dc37906d28..9b62f481472 100644 --- a/crates/rome_formatter/src/format_extensions.rs +++ b/crates/rome_formatter/src/format_extensions.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use std::cell::RefCell; +use std::marker::PhantomData; use crate::{write, Buffer, VecBuffer}; use rome_rowan::SyntaxResult; @@ -8,9 +9,7 @@ use rome_rowan::SyntaxResult; /// /// In order to take advantage of all the functions, you only need to implement the [FormatOptionalTokenAndNode::with_or] /// function. -pub trait FormatOptional { - type Context; - +pub trait FormatOptional { /// This function tries to format an optional object. If the object is [None] /// an [empty token](crate::FormatElement::Empty) is created. If exists, the utility /// formats the object and passes it to the closure. @@ -24,10 +23,8 @@ pub trait FormatOptional { /// /// struct MyFormat; /// - /// impl Format for MyFormat { - /// type Context = SimpleFormatContext; - /// - /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// impl Format for MyFormat { + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [token("MyToken")]) /// } /// } @@ -54,12 +51,9 @@ pub trait FormatOptional { fn with_or_empty( &self, with: With, - ) -> FormatWithOr) -> FormatResult<()>, Self::Context> + ) -> FormatWithOr) -> FormatResult<()>, O> where - With: Fn( - &dyn Format, - &mut Formatter, - ) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { self.with_or(with, |_| Ok(())) } @@ -76,9 +70,8 @@ pub trait FormatOptional { /// /// struct MyFormat; /// - /// impl Format for MyFormat { - /// type Context = SimpleFormatContext; - /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// impl Format for MyFormat { + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [token("MyToken")]) /// } /// } @@ -92,9 +85,9 @@ pub trait FormatOptional { /// [none_token.or_format(|f| write!(f, [token(" other result")]))] /// ) /// ); - fn or_format(&self, op: Or) -> OrFormat + fn or_format(&self, op: Or) -> OrFormat where - Or: Fn(&mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { self.with_or(|token, f| token.format(f), op) } @@ -114,9 +107,8 @@ pub trait FormatOptional { /// /// struct MyFormat; /// - /// impl Format for MyFormat { - /// type Context = SimpleFormatContext; - /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// impl Format for MyFormat { + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [token("MyToken")]) /// } /// } @@ -147,17 +139,14 @@ pub trait FormatOptional { /// ) /// ]) /// ); - fn with_or(&self, with: With, op: Or) -> FormatWithOr + fn with_or(&self, with: With, op: Or) -> FormatWithOr where - With: Fn( - &dyn Format, - &mut Formatter, - ) -> FormatResult<()>, - Or: Fn(&mut Formatter) -> FormatResult<()>; + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>; } /// Utility trait for formatting a formattable object with some additional content. -pub trait FormatWith: Format { +pub trait FormatWith: Format { /// Allows to chain a formattable object with another [elements](FormatElement) /// /// The function will decorate the result with [Ok] @@ -174,9 +163,8 @@ pub trait FormatWith: Format { /// /// struct MyFormat; /// - /// impl Format for MyFormat { - /// type Context = SimpleFormatContext; - /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// impl Format for MyFormat { + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [token("MyToken")]) /// } /// } @@ -189,49 +177,42 @@ pub trait FormatWith: Format { /// }) /// ]) /// ) - fn with(&self, with: With) -> FormatItemWith + fn with(&self, with: With) -> FormatItemWith where - With: Fn( - &dyn Format, - &mut Formatter, - ) -> FormatResult<()>; + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>; } -pub struct FormatItemWith<'a, With, Context> +pub struct FormatItemWith<'a, With, Options> where - With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { with: With, - inner: &'a dyn Format, + inner: &'a dyn Format, } -impl<'a, With, Context> Format for FormatItemWith<'a, With, Context> +impl<'a, With, Options> Format for FormatItemWith<'a, With, Options> where - With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { - type Context = Context; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { (self.with)(self.inner, f) } } -impl FormatWith for F { - fn with(&self, with: With) -> FormatItemWith +impl, O> FormatWith for F { + fn with(&self, with: With) -> FormatItemWith where - With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, { FormatItemWith { with, inner: self } } } -impl FormatOptional for SyntaxResult> { - type Context = F::Context; - - fn with_or(&self, with: With, op: Or) -> FormatWithOr +impl, O> FormatOptional for SyntaxResult> { + fn with_or(&self, with: With, op: Or) -> FormatWithOr where - With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, - Or: Fn(&mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { match self { Err(_) => FormatWithOr::With { inner: self, with }, @@ -241,16 +222,11 @@ impl FormatOptional for SyntaxResult> { } } -impl FormatOptional for Option { - type Context = F::Context; - - fn with_or(&self, with: With, op: Or) -> FormatWithOr +impl, O> FormatOptional for Option { + fn with_or(&self, with: With, op: Or) -> FormatWithOr where - With: Fn( - &dyn Format, - &mut Formatter, - ) -> FormatResult<()>, - Or: Fn(&mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { match self { None => FormatWithOr::Or(op), @@ -259,34 +235,32 @@ impl FormatOptional for Option { } } -pub type OrFormat<'a, Or, Context> = FormatWithOr< +pub type OrFormat<'a, Or, Options> = FormatWithOr< 'a, - fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + fn(&dyn Format, &mut Formatter) -> FormatResult<()>, Or, - Context, + Options, >; -pub enum FormatWithOr<'a, With, Or, Context> +pub enum FormatWithOr<'a, With, Or, Options> where - With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, - Or: Fn(&mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { With { - inner: &'a dyn Format, + inner: &'a dyn Format, with: With, }, Or(Or), } -impl<'a, With, Or, Context> Format for FormatWithOr<'a, With, Or, Context> +impl<'a, With, Or, Options> Format for FormatWithOr<'a, With, Or, Options> where - With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, - Or: Fn(&mut Formatter) -> FormatResult<()>, + With: Fn(&dyn Format, &mut Formatter) -> FormatResult<()>, + Or: Fn(&mut Formatter) -> FormatResult<()>, { - type Context = Context; - #[inline] - fn format(&self, formatter: &mut Formatter) -> FormatResult<()> { + fn format(&self, formatter: &mut Formatter) -> FormatResult<()> { match self { FormatWithOr::Or(op) => op(formatter), FormatWithOr::With { inner, with } => with(inner, formatter), @@ -296,7 +270,7 @@ where /// Utility trait that allows memorizing the output of a [Format]. /// Useful to avoid re-formatting the same object twice. -pub trait MemoizeFormat { +pub trait MemoizeFormat { /// Returns a formattable object that memoizes the result of `Format` by cloning. /// Mainly useful if the same sub-tree can appear twice in the formatted output because it's /// used inside of `if_group_breaks` or `if_group_fits_single_line`. @@ -317,9 +291,8 @@ pub trait MemoizeFormat { /// } /// } /// - /// impl Format for MyFormat { - /// type Context = SimpleFormatContext; - /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { + /// impl Format for MyFormat { + /// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// let value = self.value.get(); /// self.value.set(value + 1); /// @@ -343,38 +316,41 @@ pub trait MemoizeFormat { /// ); /// ``` /// - fn memoized(self) -> Memoized + fn memoized(self) -> Memoized where - Self: Sized + Format, + Self: Sized + Format, { Memoized::new(self) } } -impl MemoizeFormat for F where F: Format {} +impl MemoizeFormat for T where T: Format {} /// Memoizes the output of its inner [Format] to avoid re-formatting a potential expensive object. -pub struct Memoized { +pub struct Memoized { inner: F, memory: RefCell>>>, + options: PhantomData, } -impl Memoized { +impl Memoized +where + F: Format, +{ fn new(inner: F) -> Self { Self { inner, memory: RefCell::new(None), + options: PhantomData, } } } -impl Format for Memoized +impl Format for Memoized where - F: Format, + F: Format, { - type Context = F::Context; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { // Cached if let Some(memory) = self.memory.borrow().as_ref() { return match memory { diff --git a/crates/rome_formatter/src/formatter.rs b/crates/rome_formatter/src/formatter.rs index 74204bd1770..11086f0313d 100644 --- a/crates/rome_formatter/src/formatter.rs +++ b/crates/rome_formatter/src/formatter.rs @@ -83,7 +83,7 @@ impl<'buf, Context> Formatter<'buf, Context> { /// ``` pub fn join_with<'a, 'joiner>( &'a mut self, - joiner: &'joiner dyn Format, + joiner: &'joiner dyn Format, ) -> JoinBuilder<'a, 'joiner, 'buf, Context> { JoinBuilder::with(self, joiner) } @@ -114,7 +114,7 @@ impl<'buf, Context> Formatter<'buf, Context> { /// ``` pub fn fill<'a, 'with>( &'a mut self, - separator: &'with dyn Format, + separator: &'with dyn Format, ) -> FillBuilder<'a, 'with, 'buf, Context> { FillBuilder::new(self, separator) } diff --git a/crates/rome_formatter/src/lib.rs b/crates/rome_formatter/src/lib.rs index 644cdca1e6d..80910b62aa7 100644 --- a/crates/rome_formatter/src/lib.rs +++ b/crates/rome_formatter/src/lib.rs @@ -369,10 +369,8 @@ impl From<&SyntaxError> for FormatError { /// /// struct Paragraph(String); /// -/// impl Format for Paragraph { -/// type Context = SimpleFormatContext; -/// -/// fn format(&self, f: &mut Formatter) -> FormatResult<()> { +/// impl Format for Paragraph { +/// fn format(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [ /// hard_line_break(), /// dynamic_token(&self.0, TextSize::from(0)), @@ -386,43 +384,34 @@ impl From<&SyntaxError> for FormatError { /// /// assert_eq!("test\n", formatted.print().as_code()) /// ``` -pub trait Format { - /// Type of the formatter options. - type Context; - +pub trait Format { /// Formats the object - fn format(&self, f: &mut Formatter) -> FormatResult<()>; + fn format(&self, f: &mut Formatter) -> FormatResult<()>; } -impl Format for &T +impl Format for &T where - T: ?Sized + Format, + T: ?Sized + Format, { - type Context = T::Context; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { Format::format(&**self, f) } } -impl Format for &mut T +impl Format for &mut T where - T: ?Sized + Format, + T: ?Sized + Format, { - type Context = T::Context; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { Format::format(&**self, f) } } -impl Format for Option +impl Format for Option where - T: Format, + T: Format, { - type Context = T::Context; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { match self { Some(value) => value.format(f), None => Ok(()), @@ -430,13 +419,11 @@ where } } -impl Format for SyntaxResult +impl Format for SyntaxResult where - T: Format, + T: Format, { - type Context = T::Context; - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { match self { Ok(value) => value.format(f), Err(err) => Err(err.into()), @@ -477,7 +464,7 @@ pub trait FormatRule { /// use rome_formatter::prelude::*; /// use rome_formatter::{format, Formatted, FormatWithRule}; /// use rome_rowan::{Language, SyntaxNode}; -/// fn format_node, Context=SimpleFormatContext>>(node: F) -> FormatResult { +/// fn format_node>>(node: F) -> FormatResult { /// let formatted = format!(SimpleFormatContext::default(), [node]); /// let _syntax = node.item(); /// @@ -485,7 +472,7 @@ pub trait FormatRule { /// formatted /// } /// ``` -pub trait FormatWithRule: Format { +pub trait FormatWithRule: Format { type Item; /// Returns the associated item @@ -513,7 +500,7 @@ where } } -impl FormatWithRule for FormatRefWithRule<'_, T, R> +impl FormatWithRule for FormatRefWithRule<'_, T, R> where R: FormatRule, { @@ -524,12 +511,10 @@ where } } -impl Format for FormatRefWithRule<'_, T, R> +impl Format for FormatRefWithRule<'_, T, R> where R: FormatRule, { - type Context = R::Context; - #[inline] fn format(&self, f: &mut Formatter) -> FormatResult<()> { R::format(self.item, f) @@ -566,19 +551,17 @@ where } } -impl Format for FormatOwnedWithRule +impl Format for FormatOwnedWithRule where R: FormatRule, { - type Context = R::Context; - #[inline] fn format(&self, f: &mut Formatter) -> FormatResult<()> { R::format(&self.item, f) } } -impl FormatWithRule for FormatOwnedWithRule +impl FormatWithRule for FormatOwnedWithRule where R: FormatRule, { @@ -619,24 +602,20 @@ where /// Formats a syntax node file based on its features. /// /// It returns a [Formatted] result, which the user can use to override a file. -pub fn format_node< - C: FormatContext, - L: Language, - N: FormatWithRule, Context = C>, ->( - context: C, +pub fn format_node>>( + context: O, root: &N, ) -> FormatResult { tracing::trace_span!("format_node").in_scope(move || { let print_options = context.as_print_options(); - let mut context = FormatState::new(context); - let mut buffer = VecBuffer::new(&mut context); + let mut state = FormatState::new(context); + let mut buffer = VecBuffer::new(&mut state); write!(&mut buffer, [root])?; let document = buffer.into_document().into_element(); - context.assert_formatted_all_tokens(root.item()); + state.assert_formatted_all_tokens(root.item()); Ok(Formatted::new(document, print_options)) }) @@ -930,7 +909,7 @@ where pub fn format_sub_tree< C: FormatContext, L: Language, - N: FormatWithRule, Context = C>, + N: FormatWithRule>, >( context: C, root: &N, diff --git a/crates/rome_formatter/src/macros.rs b/crates/rome_formatter/src/macros.rs index f1097b29647..9ed9bc6e0eb 100644 --- a/crates/rome_formatter/src/macros.rs +++ b/crates/rome_formatter/src/macros.rs @@ -60,7 +60,11 @@ macro_rules! format { /// ```rust /// use rome_formatter::prelude::*; /// -/// let element = format_elements![token("foo:"), space_token(), token("bar")]; +/// let element = format_elements![ +/// FormatElement::Token(Token::Static { text: "foo:" }), +/// FormatElement::Space, +/// FormatElement::Token(Token::Static { text: "bar" }) +/// ]; /// ``` /// /// The macro can be also nested, although the macro needs to be decorated with the token you need. @@ -76,15 +80,15 @@ macro_rules! format { /// use rome_formatter::prelude::*; /// /// let element = format_elements![ -/// token("foo:"), -/// space_token(), -/// token("{"), -/// space_token(), -/// token("bar:"), -/// space_token(), -/// token("lorem"), -/// space_token(), -/// token("}") +/// FormatElement::Token(Token::Static { text: "foo:" }), +/// FormatElement::Space, +/// FormatElement::Token(Token::Static { text: "{" }), +/// FormatElement::Space, +/// FormatElement::Token(Token::Static { text: "bar:" }), +/// FormatElement::Space, +/// FormatElement::Token(Token::Static { text: "lorem" }), +/// FormatElement::Space, +/// FormatElement::Token(Token::Static { text: "}" }), /// ]; /// assert_eq!(r#"foo: { bar: lorem }"#, Formatted::new(element, PrinterOptions::default()).print().as_code()); /// ``` @@ -94,7 +98,7 @@ macro_rules! format { /// use rome_formatter::prelude::*; /// /// use rome_formatter::prelude::*; -/// let element = format_elements![token("single")]; +/// let element = format_elements![FormatElement::Token(Token::Static { text: "single" })]; /// assert_eq!(r#"single"#, Formatted::new(element, PrinterOptions::default()).print().as_code()); /// ``` #[macro_export] @@ -232,9 +236,8 @@ mod tests { struct TestFormat; - impl Format for TestFormat { - type Context = (); - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + impl Format<()> for TestFormat { + fn format(&self, f: &mut Formatter<()>) -> FormatResult<()> { write!(f, [token("test")]) } } diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index 4d16b4dfb1e..68ae23f471a 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -907,7 +907,7 @@ mod tests { use crate::printer::{LineEnding, Printer, PrinterOptions}; use crate::{format_args, write, FormatContext, FormatState, LineWidth, Printed, VecBuffer}; - fn format(root: &dyn Format) -> Printed { + fn format(root: &dyn Format<()>) -> Printed { format_with_options( root, PrinterOptions { @@ -917,7 +917,7 @@ mod tests { ) } - fn format_with_options(root: &dyn Format, options: PrinterOptions) -> Printed { + fn format_with_options(root: &dyn Format<()>, options: PrinterOptions) -> Printed { let mut state = FormatState::new(()); let mut buffer = VecBuffer::new(&mut state); @@ -1177,13 +1177,11 @@ two lines`, } struct FormatArrayElements<'a> { - items: Vec<&'a dyn Format>, + items: Vec<&'a dyn Format<()>>, } - impl Format for FormatArrayElements<'_> { - type Context = (); - - fn format(&self, f: &mut Formatter) -> FormatResult<()> { + impl Format<()> for FormatArrayElements<'_> { + fn format(&self, f: &mut Formatter<()>) -> FormatResult<()> { write!( f, [group_elements(&format_args!( From 9fe5507355ed5cf7712ab6e4a02952e7f9cc3e02 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Tue, 31 May 2022 11:23:40 +0200 Subject: [PATCH 03/35] refactor(formatter): Rewrite formatters --- Cargo.lock | 1 + crates/rome_formatter/Cargo.toml | 1 + crates/rome_formatter/src/buffer.rs | 147 +- crates/rome_formatter/src/builders.rs | 193 +- crates/rome_formatter/src/format_element.rs | 118 +- .../rome_formatter/src/format_extensions.rs | 8 +- crates/rome_formatter/src/formatter.rs | 159 +- crates/rome_formatter/src/lib.rs | 24 +- crates/rome_formatter/src/macros.rs | 2 +- crates/rome_formatter/src/printer/mod.rs | 5 +- crates/rome_js_formatter/src/context.rs | 2 +- crates/rome_js_formatter/src/cst.rs | 6 +- crates/rome_js_formatter/src/formatter.rs | 1270 +++--- crates/rome_js_formatter/src/generated.rs | 3894 ++++++++++++----- .../any/array_assignment_pattern_element.rs | 15 +- .../js/any/array_binding_pattern_element.rs | 17 +- .../src/js/any/array_element.rs | 8 +- .../src/js/any/arrow_function_parameters.rs | 13 +- .../src/js/any/assignment.rs | 28 +- .../src/js/any/assignment_pattern.rs | 15 +- .../rome_js_formatter/src/js/any/binding.rs | 6 +- .../src/js/any/binding_pattern.rs | 12 +- .../src/js/any/call_argument.rs | 6 +- crates/rome_js_formatter/src/js/any/class.rs | 63 +- .../src/js/any/class_member.rs | 46 +- .../src/js/any/class_member_name.rs | 14 +- .../src/js/any/constructor_parameter.rs | 17 +- .../src/js/any/declaration.rs | 34 +- .../src/js/any/declaration_clause.rs | 49 +- .../src/js/any/export_clause.rs | 34 +- .../src/js/any/export_default_declaration.rs | 15 +- .../src/js/any/export_named_specifier.rs | 11 +- .../src/js/any/expression.rs | 86 +- .../src/js/any/for_in_or_of_initializer.rs | 13 +- .../src/js/any/for_initializer.rs | 8 +- .../src/js/any/formal_parameter.rs | 8 +- .../rome_js_formatter/src/js/any/function.rs | 98 +- .../src/js/any/function_body.rs | 6 +- .../src/js/any/import_assertion_entry.rs | 11 +- .../src/js/any/import_clause.rs | 14 +- .../src/js/any/in_property.rs | 6 +- .../src/js/any/literal_expression.rs | 29 +- .../src/js/any/method_modifier.rs | 10 +- .../src/js/any/module_item.rs | 8 +- crates/rome_js_formatter/src/js/any/name.rs | 6 +- .../src/js/any/named_import.rs | 10 +- .../src/js/any/named_import_specifier.rs | 12 +- .../any/object_assignment_pattern_member.rs | 12 +- .../js/any/object_binding_pattern_member.rs | 18 +- .../src/js/any/object_member.rs | 20 +- .../src/js/any/object_member_name.rs | 13 +- .../rome_js_formatter/src/js/any/parameter.rs | 8 +- .../src/js/any/property_modifier.rs | 19 +- crates/rome_js_formatter/src/js/any/root.rs | 8 +- .../rome_js_formatter/src/js/any/statement.rs | 72 +- .../src/js/any/switch_clause.rs | 6 +- .../src/js/any/template_element.rs | 8 +- .../assignments/array_assignment_pattern.rs | 22 +- .../array_assignment_pattern_rest_element.rs | 7 +- .../js/assignments/assignment_with_default.rs | 12 +- .../assignments/computed_member_assignment.rs | 12 +- .../js/assignments/identifier_assignment.rs | 8 +- .../assignments/object_assignment_pattern.rs | 21 +- .../object_assignment_pattern_property.rs | 19 +- .../object_assignment_pattern_rest.rs | 7 +- ...t_assignment_pattern_shorthand_property.rs | 19 +- .../assignments/parenthesized_assignment.rs | 10 +- .../assignments/static_member_assignment.rs | 11 +- .../src/js/auxiliary/array_hole.rs | 4 +- .../src/js/auxiliary/case_clause.rs | 44 +- .../src/js/auxiliary/catch_clause.rs | 34 +- .../src/js/auxiliary/default_clause.rs | 36 +- .../src/js/auxiliary/directive.rs | 16 +- .../src/js/auxiliary/else_clause.rs | 9 +- .../src/js/auxiliary/expression_snipped.rs | 13 +- .../src/js/auxiliary/finally_clause.rs | 12 +- .../src/js/auxiliary/function_body.rs | 28 +- .../src/js/auxiliary/initializer_clause.rs | 12 +- .../src/js/auxiliary/module.rs | 29 +- .../src/js/auxiliary/name.rs | 6 +- .../src/js/auxiliary/new_target.rs | 8 +- .../src/js/auxiliary/private_name.rs | 6 +- .../src/js/auxiliary/reference_identifier.rs | 9 +- .../src/js/auxiliary/script.rs | 25 +- .../src/js/auxiliary/spread.rs | 6 +- .../src/js/auxiliary/static_modifier.rs | 1 + .../auxiliary/variable_declaration_clause.rs | 19 +- .../src/js/auxiliary/variable_declarator.rs | 21 +- .../src/js/bindings/array_binding_pattern.rs | 22 +- .../array_binding_pattern_rest_element.rs | 8 +- .../bindings/binding_pattern_with_default.rs | 11 +- .../src/js/bindings/constructor_parameters.rs | 22 +- .../src/js/bindings/formal_parameter.rs | 16 +- .../src/js/bindings/identifier_binding.rs | 9 +- .../src/js/bindings/object_binding_pattern.rs | 22 +- .../object_binding_pattern_property.rs | 20 +- .../bindings/object_binding_pattern_rest.rs | 9 +- ...ject_binding_pattern_shorthand_property.rs | 21 +- .../src/js/bindings/parameters.rs | 19 +- .../src/js/bindings/rest_parameter.rs | 11 +- .../js/classes/constructor_class_member.rs | 11 +- .../src/js/classes/empty_class_member.rs | 8 +- .../src/js/classes/extends_clause.rs | 13 +- .../src/js/classes/getter_class_member.rs | 11 +- .../src/js/classes/method_class_member.rs | 24 +- .../src/js/classes/property_class_member.rs | 26 +- .../src/js/classes/setter_class_member.rs | 11 +- ...tatic_initialization_block_class_member.rs | 32 +- .../src/js/declarations/catch_declaration.rs | 18 +- .../src/js/declarations/class_declaration.rs | 9 +- .../class_export_default_declaration.rs | 8 +- .../declarations/for_variable_declaration.rs | 11 +- .../js/declarations/function_declaration.rs | 9 +- .../function_export_default_declaration.rs | 7 +- .../js/declarations/variable_declaration.rs | 11 +- .../src/js/expressions/array_expression.rs | 25 +- .../expressions/arrow_function_expression.rs | 8 +- .../js/expressions/assignment_expression.rs | 22 +- .../src/js/expressions/await_expression.rs | 11 +- .../expressions/big_int_literal_expression.rs | 21 +- .../src/js/expressions/binary_expression.rs | 5 +- .../expressions/boolean_literal_expression.rs | 9 +- .../src/js/expressions/call_arguments.rs | 26 +- .../src/js/expressions/call_expression.rs | 5 +- .../src/js/expressions/class_expression.rs | 9 +- .../expressions/computed_member_expression.rs | 44 +- .../js/expressions/conditional_expression.rs | 6 +- .../src/js/expressions/function_expression.rs | 9 +- .../js/expressions/identifier_expression.rs | 9 +- .../js/expressions/import_call_expression.rs | 9 +- .../src/js/expressions/in_expression.rs | 5 +- .../js/expressions/instanceof_expression.rs | 4 +- .../src/js/expressions/logical_expression.rs | 5 +- .../src/js/expressions/new_expression.rs | 13 +- .../js/expressions/null_literal_expression.rs | 9 +- .../expressions/number_literal_expression.rs | 9 +- .../src/js/expressions/object_expression.rs | 40 +- .../expressions/parenthesized_expression.rs | 70 +- .../js/expressions/post_update_expression.rs | 8 +- .../js/expressions/pre_update_expression.rs | 8 +- .../expressions/regex_literal_expression.rs | 14 +- .../src/js/expressions/sequence_expression.rs | 175 +- .../expressions/static_member_expression.rs | 74 +- .../expressions/string_literal_expression.rs | 36 +- .../src/js/expressions/super_expression.rs | 8 +- .../src/js/expressions/template.rs | 20 +- .../js/expressions/template_chunk_element.rs | 4 +- .../src/js/expressions/template_element.rs | 5 +- .../src/js/expressions/this_expression.rs | 8 +- .../src/js/expressions/unary_expression.rs | 41 +- .../src/js/expressions/yield_argument.rs | 11 +- .../src/js/expressions/yield_expression.rs | 8 +- .../array_assignment_pattern_element_list.rs | 4 +- .../array_binding_pattern_element_list.rs | 4 +- .../src/js/lists/array_element_list.rs | 24 +- .../src/js/lists/call_argument_list.rs | 10 +- .../src/js/lists/class_member_list.rs | 7 +- .../src/js/lists/constructor_modifier_list.rs | 12 +- .../js/lists/constructor_parameter_list.rs | 13 +- .../src/js/lists/directive_list.rs | 62 +- .../lists/export_named_from_specifier_list.rs | 13 +- .../js/lists/export_named_specifier_list.rs | 13 +- .../js/lists/import_assertion_entry_list.rs | 13 +- .../src/js/lists/method_modifier_list.rs | 9 +- .../src/js/lists/module_item_list.rs | 7 +- .../js/lists/named_import_specifier_list.rs | 13 +- ...object_assignment_pattern_property_list.rs | 18 +- .../object_binding_pattern_property_list.rs | 19 +- .../src/js/lists/object_member_list.rs | 16 +- .../src/js/lists/parameter_list.rs | 16 +- .../src/js/lists/property_modifier_list.rs | 12 +- .../src/js/lists/statement_list.rs | 7 +- .../src/js/lists/switch_case_list.rs | 7 +- .../src/js/lists/template_element_list.rs | 17 +- .../src/js/lists/variable_declarator_list.rs | 76 +- .../src/js/module/default_import_specifier.rs | 11 +- .../rome_js_formatter/src/js/module/export.rs | 10 +- .../src/js/module/export_as_clause.rs | 14 +- .../export_default_declaration_clause.rs | 9 +- .../export_default_expression_clause.rs | 20 +- .../src/js/module/export_from_clause.rs | 33 +- .../src/js/module/export_named_clause.rs | 45 +- .../src/js/module/export_named_from_clause.rs | 82 +- .../js/module/export_named_from_specifier.rs | 29 +- .../export_named_shorthand_specifier.rs | 1 + .../src/js/module/export_named_specifier.rs | 17 +- .../rome_js_formatter/src/js/module/import.rs | 18 +- .../src/js/module/import_assertion.rs | 24 +- .../src/js/module/import_assertion_entry.rs | 22 +- .../src/js/module/import_bare_clause.rs | 23 +- .../src/js/module/import_default_clause.rs | 29 +- .../src/js/module/import_meta.rs | 10 +- .../src/js/module/import_named_clause.rs | 36 +- .../src/js/module/import_namespace_clause.rs | 29 +- .../src/js/module/literal_export_name.rs | 8 +- .../src/js/module/module_source.rs | 8 +- .../src/js/module/named_import_specifier.rs | 18 +- .../src/js/module/named_import_specifiers.rs | 22 +- .../js/module/namespace_import_specifier.rs | 23 +- .../shorthand_named_import_specifier.rs | 20 +- .../src/js/objects/computed_member_name.rs | 11 +- .../src/js/objects/getter_object_member.rs | 11 +- .../src/js/objects/literal_member_name.rs | 10 +- .../src/js/objects/method_object_member.rs | 1 + .../js/objects/private_class_member_name.rs | 9 +- .../src/js/objects/property_object_member.rs | 20 +- .../src/js/objects/setter_object_member.rs | 11 +- .../shorthand_property_object_member.rs | 8 +- .../src/js/statements/block_statement.rs | 32 +- .../src/js/statements/break_statement.rs | 34 +- .../src/js/statements/continue_statement.rs | 34 +- .../src/js/statements/debugger_statement.rs | 18 +- .../src/js/statements/do_while_statement.rs | 45 +- .../src/js/statements/empty_statement.rs | 7 +- .../src/js/statements/expression_statement.rs | 18 +- .../src/js/statements/for_in_statement.rs | 44 +- .../src/js/statements/for_of_statement.rs | 50 +- .../src/js/statements/for_statement.rs | 80 +- .../src/js/statements/if_statement.rs | 64 +- .../src/js/statements/labeled_statement.rs | 25 +- .../src/js/statements/return_statement.rs | 65 +- .../src/js/statements/switch_statement.rs | 53 +- .../src/js/statements/throw_statement.rs | 18 +- .../js/statements/try_finally_statement.rs | 15 +- .../src/js/statements/try_statement.rs | 11 +- .../src/js/statements/variable_statement.rs | 18 +- .../src/js/statements/while_statement.rs | 35 +- .../src/js/statements/with_statement.rs | 35 +- .../src/js/unknown/unknown.rs | 2 +- .../src/js/unknown/unknown_assignment.rs | 5 +- .../src/js/unknown/unknown_binding.rs | 5 +- .../src/js/unknown/unknown_expression.rs | 5 +- .../unknown/unknown_import_assertion_entry.rs | 4 +- .../src/js/unknown/unknown_member.rs | 5 +- .../unknown/unknown_named_import_specifier.rs | 4 +- .../src/js/unknown/unknown_parameter.rs | 5 +- .../src/js/unknown/unknown_statement.rs | 5 +- .../src/jsx/any/attribute.rs | 6 +- .../src/jsx/any/attribute_name.rs | 6 +- .../src/jsx/any/attribute_value.rs | 10 +- crates/rome_js_formatter/src/jsx/any/child.rs | 14 +- .../src/jsx/any/element_name.rs | 12 +- crates/rome_js_formatter/src/jsx/any/name.rs | 6 +- .../src/jsx/any/object_name.rs | 10 +- crates/rome_js_formatter/src/jsx/any/tag.rs | 8 +- .../src/jsx/attribute/attribute.rs | 5 +- .../attribute/attribute_initializer_clause.rs | 6 +- .../attribute/expression_attribute_value.rs | 107 +- .../src/jsx/attribute/spread_attribute.rs | 10 +- .../src/jsx/auxiliary/expression_child.rs | 5 +- .../src/jsx/auxiliary/name.rs | 5 +- .../src/jsx/auxiliary/namespace_name.rs | 11 +- .../src/jsx/auxiliary/reference_identifier.rs | 8 +- .../src/jsx/auxiliary/spread_child.rs | 5 +- .../src/jsx/auxiliary/string.rs | 5 +- .../src/jsx/auxiliary/text.rs | 9 +- .../src/jsx/expressions/tag_expression.rs | 8 +- .../src/jsx/lists/attribute_list.rs | 14 +- .../src/jsx/lists/child_list.rs | 2 +- .../src/jsx/objects/member_name.rs | 8 +- .../src/jsx/tag/closing_element.rs | 5 +- .../src/jsx/tag/closing_fragment.rs | 10 +- .../rome_js_formatter/src/jsx/tag/element.rs | 2 +- .../rome_js_formatter/src/jsx/tag/fragment.rs | 7 +- .../src/jsx/tag/opening_element.rs | 5 +- .../src/jsx/tag/opening_fragment.rs | 8 +- .../src/jsx/tag/self_closing_element.rs | 10 +- crates/rome_js_formatter/src/lib.rs | 49 +- .../any/external_module_declaration_body.rs | 11 +- .../src/ts/any/index_signature_modifier.rs | 13 +- .../src/ts/any/method_signature_modifier.rs | 21 +- .../src/ts/any/module_name.rs | 6 +- .../src/ts/any/module_reference.rs | 8 +- crates/rome_js_formatter/src/ts/any/name.rs | 6 +- .../src/ts/any/property_annotation.rs | 16 +- .../src/ts/any/property_parameter_modifier.rs | 14 +- .../ts/any/property_signature_annotation.rs | 10 +- .../src/ts/any/property_signature_modifier.rs | 26 +- .../src/ts/any/return_type.rs | 8 +- .../src/ts/any/template_element.rs | 8 +- .../rome_js_formatter/src/ts/any/ts_type.rs | 70 +- .../src/ts/any/tuple_type_element.rs | 19 +- .../src/ts/any/type_member.rs | 32 +- .../ts/any/type_predicate_parameter_name.rs | 12 +- .../src/ts/any/variable_annotation.rs | 12 +- .../src/ts/assignments/as_assignment.rs | 10 +- .../non_null_assertion_assignment.rs | 8 +- .../assignments/type_assertion_assignment.rs | 20 +- .../src/ts/auxiliary/abstract_modifier.rs | 8 +- .../ts/auxiliary/accessibility_modifier.rs | 3 +- .../src/ts/auxiliary/asserts_condition.rs | 8 +- .../auxiliary/call_signature_type_member.rs | 18 +- .../construct_signature_type_member.rs | 16 +- .../src/ts/auxiliary/declare_modifier.rs | 8 +- .../src/ts/auxiliary/default_type_clause.rs | 8 +- .../auxiliary/definite_property_annotation.rs | 9 +- .../auxiliary/definite_variable_annotation.rs | 8 +- .../empty_external_module_declaration_body.rs | 7 +- .../src/ts/auxiliary/enum_member.rs | 16 +- .../ts/auxiliary/external_module_reference.rs | 10 +- .../auxiliary/getter_signature_type_member.rs | 16 +- .../src/ts/auxiliary/implements_clause.rs | 38 +- .../auxiliary/index_signature_type_member.rs | 19 +- .../src/ts/auxiliary/mapped_type_as_clause.rs | 16 +- .../mapped_type_optional_modifier_clause.rs | 10 +- .../mapped_type_readonly_modifier_clause.rs | 10 +- .../auxiliary/method_signature_type_member.rs | 15 +- .../src/ts/auxiliary/module_block.rs | 18 +- .../ts/auxiliary/named_tuple_type_element.rs | 10 +- .../auxiliary/optional_property_annotation.rs | 11 +- .../auxiliary/optional_tuple_type_element.rs | 1 + .../src/ts/auxiliary/override_modifier.rs | 8 +- .../property_signature_type_member.rs | 15 +- .../src/ts/auxiliary/qualified_module_name.rs | 11 +- .../src/ts/auxiliary/qualified_name.rs | 11 +- .../src/ts/auxiliary/readonly_modifier.rs | 8 +- .../ts/auxiliary/rest_tuple_type_element.rs | 8 +- .../ts/auxiliary/return_type_annotation.rs | 11 +- .../auxiliary/setter_signature_type_member.rs | 31 +- .../src/ts/auxiliary/type_annotation.rs | 8 +- .../ts/auxiliary/type_constraint_clause.rs | 8 +- .../src/ts/auxiliary/type_parameter_name.rs | 8 +- .../src/ts/bindings/identifier_binding.rs | 8 +- .../ts/bindings/index_signature_parameter.rs | 8 +- .../src/ts/bindings/property_parameter.rs | 10 +- .../src/ts/bindings/this_parameter.rs | 8 +- .../src/ts/bindings/type_parameter.rs | 29 +- .../src/ts/bindings/type_parameters.rs | 21 +- .../constructor_signature_class_member.rs | 22 +- .../src/ts/classes/extends_clause.rs | 34 +- .../classes/getter_signature_class_member.rs | 24 +- .../classes/index_signature_class_member.rs | 23 +- .../classes/method_signature_class_member.rs | 25 +- .../property_signature_class_member.rs | 23 +- .../classes/setter_signature_class_member.rs | 39 +- .../declare_function_declaration.rs | 34 +- .../src/ts/declarations/enum_declaration.rs | 65 +- .../external_module_declaration.rs | 11 +- .../src/ts/declarations/global_declaration.rs | 12 +- .../declarations/import_equals_declaration.rs | 25 +- .../ts/declarations/interface_declaration.rs | 37 +- .../src/ts/declarations/module_declaration.rs | 10 +- .../ts/declarations/type_alias_declaration.rs | 23 +- .../src/ts/expressions/as_expression.rs | 10 +- .../expressions/name_with_type_arguments.rs | 8 +- .../non_null_assertion_expression.rs | 8 +- .../ts/expressions/template_chunk_element.rs | 4 +- .../src/ts/expressions/template_element.rs | 5 +- .../ts/expressions/template_literal_type.rs | 10 +- .../src/ts/expressions/type_arguments.rs | 17 +- .../expressions/type_assertion_expression.rs | 20 +- .../src/ts/lists/enum_member_list.rs | 10 +- .../ts/lists/index_signature_modifier_list.rs | 13 +- .../lists/intersection_type_element_list.rs | 48 +- .../lists/method_signature_modifier_list.rs | 12 +- .../lists/property_parameter_modifier_list.rs | 12 +- .../lists/property_signature_modifier_list.rs | 12 +- .../src/ts/lists/template_element_list.rs | 17 +- .../src/ts/lists/tuple_type_element_list.rs | 13 +- .../src/ts/lists/type_argument_list.rs | 22 +- .../src/ts/lists/type_list.rs | 22 +- .../src/ts/lists/type_member_list.rs | 82 +- .../src/ts/lists/type_parameter_list.rs | 17 +- .../src/ts/lists/union_type_variant_list.rs | 77 +- .../ts/module/export_as_namespace_clause.rs | 25 +- .../src/ts/module/export_assignment_clause.rs | 21 +- .../src/ts/module/export_declare_clause.rs | 10 +- .../src/ts/module/import_type.rs | 14 +- .../src/ts/module/import_type_qualifier.rs | 8 +- .../src/ts/statements/declare_statement.rs | 10 +- .../src/ts/types/any_type.rs | 5 +- .../src/ts/types/array_type.rs | 7 +- .../src/ts/types/asserts_return_type.rs | 10 +- .../src/ts/types/big_int_literal_type.rs | 8 +- .../src/ts/types/bigint_type.rs | 5 +- .../src/ts/types/boolean_literal_type.rs | 8 +- .../src/ts/types/boolean_type.rs | 5 +- .../src/ts/types/conditional_type.rs | 7 +- .../src/ts/types/constructor_type.rs | 17 +- .../src/ts/types/function_type.rs | 10 +- .../src/ts/types/indexed_access_type.rs | 10 +- .../src/ts/types/infer_type.rs | 10 +- .../src/ts/types/intersection_type.rs | 55 +- .../src/ts/types/mapped_type.rs | 62 +- .../src/ts/types/never_type.rs | 5 +- .../src/ts/types/non_primitive_type.rs | 8 +- .../src/ts/types/null_literal_type.rs | 8 +- .../src/ts/types/number_literal_type.rs | 8 +- .../src/ts/types/number_type.rs | 5 +- .../src/ts/types/object_type.rs | 33 +- .../src/ts/types/parenthesized_type.rs | 19 +- .../src/ts/types/predicate_return_type.rs | 10 +- .../src/ts/types/reference_type.rs | 8 +- .../src/ts/types/string_literal_type.rs | 11 +- .../src/ts/types/string_type.rs | 5 +- .../src/ts/types/symbol_type.rs | 5 +- .../src/ts/types/this_type.rs | 5 +- .../src/ts/types/tuple_type.rs | 18 +- .../src/ts/types/type_operator_type.rs | 16 +- .../src/ts/types/typeof_type.rs | 14 +- .../src/ts/types/undefined_type.rs | 8 +- .../src/ts/types/union_type.rs | 71 +- .../src/ts/types/unknown_type.rs | 6 +- .../src/ts/types/void_type.rs | 5 +- crates/rome_js_formatter/src/utils/array.rs | 80 +- .../src/utils/binary_like_expression.rs | 228 +- .../src/utils/format_conditional.rs | 224 +- .../src/utils/member_chain/flatten_item.rs | 1 - .../src/utils/member_chain/groups.rs | 38 +- .../src/utils/member_chain/mod.rs | 99 +- crates/rome_js_formatter/src/utils/mod.rs | 286 +- .../src/utils/string_utils.rs | 27 +- .../module/arrow/arrow_function.js.snap.new | 31 + .../js/module/arrow/arrow_nested.js.snap.new | 89 + .../specs/js/module/arrow/call.js.snap.new | 118 + .../js/module/arrow/currying.js.snap.new | 46 + .../specs/js/module/arrow/params.js.snap.new | 418 ++ .../module/assignment/assignment.js.snap.new | 79 + .../binding/identifier_binding.js.snap.new | 22 + .../specs/js/module/class/class.js.snap.new | 129 + .../module/class/class_comments.js.snap.new | 29 + .../js/module/export/class_clause.js.snap.new | 30 + .../js/module/export/from_clause.js.snap.new | 31 + .../module/export/function_clause.js.snap.new | 26 + .../export/variable_declaration.js.snap.new | 22 + .../expression/binary_expression.js.snap.new | 70 + .../conditional_expression.js.snap.new | 43 + .../expression/logical_expression.js.snap.new | 302 ++ .../member-chain/inline-merge.js.snap.new | 38 + .../sequence_expression.js.snap.new | 87 + .../static_member_expression.js.snap.new | 45 + .../js/module/function/function.js.snap.new | 75 + .../js/module/import/bare_import.js.snap.new | 59 + .../import/import_specifiers.js.snap.new | 64 + .../specs/js/module/interpreter.js.snap.new | 23 + .../module/invalid/block_stmt_err.js.snap.new | 34 + .../specs/js/module/newlines.js.snap.new | 145 + .../module/object/computed_member.js.snap.new | 72 + .../specs/js/module/object/object.js.snap.new | 73 + .../module/object/object_comments.js.snap.new | 23 + .../parentheses/parentheses.js.snap.new | 65 + .../js/module/statement/do_while.js.snap.new | 38 + .../module/statement/empty_blocks.js.snap.new | 73 + .../js/module/statement/for_in.js.snap.new | 34 + .../js/module/statement/for_of.js.snap.new | 37 + .../js/module/statement/if_chain.js.snap.new | 33 + .../js/module/statement/if_else.js.snap.new | 126 + .../js/module/statement/return.js.snap.new | 28 + .../js/module/statement/switch.js.snap.new | 51 + .../js/module/statement/throw.js.snap.new | 21 + .../statement/try_catch_finally.js.snap.new | 64 + .../module/statement/while_loop.js.snap.new | 61 + .../specs/js/module/string/string.js.snap.new | 189 + .../specs/js/module/suppression.js.snap.new | 68 + .../js/module/template/template.js.snap.new | 129 + .../tests/specs/js/script/with.js.snap.new | 27 + .../tests/specs/jsx/attributes.jsx.snap.new | 116 + .../tests/specs/jsx/self_closing.jsx.snap.new | 37 + .../js/arrays/numbers-in-args.js.snap.new | 42 + .../arrays/numbers-in-assignment.js.snap.new | 42 + ...s-negative-comment-after-minus.js.snap.new | 92 + .../js/arrays/numbers-negative.js.snap.new | 78 + .../js/arrays/numbers-with-holes.js.snap.new | 72 + .../prettier/js/arrays/numbers2.js.snap.new | 98 + .../js/arrow-call/arrow_call.js.snap.new | 105 + .../assignment-comments/function.js.snap.new | 121 + .../identifier.js.snap.new | 29 + .../js/assignment/binaryish.js.snap.new | 43 + .../assignment/call-with-template.js.snap.new | 38 + .../prettier/js/assignment/chain.js.snap.new | 72 + .../destructuring-heuristic.js.snap.new | 67 + .../js/assignment/destructuring.js.snap.new | 40 + .../js/assignment/issue-10218.js.snap.new | 34 + .../js/assignment/issue-1966.js.snap.new | 30 + .../js/assignment/issue-2482-1.js.snap.new | 41 + .../js/assignment/issue-6922.js.snap.new | 69 + .../js/assignment/issue-7961.js.snap.new | 27 + .../js/assignment/issue-8218.js.snap.new | 27 + .../js/assignment/lone-arg.js.snap.new | 53 + .../js/assignment/sequence.js.snap.new | 29 + .../async-do-expressions.js.snap.new | 165 + .../js/async/async-iteration.js.snap.new | 34 + .../async/conditional-expression.js.snap.new | 40 + .../prettier/js/async/parens.js.snap.new | 25 + .../class-properties.js.snap.new | 64 + .../js/babel-plugins/decimal.js.snap.new | 371 ++ .../js/babel-plugins/decorators.js.snap.new | 69 + .../babel-plugins/function-sent.js.snap.new | 46 + .../logical-assignment-operators.js.snap.new | 29 + .../object-rest-spread.js.snap.new | 33 + .../optional-catch-binding.js.snap.new | 45 + .../partial-application.js.snap.new | 143 + .../pipeline-operator-fsharp.js.snap.new | 150 + .../pipeline-operator-minimal.js.snap.new | 61 + .../record-tuple-record.js.snap.new | 93 + .../js/babel-plugins/v8intrinsic.js.snap.new | 96 + .../js/binary-expressions/arrow.js.snap.new | 63 + .../bitwise-flags.js.snap.new | 25 + .../js/binary-expressions/call.js.snap.new | 129 + .../js/binary-expressions/comment.js.snap.new | 121 + .../binary-expressions/equality.js.snap.new | 33 + .../js/binary-expressions/if.js.snap.new | 40 + .../binary-expressions/inline-jsx.js.snap.new | 36 + .../inline-object-array.js.snap.new | 202 + .../binary-expressions/jsx_parent.js.snap.new | 79 + .../js/binary-expressions/math.js.snap.new | 56 + .../js/binary-expressions/return.js.snap.new | 48 + .../short-right.js.snap.new | 49 + .../js/binary_math/parens.js.snap.new | 55 + .../bind-expressions/method_chain.js.snap.new | 72 + .../prettier/js/break-calls/break.js.snap.new | 105 + .../js/break-calls/reduce.js.snap.new | 34 + .../js/class-comment/superclass.js.snap.new | 91 + .../js/class-extends/complex.js.snap.new | 50 + .../class-static-block.js.snap.new | 69 + .../private_fields.js.snap.new | 127 + .../js/classes/assignment.js.snap.new | 83 + .../prettier/js/classes/empty.js.snap.new | 39 + .../prettier/js/classes/method.js.snap.new | 33 + .../prettier/js/classes/property.js.snap.new | 54 + .../closure-compiler-type-cast.js.snap.new | 131 + .../comment-in-the-middle.js.snap.new | 37 + .../comment-placement.js.snap.new | 47 + .../iife.js.snap.new | 42 + .../issue-4124.js.snap.new | 44 + .../issue-8045.js.snap.new | 67 + .../nested.js.snap.new | 31 + .../non-casts.js.snap.new | 49 + .../object-with-comment.js.snap.new | 38 + .../ways-to-specify-type.js.snap.new | 41 + .../pipeline_own_line.js.snap.new | 159 + .../prettier/js/comments/arrow.js.snap.new | 21 + .../comments/assignment-pattern.js.snap.new | 27 + ...ary-expressions-block-comments.js.snap.new | 104 + ...ry-expressions-single-comments.js.snap.new | 56 + .../comments/binary-expressions.js.snap.new | 147 + .../break-continue-statements.js.snap.new | 37 + .../js/comments/call_comment.js.snap.new | 54 + .../prettier/js/comments/class.js.snap.new | 35 + .../prettier/js/comments/dangling.js.snap.new | 38 + .../js/comments/dangling_array.js.snap.new | 25 + .../js/comments/dangling_for.js.snap.new | 22 + .../js/comments/dynamic_imports.js.snap.new | 45 + .../prettier/js/comments/emoji.js.snap.new | 25 + .../prettier/js/comments/export.js.snap.new | 55 + .../comments/function-declaration.js.snap.new | 133 + .../prettier/js/comments/jsdoc.js.snap.new | 69 + .../prettier/js/comments/jsx.js.snap.new | 242 + .../js/comments/multi-comments.js.snap.new | 51 + .../preserve-new-line-last.js.snap.new | 52 + .../prettier/js/comments/switch.js.snap.new | 87 + .../tagged-template-literal.js.snap.new | 41 + .../js/comments/template-literal.js.snap.new | 41 + .../comments/variable_declarator.js.snap.new | 126 + .../prettier/js/comments/while.js.snap.new | 52 + .../js/conditional/comments.js.snap.new | 195 + .../prettier/js/cursor/cursor-4.js.snap.new | 25 + .../prettier/js/cursor/cursor-7.js.snap.new | 22 + .../after_export.js.snap.new | 46 + .../before_export.js.snap.new | 25 + .../js/decorators/classes.js.snap.new | 72 + .../prettier/js/decorators/mobx.js.snap.new | 124 + .../js/decorators/multiple.js.snap.new | 83 + .../prettier/js/decorators/redux.js.snap.new | 25 + .../destructuring-ignore/ignore.js.snap.new | 94 + .../destructuring/destructuring.js.snap.new | 103 + .../js/directives/newline.js.snap.new | 29 + .../prettier/js/directives/test.js.snap.new | 60 + .../prettier/js/do/call-arguments.js.snap.new | 189 + .../tests/specs/prettier/js/do/do.js.snap.new | 298 ++ .../empty_paren_comment.js.snap.new | 49 + .../first-argument-expansion/test.js.snap.new | 299 ++ .../js/for-await/for-await.js.snap.new | 49 + .../js/for-of/async-identifier.js.snap.new | 35 + .../specs/prettier/js/for/comment.js.snap.new | 75 + .../continue-and-break-comment-1.js.snap.new | 209 + .../continue-and-break-comment-2.js.snap.new | 281 ++ ...d-break-comment-without-blocks.js.snap.new | 169 + .../specs/prettier/js/for/for.js.snap.new | 25 + .../function_expression.js.snap.new | 70 + .../array.js.snap.new | 89 + .../object.js.snap.new | 134 + .../functional_compose.js.snap.new | 80 + ...e-function-calls-with-comments.js.snap.new | 111 + .../pipe-function-calls.js.snap.new | 73 + .../ramda_compose.js.snap.new | 102 + .../redux_compose.js.snap.new | 37 + .../reselect_createselector.js.snap.new | 38 + .../rxjs_pipe.js.snap.new | 35 + .../js/generator/anonymous.js.snap.new | 51 + .../function-name-starts-with-get.js.snap.new | 29 + .../js/if/comment_before_else.js.snap.new | 45 + .../specs/prettier/js/if/else.js.snap.new | 56 + .../expr_and_same_line_comments.js.snap.new | 76 + .../prettier/js/if/if_comments.js.snap.new | 125 + .../js/if/trailing_comment.js.snap.new | 43 + .../prettier/js/ignore/ignore-2.js.snap.new | 53 + .../prettier/js/ignore/ignore.js.snap.new | 127 + .../js/ignore/issue-10661.js.snap.new | 70 + .../js/ignore/semi/directive.js.snap.new | 33 + .../js/import-assertions/empty.js.snap.new | 28 + .../js/import/empty-import.js.snap.new | 18 + .../prettier/js/in/arrow-function.js.snap.new | 21 + .../break-parent.js.snap.new | 69 + .../empty-object.js.snap.new | 62 + .../function-expression.js.snap.new | 55 + .../object.js.snap.new | 54 + .../line-suffix-boundary/boundary.js.snap.new | 72 + .../prettier/js/line/windows.js.snap.new | 25 + .../prettier/js/literal/number.js.snap.new | 182 + .../logical-assignment.js.snap.new | 113 + .../logical_expression_operators.js.snap.new | 75 + .../prettier/js/member/expand.js.snap.new | 91 + .../prettier/js/member/logical.js.snap.new | 25 + .../method-chain/break-last-call.js.snap.new | 141 + .../break-last-member.js.snap.new | 78 + .../method-chain/break-multiple.js.snap.new | 24 + .../js/method-chain/comment.js.snap.new | 125 + .../method-chain/computed-merge.js.snap.new | 45 + .../js/method-chain/conditional.js.snap.new | 62 + .../js/method-chain/cypress.js.snap.new | 25 + .../prettier/js/method-chain/d3.js.snap.new | 51 + .../js/method-chain/first_long.js.snap.new | 90 + .../js/method-chain/inline_merge.js.snap.new | 48 + .../js/method-chain/issue-11298.js.snap.new | 21 + .../js/method-chain/issue-3594.js.snap.new | 31 + .../js/method-chain/issue-3621.js.snap.new | 36 + .../js/method-chain/issue-4125.js.snap.new | 326 ++ .../js/method-chain/logical.js.snap.new | 56 + .../method-chain/multiple-members.js.snap.new | 101 + .../method-chain/object-literal.js.snap.new | 45 + .../js/method-chain/pr-7889.js.snap.new | 49 + .../js/method-chain/simple-args.js.snap.new | 21 + .../js/method-chain/square_0.js.snap.new | 31 + .../prettier/js/method-chain/test.js.snap.new | 26 + .../js/module-blocks/comments.js.snap.new | 71 + .../module-blocks/module-blocks.js.snap.new | 295 ++ .../js/module-blocks/range.js.snap.new | 79 + .../js/module-blocks/worker.js.snap.new | 85 + .../comment-inside.js.snap.new | 137 + .../colons-after-substitutions2.js.snap.new | 60 + .../multiparser-css/issue-11797.js.snap.new | 42 + .../js/multiparser-css/issue-2636.js.snap.new | 49 + .../js/multiparser-css/issue-2883.js.snap.new | 48 + .../js/multiparser-css/issue-5961.js.snap.new | 85 + .../js/multiparser-css/issue-9072.js.snap.new | 40 + ...omponents-multiple-expressions.js.snap.new | 54 + .../styled-components.js.snap.new | 517 +++ .../js/multiparser-css/var.js.snap.new | 64 + .../js/multiparser-graphql/escape.js.snap.new | 96 + .../expressions.js.snap.new | 51 + .../react-relay.js.snap.new | 48 + .../html-template-literals.js.snap.new | 76 + .../js/multiparser-html/lit-html.js.snap.new | 212 + .../js/multiparser-invalid/text.js.snap.new | 128 + .../js/new-expression/call.js.snap.new | 23 + .../no-semi.js.snap.new | 48 + .../prettier/js/no-semi/comments.js.snap.new | 34 + .../prettier/js/no-semi/issue2006.js.snap.new | 31 + .../prettier/js/no-semi/no-semi.js.snap.new | 173 + .../js/non-strict/keywords.js.snap.new | 42 + .../js/object-prop-break-in/test.js.snap.new | 77 + .../after-key.js.snap.new | 29 + .../object-property-ignore/ignore.js.snap.new | 109 + .../issue-5678.js.snap.new | 119 + .../object-value.js.snap.new | 32 + .../objects/escape-sequence-key.js.snap.new | 31 + .../prettier/js/objects/expand.js.snap.new | 27 + .../js/objects/expression.js.snap.new | 83 + .../js/objects/right-break.js.snap.new | 52 + .../js/optional-chaining/chaining.js.snap.new | 171 + .../js/optional-chaining/comments.js.snap.new | 91 + .../js/optional-chaining/eval.js.snap.new | 56 + .../js/partial-application/test.js.snap.new | 79 + .../js/performance/nested-real.js.snap.new | 179 + ...fsharp_style_pipeline_operator.js.snap.new | 314 ++ .../hack_pipeline_operator.js.snap.new | 590 +++ .../minimal_pipeline_operator.js.snap.new | 319 ++ .../js/preserve-line/comments.js.snap.new | 64 + .../js/preserve-line/member-chain.js.snap.new | 110 + .../preserve-line/parameter-list.js.snap.new | 222 + .../js/private-in/private-in.js.snap.new | 39 + .../prettier/js/quotes/functions.js.snap.new | 25 + .../js/range/multiple-statements.js.snap.new | 41 + .../js/range/multiple-statements2.js.snap.new | 41 + .../prettier/js/record/computed.js.snap.new | 253 ++ .../js/record/destructuring.js.snap.new | 104 + .../prettier/js/record/record.js.snap.new | 128 + .../prettier/js/record/spread.js.snap.new | 139 + .../js/require-amd/require.js.snap.new | 97 + .../prettier/js/require/require.js.snap.new | 48 + .../prettier/js/return/binaryish.js.snap.new | 65 + .../prettier/js/return/comment.js.snap.new | 91 + .../prettier/js/spread/spread.js.snap.new | 25 + .../js/strings/template-literals.js.snap.new | 206 + .../prettier/js/switch/comments.js.snap.new | 130 + .../js/switch/empty_lines.js.snap.new | 145 + .../prettier/js/switch/switch.js.snap.new | 95 + .../nested-functions.spec.js.snap.new | 37 + .../js/template-literals/css-prop.js.snap.new | 75 + .../template-literals/expressions.js.snap.new | 130 + ...ed-components-with-expressions.js.snap.new | 99 + .../styled-jsx-with-expressions.js.snap.new | 100 + .../template-literals/styled-jsx.js.snap.new | 172 + .../prettier/js/template/arrow.js.snap.new | 31 + .../prettier/js/template/call.js.snap.new | 42 + .../js/template/faulty-locations.js.snap.new | 44 + .../prettier/js/template/inline.js.snap.new | 72 + .../js/template/parenthesis.js.snap.new | 108 + .../prettier/js/ternaries/binary.js.snap.new | 58 + .../ternaries/indent-after-paren.js.snap.new | 594 +++ .../prettier/js/ternaries/indent.js.snap.new | 298 ++ .../ternaries/nested-in-condition.js.snap.new | 93 + .../prettier/js/ternaries/nested.js.snap.new | 198 + .../js/ternaries/parenthesis.js.snap.new | 44 + .../prettier/js/ternaries/test.js.snap.new | 63 + .../angular_async.js.snap.new | 86 + .../angular_fakeAsync.js.snap.new | 83 + .../angular_waitForAsync.js.snap.new | 83 + .../angularjs_inject.js.snap.new | 83 + .../jest-each-template-string.js.snap.new | 42 + .../test-declarations/jest-each.js.snap.new | 158 + .../test_declarations.js.snap.new | 374 ++ .../throw_expression.js.snap.new | 109 + .../js/throw_statement/binaryish.js.snap.new | 63 + .../js/throw_statement/comment.js.snap.new | 56 + .../js/throw_statement/jsx.js.snap.new | 57 + .../trailing-comma/function-calls.js.snap.new | 52 + .../js/trailing-comma/object.js.snap.new | 56 + .../trailing_whitespace.js.snap.new | 102 + .../specs/prettier/js/try/catch.js.snap.new | 61 + .../specs/prettier/js/try/empty.js.snap.new | 31 + .../js/tuple/destructuring.js.snap.new | 80 + .../specs/prettier/js/tuple/tuple.js.snap.new | 164 + .../js/unary-expression/comments.js.snap.new | 570 +++ .../prettier/js/unary/series.js.snap.new | 45 + .../unicode/combining-characters.js.snap.new | 28 + .../v8_intrinsic/intrinsic_call.js.snap.new | 93 + .../variable_declarator/multiple.js.snap.new | 60 + .../prettier/js/while/indent.js.snap.new | 76 + .../specs/prettier/js/with/indent.js.snap.new | 38 + .../prettier/js/yield/conditional.js.snap.new | 52 + .../typescript/ambient/ambient.ts.snap.new | 46 + .../argument_expansion.ts.snap.new | 111 + .../arrow-with-return-type.ts.snap.new | 78 + .../arrow/arrow_regression.ts.snap.new | 41 + .../typescript/arrow/comments.ts.snap.new | 34 + .../arrow/issue-6107-curry.ts.snap.new | 47 + .../prettier/typescript/as/as.ts.snap.new | 128 + .../typescript/as/assignment.ts.snap.new | 85 + .../typescript/as/assignment2.ts.snap.new | 76 + .../as/long-identifiers.ts.snap.new | 47 + .../typescript/as/ternary.ts.snap.new | 103 + .../typescript/assert/index.ts.snap.new | 66 + .../assignment/issue-10850.ts.snap.new | 39 + .../assignment/issue-3122.ts.snap.new | 37 + .../assignment/issue-8619.ts.snap.new | 32 + .../typescript/cast/as-const.ts.snap.new | 25 + .../typescript/cast/generic-cast.ts.snap.new | 232 + .../typescript/cast/hug-args.ts.snap.new | 60 + .../typescript/cast/parenthesis.ts.snap.new | 31 + .../catch-clause/type-annotation.ts.snap.new | 25 + .../class-comment/generic.ts.snap.new | 50 + .../class/abstract-method.ts.snap.new | 54 + .../typescript/class/constructor.ts.snap.new | 90 + .../class/empty-method-body.ts.snap.new | 35 + .../class/extends_implements.ts.snap.new | 167 + .../typescript/class/generics.ts.snap.new | 36 + .../typescript/class/methods.ts.snap.new | 48 + .../typescript/class/optional.ts.snap.new | 31 + .../classes/break-heritage.ts.snap.new | 60 + .../typescript/classes/break.ts.snap.new | 99 + .../comments-2/last-arg.ts.snap.new | 124 + .../comments/declare_function.ts.snap.new | 30 + .../typescript/comments/jsx.ts.snap.new | 29 + .../typescript/comments/location.ts.snap.new | 93 + .../comments/mapped_types.ts.snap.new | 96 + .../comments/method_types.ts.snap.new | 84 + .../comments/type-parameters.ts.snap.new | 132 + .../typescript/comments/union.ts.snap.new | 55 + .../anyIsAssignableToObject.ts.snap.new | 29 + .../compiler/castParentheses.ts.snap.new | 37 + .../typescript/compiler/castTest.ts.snap.new | 71 + .../declareDottedModuleName.ts.snap.new | 36 + ...decrementAndIncrementOperators.ts.snap.new | 161 + .../globalIsContextualKeyword.ts.snap.new | 42 + .../indexSignatureWithInitializer.ts.snap.new | 30 + ...pedTypeWithCombinedTypeMappers.ts.snap.new | 49 + .../conditional-types/comments.ts.snap.new | 133 + .../conditonal-types.ts.snap.new | 91 + .../conditional-types/infer-type.ts.snap.new | 33 + .../nested-in-condition.ts.snap.new | 52 + .../ambient/ambientDeclarations.ts.snap.new | 62 + .../classAbstractAsIdentifier.ts.snap.new | 26 + ...signabilityConstructorFunction.ts.snap.new | 25 + ...stractClinterfaceAssignability.ts.snap.new | 37 + ...stractConstructorAssignability.ts.snap.new | 38 + .../classAbstractCrashedOnce.ts.snap.new | 31 + .../classAbstractExtends.ts.snap.new | 42 + .../classAbstractFactoryFunction.ts.snap.new | 44 + .../classAbstractGeneric.ts.snap.new | 63 + ...assAbstractImportInstantiation.ts.snap.new | 26 + .../classAbstractInAModule.ts.snap.new | 26 + .../classAbstractInheritance.ts.snap.new | 48 + .../classAbstractInstantiations1.ts.snap.new | 48 + .../classAbstractInstantiations2.ts.snap.new | 119 + .../classAbstractOverloads.ts.snap.new | 62 + ...ssAbstractOverrideWithAbstract.ts.snap.new | 56 + .../classAbstractSingleLineDecl.ts.snap.new | 35 + .../classAbstractSuperCalls.ts.snap.new | 77 + ...ssAbstractUsingAbstractMethod1.ts.snap.new | 47 + ...sAbstractUsingAbstractMethods2.ts.snap.new | 72 + ...ssAppearsToHaveMembersOfObject.ts.snap.new | 31 + .../classExtendingClass.ts.snap.new | 72 + .../classExtendsItselfIndirectly.ts.snap.new | 44 + .../classIsSubtypeOfBaseType.ts.snap.new | 29 + .../classes/classExpression.ts.snap.new | 31 + ...orDefaultValuesReferencingThis.ts.snap.new | 35 + ...mplementationWithDefaultValues.ts.snap.new | 53 + ...plementationWithDefaultValues2.ts.snap.new | 53 + ...ctorOverloadsWithDefaultValues.ts.snap.new | 38 + ...verloadsWithOptionalParameters.ts.snap.new | 38 + ...constructorParameterProperties.ts.snap.new | 53 + ...onstructorParameterProperties2.ts.snap.new | 71 + ...eadonlyInConstructorParameters.ts.snap.new | 52 + .../classes/mixinAccessModifiers.ts.snap.new | 215 + .../classes/mixinClassesAnnotated.ts.snap.new | 136 + .../classes/mixinClassesAnonymous.ts.snap.new | 140 + .../classes/mixinClassesMembers.ts.snap.new | 205 + .../nestedClassDeclaration.ts.snap.new | 34 + .../es6/Symbols/symbolProperty15.ts.snap.new | 42 + .../callWithSpreadES6.ts.snap.new | 107 + ...nterfaceWithMultipleBaseTypes2.ts.snap.new | 60 + .../circularImportAlias.ts.snap.new | 50 + .../exportImportAlias.ts.snap.new | 138 + .../importAliasIdentifiers.ts.snap.new | 98 + .../invalidImportAliasIdentifiers.ts.snap.new | 56 + .../shadowedInternalModule.ts.snap.new | 76 + .../ambient/ambientDeclarations.ts.snap.new | 36 + .../functionOverloadErrorsSyntax.ts.snap.new | 49 + .../functionTypeTypeParameters.ts.snap.new | 18 + ...InitializersForwardReferencing.ts.snap.new | 106 + .../interfaceDeclaration.ts.snap.new | 34 + .../intersectionType.ts.snap.new | 25 + .../moduleDeclaration.ts.snap.new | 31 + .../tuple/contextualTypeWithTuple.ts.snap.new | 63 + .../types/tuple/indexerWithTuple.ts.snap.new | 78 + .../typeInferenceWithTupleType.ts.snap.new | 60 + .../types/tuple/wideningTuples1.ts.snap.new | 25 + .../types/tuple/wideningTuples3.ts.snap.new | 23 + .../types/tuple/wideningTuples4.ts.snap.new | 23 + ...MembersUsingClassTypeParameter.ts.snap.new | 44 + .../unionTypeCallSignatures3.ts.snap.new | 43 + .../unionTypeCallSignatures4.ts.snap.new | 62 + .../union/unionTypeEquivalence.ts.snap.new | 52 + ...unionTypePropertyAccessibility.ts.snap.new | 105 + .../abstractNewlineHandling.ts.snap.new | 50 + .../custom/call/callSignature.ts.snap.new | 31 + .../computedProperties/string.ts.snap.new | 43 + .../computedProperties/symbol.ts.snap.new | 29 + .../declare/declareModifier.d.ts.snap.new | 31 + .../custom/modifiers/minustoken.ts.snap.new | 29 + .../custom/module/moduleNamespace.ts.snap.new | 21 + .../custom/module/nestedNamespace.ts.snap.new | 29 + .../custom/new/newKeyword.ts.snap.new | 29 + .../custom/stability/moduleBlock.ts.snap.new | 57 + .../declare/declare_enum.ts.snap.new | 20 + .../declare/declare_function.ts.snap.new | 32 + .../declare/declare_interface.ts.snap.new | 33 + .../declare/declare_var.ts.snap.new | 25 + .../decorator-type-assertion.ts.snap.new | 29 + .../decorators-comments.ts.snap.new | 110 + .../decorators/decorators.ts.snap.new | 152 + .../decorators/inline-decorators.ts.snap.new | 110 + .../typescript/definite/definite.ts.snap.new | 39 + .../destructuring/destructuring.ts.snap.new | 23 + .../prettier/typescript/enum/enum.ts.snap.new | 60 + .../typescript/enum/multiline.ts.snap.new | 20 + .../error-recovery/generic.ts.snap.new | 113 + .../index-signature.ts.snap.new | 191 + .../typescript/export/export.ts.snap.new | 29 + .../single-parameter.ts.snap.new | 23 + .../function/single_expand.ts.snap.new | 37 + ...e-function-calls-with-comments.ts.snap.new | 113 + .../generic/arrow-return-type.ts.snap.new | 128 + .../typescript/generic/issue-6899.ts.snap.new | 34 + .../import-export/type-modifier.ts.snap.new | 55 + .../import-require/type-imports.ts.snap.new | 40 + .../import-type/import-type.ts.snap.new | 42 + .../typescript/interface/generic.ts.snap.new | 33 + .../typescript/interface/ignore.ts.snap.new | 210 + .../interface/long-extends.ts.snap.new | 66 + .../interface/pattern-parameters.ts.snap.new | 26 + .../interface/separator.ts.snap.new | 47 + .../typescript/interface2/break.ts.snap.new | 209 + .../interface2/comments.ts.snap.new | 84 + .../key-remapping.ts.snap.new | 36 + .../keywords/keywords-2.ts.snap.new | 116 + .../typescript/keywords/keywords.ts.snap.new | 281 ++ .../typescript/keywords/module.ts.snap.new | 150 + .../issue-10352-consistency.ts.snap.new | 52 + ...ature-with-wrapped-return-type.ts.snap.new | 39 + .../method/method-signature.ts.snap.new | 49 + .../typescript/method/semi.ts.snap.new | 29 + .../typescript/module/keyword.ts.snap.new | 71 + .../multiparser-css/issue-6259.ts.snap.new | 31 + .../typescript/new/new-signature.ts.snap.new | 144 + .../typescript/non-null/braces.ts.snap.new | 48 + .../non-null/member-chain.ts.snap.new | 33 + .../non-null/optional-chain.ts.snap.new | 50 + .../typescript/non-null/parens.ts.snap.new | 61 + .../optional-method.ts.snap.new | 39 + .../prettier-ignore/mapped-types.ts.snap.new | 134 + .../rest-type/infer-type.ts.snap.new | 35 + .../typescript/ternaries/indent.ts.snap.new | 118 + .../tsx/generic-component.tsx.snap.new | 24 + .../typescript/tsx/react.tsx.snap.new | 29 + .../tsx/type-parameters.tsx.snap.new | 52 + .../prettier/typescript/tsx/url.tsx.snap.new | 33 + ...railing-comma-for-empty-tuples.ts.snap.new | 25 + .../tuple/tuple-labeled.ts.snap.new | 40 + .../type-alias/issue-100857.ts.snap.new | 93 + .../type-alias/pattern-parameter.ts.snap.new | 26 + .../type-member-get-set.ts.snap.new | 40 + .../typeparams/class-method.ts.snap.new | 343 ++ .../typeparams/long-function-arg.ts.snap.new | 48 + .../typescript/union/comments.ts.snap.new | 35 + .../typescript/union/inlining.ts.snap.new | 104 + .../typescript/webhost/webtsc.ts.snap.new | 229 + .../ts/assignment/as_assignment.ts.snap.new | 25 + .../type_assertion_assignment.ts.snap.new | 42 + .../class/constructor_parameter.ts.snap.new | 75 + .../ts/class/implements_clause.ts.snap.new | 27 + .../specs/ts/declaration/class.ts.snap.new | 133 + .../declaration/declare_function.ts.snap.new | 25 + .../ts/declaration/interface.ts.snap.new | 69 + .../ts/expression/type_expression.ts.snap.new | 212 + .../ts/expression/type_member.ts.snap.new | 151 + .../specs/ts/module/export_clause.ts.snap.new | 45 + .../external_module_reference.ts.snap.new | 21 + .../ts/module/module_declaration.ts.snap.new | 22 + .../ts/statement/empty_block.ts.snap.new | 19 + .../ts/statement/enum_statement.ts.snap.new | 44 + .../specs/ts/type/conditional.ts.snap.new | 60 + .../specs/ts/type/import_type.ts.snap.new | 25 + .../ts/type/intersection_type.ts.snap.new | 50 + .../specs/ts/type/template_type.ts.snap.new | 32 + crates/rome_rowan/src/cursor/trivia.rs | 1 + crates/rome_rowan/src/syntax.rs | 3 +- crates/rome_rowan/src/syntax/trivia.rs | 1 + xtask/codegen/src/formatter.rs | 24 +- 951 files changed, 49465 insertions(+), 6248 deletions(-) create mode 100644 crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_function.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/arrow/currying.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/assignment/assignment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/binding/identifier_binding.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/class/class.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/class/class_comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/export/class_clause.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/export/from_clause.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/export/function_clause.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/export/variable_declaration.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/expression/binary_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/expression/conditional_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/expression/logical_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/expression/sequence_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/expression/static_member_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/import/bare_import.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/import/import_specifiers.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/interpreter.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/invalid/block_stmt_err.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/newlines.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/object/computed_member.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/object/object.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/object/object_comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/parentheses/parentheses.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/do_while.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/empty_blocks.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/for_in.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/for_of.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/if_chain.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/return.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/switch.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/throw.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/try_catch_finally.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/statement/while_loop.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/string/string.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/suppression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/module/template/template.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/js/script/with.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/jsx/self_closing.jsx.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-assignment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative-comment-after-minus.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-with-holes.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers2.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/arrow-call/arrow_call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/function.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/identifier.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/binaryish.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/chain.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring-heuristic.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-10218.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-1966.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-2482-1.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-7961.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-8218.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/assignment/sequence.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/async-do-expressions/async-do-expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/async/async-iteration.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/async/conditional-expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/async/parens.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/class-properties.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decimal.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decorators.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/function-sent.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/logical-assignment-operators.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/object-rest-spread.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/optional-catch-binding.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/partial-application.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-fsharp.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-minimal.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/record-tuple-record.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/v8intrinsic.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/arrow.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/bitwise-flags.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/equality.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/if.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-jsx.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-object-array.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/jsx_parent.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/math.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/return.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/binary_math/parens.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/bind-expressions/method_chain.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/class-comment/superclass.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/class-extends/complex.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/class-static-block/class-static-block.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/classes-private-fields/private_fields.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/classes/assignment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/classes/empty.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/classes/method.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/classes/property.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/closure-compiler-type-cast.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-in-the-middle.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-placement.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/iife.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-4124.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-8045.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/nested.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/object-with-comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/ways-to-specify-type.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments-pipeline-own-line/pipeline_own_line.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/assignment-pattern.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-block-comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-single-comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/break-continue-statements.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/class.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_for.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/emoji.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/export.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/jsdoc.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/jsx.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/multi-comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/preserve-new-line-last.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/switch.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/tagged-template-literal.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/template-literal.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/variable_declarator.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/comments/while.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/conditional/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-4.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-7.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/after_export.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/before_export.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/decorators/classes.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/decorators/mobx.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/decorators/multiple.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/decorators/redux.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/destructuring-ignore/ignore.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/destructuring/destructuring.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/directives/newline.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/directives/test.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/do/call-arguments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/do/do.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for-await/for-await.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for-of/async-identifier.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for/comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-1.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-2.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-without-blocks.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/for/for.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/object.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/functional_compose.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/ramda_compose.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/redux_compose.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/reselect_createselector.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/rxjs_pipe.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/generator/anonymous.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/generator/function-name-starts-with-get.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/if/comment_before_else.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/if/else.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/if/expr_and_same_line_comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/if/if_comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/if/trailing_comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ignore/issue-10661.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ignore/semi/directive.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/import-assertions/empty.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/import/empty-import.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/in/arrow-function.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/object.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/line-suffix-boundary/boundary.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/line/windows.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/literal/number.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/logical-assignment/logical-assignment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/logical_expressions/logical_expression_operators.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/member/logical.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-member.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-multiple.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/conditional.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/cypress.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/d3.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-11298.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3594.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3621.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/logical.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/pr-7889.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/simple-args.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/square_0.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/method-chain/test.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/module-blocks.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/range.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/worker.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-comments/comment-inside.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/colons-after-substitutions2.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-11797.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2636.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2883.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-5961.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-9072.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components-multiple-expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/var.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/escape.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/react-relay.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/html-template-literals.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/multiparser-invalid/text.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/new-expression/call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/no-semi-babylon-extensions/no-semi.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/no-semi/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/no-semi/issue2006.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/no-semi/no-semi.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/non-strict/keywords.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/object-prop-break-in/test.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/object-property-comment/after-key.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/object-property-ignore/ignore.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/object-property-ignore/issue-5678.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/objects/assignment-expression/object-value.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/objects/escape-sequence-key.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/objects/expand.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/objects/expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/objects/right-break.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/optional-chaining/chaining.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/optional-chaining/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/optional-chaining/eval.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/partial-application/test.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/performance/nested-real.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/pipeline-operator/fsharp_style_pipeline_operator.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/pipeline-operator/hack_pipeline_operator.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/pipeline-operator/minimal_pipeline_operator.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/member-chain.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/preserve-line/parameter-list.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/private-in/private-in.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/quotes/functions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/range/multiple-statements.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/range/multiple-statements2.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/record/computed.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/record/destructuring.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/record/record.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/record/spread.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/require-amd/require.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/require/require.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/return/binaryish.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/return/comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/spread/spread.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/strings/template-literals.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/switch/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/switch/empty_lines.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/switch/switch.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/tab-width/nested-functions.spec.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template-literals/css-prop.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template-literals/expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template-literals/styled-components-with-expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template-literals/styled-jsx-with-expressions.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template-literals/styled-jsx.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template/arrow.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template/call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template/faulty-locations.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template/inline.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/template/parenthesis.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/binary.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/indent-after-paren.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/indent.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/nested-in-condition.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/nested.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/parenthesis.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/ternaries/test.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_async.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_fakeAsync.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angular_waitForAsync.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/angularjs_inject.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/jest-each-template-string.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/jest-each.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/test-declarations/test_declarations.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/throw_expressions/throw_expression.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/binaryish.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/comment.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/throw_statement/jsx.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/function-calls.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/object.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/trailing-comma/trailing_whitespace.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/try/catch.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/try/empty.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/tuple/destructuring.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/tuple/tuple.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/unary-expression/comments.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/unary/series.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/unicode/combining-characters.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/v8_intrinsic/intrinsic_call.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/variable_declarator/multiple.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/while/indent.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/with/indent.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/js/yield/conditional.js.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/ambient/ambient.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/argument-expansion/argument_expansion.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/argument-expansion/arrow-with-return-type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/arrow_regression.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/comments.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/arrow/issue-6107-curry.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/as/as.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/as/assignment2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/as/long-identifiers.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/as/ternary.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/assert/index.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-10850.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-3122.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/assignment/issue-8619.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/cast/as-const.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/cast/generic-cast.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/cast/hug-args.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/cast/parenthesis.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/catch-clause/type-annotation.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class-comment/generic.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/abstract-method.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/constructor.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/empty-method-body.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/extends_implements.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/generics.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/methods.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/class/optional.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/classes/break-heritage.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/classes/break.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments-2/last-arg.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/declare_function.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/jsx.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/location.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/mapped_types.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/method_types.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/type-parameters.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/comments/union.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/anyIsAssignableToObject.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/castParentheses.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/castTest.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/declareDottedModuleName.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/decrementAndIncrementOperators.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/globalIsContextualKeyword.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/indexSignatureWithInitializer.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/compiler/mappedTypeWithCombinedTypeMappers.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conditional-types/comments.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conditional-types/conditonal-types.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conditional-types/infer-type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conditional-types/nested-in-condition.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/ambient/ambientDeclarations.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAsIdentifier.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAssignabilityConstructorFunction.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractClinterfaceAssignability.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractConstructorAssignability.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractCrashedOnce.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractExtends.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractFactoryFunction.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractGeneric.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractImportInstantiation.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInAModule.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInheritance.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations1.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractInstantiations2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractOverloads.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractOverrideWithAbstract.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractSingleLineDecl.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractSuperCalls.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractUsingAbstractMethod1.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractUsingAbstractMethods2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classHeritageSpecification/classAppearsToHaveMembersOfObject.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingClass.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classDeclarations/classHeritageSpecification/classIsSubtypeOfBaseType.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/classExpression.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorDefaultValuesReferencingThis.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorImplementationWithDefaultValues.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorImplementationWithDefaultValues2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorOverloadsWithDefaultValues.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorOverloadsWithOptionalParameters.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/constructorDeclarations/constructorParameters/readonlyInConstructorParameters.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/mixinAccessModifiers.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/mixinClassesAnnotated.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/mixinClassesAnonymous.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/mixinClassesMembers.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/classes/nestedClassDeclaration.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/es6/Symbols/symbolProperty15.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/expressions/functionCalls/callWithSpreadES6.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/interfaces/interfaceDeclarations/interfaceWithMultipleBaseTypes2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/internalModules/importDeclarations/circularImportAlias.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/internalModules/importDeclarations/exportImportAlias.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/internalModules/importDeclarations/importAliasIdentifiers.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/internalModules/importDeclarations/shadowedInternalModule.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/ambient/ambientDeclarations.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/functions/functionOverloadErrorsSyntax.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/functions/functionTypeTypeParameters.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/functions/parameterInitializersForwardReferencing.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/interfaceDeclaration/interfaceDeclaration.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/intersectionType/intersectionType.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/moduleDeclaration/moduleDeclaration.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/tuple/contextualTypeWithTuple.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/tuple/indexerWithTuple.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/tuple/typeInferenceWithTupleType.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/tuple/wideningTuples1.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/tuple/wideningTuples3.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/tuple/wideningTuples4.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/typeParameters/typeParameterLists/staticMembersUsingClassTypeParameter.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/union/unionTypeCallSignatures3.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/union/unionTypeCallSignatures4.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/union/unionTypeEquivalence.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/conformance/types/union/unionTypePropertyAccessibility.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/abstract/abstractNewlineHandling.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/call/callSignature.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/computedProperties/string.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/computedProperties/symbol.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/declare/declareModifier.d.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/modifiers/minustoken.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/module/moduleNamespace.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/module/nestedNamespace.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/new/newKeyword.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/custom/stability/moduleBlock.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/declare/declare_enum.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/declare/declare_function.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/declare/declare_interface.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/declare/declare_var.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/decorators/decorator-type-assertion.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/decorators/decorators-comments.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/decorators/decorators.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/decorators/inline-decorators.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/definite/definite.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/destructuring/destructuring.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/enum/enum.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/enum/multiline.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/error-recovery/generic.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/error-recovery/index-signature.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/export/export.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/function-type/single-parameter.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/function/single_expand.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/functional-composition/pipe-function-calls-with-comments.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/generic/arrow-return-type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/generic/issue-6899.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/import-export/type-modifier.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/import-require/type-imports.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/import-type/import-type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface/generic.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface/ignore.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface/long-extends.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface/pattern-parameters.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface/separator.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface2/break.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/interface2/comments.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/key-remapping-in-mapped-types/key-remapping.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/keywords/keywords-2.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/keywords/keywords.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/keywords/module.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/method/issue-10352-consistency.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/method/method-signature-with-wrapped-return-type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/method/method-signature.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/method/semi.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/module/keyword.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/multiparser-css/issue-6259.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/new/new-signature.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/non-null/braces.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/non-null/member-chain.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/non-null/optional-chain.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/non-null/parens.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/optional-method/optional-method.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/prettier-ignore/mapped-types.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/rest-type/infer-type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/ternaries/indent.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/tsx/generic-component.tsx.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/tsx/react.tsx.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/tsx/type-parameters.tsx.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/tsx/url.tsx.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/tuple/trailing-comma-for-empty-tuples.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/tuple/tuple-labeled.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/type-alias/issue-100857.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/type-alias/pattern-parameter.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/type-member-get-set/type-member-get-set.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/typeparams/class-method.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/typeparams/long-function-arg.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/union/comments.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/union/inlining.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/prettier/typescript/webhost/webtsc.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/assignment/as_assignment.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/assignment/type_assertion_assignment.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/class/constructor_parameter.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/class/implements_clause.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/declaration/class.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/declaration/declare_function.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/declaration/interface.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/expression/type_expression.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/expression/type_member.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/module/export_clause.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/module/external_module_reference.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/module/module_declaration.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/statement/empty_block.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/statement/enum_statement.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/type/conditional.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/type/import_type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/type/intersection_type.ts.snap.new create mode 100644 crates/rome_js_formatter/tests/specs/ts/type/template_type.ts.snap.new diff --git a/Cargo.lock b/Cargo.lock index ad068c3e8fe..642255ed340 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1370,6 +1370,7 @@ name = "rome_formatter" version = "0.1.0" dependencies = [ "cfg-if", + "drop_bomb", "rome_rowan", "tracing", ] diff --git a/crates/rome_formatter/Cargo.toml b/crates/rome_formatter/Cargo.toml index b62b00741d2..c30312aacc1 100644 --- a/crates/rome_formatter/Cargo.toml +++ b/crates/rome_formatter/Cargo.toml @@ -9,3 +9,4 @@ edition = "2021" rome_rowan = { path = "../rome_rowan" } tracing = { version = "0.1.31", default-features = false, features = ["std"] } cfg-if = "1.0.0" +drop_bomb = "0.1.5" diff --git a/crates/rome_formatter/src/buffer.rs b/crates/rome_formatter/src/buffer.rs index c0f0047e66a..1dfb8e2150d 100644 --- a/crates/rome_formatter/src/buffer.rs +++ b/crates/rome_formatter/src/buffer.rs @@ -1,5 +1,6 @@ use super::{write, Arguments, FormatElement}; use crate::format_element::List; +use crate::formatter::FormatState; use crate::group_id::UniqueGroupIdBuilder; #[cfg(debug_assertions)] use crate::printed_tokens::PrintedTokens; @@ -12,7 +13,7 @@ use std::ops::{Deref, DerefMut}; pub trait Buffer { type Context; - fn write_element(&mut self, element: FormatElement) -> FormatResult<()>; + fn write_element(&mut self, element: FormatElement); fn write_fmt(mut self: &mut Self, arguments: &Arguments) -> FormatResult<()> { write(&mut self, arguments) @@ -21,78 +22,45 @@ pub trait Buffer { fn state(&self) -> &FormatState; fn state_mut(&mut self) -> &mut FormatState; -} - -#[derive(Default)] -pub struct FormatState { - context: Context, - group_id_builder: UniqueGroupIdBuilder, - // This is using a RefCell as it only exists in debug mode, - // the Formatter is still completely immutable in release builds - #[cfg(debug_assertions)] - pub printed_tokens: PrintedTokens, -} -impl fmt::Debug for FormatState -where - Context: Debug, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("FormatContext") - .field("options", &self.context) - .finish() - } + /// Takes a snapshot of the Buffers state, excluding the formatter state. + fn snapshot(&mut self) -> BufferSnapshotId; + + /// Restores the snapshot with the given id. + /// + /// ## Panics + /// If the passed snapshot id is a snapshot of another buffer OR + /// if the snapshot is restored out of order + fn restore_snapshot(&mut self, snapshot: BufferSnapshotId); + + /// Releases the snapshot with the given id + /// + /// ## Panics + /// If the passed snapshot id is a snapshot of another buffer OR + /// If the snapshot is restored out of order. + fn release_snapshot(&mut self, snapshot: BufferSnapshotId); } -impl FormatState { - pub fn new(context: Context) -> Self { - Self { - context, - group_id_builder: Default::default(), - #[cfg(debug_assertions)] - printed_tokens: Default::default(), - } - } - - /// Returns the [FormatContext] specifying how to format the current CST - pub fn context(&self) -> &Context { - &self.context - } - - /// Creates a new group id that is unique to this document. The passed debug name is used in the - /// [std::fmt::Debug] of the document if this is a debug build. - /// The name is unused for production builds and has no meaning on the equality of two group ids. - pub fn group_id(&self, debug_name: &'static str) -> GroupId { - self.group_id_builder.group_id(debug_name) - } +/// Id of a buffer snapshot. What the meaning of the inner value is depends on the [Buffer] implementation. +/// It can either be an index into a local store with all taken snapshots that stores additional values +/// or it may be the length of the internal [FormatElement] buffer. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct BufferSnapshotId(usize); - /// Tracks the given token as formatted - #[inline] - pub fn track_token(&mut self, #[allow(unused_variables)] token: &SyntaxToken) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - self.printed_tokens.track_token(token); - } - } +impl BufferSnapshotId { + pub const fn new(id: usize) -> Self { + Self(id) } - #[inline] - pub fn assert_formatted_all_tokens( - &self, - #[allow(unused_variables)] root: &SyntaxNode, - ) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - self.printed_tokens.assert_all_tracked(root); - } - } + pub const fn value(&self) -> usize { + self.0 } } impl + ?Sized, Context> Buffer for &mut W { type Context = Context; - fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + fn write_element(&mut self, element: FormatElement) { (**self).write_element(element) } @@ -107,26 +75,38 @@ impl + ?Sized, Context> Buffer for &mut W { fn state_mut(&mut self) -> &mut FormatState { (**self).state_mut() } + + fn snapshot(&mut self) -> BufferSnapshotId { + (**self).snapshot() + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshotId) { + (**self).restore_snapshot(snapshot) + } + + fn release_snapshot(&mut self, snapshot: BufferSnapshotId) { + (**self).release_snapshot(snapshot) + } } // TODO use Smallvec internally #[derive(Debug)] pub struct VecBuffer<'a, Context> { - context: &'a mut FormatState, + state: &'a mut FormatState, elements: Vec, } impl<'a, Context> VecBuffer<'a, Context> { - pub fn new(context: &'a mut FormatState) -> Self { + pub fn new(state: &'a mut FormatState) -> Self { Self { - context, + state, elements: vec![], } } pub fn with_capacity(capacity: usize, context: &'a mut FormatState) -> Self { Self { - context, + state: context, elements: Vec::with_capacity(capacity), } } @@ -137,7 +117,7 @@ impl<'a, Context> VecBuffer<'a, Context> { buffer: &mut dyn Buffer, ) -> super::FormatResult<()> { for element in self.drain(..) { - buffer.write_element(element)?; + buffer.write_element(element); } Ok(()) @@ -147,6 +127,15 @@ impl<'a, Context> VecBuffer<'a, Context> { Document(self.elements) } + pub fn into_element(mut self) -> FormatElement { + if self.len() == 1 { + // Safety: Guaranteed by len check above + self.elements.pop().unwrap() + } else { + FormatElement::List(List::new(self.elements)) + } + } + pub fn into_vec(self) -> Vec { self.elements } @@ -169,7 +158,7 @@ impl DerefMut for VecBuffer<'_, Context> { impl Buffer for VecBuffer<'_, Context> { type Context = Context; - fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + fn write_element(&mut self, element: FormatElement) { match element { FormatElement::List(list) => { if self.elements.is_empty() { @@ -178,18 +167,30 @@ impl Buffer for VecBuffer<'_, Context> { self.elements.extend(list.into_vec()) } } - FormatElement::Empty => {} element => self.elements.push(element), } - Ok(()) } fn state(&self) -> &FormatState { - self.context + self.state } fn state_mut(&mut self) -> &mut FormatState { - &mut self.context + &mut self.state + } + + fn snapshot(&mut self) -> BufferSnapshotId { + BufferSnapshotId::new(self.elements.len()) + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshotId) { + assert!(self.elements.len() >= snapshot.value()); + + self.elements.truncate(snapshot.value()) + } + + fn release_snapshot(&mut self, snapshot: BufferSnapshotId) { + assert!(self.elements.len() >= snapshot.value()); } } @@ -202,9 +203,7 @@ impl Document { } pub fn into_element(mut self) -> FormatElement { - if self.is_empty() { - FormatElement::Empty - } else if self.0.len() == 1 { + if self.0.len() == 1 { self.0.pop().unwrap() } else { FormatElement::List(List::new(self.0)) diff --git a/crates/rome_formatter/src/builders.rs b/crates/rome_formatter/src/builders.rs index 9bbf86c0ab4..171541b304a 100644 --- a/crates/rome_formatter/src/builders.rs +++ b/crates/rome_formatter/src/builders.rs @@ -1,15 +1,18 @@ use crate::prelude::*; -use crate::{write, GroupId, TextRange, TextSize}; +use crate::{write, FormatWithRule, GroupId, TextRange, TextSize}; use crate::{Buffer, VecBuffer}; -use rome_rowan::{Language, SyntaxToken, SyntaxTokenText, TextLen}; +use rome_rowan::{ + AstNode, AstSeparatedList, Language, SyntaxNode, SyntaxResult, SyntaxToken, SyntaxTokenText, + TextLen, +}; use std::borrow::Cow; +use std::cell::Cell; use std::marker::PhantomData; /// Format element that doesn't represent any content. /// /// Can be helpful if you need to return a `FormatElement` (e.g. in an else branch) but don't want /// to show any content. -#[deprecated] pub const fn empty_element() -> Empty { Empty } @@ -197,7 +200,8 @@ impl Line { impl Format for Line { fn format(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Line(self.mode)) + f.write_element(FormatElement::Line(self.mode)); + Ok(()) } } @@ -248,7 +252,8 @@ pub struct StaticToken { impl Format for StaticToken { fn format(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Token(Token::Static { text: self.text })) + f.write_element(FormatElement::Token(Token::Static { text: self.text })); + Ok(()) } } @@ -270,7 +275,8 @@ impl Format for DynamicToken<'_> { f.write_element(FormatElement::Token(Token::Dynamic { text: self.text.to_string().into_boxed_str(), source_position: self.position, - })) + })); + Ok(()) } } @@ -313,7 +319,9 @@ impl Format for SyntaxTokenCowSlice<'_, L> { text: text.to_string().into_boxed_str(), source_position: self.start, })), - } + }; + + Ok(()) } } @@ -342,7 +350,9 @@ impl Format for SyntaxTokenTextSlice { f.write_element(FormatElement::Token(Token::SyntaxTokenSlice { slice: self.text.clone(), source_position: self.source_position, - })) + })); + + Ok(()) } } @@ -385,7 +395,8 @@ impl Format for LineSuffix<'_, O> { write!(buffer, [self.content])?; let content = buffer.into_document().into_element(); - f.write_element(FormatElement::LineSuffix(Box::new(content))) + f.write_element(FormatElement::LineSuffix(Box::new(content))); + Ok(()) } } @@ -421,7 +432,8 @@ pub struct LineSuffixBoundary; impl Format for LineSuffixBoundary { fn format(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::LineSuffixBoundary) + f.write_element(FormatElement::LineSuffixBoundary); + Ok(()) } } @@ -470,7 +482,8 @@ impl Format for Comment<'_, O> { write!(buffer, [self.content])?; let content = buffer.into_document().into_element(); - f.write_element(FormatElement::Comment(Box::new(content))) + f.write_element(FormatElement::Comment(Box::new(content))); + Ok(()) } } @@ -497,7 +510,8 @@ pub struct Space; impl Format for Space { fn format(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Space) + f.write_element(FormatElement::Space); + Ok(()) } } @@ -553,7 +567,8 @@ impl Format for Indent<'_, O> { } let content = buffer.into_document().into_element(); - f.write_element(FormatElement::Indent(Box::new(content))) + f.write_element(FormatElement::Indent(Box::new(content))); + Ok(()) } } @@ -761,7 +776,7 @@ impl Format for BlockIndent<'_, O> { let content = buffer.into_document().into_element(); - f.write_element(FormatElement::Indent(Box::new(content)))?; + f.write_element(FormatElement::Indent(Box::new(content))); match self.mode { IndentMode::Soft => write!(f, [soft_line_break()])?, @@ -879,12 +894,12 @@ impl Format for GroupElements<'_, O> { let group = Group::new(content).with_id(self.options.group_id); if !leading.is_empty() { - f.write_element(leading)?; + f.write_element(leading); } - f.write_element(FormatElement::Group(group))?; + f.write_element(FormatElement::Group(group)); if !trailing.is_empty() { - f.write_element(trailing)?; + f.write_element(trailing); } Ok(()) @@ -933,7 +948,8 @@ pub struct ExpandParent; impl Format for ExpandParent { fn format(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::ExpandParent) + f.write_element(FormatElement::ExpandParent); + Ok(()) } } @@ -1185,7 +1201,8 @@ impl Format for IfGroupBreaks<'_, O> { let content = buffer.into_document().into_element(); f.write_element(FormatElement::ConditionalGroupContent( ConditionalGroupContent::new(content, self.mode).with_group_id(self.group_id), - )) + )); + Ok(()) } } @@ -1247,6 +1264,78 @@ impl<'fmt, 'joiner, 'buf, O> JoinBuilder<'fmt, 'joiner, 'buf, O> { } } +pub struct JoinNodesBuilder<'fmt, 'buf, Sep, O> { + result: super::FormatResult<()>, + separator: Sep, + fmt: &'fmt mut Formatter<'buf, O>, + has_elements: bool, +} + +impl<'fmt, 'buf, Sep, O> JoinNodesBuilder<'fmt, 'buf, Sep, O> +where + Sep: Format, +{ + pub(super) fn new(separator: Sep, fmt: &'fmt mut Formatter<'buf, O>) -> Self { + Self { + result: Ok(()), + separator, + fmt, + has_elements: false, + } + } + + pub fn entry(&mut self, node: &SyntaxNode, content: &dyn Format) { + self.result = self.result.and_then(|_| { + if self.has_elements { + if get_lines_before(node) > 1 { + write!(self.fmt, [empty_line()])?; + } else { + write!(self.fmt, [&self.separator])?; + } + } + + self.has_elements = true; + + write!(self.fmt, [content]) + }); + } + + pub fn entries(&mut self, entries: I) -> &mut Self + where + L: Language, + F: Format, + I: IntoIterator)>, + { + for (content, node) in entries { + self.entry(&node, &content) + } + + self + } + + pub fn finish(&mut self) -> FormatResult<()> { + self.result + } +} + +/// Get the number of line breaks between two consecutive SyntaxNodes in the tree +pub fn get_lines_before(next_node: &SyntaxNode) -> usize { + // Count the newlines in the leading trivia of the next node + if let Some(leading_trivia) = next_node.first_leading_trivia() { + leading_trivia + .pieces() + .take_while(|piece| { + // Stop at the first comment piece, the comment printer + // will handle newlines between the comment and the node + !piece.is_comments() + }) + .filter(|piece| piece.is_newline()) + .count() + } else { + 0 + } +} + pub struct FillBuilder<'fmt, 'separator, 'buf, O> { result: FormatResult<()>, fmt: &'fmt mut Formatter<'buf, O>, @@ -1302,15 +1391,43 @@ impl<'a, 'separator, 'buf, O> FillBuilder<'a, 'separator, 'buf, O> { match items.len() { 0 => Ok(()), - 1 => self.fmt.write_element(items.pop().unwrap()), - _ => self - .fmt - .write_element(FormatElement::Fill(List::new(items))), + 1 => { + self.fmt.write_element(items.pop().unwrap()); + Ok(()) + } + _ => { + self.fmt + .write_element(FormatElement::Fill(List::new(items))); + Ok(()) + } } }) } } +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum TrailingSeparator { + Allowed, + Disallowed, + Mandatory, +} + +impl TrailingSeparator { + pub fn is_allowed(&self) -> bool { + matches!(self, TrailingSeparator::Allowed) + } + pub fn is_mandatory(&self) -> bool { + matches!(self, TrailingSeparator::Mandatory) + } +} + +impl Default for TrailingSeparator { + fn default() -> Self { + TrailingSeparator::Allowed + } +} + +#[derive(Copy, Clone)] pub struct FormatWith where T: Fn(&mut Formatter) -> FormatResult<()>, @@ -1338,6 +1455,32 @@ where } } +pub const fn format_once(closure: T) -> FormatOnce +where + T: FnOnce(&mut Formatter) -> FormatResult<()>, +{ + FormatOnce { + closure: Cell::new(Some(closure)), + options: PhantomData, + } +} + +pub struct FormatOnce { + closure: Cell>, + options: PhantomData, +} + +impl Format for FormatOnce +where + T: FnOnce(&mut Formatter) -> FormatResult<()>, +{ + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let closure = self.closure.take().expect("Tried to format once at least twice. This is not allowed. You may want to use format_with or .memoized instead"); + + (closure)(f) + } +} + #[derive(Default)] pub struct ConcatBuilder { elements: Vec, @@ -1395,9 +1538,7 @@ impl ConcatBuilder { #[inline] pub fn finish(mut self) -> FormatElement { - if self.elements.is_empty() { - FormatElement::Empty - } else if self.elements.len() == 1 { + if self.elements.len() == 1 { // Safety: Guaranteed to succeed by the length check above self.elements.pop().unwrap() } else { diff --git a/crates/rome_formatter/src/format_element.rs b/crates/rome_formatter/src/format_element.rs index bb13e17ed15..923988e51fb 100644 --- a/crates/rome_formatter/src/format_element.rs +++ b/crates/rome_formatter/src/format_element.rs @@ -24,82 +24,12 @@ where builder.finish() } -// -// /// Specialized version of [join_elements] for joining SyntaxNodes separated by a space, soft -// /// line break or empty line depending on the input file. -// /// -// /// This functions inspects the input source and separates consecutive elements with either -// /// a [soft_line_break_or_space] or [empty_line] depending on how many line breaks were -// /// separating the elements in the original file. -// #[inline] -// pub fn join_elements_soft_line(elements: I) -> FormatElement -// where -// I: IntoIterator, FormatElement)>, -// L: Language, -// { -// join_elements_with(elements, soft_line_break_or_space) -// } -// -// /// Specialized version of [join_elements] for joining SyntaxNodes separated by one or more -// /// line breaks depending on the input file. -// /// -// /// This functions inspects the input source and separates consecutive elements with either -// /// a [hard_line_break] or [empty_line] depending on how many line breaks were separating the -// /// elements in the original file. -// #[inline] -// pub fn join_elements_hard_line(elements: I) -> FormatElement -// where -// I: IntoIterator, FormatElement)>, -// L: Language, -// { -// join_elements_with(elements, hard_line_break) -// } -// -// /// Get the number of line breaks between two consecutive SyntaxNodes in the tree -// pub fn get_lines_before(next_node: &SyntaxNode) -> usize { -// // Count the newlines in the leading trivia of the next node -// if let Some(leading_trivia) = next_node.first_leading_trivia() { -// leading_trivia -// .pieces() -// .take_while(|piece| { -// // Stop at the first comment piece, the comment printer -// // will handle newlines between the comment and the node -// !piece.is_comments() -// }) -// .filter(|piece| piece.is_newline()) -// .count() -// } else { -// 0 -// } -// } -// -// #[inline] -// pub fn join_elements_with(elements: I, separator: fn() -> FormatElement) -> FormatElement -// where -// I: IntoIterator, FormatElement)>, -// L: Language, -// { -// concat_elements(IntersperseFn::new( -// elements.into_iter(), -// |_, next_node, next_elem| { -// if next_elem.is_empty() { -// empty_element() -// } else if get_lines_before(next_node) > 1 { -// empty_line() -// } else { -// separator() -// } -// }, -// )) -// } /// Language agnostic IR for formatting source code. /// /// Use the helper functions like [crate::space_token], [crate::soft_line_break] etc. defined in this file to create elements. #[derive(Clone, Eq, PartialEq)] pub enum FormatElement { - Empty, - /// A space token, see [crate::space_token] for documentation. Space, @@ -153,7 +83,7 @@ pub enum FormatElement { BestFitting(BestFitting), } -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum VerbatimKind { Unknown, Suppressed, @@ -202,7 +132,6 @@ impl Verbatim { impl Debug for FormatElement { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { match self { - FormatElement::Empty => write!(fmt, "Empty"), FormatElement::Space => write!(fmt, "Space"), FormatElement::Line(content) => content.fmt(fmt), FormatElement::Indent(content) => fmt.debug_tuple("Indent").field(content).finish(), @@ -251,7 +180,7 @@ pub enum LineMode { } /// A token used to gather a list of elements; see [concat_elements] and [join_elements]. -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Default, Eq, PartialEq)] pub struct List { content: Vec, } @@ -516,19 +445,6 @@ pub fn normalize_newlines(text: &str, terminators: [char; N]) -> } } -// TODO -// Consider making `Format` `Options` not an associated type? -// impl From> for Token { -// fn from(trivia: SyntaxTriviaPieceComments) -> Self { -// let range = trivia.text_range(); -// Token::from_syntax_token_cow_slice( -// normalize_newlines(trivia.text().trim(), LINE_TERMINATORS), -// &trivia.as_piece().token(), -// range.start(), -// ) -// } -// } - impl Deref for Token { type Target = str; fn deref(&self) -> &Self::Target { @@ -544,8 +460,11 @@ impl Deref for Token { impl FormatElement { /// Returns true if the element contains no content. - pub const fn is_empty(&self) -> bool { - matches!(self, FormatElement::Empty) + pub fn is_empty(&self) -> bool { + match self { + FormatElement::List(list) => list.is_empty(), + _ => false, + } } /// Returns true if this [FormatElement] is guaranteed to break across multiple lines by the printer. @@ -557,7 +476,6 @@ impl FormatElement { /// lines if this element is part of a group and the group doesn't fit on a single line. pub fn will_break(&self) -> bool { match self { - FormatElement::Empty => false, FormatElement::Space => false, FormatElement::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty), FormatElement::Indent(content) => content.will_break(), @@ -597,7 +515,7 @@ impl FormatElement { (FormatElement::List(list), content) } else { // No leading trivia - (FormatElement::Empty, list.content) + (FormatElement::List(List::default()), list.content) }; let content_end = content @@ -609,7 +527,7 @@ impl FormatElement { let trailing = if trailing_start < content.len() { FormatElement::List(List::new(content.split_off(trailing_start))) } else { - FormatElement::Empty + FormatElement::List(List::default()) }; (leading, FormatElement::List(List::new(content)), trailing) @@ -617,13 +535,17 @@ impl FormatElement { // All leading trivia ( FormatElement::List(list), - FormatElement::Empty, - FormatElement::Empty, + FormatElement::List(List::default()), + FormatElement::List(List::default()), ) } } // Non-list elements are returned directly - _ => (FormatElement::Empty, self, FormatElement::Empty), + _ => ( + FormatElement::List(List::default()), + self, + FormatElement::List(List::default()), + ), } } @@ -636,7 +558,7 @@ impl FormatElement { list.iter().rev().find_map(|element| element.last_element()) } - FormatElement::Empty | FormatElement::Line(_) | FormatElement::Comment(_) => None, + FormatElement::Line(_) | FormatElement::Comment(_) => None, FormatElement::Indent(indent) => indent.last_element(), FormatElement::Group(group) => group.content.last_element(), @@ -670,12 +592,6 @@ impl From for FormatElement { } } -impl From> for FormatElement { - fn from(element: Option) -> Self { - element.unwrap_or_else(|| FormatElement::Empty) - } -} - #[cfg(test)] mod tests { diff --git a/crates/rome_formatter/src/format_extensions.rs b/crates/rome_formatter/src/format_extensions.rs index 9b62f481472..086ee5e77cc 100644 --- a/crates/rome_formatter/src/format_extensions.rs +++ b/crates/rome_formatter/src/format_extensions.rs @@ -17,7 +17,7 @@ pub trait FormatOptional { /// ## Examples /// /// ``` - /// use rome_formatter::{FormatContext, write, format}; + /// use rome_formatter::{write, format}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// @@ -35,7 +35,7 @@ pub trait FormatOptional { /// none_token.with_or_empty(|token, f| write!(f, [token])) /// ]).unwrap(); /// - /// assert_eq!(FormatElement::Empty, none_formatted.into_format_element()); + /// assert!(none_formatted.into_format_element().is_empty()); /// /// let some_token = Some(MyFormat); /// assert_eq!( @@ -356,7 +356,7 @@ where return match memory { Ok(elements) => { for element in elements { - f.write_element(element.clone())?; + f.write_element(element.clone()); } Ok(()) @@ -372,7 +372,7 @@ where Ok(_) => { let elements = buffer.into_vec(); for element in &elements { - f.write_element(element.clone())?; + f.write_element(element.clone()); } *self.memory.borrow_mut() = Some(Ok(elements)); diff --git a/crates/rome_formatter/src/formatter.rs b/crates/rome_formatter/src/formatter.rs index 11086f0313d..6458e624112 100644 --- a/crates/rome_formatter/src/formatter.rs +++ b/crates/rome_formatter/src/formatter.rs @@ -1,9 +1,13 @@ +use crate::buffer::BufferSnapshotId; use crate::builders::{FillBuilder, JoinBuilder}; +use crate::group_id::UniqueGroupIdBuilder; use crate::prelude::*; #[cfg(debug_assertions)] use crate::printed_tokens::PrintedTokens; -use crate::{Arguments, Buffer, FormatContext, FormatState, GroupId}; +use crate::{Arguments, Buffer, GroupId}; +use drop_bomb::DebugDropBomb; use rome_rowan::{Language, SyntaxNode, SyntaxToken}; +use std::fmt; /// Handles the formatting of a CST and stores the options how the CST should be formatted (user preferences). /// The formatter is passed to the [Format] implementation of every node in the CST so that they @@ -88,6 +92,28 @@ impl<'buf, Context> Formatter<'buf, Context> { JoinBuilder::with(self, joiner) } + /// Specialized version of [join_with] for joining SyntaxNodes separated by a space, soft + /// line break or empty line depending on the input file. + /// + /// This functions inspects the input source and separates consecutive elements with either + /// a [soft_line_break_or_space] or [empty_line] depending on how many line breaks were + /// separating the elements in the original file. + pub fn join_nodes_with_soft_line<'a>( + &'a mut self, + ) -> JoinNodesBuilder<'a, 'buf, Line, Context> { + JoinNodesBuilder::new(soft_line_break_or_space(), self) + } + + /// Specialized version of [join_elements] for joining SyntaxNodes separated by one or more + /// line breaks depending on the input file. + /// + /// This functions inspects the input source and separates consecutive elements with either + /// a [hard_line_break] or [empty_line] depending on how many line breaks were separating the + /// elements in the original file. + pub fn join_nodes_with_hardline<'a>(&'a mut self) -> JoinNodesBuilder<'a, 'buf, Line, Context> { + JoinNodesBuilder::new(hard_line_break(), self) + } + /// Concatenates a list of [FormatElement]s with spaces and line breaks to fit /// them on as few lines as possible. Each element introduces a conceptual group. The printer /// first tries to print the item in flat mode but then prints it in expanded mode if it doesn't fit. @@ -121,32 +147,40 @@ impl<'buf, Context> Formatter<'buf, Context> { } impl Formatter<'_, Options> { - // TODO - - // /// Take a snapshot of the state of the formatter - // #[inline] - // pub fn snapshot(&self) -> FormatterSnapshot { - // FormatterSnapshot { - // #[cfg(debug_assertions)] - // printed_tokens: self.printed_tokens.borrow().clone(), - // } - // } - // - // #[inline] - // /// Restore the state of the formatter to a previous snapshot - // pub fn restore(&self, #[allow(unused)] snapshot: FormatterSnapshot) { - // cfg_if::cfg_if! { - // if #[cfg(debug_assertions)] { - // *self.printed_tokens.borrow_mut() = snapshot.printed_tokens; - // } - // } - // } + /// Take a snapshot of the state of the formatter + #[inline] + + pub fn snapshot(&mut self) -> FormatterSnapshot { + FormatterSnapshot { + buffer: self.buffer.snapshot(), + bomb: DebugDropBomb::new("Snapshot must either be 'released' or restored'."), + #[cfg(debug_assertions)] + printed_tokens: self.state().printed_tokens.clone(), + } + } + + #[inline] + /// Restore the state of the formatter to a previous snapshot + pub fn restore_snapshot(&mut self, mut snapshot: FormatterSnapshot) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.state_mut().printed_tokens = snapshot.printed_tokens; + } + } + snapshot.bomb.defuse(); + self.buffer.restore_snapshot(snapshot.buffer) + } + + pub fn release_snapshot(&mut self, mut snapshot: FormatterSnapshot) { + snapshot.bomb.defuse(); + self.buffer.release_snapshot(snapshot.buffer) + } } impl Buffer for Formatter<'_, O> { type Context = O; - fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + fn write_element(&mut self, element: FormatElement) { self.buffer.write_element(element) } @@ -164,6 +198,84 @@ impl Buffer for Formatter<'_, O> { fn state_mut(&mut self) -> &mut FormatState { self.buffer.state_mut() } + + fn snapshot(&mut self) -> BufferSnapshotId { + self.buffer.snapshot() + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshotId) { + self.buffer.restore_snapshot(snapshot) + } + + fn release_snapshot(&mut self, snapshot: BufferSnapshotId) { + self.buffer.release_snapshot(snapshot) + } +} + +#[derive(Default)] +pub struct FormatState { + options: O, + group_id_builder: UniqueGroupIdBuilder, + // This is using a RefCell as it only exists in debug mode, + // the Formatter is still completely immutable in release builds + #[cfg(debug_assertions)] + pub printed_tokens: PrintedTokens, +} + +impl fmt::Debug for FormatState +where + O: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("FormatContext") + .field("options", &self.options) + .finish() + } +} + +impl FormatState { + pub fn new(options: O) -> Self { + Self { + options, + group_id_builder: Default::default(), + #[cfg(debug_assertions)] + printed_tokens: Default::default(), + } + } + + /// Returns the [FormatOptions] specifying how to format the current CST + pub fn context(&self) -> &O { + &self.options + } + + /// Creates a new group id that is unique to this document. The passed debug name is used in the + /// [std::fmt::Debug] of the document if this is a debug build. + /// The name is unused for production builds and has no meaning on the equality of two group ids. + pub fn group_id(&self, debug_name: &'static str) -> GroupId { + self.group_id_builder.group_id(debug_name) + } + + /// Tracks the given token as formatted + #[inline] + pub fn track_token(&mut self, #[allow(unused_variables)] token: &SyntaxToken) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.printed_tokens.track_token(token); + } + } + } + + #[inline] + pub fn assert_formatted_all_tokens( + &self, + #[allow(unused_variables)] root: &SyntaxNode, + ) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.printed_tokens.assert_all_tracked(root); + } + } + } } /// Snapshot of the formatter state used to handle backtracking if @@ -172,7 +284,10 @@ impl Buffer for Formatter<'_, O> { /// /// In practice this only saves the set of printed tokens in debug /// mode and compiled to nothing in release mode +#[must_use = "Snapshot must either be 'released' or 'restored'."] pub struct FormatterSnapshot { + buffer: BufferSnapshotId, + bomb: DebugDropBomb, #[cfg(debug_assertions)] printed_tokens: PrintedTokens, } diff --git a/crates/rome_formatter/src/lib.rs b/crates/rome_formatter/src/lib.rs index 80910b62aa7..372871c54d9 100644 --- a/crates/rome_formatter/src/lib.rs +++ b/crates/rome_formatter/src/lib.rs @@ -37,10 +37,11 @@ pub mod prelude; pub mod printed_tokens; pub mod printer; -use crate::formatter::Formatter; +use crate::formatter::{FormatState, Formatter}; +use crate::prelude::syntax_token_cow_slice; use crate::printer::{Printer, PrinterOptions}; pub use arguments::{Argument, Arguments}; -pub use buffer::{Buffer, FormatState, VecBuffer}; +pub use buffer::{Buffer, VecBuffer}; pub use builders::{ block_indent, comment, empty_element, empty_line, group_elements, group_elements_with_options, hard_line_break, if_group_breaks, if_group_fits_on_single_line, if_group_with_id_breaks, @@ -52,8 +53,8 @@ pub use format_element::{ }; pub use group_id::GroupId; use rome_rowan::{ - Language, SyntaxElement, SyntaxError, SyntaxNode, SyntaxResult, TextRange, TextSize, - TokenAtOffset, + Language, SyntaxElement, SyntaxError, SyntaxNode, SyntaxResult, SyntaxTriviaPieceComments, + TextRange, TextSize, TokenAtOffset, }; use std::error::Error; use std::fmt; @@ -974,3 +975,18 @@ pub fn format_sub_tree< verbatim_ranges, )) } + +impl Format for SyntaxTriviaPieceComments { + fn format(&self, f: &mut Formatter) -> FormatResult<()> { + let range = self.text_range(); + + write!( + f, + [syntax_token_cow_slice( + normalize_newlines(self.text().trim(), LINE_TERMINATORS), + &self.as_piece().token(), + range.start() + )] + ) + } +} diff --git a/crates/rome_formatter/src/macros.rs b/crates/rome_formatter/src/macros.rs index 9ed9bc6e0eb..69543ff4111 100644 --- a/crates/rome_formatter/src/macros.rs +++ b/crates/rome_formatter/src/macros.rs @@ -232,7 +232,7 @@ macro_rules! best_fitting { #[cfg(test)] mod tests { use crate::prelude::*; - use crate::{write, FormatContext, FormatState, VecBuffer}; + use crate::{write, FormatState, VecBuffer}; struct TestFormat; diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index 68ae23f471a..e4aaf77a6ef 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -71,7 +71,6 @@ impl<'a> Printer<'a> { args: PrintElementArgs, ) { match element { - FormatElement::Empty => {} FormatElement::Space => { if self.state.line_width > 0 { self.state.pending_space = true; @@ -694,8 +693,6 @@ fn fits_element_on_line<'a, 'rest>( options: &PrinterOptions, ) -> Fits { match element { - FormatElement::Empty => {} - FormatElement::Space => { if state.line_width > 0 { state.pending_space = true; @@ -905,7 +902,7 @@ impl<'a, 'rest> MeasureQueue<'a, 'rest> { mod tests { use crate::prelude::*; use crate::printer::{LineEnding, Printer, PrinterOptions}; - use crate::{format_args, write, FormatContext, FormatState, LineWidth, Printed, VecBuffer}; + use crate::{format_args, write, FormatState, LineWidth, Printed, VecBuffer}; fn format(root: &dyn Format<()>) -> Printed { format_with_options( diff --git a/crates/rome_js_formatter/src/context.rs b/crates/rome_js_formatter/src/context.rs index ec3bb04d069..e3cc162fa96 100644 --- a/crates/rome_js_formatter/src/context.rs +++ b/crates/rome_js_formatter/src/context.rs @@ -64,7 +64,7 @@ impl FormatContext for JsFormatContext { self.indent_style } - fn line_with(&self) -> LineWidth { + fn line_width(&self) -> LineWidth { self.line_width } diff --git a/crates/rome_js_formatter/src/cst.rs b/crates/rome_js_formatter/src/cst.rs index fe9c8bdf5ca..0483e2316c2 100644 --- a/crates/rome_js_formatter/src/cst.rs +++ b/crates/rome_js_formatter/src/cst.rs @@ -9,8 +9,8 @@ pub struct FormatJsSyntaxNode; impl rome_formatter::FormatRule for FormatJsSyntaxNode { type Context = JsFormatContext; - fn format(node: &JsSyntaxNode, formatter: &JsFormatter) -> FormatResult { - map_syntax_node!(node.clone(), node => formatted![formatter, [node.format()]]) + fn format(node: &JsSyntaxNode, f: &mut JsFormatter) -> FormatResult<()> { + map_syntax_node!(node.clone(), node => node.format().format(f)) } } @@ -22,7 +22,7 @@ impl<'a> AsFormat<'a> for JsSyntaxNode { } } -impl IntoFormat for JsSyntaxNode { +impl IntoFormat for JsSyntaxNode { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { diff --git a/crates/rome_js_formatter/src/formatter.rs b/crates/rome_js_formatter/src/formatter.rs index b76d50493c0..4973b3ef283 100644 --- a/crates/rome_js_formatter/src/formatter.rs +++ b/crates/rome_js_formatter/src/formatter.rs @@ -1,10 +1,18 @@ use crate::prelude::*; -use crate::{AsFormat, JsFormatContext}; +use rome_formatter::{format_args, write, Buffer, FormatOwnedWithRule, FormatWithRule, VecBuffer}; +use std::cell::Cell; + use rome_formatter::{normalize_newlines, FormatResult, GroupId, LINE_TERMINATORS}; use rome_js_syntax::{JsLanguage, JsSyntaxNode, JsSyntaxToken}; -use rome_rowan::{AstNode, AstNodeList, AstSeparatedList, Language, SyntaxTriviaPiece, TextRange}; -use std::iter::once; +use crate::{AsFormat, FormatJsSyntaxToken, IntoFormat, JsFormatContext}; +use rome_rowan::{ + AstNode, AstNodeList, AstNodeListIterator, AstSeparatedList, AstSeparatedListElementsIterator, + Language, SyntaxResult, SyntaxTriviaPiece, TextRange, +}; + +use rome_rowan::syntax::SyntaxTriviaPiecesIterator; +use std::iter::{once, FusedIterator}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum TrailingSeparator { @@ -49,7 +57,7 @@ impl FormatSeparatedOptions { /// Determines if the whitespace separating comment trivias /// from their associated tokens should be printed or trimmed #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub(super) enum TriviaPrintMode { +pub enum TriviaPrintMode { Full, Trim, } @@ -65,23 +73,97 @@ pub(super) enum TriviaPrintMode { /// These nodes and tokens get tracked as [FormatElement::Verbatim], useful to understand /// if these nodes still need to have their own implementation. pub fn verbatim_node(node: &JsSyntaxNode) -> FormatVerbatimNode { - FormatVerbatimNode { node } + FormatVerbatimNode { + node, + kind: VerbatimKind::Verbatim { + length: node.text_range().len(), + }, + } } #[derive(Debug, Clone)] pub struct FormatVerbatimNode<'node> { node: &'node JsSyntaxNode, + kind: VerbatimKind, } +impl Format for FormatVerbatimNode<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + for token in self.node.descendants_tokens() { + f.state_mut().track_token(&token); + } -impl Format for FormatVerbatimNode<'_> { - type Context = JsFormatContext; + fn skip_whitespace(piece: &SyntaxTriviaPiece) -> bool { + piece.is_newline() || piece.is_whitespace() + } - fn format(&self, formatter: &Formatter) -> FormatResult { - let verbatim = format_verbatim_node_or_token(self.node, formatter); - Ok(FormatElement::Verbatim(Verbatim::new_verbatim( - verbatim, - self.node.text_range().len(), - ))) + fn write_trivia_token( + f: &mut JsFormatter, + piece: SyntaxTriviaPiece, + ) -> FormatResult<()> { + write!( + f, + [syntax_token_cow_slice( + normalize_newlines(piece.text(), LINE_TERMINATORS), + &piece.token(), + piece.text_range().start(), + )] + ) + } + + let mut buffer = VecBuffer::new(f.state_mut()); + + write!( + buffer, + [format_with(|f| { + for leading_trivia in self + .node + .first_leading_trivia() + .into_iter() + .flat_map(|trivia| trivia.pieces()) + .skip_while(skip_whitespace) + { + write_trivia_token(f, leading_trivia)?; + } + + write!( + f, + [dynamic_token( + &normalize_newlines( + &self.node.text_trimmed().to_string(), + LINE_TERMINATORS + ), + self.node.text_trimmed_range().start() + )] + )?; + + // Clippy false positive: SkipWhile does not implement DoubleEndedIterator + #[allow(clippy::needless_collect)] + let trailing_trivia: Vec<_> = self + .node + .last_trailing_trivia() + .into_iter() + .flat_map(|trivia| trivia.pieces().rev()) + .skip_while(skip_whitespace) + .collect(); + + for trailing_trivia in trailing_trivia.into_iter().rev() { + write_trivia_token(f, trailing_trivia)?; + } + + Ok(()) + })] + )?; + + let content = buffer.into_element(); + + let verbatim = Verbatim { + element: Box::new(content), + kind: self.kind, + }; + + f.write_element(FormatElement::Verbatim(verbatim)); + + Ok(()) } } @@ -96,13 +178,15 @@ pub struct FormatUnknownNode<'node> { node: &'node JsSyntaxNode, } -impl Format for FormatUnknownNode<'_> { - type Context = JsFormatContext; - - fn format(&self, formatter: &Formatter) -> FormatResult { - Ok(FormatElement::Verbatim(Verbatim::new_unknown( - format_verbatim_node_or_token(self.node, formatter), - ))) +impl Format for FormatUnknownNode<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + write!( + f, + [FormatVerbatimNode { + node: self.node, + kind: VerbatimKind::Unknown + }] + ) } } @@ -116,112 +200,103 @@ pub struct FormatSuppressedNode<'node> { node: &'node JsSyntaxNode, } -impl Format for FormatSuppressedNode<'_> { - type Context = JsFormatContext; - - fn format(&self, formatter: &Formatter) -> FormatResult { - formatted![ - formatter, +impl Format for FormatSuppressedNode<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + // Insert a force a line break to ensure the suppression comment is on its own line + // and correctly registers as a leading trivia on the opening token of this node + write!( + f, [ - // Insert a force a line break to ensure the suppression comment is on its own line - // and correctly registers as a leading trivia on the opening token of this node hard_line_break(), - FormatElement::Verbatim(Verbatim::new_suppressed(format_verbatim_node_or_token( - self.node, formatter - ))), + FormatVerbatimNode { + node: self.node, + kind: VerbatimKind::Suppressed + } ] - ] - } -} - -fn format_verbatim_node_or_token( - node: &JsSyntaxNode, - formatter: &Formatter, -) -> FormatElement { - for token in node.descendants_tokens() { - formatter.track_token(&token); - } - - fn skip_whitespace(piece: &SyntaxTriviaPiece) -> bool { - piece.is_newline() || piece.is_whitespace() - } - - fn trivia_token(piece: SyntaxTriviaPiece) -> Token { - Token::from_syntax_token_cow_slice( - normalize_newlines(piece.text(), LINE_TERMINATORS), - &piece.token(), - piece.text_range().start(), ) } - - let leading_trivia = node - .first_leading_trivia() - .into_iter() - .flat_map(|trivia| trivia.pieces()) - .skip_while(skip_whitespace) - .map(trivia_token); - - let content = Token::new_dynamic( - normalize_newlines(&node.text_trimmed().to_string(), LINE_TERMINATORS).into_owned(), - node.text_trimmed_range().start(), - ); - - // Clippy false positive: SkipWhile does not implement DoubleEndedIterator - #[allow(clippy::needless_collect)] - let trailing_trivia = node - .last_trailing_trivia() - .into_iter() - .flat_map(|trivia| trivia.pieces().rev()) - .skip_while(skip_whitespace) - .map(trivia_token) - .collect::>(); - - concat_elements( - leading_trivia - .chain(once(content)) - .chain(trailing_trivia.into_iter().rev()) - .map(FormatElement::from), - ) } -pub(crate) fn format_trailing_trivia(token: &JsSyntaxToken) -> FormatElement { - format_trailing_trivia_pieces(token.trailing_trivia().pieces()) +pub struct FormatTrailingTriviaPieces { + pieces: I, } -fn format_trailing_trivia_pieces(pieces: I) -> FormatElement +impl Format for FormatTrailingTriviaPieces where - I: IntoIterator>, + I: Iterator> + Clone, { - let mut elements = Vec::new(); - - for piece in pieces { - if let Some(comment) = piece.as_comments() { - let is_single_line = comment.text().trim_start().starts_with("//"); + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let pieces = self.pieces.clone(); - let comment = FormatElement::from(Token::from(comment)); + for piece in pieces { + if let Some(comment_piece) = piece.as_comments() { + let is_single_line = comment_piece.text().trim_start().starts_with("//"); - let content = if !is_single_line { - format_elements![space_token(), comment, space_token(),] - } else { - format_elements![ - line_suffix(format_elements![space_token(), comment]), - expand_parent() - ] - }; + let content = format_with(|f| { + if !is_single_line { + write!(f, [space_token(), comment_piece, space_token()]) + } else { + write![ + f, + [ + line_suffix(&format_args![space_token(), comment_piece]), + expand_parent() + ] + ] + } + }); - elements.push(crate::comment(content)); + write!(f, [comment(&content)])?; + } } + + Ok(()) } +} - concat_elements(elements) +pub(crate) fn format_trailing_trivia( + token: &JsSyntaxToken, +) -> FormatTrailingTriviaPieces> { + FormatTrailingTriviaPieces { + pieces: token.trailing_trivia().pieces(), + } } -pub(super) fn format_leading_trivia( +pub fn format_leading_trivia( token: &JsSyntaxToken, trim_mode: TriviaPrintMode, -) -> FormatElement { - format_leading_trivia_pieces(token.leading_trivia().pieces(), trim_mode, false) - .unwrap_or_else(|_| format_leading_trivia_with_skipped_tokens(token, trim_mode)) +) -> FormatLeadingTrivia { + FormatLeadingTrivia { token, trim_mode } +} + +pub struct FormatLeadingTrivia<'a> { + token: &'a JsSyntaxToken, + trim_mode: TriviaPrintMode, +} + +impl Format for FormatLeadingTrivia<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let trivia_written = write!( + f, + [FormatLeadingTriviaPieces { + pieces: Cell::new(Some(self.token.leading_trivia().pieces())), + trim_mode: self.trim_mode, + has_trailing_newline: false + }] + ); + + if trivia_written.is_err() { + write!( + f, + [FormatLeadingTriviaWithSkippedTokens { + token: self.token, + trim_mode: self.trim_mode + }] + )?; + } + + Ok(()) + } } /// Formats the leading trivia of a token that has leading skipped trivia. @@ -238,89 +313,107 @@ pub(super) fn format_leading_trivia( /// ## Panics /// /// If called on a token that does not have skipped trivia -fn format_leading_trivia_with_skipped_tokens( - token: &JsSyntaxToken, +struct FormatLeadingTriviaWithSkippedTokens<'a> { + token: &'a JsSyntaxToken, trim_mode: TriviaPrintMode, -) -> FormatElement { - let mut skipped_trivia_range: Option = None; - // The leading trivia for the first skipped token trivia OR the leading trivia for the token - let mut trailing_trivia = vec![]; - // The trailing trivia for the last skipped token trivia - let mut leading_trivia = vec![]; - // The formatted elements - let mut elements = vec![]; - let mut after_newline = true; - - for piece in token.leading_trivia().pieces() { - if piece.is_skipped() { - if let Some(previous_range) = skipped_trivia_range { - // Another skipped token trivia: `.. first_skipped....piece`. Everything between the skipped token trivia should - // be formatted as is. - skipped_trivia_range = Some(previous_range.cover(piece.text_range())); - // Clear the collected leading/trailing trivia. They are part of the skipped - // token trivia range. - leading_trivia.clear(); - trailing_trivia.clear(); - } else { - // This is the first skipped token trivia. - // Format the collected leading trivia as the leading trivia of this "skipped token trivia" - skipped_trivia_range = Some(piece.text_range()); - elements.push( - format_leading_trivia_pieces(leading_trivia.drain(..), trim_mode, false) - .expect("All skipped trivia pieces should have been filtered out"), - ); - } - - after_newline = false; - continue; - } - - // Everything coming after a new line (including the new line) is considered a leading trivia and not trailing trivia. - if piece.is_newline() { - after_newline = true; - } +} - if after_newline { - leading_trivia.push(piece); - } else { - trailing_trivia.push(piece); - } - } +impl Format for FormatLeadingTriviaWithSkippedTokens<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let mut skipped_trivia_range: Option = None; + // The leading trivia for the first skipped token trivia OR the leading trivia for the token + let mut trailing_trivia = vec![]; + // The trailing trivia for the last skipped token trivia + let mut leading_trivia = vec![]; + // The formatted elements + let mut after_newline = true; + + for piece in self.token.leading_trivia().pieces() { + if piece.is_skipped() { + if let Some(previous_range) = skipped_trivia_range { + // Another skipped token trivia: `.. first_skipped....piece`. Everything between the skipped token trivia should + // be formatted as is. + skipped_trivia_range = Some(previous_range.cover(piece.text_range())); + // Clear the collected leading/trailing trivia. They are part of the skipped + // token trivia range. + leading_trivia.clear(); + trailing_trivia.clear(); + } else { + // This is the first skipped token trivia. + // Format the collected leading trivia as the leading trivia of this "skipped token trivia" + skipped_trivia_range = Some(piece.text_range()); + write!( + f, + [FormatLeadingTriviaPieces { + pieces: Cell::new(Some(leading_trivia.drain(..))), + trim_mode: self.trim_mode, + has_trailing_newline: false + }] + ) + .expect("All skipped trivia pieces should have been filtered out"); + } - let skipped_trivia_range = skipped_trivia_range.expect( - "Only call this method for leading trivia containing at least one skipped token trivia.", - ); + after_newline = false; + continue; + } - // Format the skipped token trivia range - elements.push(FormatElement::from(Token::new_syntax_token_slice( - token, - skipped_trivia_range, - ))); + // Everything coming after a new line (including the new line) is considered a leading trivia and not trailing trivia. + if piece.is_newline() { + after_newline = true; + } - // `print_trailing_trivia_pieces` and `format_leading_trivia_pieces` remove any whitespace except - // if there's a comment but removing all whitespace may have a different semantic meaning. - // Insert a: - // * space if the skipped token has no trailing trivia (`skipped\n`, also works for `skipped//comment` because the comment must either be followed by a line break or the token is the EOF). - // * new line if the token has any leading trivia. This can only be the case if there was any new line between the skipped trivia and the token - // * empty: There's literally nothing between skipped and token, so don't insert anything - let skipped_separator = if !trailing_trivia.is_empty() { - space_token() - } else if !leading_trivia.is_empty() { - hard_line_break() - } else { - empty_element() - }; + if after_newline { + leading_trivia.push(piece); + } else { + trailing_trivia.push(piece); + } + } - elements.push(skipped_separator); - // Format the trailing pieces of the skipped token trivia - elements.push(format_trailing_trivia_pieces(trailing_trivia)); + let skipped_trivia_range = skipped_trivia_range.expect( + "Only call this method for leading trivia containing at least one skipped token trivia.", + ); + + // Format the skipped token trivia range + write!( + f, + [syntax_token_text_slice(self.token, skipped_trivia_range)] + )?; + + // `print_trailing_trivia_pieces` and `format_leading_trivia_pieces` remove any whitespace except + // if there's a comment but removing all whitespace may have a different semantic meaning. + // Insert a: + // * space if the skipped token has no trailing trivia (`skipped\n`, also works for `skipped//comment` because the comment must either be followed by a line break or the token is the EOF). + // * new line if the token has any leading trivia. This can only be the case if there was any new line between the skipped trivia and the token + // * empty: There's literally nothing between skipped and token, so don't insert anything + if !trailing_trivia.is_empty() { + write!(f, [space_token()])?; + } else if !leading_trivia.is_empty() { + write!(f, [hard_line_break()])?; + }; - elements.push( - format_leading_trivia_pieces(leading_trivia.into_iter(), trim_mode, after_newline) - .expect("All skipped trivia pieces should have been filtered out"), - ); + // Format the trailing pieces of the skipped token trivia + write!( + f, + [FormatTrailingTriviaPieces { + pieces: trailing_trivia.into_iter() + }] + )?; + + write!( + f, + [FormatLeadingTriviaPieces { + pieces: Cell::new(Some(leading_trivia.into_iter())), + trim_mode: self.trim_mode, + has_trailing_newline: after_newline + }] + ) + } +} - concat_elements(elements) +struct FormatLeadingTriviaPieces { + pieces: Cell>, + trim_mode: TriviaPrintMode, + has_trailing_newline: bool, } /// Formats the leading trivia pieces of a token. @@ -329,261 +422,131 @@ fn format_leading_trivia_with_skipped_tokens( /// /// Returns [Err] if the leading trivia contains any skipped trivia. Returns the formatted /// leading trivia otherwise. -fn format_leading_trivia_pieces( - pieces: I, - mut trim_mode: TriviaPrintMode, - has_trailing_newline: bool, -) -> Result +impl Format for FormatLeadingTriviaPieces where I: Iterator> + DoubleEndedIterator + ExactSizeIterator, { - let mut line_count = 0; - let mut elements = Vec::new(); - - // Get the index of the first comment in the trivia pieces list, and - // checks whether this token has any leading newline the comment - let mut has_leading_newline = false; - let mut first_comment = 0; - - let mut pieces = pieces.enumerate().peekable(); - - // Peek at the next trivia piece, stopping if it is a comment and - // advancing the iterator if it's not - while let Some((index, piece)) = pieces.peek() { - if piece.is_comments() { - // Save the index and break the loop - // without consuming the comment piece - first_comment = *index; - break; - } - - if piece.is_skipped() { - return Err(()); - } + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let pieces = self + .pieces + .take() + .expect("Leading trivia pieces can only be formatted once"); + + let mut line_count = 0; + + // Get the index of the first comment in the trivia pieces list, and + // checks whether this token has any leading newline the comment + let mut has_leading_newline = false; + let mut first_comment = 0; + + let mut pieces = pieces.enumerate().peekable(); + + // Peek at the next trivia piece, stopping if it is a comment and + // advancing the iterator if it's not + while let Some((index, piece)) = pieces.peek() { + if piece.is_comments() { + // Save the index and break the loop + // without consuming the comment piece + first_comment = *index; + break; + } - if piece.is_newline() { - has_leading_newline = true; - } + if piece.is_skipped() { + return Err(FormatError::MissingRequiredChild); + } - pieces.next(); - } + if piece.is_newline() { + has_leading_newline = true; + } - // If any newline was found between the previous token and the first comment, - // it will be prepended with a line break instead of a space - let prepend_newline = has_trailing_newline || has_leading_newline; + pieces.next(); + } - // This consumes the previously created iterator from the last trivia piece - // towards the first (that was not consumed by the previous loop) - for (index, piece) in pieces.rev() { - if let Some(comment) = piece.as_comments() { - let is_single_line = comment.text().starts_with("//"); + // If any newline was found between the previous token and the first comment, + // it will be prepended with a line break instead of a space + let prepend_newline = self.has_trailing_newline || has_leading_newline; + let mut trim_mode = self.trim_mode; - let comment = FormatElement::from(Token::from(comment)); + // This consumes the previously created iterator from the last trivia piece + // towards the first (that was not consumed by the previous loop) + for (index, piece) in pieces.rev() { + if let Some(comment_piece) = piece.as_comments() { + let is_single_line = comment_piece.text().starts_with("//"); - let element_before_comment = if prepend_newline && index == first_comment { - hard_line_break() - } else { - space_token() - }; + let format_content = format_with(|f| { + if prepend_newline && index == first_comment { + write!(f, [hard_line_break()])?; + } else { + write!(f, [space_token()])?; + }; - let element_after_comment = if is_single_line { - match line_count { - 0 | 1 => hard_line_break(), - _ => empty_line(), - } - } else { - match line_count { - 0 => space_token(), - 1 => hard_line_break(), - _ => empty_line(), - } - }; + write!(f, [comment(&comment_piece)])?; - elements.push(crate::comment(format_elements![ - element_before_comment, - comment, - element_after_comment, - ])); - - line_count = 0; - trim_mode = TriviaPrintMode::Full; - } else if piece.is_newline() && trim_mode == TriviaPrintMode::Full { - line_count += 1; - } else if piece.is_skipped() { - return Err(()); + if is_single_line { + match line_count { + 0 | 1 => write!(f, [hard_line_break()])?, + _ => write!(f, [empty_line()])?, + } + } else { + match line_count { + 0 => write!(f, [space_token()])?, + 1 => write!(f, [hard_line_break()])?, + _ => write!(f, [empty_line()])?, + } + }; + + Ok(()) + }); + + write!(f, [comment(&format_content)])?; + + line_count = 0; + trim_mode = TriviaPrintMode::Full; + } else if piece.is_newline() && trim_mode == TriviaPrintMode::Full { + line_count += 1; + } else if piece.is_skipped() { + return Err(FormatError::MissingRequiredChild); + } } - } - Ok(concat_elements(elements.into_iter().rev())) + Ok(()) + } } -pub(crate) type JsFormatter = Formatter; +pub(crate) type JsFormatter<'buf> = Formatter<'buf, JsFormatContext>; /// JS specific formatter extensions -pub(crate) trait JsFormatterExt { - fn as_formatter(&self) -> &Formatter; +pub(crate) trait JsFormatterExt<'buf> { + fn as_formatter(&self) -> &Formatter<'buf, JsFormatContext>; #[must_use] - fn delimited<'a, 'fmt>( - &'fmt self, + fn delimited<'a>( + &self, open_token: &'a JsSyntaxToken, - content: FormatElement, + content: &'a dyn Format, close_token: &'a JsSyntaxToken, - ) -> FormatDelimited<'a, 'fmt> { - FormatDelimited::new(open_token, content, close_token, self.as_formatter()) + ) -> FormatDelimited<'a> { + FormatDelimited::new(open_token, content, close_token) } /// Print out a `token` from the original source with a different `content`. /// /// This will print the trivias that belong to `token` to `content`; /// `token` is then marked as consumed by the formatter. - fn format_replaced( - &self, - current_token: &JsSyntaxToken, - content_to_replace_with: FormatElement, - ) -> FormatElement { - let f = self.as_formatter(); - - f.track_token(current_token); - - format_elements![ - format_leading_trivia(current_token, TriviaPrintMode::Full), - content_to_replace_with, - format_trailing_trivia(current_token), - ] - } - - /// Prints a separated list of nodes - /// - /// Trailing separators will be reused from the original list or - /// created by calling the `separator_factory` function. - /// The last trailing separator in the list will only be printed - /// if the outer group breaks. - fn format_separated( - &self, - list: &L, - separator_factory: F, - ) -> FormatResult> - where - L: AstSeparatedList, - for<'a> L::Node: AstNode + AsFormat<'a>, - F: Fn() -> FormatElement, - { - self.format_separated_with_options( - list, - separator_factory, - FormatSeparatedOptions::default(), - ) - } - - /// Prints a separated list of nodes - /// - /// Trailing separators will be reused from the original list or - /// created by calling the `separator_factory` function. - /// The last trailing separator in the list will only be printed - /// if the outer group breaks. - fn format_separated_with_options( + fn format_replaced<'a>( &self, - list: &L, - separator_factory: F, - options: FormatSeparatedOptions, - ) -> FormatResult> - where - L: AstSeparatedList, - for<'a> L::Node: AstNode + AsFormat<'a>, - F: Fn() -> FormatElement, - { - let mut result = Vec::with_capacity(list.len()); - let last_index = list.len().saturating_sub(1); - let formatter = self.as_formatter(); - - let trailing_separator_factory = || { - if let Some(group_id) = options.group_id { - if_group_with_id_breaks(separator_factory(), group_id) - } else { - if_group_breaks(separator_factory()) - } - }; - - let trailing_separator = options.trailing_separator; - - for (index, element) in list.elements().enumerate() { - let node = formatted![formatter, [element.node()?.format()]]?; - - // Reuse the existing trailing separator or create it if it wasn't in the - // input source. Only print the last trailing token if the outer group breaks - let separator = if let Some(separator) = element.trailing_separator()? { - if index == last_index { - if trailing_separator.is_allowed() { - // Use format_replaced instead of wrapping the result of format_token - // in order to remove only the token itself when the group doesn't break - // but still print its associated trivias unconditionally - self.format_replaced(separator, trailing_separator_factory()) - } else if trailing_separator.is_mandatory() { - formatted![formatter, [separator.format()]]? - } else { - empty_element() - } - } else { - formatted![formatter, [separator.format()]]? - } - } else if index == last_index { - if trailing_separator.is_allowed() { - trailing_separator_factory() - } else if trailing_separator.is_mandatory() { - separator_factory() - } else { - empty_element() - } - } else { - separator_factory() - }; - - result.push(format_elements![group_elements(node), separator]); + current_token: &'a JsSyntaxToken, + content_to_replace_with: &'a dyn Format, + ) -> FormatReplaced<'a> { + FormatReplaced { + token: current_token, + content: content_to_replace_with, } - - Ok(result.into_iter()) - } - - /// It formats a list of nodes that are not separated. It's an ad-hoc function to - /// format lists that implement [rome_js_syntax::AstNodeList]. - /// - /// The elements of the list are joined together using [join_elements_hard_line], which will - /// end up separated by hard lines or empty lines. - /// - /// If the formatter fails to format an element, said element gets printed verbatim. - fn format_list(&self, list: &List) -> FormatElement - where - List: AstNodeList, - for<'a> Node: AstNode + AsFormat<'a>, - { - let formatter = self.as_formatter(); - let formatted_list = list.iter().map(|module_item| { - let snapshot = formatter.snapshot(); - let format = module_item.format(); - - let elem = match formatted![formatter, [format]] { - Ok(result) => result, - Err(_) => { - formatter.restore(snapshot); - - // Lists that yield errors are formatted as they were unknown nodes. - // Doing so, the formatter formats the nodes/tokens as is. - // SAFETY: `FormatUnknownNode` always returns Ok - unknown_node(module_item.syntax()) - .format(formatter) - .unwrap() - } - }; - - (module_item.syntax().clone(), elem) - }); - join_elements_hard_line(formatted_list) } } -impl JsFormatterExt for Formatter { - fn as_formatter(&self) -> &Formatter { +impl<'buf> JsFormatterExt<'buf> for Formatter<'buf, JsFormatContext> { + fn as_formatter(&self) -> &Formatter<'buf, JsFormatContext> { self } } @@ -593,27 +556,24 @@ impl JsFormatterExt for Formatter { /// /// Calling this method is required to correctly handle the comments attached /// to the opening and closing tokens and insert them inside the group block -pub struct FormatDelimited<'a, 'fmt> { +pub struct FormatDelimited<'a> { open_token: &'a JsSyntaxToken, - content: FormatElement, + content: &'a dyn Format, close_token: &'a JsSyntaxToken, mode: DelimitedMode, - formatter: &'fmt Formatter, } -impl<'a, 'fmt> FormatDelimited<'a, 'fmt> { +impl<'a> FormatDelimited<'a> { fn new( open_token: &'a JsSyntaxToken, - content: FormatElement, + content: &'a dyn Format, close_token: &'a JsSyntaxToken, - formatter: &'fmt Formatter, ) -> Self { Self { open_token, content, close_token, mode: DelimitedMode::SoftBlockIndent(None), - formatter, } } @@ -648,112 +608,83 @@ impl<'a, 'fmt> FormatDelimited<'a, 'fmt> { pub fn soft_block_spaces_with_group_id(self, group_id: Option) -> Self { self.with_mode(DelimitedMode::SoftBlockSpaces(group_id)) } +} - pub fn finish(self) -> FormatResult { +impl Format for FormatDelimited<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { let FormatDelimited { - formatter, open_token, close_token, content, mode, } = self; - formatter.track_token(open_token); - formatter.track_token(close_token); + f.state_mut().track_token(open_token); + f.state_mut().track_token(close_token); + + write!( + f, + [format_leading_trivia(open_token, TriviaPrintMode::Full)] + )?; let open_token_trailing_trivia = format_trailing_trivia(open_token); let close_token_leading_trivia = format_leading_trivia(close_token, TriviaPrintMode::Trim); - let open_token_trailing_trivia = if !open_token_trailing_trivia.is_empty() { - formatted![ - formatter, - [open_token_trailing_trivia, soft_line_break_or_space()] - ]? - } else { - empty_element() - }; - let close_token_leading_trivia = if !close_token_leading_trivia.is_empty() { - formatted![ - formatter, - [soft_line_break_or_space(), close_token_leading_trivia] - ]? - } else { - empty_element() - }; - - let formatted_content = match mode { - DelimitedMode::BlockIndent => block_indent(formatted![ - formatter, - [ - open_token_trailing_trivia, - content, - close_token_leading_trivia - ] - ]?), - DelimitedMode::SoftBlockIndent(_) => soft_block_indent(formatted![ - formatter, - [ - open_token_trailing_trivia, - content, - close_token_leading_trivia - ] - ]?), - DelimitedMode::SoftBlockSpaces(_) => { - if open_token_trailing_trivia.is_empty() - && content.is_empty() - && close_token_leading_trivia.is_empty() - { - empty_element() - } else { - formatted![ - formatter, - [ - indent(formatted![ - formatter, - [ - soft_line_break_or_space(), - open_token_trailing_trivia, - content, - close_token_leading_trivia, - ] - ]?), - soft_line_break_or_space(), - ] - ]? + let delimited = format_with(|f| { + write!(f, [FormatTrimmedToken::new(open_token)])?; + + match mode { + DelimitedMode::BlockIndent => { + write!( + f, + [block_indent(&format_args![ + open_token_trailing_trivia, + content, close_token_leading_trivia + ])] + )?; } - } - }; + DelimitedMode::SoftBlockIndent(_) => write!( + f, + [soft_block_indent(&format_args![ + open_token_trailing_trivia, + content, close_token_leading_trivia + ])] + )?, + DelimitedMode::SoftBlockSpaces(_) => write![ + f, + [ + indent(&format_args![ + soft_line_break_or_space(), + open_token_trailing_trivia, content, close_token_leading_trivia, + ]), + soft_line_break_or_space(), + ] + ]?, + }; - let delimited = format_elements![ - Token::from(open_token), - formatted_content, - Token::from(close_token), - ]; + write!(f, [FormatTrimmedToken::new(close_token)]) + }); let grouped = match mode { // Group is useless, the block indent would expand it right anyway - DelimitedMode::BlockIndent => delimited, + DelimitedMode::BlockIndent => write!(f, [delimited])?, DelimitedMode::SoftBlockIndent(group_id) | DelimitedMode::SoftBlockSpaces(group_id) => { match group_id { - None => group_elements(delimited), - Some(group_id) => group_elements_with_options( - delimited, - GroupElementsOptions { - group_id: Some(group_id), - }, - ), + None => write!(f, [group_elements(&delimited)])?, + Some(group_id) => write!( + f, + [group_elements_with_options( + &delimited, + GroupElementsOptions { + group_id: Some(*group_id), + }, + )] + )?, } } }; - formatted![ - formatter, - [ - format_leading_trivia(open_token, TriviaPrintMode::Full), - grouped, - format_trailing_trivia(close_token), - ] - ] + write!(f, [format_trailing_trivia(close_token)]) } } @@ -763,3 +694,356 @@ enum DelimitedMode { SoftBlockIndent(Option), SoftBlockSpaces(Option), } + +/// Print out a `token` from the original source with a different `content`. +/// +/// This will print the trivias that belong to `token` to `content`; +/// `token` is then marked as consumed by the formatter. +pub struct FormatReplaced<'a> { + token: &'a JsSyntaxToken, + content: &'a dyn Format, +} + +impl Format for FormatReplaced<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + f.state_mut().track_token(self.token); + + write!( + f, + [ + format_leading_trivia(self.token, TriviaPrintMode::Full), + self.content, + format_trailing_trivia(self.token) + ] + ) + } +} + +// Idea, implement as an iterator extension iter.formatted_separated() +// Each call must return an owned element + +pub struct FormatSeparatedItem { + node: F, + separator: S, + trailing_separator_token: SyntaxResult>, + last: bool, + options: FormatSeparatedOptions, +} + +impl Format for FormatSeparatedItem +where + F: Format, + S: Format, +{ + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let trailing_separator_factory = format_with(|f| { + if let Some(group_id) = self.options.group_id { + write!(f, [if_group_with_id_breaks(&self.separator, group_id)]) + } else { + write!(f, [if_group_breaks(&self.separator)]) + } + }); + + write!(f, [group_elements(&self.node)])?; + + // Reuse the existing trailing separator or create it if it wasn't in the + // input source. Only print the last trailing token if the outer group breaks + if let Some(separator) = self.trailing_separator_token.as_ref()? { + if self.last { + if self.options.trailing_separator.is_allowed() { + // Use format_replaced instead of wrapping the result of format_token + // in order to remove only the token itself when the group doesn't break + // but still print its associated trivias unconditionally + write!( + f, + [f.format_replaced(separator, &trailing_separator_factory)] + )?; + } else if self.options.trailing_separator.is_mandatory() { + write!(f, [separator.format()])?; + } + } else { + write!(f, [separator.format()])?; + } + } else if self.last { + if self.options.trailing_separator.is_allowed() { + write!(f, [trailing_separator_factory])?; + } else if self.options.trailing_separator.is_mandatory() { + write!(f, [&self.separator])?; + } + } else { + write!(f, [&self.separator])?; + }; + + Ok(()) + } +} + +pub struct FormatSeparatedIter +where + I: Iterator>)>, +{ + inner: std::iter::Peekable, + separator: Separator, + options: FormatSeparatedOptions, +} + +impl FormatSeparatedIter +where + I: Iterator>)>, + Content: Format, + Separator: Format + Copy, +{ + pub fn new(inner: I, separator: Separator) -> Self { + Self::with_options(inner, separator, FormatSeparatedOptions::default()) + } + + pub fn with_options(inner: I, separator: Separator, options: FormatSeparatedOptions) -> Self { + Self { + inner: inner.peekable(), + separator, + options, + } + } +} + +impl Iterator for FormatSeparatedIter +where + I: Iterator>)>, + Content: Format, + Separator: Format + Copy, +{ + type Item = FormatSeparatedItem; + + fn next(&mut self) -> Option { + let (content, separator) = self.inner.next()?; + + Some(FormatSeparatedItem { + node: content, + separator: self.separator, + trailing_separator_token: separator, + last: self.inner.peek().is_none(), + options: self.options, + }) + } +} + +impl FusedIterator for FormatSeparatedIter +where + I: Iterator>)>, + Content: Format, + Separator: Format + Copy, +{ +} + +impl std::iter::ExactSizeIterator + for FormatSeparatedIter +where + I: Iterator>)>, + Content: Format, + Separator: Format + Copy, +{ +} + +pub struct FormatSeparatedListItemIter { + inner: AstSeparatedListElementsIterator, +} + +impl Iterator for FormatSeparatedListItemIter +where + N: AstNode + IntoFormat + Clone, +{ + type Item = (SyntaxResult, SyntaxResult>); + + fn next(&mut self) -> Option { + let next = self.inner.next()?; + + let separator = match next.trailing_separator() { + Ok(sep) => Ok(sep.cloned()), + Err(err) => Err(err), + }; + + Some((next.node().cloned().into_format(), separator)) + } +} + +pub trait FormatSeparatedExtension: AstSeparatedList +where + Self::Node: IntoFormat + Clone, +{ + /// Prints a separated list of nodes + /// + /// Trailing separators will be reused from the original list or + /// created by calling the `separator_factory` function. + /// The last trailing separator in the list will only be printed + /// if the outer group breaks. + /// + fn format_separated( + &self, + separator: Separator, + ) -> FormatSeparatedIter< + FormatSeparatedListItemIter, + SyntaxResult<>::Format>, + Separator, + > + where + Separator: Format + Copy; + + /// Prints a separated list of nodes + /// + /// Trailing separators will be reused from the original list or + /// created by calling the `separator_factory` function. + /// The last trailing separator in the list will only be printed + /// if the outer group breaks. + fn format_separated_with_options( + &self, + separator_factory: Separator, + options: FormatSeparatedOptions, + ) -> FormatSeparatedIter< + FormatSeparatedListItemIter, + SyntaxResult<>::Format>, + Separator, + > + where + Separator: Format + Copy; +} + +impl FormatSeparatedExtension for T +where + T: AstSeparatedList, + T::Node: IntoFormat + Clone, +{ + fn format_separated( + &self, + separator: Separator, + ) -> FormatSeparatedIter< + FormatSeparatedListItemIter, + SyntaxResult<>::Format>, + Separator, + > + where + Separator: Format + Copy, + { + let inner = FormatSeparatedListItemIter { + inner: self.elements(), + }; + + FormatSeparatedIter::new(inner, separator) + } + + fn format_separated_with_options( + &self, + separator: Separator, + options: FormatSeparatedOptions, + ) -> FormatSeparatedIter< + FormatSeparatedListItemIter, + SyntaxResult<>::Format>, + Separator, + > + where + Separator: Format + Copy, + { + let inner = FormatSeparatedListItemIter { + inner: self.elements(), + }; + + FormatSeparatedIter::with_options(inner, separator, options) + } +} + +/// Formats a node or falls back to verbatim printing if formating this node fails. +pub struct TryFormatNode { + node: Node, +} + +impl Format for TryFormatNode +where + for<'a> Node: AstNode + AsFormat<'a>, +{ + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let snapshot = f.snapshot(); + + match write![f, [self.node.format()]] { + Ok(result) => { + f.release_snapshot(snapshot); + Ok(result) + } + Err(_) => { + f.restore_snapshot(snapshot); + + // Lists that yield errors are formatted as they were unknown nodes. + // Doing so, the formatter formats the nodes/tokens as is. + // SAFETY: `FormatUnknownNode` always returns Ok + write!(f, [unknown_node(self.node.syntax())]) + } + } + } +} + +/// It formats a list of nodes that are not separated. It's an ad-hoc function to +/// format lists that implement [rome_js_syntax::AstNodeList]. +/// +/// The elements of the list are joined together using [join_elements_hard_line], which will +/// end up separated by hard lines or empty lines. +/// +/// If the formatter fails to format an element, said element gets printed verbatim. +pub struct TryFormatNodesIterator { + inner: AstNodeListIterator, +} + +impl Iterator for TryFormatNodesIterator +where + for<'a> N: AstNode + AsFormat<'a>, +{ + type Item = TryFormatNode; + + fn next(&mut self) -> Option { + let node = self.inner.next()?; + + Some(TryFormatNode { node }) + } +} + +impl FusedIterator for TryFormatNodesIterator where + for<'a> N: AstNode + AsFormat<'a> +{ +} + +impl ExactSizeIterator for TryFormatNodesIterator where + for<'a> N: AstNode + AsFormat<'a> +{ +} + +pub trait TryFormatNodeListExtension { + fn try_format_nodes(&self) -> TryFormatNodesIterator; +} + +impl TryFormatNodeListExtension for T +where + T: AstNodeList, +{ + fn try_format_nodes(&self) -> TryFormatNodesIterator { + TryFormatNodesIterator { inner: self.iter() } + } +} + +/// Formats a token without its leading or trailing trivia +/// +/// ## Warning +/// It's your responsibility to format leading or trailing comments and skipped trivia. +pub struct FormatTrimmedToken<'a> { + token: &'a JsSyntaxToken, +} + +impl<'a> FormatTrimmedToken<'a> { + pub fn new(token: &'a JsSyntaxToken) -> Self { + Self { token } + } +} + +impl Format for FormatTrimmedToken<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let trimmed_range = self.token.text_trimmed_range(); + + write!(f, [syntax_token_text_slice(self.token, trimmed_range)]) + } +} diff --git a/crates/rome_js_formatter/src/generated.rs b/crates/rome_js_formatter/src/generated.rs index ebba0090034..79f5b182e75 100644 --- a/crates/rome_js_formatter/src/generated.rs +++ b/crates/rome_js_formatter/src/generated.rs @@ -5,22 +5,30 @@ use rome_formatter::{FormatOwnedWithRule, FormatRefWithRule}; impl<'a> AsFormat<'a> for rome_js_syntax::JsScript { type Format = FormatRefWithRule<'a, rome_js_syntax::JsScript, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsScript { +impl IntoFormat for rome_js_syntax::JsScript { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsModule { type Format = FormatRefWithRule<'a, rome_js_syntax::JsModule, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsModule { +impl IntoFormat for rome_js_syntax::JsModule { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExpressionSnipped { type Format = FormatRefWithRule< @@ -28,14 +36,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExpressionSnipped { rome_js_syntax::JsExpressionSnipped, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExpressionSnipped { +impl IntoFormat for rome_js_syntax::JsExpressionSnipped { type Format = FormatOwnedWithRule< rome_js_syntax::JsExpressionSnipped, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsDirective { type Format = FormatRefWithRule< @@ -43,14 +55,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDirective { rome_js_syntax::JsDirective, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsDirective { +impl IntoFormat for rome_js_syntax::JsDirective { type Format = FormatOwnedWithRule< rome_js_syntax::JsDirective, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsBlockStatement { type Format = FormatRefWithRule< @@ -58,14 +74,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBlockStatement { rome_js_syntax::JsBlockStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsBlockStatement { +impl IntoFormat for rome_js_syntax::JsBlockStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsBlockStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsBreakStatement { type Format = FormatRefWithRule< @@ -73,14 +93,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBreakStatement { rome_js_syntax::JsBreakStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsBreakStatement { +impl IntoFormat for rome_js_syntax::JsBreakStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsBreakStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsClassDeclaration { type Format = FormatRefWithRule< @@ -88,14 +112,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassDeclaration { rome_js_syntax::JsClassDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsClassDeclaration { +impl IntoFormat for rome_js_syntax::JsClassDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsClassDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsContinueStatement { type Format = FormatRefWithRule< @@ -103,14 +131,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsContinueStatement { rome_js_syntax::JsContinueStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsContinueStatement { +impl IntoFormat for rome_js_syntax::JsContinueStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsContinueStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsDebuggerStatement { type Format = FormatRefWithRule< @@ -118,14 +150,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDebuggerStatement { rome_js_syntax::JsDebuggerStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsDebuggerStatement { +impl IntoFormat for rome_js_syntax::JsDebuggerStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsDebuggerStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsDoWhileStatement { type Format = FormatRefWithRule< @@ -133,14 +169,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDoWhileStatement { rome_js_syntax::JsDoWhileStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsDoWhileStatement { +impl IntoFormat for rome_js_syntax::JsDoWhileStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsDoWhileStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsEmptyStatement { type Format = FormatRefWithRule< @@ -148,14 +188,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsEmptyStatement { rome_js_syntax::JsEmptyStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsEmptyStatement { +impl IntoFormat for rome_js_syntax::JsEmptyStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsEmptyStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExpressionStatement { type Format = FormatRefWithRule< @@ -163,14 +207,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExpressionStatement { rome_js_syntax::JsExpressionStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExpressionStatement { +impl IntoFormat for rome_js_syntax::JsExpressionStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsExpressionStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsForInStatement { type Format = FormatRefWithRule< @@ -178,14 +226,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForInStatement { rome_js_syntax::JsForInStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsForInStatement { +impl IntoFormat for rome_js_syntax::JsForInStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsForInStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsForOfStatement { type Format = FormatRefWithRule< @@ -193,14 +245,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForOfStatement { rome_js_syntax::JsForOfStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsForOfStatement { +impl IntoFormat for rome_js_syntax::JsForOfStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsForOfStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsForStatement { type Format = FormatRefWithRule< @@ -208,14 +264,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForStatement { rome_js_syntax::JsForStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsForStatement { +impl IntoFormat for rome_js_syntax::JsForStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsForStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsIfStatement { type Format = FormatRefWithRule< @@ -223,14 +283,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIfStatement { rome_js_syntax::JsIfStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsIfStatement { +impl IntoFormat for rome_js_syntax::JsIfStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsIfStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsLabeledStatement { type Format = FormatRefWithRule< @@ -238,14 +302,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLabeledStatement { rome_js_syntax::JsLabeledStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsLabeledStatement { +impl IntoFormat for rome_js_syntax::JsLabeledStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsLabeledStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsReturnStatement { type Format = FormatRefWithRule< @@ -253,14 +321,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsReturnStatement { rome_js_syntax::JsReturnStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsReturnStatement { +impl IntoFormat for rome_js_syntax::JsReturnStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsReturnStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsSwitchStatement { type Format = FormatRefWithRule< @@ -268,14 +340,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSwitchStatement { rome_js_syntax::JsSwitchStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSwitchStatement { +impl IntoFormat for rome_js_syntax::JsSwitchStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsSwitchStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsThrowStatement { type Format = FormatRefWithRule< @@ -283,14 +359,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsThrowStatement { rome_js_syntax::JsThrowStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsThrowStatement { +impl IntoFormat for rome_js_syntax::JsThrowStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsThrowStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsTryFinallyStatement { type Format = FormatRefWithRule< @@ -298,14 +378,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTryFinallyStatement { rome_js_syntax::JsTryFinallyStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsTryFinallyStatement { +impl IntoFormat for rome_js_syntax::JsTryFinallyStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTryFinallyStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsTryStatement { type Format = FormatRefWithRule< @@ -313,14 +397,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTryStatement { rome_js_syntax::JsTryStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsTryStatement { +impl IntoFormat for rome_js_syntax::JsTryStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTryStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableStatement { type Format = FormatRefWithRule< @@ -328,14 +416,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableStatement { rome_js_syntax::JsVariableStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsVariableStatement { +impl IntoFormat for rome_js_syntax::JsVariableStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsWhileStatement { type Format = FormatRefWithRule< @@ -343,14 +435,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsWhileStatement { rome_js_syntax::JsWhileStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsWhileStatement { +impl IntoFormat for rome_js_syntax::JsWhileStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsWhileStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsWithStatement { type Format = FormatRefWithRule< @@ -358,14 +454,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsWithStatement { rome_js_syntax::JsWithStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsWithStatement { +impl IntoFormat for rome_js_syntax::JsWithStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsWithStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionDeclaration { type Format = FormatRefWithRule< @@ -373,14 +473,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionDeclaration { rome_js_syntax::JsFunctionDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsFunctionDeclaration { +impl IntoFormat for rome_js_syntax::JsFunctionDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumDeclaration { type Format = FormatRefWithRule< @@ -388,14 +492,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumDeclaration { rome_js_syntax::TsEnumDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsEnumDeclaration { +impl IntoFormat for rome_js_syntax::TsEnumDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsEnumDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAliasDeclaration { type Format = FormatRefWithRule< @@ -403,14 +511,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAliasDeclaration { rome_js_syntax::TsTypeAliasDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeAliasDeclaration { +impl IntoFormat for rome_js_syntax::TsTypeAliasDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAliasDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsInterfaceDeclaration { type Format = FormatRefWithRule< @@ -418,14 +530,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsInterfaceDeclaration { rome_js_syntax::TsInterfaceDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsInterfaceDeclaration { +impl IntoFormat for rome_js_syntax::TsInterfaceDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsInterfaceDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareFunctionDeclaration { type Format = FormatRefWithRule< @@ -433,14 +549,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareFunctionDeclaration { rome_js_syntax::TsDeclareFunctionDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsDeclareFunctionDeclaration { +impl IntoFormat for rome_js_syntax::TsDeclareFunctionDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsDeclareFunctionDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareStatement { type Format = FormatRefWithRule< @@ -448,14 +568,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareStatement { rome_js_syntax::TsDeclareStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsDeclareStatement { +impl IntoFormat for rome_js_syntax::TsDeclareStatement { type Format = FormatOwnedWithRule< rome_js_syntax::TsDeclareStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsModuleDeclaration { type Format = FormatRefWithRule< @@ -463,14 +587,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsModuleDeclaration { rome_js_syntax::TsModuleDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsModuleDeclaration { +impl IntoFormat for rome_js_syntax::TsModuleDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsModuleDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsExternalModuleDeclaration { type Format = FormatRefWithRule< @@ -478,14 +606,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExternalModuleDeclaration { rome_js_syntax::TsExternalModuleDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsExternalModuleDeclaration { +impl IntoFormat for rome_js_syntax::TsExternalModuleDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsExternalModuleDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsGlobalDeclaration { type Format = FormatRefWithRule< @@ -493,14 +625,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsGlobalDeclaration { rome_js_syntax::TsGlobalDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsGlobalDeclaration { +impl IntoFormat for rome_js_syntax::TsGlobalDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsGlobalDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsImportEqualsDeclaration { type Format = FormatRefWithRule< @@ -508,14 +644,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImportEqualsDeclaration { rome_js_syntax::TsImportEqualsDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsImportEqualsDeclaration { +impl IntoFormat for rome_js_syntax::TsImportEqualsDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsImportEqualsDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsElseClause { type Format = FormatRefWithRule< @@ -523,14 +663,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsElseClause { rome_js_syntax::JsElseClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsElseClause { +impl IntoFormat for rome_js_syntax::JsElseClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsElseClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclaration { type Format = FormatRefWithRule< @@ -538,14 +682,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclaration { rome_js_syntax::JsVariableDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsVariableDeclaration { +impl IntoFormat for rome_js_syntax::JsVariableDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsForVariableDeclaration { type Format = FormatRefWithRule< @@ -553,14 +701,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForVariableDeclaration { rome_js_syntax::JsForVariableDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsForVariableDeclaration { +impl IntoFormat for rome_js_syntax::JsForVariableDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsForVariableDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclarator { type Format = FormatRefWithRule< @@ -568,14 +720,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclarator { rome_js_syntax::JsVariableDeclarator, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsVariableDeclarator { +impl IntoFormat for rome_js_syntax::JsVariableDeclarator { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclarator, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsCaseClause { type Format = FormatRefWithRule< @@ -583,14 +739,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCaseClause { rome_js_syntax::JsCaseClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsCaseClause { +impl IntoFormat for rome_js_syntax::JsCaseClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsCaseClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsDefaultClause { type Format = FormatRefWithRule< @@ -598,14 +758,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDefaultClause { rome_js_syntax::JsDefaultClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsDefaultClause { +impl IntoFormat for rome_js_syntax::JsDefaultClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsDefaultClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsCatchClause { type Format = FormatRefWithRule< @@ -613,14 +777,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCatchClause { rome_js_syntax::JsCatchClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsCatchClause { +impl IntoFormat for rome_js_syntax::JsCatchClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsCatchClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsFinallyClause { type Format = FormatRefWithRule< @@ -628,14 +796,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFinallyClause { rome_js_syntax::JsFinallyClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsFinallyClause { +impl IntoFormat for rome_js_syntax::JsFinallyClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsFinallyClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsCatchDeclaration { type Format = FormatRefWithRule< @@ -643,14 +815,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCatchDeclaration { rome_js_syntax::JsCatchDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsCatchDeclaration { +impl IntoFormat for rome_js_syntax::JsCatchDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsCatchDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAnnotation { type Format = FormatRefWithRule< @@ -658,14 +834,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAnnotation { rome_js_syntax::TsTypeAnnotation, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeAnnotation { +impl IntoFormat for rome_js_syntax::TsTypeAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAnnotation, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::ImportMeta { type Format = FormatRefWithRule< @@ -673,12 +853,16 @@ impl<'a> AsFormat<'a> for rome_js_syntax::ImportMeta { rome_js_syntax::ImportMeta, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::ImportMeta { +impl IntoFormat for rome_js_syntax::ImportMeta { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayExpression { type Format = FormatRefWithRule< @@ -686,14 +870,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayExpression { rome_js_syntax::JsArrayExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayExpression { +impl IntoFormat for rome_js_syntax::JsArrayExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrowFunctionExpression { type Format = FormatRefWithRule< @@ -701,14 +889,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrowFunctionExpression { rome_js_syntax::JsArrowFunctionExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrowFunctionExpression { +impl IntoFormat for rome_js_syntax::JsArrowFunctionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrowFunctionExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsAssignmentExpression { type Format = FormatRefWithRule< @@ -716,14 +908,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAssignmentExpression { rome_js_syntax::JsAssignmentExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAssignmentExpression { +impl IntoFormat for rome_js_syntax::JsAssignmentExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsAssignmentExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsAwaitExpression { type Format = FormatRefWithRule< @@ -731,14 +927,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAwaitExpression { rome_js_syntax::JsAwaitExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAwaitExpression { +impl IntoFormat for rome_js_syntax::JsAwaitExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsAwaitExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsBinaryExpression { type Format = FormatRefWithRule< @@ -746,14 +946,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBinaryExpression { rome_js_syntax::JsBinaryExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsBinaryExpression { +impl IntoFormat for rome_js_syntax::JsBinaryExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsBinaryExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsCallExpression { type Format = FormatRefWithRule< @@ -761,14 +965,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCallExpression { rome_js_syntax::JsCallExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsCallExpression { +impl IntoFormat for rome_js_syntax::JsCallExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsCallExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsClassExpression { type Format = FormatRefWithRule< @@ -776,14 +984,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassExpression { rome_js_syntax::JsClassExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsClassExpression { +impl IntoFormat for rome_js_syntax::JsClassExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsClassExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberExpression { type Format = FormatRefWithRule< @@ -791,14 +1003,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberExpression { rome_js_syntax::JsComputedMemberExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsComputedMemberExpression { +impl IntoFormat for rome_js_syntax::JsComputedMemberExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsComputedMemberExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsConditionalExpression { type Format = FormatRefWithRule< @@ -806,14 +1022,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConditionalExpression { rome_js_syntax::JsConditionalExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsConditionalExpression { +impl IntoFormat for rome_js_syntax::JsConditionalExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsConditionalExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionExpression { type Format = FormatRefWithRule< @@ -821,14 +1041,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionExpression { rome_js_syntax::JsFunctionExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsFunctionExpression { +impl IntoFormat for rome_js_syntax::JsFunctionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierExpression { type Format = FormatRefWithRule< @@ -836,14 +1060,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierExpression { rome_js_syntax::JsIdentifierExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsIdentifierExpression { +impl IntoFormat for rome_js_syntax::JsIdentifierExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsIdentifierExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportCallExpression { type Format = FormatRefWithRule< @@ -851,14 +1079,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportCallExpression { rome_js_syntax::JsImportCallExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportCallExpression { +impl IntoFormat for rome_js_syntax::JsImportCallExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportCallExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsInExpression { type Format = FormatRefWithRule< @@ -866,14 +1098,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsInExpression { rome_js_syntax::JsInExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsInExpression { +impl IntoFormat for rome_js_syntax::JsInExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsInExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsInstanceofExpression { type Format = FormatRefWithRule< @@ -881,14 +1117,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsInstanceofExpression { rome_js_syntax::JsInstanceofExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsInstanceofExpression { +impl IntoFormat for rome_js_syntax::JsInstanceofExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsInstanceofExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsLogicalExpression { type Format = FormatRefWithRule< @@ -896,14 +1136,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLogicalExpression { rome_js_syntax::JsLogicalExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsLogicalExpression { +impl IntoFormat for rome_js_syntax::JsLogicalExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsLogicalExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsNewExpression { type Format = FormatRefWithRule< @@ -911,14 +1155,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNewExpression { rome_js_syntax::JsNewExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNewExpression { +impl IntoFormat for rome_js_syntax::JsNewExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsNewExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectExpression { type Format = FormatRefWithRule< @@ -926,14 +1174,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectExpression { rome_js_syntax::JsObjectExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectExpression { +impl IntoFormat for rome_js_syntax::JsObjectExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsParenthesizedExpression { type Format = FormatRefWithRule< @@ -941,14 +1193,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParenthesizedExpression { rome_js_syntax::JsParenthesizedExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsParenthesizedExpression { +impl IntoFormat for rome_js_syntax::JsParenthesizedExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsParenthesizedExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsPostUpdateExpression { type Format = FormatRefWithRule< @@ -956,14 +1212,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPostUpdateExpression { rome_js_syntax::JsPostUpdateExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPostUpdateExpression { +impl IntoFormat for rome_js_syntax::JsPostUpdateExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsPostUpdateExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsPreUpdateExpression { type Format = FormatRefWithRule< @@ -971,14 +1231,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPreUpdateExpression { rome_js_syntax::JsPreUpdateExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPreUpdateExpression { +impl IntoFormat for rome_js_syntax::JsPreUpdateExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsPreUpdateExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsSequenceExpression { type Format = FormatRefWithRule< @@ -986,14 +1250,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSequenceExpression { rome_js_syntax::JsSequenceExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSequenceExpression { +impl IntoFormat for rome_js_syntax::JsSequenceExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsSequenceExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticMemberExpression { type Format = FormatRefWithRule< @@ -1001,14 +1269,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticMemberExpression { rome_js_syntax::JsStaticMemberExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsStaticMemberExpression { +impl IntoFormat for rome_js_syntax::JsStaticMemberExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticMemberExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsSuperExpression { type Format = FormatRefWithRule< @@ -1016,14 +1288,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSuperExpression { rome_js_syntax::JsSuperExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSuperExpression { +impl IntoFormat for rome_js_syntax::JsSuperExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsSuperExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsThisExpression { type Format = FormatRefWithRule< @@ -1031,14 +1307,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsThisExpression { rome_js_syntax::JsThisExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsThisExpression { +impl IntoFormat for rome_js_syntax::JsThisExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsThisExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnaryExpression { type Format = FormatRefWithRule< @@ -1046,14 +1326,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnaryExpression { rome_js_syntax::JsUnaryExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnaryExpression { +impl IntoFormat for rome_js_syntax::JsUnaryExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnaryExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsYieldExpression { type Format = FormatRefWithRule< @@ -1061,24 +1345,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsYieldExpression { rome_js_syntax::JsYieldExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsYieldExpression { +impl IntoFormat for rome_js_syntax::JsYieldExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsYieldExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::NewTarget { type Format = FormatRefWithRule<'a, rome_js_syntax::NewTarget, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::NewTarget { +impl IntoFormat for rome_js_syntax::NewTarget { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplate { type Format = FormatRefWithRule< @@ -1086,12 +1378,16 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplate { rome_js_syntax::JsTemplate, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsTemplate { +impl IntoFormat for rome_js_syntax::JsTemplate { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAssertionExpression { type Format = FormatRefWithRule< @@ -1099,14 +1395,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAssertionExpression { rome_js_syntax::TsTypeAssertionExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeAssertionExpression { +impl IntoFormat for rome_js_syntax::TsTypeAssertionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAssertionExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAsExpression { type Format = FormatRefWithRule< @@ -1114,14 +1414,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAsExpression { rome_js_syntax::TsAsExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAsExpression { +impl IntoFormat for rome_js_syntax::TsAsExpression { type Format = FormatOwnedWithRule< rome_js_syntax::TsAsExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNonNullAssertionExpression { type Format = FormatRefWithRule< @@ -1129,14 +1433,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNonNullAssertionExpression { rome_js_syntax::TsNonNullAssertionExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNonNullAssertionExpression { +impl IntoFormat for rome_js_syntax::TsNonNullAssertionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::TsNonNullAssertionExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxTagExpression { type Format = FormatRefWithRule< @@ -1144,14 +1452,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxTagExpression { rome_js_syntax::JsxTagExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxTagExpression { +impl IntoFormat for rome_js_syntax::JsxTagExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsxTagExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeArguments { type Format = FormatRefWithRule< @@ -1159,14 +1471,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeArguments { rome_js_syntax::TsTypeArguments, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeArguments { +impl IntoFormat for rome_js_syntax::TsTypeArguments { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeArguments, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateChunkElement { type Format = FormatRefWithRule< @@ -1174,14 +1490,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateChunkElement { rome_js_syntax::JsTemplateChunkElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsTemplateChunkElement { +impl IntoFormat for rome_js_syntax::JsTemplateChunkElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTemplateChunkElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateElement { type Format = FormatRefWithRule< @@ -1189,14 +1509,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateElement { rome_js_syntax::JsTemplateElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsTemplateElement { +impl IntoFormat for rome_js_syntax::JsTemplateElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTemplateElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsCallArguments { type Format = FormatRefWithRule< @@ -1204,14 +1528,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCallArguments { rome_js_syntax::JsCallArguments, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsCallArguments { +impl IntoFormat for rome_js_syntax::JsCallArguments { type Format = FormatOwnedWithRule< rome_js_syntax::JsCallArguments, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsYieldArgument { type Format = FormatRefWithRule< @@ -1219,14 +1547,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsYieldArgument { rome_js_syntax::JsYieldArgument, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsYieldArgument { +impl IntoFormat for rome_js_syntax::JsYieldArgument { type Format = FormatOwnedWithRule< rome_js_syntax::JsYieldArgument, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameters { type Format = FormatRefWithRule< @@ -1234,14 +1566,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameters { rome_js_syntax::TsTypeParameters, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeParameters { +impl IntoFormat for rome_js_syntax::TsTypeParameters { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeParameters, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsParameters { type Format = FormatRefWithRule< @@ -1249,14 +1585,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParameters { rome_js_syntax::JsParameters, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsParameters { +impl IntoFormat for rome_js_syntax::JsParameters { type Format = FormatOwnedWithRule< rome_js_syntax::JsParameters, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsReturnTypeAnnotation { type Format = FormatRefWithRule< @@ -1264,14 +1604,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsReturnTypeAnnotation { rome_js_syntax::TsReturnTypeAnnotation, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsReturnTypeAnnotation { +impl IntoFormat for rome_js_syntax::TsReturnTypeAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsReturnTypeAnnotation, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionBody { type Format = FormatRefWithRule< @@ -1279,24 +1623,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionBody { rome_js_syntax::JsFunctionBody, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsFunctionBody { +impl IntoFormat for rome_js_syntax::JsFunctionBody { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionBody, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsSpread { type Format = FormatRefWithRule<'a, rome_js_syntax::JsSpread, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSpread { +impl IntoFormat for rome_js_syntax::JsSpread { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayHole { type Format = FormatRefWithRule< @@ -1304,14 +1656,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayHole { rome_js_syntax::JsArrayHole, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayHole { +impl IntoFormat for rome_js_syntax::JsArrayHole { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayHole, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsReferenceIdentifier { type Format = FormatRefWithRule< @@ -1319,14 +1675,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsReferenceIdentifier { rome_js_syntax::JsReferenceIdentifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsReferenceIdentifier { +impl IntoFormat for rome_js_syntax::JsReferenceIdentifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsReferenceIdentifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsPrivateName { type Format = FormatRefWithRule< @@ -1334,14 +1694,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPrivateName { rome_js_syntax::JsPrivateName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPrivateName { +impl IntoFormat for rome_js_syntax::JsPrivateName { type Format = FormatOwnedWithRule< rome_js_syntax::JsPrivateName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsLiteralMemberName { type Format = FormatRefWithRule< @@ -1349,14 +1713,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLiteralMemberName { rome_js_syntax::JsLiteralMemberName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsLiteralMemberName { +impl IntoFormat for rome_js_syntax::JsLiteralMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsLiteralMemberName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberName { type Format = FormatRefWithRule< @@ -1364,14 +1732,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberName { rome_js_syntax::JsComputedMemberName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsComputedMemberName { +impl IntoFormat for rome_js_syntax::JsComputedMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsComputedMemberName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyObjectMember { type Format = FormatRefWithRule< @@ -1379,14 +1751,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyObjectMember { rome_js_syntax::JsPropertyObjectMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPropertyObjectMember { +impl IntoFormat for rome_js_syntax::JsPropertyObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsPropertyObjectMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodObjectMember { type Format = FormatRefWithRule< @@ -1394,14 +1770,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodObjectMember { rome_js_syntax::JsMethodObjectMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsMethodObjectMember { +impl IntoFormat for rome_js_syntax::JsMethodObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsMethodObjectMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsGetterObjectMember { type Format = FormatRefWithRule< @@ -1409,14 +1789,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsGetterObjectMember { rome_js_syntax::JsGetterObjectMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsGetterObjectMember { +impl IntoFormat for rome_js_syntax::JsGetterObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsGetterObjectMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsSetterObjectMember { type Format = FormatRefWithRule< @@ -1424,14 +1808,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSetterObjectMember { rome_js_syntax::JsSetterObjectMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSetterObjectMember { +impl IntoFormat for rome_js_syntax::JsSetterObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsSetterObjectMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsShorthandPropertyObjectMember { type Format = FormatRefWithRule< @@ -1439,14 +1827,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsShorthandPropertyObjectMember { rome_js_syntax::JsShorthandPropertyObjectMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsShorthandPropertyObjectMember { +impl IntoFormat for rome_js_syntax::JsShorthandPropertyObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsShorthandPropertyObjectMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExtendsClause { type Format = FormatRefWithRule< @@ -1454,14 +1846,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExtendsClause { rome_js_syntax::JsExtendsClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExtendsClause { +impl IntoFormat for rome_js_syntax::JsExtendsClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExtendsClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsImplementsClause { type Format = FormatRefWithRule< @@ -1469,14 +1865,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImplementsClause { rome_js_syntax::TsImplementsClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsImplementsClause { +impl IntoFormat for rome_js_syntax::TsImplementsClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsImplementsClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsClassExportDefaultDeclaration { type Format = FormatRefWithRule< @@ -1484,14 +1884,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassExportDefaultDeclaration { rome_js_syntax::JsClassExportDefaultDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsClassExportDefaultDeclaration { +impl IntoFormat for rome_js_syntax::JsClassExportDefaultDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsClassExportDefaultDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsPrivateClassMemberName { type Format = FormatRefWithRule< @@ -1499,14 +1903,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPrivateClassMemberName { rome_js_syntax::JsPrivateClassMemberName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPrivateClassMemberName { +impl IntoFormat for rome_js_syntax::JsPrivateClassMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsPrivateClassMemberName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorClassMember { type Format = FormatRefWithRule< @@ -1514,14 +1922,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorClassMember { rome_js_syntax::JsConstructorClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsConstructorClassMember { +impl IntoFormat for rome_js_syntax::JsConstructorClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticInitializationBlockClassMember { type Format = FormatRefWithRule< @@ -1529,14 +1941,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticInitializationBlockClassMember rome_js_syntax::JsStaticInitializationBlockClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsStaticInitializationBlockClassMember { +impl IntoFormat for rome_js_syntax::JsStaticInitializationBlockClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticInitializationBlockClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyClassMember { type Format = FormatRefWithRule< @@ -1544,14 +1960,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyClassMember { rome_js_syntax::JsPropertyClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPropertyClassMember { +impl IntoFormat for rome_js_syntax::JsPropertyClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsPropertyClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodClassMember { type Format = FormatRefWithRule< @@ -1559,14 +1979,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodClassMember { rome_js_syntax::JsMethodClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsMethodClassMember { +impl IntoFormat for rome_js_syntax::JsMethodClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsMethodClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsGetterClassMember { type Format = FormatRefWithRule< @@ -1574,14 +1998,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsGetterClassMember { rome_js_syntax::JsGetterClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsGetterClassMember { +impl IntoFormat for rome_js_syntax::JsGetterClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsGetterClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsSetterClassMember { type Format = FormatRefWithRule< @@ -1589,14 +2017,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSetterClassMember { rome_js_syntax::JsSetterClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSetterClassMember { +impl IntoFormat for rome_js_syntax::JsSetterClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsSetterClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructorSignatureClassMember { type Format = FormatRefWithRule< @@ -1604,14 +2036,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructorSignatureClassMember { rome_js_syntax::TsConstructorSignatureClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsConstructorSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsConstructorSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsConstructorSignatureClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureClassMember { type Format = FormatRefWithRule< @@ -1619,14 +2055,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureClassMember { rome_js_syntax::TsPropertySignatureClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsPropertySignatureClassMember { +impl IntoFormat for rome_js_syntax::TsPropertySignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertySignatureClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureClassMember { type Format = FormatRefWithRule< @@ -1634,14 +2074,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureClassMember { rome_js_syntax::TsMethodSignatureClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMethodSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsMethodSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsMethodSignatureClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsGetterSignatureClassMember { type Format = FormatRefWithRule< @@ -1649,14 +2093,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsGetterSignatureClassMember { rome_js_syntax::TsGetterSignatureClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsGetterSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsGetterSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsGetterSignatureClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsSetterSignatureClassMember { type Format = FormatRefWithRule< @@ -1664,14 +2112,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsSetterSignatureClassMember { rome_js_syntax::TsSetterSignatureClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsSetterSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsSetterSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsSetterSignatureClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureClassMember { type Format = FormatRefWithRule< @@ -1679,14 +2131,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureClassMember { rome_js_syntax::TsIndexSignatureClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsIndexSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsEmptyClassMember { type Format = FormatRefWithRule< @@ -1694,14 +2150,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsEmptyClassMember { rome_js_syntax::JsEmptyClassMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsEmptyClassMember { +impl IntoFormat for rome_js_syntax::JsEmptyClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsEmptyClassMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticModifier { type Format = FormatRefWithRule< @@ -1709,14 +2169,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticModifier { rome_js_syntax::JsStaticModifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsStaticModifier { +impl IntoFormat for rome_js_syntax::JsStaticModifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticModifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareModifier { type Format = FormatRefWithRule< @@ -1724,14 +2188,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareModifier { rome_js_syntax::TsDeclareModifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsDeclareModifier { +impl IntoFormat for rome_js_syntax::TsDeclareModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsDeclareModifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsReadonlyModifier { type Format = FormatRefWithRule< @@ -1739,14 +2207,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsReadonlyModifier { rome_js_syntax::TsReadonlyModifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsReadonlyModifier { +impl IntoFormat for rome_js_syntax::TsReadonlyModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsReadonlyModifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAbstractModifier { type Format = FormatRefWithRule< @@ -1754,14 +2226,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAbstractModifier { rome_js_syntax::TsAbstractModifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAbstractModifier { +impl IntoFormat for rome_js_syntax::TsAbstractModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAbstractModifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsOverrideModifier { type Format = FormatRefWithRule< @@ -1769,14 +2245,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsOverrideModifier { rome_js_syntax::TsOverrideModifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsOverrideModifier { +impl IntoFormat for rome_js_syntax::TsOverrideModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsOverrideModifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAccessibilityModifier { type Format = FormatRefWithRule< @@ -1784,14 +2264,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAccessibilityModifier { rome_js_syntax::TsAccessibilityModifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAccessibilityModifier { +impl IntoFormat for rome_js_syntax::TsAccessibilityModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAccessibilityModifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorParameters { type Format = FormatRefWithRule< @@ -1799,14 +2283,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorParameters { rome_js_syntax::JsConstructorParameters, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsConstructorParameters { +impl IntoFormat for rome_js_syntax::JsConstructorParameters { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorParameters, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsRestParameter { type Format = FormatRefWithRule< @@ -1814,14 +2302,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsRestParameter { rome_js_syntax::JsRestParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsRestParameter { +impl IntoFormat for rome_js_syntax::JsRestParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsRestParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertyParameter { type Format = FormatRefWithRule< @@ -1829,14 +2321,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertyParameter { rome_js_syntax::TsPropertyParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsPropertyParameter { +impl IntoFormat for rome_js_syntax::TsPropertyParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertyParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsInitializerClause { type Format = FormatRefWithRule< @@ -1844,14 +2340,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsInitializerClause { rome_js_syntax::JsInitializerClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsInitializerClause { +impl IntoFormat for rome_js_syntax::JsInitializerClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsInitializerClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsOptionalPropertyAnnotation { type Format = FormatRefWithRule< @@ -1859,14 +2359,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsOptionalPropertyAnnotation { rome_js_syntax::TsOptionalPropertyAnnotation, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsOptionalPropertyAnnotation { +impl IntoFormat for rome_js_syntax::TsOptionalPropertyAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsOptionalPropertyAnnotation, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsDefinitePropertyAnnotation { type Format = FormatRefWithRule< @@ -1874,14 +2378,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDefinitePropertyAnnotation { rome_js_syntax::TsDefinitePropertyAnnotation, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsDefinitePropertyAnnotation { +impl IntoFormat for rome_js_syntax::TsDefinitePropertyAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsDefinitePropertyAnnotation, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureParameter { type Format = FormatRefWithRule< @@ -1889,14 +2397,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureParameter { rome_js_syntax::TsIndexSignatureParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureParameter { +impl IntoFormat for rome_js_syntax::TsIndexSignatureParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierAssignment { type Format = FormatRefWithRule< @@ -1904,14 +2416,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierAssignment { rome_js_syntax::JsIdentifierAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsIdentifierAssignment { +impl IntoFormat for rome_js_syntax::JsIdentifierAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsIdentifierAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticMemberAssignment { type Format = FormatRefWithRule< @@ -1919,14 +2435,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticMemberAssignment { rome_js_syntax::JsStaticMemberAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsStaticMemberAssignment { +impl IntoFormat for rome_js_syntax::JsStaticMemberAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticMemberAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberAssignment { type Format = FormatRefWithRule< @@ -1934,14 +2454,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberAssignment { rome_js_syntax::JsComputedMemberAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsComputedMemberAssignment { +impl IntoFormat for rome_js_syntax::JsComputedMemberAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsComputedMemberAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsParenthesizedAssignment { type Format = FormatRefWithRule< @@ -1949,14 +2473,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParenthesizedAssignment { rome_js_syntax::JsParenthesizedAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsParenthesizedAssignment { +impl IntoFormat for rome_js_syntax::JsParenthesizedAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsParenthesizedAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNonNullAssertionAssignment { type Format = FormatRefWithRule< @@ -1964,14 +2492,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNonNullAssertionAssignment { rome_js_syntax::TsNonNullAssertionAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNonNullAssertionAssignment { +impl IntoFormat for rome_js_syntax::TsNonNullAssertionAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::TsNonNullAssertionAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAsAssignment { type Format = FormatRefWithRule< @@ -1979,14 +2511,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAsAssignment { rome_js_syntax::TsAsAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAsAssignment { +impl IntoFormat for rome_js_syntax::TsAsAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::TsAsAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAssertionAssignment { type Format = FormatRefWithRule< @@ -1994,14 +2530,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAssertionAssignment { rome_js_syntax::TsTypeAssertionAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeAssertionAssignment { +impl IntoFormat for rome_js_syntax::TsTypeAssertionAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAssertionAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsAssignmentWithDefault { type Format = FormatRefWithRule< @@ -2009,14 +2549,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAssignmentWithDefault { rome_js_syntax::JsAssignmentWithDefault, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAssignmentWithDefault { +impl IntoFormat for rome_js_syntax::JsAssignmentWithDefault { type Format = FormatOwnedWithRule< rome_js_syntax::JsAssignmentWithDefault, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPattern { type Format = FormatRefWithRule< @@ -2024,14 +2568,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPattern { rome_js_syntax::JsArrayAssignmentPattern, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayAssignmentPattern { +impl IntoFormat for rome_js_syntax::JsArrayAssignmentPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayAssignmentPattern, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPattern { type Format = FormatRefWithRule< @@ -2039,14 +2587,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPattern { rome_js_syntax::JsObjectAssignmentPattern, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPattern { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPattern, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPatternRestElement { type Format = FormatRefWithRule< @@ -2054,14 +2606,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPatternRestElement { rome_js_syntax::JsArrayAssignmentPatternRestElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternRestElement { +impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternRestElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayAssignmentPatternRestElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternShorthandProperty { type Format = FormatRefWithRule< @@ -2069,14 +2625,20 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternShorthandProp rome_js_syntax::JsObjectAssignmentPatternShorthandProperty, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternShorthandProperty { +impl IntoFormat + for rome_js_syntax::JsObjectAssignmentPatternShorthandProperty +{ type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternShorthandProperty, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternProperty { type Format = FormatRefWithRule< @@ -2084,14 +2646,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternProperty { rome_js_syntax::JsObjectAssignmentPatternProperty, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternProperty { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternProperty { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternProperty, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternRest { type Format = FormatRefWithRule< @@ -2099,14 +2665,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternRest { rome_js_syntax::JsObjectAssignmentPatternRest, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternRest { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternRest { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternRest, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierBinding { type Format = FormatRefWithRule< @@ -2114,14 +2684,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierBinding { rome_js_syntax::JsIdentifierBinding, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsIdentifierBinding { +impl IntoFormat for rome_js_syntax::JsIdentifierBinding { type Format = FormatOwnedWithRule< rome_js_syntax::JsIdentifierBinding, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsBindingPatternWithDefault { type Format = FormatRefWithRule< @@ -2129,14 +2703,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBindingPatternWithDefault { rome_js_syntax::JsBindingPatternWithDefault, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsBindingPatternWithDefault { +impl IntoFormat for rome_js_syntax::JsBindingPatternWithDefault { type Format = FormatOwnedWithRule< rome_js_syntax::JsBindingPatternWithDefault, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPattern { type Format = FormatRefWithRule< @@ -2144,14 +2722,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPattern { rome_js_syntax::JsArrayBindingPattern, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayBindingPattern { +impl IntoFormat for rome_js_syntax::JsArrayBindingPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayBindingPattern, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPattern { type Format = FormatRefWithRule< @@ -2159,14 +2741,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPattern { rome_js_syntax::JsObjectBindingPattern, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPattern { +impl IntoFormat for rome_js_syntax::JsObjectBindingPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPattern, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPatternRestElement { type Format = FormatRefWithRule< @@ -2174,14 +2760,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPatternRestElement { rome_js_syntax::JsArrayBindingPatternRestElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayBindingPatternRestElement { +impl IntoFormat for rome_js_syntax::JsArrayBindingPatternRestElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayBindingPatternRestElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternProperty { type Format = FormatRefWithRule< @@ -2189,14 +2779,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternProperty { rome_js_syntax::JsObjectBindingPatternProperty, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternProperty { +impl IntoFormat for rome_js_syntax::JsObjectBindingPatternProperty { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternProperty, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternRest { type Format = FormatRefWithRule< @@ -2204,14 +2798,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternRest { rome_js_syntax::JsObjectBindingPatternRest, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternRest { +impl IntoFormat for rome_js_syntax::JsObjectBindingPatternRest { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternRest, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternShorthandProperty { type Format = FormatRefWithRule< @@ -2219,14 +2817,20 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternShorthandPropert rome_js_syntax::JsObjectBindingPatternShorthandProperty, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternShorthandProperty { +impl IntoFormat + for rome_js_syntax::JsObjectBindingPatternShorthandProperty +{ type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternShorthandProperty, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsStringLiteralExpression { type Format = FormatRefWithRule< @@ -2234,14 +2838,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStringLiteralExpression { rome_js_syntax::JsStringLiteralExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsStringLiteralExpression { +impl IntoFormat for rome_js_syntax::JsStringLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsStringLiteralExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsNumberLiteralExpression { type Format = FormatRefWithRule< @@ -2249,14 +2857,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNumberLiteralExpression { rome_js_syntax::JsNumberLiteralExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNumberLiteralExpression { +impl IntoFormat for rome_js_syntax::JsNumberLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsNumberLiteralExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsBigIntLiteralExpression { type Format = FormatRefWithRule< @@ -2264,14 +2876,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBigIntLiteralExpression { rome_js_syntax::JsBigIntLiteralExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsBigIntLiteralExpression { +impl IntoFormat for rome_js_syntax::JsBigIntLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsBigIntLiteralExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsBooleanLiteralExpression { type Format = FormatRefWithRule< @@ -2279,14 +2895,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBooleanLiteralExpression { rome_js_syntax::JsBooleanLiteralExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsBooleanLiteralExpression { +impl IntoFormat for rome_js_syntax::JsBooleanLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsBooleanLiteralExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsNullLiteralExpression { type Format = FormatRefWithRule< @@ -2294,14 +2914,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNullLiteralExpression { rome_js_syntax::JsNullLiteralExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNullLiteralExpression { +impl IntoFormat for rome_js_syntax::JsNullLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsNullLiteralExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsRegexLiteralExpression { type Format = FormatRefWithRule< @@ -2309,14 +2933,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsRegexLiteralExpression { rome_js_syntax::JsRegexLiteralExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsRegexLiteralExpression { +impl IntoFormat for rome_js_syntax::JsRegexLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsRegexLiteralExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclarationClause { type Format = FormatRefWithRule< @@ -2324,14 +2952,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclarationClause { rome_js_syntax::JsVariableDeclarationClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsVariableDeclarationClause { +impl IntoFormat for rome_js_syntax::JsVariableDeclarationClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclarationClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsDefiniteVariableAnnotation { type Format = FormatRefWithRule< @@ -2339,34 +2971,46 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDefiniteVariableAnnotation { rome_js_syntax::TsDefiniteVariableAnnotation, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsDefiniteVariableAnnotation { +impl IntoFormat for rome_js_syntax::TsDefiniteVariableAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsDefiniteVariableAnnotation, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExport { type Format = FormatRefWithRule<'a, rome_js_syntax::JsExport, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExport { +impl IntoFormat for rome_js_syntax::JsExport { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImport { type Format = FormatRefWithRule<'a, rome_js_syntax::JsImport, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImport { +impl IntoFormat for rome_js_syntax::JsImport { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportBareClause { type Format = FormatRefWithRule< @@ -2374,14 +3018,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportBareClause { rome_js_syntax::JsImportBareClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportBareClause { +impl IntoFormat for rome_js_syntax::JsImportBareClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportBareClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportNamedClause { type Format = FormatRefWithRule< @@ -2389,14 +3037,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportNamedClause { rome_js_syntax::JsImportNamedClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportNamedClause { +impl IntoFormat for rome_js_syntax::JsImportNamedClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportNamedClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportDefaultClause { type Format = FormatRefWithRule< @@ -2404,14 +3056,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportDefaultClause { rome_js_syntax::JsImportDefaultClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportDefaultClause { +impl IntoFormat for rome_js_syntax::JsImportDefaultClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportDefaultClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportNamespaceClause { type Format = FormatRefWithRule< @@ -2419,14 +3075,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportNamespaceClause { rome_js_syntax::JsImportNamespaceClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportNamespaceClause { +impl IntoFormat for rome_js_syntax::JsImportNamespaceClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportNamespaceClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsModuleSource { type Format = FormatRefWithRule< @@ -2434,14 +3094,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsModuleSource { rome_js_syntax::JsModuleSource, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsModuleSource { +impl IntoFormat for rome_js_syntax::JsModuleSource { type Format = FormatOwnedWithRule< rome_js_syntax::JsModuleSource, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertion { type Format = FormatRefWithRule< @@ -2449,14 +3113,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertion { rome_js_syntax::JsImportAssertion, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportAssertion { +impl IntoFormat for rome_js_syntax::JsImportAssertion { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportAssertion, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsDefaultImportSpecifier { type Format = FormatRefWithRule< @@ -2464,14 +3132,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDefaultImportSpecifier { rome_js_syntax::JsDefaultImportSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsDefaultImportSpecifier { +impl IntoFormat for rome_js_syntax::JsDefaultImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsDefaultImportSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifiers { type Format = FormatRefWithRule< @@ -2479,14 +3151,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifiers { rome_js_syntax::JsNamedImportSpecifiers, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNamedImportSpecifiers { +impl IntoFormat for rome_js_syntax::JsNamedImportSpecifiers { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamedImportSpecifiers, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsNamespaceImportSpecifier { type Format = FormatRefWithRule< @@ -2494,14 +3170,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamespaceImportSpecifier { rome_js_syntax::JsNamespaceImportSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNamespaceImportSpecifier { +impl IntoFormat for rome_js_syntax::JsNamespaceImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamespaceImportSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsShorthandNamedImportSpecifier { type Format = FormatRefWithRule< @@ -2509,14 +3189,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsShorthandNamedImportSpecifier { rome_js_syntax::JsShorthandNamedImportSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsShorthandNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsShorthandNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsShorthandNamedImportSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifier { type Format = FormatRefWithRule< @@ -2524,14 +3208,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifier { rome_js_syntax::JsNamedImportSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamedImportSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsLiteralExportName { type Format = FormatRefWithRule< @@ -2539,14 +3227,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLiteralExportName { rome_js_syntax::JsLiteralExportName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsLiteralExportName { +impl IntoFormat for rome_js_syntax::JsLiteralExportName { type Format = FormatOwnedWithRule< rome_js_syntax::JsLiteralExportName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertionEntry { type Format = FormatRefWithRule< @@ -2554,14 +3246,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertionEntry { rome_js_syntax::JsImportAssertionEntry, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportAssertionEntry { +impl IntoFormat for rome_js_syntax::JsImportAssertionEntry { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportAssertionEntry, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportDefaultDeclarationClause { type Format = FormatRefWithRule< @@ -2569,14 +3265,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportDefaultDeclarationClause { rome_js_syntax::JsExportDefaultDeclarationClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportDefaultDeclarationClause { +impl IntoFormat for rome_js_syntax::JsExportDefaultDeclarationClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportDefaultDeclarationClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportDefaultExpressionClause { type Format = FormatRefWithRule< @@ -2584,14 +3284,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportDefaultExpressionClause { rome_js_syntax::JsExportDefaultExpressionClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportDefaultExpressionClause { +impl IntoFormat for rome_js_syntax::JsExportDefaultExpressionClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportDefaultExpressionClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedClause { type Format = FormatRefWithRule< @@ -2599,14 +3303,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedClause { rome_js_syntax::JsExportNamedClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedClause { +impl IntoFormat for rome_js_syntax::JsExportNamedClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportFromClause { type Format = FormatRefWithRule< @@ -2614,14 +3322,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportFromClause { rome_js_syntax::JsExportFromClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportFromClause { +impl IntoFormat for rome_js_syntax::JsExportFromClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportFromClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromClause { type Format = FormatRefWithRule< @@ -2629,14 +3341,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromClause { rome_js_syntax::JsExportNamedFromClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedFromClause { +impl IntoFormat for rome_js_syntax::JsExportNamedFromClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedFromClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsExportAsNamespaceClause { type Format = FormatRefWithRule< @@ -2644,14 +3360,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExportAsNamespaceClause { rome_js_syntax::TsExportAsNamespaceClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsExportAsNamespaceClause { +impl IntoFormat for rome_js_syntax::TsExportAsNamespaceClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExportAsNamespaceClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsExportAssignmentClause { type Format = FormatRefWithRule< @@ -2659,14 +3379,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExportAssignmentClause { rome_js_syntax::TsExportAssignmentClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsExportAssignmentClause { +impl IntoFormat for rome_js_syntax::TsExportAssignmentClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExportAssignmentClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsExportDeclareClause { type Format = FormatRefWithRule< @@ -2674,14 +3398,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExportDeclareClause { rome_js_syntax::TsExportDeclareClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsExportDeclareClause { +impl IntoFormat for rome_js_syntax::TsExportDeclareClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExportDeclareClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionExportDefaultDeclaration { type Format = FormatRefWithRule< @@ -2689,14 +3417,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionExportDefaultDeclaration { rome_js_syntax::JsFunctionExportDefaultDeclaration, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsFunctionExportDefaultDeclaration { +impl IntoFormat for rome_js_syntax::JsFunctionExportDefaultDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionExportDefaultDeclaration, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedShorthandSpecifier { type Format = FormatRefWithRule< @@ -2704,14 +3436,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedShorthandSpecifier { rome_js_syntax::JsExportNamedShorthandSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedShorthandSpecifier { +impl IntoFormat for rome_js_syntax::JsExportNamedShorthandSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedShorthandSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedSpecifier { type Format = FormatRefWithRule< @@ -2719,14 +3455,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedSpecifier { rome_js_syntax::JsExportNamedSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedSpecifier { +impl IntoFormat for rome_js_syntax::JsExportNamedSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportAsClause { type Format = FormatRefWithRule< @@ -2734,14 +3474,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportAsClause { rome_js_syntax::JsExportAsClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportAsClause { +impl IntoFormat for rome_js_syntax::JsExportAsClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportAsClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromSpecifier { type Format = FormatRefWithRule< @@ -2749,24 +3493,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromSpecifier { rome_js_syntax::JsExportNamedFromSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifier { +impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedFromSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsName, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsName { +impl IntoFormat for rome_js_syntax::JsName { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsFormalParameter { type Format = FormatRefWithRule< @@ -2774,14 +3526,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFormalParameter { rome_js_syntax::JsFormalParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsFormalParameter { +impl IntoFormat for rome_js_syntax::JsFormalParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsFormalParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsThisParameter { type Format = FormatRefWithRule< @@ -2789,24 +3545,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsThisParameter { rome_js_syntax::TsThisParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsThisParameter { +impl IntoFormat for rome_js_syntax::TsThisParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsThisParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyType { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyType, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyType { +impl IntoFormat for rome_js_syntax::TsAnyType { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsUnknownType { type Format = FormatRefWithRule< @@ -2814,14 +3578,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUnknownType { rome_js_syntax::TsUnknownType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsUnknownType { +impl IntoFormat for rome_js_syntax::TsUnknownType { type Format = FormatOwnedWithRule< rome_js_syntax::TsUnknownType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNumberType { type Format = FormatRefWithRule< @@ -2829,14 +3597,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNumberType { rome_js_syntax::TsNumberType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNumberType { +impl IntoFormat for rome_js_syntax::TsNumberType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNumberType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsBooleanType { type Format = FormatRefWithRule< @@ -2844,14 +3616,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBooleanType { rome_js_syntax::TsBooleanType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsBooleanType { +impl IntoFormat for rome_js_syntax::TsBooleanType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBooleanType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsBigintType { type Format = FormatRefWithRule< @@ -2859,14 +3635,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBigintType { rome_js_syntax::TsBigintType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsBigintType { +impl IntoFormat for rome_js_syntax::TsBigintType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBigintType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsStringType { type Format = FormatRefWithRule< @@ -2874,14 +3654,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsStringType { rome_js_syntax::TsStringType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsStringType { +impl IntoFormat for rome_js_syntax::TsStringType { type Format = FormatOwnedWithRule< rome_js_syntax::TsStringType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsSymbolType { type Format = FormatRefWithRule< @@ -2889,14 +3673,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsSymbolType { rome_js_syntax::TsSymbolType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsSymbolType { +impl IntoFormat for rome_js_syntax::TsSymbolType { type Format = FormatOwnedWithRule< rome_js_syntax::TsSymbolType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsVoidType { type Format = FormatRefWithRule< @@ -2904,12 +3692,16 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsVoidType { rome_js_syntax::TsVoidType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsVoidType { +impl IntoFormat for rome_js_syntax::TsVoidType { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsUndefinedType { type Format = FormatRefWithRule< @@ -2917,14 +3709,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUndefinedType { rome_js_syntax::TsUndefinedType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsUndefinedType { +impl IntoFormat for rome_js_syntax::TsUndefinedType { type Format = FormatOwnedWithRule< rome_js_syntax::TsUndefinedType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNeverType { type Format = FormatRefWithRule< @@ -2932,14 +3728,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNeverType { rome_js_syntax::TsNeverType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNeverType { +impl IntoFormat for rome_js_syntax::TsNeverType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNeverType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsParenthesizedType { type Format = FormatRefWithRule< @@ -2947,14 +3747,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsParenthesizedType { rome_js_syntax::TsParenthesizedType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsParenthesizedType { +impl IntoFormat for rome_js_syntax::TsParenthesizedType { type Format = FormatOwnedWithRule< rome_js_syntax::TsParenthesizedType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsReferenceType { type Format = FormatRefWithRule< @@ -2962,14 +3766,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsReferenceType { rome_js_syntax::TsReferenceType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsReferenceType { +impl IntoFormat for rome_js_syntax::TsReferenceType { type Format = FormatOwnedWithRule< rome_js_syntax::TsReferenceType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsArrayType { type Format = FormatRefWithRule< @@ -2977,14 +3785,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsArrayType { rome_js_syntax::TsArrayType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsArrayType { +impl IntoFormat for rome_js_syntax::TsArrayType { type Format = FormatOwnedWithRule< rome_js_syntax::TsArrayType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTupleType { type Format = FormatRefWithRule< @@ -2992,14 +3804,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTupleType { rome_js_syntax::TsTupleType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTupleType { +impl IntoFormat for rome_js_syntax::TsTupleType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTupleType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeofType { type Format = FormatRefWithRule< @@ -3007,14 +3823,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeofType { rome_js_syntax::TsTypeofType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeofType { +impl IntoFormat for rome_js_syntax::TsTypeofType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeofType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsImportType { type Format = FormatRefWithRule< @@ -3022,14 +3842,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImportType { rome_js_syntax::TsImportType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsImportType { +impl IntoFormat for rome_js_syntax::TsImportType { type Format = FormatOwnedWithRule< rome_js_syntax::TsImportType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeOperatorType { type Format = FormatRefWithRule< @@ -3037,14 +3861,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeOperatorType { rome_js_syntax::TsTypeOperatorType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeOperatorType { +impl IntoFormat for rome_js_syntax::TsTypeOperatorType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeOperatorType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexedAccessType { type Format = FormatRefWithRule< @@ -3052,14 +3880,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexedAccessType { rome_js_syntax::TsIndexedAccessType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIndexedAccessType { +impl IntoFormat for rome_js_syntax::TsIndexedAccessType { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexedAccessType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedType { type Format = FormatRefWithRule< @@ -3067,14 +3899,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedType { rome_js_syntax::TsMappedType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMappedType { +impl IntoFormat for rome_js_syntax::TsMappedType { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsObjectType { type Format = FormatRefWithRule< @@ -3082,14 +3918,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsObjectType { rome_js_syntax::TsObjectType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsObjectType { +impl IntoFormat for rome_js_syntax::TsObjectType { type Format = FormatOwnedWithRule< rome_js_syntax::TsObjectType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNonPrimitiveType { type Format = FormatRefWithRule< @@ -3097,14 +3937,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNonPrimitiveType { rome_js_syntax::TsNonPrimitiveType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNonPrimitiveType { +impl IntoFormat for rome_js_syntax::TsNonPrimitiveType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNonPrimitiveType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsThisType { type Format = FormatRefWithRule< @@ -3112,12 +3956,16 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsThisType { rome_js_syntax::TsThisType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsThisType { +impl IntoFormat for rome_js_syntax::TsThisType { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNumberLiteralType { type Format = FormatRefWithRule< @@ -3125,14 +3973,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNumberLiteralType { rome_js_syntax::TsNumberLiteralType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNumberLiteralType { +impl IntoFormat for rome_js_syntax::TsNumberLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNumberLiteralType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsBigIntLiteralType { type Format = FormatRefWithRule< @@ -3140,14 +3992,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBigIntLiteralType { rome_js_syntax::TsBigIntLiteralType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsBigIntLiteralType { +impl IntoFormat for rome_js_syntax::TsBigIntLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBigIntLiteralType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsStringLiteralType { type Format = FormatRefWithRule< @@ -3155,14 +4011,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsStringLiteralType { rome_js_syntax::TsStringLiteralType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsStringLiteralType { +impl IntoFormat for rome_js_syntax::TsStringLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsStringLiteralType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNullLiteralType { type Format = FormatRefWithRule< @@ -3170,14 +4030,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNullLiteralType { rome_js_syntax::TsNullLiteralType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNullLiteralType { +impl IntoFormat for rome_js_syntax::TsNullLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNullLiteralType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsBooleanLiteralType { type Format = FormatRefWithRule< @@ -3185,14 +4049,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBooleanLiteralType { rome_js_syntax::TsBooleanLiteralType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsBooleanLiteralType { +impl IntoFormat for rome_js_syntax::TsBooleanLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBooleanLiteralType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateLiteralType { type Format = FormatRefWithRule< @@ -3200,14 +4068,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateLiteralType { rome_js_syntax::TsTemplateLiteralType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTemplateLiteralType { +impl IntoFormat for rome_js_syntax::TsTemplateLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTemplateLiteralType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsInferType { type Format = FormatRefWithRule< @@ -3215,14 +4087,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsInferType { rome_js_syntax::TsInferType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsInferType { +impl IntoFormat for rome_js_syntax::TsInferType { type Format = FormatOwnedWithRule< rome_js_syntax::TsInferType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsIntersectionType { type Format = FormatRefWithRule< @@ -3230,14 +4106,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIntersectionType { rome_js_syntax::TsIntersectionType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIntersectionType { +impl IntoFormat for rome_js_syntax::TsIntersectionType { type Format = FormatOwnedWithRule< rome_js_syntax::TsIntersectionType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsUnionType { type Format = FormatRefWithRule< @@ -3245,14 +4125,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUnionType { rome_js_syntax::TsUnionType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsUnionType { +impl IntoFormat for rome_js_syntax::TsUnionType { type Format = FormatOwnedWithRule< rome_js_syntax::TsUnionType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsFunctionType { type Format = FormatRefWithRule< @@ -3260,14 +4144,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsFunctionType { rome_js_syntax::TsFunctionType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsFunctionType { +impl IntoFormat for rome_js_syntax::TsFunctionType { type Format = FormatOwnedWithRule< rome_js_syntax::TsFunctionType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructorType { type Format = FormatRefWithRule< @@ -3275,14 +4163,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructorType { rome_js_syntax::TsConstructorType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsConstructorType { +impl IntoFormat for rome_js_syntax::TsConstructorType { type Format = FormatOwnedWithRule< rome_js_syntax::TsConstructorType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsConditionalType { type Format = FormatRefWithRule< @@ -3290,14 +4182,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConditionalType { rome_js_syntax::TsConditionalType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsConditionalType { +impl IntoFormat for rome_js_syntax::TsConditionalType { type Format = FormatOwnedWithRule< rome_js_syntax::TsConditionalType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsIdentifierBinding { type Format = FormatRefWithRule< @@ -3305,14 +4201,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIdentifierBinding { rome_js_syntax::TsIdentifierBinding, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIdentifierBinding { +impl IntoFormat for rome_js_syntax::TsIdentifierBinding { type Format = FormatOwnedWithRule< rome_js_syntax::TsIdentifierBinding, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumMember { type Format = FormatRefWithRule< @@ -3320,14 +4220,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumMember { rome_js_syntax::TsEnumMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsEnumMember { +impl IntoFormat for rome_js_syntax::TsEnumMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsEnumMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsExternalModuleReference { type Format = FormatRefWithRule< @@ -3335,14 +4239,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExternalModuleReference { rome_js_syntax::TsExternalModuleReference, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsExternalModuleReference { +impl IntoFormat for rome_js_syntax::TsExternalModuleReference { type Format = FormatOwnedWithRule< rome_js_syntax::TsExternalModuleReference, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsModuleBlock { type Format = FormatRefWithRule< @@ -3350,14 +4258,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsModuleBlock { rome_js_syntax::TsModuleBlock, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsModuleBlock { +impl IntoFormat for rome_js_syntax::TsModuleBlock { type Format = FormatOwnedWithRule< rome_js_syntax::TsModuleBlock, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsQualifiedModuleName { type Format = FormatRefWithRule< @@ -3365,14 +4277,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsQualifiedModuleName { rome_js_syntax::TsQualifiedModuleName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsQualifiedModuleName { +impl IntoFormat for rome_js_syntax::TsQualifiedModuleName { type Format = FormatOwnedWithRule< rome_js_syntax::TsQualifiedModuleName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { type Format = FormatRefWithRule< @@ -3380,14 +4296,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { rome_js_syntax::TsEmptyExternalModuleDeclarationBody, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { +impl IntoFormat for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { type Format = FormatOwnedWithRule< rome_js_syntax::TsEmptyExternalModuleDeclarationBody, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameterName { type Format = FormatRefWithRule< @@ -3395,14 +4315,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameterName { rome_js_syntax::TsTypeParameterName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeParameterName { +impl IntoFormat for rome_js_syntax::TsTypeParameterName { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeParameterName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsPredicateReturnType { type Format = FormatRefWithRule< @@ -3410,14 +4334,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPredicateReturnType { rome_js_syntax::TsPredicateReturnType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsPredicateReturnType { +impl IntoFormat for rome_js_syntax::TsPredicateReturnType { type Format = FormatOwnedWithRule< rome_js_syntax::TsPredicateReturnType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAssertsReturnType { type Format = FormatRefWithRule< @@ -3425,14 +4353,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAssertsReturnType { rome_js_syntax::TsAssertsReturnType, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAssertsReturnType { +impl IntoFormat for rome_js_syntax::TsAssertsReturnType { type Format = FormatOwnedWithRule< rome_js_syntax::TsAssertsReturnType, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsAssertsCondition { type Format = FormatRefWithRule< @@ -3440,14 +4372,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAssertsCondition { rome_js_syntax::TsAssertsCondition, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAssertsCondition { +impl IntoFormat for rome_js_syntax::TsAssertsCondition { type Format = FormatOwnedWithRule< rome_js_syntax::TsAssertsCondition, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameter { type Format = FormatRefWithRule< @@ -3455,14 +4391,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameter { rome_js_syntax::TsTypeParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeParameter { +impl IntoFormat for rome_js_syntax::TsTypeParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeConstraintClause { type Format = FormatRefWithRule< @@ -3470,14 +4410,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeConstraintClause { rome_js_syntax::TsTypeConstraintClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeConstraintClause { +impl IntoFormat for rome_js_syntax::TsTypeConstraintClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeConstraintClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsDefaultTypeClause { type Format = FormatRefWithRule< @@ -3485,14 +4429,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDefaultTypeClause { rome_js_syntax::TsDefaultTypeClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsDefaultTypeClause { +impl IntoFormat for rome_js_syntax::TsDefaultTypeClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsDefaultTypeClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsExtendsClause { type Format = FormatRefWithRule< @@ -3500,14 +4448,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExtendsClause { rome_js_syntax::TsExtendsClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsExtendsClause { +impl IntoFormat for rome_js_syntax::TsExtendsClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExtendsClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNameWithTypeArguments { type Format = FormatRefWithRule< @@ -3515,14 +4467,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNameWithTypeArguments { rome_js_syntax::TsNameWithTypeArguments, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNameWithTypeArguments { +impl IntoFormat for rome_js_syntax::TsNameWithTypeArguments { type Format = FormatOwnedWithRule< rome_js_syntax::TsNameWithTypeArguments, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsCallSignatureTypeMember { type Format = FormatRefWithRule< @@ -3530,14 +4486,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsCallSignatureTypeMember { rome_js_syntax::TsCallSignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsCallSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsCallSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsCallSignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureTypeMember { type Format = FormatRefWithRule< @@ -3545,14 +4505,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureTypeMember { rome_js_syntax::TsPropertySignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsPropertySignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsPropertySignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertySignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructSignatureTypeMember { type Format = FormatRefWithRule< @@ -3560,14 +4524,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructSignatureTypeMember { rome_js_syntax::TsConstructSignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsConstructSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsConstructSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsConstructSignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureTypeMember { type Format = FormatRefWithRule< @@ -3575,14 +4543,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureTypeMember { rome_js_syntax::TsMethodSignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMethodSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsMethodSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsMethodSignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsGetterSignatureTypeMember { type Format = FormatRefWithRule< @@ -3590,14 +4562,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsGetterSignatureTypeMember { rome_js_syntax::TsGetterSignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsGetterSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsGetterSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsGetterSignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsSetterSignatureTypeMember { type Format = FormatRefWithRule< @@ -3605,14 +4581,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsSetterSignatureTypeMember { rome_js_syntax::TsSetterSignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsSetterSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsSetterSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsSetterSignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureTypeMember { type Format = FormatRefWithRule< @@ -3620,14 +4600,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureTypeMember { rome_js_syntax::TsIndexSignatureTypeMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsIndexSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureTypeMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeReadonlyModifierClause { type Format = FormatRefWithRule< @@ -3635,14 +4619,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeReadonlyModifierClause { rome_js_syntax::TsMappedTypeReadonlyModifierClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMappedTypeReadonlyModifierClause { +impl IntoFormat for rome_js_syntax::TsMappedTypeReadonlyModifierClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedTypeReadonlyModifierClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeAsClause { type Format = FormatRefWithRule< @@ -3650,14 +4638,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeAsClause { rome_js_syntax::TsMappedTypeAsClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMappedTypeAsClause { +impl IntoFormat for rome_js_syntax::TsMappedTypeAsClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedTypeAsClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeOptionalModifierClause { type Format = FormatRefWithRule< @@ -3665,14 +4657,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeOptionalModifierClause { rome_js_syntax::TsMappedTypeOptionalModifierClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMappedTypeOptionalModifierClause { +impl IntoFormat for rome_js_syntax::TsMappedTypeOptionalModifierClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedTypeOptionalModifierClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsImportTypeQualifier { type Format = FormatRefWithRule< @@ -3680,14 +4676,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImportTypeQualifier { rome_js_syntax::TsImportTypeQualifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsImportTypeQualifier { +impl IntoFormat for rome_js_syntax::TsImportTypeQualifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsImportTypeQualifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsNamedTupleTypeElement { type Format = FormatRefWithRule< @@ -3695,14 +4695,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNamedTupleTypeElement { rome_js_syntax::TsNamedTupleTypeElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsNamedTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsNamedTupleTypeElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsNamedTupleTypeElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsRestTupleTypeElement { type Format = FormatRefWithRule< @@ -3710,14 +4714,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsRestTupleTypeElement { rome_js_syntax::TsRestTupleTypeElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsRestTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsRestTupleTypeElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsRestTupleTypeElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsOptionalTupleTypeElement { type Format = FormatRefWithRule< @@ -3725,14 +4733,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsOptionalTupleTypeElement { rome_js_syntax::TsOptionalTupleTypeElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsOptionalTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsOptionalTupleTypeElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsOptionalTupleTypeElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateChunkElement { type Format = FormatRefWithRule< @@ -3740,14 +4752,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateChunkElement { rome_js_syntax::TsTemplateChunkElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTemplateChunkElement { +impl IntoFormat for rome_js_syntax::TsTemplateChunkElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsTemplateChunkElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateElement { type Format = FormatRefWithRule< @@ -3755,14 +4771,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateElement { rome_js_syntax::TsTemplateElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTemplateElement { +impl IntoFormat for rome_js_syntax::TsTemplateElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsTemplateElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::TsQualifiedName { type Format = FormatRefWithRule< @@ -3770,14 +4790,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsQualifiedName { rome_js_syntax::TsQualifiedName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsQualifiedName { +impl IntoFormat for rome_js_syntax::TsQualifiedName { type Format = FormatOwnedWithRule< rome_js_syntax::TsQualifiedName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxElement { type Format = FormatRefWithRule< @@ -3785,12 +4809,16 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxElement { rome_js_syntax::JsxElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxElement { +impl IntoFormat for rome_js_syntax::JsxElement { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxSelfClosingElement { type Format = FormatRefWithRule< @@ -3798,14 +4826,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxSelfClosingElement { rome_js_syntax::JsxSelfClosingElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxSelfClosingElement { +impl IntoFormat for rome_js_syntax::JsxSelfClosingElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsxSelfClosingElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxFragment { type Format = FormatRefWithRule< @@ -3813,14 +4845,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxFragment { rome_js_syntax::JsxFragment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxFragment { +impl IntoFormat for rome_js_syntax::JsxFragment { type Format = FormatOwnedWithRule< rome_js_syntax::JsxFragment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxOpeningElement { type Format = FormatRefWithRule< @@ -3828,14 +4864,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxOpeningElement { rome_js_syntax::JsxOpeningElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxOpeningElement { +impl IntoFormat for rome_js_syntax::JsxOpeningElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsxOpeningElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxClosingElement { type Format = FormatRefWithRule< @@ -3843,14 +4883,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxClosingElement { rome_js_syntax::JsxClosingElement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxClosingElement { +impl IntoFormat for rome_js_syntax::JsxClosingElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsxClosingElement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxOpeningFragment { type Format = FormatRefWithRule< @@ -3858,14 +4902,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxOpeningFragment { rome_js_syntax::JsxOpeningFragment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxOpeningFragment { +impl IntoFormat for rome_js_syntax::JsxOpeningFragment { type Format = FormatOwnedWithRule< rome_js_syntax::JsxOpeningFragment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxClosingFragment { type Format = FormatRefWithRule< @@ -3873,24 +4921,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxClosingFragment { rome_js_syntax::JsxClosingFragment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxClosingFragment { +impl IntoFormat for rome_js_syntax::JsxClosingFragment { type Format = FormatOwnedWithRule< rome_js_syntax::JsxClosingFragment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxName, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxName { +impl IntoFormat for rome_js_syntax::JsxName { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxReferenceIdentifier { type Format = FormatRefWithRule< @@ -3898,14 +4954,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxReferenceIdentifier { rome_js_syntax::JsxReferenceIdentifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxReferenceIdentifier { +impl IntoFormat for rome_js_syntax::JsxReferenceIdentifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsxReferenceIdentifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxNamespaceName { type Format = FormatRefWithRule< @@ -3913,14 +4973,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxNamespaceName { rome_js_syntax::JsxNamespaceName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxNamespaceName { +impl IntoFormat for rome_js_syntax::JsxNamespaceName { type Format = FormatOwnedWithRule< rome_js_syntax::JsxNamespaceName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxMemberName { type Format = FormatRefWithRule< @@ -3928,14 +4992,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxMemberName { rome_js_syntax::JsxMemberName, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxMemberName { +impl IntoFormat for rome_js_syntax::JsxMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsxMemberName, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttribute { type Format = FormatRefWithRule< @@ -3943,14 +5011,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttribute { rome_js_syntax::JsxAttribute, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAttribute { +impl IntoFormat for rome_js_syntax::JsxAttribute { type Format = FormatOwnedWithRule< rome_js_syntax::JsxAttribute, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxSpreadAttribute { type Format = FormatRefWithRule< @@ -3958,14 +5030,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxSpreadAttribute { rome_js_syntax::JsxSpreadAttribute, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxSpreadAttribute { +impl IntoFormat for rome_js_syntax::JsxSpreadAttribute { type Format = FormatOwnedWithRule< rome_js_syntax::JsxSpreadAttribute, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttributeInitializerClause { type Format = FormatRefWithRule< @@ -3973,24 +5049,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttributeInitializerClause { rome_js_syntax::JsxAttributeInitializerClause, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAttributeInitializerClause { +impl IntoFormat for rome_js_syntax::JsxAttributeInitializerClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsxAttributeInitializerClause, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxString { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxString, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxString { +impl IntoFormat for rome_js_syntax::JsxString { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxExpressionAttributeValue { type Format = FormatRefWithRule< @@ -3998,24 +5082,32 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxExpressionAttributeValue { rome_js_syntax::JsxExpressionAttributeValue, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxExpressionAttributeValue { +impl IntoFormat for rome_js_syntax::JsxExpressionAttributeValue { type Format = FormatOwnedWithRule< rome_js_syntax::JsxExpressionAttributeValue, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxText { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxText, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxText { +impl IntoFormat for rome_js_syntax::JsxText { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxExpressionChild { type Format = FormatRefWithRule< @@ -4023,14 +5115,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxExpressionChild { rome_js_syntax::JsxExpressionChild, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxExpressionChild { +impl IntoFormat for rome_js_syntax::JsxExpressionChild { type Format = FormatOwnedWithRule< rome_js_syntax::JsxExpressionChild, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsxSpreadChild { type Format = FormatRefWithRule< @@ -4038,14 +5134,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxSpreadChild { rome_js_syntax::JsxSpreadChild, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxSpreadChild { +impl IntoFormat for rome_js_syntax::JsxSpreadChild { type Format = FormatOwnedWithRule< rome_js_syntax::JsxSpreadChild, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsArrayAssignmentPatternElementList; impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPatternElementList { @@ -4054,14 +5154,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPatternElementList { rome_js_syntax::JsArrayAssignmentPatternElementList, FormatJsArrayAssignmentPatternElementList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternElementList { +impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternElementList { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayAssignmentPatternElementList, FormatJsArrayAssignmentPatternElementList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsArrayBindingPatternElementList; impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPatternElementList { @@ -4070,43 +5174,59 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPatternElementList { rome_js_syntax::JsArrayBindingPatternElementList, FormatJsArrayBindingPatternElementList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayBindingPatternElementList { +impl IntoFormat for rome_js_syntax::JsArrayBindingPatternElementList { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayBindingPatternElementList, FormatJsArrayBindingPatternElementList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsArrayElementList; impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayElementList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsArrayElementList, FormatJsArrayElementList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsArrayElementList { +impl IntoFormat for rome_js_syntax::JsArrayElementList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsCallArgumentList; impl<'a> AsFormat<'a> for rome_js_syntax::JsCallArgumentList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsCallArgumentList, FormatJsCallArgumentList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsCallArgumentList { +impl IntoFormat for rome_js_syntax::JsCallArgumentList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsClassMemberList; impl<'a> AsFormat<'a> for rome_js_syntax::JsClassMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsClassMemberList, FormatJsClassMemberList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsClassMemberList { +impl IntoFormat for rome_js_syntax::JsClassMemberList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsConstructorModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorModifierList { @@ -4115,14 +5235,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorModifierList { rome_js_syntax::JsConstructorModifierList, FormatJsConstructorModifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsConstructorModifierList { +impl IntoFormat for rome_js_syntax::JsConstructorModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorModifierList, FormatJsConstructorModifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsConstructorParameterList; impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorParameterList { @@ -4131,23 +5255,31 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorParameterList { rome_js_syntax::JsConstructorParameterList, FormatJsConstructorParameterList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsConstructorParameterList { +impl IntoFormat for rome_js_syntax::JsConstructorParameterList { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorParameterList, FormatJsConstructorParameterList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsDirectiveList; impl<'a> AsFormat<'a> for rome_js_syntax::JsDirectiveList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsDirectiveList, FormatJsDirectiveList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsDirectiveList { +impl IntoFormat for rome_js_syntax::JsDirectiveList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsExportNamedFromSpecifierList; impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromSpecifierList { @@ -4156,14 +5288,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromSpecifierList { rome_js_syntax::JsExportNamedFromSpecifierList, FormatJsExportNamedFromSpecifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifierList { +impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedFromSpecifierList, FormatJsExportNamedFromSpecifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsExportNamedSpecifierList; impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedSpecifierList { @@ -4172,14 +5308,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedSpecifierList { rome_js_syntax::JsExportNamedSpecifierList, FormatJsExportNamedSpecifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsExportNamedSpecifierList { +impl IntoFormat for rome_js_syntax::JsExportNamedSpecifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedSpecifierList, FormatJsExportNamedSpecifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsImportAssertionEntryList; impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertionEntryList { @@ -4188,34 +5328,46 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertionEntryList { rome_js_syntax::JsImportAssertionEntryList, FormatJsImportAssertionEntryList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsImportAssertionEntryList { +impl IntoFormat for rome_js_syntax::JsImportAssertionEntryList { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportAssertionEntryList, FormatJsImportAssertionEntryList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsMethodModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodModifierList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsMethodModifierList, FormatJsMethodModifierList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsMethodModifierList { +impl IntoFormat for rome_js_syntax::JsMethodModifierList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsModuleItemList; impl<'a> AsFormat<'a> for rome_js_syntax::JsModuleItemList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsModuleItemList, FormatJsModuleItemList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsModuleItemList { +impl IntoFormat for rome_js_syntax::JsModuleItemList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsNamedImportSpecifierList; impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifierList { @@ -4224,14 +5376,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifierList { rome_js_syntax::JsNamedImportSpecifierList, FormatJsNamedImportSpecifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsNamedImportSpecifierList { +impl IntoFormat for rome_js_syntax::JsNamedImportSpecifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamedImportSpecifierList, FormatJsNamedImportSpecifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsObjectAssignmentPatternPropertyList; impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternPropertyList { @@ -4240,14 +5396,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternPropertyList rome_js_syntax::JsObjectAssignmentPatternPropertyList, FormatJsObjectAssignmentPatternPropertyList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternPropertyList { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternPropertyList { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternPropertyList, FormatJsObjectAssignmentPatternPropertyList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsObjectBindingPatternPropertyList; impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternPropertyList { @@ -4256,73 +5416,101 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternPropertyList { rome_js_syntax::JsObjectBindingPatternPropertyList, FormatJsObjectBindingPatternPropertyList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternPropertyList { +impl IntoFormat for rome_js_syntax::JsObjectBindingPatternPropertyList { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternPropertyList, FormatJsObjectBindingPatternPropertyList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsObjectMemberList; impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsObjectMemberList, FormatJsObjectMemberList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsObjectMemberList { +impl IntoFormat for rome_js_syntax::JsObjectMemberList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsParameterList; impl<'a> AsFormat<'a> for rome_js_syntax::JsParameterList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsParameterList, FormatJsParameterList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsParameterList { +impl IntoFormat for rome_js_syntax::JsParameterList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsPropertyModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyModifierList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsPropertyModifierList, FormatJsPropertyModifierList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsPropertyModifierList { +impl IntoFormat for rome_js_syntax::JsPropertyModifierList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsStatementList; impl<'a> AsFormat<'a> for rome_js_syntax::JsStatementList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsStatementList, FormatJsStatementList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsStatementList { +impl IntoFormat for rome_js_syntax::JsStatementList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsSwitchCaseList; impl<'a> AsFormat<'a> for rome_js_syntax::JsSwitchCaseList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsSwitchCaseList, FormatJsSwitchCaseList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsSwitchCaseList { +impl IntoFormat for rome_js_syntax::JsSwitchCaseList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsTemplateElementList; impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateElementList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsTemplateElementList, FormatJsTemplateElementList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsTemplateElementList { +impl IntoFormat for rome_js_syntax::JsTemplateElementList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsVariableDeclaratorList; impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclaratorList { @@ -4331,41 +5519,57 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclaratorList { rome_js_syntax::JsVariableDeclaratorList, FormatJsVariableDeclaratorList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsVariableDeclaratorList { +impl IntoFormat for rome_js_syntax::JsVariableDeclaratorList { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclaratorList, FormatJsVariableDeclaratorList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAttributeList; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttributeList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAttributeList, FormatJsxAttributeList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAttributeList { +impl IntoFormat for rome_js_syntax::JsxAttributeList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxChildList; impl<'a> AsFormat<'a> for rome_js_syntax::JsxChildList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxChildList, FormatJsxChildList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxChildList { +impl IntoFormat for rome_js_syntax::JsxChildList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsEnumMemberList; impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsEnumMemberList, FormatTsEnumMemberList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsEnumMemberList { +impl IntoFormat for rome_js_syntax::TsEnumMemberList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsIndexSignatureModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureModifierList { @@ -4374,14 +5578,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureModifierList { rome_js_syntax::TsIndexSignatureModifierList, FormatTsIndexSignatureModifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureModifierList { +impl IntoFormat for rome_js_syntax::TsIndexSignatureModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureModifierList, FormatTsIndexSignatureModifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsIntersectionTypeElementList; impl<'a> AsFormat<'a> for rome_js_syntax::TsIntersectionTypeElementList { @@ -4390,14 +5598,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIntersectionTypeElementList { rome_js_syntax::TsIntersectionTypeElementList, FormatTsIntersectionTypeElementList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsIntersectionTypeElementList { +impl IntoFormat for rome_js_syntax::TsIntersectionTypeElementList { type Format = FormatOwnedWithRule< rome_js_syntax::TsIntersectionTypeElementList, FormatTsIntersectionTypeElementList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsMethodSignatureModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureModifierList { @@ -4406,14 +5618,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureModifierList { rome_js_syntax::TsMethodSignatureModifierList, FormatTsMethodSignatureModifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsMethodSignatureModifierList { +impl IntoFormat for rome_js_syntax::TsMethodSignatureModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsMethodSignatureModifierList, FormatTsMethodSignatureModifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsPropertyParameterModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertyParameterModifierList { @@ -4422,14 +5638,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertyParameterModifierList { rome_js_syntax::TsPropertyParameterModifierList, FormatTsPropertyParameterModifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsPropertyParameterModifierList { +impl IntoFormat for rome_js_syntax::TsPropertyParameterModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertyParameterModifierList, FormatTsPropertyParameterModifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsPropertySignatureModifierList; impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureModifierList { @@ -4438,96 +5658,132 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureModifierList { rome_js_syntax::TsPropertySignatureModifierList, FormatTsPropertySignatureModifierList, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsPropertySignatureModifierList { +impl IntoFormat for rome_js_syntax::TsPropertySignatureModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertySignatureModifierList, FormatTsPropertySignatureModifierList, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsTemplateElementList; impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateElementList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTemplateElementList, FormatTsTemplateElementList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTemplateElementList { +impl IntoFormat for rome_js_syntax::TsTemplateElementList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsTupleTypeElementList; impl<'a> AsFormat<'a> for rome_js_syntax::TsTupleTypeElementList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTupleTypeElementList, FormatTsTupleTypeElementList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTupleTypeElementList { +impl IntoFormat for rome_js_syntax::TsTupleTypeElementList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsTypeArgumentList; impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeArgumentList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTypeArgumentList, FormatTsTypeArgumentList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeArgumentList { +impl IntoFormat for rome_js_syntax::TsTypeArgumentList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsTypeList; impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTypeList, FormatTsTypeList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeList { +impl IntoFormat for rome_js_syntax::TsTypeList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsTypeMemberList; impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTypeMemberList, FormatTsTypeMemberList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeMemberList { +impl IntoFormat for rome_js_syntax::TsTypeMemberList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsTypeParameterList; impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameterList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTypeParameterList, FormatTsTypeParameterList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsTypeParameterList { +impl IntoFormat for rome_js_syntax::TsTypeParameterList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsUnionTypeVariantList; impl<'a> AsFormat<'a> for rome_js_syntax::TsUnionTypeVariantList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsUnionTypeVariantList, FormatTsUnionTypeVariantList>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsUnionTypeVariantList { +impl IntoFormat for rome_js_syntax::TsUnionTypeVariantList { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknown { type Format = FormatRefWithRule<'a, rome_js_syntax::JsUnknown, FormatNodeRule>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknown { +impl IntoFormat for rome_js_syntax::JsUnknown { type Format = FormatOwnedWithRule>; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownStatement { type Format = FormatRefWithRule< @@ -4535,14 +5791,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownStatement { rome_js_syntax::JsUnknownStatement, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownStatement { +impl IntoFormat for rome_js_syntax::JsUnknownStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownStatement, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownExpression { type Format = FormatRefWithRule< @@ -4550,14 +5810,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownExpression { rome_js_syntax::JsUnknownExpression, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownExpression { +impl IntoFormat for rome_js_syntax::JsUnknownExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownExpression, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownMember { type Format = FormatRefWithRule< @@ -4565,14 +5829,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownMember { rome_js_syntax::JsUnknownMember, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownMember { +impl IntoFormat for rome_js_syntax::JsUnknownMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownMember, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownBinding { type Format = FormatRefWithRule< @@ -4580,14 +5848,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownBinding { rome_js_syntax::JsUnknownBinding, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownBinding { +impl IntoFormat for rome_js_syntax::JsUnknownBinding { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownBinding, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownAssignment { type Format = FormatRefWithRule< @@ -4595,14 +5867,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownAssignment { rome_js_syntax::JsUnknownAssignment, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownAssignment { +impl IntoFormat for rome_js_syntax::JsUnknownAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownAssignment, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownParameter { type Format = FormatRefWithRule< @@ -4610,14 +5886,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownParameter { rome_js_syntax::JsUnknownParameter, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownParameter { +impl IntoFormat for rome_js_syntax::JsUnknownParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownParameter, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownImportAssertionEntry { type Format = FormatRefWithRule< @@ -4625,14 +5905,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownImportAssertionEntry { rome_js_syntax::JsUnknownImportAssertionEntry, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownImportAssertionEntry { +impl IntoFormat for rome_js_syntax::JsUnknownImportAssertionEntry { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownImportAssertionEntry, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownNamedImportSpecifier { type Format = FormatRefWithRule< @@ -4640,52 +5924,72 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownNamedImportSpecifier { rome_js_syntax::JsUnknownNamedImportSpecifier, FormatNodeRule, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsUnknownNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsUnknownNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownNamedImportSpecifier, FormatNodeRule, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyRoot; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyRoot { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyRoot, FormatJsAnyRoot>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyRoot { +impl IntoFormat for rome_js_syntax::JsAnyRoot { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyExpression; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExpression { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyExpression, FormatJsAnyExpression>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyExpression { +impl IntoFormat for rome_js_syntax::JsAnyExpression { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyStatement; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyStatement { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyStatement, FormatJsAnyStatement>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyStatement { +impl IntoFormat for rome_js_syntax::JsAnyStatement { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyForInitializer; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyForInitializer { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyForInitializer, FormatJsAnyForInitializer>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyForInitializer { +impl IntoFormat for rome_js_syntax::JsAnyForInitializer { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyForInOrOfInitializer; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyForInOrOfInitializer { @@ -4694,87 +5998,119 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyForInOrOfInitializer { rome_js_syntax::JsAnyForInOrOfInitializer, FormatJsAnyForInOrOfInitializer, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyForInOrOfInitializer { +impl IntoFormat for rome_js_syntax::JsAnyForInOrOfInitializer { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyForInOrOfInitializer, FormatJsAnyForInOrOfInitializer, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyAssignmentPattern; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyAssignmentPattern { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyAssignmentPattern, FormatJsAnyAssignmentPattern>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyAssignmentPattern { +impl IntoFormat for rome_js_syntax::JsAnyAssignmentPattern { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnySwitchClause; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnySwitchClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnySwitchClause, FormatJsAnySwitchClause>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnySwitchClause { +impl IntoFormat for rome_js_syntax::JsAnySwitchClause { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyBindingPattern; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyBindingPattern { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyBindingPattern, FormatJsAnyBindingPattern>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyBindingPattern { +impl IntoFormat for rome_js_syntax::JsAnyBindingPattern { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyDeclarationClause; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyDeclarationClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyDeclarationClause, FormatJsAnyDeclarationClause>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyDeclarationClause { +impl IntoFormat for rome_js_syntax::JsAnyDeclarationClause { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyLiteralExpression; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyLiteralExpression { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyLiteralExpression, FormatJsAnyLiteralExpression>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyLiteralExpression { +impl IntoFormat for rome_js_syntax::JsAnyLiteralExpression { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyTemplateElement; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyTemplateElement { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyTemplateElement, FormatJsAnyTemplateElement>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyTemplateElement { +impl IntoFormat for rome_js_syntax::JsAnyTemplateElement { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyBinding; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyBinding { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyBinding, FormatJsAnyBinding>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyBinding { +impl IntoFormat for rome_js_syntax::JsAnyBinding { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyArrowFunctionParameters; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrowFunctionParameters { @@ -4783,119 +6119,167 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrowFunctionParameters { rome_js_syntax::JsAnyArrowFunctionParameters, FormatJsAnyArrowFunctionParameters, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyArrowFunctionParameters { +impl IntoFormat for rome_js_syntax::JsAnyArrowFunctionParameters { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyArrowFunctionParameters, FormatJsAnyArrowFunctionParameters, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyFunctionBody; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyFunctionBody { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyFunctionBody, FormatJsAnyFunctionBody>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyFunctionBody { +impl IntoFormat for rome_js_syntax::JsAnyFunctionBody { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyArrayElement; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayElement { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyArrayElement, FormatJsAnyArrayElement>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyArrayElement { +impl IntoFormat for rome_js_syntax::JsAnyArrayElement { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyName; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyName, FormatJsAnyName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyName { +impl IntoFormat for rome_js_syntax::JsAnyName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyInProperty; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyInProperty { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyInProperty, FormatJsAnyInProperty>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyInProperty { +impl IntoFormat for rome_js_syntax::JsAnyInProperty { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyAssignment; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyAssignment { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyAssignment, FormatJsAnyAssignment>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyAssignment { +impl IntoFormat for rome_js_syntax::JsAnyAssignment { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyObjectMemberName; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectMemberName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyObjectMemberName, FormatJsAnyObjectMemberName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyObjectMemberName { +impl IntoFormat for rome_js_syntax::JsAnyObjectMemberName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyObjectMember; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectMember { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyObjectMember, FormatJsAnyObjectMember>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyObjectMember { +impl IntoFormat for rome_js_syntax::JsAnyObjectMember { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyFormalParameter; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyFormalParameter { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyFormalParameter, FormatJsAnyFormalParameter>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyFormalParameter { +impl IntoFormat for rome_js_syntax::JsAnyFormalParameter { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyClassMember; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyClassMember { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyClassMember, FormatJsAnyClassMember>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyClassMember { +impl IntoFormat for rome_js_syntax::JsAnyClassMember { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyClass; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyClass { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyClass, FormatJsAnyClass>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyClass { +impl IntoFormat for rome_js_syntax::JsAnyClass { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyClassMemberName; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyClassMemberName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyClassMemberName, FormatJsAnyClassMemberName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyClassMemberName { +impl IntoFormat for rome_js_syntax::JsAnyClassMemberName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyConstructorParameter; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyConstructorParameter { @@ -4904,14 +6288,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyConstructorParameter { rome_js_syntax::JsAnyConstructorParameter, FormatJsAnyConstructorParameter, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyConstructorParameter { +impl IntoFormat for rome_js_syntax::JsAnyConstructorParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyConstructorParameter, FormatJsAnyConstructorParameter, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyPropertyParameterModifier; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertyParameterModifier { @@ -4920,14 +6308,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertyParameterModifier { rome_js_syntax::TsAnyPropertyParameterModifier, FormatTsAnyPropertyParameterModifier, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyPropertyParameterModifier { +impl IntoFormat for rome_js_syntax::TsAnyPropertyParameterModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyPropertyParameterModifier, FormatTsAnyPropertyParameterModifier, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyPropertyAnnotation; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertyAnnotation { @@ -4936,23 +6328,31 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertyAnnotation { rome_js_syntax::TsAnyPropertyAnnotation, FormatTsAnyPropertyAnnotation, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyPropertyAnnotation { +impl IntoFormat for rome_js_syntax::TsAnyPropertyAnnotation { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyPropertyModifier; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyPropertyModifier { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyPropertyModifier, FormatJsAnyPropertyModifier>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyPropertyModifier { +impl IntoFormat for rome_js_syntax::JsAnyPropertyModifier { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyPropertySignatureAnnotation; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertySignatureAnnotation { @@ -4961,14 +6361,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertySignatureAnnotation { rome_js_syntax::TsAnyPropertySignatureAnnotation, FormatTsAnyPropertySignatureAnnotation, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureAnnotation { +impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyPropertySignatureAnnotation, FormatTsAnyPropertySignatureAnnotation, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyPropertySignatureModifier; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertySignatureModifier { @@ -4977,25 +6381,33 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertySignatureModifier { rome_js_syntax::TsAnyPropertySignatureModifier, FormatTsAnyPropertySignatureModifier, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureModifier { +impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyPropertySignatureModifier, FormatTsAnyPropertySignatureModifier, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyMethodModifier; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyMethodModifier { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyMethodModifier, FormatJsAnyMethodModifier>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyMethodModifier { +impl IntoFormat for rome_js_syntax::JsAnyMethodModifier { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyMethodSignatureModifier; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyMethodSignatureModifier { @@ -5004,14 +6416,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyMethodSignatureModifier { rome_js_syntax::TsAnyMethodSignatureModifier, FormatTsAnyMethodSignatureModifier, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyMethodSignatureModifier { +impl IntoFormat for rome_js_syntax::TsAnyMethodSignatureModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyMethodSignatureModifier, FormatTsAnyMethodSignatureModifier, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyIndexSignatureModifier; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyIndexSignatureModifier { @@ -5020,23 +6436,31 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyIndexSignatureModifier { rome_js_syntax::TsAnyIndexSignatureModifier, FormatTsAnyIndexSignatureModifier, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyIndexSignatureModifier { +impl IntoFormat for rome_js_syntax::TsAnyIndexSignatureModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyIndexSignatureModifier, FormatTsAnyIndexSignatureModifier, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsType; impl<'a> AsFormat<'a> for rome_js_syntax::TsType { type Format = FormatRefWithRule<'a, rome_js_syntax::TsType, FormatTsType>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsType { +impl IntoFormat for rome_js_syntax::TsType { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyArrayAssignmentPatternElement; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayAssignmentPatternElement { @@ -5045,14 +6469,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayAssignmentPatternElement { rome_js_syntax::JsAnyArrayAssignmentPatternElement, FormatJsAnyArrayAssignmentPatternElement, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyArrayAssignmentPatternElement { +impl IntoFormat for rome_js_syntax::JsAnyArrayAssignmentPatternElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyArrayAssignmentPatternElement, FormatJsAnyArrayAssignmentPatternElement, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyObjectAssignmentPatternMember; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectAssignmentPatternMember { @@ -5061,14 +6489,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectAssignmentPatternMember { rome_js_syntax::JsAnyObjectAssignmentPatternMember, FormatJsAnyObjectAssignmentPatternMember, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyObjectAssignmentPatternMember { +impl IntoFormat for rome_js_syntax::JsAnyObjectAssignmentPatternMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyObjectAssignmentPatternMember, FormatJsAnyObjectAssignmentPatternMember, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyArrayBindingPatternElement; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayBindingPatternElement { @@ -5077,14 +6509,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayBindingPatternElement { rome_js_syntax::JsAnyArrayBindingPatternElement, FormatJsAnyArrayBindingPatternElement, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyArrayBindingPatternElement { +impl IntoFormat for rome_js_syntax::JsAnyArrayBindingPatternElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyArrayBindingPatternElement, FormatJsAnyArrayBindingPatternElement, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyObjectBindingPatternMember; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectBindingPatternMember { @@ -5093,32 +6529,44 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectBindingPatternMember { rome_js_syntax::JsAnyObjectBindingPatternMember, FormatJsAnyObjectBindingPatternMember, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyObjectBindingPatternMember { +impl IntoFormat for rome_js_syntax::JsAnyObjectBindingPatternMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyObjectBindingPatternMember, FormatJsAnyObjectBindingPatternMember, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyDeclaration; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyDeclaration { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyDeclaration, FormatJsAnyDeclaration>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyDeclaration { +impl IntoFormat for rome_js_syntax::JsAnyDeclaration { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyReturnType; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyReturnType { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyReturnType, FormatTsAnyReturnType>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyReturnType { +impl IntoFormat for rome_js_syntax::TsAnyReturnType { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyVariableAnnotation; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyVariableAnnotation { @@ -5127,39 +6575,55 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyVariableAnnotation { rome_js_syntax::TsAnyVariableAnnotation, FormatTsAnyVariableAnnotation, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyVariableAnnotation { +impl IntoFormat for rome_js_syntax::TsAnyVariableAnnotation { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyModuleItem; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyModuleItem { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyModuleItem, FormatJsAnyModuleItem>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyModuleItem { +impl IntoFormat for rome_js_syntax::JsAnyModuleItem { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyImportClause; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyImportClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyImportClause, FormatJsAnyImportClause>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyImportClause { +impl IntoFormat for rome_js_syntax::JsAnyImportClause { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyNamedImport; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyNamedImport { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyNamedImport, FormatJsAnyNamedImport>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyNamedImport { +impl IntoFormat for rome_js_syntax::JsAnyNamedImport { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyNamedImportSpecifier; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyNamedImportSpecifier { @@ -5168,14 +6632,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyNamedImportSpecifier { rome_js_syntax::JsAnyNamedImportSpecifier, FormatJsAnyNamedImportSpecifier, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsAnyNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyNamedImportSpecifier, FormatJsAnyNamedImportSpecifier, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyImportAssertionEntry; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyImportAssertionEntry { @@ -5184,23 +6652,31 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyImportAssertionEntry { rome_js_syntax::JsAnyImportAssertionEntry, FormatJsAnyImportAssertionEntry, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyImportAssertionEntry { +impl IntoFormat for rome_js_syntax::JsAnyImportAssertionEntry { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyImportAssertionEntry, FormatJsAnyImportAssertionEntry, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyExportClause; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyExportClause, FormatJsAnyExportClause>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyExportClause { +impl IntoFormat for rome_js_syntax::JsAnyExportClause { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyExportDefaultDeclaration; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportDefaultDeclaration { @@ -5209,14 +6685,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportDefaultDeclaration { rome_js_syntax::JsAnyExportDefaultDeclaration, FormatJsAnyExportDefaultDeclaration, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyExportDefaultDeclaration { +impl IntoFormat for rome_js_syntax::JsAnyExportDefaultDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyExportDefaultDeclaration, FormatJsAnyExportDefaultDeclaration, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyExportNamedSpecifier; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportNamedSpecifier { @@ -5225,70 +6705,98 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportNamedSpecifier { rome_js_syntax::JsAnyExportNamedSpecifier, FormatJsAnyExportNamedSpecifier, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyExportNamedSpecifier { +impl IntoFormat for rome_js_syntax::JsAnyExportNamedSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyExportNamedSpecifier, FormatJsAnyExportNamedSpecifier, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyFunction; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyFunction { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyFunction, FormatJsAnyFunction>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyFunction { +impl IntoFormat for rome_js_syntax::JsAnyFunction { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyParameter; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyParameter { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyParameter, FormatJsAnyParameter>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyParameter { +impl IntoFormat for rome_js_syntax::JsAnyParameter { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsAnyCallArgument; impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyCallArgument { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyCallArgument, FormatJsAnyCallArgument>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsAnyCallArgument { +impl IntoFormat for rome_js_syntax::JsAnyCallArgument { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyName; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyName { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyName, FormatTsAnyName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyName { +impl IntoFormat for rome_js_syntax::TsAnyName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyModuleReference; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyModuleReference { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyModuleReference, FormatTsAnyModuleReference>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyModuleReference { +impl IntoFormat for rome_js_syntax::TsAnyModuleReference { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyModuleName; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyModuleName { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyModuleName, FormatTsAnyModuleName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyModuleName { +impl IntoFormat for rome_js_syntax::TsAnyModuleName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyExternalModuleDeclarationBody; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyExternalModuleDeclarationBody { @@ -5297,14 +6805,18 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyExternalModuleDeclarationBody { rome_js_syntax::TsAnyExternalModuleDeclarationBody, FormatTsAnyExternalModuleDeclarationBody, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyExternalModuleDeclarationBody { +impl IntoFormat for rome_js_syntax::TsAnyExternalModuleDeclarationBody { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyExternalModuleDeclarationBody, FormatTsAnyExternalModuleDeclarationBody, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyTypePredicateParameterName; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTypePredicateParameterName { @@ -5313,119 +6825,167 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTypePredicateParameterName { rome_js_syntax::TsAnyTypePredicateParameterName, FormatTsAnyTypePredicateParameterName, >; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyTypePredicateParameterName { +impl IntoFormat for rome_js_syntax::TsAnyTypePredicateParameterName { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyTypePredicateParameterName, FormatTsAnyTypePredicateParameterName, >; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyTypeMember; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTypeMember { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyTypeMember, FormatTsAnyTypeMember>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyTypeMember { +impl IntoFormat for rome_js_syntax::TsAnyTypeMember { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyTupleTypeElement; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTupleTypeElement { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyTupleTypeElement, FormatTsAnyTupleTypeElement>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsAnyTupleTypeElement { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatTsAnyTemplateElement; impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTemplateElement { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyTemplateElement, FormatTsAnyTemplateElement>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::TsAnyTemplateElement { +impl IntoFormat for rome_js_syntax::TsAnyTemplateElement { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyTag; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyTag { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyTag, FormatJsxAnyTag>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyTag { +impl IntoFormat for rome_js_syntax::JsxAnyTag { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyElementName; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyElementName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyElementName, FormatJsxAnyElementName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyElementName { +impl IntoFormat for rome_js_syntax::JsxAnyElementName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyObjectName; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyObjectName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyObjectName, FormatJsxAnyObjectName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyObjectName { +impl IntoFormat for rome_js_syntax::JsxAnyObjectName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyName; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyName, FormatJsxAnyName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyName { +impl IntoFormat for rome_js_syntax::JsxAnyName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyAttribute; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyAttribute { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyAttribute, FormatJsxAnyAttribute>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyAttribute { +impl IntoFormat for rome_js_syntax::JsxAnyAttribute { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyAttributeName; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyAttributeName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyAttributeName, FormatJsxAnyAttributeName>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyAttributeName { +impl IntoFormat for rome_js_syntax::JsxAnyAttributeName { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyAttributeValue; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyAttributeValue { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyAttributeValue, FormatJsxAnyAttributeValue>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyAttributeValue { +impl IntoFormat for rome_js_syntax::JsxAnyAttributeValue { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } pub struct FormatJsxAnyChild; impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyChild { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyChild, FormatJsxAnyChild>; - fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } + fn format(&'a self) -> Self::Format { + FormatRefWithRule::new(self) + } } -impl IntoFormat for rome_js_syntax::JsxAnyChild { +impl IntoFormat for rome_js_syntax::JsxAnyChild { type Format = FormatOwnedWithRule; - fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } + fn into_format(self) -> Self::Format { + FormatOwnedWithRule::new(self) + } } diff --git a/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs b/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs index b7c4d7cd8e2..aa6ffdae35f 100644 --- a/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs +++ b/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs @@ -5,23 +5,18 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrayAssignmentPatternElement; impl FormatRule for FormatJsAnyArrayAssignmentPatternElement { type Context = JsFormatContext; - fn format( - node: &JsAnyArrayAssignmentPatternElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyArrayAssignmentPatternElement, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyArrayAssignmentPatternElement::JsAssignmentWithDefault(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyArrayAssignmentPatternElement::JsAnyAssignmentPattern(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyArrayAssignmentPatternElement::JsArrayAssignmentPatternRestElement(node) => { - formatted![formatter, [node.format()]] - } - JsAnyArrayAssignmentPatternElement::JsArrayHole(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + JsAnyArrayAssignmentPatternElement::JsArrayHole(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs b/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs index 44c15e78ef0..4f1447371bc 100644 --- a/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs +++ b/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs @@ -5,22 +5,15 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrayBindingPatternElement; impl FormatRule for FormatJsAnyArrayBindingPatternElement { type Context = JsFormatContext; - fn format( - node: &JsAnyArrayBindingPatternElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyArrayBindingPatternElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyArrayBindingPatternElement::JsArrayHole(node) => { - formatted![formatter, [node.format()]] - } - JsAnyArrayBindingPatternElement::JsAnyBindingPattern(node) => { - formatted![formatter, [node.format()]] - } + JsAnyArrayBindingPatternElement::JsArrayHole(node) => node.format().format(f), + JsAnyArrayBindingPatternElement::JsAnyBindingPattern(node) => node.format().format(f), JsAnyArrayBindingPatternElement::JsBindingPatternWithDefault(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyArrayBindingPatternElement::JsArrayBindingPatternRestElement(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } } } diff --git a/crates/rome_js_formatter/src/js/any/array_element.rs b/crates/rome_js_formatter/src/js/any/array_element.rs index f5b1fe58566..8375813819f 100644 --- a/crates/rome_js_formatter/src/js/any/array_element.rs +++ b/crates/rome_js_formatter/src/js/any/array_element.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrayElement; impl FormatRule for FormatJsAnyArrayElement { type Context = JsFormatContext; - fn format(node: &JsAnyArrayElement, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyArrayElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyArrayElement::JsAnyExpression(node) => formatted![formatter, [node.format()]], - JsAnyArrayElement::JsSpread(node) => formatted![formatter, [node.format()]], - JsAnyArrayElement::JsArrayHole(node) => formatted![formatter, [node.format()]], + JsAnyArrayElement::JsAnyExpression(node) => node.format().format(f), + JsAnyArrayElement::JsSpread(node) => node.format().format(f), + JsAnyArrayElement::JsArrayHole(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs b/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs index acf11162fe0..1e35a1af7dd 100644 --- a/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs +++ b/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrowFunctionParameters; impl FormatRule for FormatJsAnyArrowFunctionParameters { type Context = JsFormatContext; - fn format( - node: &JsAnyArrowFunctionParameters, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyArrowFunctionParameters, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyArrowFunctionParameters::JsParameters(node) => { - formatted![formatter, [node.format()]] - } - JsAnyArrowFunctionParameters::JsAnyBinding(node) => { - formatted![formatter, [node.format()]] - } + JsAnyArrowFunctionParameters::JsParameters(node) => node.format().format(f), + JsAnyArrowFunctionParameters::JsAnyBinding(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/assignment.rs b/crates/rome_js_formatter/src/js/any/assignment.rs index 56f08e3a433..7eaf59c567b 100644 --- a/crates/rome_js_formatter/src/js/any/assignment.rs +++ b/crates/rome_js_formatter/src/js/any/assignment.rs @@ -5,26 +5,16 @@ use crate::prelude::*; use rome_js_syntax::JsAnyAssignment; impl FormatRule for FormatJsAnyAssignment { type Context = JsFormatContext; - fn format(node: &JsAnyAssignment, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyAssignment, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyAssignment::JsIdentifierAssignment(node) => formatted![formatter, [node.format()]], - JsAnyAssignment::JsStaticMemberAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::JsComputedMemberAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::JsParenthesizedAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::TsNonNullAssertionAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::TsAsAssignment(node) => formatted![formatter, [node.format()]], - JsAnyAssignment::TsTypeAssertionAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::JsUnknownAssignment(node) => formatted![formatter, [node.format()]], + JsAnyAssignment::JsIdentifierAssignment(node) => node.format().format(f), + JsAnyAssignment::JsStaticMemberAssignment(node) => node.format().format(f), + JsAnyAssignment::JsComputedMemberAssignment(node) => node.format().format(f), + JsAnyAssignment::JsParenthesizedAssignment(node) => node.format().format(f), + JsAnyAssignment::TsNonNullAssertionAssignment(node) => node.format().format(f), + JsAnyAssignment::TsAsAssignment(node) => node.format().format(f), + JsAnyAssignment::TsTypeAssertionAssignment(node) => node.format().format(f), + JsAnyAssignment::JsUnknownAssignment(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/assignment_pattern.rs b/crates/rome_js_formatter/src/js/any/assignment_pattern.rs index a7316b0416e..d9d4f542bd8 100644 --- a/crates/rome_js_formatter/src/js/any/assignment_pattern.rs +++ b/crates/rome_js_formatter/src/js/any/assignment_pattern.rs @@ -5,18 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyAssignmentPattern; impl FormatRule for FormatJsAnyAssignmentPattern { type Context = JsFormatContext; - fn format( - node: &JsAnyAssignmentPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyAssignmentPattern::JsAnyAssignment(node) => formatted![formatter, [node.format()]], - JsAnyAssignmentPattern::JsArrayAssignmentPattern(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignmentPattern::JsObjectAssignmentPattern(node) => { - formatted![formatter, [node.format()]] - } + JsAnyAssignmentPattern::JsAnyAssignment(node) => node.format().format(f), + JsAnyAssignmentPattern::JsArrayAssignmentPattern(node) => node.format().format(f), + JsAnyAssignmentPattern::JsObjectAssignmentPattern(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/binding.rs b/crates/rome_js_formatter/src/js/any/binding.rs index a7984ce9ea1..dd9b93cd3ca 100644 --- a/crates/rome_js_formatter/src/js/any/binding.rs +++ b/crates/rome_js_formatter/src/js/any/binding.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyBinding; impl FormatRule for FormatJsAnyBinding { type Context = JsFormatContext; - fn format(node: &JsAnyBinding, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyBinding, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyBinding::JsIdentifierBinding(node) => formatted![formatter, [node.format()]], - JsAnyBinding::JsUnknownBinding(node) => formatted![formatter, [node.format()]], + JsAnyBinding::JsIdentifierBinding(node) => node.format().format(f), + JsAnyBinding::JsUnknownBinding(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/binding_pattern.rs b/crates/rome_js_formatter/src/js/any/binding_pattern.rs index 4cc9376a8e1..684fc410e55 100644 --- a/crates/rome_js_formatter/src/js/any/binding_pattern.rs +++ b/crates/rome_js_formatter/src/js/any/binding_pattern.rs @@ -5,15 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyBindingPattern; impl FormatRule for FormatJsAnyBindingPattern { type Context = JsFormatContext; - fn format(node: &JsAnyBindingPattern, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyBindingPattern::JsAnyBinding(node) => formatted![formatter, [node.format()]], - JsAnyBindingPattern::JsArrayBindingPattern(node) => { - formatted![formatter, [node.format()]] - } - JsAnyBindingPattern::JsObjectBindingPattern(node) => { - formatted![formatter, [node.format()]] - } + JsAnyBindingPattern::JsAnyBinding(node) => node.format().format(f), + JsAnyBindingPattern::JsArrayBindingPattern(node) => node.format().format(f), + JsAnyBindingPattern::JsObjectBindingPattern(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/call_argument.rs b/crates/rome_js_formatter/src/js/any/call_argument.rs index 2e02881bb81..1bf6bd8e5b2 100644 --- a/crates/rome_js_formatter/src/js/any/call_argument.rs +++ b/crates/rome_js_formatter/src/js/any/call_argument.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyCallArgument; impl FormatRule for FormatJsAnyCallArgument { type Context = JsFormatContext; - fn format(node: &JsAnyCallArgument, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyCallArgument, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyCallArgument::JsAnyExpression(node) => formatted![formatter, [node.format()]], - JsAnyCallArgument::JsSpread(node) => formatted![formatter, [node.format()]], + JsAnyCallArgument::JsAnyExpression(node) => node.format().format(f), + JsAnyCallArgument::JsSpread(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/class.rs b/crates/rome_js_formatter/src/js/any/class.rs index 212ee7c6c5e..fdfd348b3dd 100644 --- a/crates/rome_js_formatter/src/js/any/class.rs +++ b/crates/rome_js_formatter/src/js/any/class.rs @@ -1,4 +1,6 @@ use crate::generated::FormatJsAnyClass; +use rome_formatter::{format_args, write}; + use crate::prelude::*; use rome_js_syntax::JsAnyClass; use rome_rowan::AstNode; @@ -6,47 +8,48 @@ use rome_rowan::AstNode; impl FormatRule for FormatJsAnyClass { type Context = JsFormatContext; - fn format(node: &JsAnyClass, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyClass, f: &mut JsFormatter) -> FormatResult<()> { let abstract_token = node.abstract_token(); let id = node.id(); let extends = node.extends_clause(); let implements_clause = node.implements_clause(); - let format = implements_clause.format(); + if let Some(abstract_token) = abstract_token { + write!(f, [abstract_token.format(), space_token()])?; + } + + write!(f, [node.class_token().format()])?; + + if let Some(id) = id? { + write!(f, [space_token(), id.format()])?; + } + + write!(f, [node.type_parameters().format()])?; + + if let Some(extends) = extends { + write!(f, [space_token(), extends.format()])?; + } + + if let Some(implements_clause) = implements_clause { + write!(f, [space_token(), implements_clause.format()])?; + } + + let members = format_with(|f| { + let mut join = f.join_nodes_with_hardline(); + + for member in node.members() { + join.entry(&member.syntax(), &member.format()); + } - let implements_clause = format.with_or_empty(|implements_clause| { - formatted![formatter, [space_token(), implements_clause]] + join.finish() }); - formatted![ - formatter, + write![ + f, [ - abstract_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), - node.class_token().format(), - id.format() - .with_or_empty(|id| formatted![formatter, [space_token(), id]]), - node.type_parameters().format(), - extends.format().with_or_empty(|extends_clause| formatted![ - formatter, - [space_token(), extends_clause] - ]), - implements_clause, space_token(), - formatter - .delimited( - &node.l_curly_token()?, - join_elements_hard_line( - node.members() - .into_iter() - .map(|node| node.syntax().clone()) - .zip(formatter.format_all(node.members().iter().formatted())?) - ), - &node.r_curly_token()? - ) + f.delimited(&node.l_curly_token()?, &members, &node.r_curly_token()?) .block_indent() - .finish() ] ] } diff --git a/crates/rome_js_formatter/src/js/any/class_member.rs b/crates/rome_js_formatter/src/js/any/class_member.rs index 96991ef3156..bf276048b65 100644 --- a/crates/rome_js_formatter/src/js/any/class_member.rs +++ b/crates/rome_js_formatter/src/js/any/class_member.rs @@ -5,38 +5,24 @@ use crate::prelude::*; use rome_js_syntax::JsAnyClassMember; impl FormatRule for FormatJsAnyClassMember { type Context = JsFormatContext; - fn format(node: &JsAnyClassMember, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyClassMember, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyClassMember::JsConstructorClassMember(node) => { - formatted![formatter, [node.format()]] - } + JsAnyClassMember::JsConstructorClassMember(node) => node.format().format(f), JsAnyClassMember::JsStaticInitializationBlockClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::JsPropertyClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsMethodClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsGetterClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsSetterClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::TsConstructorSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsPropertySignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsMethodSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsGetterSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsSetterSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsIndexSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::JsEmptyClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsUnknownMember(node) => formatted![formatter, [node.format()]], + node.format().format(f) + } + JsAnyClassMember::JsPropertyClassMember(node) => node.format().format(f), + JsAnyClassMember::JsMethodClassMember(node) => node.format().format(f), + JsAnyClassMember::JsGetterClassMember(node) => node.format().format(f), + JsAnyClassMember::JsSetterClassMember(node) => node.format().format(f), + JsAnyClassMember::TsConstructorSignatureClassMember(node) => node.format().format(f), + JsAnyClassMember::TsPropertySignatureClassMember(node) => node.format().format(f), + JsAnyClassMember::TsMethodSignatureClassMember(node) => node.format().format(f), + JsAnyClassMember::TsGetterSignatureClassMember(node) => node.format().format(f), + JsAnyClassMember::TsSetterSignatureClassMember(node) => node.format().format(f), + JsAnyClassMember::TsIndexSignatureClassMember(node) => node.format().format(f), + JsAnyClassMember::JsEmptyClassMember(node) => node.format().format(f), + JsAnyClassMember::JsUnknownMember(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/class_member_name.rs b/crates/rome_js_formatter/src/js/any/class_member_name.rs index a95ff6754dd..fdd1d7f44a5 100644 --- a/crates/rome_js_formatter/src/js/any/class_member_name.rs +++ b/crates/rome_js_formatter/src/js/any/class_member_name.rs @@ -5,17 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyClassMemberName; impl FormatRule for FormatJsAnyClassMemberName { type Context = JsFormatContext; - fn format(node: &JsAnyClassMemberName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyClassMemberName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyClassMemberName::JsLiteralMemberName(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMemberName::JsComputedMemberName(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMemberName::JsPrivateClassMemberName(node) => { - formatted![formatter, [node.format()]] - } + JsAnyClassMemberName::JsLiteralMemberName(node) => node.format().format(f), + JsAnyClassMemberName::JsComputedMemberName(node) => node.format().format(f), + JsAnyClassMemberName::JsPrivateClassMemberName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/constructor_parameter.rs b/crates/rome_js_formatter/src/js/any/constructor_parameter.rs index abff46db6bb..57d2384afd8 100644 --- a/crates/rome_js_formatter/src/js/any/constructor_parameter.rs +++ b/crates/rome_js_formatter/src/js/any/constructor_parameter.rs @@ -5,20 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyConstructorParameter; impl FormatRule for FormatJsAnyConstructorParameter { type Context = JsFormatContext; - fn format( - node: &JsAnyConstructorParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyConstructorParameter, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyConstructorParameter::JsAnyFormalParameter(node) => { - formatted![formatter, [node.format()]] - } - JsAnyConstructorParameter::JsRestParameter(node) => { - formatted![formatter, [node.format()]] - } - JsAnyConstructorParameter::TsPropertyParameter(node) => { - formatted![formatter, [node.format()]] - } + JsAnyConstructorParameter::JsAnyFormalParameter(node) => node.format().format(f), + JsAnyConstructorParameter::JsRestParameter(node) => node.format().format(f), + JsAnyConstructorParameter::TsPropertyParameter(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/declaration.rs b/crates/rome_js_formatter/src/js/any/declaration.rs index bdc87e21123..b7f9fe014a2 100644 --- a/crates/rome_js_formatter/src/js/any/declaration.rs +++ b/crates/rome_js_formatter/src/js/any/declaration.rs @@ -5,29 +5,19 @@ use crate::prelude::*; use rome_js_syntax::JsAnyDeclaration; impl FormatRule for FormatJsAnyDeclaration { type Context = JsFormatContext; - fn format(node: &JsAnyDeclaration, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyDeclaration, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyDeclaration::JsClassDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::JsFunctionDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::JsVariableDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsEnumDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsTypeAliasDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsInterfaceDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsModuleDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsExternalModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsGlobalDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsImportEqualsDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyDeclaration::JsClassDeclaration(node) => node.format().format(f), + JsAnyDeclaration::JsFunctionDeclaration(node) => node.format().format(f), + JsAnyDeclaration::JsVariableDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsEnumDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsTypeAliasDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsInterfaceDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsDeclareFunctionDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsModuleDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsExternalModuleDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsGlobalDeclaration(node) => node.format().format(f), + JsAnyDeclaration::TsImportEqualsDeclaration(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/declaration_clause.rs b/crates/rome_js_formatter/src/js/any/declaration_clause.rs index 9e8e960ebc2..5d64deb46b1 100644 --- a/crates/rome_js_formatter/src/js/any/declaration_clause.rs +++ b/crates/rome_js_formatter/src/js/any/declaration_clause.rs @@ -5,44 +5,19 @@ use crate::prelude::*; use rome_js_syntax::JsAnyDeclarationClause; impl FormatRule for FormatJsAnyDeclarationClause { type Context = JsFormatContext; - fn format( - node: &JsAnyDeclarationClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyDeclarationClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyDeclarationClause::JsClassDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::JsFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::JsVariableDeclarationClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsEnumDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsTypeAliasDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsInterfaceDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsExternalModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsGlobalDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsImportEqualsDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyDeclarationClause::JsClassDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::JsFunctionDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::JsVariableDeclarationClause(node) => node.format().format(f), + JsAnyDeclarationClause::TsEnumDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsTypeAliasDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsInterfaceDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsDeclareFunctionDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsModuleDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsExternalModuleDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsGlobalDeclaration(node) => node.format().format(f), + JsAnyDeclarationClause::TsImportEqualsDeclaration(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/export_clause.rs b/crates/rome_js_formatter/src/js/any/export_clause.rs index 683e81ced89..2d599e7b856 100644 --- a/crates/rome_js_formatter/src/js/any/export_clause.rs +++ b/crates/rome_js_formatter/src/js/any/export_clause.rs @@ -5,31 +5,17 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExportClause; impl FormatRule for FormatJsAnyExportClause { type Context = JsFormatContext; - fn format(node: &JsAnyExportClause, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyExportClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyExportClause::JsExportDefaultDeclarationClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::JsExportDefaultExpressionClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::JsExportNamedClause(node) => formatted![formatter, [node.format()]], - JsAnyExportClause::JsExportFromClause(node) => formatted![formatter, [node.format()]], - JsAnyExportClause::JsExportNamedFromClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::JsAnyDeclarationClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::TsExportAsNamespaceClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::TsExportAssignmentClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::TsExportDeclareClause(node) => { - formatted![formatter, [node.format()]] - } + JsAnyExportClause::JsExportDefaultDeclarationClause(node) => node.format().format(f), + JsAnyExportClause::JsExportDefaultExpressionClause(node) => node.format().format(f), + JsAnyExportClause::JsExportNamedClause(node) => node.format().format(f), + JsAnyExportClause::JsExportFromClause(node) => node.format().format(f), + JsAnyExportClause::JsExportNamedFromClause(node) => node.format().format(f), + JsAnyExportClause::JsAnyDeclarationClause(node) => node.format().format(f), + JsAnyExportClause::TsExportAsNamespaceClause(node) => node.format().format(f), + JsAnyExportClause::TsExportAssignmentClause(node) => node.format().format(f), + JsAnyExportClause::TsExportDeclareClause(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/export_default_declaration.rs b/crates/rome_js_formatter/src/js/any/export_default_declaration.rs index 8b15f2177e5..fc3761b324d 100644 --- a/crates/rome_js_formatter/src/js/any/export_default_declaration.rs +++ b/crates/rome_js_formatter/src/js/any/export_default_declaration.rs @@ -5,23 +5,18 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExportDefaultDeclaration; impl FormatRule for FormatJsAnyExportDefaultDeclaration { type Context = JsFormatContext; - fn format( - node: &JsAnyExportDefaultDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyExportDefaultDeclaration, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyExportDefaultDeclaration::JsClassExportDefaultDeclaration(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyExportDefaultDeclaration::JsFunctionExportDefaultDeclaration(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyExportDefaultDeclaration::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportDefaultDeclaration::TsInterfaceDeclaration(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + JsAnyExportDefaultDeclaration::TsInterfaceDeclaration(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/export_named_specifier.rs b/crates/rome_js_formatter/src/js/any/export_named_specifier.rs index f93f62b4791..f7bc1daed0a 100644 --- a/crates/rome_js_formatter/src/js/any/export_named_specifier.rs +++ b/crates/rome_js_formatter/src/js/any/export_named_specifier.rs @@ -5,17 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExportNamedSpecifier; impl FormatRule for FormatJsAnyExportNamedSpecifier { type Context = JsFormatContext; - fn format( - node: &JsAnyExportNamedSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyExportNamedSpecifier, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyExportNamedSpecifier::JsExportNamedShorthandSpecifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportNamedSpecifier::JsExportNamedSpecifier(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + JsAnyExportNamedSpecifier::JsExportNamedSpecifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/expression.rs b/crates/rome_js_formatter/src/js/any/expression.rs index d352041e4e7..8c0823a6c49 100644 --- a/crates/rome_js_formatter/src/js/any/expression.rs +++ b/crates/rome_js_formatter/src/js/any/expression.rs @@ -5,57 +5,43 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExpression; impl FormatRule for FormatJsAnyExpression { type Context = JsFormatContext; - fn format(node: &JsAnyExpression, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyExpression, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyExpression::JsAnyLiteralExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::ImportMeta(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsArrayExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsArrowFunctionExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsAssignmentExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsAwaitExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsBinaryExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsCallExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsClassExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsComputedMemberExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsConditionalExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsFunctionExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsIdentifierExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsImportCallExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsInExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsInstanceofExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsLogicalExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsNewExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsObjectExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsParenthesizedExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsPostUpdateExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsPreUpdateExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsSequenceExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsStaticMemberExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsSuperExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsThisExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsUnaryExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsUnknownExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsYieldExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::NewTarget(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsTemplate(node) => formatted![formatter, [node.format()]], - JsAnyExpression::TsTypeAssertionExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::TsAsExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::TsNonNullAssertionExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsxTagExpression(node) => formatted![formatter, [node.format()]], + JsAnyExpression::JsAnyLiteralExpression(node) => node.format().format(f), + JsAnyExpression::ImportMeta(node) => node.format().format(f), + JsAnyExpression::JsArrayExpression(node) => node.format().format(f), + JsAnyExpression::JsArrowFunctionExpression(node) => node.format().format(f), + JsAnyExpression::JsAssignmentExpression(node) => node.format().format(f), + JsAnyExpression::JsAwaitExpression(node) => node.format().format(f), + JsAnyExpression::JsBinaryExpression(node) => node.format().format(f), + JsAnyExpression::JsCallExpression(node) => node.format().format(f), + JsAnyExpression::JsClassExpression(node) => node.format().format(f), + JsAnyExpression::JsComputedMemberExpression(node) => node.format().format(f), + JsAnyExpression::JsConditionalExpression(node) => node.format().format(f), + JsAnyExpression::JsFunctionExpression(node) => node.format().format(f), + JsAnyExpression::JsIdentifierExpression(node) => node.format().format(f), + JsAnyExpression::JsImportCallExpression(node) => node.format().format(f), + JsAnyExpression::JsInExpression(node) => node.format().format(f), + JsAnyExpression::JsInstanceofExpression(node) => node.format().format(f), + JsAnyExpression::JsLogicalExpression(node) => node.format().format(f), + JsAnyExpression::JsNewExpression(node) => node.format().format(f), + JsAnyExpression::JsObjectExpression(node) => node.format().format(f), + JsAnyExpression::JsParenthesizedExpression(node) => node.format().format(f), + JsAnyExpression::JsPostUpdateExpression(node) => node.format().format(f), + JsAnyExpression::JsPreUpdateExpression(node) => node.format().format(f), + JsAnyExpression::JsSequenceExpression(node) => node.format().format(f), + JsAnyExpression::JsStaticMemberExpression(node) => node.format().format(f), + JsAnyExpression::JsSuperExpression(node) => node.format().format(f), + JsAnyExpression::JsThisExpression(node) => node.format().format(f), + JsAnyExpression::JsUnaryExpression(node) => node.format().format(f), + JsAnyExpression::JsUnknownExpression(node) => node.format().format(f), + JsAnyExpression::JsYieldExpression(node) => node.format().format(f), + JsAnyExpression::NewTarget(node) => node.format().format(f), + JsAnyExpression::JsTemplate(node) => node.format().format(f), + JsAnyExpression::TsTypeAssertionExpression(node) => node.format().format(f), + JsAnyExpression::TsAsExpression(node) => node.format().format(f), + JsAnyExpression::TsNonNullAssertionExpression(node) => node.format().format(f), + JsAnyExpression::JsxTagExpression(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs b/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs index 4d9a97adc18..df855df25c6 100644 --- a/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs +++ b/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyForInOrOfInitializer; impl FormatRule for FormatJsAnyForInOrOfInitializer { type Context = JsFormatContext; - fn format( - node: &JsAnyForInOrOfInitializer, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyForInOrOfInitializer, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyForInOrOfInitializer::JsAnyAssignmentPattern(node) => { - formatted![formatter, [node.format()]] - } - JsAnyForInOrOfInitializer::JsForVariableDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyForInOrOfInitializer::JsAnyAssignmentPattern(node) => node.format().format(f), + JsAnyForInOrOfInitializer::JsForVariableDeclaration(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/for_initializer.rs b/crates/rome_js_formatter/src/js/any/for_initializer.rs index 3fdf3c02c3b..60f2a54c0ad 100644 --- a/crates/rome_js_formatter/src/js/any/for_initializer.rs +++ b/crates/rome_js_formatter/src/js/any/for_initializer.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyForInitializer; impl FormatRule for FormatJsAnyForInitializer { type Context = JsFormatContext; - fn format(node: &JsAnyForInitializer, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyForInitializer, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyForInitializer::JsVariableDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyForInitializer::JsAnyExpression(node) => formatted![formatter, [node.format()]], + JsAnyForInitializer::JsVariableDeclaration(node) => node.format().format(f), + JsAnyForInitializer::JsAnyExpression(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/formal_parameter.rs b/crates/rome_js_formatter/src/js/any/formal_parameter.rs index 7ab482a4fbe..2a5da1a527e 100644 --- a/crates/rome_js_formatter/src/js/any/formal_parameter.rs +++ b/crates/rome_js_formatter/src/js/any/formal_parameter.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyFormalParameter; impl FormatRule for FormatJsAnyFormalParameter { type Context = JsFormatContext; - fn format(node: &JsAnyFormalParameter, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyFormalParameter, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyFormalParameter::JsFormalParameter(node) => formatted![formatter, [node.format()]], - JsAnyFormalParameter::JsUnknownParameter(node) => { - formatted![formatter, [node.format()]] - } + JsAnyFormalParameter::JsFormalParameter(node) => node.format().format(f), + JsAnyFormalParameter::JsUnknownParameter(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/function.rs b/crates/rome_js_formatter/src/js/any/function.rs index dc1d1149583..2045fcafd83 100644 --- a/crates/rome_js_formatter/src/js/any/function.rs +++ b/crates/rome_js_formatter/src/js/any/function.rs @@ -1,7 +1,7 @@ -use crate::prelude::*; - use crate::generated::FormatJsAnyFunction; +use crate::prelude::*; use crate::utils::is_simple_expression; +use rome_formatter::{format_args, write}; use rome_js_syntax::{ JsAnyArrowFunctionParameters, JsAnyExpression, JsAnyFunction, JsAnyFunctionBody, }; @@ -9,56 +9,45 @@ use rome_js_syntax::{ impl FormatRule for FormatJsAnyFunction { type Context = JsFormatContext; - fn format(node: &JsAnyFunction, formatter: &JsFormatter) -> FormatResult { - let mut tokens = vec![]; - - tokens.push(formatted![ - formatter, - [node - .async_token() - .format() - .with_or_empty(|token| { formatted![formatter, [token, space_token()]] })] - ]?); + fn format(node: &JsAnyFunction, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(async_token) = node.async_token() { + write!(f, [async_token.format(), space_token()])?; + } - tokens.push(formatted![formatter, [node.function_token().format()]]?); - tokens.push(formatted![formatter, [node.star_token().format()]]?); + write!( + f, + [node.function_token().format(), node.star_token().format()] + )?; - tokens.push(match node { - JsAnyFunction::JsArrowFunctionExpression(_) => empty_element(), - _ => formatted![ - formatter, - [node - .id() - .format() - .with_or(|id| formatted![formatter, [space_token(), id]], space_token,)] - ]?, - }); + if !matches!(node, JsAnyFunction::JsArrowFunctionExpression(_)) { + match node.id()? { + Some(id) => { + write!(f, [space_token(), id.format()])?; + } + None => { + write!(f, [space_token()])?; + } + } + } - tokens.push(formatted![formatter, [node.type_parameters().format()]]?); + write!(f, [node.type_parameters().format()])?; - tokens.push(match node.parameters()? { - JsAnyArrowFunctionParameters::JsAnyBinding(binding) => group_elements(formatted![ - formatter, - [ + match node.parameters()? { + JsAnyArrowFunctionParameters::JsAnyBinding(binding) => write!( + f, + [group_elements(&format_args![ token("("), - soft_block_indent(formatted![ - formatter, - [binding.format(), if_group_breaks(token(",")),] - ]?), + soft_block_indent(&format_args![ + binding.format(), + if_group_breaks(&token(",")), + ]), token(")"), - ] - ]?), - JsAnyArrowFunctionParameters::JsParameters(params) => { - formatted![formatter, [params.format()]]? - } - }); - - tokens.push(formatted![ - formatter, - [node.return_type_annotation().format()] - ]?); + ])] + )?, + JsAnyArrowFunctionParameters::JsParameters(params) => write![f, [params.format()]]?, + } - tokens.push(space_token()); + write![f, [node.return_type_annotation().format(), space_token()]]?; // We create a new group for everything after the parameters. That way if the parameters // get broken, we don't line break the arrow and the body if they can fit on the same line. @@ -73,10 +62,7 @@ impl FormatRule for FormatJsAnyFunction { // The line break for `a + b` is not necessary // if let JsAnyFunction::JsArrowFunctionExpression(arrow) = node { - tokens.push(formatted![ - formatter, - [arrow.fat_arrow_token().format(), space_token()] - ]?); + write![f, [arrow.fat_arrow_token().format(), space_token()]]?; } let body = node.body()?; @@ -110,14 +96,16 @@ impl FormatRule for FormatJsAnyFunction { }; if body_has_soft_line_break { - tokens.push(formatted![formatter, [node.body().format()]]?); + write![f, [node.body().format()]]?; } else { - tokens.push(group_elements(soft_line_indent_or_space(formatted![ - formatter, - [node.body().format()] - ]?))); + write!( + f, + [group_elements(&soft_line_indent_or_space( + &node.body().format() + ))] + )?; } - Ok(concat_elements(tokens)) + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/any/function_body.rs b/crates/rome_js_formatter/src/js/any/function_body.rs index e3735cbd9e1..05c38962c7e 100644 --- a/crates/rome_js_formatter/src/js/any/function_body.rs +++ b/crates/rome_js_formatter/src/js/any/function_body.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyFunctionBody; impl FormatRule for FormatJsAnyFunctionBody { type Context = JsFormatContext; - fn format(node: &JsAnyFunctionBody, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyFunctionBody, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyFunctionBody::JsAnyExpression(node) => formatted![formatter, [node.format()]], - JsAnyFunctionBody::JsFunctionBody(node) => formatted![formatter, [node.format()]], + JsAnyFunctionBody::JsAnyExpression(node) => node.format().format(f), + JsAnyFunctionBody::JsFunctionBody(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs b/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs index dc51fc94bb4..5868fbab651 100644 --- a/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs +++ b/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs @@ -5,16 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyImportAssertionEntry; impl FormatRule for FormatJsAnyImportAssertionEntry { type Context = JsFormatContext; - fn format( - node: &JsAnyImportAssertionEntry, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyImportAssertionEntry, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyImportAssertionEntry::JsImportAssertionEntry(node) => { - formatted![formatter, [node.format()]] - } + JsAnyImportAssertionEntry::JsImportAssertionEntry(node) => node.format().format(f), JsAnyImportAssertionEntry::JsUnknownImportAssertionEntry(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } } } diff --git a/crates/rome_js_formatter/src/js/any/import_clause.rs b/crates/rome_js_formatter/src/js/any/import_clause.rs index 52edd35406e..6ed2fa9bbc8 100644 --- a/crates/rome_js_formatter/src/js/any/import_clause.rs +++ b/crates/rome_js_formatter/src/js/any/import_clause.rs @@ -5,16 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsAnyImportClause; impl FormatRule for FormatJsAnyImportClause { type Context = JsFormatContext; - fn format(node: &JsAnyImportClause, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyImportClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyImportClause::JsImportBareClause(node) => formatted![formatter, [node.format()]], - JsAnyImportClause::JsImportNamedClause(node) => formatted![formatter, [node.format()]], - JsAnyImportClause::JsImportDefaultClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyImportClause::JsImportNamespaceClause(node) => { - formatted![formatter, [node.format()]] - } + JsAnyImportClause::JsImportBareClause(node) => node.format().format(f), + JsAnyImportClause::JsImportNamedClause(node) => node.format().format(f), + JsAnyImportClause::JsImportDefaultClause(node) => node.format().format(f), + JsAnyImportClause::JsImportNamespaceClause(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/in_property.rs b/crates/rome_js_formatter/src/js/any/in_property.rs index fc682820c08..373bede6482 100644 --- a/crates/rome_js_formatter/src/js/any/in_property.rs +++ b/crates/rome_js_formatter/src/js/any/in_property.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyInProperty; impl FormatRule for FormatJsAnyInProperty { type Context = JsFormatContext; - fn format(node: &JsAnyInProperty, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyInProperty, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyInProperty::JsPrivateName(node) => formatted![formatter, [node.format()]], - JsAnyInProperty::JsAnyExpression(node) => formatted![formatter, [node.format()]], + JsAnyInProperty::JsPrivateName(node) => node.format().format(f), + JsAnyInProperty::JsAnyExpression(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/literal_expression.rs b/crates/rome_js_formatter/src/js/any/literal_expression.rs index df81549383f..f9c2bfeef4b 100644 --- a/crates/rome_js_formatter/src/js/any/literal_expression.rs +++ b/crates/rome_js_formatter/src/js/any/literal_expression.rs @@ -5,29 +5,14 @@ use crate::prelude::*; use rome_js_syntax::JsAnyLiteralExpression; impl FormatRule for FormatJsAnyLiteralExpression { type Context = JsFormatContext; - fn format( - node: &JsAnyLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyLiteralExpression::JsStringLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsNumberLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsBigIntLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsBooleanLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsNullLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsRegexLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } + JsAnyLiteralExpression::JsStringLiteralExpression(node) => node.format().format(f), + JsAnyLiteralExpression::JsNumberLiteralExpression(node) => node.format().format(f), + JsAnyLiteralExpression::JsBigIntLiteralExpression(node) => node.format().format(f), + JsAnyLiteralExpression::JsBooleanLiteralExpression(node) => node.format().format(f), + JsAnyLiteralExpression::JsNullLiteralExpression(node) => node.format().format(f), + JsAnyLiteralExpression::JsRegexLiteralExpression(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/method_modifier.rs b/crates/rome_js_formatter/src/js/any/method_modifier.rs index 3f34c3cf17c..f4ffd437ab7 100644 --- a/crates/rome_js_formatter/src/js/any/method_modifier.rs +++ b/crates/rome_js_formatter/src/js/any/method_modifier.rs @@ -5,13 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyMethodModifier; impl FormatRule for FormatJsAnyMethodModifier { type Context = JsFormatContext; - fn format(node: &JsAnyMethodModifier, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyMethodModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyMethodModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyMethodModifier::JsStaticModifier(node) => formatted![formatter, [node.format()]], - JsAnyMethodModifier::TsOverrideModifier(node) => formatted![formatter, [node.format()]], + JsAnyMethodModifier::TsAccessibilityModifier(node) => node.format().format(f), + JsAnyMethodModifier::JsStaticModifier(node) => node.format().format(f), + JsAnyMethodModifier::TsOverrideModifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/module_item.rs b/crates/rome_js_formatter/src/js/any/module_item.rs index 6b848ee2d0b..db5970caded 100644 --- a/crates/rome_js_formatter/src/js/any/module_item.rs +++ b/crates/rome_js_formatter/src/js/any/module_item.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyModuleItem; impl FormatRule for FormatJsAnyModuleItem { type Context = JsFormatContext; - fn format(node: &JsAnyModuleItem, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyModuleItem, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyModuleItem::JsAnyStatement(node) => formatted![formatter, [node.format()]], - JsAnyModuleItem::JsExport(node) => formatted![formatter, [node.format()]], - JsAnyModuleItem::JsImport(node) => formatted![formatter, [node.format()]], + JsAnyModuleItem::JsAnyStatement(node) => node.format().format(f), + JsAnyModuleItem::JsExport(node) => node.format().format(f), + JsAnyModuleItem::JsImport(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/name.rs b/crates/rome_js_formatter/src/js/any/name.rs index d84a462e54f..b4b8f1a2841 100644 --- a/crates/rome_js_formatter/src/js/any/name.rs +++ b/crates/rome_js_formatter/src/js/any/name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyName; impl FormatRule for FormatJsAnyName { type Context = JsFormatContext; - fn format(node: &JsAnyName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyName::JsName(node) => formatted![formatter, [node.format()]], - JsAnyName::JsPrivateName(node) => formatted![formatter, [node.format()]], + JsAnyName::JsName(node) => node.format().format(f), + JsAnyName::JsPrivateName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/named_import.rs b/crates/rome_js_formatter/src/js/any/named_import.rs index 926a39c6a39..e89d154a2a0 100644 --- a/crates/rome_js_formatter/src/js/any/named_import.rs +++ b/crates/rome_js_formatter/src/js/any/named_import.rs @@ -5,14 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyNamedImport; impl FormatRule for FormatJsAnyNamedImport { type Context = JsFormatContext; - fn format(node: &JsAnyNamedImport, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyNamedImport, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyNamedImport::JsNamedImportSpecifiers(node) => { - formatted![formatter, [node.format()]] - } - JsAnyNamedImport::JsNamespaceImportSpecifier(node) => { - formatted![formatter, [node.format()]] - } + JsAnyNamedImport::JsNamedImportSpecifiers(node) => node.format().format(f), + JsAnyNamedImport::JsNamespaceImportSpecifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/named_import_specifier.rs b/crates/rome_js_formatter/src/js/any/named_import_specifier.rs index 2cc3bca6a03..5dbae629f49 100644 --- a/crates/rome_js_formatter/src/js/any/named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/any/named_import_specifier.rs @@ -7,17 +7,15 @@ impl FormatRule for FormatJsAnyNamedImportSpecifier { type Context = JsFormatContext; fn format( node: &JsAnyNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { JsAnyNamedImportSpecifier::JsShorthandNamedImportSpecifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyNamedImportSpecifier::JsNamedImportSpecifier(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + JsAnyNamedImportSpecifier::JsNamedImportSpecifier(node) => node.format().format(f), JsAnyNamedImportSpecifier::JsUnknownNamedImportSpecifier(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } } } diff --git a/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs b/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs index 0053ba8f59c..f55eeeea7e5 100644 --- a/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs +++ b/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs @@ -7,20 +7,20 @@ impl FormatRule for FormatJsAnyObjectAssignm type Context = JsFormatContext; fn format( node: &JsAnyObjectAssignmentPatternMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { JsAnyObjectAssignmentPatternMember::JsObjectAssignmentPatternShorthandProperty( node, - ) => formatted![formatter, [node.format()]], + ) => node.format().format(f), JsAnyObjectAssignmentPatternMember::JsObjectAssignmentPatternProperty(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyObjectAssignmentPatternMember::JsObjectAssignmentPatternRest(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyObjectAssignmentPatternMember::JsUnknownAssignment(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } } } diff --git a/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs b/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs index 235c4244de1..17c8153e4ea 100644 --- a/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs +++ b/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs @@ -7,24 +7,20 @@ impl FormatRule for FormatJsAnyObjectBindingPat type Context = JsFormatContext; fn format( node: &JsAnyObjectBindingPatternMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { JsAnyObjectBindingPatternMember::JsObjectBindingPatternProperty(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyObjectBindingPatternMember::JsObjectBindingPatternRest(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } JsAnyObjectBindingPatternMember::JsObjectBindingPatternShorthandProperty(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectBindingPatternMember::JsIdentifierBinding(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectBindingPatternMember::JsUnknownBinding(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + JsAnyObjectBindingPatternMember::JsIdentifierBinding(node) => node.format().format(f), + JsAnyObjectBindingPatternMember::JsUnknownBinding(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/object_member.rs b/crates/rome_js_formatter/src/js/any/object_member.rs index 17c842d9f49..c0fd8e8f336 100644 --- a/crates/rome_js_formatter/src/js/any/object_member.rs +++ b/crates/rome_js_formatter/src/js/any/object_member.rs @@ -5,19 +5,15 @@ use crate::prelude::*; use rome_js_syntax::JsAnyObjectMember; impl FormatRule for FormatJsAnyObjectMember { type Context = JsFormatContext; - fn format(node: &JsAnyObjectMember, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyObjectMember, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyObjectMember::JsPropertyObjectMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectMember::JsMethodObjectMember(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsGetterObjectMember(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsSetterObjectMember(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsShorthandPropertyObjectMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectMember::JsSpread(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsUnknownMember(node) => formatted![formatter, [node.format()]], + JsAnyObjectMember::JsPropertyObjectMember(node) => node.format().format(f), + JsAnyObjectMember::JsMethodObjectMember(node) => node.format().format(f), + JsAnyObjectMember::JsGetterObjectMember(node) => node.format().format(f), + JsAnyObjectMember::JsSetterObjectMember(node) => node.format().format(f), + JsAnyObjectMember::JsShorthandPropertyObjectMember(node) => node.format().format(f), + JsAnyObjectMember::JsSpread(node) => node.format().format(f), + JsAnyObjectMember::JsUnknownMember(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/object_member_name.rs b/crates/rome_js_formatter/src/js/any/object_member_name.rs index 2f5e3775d6f..4ff59028376 100644 --- a/crates/rome_js_formatter/src/js/any/object_member_name.rs +++ b/crates/rome_js_formatter/src/js/any/object_member_name.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyObjectMemberName; impl FormatRule for FormatJsAnyObjectMemberName { type Context = JsFormatContext; - fn format( - node: &JsAnyObjectMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyObjectMemberName, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyObjectMemberName::JsLiteralMemberName(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectMemberName::JsComputedMemberName(node) => { - formatted![formatter, [node.format()]] - } + JsAnyObjectMemberName::JsLiteralMemberName(node) => node.format().format(f), + JsAnyObjectMemberName::JsComputedMemberName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/parameter.rs b/crates/rome_js_formatter/src/js/any/parameter.rs index edfba83b1e9..bcccf5c1f3b 100644 --- a/crates/rome_js_formatter/src/js/any/parameter.rs +++ b/crates/rome_js_formatter/src/js/any/parameter.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyParameter; impl FormatRule for FormatJsAnyParameter { type Context = JsFormatContext; - fn format(node: &JsAnyParameter, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyParameter, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyParameter::JsAnyFormalParameter(node) => formatted![formatter, [node.format()]], - JsAnyParameter::JsRestParameter(node) => formatted![formatter, [node.format()]], - JsAnyParameter::TsThisParameter(node) => formatted![formatter, [node.format()]], + JsAnyParameter::JsAnyFormalParameter(node) => node.format().format(f), + JsAnyParameter::JsRestParameter(node) => node.format().format(f), + JsAnyParameter::TsThisParameter(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/property_modifier.rs b/crates/rome_js_formatter/src/js/any/property_modifier.rs index 11760aaaa31..59f7a7a90ea 100644 --- a/crates/rome_js_formatter/src/js/any/property_modifier.rs +++ b/crates/rome_js_formatter/src/js/any/property_modifier.rs @@ -5,21 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsAnyPropertyModifier; impl FormatRule for FormatJsAnyPropertyModifier { type Context = JsFormatContext; - fn format( - node: &JsAnyPropertyModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsAnyPropertyModifier, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyPropertyModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyPropertyModifier::JsStaticModifier(node) => formatted![formatter, [node.format()]], - JsAnyPropertyModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyPropertyModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } + JsAnyPropertyModifier::TsAccessibilityModifier(node) => node.format().format(f), + JsAnyPropertyModifier::JsStaticModifier(node) => node.format().format(f), + JsAnyPropertyModifier::TsReadonlyModifier(node) => node.format().format(f), + JsAnyPropertyModifier::TsOverrideModifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/root.rs b/crates/rome_js_formatter/src/js/any/root.rs index 7d697990097..7a0360c67e7 100644 --- a/crates/rome_js_formatter/src/js/any/root.rs +++ b/crates/rome_js_formatter/src/js/any/root.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyRoot; impl FormatRule for FormatJsAnyRoot { type Context = JsFormatContext; - fn format(node: &JsAnyRoot, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyRoot, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyRoot::JsScript(node) => formatted![formatter, [node.format()]], - JsAnyRoot::JsModule(node) => formatted![formatter, [node.format()]], - JsAnyRoot::JsExpressionSnipped(node) => formatted![formatter, [node.format()]], + JsAnyRoot::JsScript(node) => node.format().format(f), + JsAnyRoot::JsModule(node) => node.format().format(f), + JsAnyRoot::JsExpressionSnipped(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/statement.rs b/crates/rome_js_formatter/src/js/any/statement.rs index 030abd5a44d..f51ac7663c0 100644 --- a/crates/rome_js_formatter/src/js/any/statement.rs +++ b/crates/rome_js_formatter/src/js/any/statement.rs @@ -5,46 +5,40 @@ use crate::prelude::*; use rome_js_syntax::JsAnyStatement; impl FormatRule for FormatJsAnyStatement { type Context = JsFormatContext; - fn format(node: &JsAnyStatement, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyStatement, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyStatement::JsBlockStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsBreakStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsClassDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsContinueStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsDebuggerStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsDoWhileStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsEmptyStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsExpressionStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsForInStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsForOfStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsForStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsIfStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsLabeledStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsReturnStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsSwitchStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsThrowStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsTryFinallyStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsTryStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsUnknownStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsVariableStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsWhileStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsWithStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsFunctionDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsEnumDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsTypeAliasDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsInterfaceDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyStatement::TsDeclareStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsModuleDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsExternalModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyStatement::TsGlobalDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsImportEqualsDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyStatement::JsBlockStatement(node) => node.format().format(f), + JsAnyStatement::JsBreakStatement(node) => node.format().format(f), + JsAnyStatement::JsClassDeclaration(node) => node.format().format(f), + JsAnyStatement::JsContinueStatement(node) => node.format().format(f), + JsAnyStatement::JsDebuggerStatement(node) => node.format().format(f), + JsAnyStatement::JsDoWhileStatement(node) => node.format().format(f), + JsAnyStatement::JsEmptyStatement(node) => node.format().format(f), + JsAnyStatement::JsExpressionStatement(node) => node.format().format(f), + JsAnyStatement::JsForInStatement(node) => node.format().format(f), + JsAnyStatement::JsForOfStatement(node) => node.format().format(f), + JsAnyStatement::JsForStatement(node) => node.format().format(f), + JsAnyStatement::JsIfStatement(node) => node.format().format(f), + JsAnyStatement::JsLabeledStatement(node) => node.format().format(f), + JsAnyStatement::JsReturnStatement(node) => node.format().format(f), + JsAnyStatement::JsSwitchStatement(node) => node.format().format(f), + JsAnyStatement::JsThrowStatement(node) => node.format().format(f), + JsAnyStatement::JsTryFinallyStatement(node) => node.format().format(f), + JsAnyStatement::JsTryStatement(node) => node.format().format(f), + JsAnyStatement::JsUnknownStatement(node) => node.format().format(f), + JsAnyStatement::JsVariableStatement(node) => node.format().format(f), + JsAnyStatement::JsWhileStatement(node) => node.format().format(f), + JsAnyStatement::JsWithStatement(node) => node.format().format(f), + JsAnyStatement::JsFunctionDeclaration(node) => node.format().format(f), + JsAnyStatement::TsEnumDeclaration(node) => node.format().format(f), + JsAnyStatement::TsTypeAliasDeclaration(node) => node.format().format(f), + JsAnyStatement::TsInterfaceDeclaration(node) => node.format().format(f), + JsAnyStatement::TsDeclareFunctionDeclaration(node) => node.format().format(f), + JsAnyStatement::TsDeclareStatement(node) => node.format().format(f), + JsAnyStatement::TsModuleDeclaration(node) => node.format().format(f), + JsAnyStatement::TsExternalModuleDeclaration(node) => node.format().format(f), + JsAnyStatement::TsGlobalDeclaration(node) => node.format().format(f), + JsAnyStatement::TsImportEqualsDeclaration(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/switch_clause.rs b/crates/rome_js_formatter/src/js/any/switch_clause.rs index 944efbb6ca5..60bd0783580 100644 --- a/crates/rome_js_formatter/src/js/any/switch_clause.rs +++ b/crates/rome_js_formatter/src/js/any/switch_clause.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnySwitchClause; impl FormatRule for FormatJsAnySwitchClause { type Context = JsFormatContext; - fn format(node: &JsAnySwitchClause, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnySwitchClause, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnySwitchClause::JsCaseClause(node) => formatted![formatter, [node.format()]], - JsAnySwitchClause::JsDefaultClause(node) => formatted![formatter, [node.format()]], + JsAnySwitchClause::JsCaseClause(node) => node.format().format(f), + JsAnySwitchClause::JsDefaultClause(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/template_element.rs b/crates/rome_js_formatter/src/js/any/template_element.rs index ff583ae72ed..9f07073b956 100644 --- a/crates/rome_js_formatter/src/js/any/template_element.rs +++ b/crates/rome_js_formatter/src/js/any/template_element.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyTemplateElement; impl FormatRule for FormatJsAnyTemplateElement { type Context = JsFormatContext; - fn format(node: &JsAnyTemplateElement, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsAnyTemplateElement, f: &mut Formatter) -> FormatResult<()> { match node { - JsAnyTemplateElement::JsTemplateChunkElement(node) => { - formatted![formatter, [node.format()]] - } - JsAnyTemplateElement::JsTemplateElement(node) => formatted![formatter, [node.format()]], + JsAnyTemplateElement::JsTemplateChunkElement(node) => node.format().format(f), + JsAnyTemplateElement::JsTemplateElement(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs index c09840c79cf..7db21134a68 100644 --- a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs +++ b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsArrayAssignmentPattern; use rome_js_syntax::JsArrayAssignmentPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrayAssignmentPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsArrayAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayAssignmentPatternFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - formatter - .delimited( - &l_brack_token?, - formatted![formatter, [elements.format()]]?, - &r_brack_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_brack_token?, &elements.format(), &r_brack_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs index 0eb58d7137a..b804dc592e2 100644 --- a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs +++ b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsArrayAssignmentPatternRestElement; @@ -9,13 +10,13 @@ impl FormatNodeFields { fn format_fields( node: &JsArrayAssignmentPatternRestElement, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsArrayAssignmentPatternRestElementFields { dotdotdot_token, pattern, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), pattern.format()]] + write!(f, [dotdotdot_token.format(), pattern.format()]) } } diff --git a/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs b/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs index a775d7ba2b9..4b7d49b2730 100644 --- a/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs +++ b/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs @@ -1,22 +1,20 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAssignmentWithDefault; use rome_js_syntax::JsAssignmentWithDefaultFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsAssignmentWithDefault, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsAssignmentWithDefault, f: &mut JsFormatter) -> FormatResult<()> { let JsAssignmentWithDefaultFields { pattern, eq_token, default, } = node.as_fields(); - formatted![ - formatter, + write!( + f, [ pattern.format(), space_token(), @@ -24,6 +22,6 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsComputedMemberAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsComputedMemberAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsComputedMemberAssignmentFields { object, l_brack_token, @@ -16,14 +14,14 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsIdentifierAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsIdentifierAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierAssignmentFields { name_token } = node.as_fields(); - formatted![formatter, [name_token.format()]] + write![f, [name_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs index 4c735588ec0..a7632ff4a3c 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs @@ -1,26 +1,23 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsObjectAssignmentPattern; use rome_js_syntax::JsObjectAssignmentPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectAssignmentPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsObjectAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectAssignmentPatternFields { l_curly_token, properties, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [properties.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &properties.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs index 2225a3ca958..69a18ef4f19 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsObjectAssignmentPatternProperty; @@ -9,8 +10,8 @@ impl FormatNodeFields { fn format_fields( node: &JsObjectAssignmentPatternProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectAssignmentPatternPropertyFields { member, colon_token, @@ -18,16 +19,20 @@ impl FormatNodeFields init, } = node.as_fields(); - formatted![ - formatter, + write!( + f, [ member.format(), colon_token.format(), space_token(), pattern.format(), - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]), ] - ] + )?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs index e328005a19f..6835604b8c4 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsObjectAssignmentPatternRest; @@ -9,13 +10,13 @@ impl FormatNodeFields { fn format_fields( node: &JsObjectAssignmentPatternRest, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectAssignmentPatternRestFields { dotdotdot_token, target, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), target.format()?,]] + write!(f, [dotdotdot_token.format(), target.format()]) } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs index 6de00d3bfd0..b92429f496a 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsObjectAssignmentPatternShorthandProperty; @@ -9,18 +10,16 @@ impl FormatNodeFields { fn format_fields( node: &JsObjectAssignmentPatternShorthandProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectAssignmentPatternShorthandPropertyFields { identifier, init } = node.as_fields(); - formatted![ - formatter, - [ - identifier.format()?, - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]) - ] - ] + write!(f, [identifier.format()?,])?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs b/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs index 9b2e640998d..2ae3567d73c 100644 --- a/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs +++ b/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsParenthesizedAssignment; use rome_js_syntax::JsParenthesizedAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsParenthesizedAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsParenthesizedAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsParenthesizedAssignmentFields { l_paren_token, assignment, r_paren_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_paren_token.format(), assignment.format(), diff --git a/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs b/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs index 44827bc5b66..6646ffd98e4 100644 --- a/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs +++ b/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs @@ -1,22 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsStaticMemberAssignment; use rome_js_syntax::JsStaticMemberAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStaticMemberAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsStaticMemberAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsStaticMemberAssignmentFields { object, dot_token, member, } = node.as_fields(); - formatted![ - formatter, - [object.format(), dot_token.format(), member.format(),] - ] + write![f, [object.format(), dot_token.format(), member.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs b/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs index eba22d0ea5f..4dc7f0f5e63 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs @@ -4,7 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsArrayHole; impl FormatNodeFields for FormatNodeRule { - fn format_fields(_: &JsArrayHole, _: &JsFormatter) -> FormatResult { - Ok(empty_element()) + fn format_fields(_: &JsArrayHole, _: &mut JsFormatter) -> FormatResult<()> { + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs index a7fa42e30d8..fcb696245b6 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs @@ -1,13 +1,14 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::prelude::*; -use rome_js_syntax::JsAnyStatement; -use rome_rowan::AstNodeList; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; +use rome_js_syntax::JsAnyStatement; use rome_js_syntax::JsCaseClause; use rome_js_syntax::JsCaseClauseFields; +use rome_rowan::AstNodeList; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsCaseClause, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsCaseClause, f: &mut JsFormatter) -> FormatResult<()> { let JsCaseClauseFields { case_token, test, @@ -15,27 +16,40 @@ impl FormatNodeFields for FormatNodeRule { consequent, } = node.as_fields(); + write!( + f, + [ + case_token.format(), + space_token(), + test.format(), + colon_token.format() + ] + )?; + let is_first_child_block_stmt = matches!( consequent.iter().next(), Some(JsAnyStatement::JsBlockStatement(_)) ); - let case_word = case_token.format(); - let colon = colon_token.format(); - let test = test.format(); - let cons = formatter.format_list(&consequent); - let cons = if cons.is_empty() { + let format_consequent = format_with(|f| { + f.join_with(&hard_line_break()) + .entries(consequent.try_format_nodes()) + .finish() + }); + + if consequent.is_empty() { // Skip inserting an indent block is the consequent is empty to print // the trailing comments for the case clause inline if there is no // block to push them into - hard_line_break() + return write!(f, [hard_line_break()]); } else if is_first_child_block_stmt { - formatted![formatter, [space_token(), cons]]? + write![f, [space_token(), format_consequent]] } else { // no line break needed after because it is added by the indent in the switch statement - indent(formatted![formatter, [hard_line_break(), cons]]?) - }; - - formatted![formatter, [case_word, space_token(), test, colon, cons]] + write!( + f, + [indent(&format_args![hard_line_break(), format_consequent])] + ) + } } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs index 1dbbcbcd16e..d461caf60b0 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs @@ -1,39 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsCatchClause; use rome_js_syntax::JsCatchClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsCatchClause, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsCatchClause, f: &mut JsFormatter) -> FormatResult<()> { let JsCatchClauseFields { catch_token, declaration, body, } = node.as_fields(); - formatted![ - formatter, - [declaration.format().with_or( - |declaration| { - formatted![ - formatter, - [ - catch_token.format(), - space_token(), - declaration, - space_token(), - body.format() - ] - ] - }, - || { - formatted![ - formatter, - [catch_token.format(), space_token(), body.format()] - ] - }, - )] - ] + write!(f, [catch_token.format(), space_token()])?; + + if let Some(declaration) = declaration { + write![f, [declaration.format(), space_token()]]?; + } + + write!(f, [body.format()]) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs index b5ecf849f89..29ac5d2cb6a 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs @@ -1,15 +1,14 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsDefaultClause; use rome_js_syntax::{JsAnyStatement, JsDefaultClauseFields}; use rome_rowan::AstNodeList; +use std::os::linux::raw::stat; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDefaultClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsDefaultClause, f: &mut JsFormatter) -> FormatResult<()> { let JsDefaultClauseFields { default_token, colon_token, @@ -21,18 +20,27 @@ impl FormatNodeFields for FormatNodeRule { Some(JsAnyStatement::JsBlockStatement(_)) ); - let default = default_token.format(); - let colon = colon_token.format(); - let statements = formatter.format_list(&consequent); + write!( + f, + [default_token.format(), colon_token.format(), space_token()] + )?; + + let format_statements = format_with(|f| { + f.join_with(&hard_line_break()) + .entries(consequent.try_format_nodes()) + .finish() + }); - let formatted_cons = if statements.is_empty() { - hard_line_break() + if consequent.is_empty() { + write!(f, [hard_line_break()]) } else if first_child_is_block_stmt { - formatted![formatter, [space_token(), statements]]? + write!(f, [space_token(), format_statements]) } else { // no line break needed after because it is added by the indent in the switch statement - indent(formatted![formatter, [hard_line_break(), statements]]?) - }; - formatted![formatter, [default, colon, space_token(), formatted_cons]] + write!( + f, + [indent(&format_args!(hard_line_break(), format_statements))] + ) + } } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/directive.rs b/crates/rome_js_formatter/src/js/auxiliary/directive.rs index 1257f4d6037..1c46c65a954 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/directive.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/directive.rs @@ -1,20 +1,24 @@ use crate::prelude::*; -use crate::utils::{format_with_semicolon, FormatLiteralStringToken}; +use crate::utils::{FormatLiteralStringToken, FormatWithSemicolon}; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::JsDirective; use rome_js_syntax::JsDirectiveFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsDirective, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsDirective, f: &mut JsFormatter) -> FormatResult<()> { let JsDirectiveFields { value_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - FormatLiteralStringToken::from_directive(&value_token?).format(formatter)?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &FormatLiteralStringToken::from_directive(&value_token?), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs index c16c8d04f0e..f40bc6963b4 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsElseClause; use rome_js_syntax::JsElseClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsElseClause, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsElseClause, f: &mut JsFormatter) -> FormatResult<()> { let JsElseClauseFields { else_token, alternate, } = node.as_fields(); - formatted![ - formatter, - [else_token.format(), space_token(), alternate.format(),] - ] + write![f, [else_token.format(), space_token(), alternate.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs b/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs index 25075b461df..0ab044242e5 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs @@ -1,24 +1,21 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsExpressionSnipped; use rome_js_syntax::JsExpressionSnippedFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExpressionSnipped, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExpressionSnipped, f: &mut JsFormatter) -> FormatResult<()> { let JsExpressionSnippedFields { expression, eof_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ expression.format(), - formatter.format_replaced(&eof_token?, empty_element()), + f.format_replaced(&eof_token?, &empty_element()), ] ] } diff --git a/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs index 781358f55ea..c90379ae321 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs @@ -1,22 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsFinallyClause; use rome_js_syntax::JsFinallyClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFinallyClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsFinallyClause, f: &mut JsFormatter) -> FormatResult<()> { let JsFinallyClauseFields { finally_token, body, } = node.as_fields(); - formatted![ - formatter, - [finally_token.format(), space_token(), body.format()] - ] + write![f, [finally_token.format(), space_token(), body.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/function_body.rs b/crates/rome_js_formatter/src/js/auxiliary/function_body.rs index eeec8987c80..0cda2fe21e8 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/function_body.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/function_body.rs @@ -1,14 +1,12 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsFunctionBody; use rome_js_syntax::JsFunctionBodyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFunctionBody, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsFunctionBody, f: &mut JsFormatter) -> FormatResult<()> { let JsFunctionBodyFields { l_curly_token, directives, @@ -16,16 +14,20 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - formatter - .delimited( + let format_statements = format_with(|f| { + f.join_with(&hard_line_break()) + .entries(statements.try_format_nodes()) + .finish() + }); + + write!( + f, + [f.delimited( &l_curly_token?, - formatted![ - formatter, - [directives.format(), formatter.format_list(&statements),] - ]?, + &format_args![directives.format(), format_statements], &r_curly_token?, ) - .block_indent() - .finish() + .block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs index cc3a9c11102..c9a241f1fa3 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs @@ -1,22 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsInitializerClause; use rome_js_syntax::JsInitializerClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsInitializerClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsInitializerClause, f: &mut JsFormatter) -> FormatResult<()> { let JsInitializerClauseFields { eq_token, expression, } = node.as_fields(); - formatted![ - formatter, - [eq_token.format(), space_token(), expression.format()] - ] + write![f, [eq_token.format(), space_token(), expression.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/module.rs b/crates/rome_js_formatter/src/js/auxiliary/module.rs index 5e000bab159..2b12b09fb03 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/module.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/module.rs @@ -1,12 +1,14 @@ use crate::prelude::*; -use crate::utils::format_interpreter; +use rome_formatter::{format_args, write}; +use crate::formatter::TryFormatNodeListExtension; +use crate::utils::FormatInterpreterToken; use crate::FormatNodeFields; use rome_js_syntax::JsModule; use rome_js_syntax::JsModuleFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsModule, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsModule, f: &mut JsFormatter) -> FormatResult<()> { let JsModuleFields { interpreter_token, directives, @@ -14,15 +16,24 @@ impl FormatNodeFields for FormatNodeRule { eof_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ - format_interpreter(interpreter_token, formatter)?, - directives.format(), - formatter.format_list(&items), - formatter.format_replaced(&eof_token?, empty_element()), + FormatInterpreterToken::new(interpreter_token.as_ref()), + directives.format() + ] + ]?; + + f.join_with(&hard_line_break()) + .entries(items.try_format_nodes()) + .finish()?; + + write!( + f, + [ + f.format_replaced(&eof_token?, &empty_element()), hard_line_break() ] - ] + ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/name.rs b/crates/rome_js_formatter/src/js/auxiliary/name.rs index bc66baebcd2..3ae95ae8624 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/name.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/name.rs @@ -1,13 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsName; use rome_js_syntax::JsNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsName, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsName, f: &mut JsFormatter) -> FormatResult<()> { let JsNameFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/new_target.rs b/crates/rome_js_formatter/src/js/auxiliary/new_target.rs index c967888c1df..a0c2e2779dd 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/new_target.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/new_target.rs @@ -1,19 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::NewTarget; use rome_js_syntax::NewTargetFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &NewTarget, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &NewTarget, f: &mut JsFormatter) -> FormatResult<()> { let NewTargetFields { new_token, dot_token, target_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ new_token.format(), dot_token.format(), diff --git a/crates/rome_js_formatter/src/js/auxiliary/private_name.rs b/crates/rome_js_formatter/src/js/auxiliary/private_name.rs index d80cef61882..06621763a49 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/private_name.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/private_name.rs @@ -1,16 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsPrivateName; use rome_js_syntax::JsPrivateNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsPrivateName, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsPrivateName, f: &mut JsFormatter) -> FormatResult<()> { let JsPrivateNameFields { hash_token, value_token, } = node.as_fields(); - formatted![formatter, [hash_token.format(), value_token.format()]] + write![f, [hash_token.format(), value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs b/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs index 4445bf63f7d..335c2d27ea8 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsReferenceIdentifier; use rome_js_syntax::JsReferenceIdentifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsReferenceIdentifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsReferenceIdentifier, f: &mut JsFormatter) -> FormatResult<()> { let JsReferenceIdentifierFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/script.rs b/crates/rome_js_formatter/src/js/auxiliary/script.rs index 43e65195a65..a09fe2f0798 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/script.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/script.rs @@ -1,12 +1,14 @@ use crate::prelude::*; -use crate::utils::format_interpreter; +use crate::utils::FormatInterpreterToken; +use rome_formatter::{format_args, write}; +use crate::formatter::TryFormatNodeListExtension; use crate::FormatNodeFields; use rome_js_syntax::JsScript; use rome_js_syntax::JsScriptFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsScript, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsScript, f: &mut JsFormatter) -> FormatResult<()> { let JsScriptFields { interpreter_token, directives, @@ -14,13 +16,22 @@ impl FormatNodeFields for FormatNodeRule { eof_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ - format_interpreter(interpreter_token, formatter)?, + FormatInterpreterToken::new(interpreter_token.as_ref()), directives.format(), - formatter.format_list(&statements), - formatter.format_replaced(&eof_token?, empty_element()), + ] + ]?; + + f.join_with(&hard_line_break()) + .entries(statements.try_format_nodes()) + .finish()?; + + write![ + f, + [ + f.format_replaced(&eof_token?, &empty_element()), hard_line_break() ] ] diff --git a/crates/rome_js_formatter/src/js/auxiliary/spread.rs b/crates/rome_js_formatter/src/js/auxiliary/spread.rs index fcb2654747f..61e69b70f6c 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/spread.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/spread.rs @@ -1,16 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsSpread; use rome_js_syntax::JsSpreadFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsSpread, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsSpread, f: &mut JsFormatter) -> FormatResult<()> { let JsSpreadFields { dotdotdot_token, argument, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), argument.format()]] + write![f, [dotdotdot_token.format(), argument.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs index 3ec7f421f92..b96ebb25e7e 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsStaticModifier; diff --git a/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs index f00899cc763..8c0ca09ccd2 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs @@ -1,24 +1,23 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; - +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsVariableDeclarationClause; use rome_js_syntax::JsVariableDeclarationClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableDeclarationClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsVariableDeclarationClause, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableDeclarationClauseFields { declaration, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [declaration.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &declaration.format(), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs b/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs index 4b953ca152c..f04c2995aa0 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs @@ -1,26 +1,25 @@ use crate::prelude::*; -use crate::utils::format_initializer_clause; - +use crate::utils::FormatInitializerClause; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsVariableDeclarator; use rome_js_syntax::JsVariableDeclaratorFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableDeclarator, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsVariableDeclarator, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableDeclaratorFields { id, variable_annotation, initializer, } = node.as_fields(); - let initializer = format_initializer_clause(formatter, initializer)?; - - formatted![ - formatter, - [id.format(), variable_annotation.format(), initializer] + write![ + f, + [ + id.format(), + variable_annotation.format(), + FormatInitializerClause::new(initializer.as_ref()) + ] ] } } diff --git a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs index b7fb5c10748..5e51782ef2d 100644 --- a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs +++ b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsArrayBindingPattern; use rome_js_syntax::JsArrayBindingPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrayBindingPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsArrayBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayBindingPatternFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - formatter - .delimited( - &l_brack_token?, - formatted![formatter, [elements.format()]]?, - &r_brack_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_brack_token?, &elements.format(), &r_brack_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs index 406670b0578..b4651ab5d48 100644 --- a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs +++ b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs @@ -1,6 +1,6 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsArrayBindingPatternRestElement; use rome_js_syntax::JsArrayBindingPatternRestElementFields; @@ -9,13 +9,13 @@ impl FormatNodeFields { fn format_fields( node: &JsArrayBindingPatternRestElement, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsArrayBindingPatternRestElementFields { dotdotdot_token, pattern, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), pattern.format(),]] + write![f, [dotdotdot_token.format(), pattern.format()]] } } diff --git a/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs b/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs index d5690d111d6..f4c5b33c230 100644 --- a/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs +++ b/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs @@ -1,22 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsBindingPatternWithDefault; use rome_js_syntax::JsBindingPatternWithDefaultFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBindingPatternWithDefault, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsBindingPatternWithDefault, f: &mut JsFormatter) -> FormatResult<()> { let JsBindingPatternWithDefaultFields { pattern, eq_token, default, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ pattern.format(), space_token(), diff --git a/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs b/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs index 8a196ba135f..1e6d0b2c820 100644 --- a/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs +++ b/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsConstructorParameters; use rome_js_syntax::JsConstructorParametersFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsConstructorParameters, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsConstructorParameters, f: &mut JsFormatter) -> FormatResult<()> { let JsConstructorParametersFields { l_paren_token, parameters, r_paren_token, } = node.as_fields(); - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [parameters.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_paren_token?, ¶meters.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs b/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs index 17661e08cfe..8153bbd54cb 100644 --- a/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs +++ b/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_initializer_clause; +use rome_formatter::{format_args, write}; +use crate::utils::FormatInitializerClause; use crate::FormatNodeFields; use rome_js_syntax::JsFormalParameter; use rome_js_syntax::JsFormalParameterFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFormalParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsFormalParameter, f: &mut JsFormatter) -> FormatResult<()> { let JsFormalParameterFields { binding, question_mark_token, @@ -17,15 +15,13 @@ impl FormatNodeFields for FormatNodeRule { initializer, } = node.as_fields(); - let initializer = format_initializer_clause(formatter, initializer)?; - - formatted![ - formatter, + write![ + f, [ binding.format(), question_mark_token.format(), type_annotation.format(), - initializer + FormatInitializerClause::new(initializer.as_ref()) ] ] } diff --git a/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs b/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs index 567e88f5efb..a71fe228b0a 100644 --- a/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs +++ b/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsIdentifierBinding; use rome_js_syntax::JsIdentifierBindingFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsIdentifierBinding, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsIdentifierBinding, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierBindingFields { name_token } = node.as_fields(); - formatted![formatter, [name_token.format()]] + write![f, [name_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs index b9f9709c3f6..dde96363c34 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsObjectBindingPattern; use rome_js_syntax::JsObjectBindingPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectBindingPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsObjectBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectBindingPatternFields { l_curly_token, properties, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [properties.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &properties.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs index b9f665a5330..475e0f58d51 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs @@ -1,6 +1,6 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsObjectBindingPatternProperty; use rome_js_syntax::JsObjectBindingPatternPropertyFields; @@ -9,8 +9,8 @@ impl FormatNodeFields { fn format_fields( node: &JsObjectBindingPatternProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectBindingPatternPropertyFields { member, colon_token, @@ -18,16 +18,20 @@ impl FormatNodeFields init, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ member.format(), colon_token.format(), space_token(), pattern.format(), - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]), ] - ] + ]?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs index f81b8f4706f..b6db6bd3b1b 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsObjectBindingPatternRest; use rome_js_syntax::JsObjectBindingPatternRestFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectBindingPatternRest, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsObjectBindingPatternRest, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectBindingPatternRestFields { dotdotdot_token, binding, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), binding.format(),]] + write![f, [dotdotdot_token.format(), binding.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs index 5e4f560ee60..92b1c339cd6 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs @@ -1,6 +1,6 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsObjectBindingPatternShorthandProperty; use rome_js_syntax::JsObjectBindingPatternShorthandPropertyFields; @@ -9,17 +9,16 @@ impl FormatNodeFields { fn format_fields( node: &JsObjectBindingPatternShorthandProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectBindingPatternShorthandPropertyFields { identifier, init } = node.as_fields(); - formatted![ - formatter, - [ - identifier.format(), - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]) - ] - ] + write![f, [identifier.format()]]?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/bindings/parameters.rs b/crates/rome_js_formatter/src/js/bindings/parameters.rs index b57c6368373..fd260c87208 100644 --- a/crates/rome_js_formatter/src/js/bindings/parameters.rs +++ b/crates/rome_js_formatter/src/js/bindings/parameters.rs @@ -1,24 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsParameters; use rome_js_syntax::JsParametersFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsParameters, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsParameters, f: &mut JsFormatter) -> FormatResult<()> { let JsParametersFields { l_paren_token, items, r_paren_token, } = node.as_fields(); - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [items.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_paren_token?, &items.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs b/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs index 2dfe6062ceb..8b57a4c6b99 100644 --- a/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs +++ b/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs @@ -1,22 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsRestParameter; use rome_js_syntax::JsRestParameterFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsRestParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsRestParameter, f: &mut JsFormatter) -> FormatResult<()> { let JsRestParameterFields { dotdotdot_token, binding, type_annotation, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ dotdotdot_token.format(), binding.format(), diff --git a/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs b/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs index b1c70e866d9..888dccb19b6 100644 --- a/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs +++ b/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsConstructorClassMember; use rome_js_syntax::JsConstructorClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsConstructorClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsConstructorClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsConstructorClassMemberFields { modifiers, name, @@ -16,8 +13,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsEmptyClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsEmptyClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsEmptyClassMemberFields { semicolon_token } = node.as_fields(); - Ok(formatter.format_replaced(&semicolon_token?, empty_element())) + write!(f, [f.format_replaced(&semicolon_token?, &empty_element())]) } } diff --git a/crates/rome_js_formatter/src/js/classes/extends_clause.rs b/crates/rome_js_formatter/src/js/classes/extends_clause.rs index c8ca92d2d81..bf51e609852 100644 --- a/crates/rome_js_formatter/src/js/classes/extends_clause.rs +++ b/crates/rome_js_formatter/src/js/classes/extends_clause.rs @@ -1,28 +1,25 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsExtendsClause; use rome_js_syntax::JsExtendsClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExtendsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExtendsClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExtendsClauseFields { extends_token, super_class, type_arguments, } = node.as_fields(); - Ok(formatted![ - formatter, + write![ + f, [ extends_token.format(), space_token(), super_class.format(), type_arguments.format(), ] - ]?) + ] } } diff --git a/crates/rome_js_formatter/src/js/classes/getter_class_member.rs b/crates/rome_js_formatter/src/js/classes/getter_class_member.rs index ee6d8e91f39..dba2d93d725 100644 --- a/crates/rome_js_formatter/src/js/classes/getter_class_member.rs +++ b/crates/rome_js_formatter/src/js/classes/getter_class_member.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsGetterClassMember; use rome_js_syntax::JsGetterClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsGetterClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsGetterClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsGetterClassMemberFields { modifiers, get_token, @@ -19,8 +16,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsMethodClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsMethodClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsMethodClassMemberFields { modifiers, async_token, @@ -21,14 +18,15 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsPropertyClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsPropertyClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsPropertyClassMemberFields { modifiers, name, @@ -19,21 +16,20 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsSetterClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsSetterClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsSetterClassMemberFields { modifiers, set_token, @@ -19,8 +16,8 @@ impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &JsStaticInitializationBlockClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsStaticInitializationBlockClassMemberFields { static_token, l_curly_token, @@ -18,15 +19,20 @@ impl FormatNodeFields r_curly_token, } = node.as_fields(); - let static_token = static_token.format(); - let separated = formatter - .delimited( - &l_curly_token?, - formatter.format_list(&statements), - &r_curly_token?, - ) - .block_indent() - .finish()?; - formatted![formatter, [static_token, space_token(), separated]] + write!(f, [static_token.format(), space_token()])?; + + let format_statements = format_with(|f| { + f.join_with(&hard_line_break()) + .entries(statements.try_format_nodes()) + .finish() + }); + + write!( + f, + [ + f.delimited(&l_curly_token?, &format_statements, &r_curly_token?) + .block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs b/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs index 3ccf37a88ae..3aec7b89d31 100644 --- a/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsCatchDeclaration; use rome_js_syntax::JsCatchDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsCatchDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsCatchDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let JsCatchDeclarationFields { l_paren_token, binding, @@ -16,13 +13,14 @@ impl FormatNodeFields for FormatNodeRule type_annotation, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [f.delimited( &l_paren_token?, - formatted![formatter, [binding.format(), type_annotation.format()]]?, + &format_args![binding.format(), type_annotation.format()], &r_paren_token?, ) - .soft_block_indent() - .finish() + .soft_block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/js/declarations/class_declaration.rs b/crates/rome_js_formatter/src/js/declarations/class_declaration.rs index 97ec925eb95..12e2403f5ad 100644 --- a/crates/rome_js_formatter/src/js/declarations/class_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/class_declaration.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyClass, JsClassDeclaration}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsClassDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyClass::from(node.clone()).format()]] + fn format_fields(node: &JsClassDeclaration, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyClass::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs b/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs index a0b3a723edc..ec0a8417e52 100644 --- a/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs @@ -1,6 +1,6 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsAnyClass; use rome_js_syntax::JsClassExportDefaultDeclaration; @@ -9,8 +9,8 @@ impl FormatNodeFields { fn format_fields( node: &JsClassExportDefaultDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyClass::from(node.clone()).format()]] + f: &mut JsFormatter, + ) -> FormatResult<()> { + write![f, [JsAnyClass::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs b/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs index bf346641a17..52b8de6c4da 100644 --- a/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs @@ -1,21 +1,18 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsForVariableDeclaration; use rome_js_syntax::JsForVariableDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForVariableDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsForVariableDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let JsForVariableDeclarationFields { kind_token, declarator, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [kind_token.format(), space_token(), declarator.format(),] ] } diff --git a/crates/rome_js_formatter/src/js/declarations/function_declaration.rs b/crates/rome_js_formatter/src/js/declarations/function_declaration.rs index 3ea96a21d6e..f416e493fa2 100644 --- a/crates/rome_js_formatter/src/js/declarations/function_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/function_declaration.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyFunction, JsFunctionDeclaration}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFunctionDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + fn format_fields(node: &JsFunctionDeclaration, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs b/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs index 5bd4c7b9b01..c1e09807bb0 100644 --- a/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAnyFunction; @@ -9,8 +10,8 @@ impl FormatNodeFields { fn format_fields( node: &JsFunctionExportDefaultDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + f: &mut JsFormatter, + ) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs b/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs index 583e8987908..e2d60e91f0b 100644 --- a/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs @@ -1,19 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsVariableDeclaration; use rome_js_syntax::JsVariableDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsVariableDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableDeclarationFields { kind, declarators } = node.as_fields(); - formatted![ - formatter, - [kind.format(), space_token(), declarators.format(),] - ] + write![f, [kind.format(), space_token(), declarators.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/array_expression.rs b/crates/rome_js_formatter/src/js/expressions/array_expression.rs index 2913c0d000c..cdb3d1f6307 100644 --- a/crates/rome_js_formatter/src/js/expressions/array_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/array_expression.rs @@ -1,29 +1,28 @@ -use crate::prelude::*; - use crate::generated::FormatJsArrayElementList; +use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsArrayExpression; use rome_js_syntax::JsArrayExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrayExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsArrayExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayExpressionFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - let group_id = formatter.group_id("array"); + let group_id = f.group_id("array"); - let elements = - FormatJsArrayElementList::format_with_group_id(&elements, formatter, Some(group_id))?; + let elements = format_with(|f| { + FormatJsArrayElementList::format_with_group_id(&elements, f, Some(group_id)) + }); - formatter - .delimited(&l_brack_token?, elements, &r_brack_token?) - .soft_block_indent_with_group_id(Some(group_id)) - .finish() + write!( + f, + [f.delimited(&l_brack_token?, &elements, &r_brack_token?) + .soft_block_indent_with_group_id(Some(group_id))] + ) } } diff --git a/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs b/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs index 563156acb14..55d4778cda1 100644 --- a/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs @@ -1,13 +1,11 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::{JsAnyFunction, JsArrowFunctionExpression}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrowFunctionExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + fn format_fields(node: &JsArrowFunctionExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs b/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs index 764745f85ea..ba1c566936f 100644 --- a/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs @@ -1,32 +1,26 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsAssignmentExpression; use rome_js_syntax::JsAssignmentExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsAssignmentExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsAssignmentExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsAssignmentExpressionFields { left, operator_token, right, } = node.as_fields(); - Ok(group_elements(formatted![ - formatter, - [ + write!( + f, + [group_elements(&format_args![ left.format(), space_token(), operator_token.format(), line_suffix_boundary(), - group_elements(soft_line_indent_or_space(formatted![ - formatter, - [right.format()] - ]?)), - ] - ]?)) + group_elements(&soft_line_indent_or_space(&right.format())), + ])] + ) } } diff --git a/crates/rome_js_formatter/src/js/expressions/await_expression.rs b/crates/rome_js_formatter/src/js/expressions/await_expression.rs index 27a131d4ccf..7e25c9d7823 100644 --- a/crates/rome_js_formatter/src/js/expressions/await_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/await_expression.rs @@ -1,22 +1,17 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAwaitExpression; use rome_js_syntax::JsAwaitExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsAwaitExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsAwaitExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsAwaitExpressionFields { await_token, argument, } = node.as_fields(); - formatted![ - formatter, - [await_token.format(), space_token(), argument.format(),] - ] + write![f, [await_token.format(), space_token(), argument.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs index f5be76faa45..2b0781819c9 100644 --- a/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs @@ -1,3 +1,4 @@ +use rome_formatter::write; use std::borrow::Cow; use crate::prelude::*; @@ -8,20 +9,22 @@ use rome_js_syntax::JsBigIntLiteralExpression; use rome_js_syntax::JsBigIntLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBigIntLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsBigIntLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsBigIntLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; let original = value_token.text_trimmed(); match original.to_ascii_lowercase_cow() { - Cow::Borrowed(_) => formatted![formatter, [value_token.format()]], - Cow::Owned(lowercase) => Ok(formatter.format_replaced( - &value_token, - Token::new_dynamic(lowercase, value_token.text_trimmed_range().start()).into(), - )), + Cow::Borrowed(_) => write![f, [value_token.format()]], + Cow::Owned(lowercase) => { + write!( + f, + [f.format_replaced( + &value_token, + &dynamic_token(&lowercase, value_token.text_trimmed_range().start()) + )] + ) + } } } } diff --git a/crates/rome_js_formatter/src/js/expressions/binary_expression.rs b/crates/rome_js_formatter/src/js/expressions/binary_expression.rs index 5047166b85e..82a2fe92dc0 100644 --- a/crates/rome_js_formatter/src/js/expressions/binary_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/binary_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsBinaryExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBinaryExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsBinaryExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsBinaryExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs index 50eb3c7c6c0..016eea398ed 100644 --- a/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsBooleanLiteralExpression; use rome_js_syntax::JsBooleanLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBooleanLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsBooleanLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsBooleanLiteralExpressionFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } 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 f70609e3986..9f13c814c21 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,13 @@ use crate::prelude::*; use crate::utils::{is_simple_expression, token_has_comments}; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsCallArgumentsFields; use rome_js_syntax::{JsAnyCallArgument, JsCallArguments}; use rome_rowan::{AstSeparatedList, SyntaxResult}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsCallArguments, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsCallArguments, f: &mut JsFormatter) -> FormatResult<()> { let JsCallArgumentsFields { l_paren_token, args, @@ -18,8 +15,8 @@ impl FormatNodeFields for FormatNodeRule { } = node.as_fields(); if is_simple_function_arguments(node)? { - return formatted![ - formatter, + return write![ + f, [ l_paren_token.format(), args.format(), @@ -28,14 +25,13 @@ impl FormatNodeFields for FormatNodeRule { ]; } - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [args.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_paren_token?, &args.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/expressions/call_expression.rs b/crates/rome_js_formatter/src/js/expressions/call_expression.rs index f24613ca0fc..115716b15be 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_expression.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsCallExpression; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsCallExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsCallExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_call_expression(node.syntax(), formatter) } } diff --git a/crates/rome_js_formatter/src/js/expressions/class_expression.rs b/crates/rome_js_formatter/src/js/expressions/class_expression.rs index 0a291460a9d..caffb7ce464 100644 --- a/crates/rome_js_formatter/src/js/expressions/class_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/class_expression.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyClass, JsClassExpression}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsClassExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyClass::from(node.clone()).format()]] + fn format_fields(node: &JsClassExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyClass::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs b/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs index 7ce5a17ed1c..6928c27d53f 100644 --- a/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs @@ -1,15 +1,12 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsComputedMemberExpression; use rome_js_syntax::JsComputedMemberExpressionFields; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsComputedMemberExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsComputedMemberExpression, f: &mut JsFormatter) -> FormatResult<()> { let mut current = node.clone(); // Find the left most computed expression @@ -28,22 +25,19 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { fn format_fields( node: &JsConditionalExpression, - formatter: &JsFormatter, - ) -> FormatResult { - format_conditional(Conditional::Expression(node.clone()), formatter, false) + formatter: &mut JsFormatter, + ) -> FormatResult<()> { + format_conditional(&Conditional::Expression(node.clone()), formatter, false) } } diff --git a/crates/rome_js_formatter/src/js/expressions/function_expression.rs b/crates/rome_js_formatter/src/js/expressions/function_expression.rs index 51685894dac..c316bb6a579 100644 --- a/crates/rome_js_formatter/src/js/expressions/function_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/function_expression.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyFunction, JsFunctionExpression}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFunctionExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + fn format_fields(node: &JsFunctionExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs b/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs index 45a77b76bd1..159e4223015 100644 --- a/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsIdentifierExpression; use rome_js_syntax::JsIdentifierExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsIdentifierExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsIdentifierExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierExpressionFields { name } = node.as_fields(); - formatted![formatter, [name.format()]] + write![f, [name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs b/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs index 83f5c82c232..509e7655e12 100644 --- a/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsImportCallExpression; use rome_js_syntax::JsImportCallExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportCallExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportCallExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsImportCallExpressionFields { import_token, arguments, } = node.as_fields(); - formatted![formatter, [import_token.format(), arguments.format(),]] + write![f, [import_token.format(), arguments.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/in_expression.rs b/crates/rome_js_formatter/src/js/expressions/in_expression.rs index dcf3366311c..0baa276201d 100644 --- a/crates/rome_js_formatter/src/js/expressions/in_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/in_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsInExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsInExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsInExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsInExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs b/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs index 36cfed23263..5875e185a56 100644 --- a/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs @@ -7,8 +7,8 @@ use rome_js_syntax::JsInstanceofExpression; impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &JsInstanceofExpression, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsInstanceofExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/logical_expression.rs b/crates/rome_js_formatter/src/js/expressions/logical_expression.rs index 5943be2bb02..a3d3efb9b0d 100644 --- a/crates/rome_js_formatter/src/js/expressions/logical_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/logical_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsLogicalExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsLogicalExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsLogicalExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsLogicalExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/new_expression.rs b/crates/rome_js_formatter/src/js/expressions/new_expression.rs index c251a6c5e45..488f52a828d 100644 --- a/crates/rome_js_formatter/src/js/expressions/new_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/new_expression.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsNewExpression; use rome_js_syntax::JsNewExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNewExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsNewExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNewExpressionFields { new_token, callee, @@ -16,8 +13,8 @@ impl FormatNodeFields for FormatNodeRule { arguments, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ new_token.format(), space_token(), @@ -25,7 +22,7 @@ impl FormatNodeFields for FormatNodeRule { type_arguments.format(), arguments .format() - .or_format(|| formatted![formatter, [token("("), token(")")]]), + .or_format(|f| write![f, [token("("), token(")")]]), ] ] } diff --git a/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs index 192499f4ac7..5c3dc80167b 100644 --- a/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsNullLiteralExpression; use rome_js_syntax::JsNullLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNullLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsNullLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNullLiteralExpressionFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs index 9a74aef9b9d..96023c8ac28 100644 --- a/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsNumberLiteralExpression; use rome_js_syntax::JsNumberLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNumberLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsNumberLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNumberLiteralExpressionFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } 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 0912c42f2e1..c9ddb3be04f 100644 --- a/crates/rome_js_formatter/src/js/expressions/object_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/object_expression.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::utils::has_leading_newline; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsObjectExpression; use rome_js_syntax::JsObjectExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsObjectExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectExpressionFields { l_curly_token, members, @@ -16,23 +14,31 @@ impl FormatNodeFields for FormatNodeRule } = node.as_fields(); let has_newline = has_leading_newline(members.syntax()); - let members_content = formatted![formatter, [members.format()]]?; if members.is_empty() { - formatter - .delimited(&l_curly_token?, members_content, &r_curly_token?) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .soft_block_indent() + ] + ) } else if has_newline { - formatter - .delimited(&l_curly_token?, members_content, &r_curly_token?) - .block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .block_indent() + ] + ) } else { - formatter - .delimited(&l_curly_token?, members_content, &r_curly_token?) - .soft_block_spaces() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .soft_block_spaces() + ] + ) } } } diff --git a/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs b/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs index 6cd8c7f60e8..2f7c0da17dd 100644 --- a/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::utils::{is_simple_expression, FormatPrecedence}; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::{ @@ -9,10 +10,7 @@ use rome_js_syntax::{ use rome_rowan::{AstNode, SyntaxResult}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsParenthesizedExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsParenthesizedExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsParenthesizedExpressionFields { l_paren_token, expression, @@ -24,32 +22,29 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsPostUpdateExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsPostUpdateExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsPostUpdateExpressionFields { operand, operator_token, } = node.as_fields(); - formatted![formatter, [operand.format(), operator_token.format(),]] + write![f, [operand.format(), operator_token.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs b/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs index ef0c9924930..bf56f9ba898 100644 --- a/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs @@ -1,19 +1,17 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsPreUpdateExpression; use rome_js_syntax::JsPreUpdateExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsPreUpdateExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsPreUpdateExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsPreUpdateExpressionFields { operator_token, operand, } = node.as_fields(); - formatted![formatter, [operator_token.format(), operand.format(),]] + write![f, [operator_token.format(), operand.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs index 86695c38511..66eec9fa2cb 100644 --- a/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use std::fmt; use crate::FormatNodeFields; @@ -7,10 +8,7 @@ use rome_js_syntax::JsRegexLiteralExpression; use rome_js_syntax::JsRegexLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsRegexLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsRegexLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsRegexLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; let trimmed_raw_string = value_token.text_trimmed(); @@ -19,8 +17,9 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule(); - let sorted_regex_literal = Token::from_syntax_token_cow_slice( + let sorted_regex_literal = syntax_token_cow_slice( std::borrow::Cow::Owned(std::format!( "{}{}", &trimmed_raw_string[0..end_slash_pos + 1], @@ -38,6 +37,7 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsSequenceExpression, - formatter: &JsFormatter, - ) -> FormatResult { - let mut current = node.clone(); - let parent = current.syntax().parent(); + fn format_fields(node: &JsSequenceExpression, f: &mut JsFormatter) -> FormatResult<()> { + let mut content = format_with(|f| { + let mut current = node.clone(); + let parent = current.syntax().parent(); - let has_already_indentation = parent.map_or(false, |parent| { - // Return statement already does the indentation for us - // Arrow function body can't have a sequence expression unless it's parenthesized, otherwise - // would be a syntax error - if matches!(parent.kind(), JsSyntaxKind::JS_RETURN_STATEMENT) { - true - } else if matches!(parent.kind(), JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION) { - // In case we are inside a sequence expression, we have to go up a level and see the great parent. - // Arrow function body and return statements applying indentation for us, so we signal the - // sequence expression to not add other indentation levels - let great_parent = parent.parent().map(|gp| gp.kind()); + let has_already_indentation = parent.map_or(false, |parent| { + // Return statement already does the indentation for us + // Arrow function body can't have a sequence expression unless it's parenthesized, otherwise + // would be a syntax error + if matches!(parent.kind(), JsSyntaxKind::JS_RETURN_STATEMENT) { + true + } else if matches!(parent.kind(), JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION) { + // In case we are inside a sequence expression, we have to go up a level and see the great parent. + // Arrow function body and return statements applying indentation for us, so we signal the + // sequence expression to not add other indentation levels + let great_parent = parent.parent().map(|gp| gp.kind()); - matches!( - great_parent, - Some( - JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION - | JsSyntaxKind::JS_RETURN_STATEMENT - | JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER + matches!( + great_parent, + Some( + JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION + | JsSyntaxKind::JS_RETURN_STATEMENT + | JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER + ) ) - ) - } else { - false - } - }); - - // Find the left most sequence expression - while let Some(sequence_expression) = - JsSequenceExpression::cast(current.left()?.syntax().clone()) - { - current = sequence_expression; - } - - // Format the left most sequence expression - let JsSequenceExpressionFields { - left, - comma_token, - right, - } = current.as_fields(); - - let mut formatted = ConcatBuilder::default(); + } else { + false + } + }); - formatted.entry(formatted![ - formatter, - [left.format()?, comma_token.format()?] - ]?); - - let mut previous_right = right; + // Find the left most sequence expression + while let Some(sequence_expression) = + JsSequenceExpression::cast(current.left()?.syntax().clone()) + { + current = sequence_expression; + } - // Traverse upwards again and concatenate the sequence expression until we find the first non-sequence expression - while let Some(parent_sequence) = current - .syntax() - .parent() - .and_then(JsSequenceExpression::cast) - { + // Format the left most sequence expression let JsSequenceExpressionFields { - left: _left, + left, comma_token, right, - } = parent_sequence.as_fields(); + } = current.as_fields(); - if has_already_indentation { - formatted.entry(formatted![ - formatter, - [ - soft_line_break_or_space(), - previous_right.format()?, - comma_token.format()?, - ] - ]?); - } else { - formatted.entry(formatted![ - formatter, - [indent(formatted![ - formatter, + write![f, [left.format()?, comma_token.format()?]]?; + + let mut previous_right = right; + + // Traverse upwards again and concatenate the sequence expression until we find the first non-sequence expression + while let Some(parent_sequence) = current + .syntax() + .parent() + .and_then(JsSequenceExpression::cast) + { + let JsSequenceExpressionFields { + left: _left, + comma_token, + right, + } = parent_sequence.as_fields(); + + if has_already_indentation { + write![ + f, [ soft_line_break_or_space(), previous_right.format()?, comma_token.format()?, ] - ]?),] - ]?) + ]?; + } else { + write![ + f, + [indent(&format_args![ + soft_line_break_or_space(), + previous_right.format()?, + comma_token.format()?, + ])] + ]?; + } + previous_right = right; + current = parent_sequence; } - previous_right = right; - current = parent_sequence; - } - if has_already_indentation { - formatted.entry(formatted![ - formatter, - [soft_line_break_or_space(), previous_right.format()?,] - ]?); - } else { - formatted.entry(formatted![ - formatter, - [indent(formatted![ - formatter, - [soft_line_break_or_space(), previous_right.format()?,] - ]?),] - ]?) - } + if has_already_indentation { + write![f, [soft_line_break_or_space(), previous_right.format()?,]]?; + } else { + write![ + f, + [indent(&format_args![ + soft_line_break_or_space(), + previous_right.format(), + ])] + ]?; + } + + Ok(()) + }); - Ok(group_elements(formatted.finish())) + write!(f, [group_elements(&content)]) } } diff --git a/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs b/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs index c0e062aff4f..182d4612b8c 100644 --- a/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs @@ -1,3 +1,4 @@ +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::JsSyntaxKind; use rome_rowan::AstNode; @@ -8,48 +9,49 @@ use rome_js_syntax::JsStaticMemberExpression; use rome_js_syntax::JsStaticMemberExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStaticMemberExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsStaticMemberExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsStaticMemberExpressionFields { object, operator_token, member, } = node.as_fields(); - let object_syntax = object.clone()?.syntax().clone(); - - let is_object_number_literal = - object_syntax.kind() == JsSyntaxKind::JS_NUMBER_LITERAL_EXPRESSION; - - let has_object_trailing_trivia = - object_syntax.last_trailing_trivia().unwrap().pieces().len() > 0; - let has_operator_leading_trivia = - operator_token.clone()?.leading_trivia().pieces().len() > 0; - - let formatted_object = formatted![formatter, [object?.format()]]?; - - if is_object_number_literal && (has_object_trailing_trivia || has_operator_leading_trivia) { - let (object_leading, object_content, object_trailing) = formatted_object.split_trivia(); - - Ok(group_elements(formatted![ - formatter, - [ - object_leading, - token("("), - object_content, - token(")"), - object_trailing, - operator_token.format(), - member.format(), + let content = format_with(|f| { + let object_syntax = object.clone()?.syntax().clone(); + + let is_object_number_literal = + object_syntax.kind() == JsSyntaxKind::JS_NUMBER_LITERAL_EXPRESSION; + + let has_object_trailing_trivia = + object_syntax.last_trailing_trivia().unwrap().pieces().len() > 0; + let has_operator_leading_trivia = + operator_token.clone()?.leading_trivia().pieces().len() > 0; + + if is_object_number_literal + && (has_object_trailing_trivia || has_operator_leading_trivia) + { + let mut buffer = VecBuffer::new(f.state_mut()); + write![buffer, [object.format()]]?; + let formatted_object = buffer.into_document().into_element(); + + let (object_leading, object_content, object_trailing) = + formatted_object.split_trivia(); + + f.write_element(object_leading); + write!(f, [token("(")])?; + f.write_element(object_content); + write!(f, [token(")")])?; + f.write_element(object_trailing); + + write!(f, [operator_token.format(), member.format()]) + } else { + write![ + f, + [object.format(), operator_token.format(), member.format()] ] - ]?)) - } else { - Ok(group_elements(formatted![ - formatter, - [formatted_object, operator_token.format(), member.format(),] - ]?)) - } + } + }); + + write!(f, [group_elements(&content)]) } } diff --git a/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs index 88c6f12d9d0..947444da04f 100644 --- a/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs @@ -1,4 +1,6 @@ use crate::prelude::*; +use rome_formatter::{write, Buffer, VecBuffer}; + use crate::utils::FormatLiteralStringToken; use crate::FormatNodeFields; use rome_js_syntax::JsExpressionStatement; @@ -7,10 +9,7 @@ use rome_js_syntax::JsStringLiteralExpressionFields; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStringLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsStringLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsStringLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; @@ -19,17 +18,30 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsSuperExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsSuperExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsSuperExpressionFields { super_token } = node.as_fields(); - formatted![formatter, [super_token.format()]] + write![f, [super_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/template.rs b/crates/rome_js_formatter/src/js/expressions/template.rs index f3b7c38a811..9e0e6b95387 100644 --- a/crates/rome_js_formatter/src/js/expressions/template.rs +++ b/crates/rome_js_formatter/src/js/expressions/template.rs @@ -1,11 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsTemplate; use rome_js_syntax::JsTemplateFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsTemplate, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsTemplate, f: &mut JsFormatter) -> FormatResult<()> { let JsTemplateFields { tag, type_arguments, @@ -14,19 +15,18 @@ impl FormatNodeFields for FormatNodeRule { r_tick_token, } = node.as_fields(); - let l_tick = l_tick_token.format(); - let r_tick = r_tick_token.format(); - - formatted![ - formatter, + write![ + f, [ tag.format(), type_arguments.format(), line_suffix_boundary(), - l_tick, - concat_elements(formatter.format_all(elements.iter().formatted())?), - r_tick + l_tick_token.format(), ] - ] + ]?; + + f.join().entries(elements.iter().formatted()).finish()?; + + write!(f, [r_tick_token.format()]) } } diff --git a/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs b/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs index 767efe1ff6a..0019cbbf133 100644 --- a/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs +++ b/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs @@ -7,8 +7,8 @@ use rome_js_syntax::{JsTemplateChunkElement, JsTemplateChunkElementFields}; impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &JsTemplateChunkElement, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { let JsTemplateChunkElementFields { template_chunk_token, } = node.as_fields(); diff --git a/crates/rome_js_formatter/src/js/expressions/template_element.rs b/crates/rome_js_formatter/src/js/expressions/template_element.rs index bac57111d59..0a43848eafb 100644 --- a/crates/rome_js_formatter/src/js/expressions/template_element.rs +++ b/crates/rome_js_formatter/src/js/expressions/template_element.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsTemplateElement; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsTemplateElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsTemplateElement, formatter: &mut JsFormatter) -> FormatResult<()> { format_template_literal(TemplateElement::Js(node.clone()), formatter) } } diff --git a/crates/rome_js_formatter/src/js/expressions/this_expression.rs b/crates/rome_js_formatter/src/js/expressions/this_expression.rs index d29a1015346..083af2c21e8 100644 --- a/crates/rome_js_formatter/src/js/expressions/this_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/this_expression.rs @@ -1,16 +1,14 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsThisExpression; use rome_js_syntax::JsThisExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsThisExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsThisExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsThisExpressionFields { this_token } = node.as_fields(); - formatted![formatter, [this_token.format()]] + write![f, [this_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/unary_expression.rs b/crates/rome_js_formatter/src/js/expressions/unary_expression.rs index 97a08554db3..e561c96dace 100644 --- a/crates/rome_js_formatter/src/js/expressions/unary_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/unary_expression.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::utils::is_simple_expression; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsPreUpdateOperator; @@ -7,10 +8,7 @@ use rome_js_syntax::{JsAnyExpression, JsUnaryExpression}; use rome_js_syntax::{JsUnaryExpressionFields, JsUnaryOperator}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnaryExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnaryExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsUnaryExpressionFields { operator_token, argument, @@ -27,8 +25,8 @@ impl FormatNodeFields for FormatNodeRule { ); if is_keyword_operator { - return formatted![ - formatter, + return write![ + f, [operator_token.format(), space_token(), argument.format(),] ]; } @@ -56,9 +54,9 @@ impl FormatNodeFields for FormatNodeRule { }; if is_ambiguous_expression { - let parenthesized = if is_simple_expression(&argument)? { - formatted![ - formatter, + if is_simple_expression(&argument)? { + write![ + f, [ operator_token.format(), token("("), @@ -67,25 +65,20 @@ impl FormatNodeFields for FormatNodeRule { ] ] } else { - formatted![ - formatter, + write![ + f, [ operator_token.format(), - group_elements(formatted![ - formatter, - [ - token("("), - soft_block_indent(formatted![formatter, [argument.format()]]?), - token(")"), - ] - ]?), + group_elements(&format_args![ + token("("), + soft_block_indent(&argument.format()), + token(")"), + ]), ] ] - }; - - return parenthesized; + } + } else { + write![f, [operator_token.format(), argument.format(),]] } - - formatted![formatter, [operator_token.format(), argument.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/yield_argument.rs b/crates/rome_js_formatter/src/js/expressions/yield_argument.rs index c6c5c9105ab..0c24411f654 100644 --- a/crates/rome_js_formatter/src/js/expressions/yield_argument.rs +++ b/crates/rome_js_formatter/src/js/expressions/yield_argument.rs @@ -1,22 +1,17 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsYieldArgument; use rome_js_syntax::JsYieldArgumentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsYieldArgument, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsYieldArgument, f: &mut JsFormatter) -> FormatResult<()> { let JsYieldArgumentFields { star_token, expression, } = node.as_fields(); - formatted![ - formatter, - [star_token.format(), space_token(), expression.format()] - ] + write![f, [star_token.format(), space_token(), expression.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/yield_expression.rs b/crates/rome_js_formatter/src/js/expressions/yield_expression.rs index e663e8f5c1b..f885dcf6b55 100644 --- a/crates/rome_js_formatter/src/js/expressions/yield_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/yield_expression.rs @@ -1,19 +1,17 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsYieldExpression; use rome_js_syntax::JsYieldExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsYieldExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsYieldExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsYieldExpressionFields { yield_token, argument, } = node.as_fields(); - formatted![formatter, [yield_token.format(), argument.format()]] + write![f, [yield_token.format(), argument.format()]] } } diff --git a/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs b/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs index 77ac9baff06..a18313aaf5a 100644 --- a/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs @@ -8,8 +8,8 @@ impl FormatRule for FormatJsArrayAssignment fn format( node: &JsArrayAssignmentPatternElementList, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { format_array_node(node, formatter) } } diff --git a/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs b/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs index f533ff41f24..588e1d00426 100644 --- a/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs @@ -8,8 +8,8 @@ impl FormatRule for FormatJsArrayBindingPatter fn format( node: &JsArrayBindingPatternElementList, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { format_array_node(node, formatter) } } diff --git a/crates/rome_js_formatter/src/js/lists/array_element_list.rs b/crates/rome_js_formatter/src/js/lists/array_element_list.rs index 2acbce24e04..229d8e726df 100644 --- a/crates/rome_js_formatter/src/js/lists/array_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/array_element_list.rs @@ -2,7 +2,7 @@ use crate::prelude::*; use rome_formatter::GroupId; use std::convert::Infallible; -use crate::formatter::FormatSeparatedOptions; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions}; use crate::utils::array::format_array_node; use crate::generated::FormatJsArrayElementList; @@ -13,7 +13,7 @@ use rome_rowan::{AstNode, AstSeparatedList}; impl FormatRule for FormatJsArrayElementList { type Context = JsFormatContext; - fn format(node: &JsArrayElementList, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsArrayElementList, formatter: &mut JsFormatter) -> FormatResult<()> { Self::format_with_group_id(node, formatter, None) } } @@ -22,21 +22,21 @@ impl FormatJsArrayElementList { /// Formats the array list with pub fn format_with_group_id( node: &JsArrayElementList, - formatter: &JsFormatter, + f: &mut JsFormatter, group_id: Option, - ) -> FormatResult { + ) -> FormatResult<()> { if !has_formatter_trivia(node.syntax()) && can_print_fill(node) { - return Ok(fill_elements( - // Using format_separated is valid in this case as can_print_fill does not allow holes - formatter.format_separated_with_options( - node, - || token(","), + // Using format_separated is valid in this case as can_print_fill does not allow holes + return f + .fill(&soft_line_break_or_space()) + .entries(node.format_separated_with_options( + token(","), FormatSeparatedOptions::default().with_group_id(group_id), - )?, - )); + )) + .finish(); } - format_array_node(node, formatter) + format_array_node(node, f) } } 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 7aaf528c435..2c4fc7f221e 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,3 +1,4 @@ +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedIter}; use crate::generated::FormatJsCallArgumentList; use crate::prelude::*; use rome_js_syntax::JsCallArgumentList; @@ -5,10 +6,9 @@ use rome_js_syntax::JsCallArgumentList; impl FormatRule for FormatJsCallArgumentList { type Context = JsFormatContext; - fn format(node: &JsCallArgumentList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &JsCallArgumentList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/class_member_list.rs b/crates/rome_js_formatter/src/js/lists/class_member_list.rs index c433040dc4c..f03d69c19b1 100644 --- a/crates/rome_js_formatter/src/js/lists/class_member_list.rs +++ b/crates/rome_js_formatter/src/js/lists/class_member_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::generated::FormatJsClassMemberList; use crate::prelude::*; use rome_js_syntax::JsClassMemberList; @@ -5,7 +6,9 @@ use rome_js_syntax::JsClassMemberList; impl FormatRule for FormatJsClassMemberList { type Context = JsFormatContext; - fn format(node: &JsClassMemberList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn format(node: &JsClassMemberList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&hard_line_break()) + .entries(node.try_format_nodes()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs b/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs index cfefd469cc1..df439c0a1ea 100644 --- a/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs @@ -6,13 +6,9 @@ use rome_rowan::AstNodeList; impl FormatRule for FormatJsConstructorModifierList { type Context = JsFormatContext; - fn format( - node: &JsConstructorModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(node.iter().formatted())?, - )) + fn format(node: &JsConstructorModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(node.iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs b/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs index 4e869b103f2..ea696e37e9b 100644 --- a/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs +++ b/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatJsConstructorParameterList; use crate::prelude::*; use rome_js_syntax::JsConstructorParameterList; @@ -5,13 +6,9 @@ use rome_js_syntax::JsConstructorParameterList; impl FormatRule for FormatJsConstructorParameterList { type Context = JsFormatContext; - fn format( - node: &JsConstructorParameterList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &JsConstructorParameterList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/directive_list.rs b/crates/rome_js_formatter/src/js/lists/directive_list.rs index 16797ea034e..5e7cf09e6c8 100644 --- a/crates/rome_js_formatter/src/js/lists/directive_list.rs +++ b/crates/rome_js_formatter/src/js/lists/directive_list.rs @@ -1,44 +1,44 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::generated::FormatJsDirectiveList; use crate::prelude::*; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsDirectiveList; use rome_rowan::{AstNode, AstNodeList}; impl FormatRule for FormatJsDirectiveList { type Context = JsFormatContext; - fn format(node: &JsDirectiveList, formatter: &JsFormatter) -> FormatResult { - if !node.is_empty() { - let syntax_node = node.syntax(); - let next_sibling = syntax_node.next_sibling(); - // if next_sibling's first leading_trivia has more than one new_line, we should add an extra empty line at the end of - // JsDirectiveList, for example: - //```js - // "use strict"; <- first leading new_line - // <- second leading new_line - // function foo() { + fn format(node: &JsDirectiveList, f: &mut JsFormatter) -> FormatResult<()> { + if node.is_empty() { + return Ok(()); + } + + let syntax_node = node.syntax(); + let next_sibling = syntax_node.next_sibling(); + // if next_sibling's first leading_trivia has more than one new_line, we should add an extra empty line at the end of + // JsDirectiveList, for example: + //```js + // "use strict"; <- first leading new_line + // <- second leading new_line + // function foo() { + + // } + //``` + // so we should keep an extra empty line after JsDirectiveList + let need_extra_empty_line = if let Some(next_sibling) = next_sibling { + get_lines_before(&next_sibling) > 1 + } else { + false + }; + + f.join_with(&hard_line_break()) + .entries(node.try_format_nodes()) + .finish()?; - // } - //``` - // so we should keep an extra empty line after JsDirectiveList - let need_extra_empty_line = if let Some(next_sibling) = next_sibling { - get_lines_before(&next_sibling) > 1 - } else { - false - }; - formatted![ - formatter, - [ - formatter.format_list(node), - hard_line_break(), - if need_extra_empty_line { - empty_line() - } else { - empty_element() - } - ] - ] + if need_extra_empty_line { + write!(f, [empty_line()]) } else { - Ok(empty_element()) + write!(f, [hard_line_break()]) } } } diff --git a/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs b/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs index c2ea7c74600..6a8757005ba 100644 --- a/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatJsExportNamedFromSpecifierList; use crate::prelude::*; use rome_js_syntax::JsExportNamedFromSpecifierList; @@ -5,13 +6,9 @@ use rome_js_syntax::JsExportNamedFromSpecifierList; impl FormatRule for FormatJsExportNamedFromSpecifierList { type Context = JsFormatContext; - fn format( - node: &JsExportNamedFromSpecifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &JsExportNamedFromSpecifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs b/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs index 7cf8e136004..5f7b9eb0db5 100644 --- a/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatJsExportNamedSpecifierList; use crate::prelude::*; use rome_js_syntax::JsExportNamedSpecifierList; @@ -5,13 +6,9 @@ use rome_js_syntax::JsExportNamedSpecifierList; impl FormatRule for FormatJsExportNamedSpecifierList { type Context = JsFormatContext; - fn format( - node: &JsExportNamedSpecifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &JsExportNamedSpecifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs b/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs index c26f8211837..922d528112f 100644 --- a/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs +++ b/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatJsImportAssertionEntryList; use crate::prelude::*; use rome_js_syntax::JsImportAssertionEntryList; @@ -5,13 +6,9 @@ use rome_js_syntax::JsImportAssertionEntryList; impl FormatRule for FormatJsImportAssertionEntryList { type Context = JsFormatContext; - fn format( - node: &JsImportAssertionEntryList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &JsImportAssertionEntryList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs b/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs index e02edb5d5f2..bce9ebf8224 100644 --- a/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs @@ -6,10 +6,9 @@ use rome_js_syntax::JsMethodModifierList; impl FormatRule for FormatJsMethodModifierList { type Context = JsFormatContext; - fn format(node: &JsMethodModifierList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn format(node: &JsMethodModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/module_item_list.rs b/crates/rome_js_formatter/src/js/lists/module_item_list.rs index ffc82a8f1fd..1a636ba7ddd 100644 --- a/crates/rome_js_formatter/src/js/lists/module_item_list.rs +++ b/crates/rome_js_formatter/src/js/lists/module_item_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::generated::FormatJsModuleItemList; use crate::prelude::*; use rome_js_syntax::JsModuleItemList; @@ -5,7 +6,9 @@ use rome_js_syntax::JsModuleItemList; impl FormatRule for FormatJsModuleItemList { type Context = JsFormatContext; - fn format(node: &JsModuleItemList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn format(node: &JsModuleItemList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&hard_line_break()) + .entries(node.try_format_nodes()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs b/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs index 12ee5002aea..593d6419bf6 100644 --- a/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatJsNamedImportSpecifierList; use crate::prelude::*; use rome_js_syntax::JsNamedImportSpecifierList; @@ -5,13 +6,9 @@ use rome_js_syntax::JsNamedImportSpecifierList; impl FormatRule for FormatJsNamedImportSpecifierList { type Context = JsFormatContext; - fn format( - node: &JsNamedImportSpecifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &JsNamedImportSpecifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs b/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs index 4ec03d5493e..a23e3f1ae3e 100644 --- a/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs +++ b/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs @@ -1,4 +1,4 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatJsObjectAssignmentPatternPropertyList; use crate::prelude::*; use rome_js_syntax::{JsAnyObjectAssignmentPatternMember, JsObjectAssignmentPatternPropertyList}; @@ -10,8 +10,8 @@ impl FormatRule fn format( node: &JsObjectAssignmentPatternPropertyList, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { // The trailing separator is disallowed after a rest element let has_trailing_rest = match node.into_iter().last() { Some(elem) => matches!( @@ -27,13 +27,11 @@ impl FormatRule TrailingSeparator::Allowed }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated_with_options( + token(","), FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs b/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs index 682cf4a676f..ccb58cc35e7 100644 --- a/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs +++ b/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs @@ -1,4 +1,4 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatJsObjectBindingPatternPropertyList; use crate::prelude::*; use rome_js_syntax::{JsAnyObjectBindingPatternMember, JsObjectBindingPatternPropertyList}; @@ -6,10 +6,7 @@ use rome_js_syntax::{JsAnyObjectBindingPatternMember, JsObjectBindingPatternProp impl FormatRule for FormatJsObjectBindingPatternPropertyList { type Context = JsFormatContext; - fn format( - node: &JsObjectBindingPatternPropertyList, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsObjectBindingPatternPropertyList, f: &mut JsFormatter) -> FormatResult<()> { // The trailing separator is disallowed after a rest element let has_trailing_rest = match node.into_iter().last() { Some(elem) => matches!( @@ -25,13 +22,11 @@ impl FormatRule for FormatJsObjectBindingPat TrailingSeparator::Allowed }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated_with_options( + token(","), FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/object_member_list.rs b/crates/rome_js_formatter/src/js/lists/object_member_list.rs index 149b4c60400..5f95198fbcf 100644 --- a/crates/rome_js_formatter/src/js/lists/object_member_list.rs +++ b/crates/rome_js_formatter/src/js/lists/object_member_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatJsObjectMemberList; use crate::prelude::*; use rome_js_syntax::JsObjectMemberList; @@ -6,14 +7,13 @@ use rome_rowan::{AstNode, AstSeparatedList}; impl FormatRule for FormatJsObjectMemberList { type Context = JsFormatContext; - fn format(node: &JsObjectMemberList, formatter: &JsFormatter) -> FormatResult { - let members = formatter.format_separated(node, || token(","))?; + fn format(node: &JsObjectMemberList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join_nodes_with_soft_line(); - Ok(join_elements_soft_line( - node.elements() - // This unwrap is guarded by the call to format_separated above - .map(|node| node.node().unwrap().syntax().clone()) - .zip(members), - )) + for (element, formatted) in node.elements().zip(node.format_separated(token(","))) { + join.entry(element.node()?.syntax(), &formatted); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/parameter_list.rs b/crates/rome_js_formatter/src/js/lists/parameter_list.rs index 3b436a09b98..fdc3f9c22fe 100644 --- a/crates/rome_js_formatter/src/js/lists/parameter_list.rs +++ b/crates/rome_js_formatter/src/js/lists/parameter_list.rs @@ -1,4 +1,4 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatJsParameterList; use crate::prelude::*; use rome_js_syntax::{JsAnyParameter, JsParameterList}; @@ -6,7 +6,7 @@ use rome_js_syntax::{JsAnyParameter, JsParameterList}; impl FormatRule for FormatJsParameterList { type Context = JsFormatContext; - fn format(node: &JsParameterList, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsParameterList, f: &mut JsFormatter) -> FormatResult<()> { // The trailing separator is disallowed if the last element in the list is a rest parameter let has_trailing_rest = match node.into_iter().last() { Some(elem) => matches!(elem?, JsAnyParameter::JsRestParameter(_)), @@ -19,13 +19,11 @@ impl FormatRule for FormatJsParameterList { TrailingSeparator::Allowed }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated_with_options( + token(","), FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs b/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs index 736c0e14298..b4904cc4d1c 100644 --- a/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::JsPropertyModifierList; impl FormatRule for FormatJsPropertyModifierList { type Context = JsFormatContext; - fn format( - node: &JsPropertyModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn format(node: &JsPropertyModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/statement_list.rs b/crates/rome_js_formatter/src/js/lists/statement_list.rs index 242e571c6b9..20aa231b2d8 100644 --- a/crates/rome_js_formatter/src/js/lists/statement_list.rs +++ b/crates/rome_js_formatter/src/js/lists/statement_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::generated::FormatJsStatementList; use crate::prelude::*; use rome_js_syntax::JsStatementList; @@ -5,7 +6,9 @@ use rome_js_syntax::JsStatementList; impl FormatRule for FormatJsStatementList { type Context = JsFormatContext; - fn format(node: &JsStatementList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn format(node: &JsStatementList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&hard_line_break()) + .entries(node.try_format_nodes()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/switch_case_list.rs b/crates/rome_js_formatter/src/js/lists/switch_case_list.rs index 9c73b2838d7..13fa210d6b1 100644 --- a/crates/rome_js_formatter/src/js/lists/switch_case_list.rs +++ b/crates/rome_js_formatter/src/js/lists/switch_case_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::TryFormatNodeListExtension; use crate::generated::FormatJsSwitchCaseList; use crate::prelude::*; use rome_js_syntax::JsSwitchCaseList; @@ -5,7 +6,9 @@ use rome_js_syntax::JsSwitchCaseList; impl FormatRule for FormatJsSwitchCaseList { type Context = JsFormatContext; - fn format(node: &JsSwitchCaseList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn format(node: &JsSwitchCaseList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&hard_line_break()) + .entries(node.try_format_nodes()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/template_element_list.rs b/crates/rome_js_formatter/src/js/lists/template_element_list.rs index 88037e0d0ee..37095f2393d 100644 --- a/crates/rome_js_formatter/src/js/lists/template_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/template_element_list.rs @@ -5,14 +5,13 @@ use rome_js_syntax::JsTemplateElementList; impl FormatRule for FormatJsTemplateElementList { type Context = JsFormatContext; - fn format( - node: &JsTemplateElementList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(concat_elements( - formatter - .format_all(node.iter().formatted())? - .map(group_elements), - )) + fn format(node: &JsTemplateElementList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join(); + + for element in node { + join.entry(&group_elements(&element.format())); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs b/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs index edd0efa44a7..1af75b19c7b 100644 --- a/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs +++ b/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::generated::FormatJsVariableDeclaratorList; use crate::AsFormat; @@ -8,54 +9,53 @@ use rome_rowan::AstSeparatedList; impl FormatRule for FormatJsVariableDeclaratorList { type Context = JsFormatContext; - fn format( - node: &JsVariableDeclaratorList, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &JsVariableDeclaratorList, f: &mut JsFormatter) -> FormatResult<()> { let last_index = node.len().saturating_sub(1); - let declarators = node - .elements() - .enumerate() - .map(|(index, element)| { - let node = formatted![formatter, [element.node()?.format()]]?; - let separator = match element.trailing_separator()? { + let mut declarators = node.elements().enumerate().map(|(index, element)| { + format_with(move |f| { + write!(f, [group_elements(&element.node().format())])?; + + match element.trailing_separator()? { None => { - if index == last_index { - empty_element() - } else { - token(",") + if index != last_index { + write!(f, [token(",")])?; } } Some(separator) => { - if index == last_index { - empty_element() - } else { - formatted![formatter, [separator.format()]]? + if index != last_index { + write!(f, [separator.format()])?; } } }; - Ok(format_elements![group_elements(node), separator]) + Ok(()) }) - .collect::>>()?; - - let mut items = declarators.into_iter(); - - let leading_element = items.next(); - let trailing_elements = join_elements(soft_line_break_or_space(), items); - - Ok(group_elements(concat_elements( - leading_element - .into_iter() - .chain(if !trailing_elements.is_empty() { - Some(indent(formatted![ - formatter, - [soft_line_break_or_space(), trailing_elements] - ]?)) - } else { - None - }), - ))) + }); + + let leading_element = declarators + .next() + .ok_or(FormatError::MissingRequiredChild)?; + + let other_declarators = format_once(|f| { + if node.len() == 1 { + // No more declarators, avoid single line break + return Ok(()); + } + + write!(f, [soft_line_break_or_space()])?; + + f.join_with(&soft_line_break_or_space()) + .entries(declarators) + .finish() + }); + + write!( + f, + [group_elements(&format_args!( + leading_element, + indent(&other_declarators) + ))] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/default_import_specifier.rs b/crates/rome_js_formatter/src/js/module/default_import_specifier.rs index d9585a79031..82b38c84b22 100644 --- a/crates/rome_js_formatter/src/js/module/default_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/default_import_specifier.rs @@ -1,22 +1,17 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsDefaultImportSpecifier; use rome_js_syntax::JsDefaultImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDefaultImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsDefaultImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsDefaultImportSpecifierFields { local_name, trailing_comma_token, } = node.as_fields(); - formatted![ - formatter, - [local_name.format(), trailing_comma_token.format()] - ] + write![f, [local_name.format(), trailing_comma_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/module/export.rs b/crates/rome_js_formatter/src/js/module/export.rs index dc6cce81747..86ef22f281a 100644 --- a/crates/rome_js_formatter/src/js/module/export.rs +++ b/crates/rome_js_formatter/src/js/module/export.rs @@ -1,18 +1,20 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsExport; use rome_js_syntax::JsExportFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsExport, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsExport, f: &mut JsFormatter) -> FormatResult<()> { let JsExportFields { export_token, export_clause, } = node.as_fields(); - let export_token = export_token.format(); - let export_clause = export_clause.format(); - formatted![formatter, [export_token, space_token(), export_clause]] + write![ + f, + [export_token.format(), space_token(), export_clause.format()] + ] } } diff --git a/crates/rome_js_formatter/src/js/module/export_as_clause.rs b/crates/rome_js_formatter/src/js/module/export_as_clause.rs index af4dbb9ab6f..4def4aa2376 100644 --- a/crates/rome_js_formatter/src/js/module/export_as_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_as_clause.rs @@ -1,22 +1,20 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsExportAsClause; use rome_js_syntax::JsExportAsClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportAsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExportAsClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportAsClauseFields { as_token, exported_name, } = node.as_fields(); - let as_token = as_token.format(); - let exported_name = exported_name.format(); - - formatted![formatter, [as_token, space_token(), exported_name]] + write![ + f, + [as_token.format(), space_token(), exported_name.format()] + ] } } diff --git a/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs b/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs index 64fa2004b9e..cfae81b5ff0 100644 --- a/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsExportDefaultDeclarationClause, JsExportDefaultDeclarationClauseFields}; impl FormatNodeFields @@ -7,16 +8,16 @@ impl FormatNodeFields { fn format_fields( node: &JsExportDefaultDeclarationClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsExportDefaultDeclarationClauseFields { default_token, declaration, semicolon_token: _, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [default_token.format(), space_token(), declaration.format()] ] } diff --git a/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs b/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs index c8ce8f12965..edc9ea5e87e 100644 --- a/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs @@ -1,6 +1,7 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExportDefaultExpressionClause; use rome_js_syntax::JsExportDefaultExpressionClauseFields; @@ -10,21 +11,20 @@ impl FormatNodeFields { fn format_fields( node: &JsExportDefaultExpressionClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsExportDefaultExpressionClauseFields { default_token, expression, semicolon_token, } = node.as_fields(); - let default_token = default_token.format(); - let class = expression.format(); - - format_with_semicolon( - formatter, - formatted![formatter, [default_token, space_token(), class]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(default_token.format(), space_token(), expression.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/module/export_from_clause.rs b/crates/rome_js_formatter/src/js/module/export_from_clause.rs index eb5f3dfba2e..25698da5302 100644 --- a/crates/rome_js_formatter/src/js/module/export_from_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_from_clause.rs @@ -1,16 +1,13 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; -use crate::utils::format_with_semicolon; - +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExportFromClause; use rome_js_syntax::JsExportFromClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportFromClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExportFromClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportFromClauseFields { star_token, export_as, @@ -20,26 +17,24 @@ impl FormatNodeFields for FormatNodeRule semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( star_token.format(), space_token(), export_as .format() - .with_or_empty(|as_token| formatted![formatter, [as_token, space_token()]]), + .with_or_empty(|as_token, f| write![f, [as_token, space_token()]]), from_token.format(), space_token(), source.format(), - assertion.format().with_or_empty(|assertion| formatted![ - formatter, - [space_token(), assertion] - ]), - ] - ]?, - semicolon_token, + assertion + .format() + .with_or_empty(|assertion, f| write![f, [space_token(), assertion]]), + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/module/export_named_clause.rs b/crates/rome_js_formatter/src/js/module/export_named_clause.rs index b6e5cb4fcd9..060b01714b5 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_clause.rs @@ -1,16 +1,13 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; -use crate::utils::format_with_semicolon; - +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExportNamedClause; use rome_js_syntax::JsExportNamedClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportNamedClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExportNamedClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedClauseFields { type_token, l_curly_token, @@ -19,29 +16,25 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsExportNamedFromClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExportNamedFromClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedFromClauseFields { type_token, l_curly_token, @@ -23,46 +20,53 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsExportNamedFromSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExportNamedFromSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedFromSpecifierFields { type_token, source_name, export_as, } = node.as_fields(); - formatted![ - formatter, - [ - type_token - .format() - .with_or_empty(|type_token| formatted![formatter, [type_token, space_token()]]), - source_name.format(), - export_as - .format() - .with_or_empty(|export_as| formatted![formatter, [space_token(), export_as]]) - ] - ] + if let Some(type_token) = type_token { + write!(f, [type_token.format(), space_token()])?; + } + + write!(f, [source_name.format()])?; + + if let Some(export_as) = export_as { + write!(f, [space_token(), export_as.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs index 7fcdfb3d91b..23ef44ca292 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsExportNamedShorthandSpecifier; diff --git a/crates/rome_js_formatter/src/js/module/export_named_specifier.rs b/crates/rome_js_formatter/src/js/module/export_named_specifier.rs index e16589702c7..4bec70b956d 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_specifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsExportNamedSpecifier; use rome_js_syntax::JsExportNamedSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportNamedSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExportNamedSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedSpecifierFields { type_token, local_name, @@ -16,12 +14,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields(node: &JsImport, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsImport, f: &mut JsFormatter) -> FormatResult<()> { let JsImportFields { import_token, import_clause, semicolon_token, } = node.as_fields(); - let import_token = import_token.format(); - let import_clause = import_clause.format(); - - format_with_semicolon( - formatter, - formatted![formatter, [import_token, space_token(), import_clause]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(import_token.format(), space_token(), import_clause.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/module/import_assertion.rs b/crates/rome_js_formatter/src/js/module/import_assertion.rs index 066a73e6c44..9f329986078 100644 --- a/crates/rome_js_formatter/src/js/module/import_assertion.rs +++ b/crates/rome_js_formatter/src/js/module/import_assertion.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsImportAssertion; use rome_js_syntax::JsImportAssertionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportAssertion, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportAssertion, f: &mut JsFormatter) -> FormatResult<()> { let JsImportAssertionFields { assert_token, l_curly_token, @@ -16,15 +13,14 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - let result = formatter - .delimited( - &l_curly_token?, - formatted![formatter, [assertions.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish()?; + write![f, [assert_token.format(), space_token()]]?; - formatted![formatter, [assert_token.format(), space_token(), result]] + write!( + f, + [ + f.delimited(&l_curly_token?, &assertions.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs b/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs index 75b7a2be4b6..a5394595b05 100644 --- a/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs +++ b/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs @@ -1,14 +1,13 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::utils::FormatLiteralStringToken; use crate::FormatNodeFields; use rome_js_syntax::JsImportAssertionEntryFields; use rome_js_syntax::{JsImportAssertionEntry, JsSyntaxKind}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportAssertionEntry, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportAssertionEntry, f: &mut JsFormatter) -> FormatResult<()> { let JsImportAssertionEntryFields { key, colon_token, @@ -17,20 +16,21 @@ impl FormatNodeFields for FormatNodeRule { - formatted![formatter, [FormatLiteralStringToken::from_string(&key)]]? + write!(f, [FormatLiteralStringToken::from_string(&key)])?; + } + _ => { + write![f, [key.format()]]?; } - _ => formatted![formatter, [key.format()]]?, }; - formatted![ - formatter, + write![ + f, [ - formatted_key, colon_token.format(), space_token(), - FormatLiteralStringToken::from_string(&value_token?) + FormatLiteralStringToken::from_string(&value_token?), ] ] } diff --git a/crates/rome_js_formatter/src/js/module/import_bare_clause.rs b/crates/rome_js_formatter/src/js/module/import_bare_clause.rs index b01b4286bf0..d4611667688 100644 --- a/crates/rome_js_formatter/src/js/module/import_bare_clause.rs +++ b/crates/rome_js_formatter/src/js/module/import_bare_clause.rs @@ -1,24 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsImportBareClause; use rome_js_syntax::JsImportBareClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportBareClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportBareClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportBareClauseFields { source, assertion } = node.as_fields(); - formatted![ - formatter, - [ - source.format(), - assertion - .format() - .with_or_empty(|assertion| formatted![formatter, [space_token(), assertion]]) - ] - ] + write!(f, [source.format()])?; + + if let Some(assertion) = assertion { + write!(f, [space_token(), assertion.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/module/import_default_clause.rs b/crates/rome_js_formatter/src/js/module/import_default_clause.rs index d1076ac4ed1..2555ca2fd4e 100644 --- a/crates/rome_js_formatter/src/js/module/import_default_clause.rs +++ b/crates/rome_js_formatter/src/js/module/import_default_clause.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsImportDefaultClause; use rome_js_syntax::JsImportDefaultClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportDefaultClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportDefaultClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportDefaultClauseFields { type_token, local_name, @@ -17,21 +14,25 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields(node: &ImportMeta, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &ImportMeta, f: &mut JsFormatter) -> FormatResult<()> { let ImportMetaFields { import_token, dot_token, meta_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ import_token.format(), dot_token.format(), diff --git a/crates/rome_js_formatter/src/js/module/import_named_clause.rs b/crates/rome_js_formatter/src/js/module/import_named_clause.rs index ab09b33e11d..0d082d8b57f 100644 --- a/crates/rome_js_formatter/src/js/module/import_named_clause.rs +++ b/crates/rome_js_formatter/src/js/module/import_named_clause.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsImportNamedClause; use rome_js_syntax::JsImportNamedClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportNamedClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportNamedClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportNamedClauseFields { type_token, default_specifier, @@ -18,24 +15,29 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsImportNamespaceClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsImportNamespaceClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportNamespaceClauseFields { type_token, star_token, @@ -19,12 +16,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsLiteralExportName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsLiteralExportName, f: &mut JsFormatter) -> FormatResult<()> { let JsLiteralExportNameFields { value } = node.as_fields(); - formatted![formatter, [FormatLiteralStringToken::from_string(&value?)]] + write!(f, [FormatLiteralStringToken::from_string(&value?)]) } } diff --git a/crates/rome_js_formatter/src/js/module/module_source.rs b/crates/rome_js_formatter/src/js/module/module_source.rs index bd80d9a57e2..e642bacce37 100644 --- a/crates/rome_js_formatter/src/js/module/module_source.rs +++ b/crates/rome_js_formatter/src/js/module/module_source.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::utils::FormatLiteralStringToken; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsModuleSource; use rome_js_syntax::JsModuleSourceFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsModuleSource, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsModuleSource, f: &mut JsFormatter) -> FormatResult<()> { let JsModuleSourceFields { value_token } = node.as_fields(); - FormatLiteralStringToken::from_string(&value_token?).format(formatter) + write!(f, [FormatLiteralStringToken::from_string(&value_token?)]) } } diff --git a/crates/rome_js_formatter/src/js/module/named_import_specifier.rs b/crates/rome_js_formatter/src/js/module/named_import_specifier.rs index fc2d06199c5..d361f150eec 100644 --- a/crates/rome_js_formatter/src/js/module/named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/named_import_specifier.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsNamedImportSpecifier; use rome_js_syntax::JsNamedImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsNamedImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsNamedImportSpecifierFields { type_token, name, @@ -16,12 +13,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsNamedImportSpecifiers, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsNamedImportSpecifiers, f: &mut JsFormatter) -> FormatResult<()> { let JsNamedImportSpecifiersFields { l_curly_token, specifiers, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [specifiers.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &specifiers.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs b/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs index 3d171e7135a..10a7f09759d 100644 --- a/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs @@ -1,27 +1,26 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsNamespaceImportSpecifier; use rome_js_syntax::JsNamespaceImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNamespaceImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsNamespaceImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsNamespaceImportSpecifierFields { star_token, as_token, local_name, } = node.as_fields(); - let star = star_token.format(); - let as_token = as_token.format(); - let local_name = local_name.format(); - - formatted![ - formatter, - [star, space_token(), as_token, space_token(), local_name] + write![ + f, + [ + star_token.format(), + space_token(), + as_token.format(), + space_token(), + local_name.format() + ] ] } } diff --git a/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs b/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs index 271d5ff5c84..a933adbe7b3 100644 --- a/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs @@ -1,6 +1,6 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsShorthandNamedImportSpecifier; use rome_js_syntax::JsShorthandNamedImportSpecifierFields; @@ -9,21 +9,17 @@ impl FormatNodeFields { fn format_fields( node: &JsShorthandNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsShorthandNamedImportSpecifierFields { type_token, local_name, } = node.as_fields(); - formatted![ - formatter, - [ - type_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), - local_name.format() - ] - ] + if let Some(type_token) = type_token { + write!(f, [type_token.format(), space_token()])?; + } + + write![f, [local_name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/objects/computed_member_name.rs b/crates/rome_js_formatter/src/js/objects/computed_member_name.rs index a94628da3f4..250126b199d 100644 --- a/crates/rome_js_formatter/src/js/objects/computed_member_name.rs +++ b/crates/rome_js_formatter/src/js/objects/computed_member_name.rs @@ -1,22 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsComputedMemberName; use rome_js_syntax::JsComputedMemberNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsComputedMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsComputedMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsComputedMemberNameFields { l_brack_token, expression, r_brack_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_brack_token.format(), expression.format(), diff --git a/crates/rome_js_formatter/src/js/objects/getter_object_member.rs b/crates/rome_js_formatter/src/js/objects/getter_object_member.rs index 0693fb912cb..119b26cde8e 100644 --- a/crates/rome_js_formatter/src/js/objects/getter_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/getter_object_member.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsGetterObjectMember; use rome_js_syntax::JsGetterObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsGetterObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsGetterObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsGetterObjectMemberFields { get_token, name, @@ -18,8 +15,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsLiteralMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsLiteralMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsLiteralMemberNameFields { value } = node.as_fields(); let value = value?; match value.kind() { JsSyntaxKind::JS_STRING_LITERAL => { - formatted![formatter, [FormatLiteralStringToken::from_string(&value)]] + write!(f, [FormatLiteralStringToken::from_string(&value)]) } - _ => formatted![formatter, [value.format()]], + _ => write![f, [value.format()]], } } } diff --git a/crates/rome_js_formatter/src/js/objects/method_object_member.rs b/crates/rome_js_formatter/src/js/objects/method_object_member.rs index 97db3eb2281..c4d778c8f0e 100644 --- a/crates/rome_js_formatter/src/js/objects/method_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/method_object_member.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsMethodObjectMember; diff --git a/crates/rome_js_formatter/src/js/objects/private_class_member_name.rs b/crates/rome_js_formatter/src/js/objects/private_class_member_name.rs index 620385db54a..72388a1e3b2 100644 --- a/crates/rome_js_formatter/src/js/objects/private_class_member_name.rs +++ b/crates/rome_js_formatter/src/js/objects/private_class_member_name.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsPrivateClassMemberName; use rome_js_syntax::JsPrivateClassMemberNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsPrivateClassMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsPrivateClassMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsPrivateClassMemberNameFields { hash_token, id_token, } = node.as_fields(); - formatted![formatter, [hash_token.format(), id_token.format(),]] + write![f, [hash_token.format(), id_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/objects/property_object_member.rs b/crates/rome_js_formatter/src/js/objects/property_object_member.rs index 37286e1f801..37396b2be34 100644 --- a/crates/rome_js_formatter/src/js/objects/property_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/property_object_member.rs @@ -1,23 +1,25 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsPropertyObjectMember; use rome_js_syntax::JsPropertyObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsPropertyObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsPropertyObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsPropertyObjectMemberFields { name, colon_token, value, } = node.as_fields(); - let key = name.format(); - let colon = colon_token.format(); - let value = value.format(); - formatted![formatter, [key, colon, space_token(), value]] + write![ + f, + [ + name.format(), + colon_token.format(), + space_token(), + value.format() + ] + ] } } diff --git a/crates/rome_js_formatter/src/js/objects/setter_object_member.rs b/crates/rome_js_formatter/src/js/objects/setter_object_member.rs index 391964c773b..2f2725974b2 100644 --- a/crates/rome_js_formatter/src/js/objects/setter_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/setter_object_member.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsSetterObjectMember; use rome_js_syntax::JsSetterObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsSetterObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsSetterObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsSetterObjectMemberFields { set_token, name, @@ -18,8 +15,8 @@ impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &JsShorthandPropertyObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsShorthandPropertyObjectMemberFields { name } = node.as_fields(); - formatted![formatter, [name.format()]] + write![f, [name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/statements/block_statement.rs b/crates/rome_js_formatter/src/js/statements/block_statement.rs index aa33df71e78..589e1d6d0ac 100644 --- a/crates/rome_js_formatter/src/js/statements/block_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/block_statement.rs @@ -1,40 +1,44 @@ use crate::prelude::*; - +use rome_formatter::{format_args, write}; use rome_js_syntax::JsAnyStatement; use rome_js_syntax::JsBlockStatement; +use crate::formatter::TryFormatNodeListExtension; use crate::FormatNodeFields; use rome_js_syntax::JsBlockStatementFields; use rome_js_syntax::JsSyntaxKind; use rome_rowan::{AstNode, AstNodeList}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBlockStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsBlockStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsBlockStatementFields { l_curly_token, statements, r_curly_token, } = node.as_fields(); - let stmts = formatter.format_list(&statements); - if is_non_collapsable_empty_block(node) { - formatted![ - formatter, + write!( + f, [ l_curly_token.format(), hard_line_break(), r_curly_token.format() ] - ] + ) } else { - formatter - .delimited(&l_curly_token?, stmts, &r_curly_token?) - .block_indent() - .finish() + let format_statements = format_with(|f| { + f.join_with(&hard_line_break()) + .entries(statements.try_format_nodes()) + .finish() + }); + write!( + f, + [ + f.delimited(&l_curly_token?, &format_statements, &r_curly_token?) + .block_indent() + ] + ) } } } diff --git a/crates/rome_js_formatter/src/js/statements/break_statement.rs b/crates/rome_js_formatter/src/js/statements/break_statement.rs index 2ffd2050083..e8eb9a21c75 100644 --- a/crates/rome_js_formatter/src/js/statements/break_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/break_statement.rs @@ -1,33 +1,33 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsBreakStatement; use rome_js_syntax::JsBreakStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBreakStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsBreakStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsBreakStatementFields { break_token, label_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ - break_token.format(), - label_token - .format() - .with_or_empty(|label| formatted![formatter, [space_token(), label]]) - ] - ]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_with(|f| { + write!(f, [break_token.format()])?; + + if let Some(label_token) = &label_token { + write!(f, [space_token(), label_token.format()])?; + } + + Ok(()) + }), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/continue_statement.rs b/crates/rome_js_formatter/src/js/statements/continue_statement.rs index 7c6098cf2f5..09e2cbdf00e 100644 --- a/crates/rome_js_formatter/src/js/statements/continue_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/continue_statement.rs @@ -1,33 +1,33 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsContinueStatement; use rome_js_syntax::JsContinueStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsContinueStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsContinueStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsContinueStatementFields { continue_token, label_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ - continue_token.format(), - label_token - .format() - .with_or_empty(|token| formatted![formatter, [space_token(), token]]) - ] - ]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_with(|f| { + write!(f, [continue_token.format()])?; + + if let Some(label_token) = &label_token { + write!(f, [space_token(), label_token.format()])?; + } + + Ok(()) + }), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/debugger_statement.rs b/crates/rome_js_formatter/src/js/statements/debugger_statement.rs index 2312632aeed..e2fd882f152 100644 --- a/crates/rome_js_formatter/src/js/statements/debugger_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/debugger_statement.rs @@ -1,24 +1,24 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsDebuggerStatement; use rome_js_syntax::JsDebuggerStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDebuggerStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsDebuggerStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsDebuggerStatementFields { debugger_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [debugger_token.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(debugger_token.format()), + semicolon_token.as_ref() + ),] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/do_while_statement.rs b/crates/rome_js_formatter/src/js/statements/do_while_statement.rs index dc809b76a9a..a53c57fd23e 100644 --- a/crates/rome_js_formatter/src/js/statements/do_while_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/do_while_statement.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsDoWhileStatementFields; use rome_js_syntax::{JsAnyStatement, JsDoWhileStatement}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDoWhileStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsDoWhileStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsDoWhileStatementFields { do_token, body, @@ -19,31 +16,29 @@ impl FormatNodeFields for FormatNodeRule semicolon_token, } = node.as_fields(); - let head = formatted![formatter, [do_token.format()]]?; + write!(f, [do_token.format()])?; + + match body? { + JsAnyStatement::JsEmptyStatement(body) => { + write!(f, [body.format(), hard_line_break()])?; + } + body => { + write!(f, [space_token(), body.format()])?; + } + }; - let tail = formatted![ - formatter, + write![ + f, [ space_token(), while_token.format(), space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [test.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - semicolon_token.format().or_format(|| token(";")) + f.delimited(&l_paren_token?, &test.format(), &r_paren_token?,) + .soft_block_indent(), + semicolon_token + .format() + .or_format(|f| write!(f, [token(";")])) ] - ]?; - - let body = body?; - if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - formatted![formatter, [head, body.format(), hard_line_break(), tail,]] - } else { - formatted![formatter, [head, space_token(), body.format(), tail,]] - } + ] } } diff --git a/crates/rome_js_formatter/src/js/statements/empty_statement.rs b/crates/rome_js_formatter/src/js/statements/empty_statement.rs index 4426491e6d8..a824898bae6 100644 --- a/crates/rome_js_formatter/src/js/statements/empty_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/empty_statement.rs @@ -1,11 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::{JsEmptyStatement, JsEmptyStatementFields, JsSyntaxKind}; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsEmptyStatement, formatter: &JsFormatter) -> FormatResult<()> { + fn format_fields(node: &JsEmptyStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsEmptyStatementFields { semicolon_token } = node.as_fields(); let parent_kind = node.syntax().parent().map(|p| p.kind()); @@ -15,9 +16,9 @@ impl FormatNodeFields for FormatNodeRule { | Some(JsSyntaxKind::JS_IF_STATEMENT) | Some(JsSyntaxKind::JS_ELSE_CLAUSE) ) { - write!(f, [semicolon_token]) + write!(f, [semicolon_token.format()]) } else { - Ok(formatter.format_replaced(&semicolon_token?, empty_element())) + write!(f, [f.format_replaced(&semicolon_token?, &empty_element())]) } } } diff --git a/crates/rome_js_formatter/src/js/statements/expression_statement.rs b/crates/rome_js_formatter/src/js/statements/expression_statement.rs index f61a91861fa..71bf8468e2b 100644 --- a/crates/rome_js_formatter/src/js/statements/expression_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/expression_statement.rs @@ -1,24 +1,24 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExpressionStatement; use rome_js_syntax::JsExpressionStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExpressionStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsExpressionStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsExpressionStatementFields { expression, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [expression.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(expression.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/for_in_statement.rs b/crates/rome_js_formatter/src/js/statements/for_in_statement.rs index 22c5c0ffcba..a2ec86492fd 100644 --- a/crates/rome_js_formatter/src/js/statements/for_in_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/for_in_statement.rs @@ -1,15 +1,12 @@ -use rome_js_syntax::JsForInStatement; - use crate::prelude::*; -use crate::utils::format_head_body_statement; +use crate::utils::FormatBodyStatement; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; +use rome_js_syntax::JsForInStatement; use rome_js_syntax::JsForInStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForInStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsForInStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsForInStatementFields { for_token, l_paren_token, @@ -25,23 +22,20 @@ impl FormatNodeFields for FormatNodeRule { let in_token = in_token.format(); let expression = expression.format(); - Ok(group_elements(format_head_body_statement( - formatter, - formatted![ - formatter, - [ - for_token, - space_token(), - l_paren_token.format(), - group_elements(formatted![formatter, [initializer]]?), - space_token(), - in_token, - space_token(), - expression, - r_paren_token.format(), - ] - ]?, - body?, - )?)) + write!( + f, + [group_elements(&format_args!( + for_token, + space_token(), + l_paren_token.format(), + group_elements(&initializer), + space_token(), + in_token, + space_token(), + expression, + r_paren_token.format(), + FormatBodyStatement::new(&body?) + ))] + ) } } diff --git a/crates/rome_js_formatter/src/js/statements/for_of_statement.rs b/crates/rome_js_formatter/src/js/statements/for_of_statement.rs index 3368d1db124..78018c28868 100644 --- a/crates/rome_js_formatter/src/js/statements/for_of_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/for_of_statement.rs @@ -1,16 +1,13 @@ -use rome_js_syntax::JsForOfStatement; - use crate::prelude::*; -use crate::utils::format_head_body_statement; +use crate::utils::FormatBodyStatement; +use rome_formatter::{format_args, write}; +use rome_js_syntax::JsForOfStatement; use crate::FormatNodeFields; use rome_js_syntax::JsForOfStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForOfStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsForOfStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsForOfStatementFields { for_token, await_token, @@ -22,26 +19,23 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - Ok(group_elements(format_head_body_statement( - formatter, - formatted![ - formatter, - [ - for_token.format(), - space_token(), - await_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), - l_paren_token.format(), - group_elements(formatted![formatter, [initializer.format()]]?), - space_token(), - of_token.format(), - space_token(), - expression.format(), - r_paren_token.format() - ] - ]?, - body?, - )?)) + write!( + f, + [group_elements(&format_args![ + for_token.format(), + space_token(), + await_token + .format() + .with_or_empty(|token, f| write![f, [token, space_token()]]), + l_paren_token.format(), + group_elements(&initializer.format()), + space_token(), + of_token.format(), + space_token(), + expression.format(), + r_paren_token.format(), + FormatBodyStatement::new(&body?) + ])] + ) } } diff --git a/crates/rome_js_formatter/src/js/statements/for_statement.rs b/crates/rome_js_formatter/src/js/statements/for_statement.rs index b7220781af7..eb9cbc7bbff 100644 --- a/crates/rome_js_formatter/src/js/statements/for_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/for_statement.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsAnyStatement; @@ -6,10 +7,7 @@ use rome_js_syntax::JsForStatement; use rome_js_syntax::JsForStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsForStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsForStatementFields { for_token, l_paren_token, @@ -22,45 +20,47 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - let inner = if initializer.is_some() || test.is_some() || update.is_some() { - formatted![ - formatter, + let condition = format_with(|f| { + if initializer.is_some() || test.is_some() || update.is_some() { + write![ + f, + [ + initializer.format(), + first_semi_token.format(), + soft_line_break_or_space(), + test.format(), + second_semi_token.format(), + soft_line_break_or_space(), + update.format(), + ] + ] + } else { + write![f, [first_semi_token.format(), second_semi_token.format()]] + } + }); + + let content = format_with(|f| { + write!( + f, [ - initializer.format(), - first_semi_token.format(), - soft_line_break_or_space(), - test.format(), - second_semi_token.format(), - soft_line_break_or_space(), - update.format(), + for_token.format(), + space_token(), + f.delimited(l_paren_token.as_ref()?, &condition, r_paren_token.as_ref()?,) + .soft_block_indent(), ] - ]? - } else { - formatted![ - formatter, - [first_semi_token.format(), second_semi_token.format(),] - ]? - }; + )?; - // Force semicolon insertion for empty bodies - let body = body?; - let body = if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - formatted![formatter, [body.format(), token(";")]]? - } else { - formatted![formatter, [space_token(), body.format()]]? - }; + // Force semicolon insertion for empty bodies + match body.as_ref()? { + JsAnyStatement::JsEmptyStatement(body) => { + write![f, [body.format(), token(";")]] + } + body => { + write!(f, [space_token(), body.format()]) + } + } + }); - Ok(group_elements(formatted![ - formatter, - [ - for_token.format(), - space_token(), - formatter - .delimited(&l_paren_token?, inner, &r_paren_token?,) - .soft_block_indent() - .finish()?, - body - ] - ]?)) + write!(f, [group_elements(&content)]) } } diff --git a/crates/rome_js_formatter/src/js/statements/if_statement.rs b/crates/rome_js_formatter/src/js/statements/if_statement.rs index 0048a8f8d27..275f71dfdc9 100644 --- a/crates/rome_js_formatter/src/js/statements/if_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/if_statement.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsSyntaxToken; @@ -6,10 +7,9 @@ use rome_js_syntax::{JsAnyStatement, JsElseClauseFields, JsIfStatement}; use rome_js_syntax::{JsElseClause, JsIfStatementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsIfStatement, formatter: &JsFormatter) -> FormatResult { - let (head, mut else_clause) = format_if_element(formatter, None, node)?; + fn format_fields(node: &JsIfStatement, f: &mut JsFormatter) -> FormatResult<()> { + let mut else_clause = format_if_element(f, None, node)?; - let mut if_chain = vec![head]; while let Some(clause) = else_clause.take() { let JsElseClauseFields { else_token, @@ -18,34 +18,27 @@ impl FormatNodeFields for FormatNodeRule { match alternate? { JsAnyStatement::JsIfStatement(stmt) => { - let (head, alternate) = format_if_element(formatter, Some(else_token?), &stmt)?; + let alternate = format_if_element(f, Some(else_token?), &stmt)?; - if_chain.push(head); else_clause = alternate; } alternate => { - if_chain.push(formatted![ - formatter, - [ - space_token(), - else_token.format(), - into_block(formatter, alternate)?, - ] - ]?); + write![f, [space_token(), else_token.format(),]]?; + write_consequent_as_block(f, alternate)?; } } } - Ok(concat_elements(if_chain)) + Ok(()) } } /// Format a single `else? if(test) consequent` element, returning the next else clause fn format_if_element( - formatter: &JsFormatter, + f: &mut JsFormatter, else_token: Option, stmt: &JsIfStatement, -) -> FormatResult<(FormatElement, Option)> { +) -> FormatResult> { let JsIfStatementFields { if_token, l_paren_token, @@ -55,48 +48,43 @@ fn format_if_element( else_clause, } = stmt.as_fields(); - let head = formatted![ - formatter, + if let Some(else_token) = else_token { + write!(f, [space_token(), else_token.format(), space_token()])?; + } + + write![ + f, [ - else_token.format().with_or_empty(|token| formatted![ - formatter, - [space_token(), token, space_token(),] - ]), if_token.format(), space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [test.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - into_block(formatter, consequent?)?, + f.delimited(&l_paren_token?, &test.format(), &r_paren_token?,) + .soft_block_indent(), ] ]?; - Ok((head, else_clause)) + write_consequent_as_block(f, consequent?)?; + + Ok(else_clause) } /// Wraps the statement into a block if its not already a JsBlockStatement -fn into_block(formatter: &JsFormatter, stmt: JsAnyStatement) -> FormatResult { +fn write_consequent_as_block(f: &mut JsFormatter, stmt: JsAnyStatement) -> FormatResult<()> { if matches!(stmt, JsAnyStatement::JsBlockStatement(_)) { - return formatted![formatter, [space_token(), stmt.format()]]; + return write![f, [space_token(), stmt.format()]]; } // If the body is an empty statement, force a line break to ensure behavior // is coherent with `is_non_collapsable_empty_block` if matches!(stmt, JsAnyStatement::JsEmptyStatement(_)) { - return formatted![formatter, [stmt.format(), hard_line_break()]]; + return write![f, [stmt.format(), hard_line_break()]]; } - formatted![ - formatter, + write![ + f, [ space_token(), token("{"), - block_indent(formatted![formatter, [stmt.format()]]?), + block_indent(&stmt.format()), token("}"), ] ] diff --git a/crates/rome_js_formatter/src/js/statements/labeled_statement.rs b/crates/rome_js_formatter/src/js/statements/labeled_statement.rs index 495b3ad9c13..5ca7ad45de8 100644 --- a/crates/rome_js_formatter/src/js/statements/labeled_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/labeled_statement.rs @@ -1,31 +1,28 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsLabeledStatementFields; use rome_js_syntax::{JsAnyStatement, JsLabeledStatement}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsLabeledStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsLabeledStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsLabeledStatementFields { label_token, colon_token, body, } = node.as_fields(); - let label = label_token.format(); - let colon = colon_token.format(); + write!(f, [label_token.format(), colon_token.format()])?; - let body = body?; - if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - // If the body is an empty statement, force semicolon insertion - let statement = body.format(); - formatted![formatter, [label, colon, statement, token(";")]] - } else { - let statement = body.format(); - formatted![formatter, [label, colon, space_token(), statement]] + match body? { + JsAnyStatement::JsEmptyStatement(empty) => { + // If the body is an empty statement, force semicolon insertion + write!(f, [empty.format(), token(";")]) + } + body => { + write!(f, [space_token(), body.format()]) + } } } } diff --git a/crates/rome_js_formatter/src/js/statements/return_statement.rs b/crates/rome_js_formatter/src/js/statements/return_statement.rs index b3611203a6f..e2ff4537a27 100644 --- a/crates/rome_js_formatter/src/js/statements/return_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/return_statement.rs @@ -1,52 +1,45 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; -use rome_js_syntax::{JsReturnStatement, JsReturnStatementFields, JsSyntaxKind}; +use rome_formatter::{format_args, write}; +use rome_js_syntax::{JsAnyExpression, JsReturnStatement, JsReturnStatementFields, JsSyntaxKind}; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsReturnStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsReturnStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsReturnStatementFields { return_token, argument, semicolon_token, } = node.as_fields(); - let return_token = return_token.format(); + write!( + f, + [FormatWithSemicolon::new( + &format_with(|f| { + write!(f, [return_token.format()])?; - let argument = if let Some(argument) = argument { - if matches!( - argument.syntax().kind(), - JsSyntaxKind::JS_SEQUENCE_EXPRESSION - ) { - formatted![ - formatter, - [ - space_token(), - group_elements(formatted![ - formatter, - [ - token("("), - soft_block_indent(formatted![formatter, [argument.format()]]?), - token(")") - ] - ]?), - ] - ]? - } else { - formatted![formatter, [space_token(), argument.format()]]? - } - } else { - empty_element() - }; + if let Some(argument) = &argument { + write!(f, [space_token()])?; - format_with_semicolon( - formatter, - formatted![formatter, [return_token, argument]]?, - semicolon_token, + if let JsAnyExpression::JsSequenceExpression(expression) = argument { + write![ + f, + [group_elements(&format_args![ + token("("), + soft_block_indent(&argument.format()), + token(")") + ])] + ]?; + } else { + write![f, [argument.format()]]?; + } + } + + Ok(()) + }), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/switch_statement.rs b/crates/rome_js_formatter/src/js/statements/switch_statement.rs index dae9617ad3a..db38a9c46e8 100644 --- a/crates/rome_js_formatter/src/js/statements/switch_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/switch_statement.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsSwitchStatement, JsSwitchStatementFields}; use rome_rowan::{AstNode, AstNodeList}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsSwitchStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsSwitchStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsSwitchStatementFields { switch_token, l_paren_token, @@ -18,37 +16,32 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - formatted![ - formatter, + let format_cases = format_once(|f| { + if cases.is_empty() { + write!(f, [hard_line_break()])?; + } else { + let mut join = f.join_nodes_with_hardline(); + + for case in cases { + join.entry(&case.syntax(), &case.format()); + } + + join.finish()?; + } + + Ok(()) + }); + + write![ + f, [ switch_token.format(), space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [discriminant.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, + f.delimited(&l_paren_token?, &discriminant.format(), &r_paren_token?,) + .soft_block_indent(), space_token(), - formatter - .delimited( - &l_curly_token?, - if cases.is_empty() { - hard_line_break() - } else { - join_elements_hard_line( - cases - .iter() - .map(|node| node.syntax().clone()) - .zip(formatter.format_all(cases.iter().formatted())?), - ) - }, - &r_curly_token? - ) + f.delimited(&l_curly_token?, &format_cases, &r_curly_token?) .block_indent() - .finish()? ] ] } diff --git a/crates/rome_js_formatter/src/js/statements/throw_statement.rs b/crates/rome_js_formatter/src/js/statements/throw_statement.rs index 7c4add5f8b0..e782393699a 100644 --- a/crates/rome_js_formatter/src/js/statements/throw_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/throw_statement.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsThrowStatement; use rome_js_syntax::JsThrowStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsThrowStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsThrowStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsThrowStatementFields { throw_token, argument, @@ -19,10 +17,12 @@ impl FormatNodeFields for FormatNodeRule { let throw_token = throw_token.format(); let exception = argument.format(); - format_with_semicolon( - formatter, - formatted![formatter, [throw_token, space_token(), exception]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(throw_token, space_token(), exception), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs b/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs index 2fb37edecb5..553c22b52af 100644 --- a/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsTryFinallyStatement; use rome_js_syntax::JsTryFinallyStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsTryFinallyStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsTryFinallyStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsTryFinallyStatementFields { try_token, body, @@ -16,18 +14,15 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsTryStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsTryStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsTryStatementFields { try_token, body, catch_clause, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ try_token.format(), space_token(), diff --git a/crates/rome_js_formatter/src/js/statements/variable_statement.rs b/crates/rome_js_formatter/src/js/statements/variable_statement.rs index 86431546ccd..4c60d5009b0 100644 --- a/crates/rome_js_formatter/src/js/statements/variable_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/variable_statement.rs @@ -1,24 +1,24 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsVariableStatement; use rome_js_syntax::JsVariableStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsVariableStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableStatementFields { declaration, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [declaration.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &declaration.format(), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/while_statement.rs b/crates/rome_js_formatter/src/js/statements/while_statement.rs index bdf9a7ce6a7..7ecd4cbd353 100644 --- a/crates/rome_js_formatter/src/js/statements/while_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/while_statement.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_head_body_statement; +use crate::utils::FormatBodyStatement; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsWhileStatement; use rome_js_syntax::JsWhileStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsWhileStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsWhileStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsWhileStatementFields { while_token, l_paren_token, @@ -18,24 +16,15 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - format_head_body_statement( - formatter, - formatted![ - formatter, - [ - while_token.format(), - space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [test.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - ] - ]?, - body?, + write!( + f, + [ + while_token.format(), + space_token(), + f.delimited(&l_paren_token?, &test.format(), &r_paren_token?,) + .soft_block_indent(), + FormatBodyStatement::new(&body?) + ] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/with_statement.rs b/crates/rome_js_formatter/src/js/statements/with_statement.rs index 74acd875701..94dc343dfa2 100644 --- a/crates/rome_js_formatter/src/js/statements/with_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/with_statement.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_head_body_statement; +use rome_formatter::{format_args, write}; +use crate::utils::FormatBodyStatement; use crate::FormatNodeFields; use rome_js_syntax::JsWithStatement; use rome_js_syntax::JsWithStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsWithStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsWithStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsWithStatementFields { with_token, l_paren_token, @@ -18,24 +16,15 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - format_head_body_statement( - formatter, - formatted![ - formatter, - [ - with_token.format(), - space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [object.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - ] - ]?, - body?, + write!( + f, + [ + with_token.format(), + space_token(), + f.delimited(&l_paren_token?, &object.format(), &r_paren_token?,) + .soft_block_indent(), + FormatBodyStatement::new(&body?) + ] ) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown.rs b/crates/rome_js_formatter/src/js/unknown/unknown.rs index 9bf277de4f3..e46f296f448 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown.rs @@ -5,7 +5,7 @@ use rome_js_syntax::JsUnknown; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsUnknown, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsUnknown, formatter: &mut JsFormatter) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs b/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs index 5114f3eac51..e977e0720b5 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs @@ -5,10 +5,7 @@ use rome_js_syntax::JsUnknownAssignment; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnknownAssignment, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs b/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs index cb2e6fcc401..2253cb9f5aa 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsUnknownBinding; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownBinding, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnknownBinding, formatter: &mut JsFormatter) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs b/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs index 6f600fb0093..f1dbc3f6de2 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsUnknownExpression; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnknownExpression, formatter: &mut JsFormatter) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs b/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs index 2727d894539..d36047efade 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs @@ -10,8 +10,8 @@ impl FormatNodeFields { fn format_fields( node: &JsUnknownImportAssertionEntry, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_member.rs b/crates/rome_js_formatter/src/js/unknown/unknown_member.rs index 53e55dbcf54..6eeae75fa89 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_member.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_member.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsUnknownMember; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnknownMember, formatter: &mut JsFormatter) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs b/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs index 3cb79da2e7b..d0dd7583b35 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs @@ -10,8 +10,8 @@ impl FormatNodeFields { fn format_fields( node: &JsUnknownNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs b/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs index 54740420ec8..b48b5bffe4f 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsUnknownParameter; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnknownParameter, formatter: &mut JsFormatter) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs b/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs index 75230cdf800..7518b8f3294 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsUnknownStatement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsUnknownStatement, formatter: &mut JsFormatter) -> FormatResult<()> { unknown_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/any/attribute.rs b/crates/rome_js_formatter/src/jsx/any/attribute.rs index 4b06181502d..0b8ffddda85 100644 --- a/crates/rome_js_formatter/src/jsx/any/attribute.rs +++ b/crates/rome_js_formatter/src/jsx/any/attribute.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyAttribute; impl FormatRule for FormatJsxAnyAttribute { type Context = JsFormatContext; - fn format(node: &JsxAnyAttribute, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyAttribute, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyAttribute::JsxAttribute(node) => formatted![formatter, [node.format()]], - JsxAnyAttribute::JsxSpreadAttribute(node) => formatted![formatter, [node.format()]], + JsxAnyAttribute::JsxAttribute(node) => node.format().format(f), + JsxAnyAttribute::JsxSpreadAttribute(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/attribute_name.rs b/crates/rome_js_formatter/src/jsx/any/attribute_name.rs index 3be92016ec3..09bd8c452a7 100644 --- a/crates/rome_js_formatter/src/jsx/any/attribute_name.rs +++ b/crates/rome_js_formatter/src/jsx/any/attribute_name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyAttributeName; impl FormatRule for FormatJsxAnyAttributeName { type Context = JsFormatContext; - fn format(node: &JsxAnyAttributeName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyAttributeName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyAttributeName::JsxName(node) => formatted![formatter, [node.format()]], - JsxAnyAttributeName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyAttributeName::JsxName(node) => node.format().format(f), + JsxAnyAttributeName::JsxNamespaceName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/attribute_value.rs b/crates/rome_js_formatter/src/jsx/any/attribute_value.rs index 10907a393e3..f7865668e2e 100644 --- a/crates/rome_js_formatter/src/jsx/any/attribute_value.rs +++ b/crates/rome_js_formatter/src/jsx/any/attribute_value.rs @@ -5,13 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyAttributeValue; impl FormatRule for FormatJsxAnyAttributeValue { type Context = JsFormatContext; - fn format(node: &JsxAnyAttributeValue, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyAttributeValue, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyAttributeValue::JsxAnyTag(node) => formatted![formatter, [node.format()]], - JsxAnyAttributeValue::JsxString(node) => formatted![formatter, [node.format()]], - JsxAnyAttributeValue::JsxExpressionAttributeValue(node) => { - formatted![formatter, [node.format()]] - } + JsxAnyAttributeValue::JsxAnyTag(node) => node.format().format(f), + JsxAnyAttributeValue::JsxString(node) => node.format().format(f), + JsxAnyAttributeValue::JsxExpressionAttributeValue(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/child.rs b/crates/rome_js_formatter/src/jsx/any/child.rs index 69585692b21..145dd2dd625 100644 --- a/crates/rome_js_formatter/src/jsx/any/child.rs +++ b/crates/rome_js_formatter/src/jsx/any/child.rs @@ -5,14 +5,14 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyChild; impl FormatRule for FormatJsxAnyChild { type Context = JsFormatContext; - fn format(node: &JsxAnyChild, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyChild, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyChild::JsxElement(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxSelfClosingElement(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxText(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxExpressionChild(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxSpreadChild(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxFragment(node) => formatted![formatter, [node.format()]], + JsxAnyChild::JsxElement(node) => node.format().format(f), + JsxAnyChild::JsxSelfClosingElement(node) => node.format().format(f), + JsxAnyChild::JsxText(node) => node.format().format(f), + JsxAnyChild::JsxExpressionChild(node) => node.format().format(f), + JsxAnyChild::JsxSpreadChild(node) => node.format().format(f), + JsxAnyChild::JsxFragment(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/element_name.rs b/crates/rome_js_formatter/src/jsx/any/element_name.rs index 074e1ec59e5..1ec70481b5a 100644 --- a/crates/rome_js_formatter/src/jsx/any/element_name.rs +++ b/crates/rome_js_formatter/src/jsx/any/element_name.rs @@ -5,14 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyElementName; impl FormatRule for FormatJsxAnyElementName { type Context = JsFormatContext; - fn format(node: &JsxAnyElementName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyElementName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyElementName::JsxName(node) => formatted![formatter, [node.format()]], - JsxAnyElementName::JsxReferenceIdentifier(node) => { - formatted![formatter, [node.format()]] - } - JsxAnyElementName::JsxMemberName(node) => formatted![formatter, [node.format()]], - JsxAnyElementName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyElementName::JsxName(node) => node.format().format(f), + JsxAnyElementName::JsxReferenceIdentifier(node) => node.format().format(f), + JsxAnyElementName::JsxMemberName(node) => node.format().format(f), + JsxAnyElementName::JsxNamespaceName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/name.rs b/crates/rome_js_formatter/src/jsx/any/name.rs index abc34a691af..1c625ba744c 100644 --- a/crates/rome_js_formatter/src/jsx/any/name.rs +++ b/crates/rome_js_formatter/src/jsx/any/name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyName; impl FormatRule for FormatJsxAnyName { type Context = JsFormatContext; - fn format(node: &JsxAnyName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyName::JsxName(node) => formatted![formatter, [node.format()]], - JsxAnyName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyName::JsxName(node) => node.format().format(f), + JsxAnyName::JsxNamespaceName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/object_name.rs b/crates/rome_js_formatter/src/jsx/any/object_name.rs index ae6437478f0..55fab7c6c8b 100644 --- a/crates/rome_js_formatter/src/jsx/any/object_name.rs +++ b/crates/rome_js_formatter/src/jsx/any/object_name.rs @@ -5,13 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyObjectName; impl FormatRule for FormatJsxAnyObjectName { type Context = JsFormatContext; - fn format(node: &JsxAnyObjectName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyObjectName, f: &mut Formatter) -> FormatResult<()> { match node { - JsxAnyObjectName::JsxReferenceIdentifier(node) => { - formatted![formatter, [node.format()]] - } - JsxAnyObjectName::JsxMemberName(node) => formatted![formatter, [node.format()]], - JsxAnyObjectName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyObjectName::JsxReferenceIdentifier(node) => node.format().format(f), + JsxAnyObjectName::JsxMemberName(node) => node.format().format(f), + JsxAnyObjectName::JsxNamespaceName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/tag.rs b/crates/rome_js_formatter/src/jsx/any/tag.rs index 20a8412811f..d59004e023e 100644 --- a/crates/rome_js_formatter/src/jsx/any/tag.rs +++ b/crates/rome_js_formatter/src/jsx/any/tag.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyTag; impl FormatRule for FormatJsxAnyTag { type Context = JsFormatContext; - fn format(node: &JsxAnyTag, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxAnyTag, f: &mut Formatter) -> FormatResult<()> { match node { - JsxAnyTag::JsxElement(node) => formatted![formatter, [node.format()]], - JsxAnyTag::JsxSelfClosingElement(node) => formatted![formatter, [node.format()]], - JsxAnyTag::JsxFragment(node) => formatted![formatter, [node.format()]], + JsxAnyTag::JsxElement(node) => node.format().format(f), + JsxAnyTag::JsxSelfClosingElement(node) => node.format().format(f), + JsxAnyTag::JsxFragment(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/attribute.rs b/crates/rome_js_formatter/src/jsx/attribute/attribute.rs index a6fbf43e13a..475b1bca08e 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/attribute.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/attribute.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxAttribute, JsxAttributeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxAttribute, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsxAttribute, f: &mut JsFormatter) -> FormatResult<()> { let JsxAttributeFields { name, initializer } = node.as_fields(); - formatted![formatter, [name.format(), initializer.format()]] + write![f, [name.format(), initializer.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs index 93bbd8a9360..51581a11a37 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs @@ -1,11 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxAttributeInitializerClause, JsxAttributeInitializerClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxAttributeInitializerClause, f: &JsFormatter) -> FormatResult<()> { + fn format_fields( + node: &JsxAttributeInitializerClause, + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsxAttributeInitializerClauseFields { eq_token, value } = node.as_fields(); write![f, [eq_token.format(), value.format()]] diff --git a/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs b/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs index b9725080fec..bcfce6362e2 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs @@ -1,72 +1,69 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{ JsAnyExpression, JsxExpressionAttributeValue, JsxExpressionAttributeValueFields, }; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxExpressionAttributeValue, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxExpressionAttributeValue, f: &mut JsFormatter) -> FormatResult<()> { let JsxExpressionAttributeValueFields { l_curly_token, expression, r_curly_token, } = node.as_fields(); - let expression = expression?; + write!( + f, + [group_elements(&format_with(|f| { + write!(f, [l_curly_token.format()])?; - // When the inner expression for a prop is an object, array, or call expression, we want to combine the - // delimiters of the expression (`{`, `}`, `[`, `]`, or `(`, `)`) with the delimiters of the JSX - // attribute (`{`, `}`), so that we don't end up with redundant indents. Therefore we do not - // soft indent the expression - // - // Good: - // ```jsx - // - // ``` - // - // Bad: - // ```jsx - // - // ``` - // - let formatted_expression = if matches!( - expression, - JsAnyExpression::JsObjectExpression(_) - | JsAnyExpression::JsArrayExpression(_) - | JsAnyExpression::JsCallExpression(_) - ) { - formatted![formatter, [expression.format()]]? - } else { - soft_block_indent(formatted![formatter, [expression.format()]]?) - }; + let expression = expression.as_ref()?; + + // When the inner expression for a prop is an object, array, or call expression, we want to combine the + // delimiters of the expression (`{`, `}`, `[`, `]`, or `(`, `)`) with the delimiters of the JSX + // attribute (`{`, `}`), so that we don't end up with redundant indents. Therefore we do not + // soft indent the expression + // + // Good: + // ```jsx + // + // ``` + // + // Bad: + // ```jsx + // + // ``` + // + if matches!( + expression, + JsAnyExpression::JsObjectExpression(_) + | JsAnyExpression::JsArrayExpression(_) + | JsAnyExpression::JsCallExpression(_) + ) { + write!(f, [expression.format()])?; + } else { + write!(f, [soft_block_indent(&expression.format())])?; + }; - Ok(group_elements(formatted![ - formatter, - [ - l_curly_token.format(), - formatted_expression, - line_suffix_boundary(), - r_curly_token.format(), - ] - ]?)) + write!(f, [line_suffix_boundary(), r_curly_token.format()]) + }))] + ) } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs b/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs index c5f7658ac63..edab661c9ed 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxSpreadAttribute, JsxSpreadAttributeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxSpreadAttribute, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxSpreadAttribute, f: &mut JsFormatter) -> FormatResult<()> { let JsxSpreadAttributeFields { l_curly_token, dotdotdot_token, @@ -14,8 +12,8 @@ impl FormatNodeFields for FormatNodeRule r_curly_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_curly_token.format(), dotdotdot_token.format(), diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs b/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs index ddc80bf66a4..47990fcc83d 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs @@ -5,10 +5,7 @@ use rome_js_syntax::JsxExpressionChild; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxExpressionChild, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxExpressionChild, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/name.rs b/crates/rome_js_formatter/src/jsx/auxiliary/name.rs index 941d97d825c..0dd6168541a 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/name.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/name.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxName, JsxNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxName, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsxName, f: &mut JsFormatter) -> FormatResult<()> { let JsxNameFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs b/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs index 95d013a508f..8a6fc128d67 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs @@ -1,21 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxNamespaceName, JsxNamespaceNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxNamespaceName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxNamespaceName, f: &mut JsFormatter) -> FormatResult<()> { let JsxNamespaceNameFields { namespace, colon_token, name, } = node.as_fields(); - formatted![ - formatter, - [namespace.format(), colon_token.format(), name.format()] - ] + write![f, [namespace.format(), colon_token.format(), name.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs b/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs index 284c2b80cde..f124b9e6294 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsxReferenceIdentifier; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxReferenceIdentifier, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [node.value_token().format()]] + fn format_fields(node: &JsxReferenceIdentifier, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [node.value_token().format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs b/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs index f8862914796..24337769ffe 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs @@ -5,10 +5,7 @@ use rome_js_syntax::JsxSpreadChild; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxSpreadChild, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxSpreadChild, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/string.rs b/crates/rome_js_formatter/src/jsx/auxiliary/string.rs index 1fbef61a1f0..9725b5058f0 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/string.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/string.rs @@ -1,9 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsxString; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxString, formatter: &JsFormatter) -> FormatResult { - formatted![formatter, [node.value_token().format()]] + fn format_fields(node: &JsxString, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [node.value_token().format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/text.rs b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs index 2087e17f910..28fe040e031 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/text.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxText, JsxTextFields}; use std::borrow::Cow; use std::fmt; @@ -7,14 +8,16 @@ use std::ops::Range; use std::str::CharIndices; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxText, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsxText, f: &mut JsFormatter) -> FormatResult<()> { let JsxTextFields { value_token } = node.as_fields(); let token = value_token?; let new_text = clean_jsx_text(token.text()); let start = token.text_range().start(); - let new_token = Token::from_syntax_token_cow_slice(new_text, &token, start); - Ok(formatter.format_replaced(&token, FormatElement::from(new_token))) + write!( + f, + [f.format_replaced(&token, &syntax_token_cow_slice(new_text, &token, start))] + ) } } diff --git a/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs b/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs index 956bde79b09..3fcf4220c0c 100644 --- a/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs +++ b/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsxTagExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxTagExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [node.tag().format()]] + fn format_fields(node: &JsxTagExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [node.tag().format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs b/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs index 02b850c0e4f..be3e5cd7336 100644 --- a/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs +++ b/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs @@ -1,16 +1,18 @@ use crate::generated::FormatJsxAttributeList; use crate::prelude::*; +use rome_formatter::write; use rome_js_syntax::JsxAttributeList; impl FormatRule for FormatJsxAttributeList { type Context = JsFormatContext; - fn format(node: &JsxAttributeList, formatter: &JsFormatter) -> FormatResult { - let attributes = join_elements( - soft_line_break_or_space(), - formatter.format_all(node.iter().formatted())?, - ); + fn format(node: &JsxAttributeList, f: &mut JsFormatter) -> FormatResult<()> { + let attributes = format_with(|f| { + f.join_with(&soft_line_break_or_space()) + .entries(node.iter().formatted()) + .finish() + }); - Ok(group_elements(soft_block_indent(attributes))) + write!(f, [group_elements(&soft_block_indent(&attributes))]) } } diff --git a/crates/rome_js_formatter/src/jsx/lists/child_list.rs b/crates/rome_js_formatter/src/jsx/lists/child_list.rs index 622ba1df988..2da16c4c470 100644 --- a/crates/rome_js_formatter/src/jsx/lists/child_list.rs +++ b/crates/rome_js_formatter/src/jsx/lists/child_list.rs @@ -7,7 +7,7 @@ use rome_rowan::AstNode; impl FormatRule for FormatJsxChildList { type Context = JsFormatContext; - fn format(node: &JsxChildList, formatter: &JsFormatter) -> FormatResult { + fn format(node: &JsxChildList, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/objects/member_name.rs b/crates/rome_js_formatter/src/jsx/objects/member_name.rs index 6dd25c95ea3..f6d742b0596 100644 --- a/crates/rome_js_formatter/src/jsx/objects/member_name.rs +++ b/crates/rome_js_formatter/src/jsx/objects/member_name.rs @@ -1,18 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxMemberName, JsxMemberNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxMemberName, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsxMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsxMemberNameFields { object, dot_token, member, } = node.as_fields(); - formatted![ - formatter, - [object.format(), dot_token.format(), member.format(),] - ] + write![f, [object.format(), dot_token.format(), member.format(),]] } } diff --git a/crates/rome_js_formatter/src/jsx/tag/closing_element.rs b/crates/rome_js_formatter/src/jsx/tag/closing_element.rs index 5cd4148f85c..eb4776a28e7 100644 --- a/crates/rome_js_formatter/src/jsx/tag/closing_element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/closing_element.rs @@ -5,10 +5,7 @@ use rome_js_syntax::JsxClosingElement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxClosingElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxClosingElement, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs b/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs index f9ca216d08d..ba79ac574b7 100644 --- a/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs +++ b/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxClosingFragment, JsxClosingFragmentFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxClosingFragment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxClosingFragment, f: &mut JsFormatter) -> FormatResult<()> { let JsxClosingFragmentFields { r_angle_token, slash_token, l_angle_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_angle_token.format(), slash_token.format(), diff --git a/crates/rome_js_formatter/src/jsx/tag/element.rs b/crates/rome_js_formatter/src/jsx/tag/element.rs index c9cc333b1f1..026304b00d4 100644 --- a/crates/rome_js_formatter/src/jsx/tag/element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/element.rs @@ -5,7 +5,7 @@ use rome_js_syntax::JsxElement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxElement, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsxElement, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/tag/fragment.rs b/crates/rome_js_formatter/src/jsx/tag/fragment.rs index b1aff3153bf..4a531c278f3 100644 --- a/crates/rome_js_formatter/src/jsx/tag/fragment.rs +++ b/crates/rome_js_formatter/src/jsx/tag/fragment.rs @@ -1,17 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxFragment, JsxFragmentFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxFragment, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &JsxFragment, f: &mut JsFormatter) -> FormatResult<()> { let JsxFragmentFields { opening_fragment, children, closing_fragment, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ opening_fragment.format(), children.format(), diff --git a/crates/rome_js_formatter/src/jsx/tag/opening_element.rs b/crates/rome_js_formatter/src/jsx/tag/opening_element.rs index dfa35aad799..caa76e1e908 100644 --- a/crates/rome_js_formatter/src/jsx/tag/opening_element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/opening_element.rs @@ -5,10 +5,7 @@ use rome_js_syntax::JsxOpeningElement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxOpeningElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxOpeningElement, formatter: &mut JsFormatter) -> FormatResult<()> { verbatim_node(node.syntax()).format(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs b/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs index b5c313ee54d..465289c8849 100644 --- a/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs +++ b/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxOpeningFragment, JsxOpeningFragmentFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxOpeningFragment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxOpeningFragment, f: &mut JsFormatter) -> FormatResult<()> { let JsxOpeningFragmentFields { r_angle_token, l_angle_token, } = node.as_fields(); - formatted![formatter, [l_angle_token.format(), r_angle_token.format()]] + write![f, [l_angle_token.format(), r_angle_token.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs b/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs index fd8b3e1cac9..c9c305726a3 100644 --- a/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsxSelfClosingElement, JsxSelfClosingElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxSelfClosingElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &JsxSelfClosingElement, f: &mut JsFormatter) -> FormatResult<()> { let JsxSelfClosingElementFields { l_angle_token, name, @@ -16,8 +14,8 @@ impl FormatNodeFields for FormatNodeRule { - type Format: Format; + type Format: Format; /// Returns an object that is able to format this object. fn format(&'a self) -> Self::Format; @@ -83,15 +84,15 @@ where /// Used to convert this object into an object that can be formatted. /// /// The difference to [AsFormat] is that this trait takes ownership of `self`. -pub trait IntoFormat { - type Format: Format; +pub trait IntoFormat { + type Format: Format; fn into_format(self) -> Self::Format; } -impl IntoFormat for SyntaxResult +impl IntoFormat for SyntaxResult where - T: IntoFormat, + T: IntoFormat, { type Format = SyntaxResult; @@ -103,9 +104,9 @@ where /// Implement [IntoFormat] for [Option] when `T` implements [IntoFormat] /// /// Allows to call format on optional AST fields without having to unwrap the field first. -impl IntoFormat for Option +impl IntoFormat for Option where - T: IntoFormat, + T: IntoFormat, { type Format = Option; @@ -117,28 +118,32 @@ where /// Formatting specific [Iterator] extensions pub trait FormattedIterExt { /// Converts every item to an object that knows how to format it. - fn formatted(self) -> FormattedIter + fn formatted(self) -> FormattedIter where Self: Iterator + Sized, - Self::Item: IntoFormat, + Self::Item: IntoFormat, { - FormattedIter { inner: self } + FormattedIter { + inner: self, + options: PhantomData, + } } } impl FormattedIterExt for I where I: Iterator {} -pub struct FormattedIter +pub struct FormattedIter where Iter: Iterator, { inner: Iter, + options: PhantomData, } -impl Iterator for FormattedIter +impl Iterator for FormattedIter where Iter: Iterator, - Item: IntoFormat, + Item: IntoFormat, { type Item = Item::Format; @@ -147,17 +152,17 @@ where } } -impl FusedIterator for FormattedIter +impl FusedIterator for FormattedIter where Iter: FusedIterator, - Item: IntoFormat, + Item: IntoFormat, { } -impl ExactSizeIterator for FormattedIter +impl ExactSizeIterator for FormattedIter where Iter: Iterator + ExactSizeIterator, - Item: IntoFormat, + Item: IntoFormat, { } @@ -175,7 +180,7 @@ where { type Context = JsFormatContext; - fn format(node: &N, f: &JsFormatter) -> FormatResult<()> { + fn format(node: &N, f: &mut JsFormatter) -> FormatResult<()> { let syntax = node.syntax(); if has_formatter_suppressions(syntax) { write!(f, [suppressed_node(syntax)])?; @@ -192,7 +197,7 @@ where T: AstNode, { /// Formats the node's fields. - fn format_fields(item: &T, formatter: &mut JsFormatter) -> FormatResult; + fn format_fields(item: &T, f: &mut JsFormatter) -> FormatResult<()>; } /// Format implementation specific to JavaScript tokens. @@ -208,7 +213,7 @@ impl FormatRule for FormatJsSyntaxToken { f, [ format_leading_trivia(token, formatter::TriviaPrintMode::Full), - Token::from(token), + FormatTrimmedToken::new(token), format_trailing_trivia(token), ] ) @@ -223,7 +228,7 @@ impl<'a> AsFormat<'a> for JsSyntaxToken { } } -impl IntoFormat for JsSyntaxToken { +impl IntoFormat for JsSyntaxToken { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { diff --git a/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs b/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs index 5f4ebc1f905..d1ececbc678 100644 --- a/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs +++ b/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs @@ -5,17 +5,12 @@ use crate::prelude::*; use rome_js_syntax::TsAnyExternalModuleDeclarationBody; impl FormatRule for FormatTsAnyExternalModuleDeclarationBody { type Context = JsFormatContext; - fn format( - node: &TsAnyExternalModuleDeclarationBody, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &TsAnyExternalModuleDeclarationBody, f: &mut JsFormatter) -> FormatResult<()> { match node { TsAnyExternalModuleDeclarationBody::TsEmptyExternalModuleDeclarationBody(node) => { - formatted![formatter, [node.format()]] - } - TsAnyExternalModuleDeclarationBody::TsModuleBlock(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + TsAnyExternalModuleDeclarationBody::TsModuleBlock(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs b/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs index b4b52e4c483..93af0d4d8be 100644 --- a/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyIndexSignatureModifier; impl FormatRule for FormatTsAnyIndexSignatureModifier { type Context = JsFormatContext; - fn format( - node: &TsAnyIndexSignatureModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &TsAnyIndexSignatureModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyIndexSignatureModifier::JsStaticModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyIndexSignatureModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyIndexSignatureModifier::JsStaticModifier(node) => node.format().format(f), + TsAnyIndexSignatureModifier::TsReadonlyModifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs b/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs index d9103fe463d..895e7e07fc2 100644 --- a/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs @@ -5,23 +5,12 @@ use crate::prelude::*; use rome_js_syntax::TsAnyMethodSignatureModifier; impl FormatRule for FormatTsAnyMethodSignatureModifier { type Context = JsFormatContext; - fn format( - node: &TsAnyMethodSignatureModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &TsAnyMethodSignatureModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyMethodSignatureModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyMethodSignatureModifier::JsStaticModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyMethodSignatureModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyMethodSignatureModifier::TsAbstractModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyMethodSignatureModifier::TsAccessibilityModifier(node) => node.format().format(f), + TsAnyMethodSignatureModifier::JsStaticModifier(node) => node.format().format(f), + TsAnyMethodSignatureModifier::TsOverrideModifier(node) => node.format().format(f), + TsAnyMethodSignatureModifier::TsAbstractModifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/module_name.rs b/crates/rome_js_formatter/src/ts/any/module_name.rs index ecc2745c11d..c2d07cb954b 100644 --- a/crates/rome_js_formatter/src/ts/any/module_name.rs +++ b/crates/rome_js_formatter/src/ts/any/module_name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyModuleName; impl FormatRule for FormatTsAnyModuleName { type Context = JsFormatContext; - fn format(node: &TsAnyModuleName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsAnyModuleName, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyModuleName::TsIdentifierBinding(node) => formatted![formatter, [node.format()]], - TsAnyModuleName::TsQualifiedModuleName(node) => formatted![formatter, [node.format()]], + TsAnyModuleName::TsIdentifierBinding(node) => node.format().format(f), + TsAnyModuleName::TsQualifiedModuleName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/module_reference.rs b/crates/rome_js_formatter/src/ts/any/module_reference.rs index af4b13e4d4a..f7862488314 100644 --- a/crates/rome_js_formatter/src/ts/any/module_reference.rs +++ b/crates/rome_js_formatter/src/ts/any/module_reference.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyModuleReference; impl FormatRule for FormatTsAnyModuleReference { type Context = JsFormatContext; - fn format(node: &TsAnyModuleReference, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsAnyModuleReference, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyModuleReference::TsAnyName(node) => formatted![formatter, [node.format()]], - TsAnyModuleReference::TsExternalModuleReference(node) => { - formatted![formatter, [node.format()]] - } + TsAnyModuleReference::TsAnyName(node) => node.format().format(f), + TsAnyModuleReference::TsExternalModuleReference(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/name.rs b/crates/rome_js_formatter/src/ts/any/name.rs index 2df5789aa21..333dfed02e1 100644 --- a/crates/rome_js_formatter/src/ts/any/name.rs +++ b/crates/rome_js_formatter/src/ts/any/name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyName; impl FormatRule for FormatTsAnyName { type Context = JsFormatContext; - fn format(node: &TsAnyName, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsAnyName, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyName::JsReferenceIdentifier(node) => formatted![formatter, [node.format()]], - TsAnyName::TsQualifiedName(node) => formatted![formatter, [node.format()]], + TsAnyName::JsReferenceIdentifier(node) => node.format().format(f), + TsAnyName::TsQualifiedName(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_annotation.rs b/crates/rome_js_formatter/src/ts/any/property_annotation.rs index 79de7466082..830d72c1fc6 100644 --- a/crates/rome_js_formatter/src/ts/any/property_annotation.rs +++ b/crates/rome_js_formatter/src/ts/any/property_annotation.rs @@ -7,18 +7,12 @@ impl FormatRule for FormatTsAnyPropertyAnnotation { type Context = JsFormatContext; fn format( node: &TsAnyPropertyAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { - TsAnyPropertyAnnotation::TsTypeAnnotation(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyAnnotation::TsOptionalPropertyAnnotation(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyAnnotation::TsDefinitePropertyAnnotation(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertyAnnotation::TsTypeAnnotation(node) => node.format().format(f), + TsAnyPropertyAnnotation::TsOptionalPropertyAnnotation(node) => node.format().format(f), + TsAnyPropertyAnnotation::TsDefinitePropertyAnnotation(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs b/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs index d379ffabf58..86f5f4ce89a 100644 --- a/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs @@ -7,18 +7,14 @@ impl FormatRule for FormatTsAnyPropertyParameter type Context = JsFormatContext; fn format( node: &TsAnyPropertyParameterModifier, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { TsAnyPropertyParameterModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyParameterModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyParameterModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + TsAnyPropertyParameterModifier::TsReadonlyModifier(node) => node.format().format(f), + TsAnyPropertyParameterModifier::TsOverrideModifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs b/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs index 981d6dcf677..d7d452166f2 100644 --- a/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs +++ b/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs @@ -7,14 +7,12 @@ impl FormatRule for FormatTsAnyPropertySignatu type Context = JsFormatContext; fn format( node: &TsAnyPropertySignatureAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { - TsAnyPropertySignatureAnnotation::TsTypeAnnotation(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertySignatureAnnotation::TsTypeAnnotation(node) => node.format().format(f), TsAnyPropertySignatureAnnotation::TsOptionalPropertyAnnotation(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs b/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs index aa70743e6d0..6523a6fa260 100644 --- a/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs @@ -7,27 +7,17 @@ impl FormatRule for FormatTsAnyPropertySignature type Context = JsFormatContext; fn format( node: &TsAnyPropertySignatureModifier, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { - TsAnyPropertySignatureModifier::TsDeclareModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertySignatureModifier::TsDeclareModifier(node) => node.format().format(f), TsAnyPropertySignatureModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::JsStaticModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsAbstractModifier(node) => { - formatted![formatter, [node.format()]] + node.format().format(f) } + TsAnyPropertySignatureModifier::JsStaticModifier(node) => node.format().format(f), + TsAnyPropertySignatureModifier::TsReadonlyModifier(node) => node.format().format(f), + TsAnyPropertySignatureModifier::TsOverrideModifier(node) => node.format().format(f), + TsAnyPropertySignatureModifier::TsAbstractModifier(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/return_type.rs b/crates/rome_js_formatter/src/ts/any/return_type.rs index 013338d613a..94555c96d8a 100644 --- a/crates/rome_js_formatter/src/ts/any/return_type.rs +++ b/crates/rome_js_formatter/src/ts/any/return_type.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::TsAnyReturnType; impl FormatRule for FormatTsAnyReturnType { type Context = JsFormatContext; - fn format(node: &TsAnyReturnType, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsAnyReturnType, f: &mut Formatter) -> FormatResult<()> { match node { - TsAnyReturnType::TsType(node) => formatted![formatter, [node.format()]], - TsAnyReturnType::TsPredicateReturnType(node) => formatted![formatter, [node.format()]], - TsAnyReturnType::TsAssertsReturnType(node) => formatted![formatter, [node.format()]], + TsAnyReturnType::TsType(node) => node.format().format(f), + TsAnyReturnType::TsPredicateReturnType(node) => node.format().format(f), + TsAnyReturnType::TsAssertsReturnType(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/template_element.rs b/crates/rome_js_formatter/src/ts/any/template_element.rs index 14eae0e051e..a5724c3b183 100644 --- a/crates/rome_js_formatter/src/ts/any/template_element.rs +++ b/crates/rome_js_formatter/src/ts/any/template_element.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTemplateElement; impl FormatRule for FormatTsAnyTemplateElement { type Context = JsFormatContext; - fn format(node: &TsAnyTemplateElement, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsAnyTemplateElement, f: &mut Formatter) -> FormatResult<()> { match node { - TsAnyTemplateElement::TsTemplateChunkElement(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTemplateElement::TsTemplateElement(node) => formatted![formatter, [node.format()]], + TsAnyTemplateElement::TsTemplateChunkElement(node) => node.format().format(f), + TsAnyTemplateElement::TsTemplateElement(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/ts_type.rs b/crates/rome_js_formatter/src/ts/any/ts_type.rs index ca52e8c866b..670138e04f4 100644 --- a/crates/rome_js_formatter/src/ts/any/ts_type.rs +++ b/crates/rome_js_formatter/src/ts/any/ts_type.rs @@ -5,42 +5,42 @@ use crate::prelude::*; use rome_js_syntax::TsType; impl FormatRule for FormatTsType { type Context = JsFormatContext; - fn format(node: &TsType, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsType, f: &mut Formatter) -> FormatResult<()> { match node { - TsType::TsAnyType(node) => formatted![formatter, [node.format()]], - TsType::TsUnknownType(node) => formatted![formatter, [node.format()]], - TsType::TsNumberType(node) => formatted![formatter, [node.format()]], - TsType::TsBooleanType(node) => formatted![formatter, [node.format()]], - TsType::TsBigintType(node) => formatted![formatter, [node.format()]], - TsType::TsStringType(node) => formatted![formatter, [node.format()]], - TsType::TsSymbolType(node) => formatted![formatter, [node.format()]], - TsType::TsVoidType(node) => formatted![formatter, [node.format()]], - TsType::TsUndefinedType(node) => formatted![formatter, [node.format()]], - TsType::TsNeverType(node) => formatted![formatter, [node.format()]], - TsType::TsParenthesizedType(node) => formatted![formatter, [node.format()]], - TsType::TsReferenceType(node) => formatted![formatter, [node.format()]], - TsType::TsArrayType(node) => formatted![formatter, [node.format()]], - TsType::TsTupleType(node) => formatted![formatter, [node.format()]], - TsType::TsTypeofType(node) => formatted![formatter, [node.format()]], - TsType::TsImportType(node) => formatted![formatter, [node.format()]], - TsType::TsTypeOperatorType(node) => formatted![formatter, [node.format()]], - TsType::TsIndexedAccessType(node) => formatted![formatter, [node.format()]], - TsType::TsMappedType(node) => formatted![formatter, [node.format()]], - TsType::TsObjectType(node) => formatted![formatter, [node.format()]], - TsType::TsNonPrimitiveType(node) => formatted![formatter, [node.format()]], - TsType::TsThisType(node) => formatted![formatter, [node.format()]], - TsType::TsNumberLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsBigIntLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsStringLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsNullLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsBooleanLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsTemplateLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsInferType(node) => formatted![formatter, [node.format()]], - TsType::TsIntersectionType(node) => formatted![formatter, [node.format()]], - TsType::TsUnionType(node) => formatted![formatter, [node.format()]], - TsType::TsFunctionType(node) => formatted![formatter, [node.format()]], - TsType::TsConstructorType(node) => formatted![formatter, [node.format()]], - TsType::TsConditionalType(node) => formatted![formatter, [node.format()]], + TsType::TsAnyType(node) => node.format().format(f), + TsType::TsUnknownType(node) => node.format().format(f), + TsType::TsNumberType(node) => node.format().format(f), + TsType::TsBooleanType(node) => node.format().format(f), + TsType::TsBigintType(node) => node.format().format(f), + TsType::TsStringType(node) => node.format().format(f), + TsType::TsSymbolType(node) => node.format().format(f), + TsType::TsVoidType(node) => node.format().format(f), + TsType::TsUndefinedType(node) => node.format().format(f), + TsType::TsNeverType(node) => node.format().format(f), + TsType::TsParenthesizedType(node) => node.format().format(f), + TsType::TsReferenceType(node) => node.format().format(f), + TsType::TsArrayType(node) => node.format().format(f), + TsType::TsTupleType(node) => node.format().format(f), + TsType::TsTypeofType(node) => node.format().format(f), + TsType::TsImportType(node) => node.format().format(f), + TsType::TsTypeOperatorType(node) => node.format().format(f), + TsType::TsIndexedAccessType(node) => node.format().format(f), + TsType::TsMappedType(node) => node.format().format(f), + TsType::TsObjectType(node) => node.format().format(f), + TsType::TsNonPrimitiveType(node) => node.format().format(f), + TsType::TsThisType(node) => node.format().format(f), + TsType::TsNumberLiteralType(node) => node.format().format(f), + TsType::TsBigIntLiteralType(node) => node.format().format(f), + TsType::TsStringLiteralType(node) => node.format().format(f), + TsType::TsNullLiteralType(node) => node.format().format(f), + TsType::TsBooleanLiteralType(node) => node.format().format(f), + TsType::TsTemplateLiteralType(node) => node.format().format(f), + TsType::TsInferType(node) => node.format().format(f), + TsType::TsIntersectionType(node) => node.format().format(f), + TsType::TsUnionType(node) => node.format().format(f), + TsType::TsFunctionType(node) => node.format().format(f), + TsType::TsConstructorType(node) => node.format().format(f), + TsType::TsConditionalType(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs b/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs index c7107bd20c1..11d353a7285 100644 --- a/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs @@ -5,21 +5,12 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTupleTypeElement; impl FormatRule for FormatTsAnyTupleTypeElement { type Context = JsFormatContext; - fn format( - node: &TsAnyTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format(node: &TsAnyTupleTypeElement, f: &mut Formatter) -> FormatResult<()> { match node { - TsAnyTupleTypeElement::TsNamedTupleTypeElement(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTupleTypeElement::TsType(node) => formatted![formatter, [node.format()]], - TsAnyTupleTypeElement::TsRestTupleTypeElement(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTupleTypeElement::TsOptionalTupleTypeElement(node) => { - formatted![formatter, [node.format()]] - } + TsAnyTupleTypeElement::TsNamedTupleTypeElement(node) => node.format().format(f), + TsAnyTupleTypeElement::TsType(node) => node.format().format(f), + TsAnyTupleTypeElement::TsRestTupleTypeElement(node) => node.format().format(f), + TsAnyTupleTypeElement::TsOptionalTupleTypeElement(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/type_member.rs b/crates/rome_js_formatter/src/ts/any/type_member.rs index 1561dc87c58..ba8d8232aed 100644 --- a/crates/rome_js_formatter/src/ts/any/type_member.rs +++ b/crates/rome_js_formatter/src/ts/any/type_member.rs @@ -5,30 +5,16 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTypeMember; impl FormatRule for FormatTsAnyTypeMember { type Context = JsFormatContext; - fn format(node: &TsAnyTypeMember, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsAnyTypeMember, f: &mut Formatter) -> FormatResult<()> { match node { - TsAnyTypeMember::TsCallSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsPropertySignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsConstructSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsMethodSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsGetterSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsSetterSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsIndexSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::JsUnknownMember(node) => formatted![formatter, [node.format()]], + TsAnyTypeMember::TsCallSignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::TsPropertySignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::TsConstructSignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::TsMethodSignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::TsGetterSignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::TsSetterSignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::TsIndexSignatureTypeMember(node) => node.format().format(f), + TsAnyTypeMember::JsUnknownMember(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs b/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs index 0b7dc083233..c8326b779e0 100644 --- a/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs +++ b/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs @@ -7,15 +7,11 @@ impl FormatRule for FormatTsAnyTypePredicatePar type Context = JsFormatContext; fn format( node: &TsAnyTypePredicateParameterName, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { - TsAnyTypePredicateParameterName::JsReferenceIdentifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypePredicateParameterName::TsThisType(node) => { - formatted![formatter, [node.format()]] - } + TsAnyTypePredicateParameterName::JsReferenceIdentifier(node) => node.format().format(f), + TsAnyTypePredicateParameterName::TsThisType(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/variable_annotation.rs b/crates/rome_js_formatter/src/ts/any/variable_annotation.rs index a5224b5df19..964cad3faf5 100644 --- a/crates/rome_js_formatter/src/ts/any/variable_annotation.rs +++ b/crates/rome_js_formatter/src/ts/any/variable_annotation.rs @@ -7,15 +7,11 @@ impl FormatRule for FormatTsAnyVariableAnnotation { type Context = JsFormatContext; fn format( node: &TsAnyVariableAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut Formatter, + ) -> FormatResult<()> { match node { - TsAnyVariableAnnotation::TsTypeAnnotation(node) => { - formatted![formatter, [node.format()]] - } - TsAnyVariableAnnotation::TsDefiniteVariableAnnotation(node) => { - formatted![formatter, [node.format()]] - } + TsAnyVariableAnnotation::TsTypeAnnotation(node) => node.format().format(f), + TsAnyVariableAnnotation::TsDefiniteVariableAnnotation(node) => node.format().format(f), } } } diff --git a/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs b/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs index 46bf8055b77..dc5b12a231c 100644 --- a/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs +++ b/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsAsAssignment; use rome_js_syntax::TsAsAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAsAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsAsAssignment, f: &mut JsFormatter) -> FormatResult<()> { let TsAsAssignmentFields { assignment, as_token, ty, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ assignment.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs b/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs index 2ee989e9d42..45e2aa2420e 100644 --- a/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs +++ b/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs @@ -1,19 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsNonNullAssertionAssignment; use rome_js_syntax::TsNonNullAssertionAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNonNullAssertionAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNonNullAssertionAssignment, f: &mut JsFormatter) -> FormatResult<()> { let TsNonNullAssertionAssignmentFields { assignment, excl_token, } = node.as_fields(); - formatted![formatter, [assignment.format(), excl_token.format()]] + write![f, [assignment.format(), excl_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs b/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs index 13bd544fe63..6155f10ebb8 100644 --- a/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs +++ b/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsTypeAssertionAssignmentFields; use crate::FormatNodeFields; use rome_js_syntax::TsTypeAssertionAssignment; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeAssertionAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeAssertionAssignment, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAssertionAssignmentFields { l_angle_token, ty, @@ -16,17 +14,11 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsAbstractModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsAbstractModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsAbstractModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs index 8e2b1e70ffb..f695fbb9fef 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs @@ -1,10 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsAccessibilityModifier; use rome_js_syntax::TsAccessibilityModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsAccessibilityModifier, f: &JsFormatter) -> FormatResult<()> { + fn format_fields(node: &TsAccessibilityModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsAccessibilityModifierFields { modifier_token } = node.as_fields(); write![f, [modifier_token.format()]] diff --git a/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs b/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs index 9b454737336..dc89cd85066 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsAssertsCondition; use rome_js_syntax::TsAssertsConditionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAssertsCondition, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsAssertsCondition, f: &mut JsFormatter) -> FormatResult<()> { let TsAssertsConditionFields { is_token, ty } = node.as_fields(); - formatted![formatter, [is_token.format(), space_token(), ty.format()]] + write![f, [is_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs index 2bf2e646392..e9501f0c06e 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsCallSignatureTypeMember, TsCallSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsCallSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsCallSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsCallSignatureTypeMemberFields { type_parameters, parameters, @@ -15,16 +13,14 @@ impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &TsConstructSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsConstructSignatureTypeMemberFields { new_token, type_parameters, @@ -18,17 +20,15 @@ impl FormatNodeFields separator_token, } = node.as_fields(); - let separator_token = format_type_member_separator(separator_token, formatter); - - formatted![ - formatter, + write![ + f, [ new_token.format(), space_token(), type_parameters.format(), parameters.format(), type_annotation.format(), - separator_token, + FormatTypeMemberSeparator::new(separator_token.as_ref()), ] ] } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs index 3069febc6f9..25aa2f35647 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsDeclareModifier; use rome_js_syntax::TsDeclareModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDeclareModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsDeclareModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsDeclareModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs index 77364d4315c..0a2a2de7355 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsDefaultTypeClause, TsDefaultTypeClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDefaultTypeClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsDefaultTypeClause, f: &mut JsFormatter) -> FormatResult<()> { let TsDefaultTypeClauseFields { eq_token, ty } = node.as_fields(); - formatted![formatter, [eq_token.format(), space_token(), ty.format()]] + write![f, [eq_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs b/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs index 794bf55fe0c..732e87ad65d 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs @@ -1,19 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsDefinitePropertyAnnotation; use rome_js_syntax::TsDefinitePropertyAnnotationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDefinitePropertyAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsDefinitePropertyAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsDefinitePropertyAnnotationFields { excl_token, type_annotation, } = node.as_fields(); - formatted![formatter, [excl_token.format(), type_annotation.format()]] + + write![f, [excl_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs b/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs index 03bc7adc7a0..06dde689327 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsDefiniteVariableAnnotation; use rome_js_syntax::TsDefiniteVariableAnnotationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDefiniteVariableAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsDefiniteVariableAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsDefiniteVariableAnnotationFields { excl_token, type_annotation, } = node.as_fields(); - formatted![formatter, [excl_token.format(), type_annotation.format(),]] + write![f, [excl_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs b/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs index a13a86a9d7f..abecbc0f2e8 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsEmptyExternalModuleDeclarationBody; use rome_js_syntax::TsEmptyExternalModuleDeclarationBodyFields; @@ -8,9 +9,9 @@ impl FormatNodeFields { fn format_fields( node: &TsEmptyExternalModuleDeclarationBody, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsEmptyExternalModuleDeclarationBodyFields { semicolon_token } = node.as_fields(); - formatted![formatter, [semicolon_token.format()]] + write![f, [semicolon_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs index 356e00e0661..5bdf6e6269d 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs @@ -1,15 +1,19 @@ use crate::prelude::*; -use crate::utils::format_initializer_clause; +use crate::utils::FormatInitializerClause; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsEnumMember, TsEnumMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsEnumMember, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsEnumMember, f: &mut JsFormatter) -> FormatResult<()> { let TsEnumMemberFields { name, initializer } = node.as_fields(); - let name = name.format(); - let initializer = format_initializer_clause(formatter, initializer)?; - - formatted![formatter, [name, initializer]] + write!( + f, + [ + name.format(), + FormatInitializerClause::new(initializer.as_ref()) + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs b/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs index 131525d8ea4..4afaec8635b 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsExternalModuleReference; use rome_js_syntax::TsExternalModuleReferenceFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExternalModuleReference, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsExternalModuleReference, f: &mut JsFormatter) -> FormatResult<()> { let TsExternalModuleReferenceFields { require_token, l_paren_token, @@ -15,8 +13,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsGetterSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsGetterSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsGetterSignatureTypeMemberFields { get_token, name, @@ -17,10 +15,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsImplementsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsImplementsClause, f: &mut JsFormatter) -> FormatResult<()> { let TsImplementsClauseFields { implements_token, types, @@ -16,22 +14,20 @@ impl FormatNodeFields for FormatNodeRule let implements_token = implements_token.format().memoized(); let types = types.format().memoized(); - Ok(group_elements(formatted![ - formatter, - [ - if_group_breaks(block_indent(formatted![ - formatter, - [ - &implements_token, - space_token(), - soft_block_indent(formatted![formatter, [&types]]?) - ] - ]?)), - if_group_fits_on_single_line(formatted![ - formatter, - [&implements_token, space_token(), &types] - ]?), - ] - ]?)) + write!( + f, + [group_elements(&format_args![ + if_group_breaks(&block_indent(&format_args![ + &implements_token, + space_token(), + soft_block_indent(&types) + ])), + if_group_fits_on_single_line(&format_args![ + &implements_token, + space_token(), + &types + ]), + ])] + ) } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs index 6056883e55b..047c9b30bcd 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsIndexSignatureTypeMember, TsIndexSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsIndexSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexSignatureTypeMemberFields { readonly_token, l_brack_token, @@ -17,20 +15,17 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsMappedTypeAsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsMappedTypeAsClause, f: &mut JsFormatter) -> FormatResult<()> { let TsMappedTypeAsClauseFields { as_token, ty } = node.as_fields(); - formatted![ - formatter, - [ - as_token - .format() - .with(|as_token| { formatted![formatter, [as_token, space_token()]] }), - ty.format() - ] - ] + write![f, [as_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs index 01adae8c431..1c01cc4009c 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsMappedTypeOptionalModifierClause; use rome_js_syntax::TsMappedTypeOptionalModifierClauseFields; @@ -8,16 +9,13 @@ impl FormatNodeFields { fn format_fields( node: &TsMappedTypeOptionalModifierClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsMappedTypeOptionalModifierClauseFields { operator_token, question_mark_token, } = node.as_fields(); - formatted![ - formatter, - [operator_token.format(), question_mark_token.format()] - ] + write![f, [operator_token.format(), question_mark_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs index 87dcb6190d7..3139dd0d9cf 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsMappedTypeReadonlyModifierClause; use rome_js_syntax::TsMappedTypeReadonlyModifierClauseFields; @@ -8,15 +9,12 @@ impl FormatNodeFields { fn format_fields( node: &TsMappedTypeReadonlyModifierClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsMappedTypeReadonlyModifierClauseFields { operator_token, readonly_token, } = node.as_fields(); - formatted![ - formatter, - [operator_token.format(), readonly_token.format()] - ] + write![f, [operator_token.format(), readonly_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs index ab3f451bbf2..4f7db8eae47 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsMethodSignatureTypeMember, TsMethodSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsMethodSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsMethodSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsMethodSignatureTypeMemberFields { name, optional_token, @@ -17,16 +15,15 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields(node: &TsModuleBlock, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsModuleBlock, f: &mut JsFormatter) -> FormatResult<()> { let TsModuleBlockFields { l_curly_token, items, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [items.format()]]?, - &r_curly_token?, - ) - .block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &items.format(), &r_curly_token?,) + .block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs index 8922a80496e..29fcd5a2849 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsNamedTupleTypeElement, TsNamedTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNamedTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNamedTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { let TsNamedTupleTypeElementFields { ty, question_mark_token, @@ -14,8 +12,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsOptionalPropertyAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsOptionalPropertyAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsOptionalPropertyAnnotationFields { question_mark_token, type_annotation, } = node.as_fields(); - formatted![ - formatter, - [question_mark_token.format(), type_annotation.format()] - ] + write![f, [question_mark_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs index 204dd05dc29..c59cb14f354 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsOptionalTupleTypeElement, TsOptionalTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { diff --git a/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs index 4c6a2685620..5c8ab577a33 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsOverrideModifier; use rome_js_syntax::TsOverrideModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsOverrideModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsOverrideModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsOverrideModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs index b5c6d9f254c..1b198d6d97a 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs @@ -1,6 +1,7 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsPropertySignatureTypeMember, TsPropertySignatureTypeMemberFields}; impl FormatNodeFields @@ -8,8 +9,8 @@ impl FormatNodeFields { fn format_fields( node: &TsPropertySignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsPropertySignatureTypeMemberFields { readonly_token, name, @@ -18,17 +19,15 @@ impl FormatNodeFields separator_token, } = node.as_fields(); - let separator = format_type_member_separator(separator_token, formatter); - - formatted![ - formatter, + write![ + f, [ readonly_token.format(), space_token(), name.format(), optional_token.format(), type_annotation.format(), - separator + FormatTypeMemberSeparator::new(separator_token.as_ref()) ] ] } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs b/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs index f9998f1be14..010eac5e8c8 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs @@ -1,22 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsQualifiedModuleName; use rome_js_syntax::TsQualifiedModuleNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsQualifiedModuleName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsQualifiedModuleName, f: &mut JsFormatter) -> FormatResult<()> { let TsQualifiedModuleNameFields { left, dot_token, right, } = node.as_fields(); - formatted![ - formatter, - [left.format(), dot_token.format(), right.format(),] - ] + write![f, [left.format(), dot_token.format(), right.format(),]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs b/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs index 809a8c53d3e..5afabd26be6 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs @@ -1,22 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsQualifiedName; use rome_js_syntax::TsQualifiedNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsQualifiedName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsQualifiedName, f: &mut JsFormatter) -> FormatResult<()> { let TsQualifiedNameFields { left, dot_token, right, } = node.as_fields(); - formatted![ - formatter, - [left.format(), dot_token.format(), right.format(),] - ] + write![f, [left.format(), dot_token.format(), right.format(),]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs index f081ed8d2b3..1813dd61893 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsReadonlyModifier; use rome_js_syntax::TsReadonlyModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsReadonlyModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsReadonlyModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsReadonlyModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs index b10a0f10861..045f78c69ed 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs @@ -1,18 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsRestTupleTypeElement, TsRestTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsRestTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsRestTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { let TsRestTupleTypeElementFields { dotdotdot_token, ty, } = node.as_fields(); let dotdotdot = dotdotdot_token.format(); let ty = ty.format(); - formatted![formatter, [dotdotdot, ty]] + write![f, [dotdotdot, ty]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs b/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs index cd385758849..252f4be3a0c 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs @@ -1,17 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsReturnTypeAnnotation; use rome_js_syntax::TsReturnTypeAnnotationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsReturnTypeAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsReturnTypeAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsReturnTypeAnnotationFields { colon_token, ty } = node.as_fields(); - formatted![ - formatter, - [colon_token.format(), space_token(), ty.format()] - ] + write![f, [colon_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs index 63a814b91b0..e154d6647c5 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsSetterSignatureTypeMember, TsSetterSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsSetterSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsSetterSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsSetterSignatureTypeMemberFields { set_token, name, @@ -17,23 +15,16 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsTypeAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAnnotationFields { colon_token, ty } = node.as_fields(); let colon = colon_token.format(); let ty = ty.format(); - formatted![formatter, [colon, space_token(), ty]] + write![f, [colon, space_token(), ty]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs index 4a7f7678d27..17dc98740d7 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsTypeConstraintClause, TsTypeConstraintClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeConstraintClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeConstraintClause, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeConstraintClauseFields { extends_token, ty } = node.as_fields(); let extends = extends_token.format(); let ty = ty.format(); - formatted![formatter, [extends, space_token(), ty]] + write![f, [extends, space_token(), ty]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs b/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs index fd1cb180e73..6355f3b4858 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsTypeParameterName, TsTypeParameterNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeParameterName, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeParameterName, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeParameterNameFields { ident_token } = node.as_fields(); - formatted![formatter, [ident_token.format()]] + write![f, [ident_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs b/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs index 8ef58034ca6..2e25d672c19 100644 --- a/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs +++ b/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsIdentifierBinding, TsIdentifierBindingFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIdentifierBinding, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsIdentifierBinding, f: &mut JsFormatter) -> FormatResult<()> { let TsIdentifierBindingFields { name_token } = node.as_fields(); - formatted![formatter, [name_token.format()]] + write![f, [name_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs b/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs index bcd65f25f09..c518f3029ea 100644 --- a/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs +++ b/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsIndexSignatureParameter, TsIndexSignatureParameterFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexSignatureParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsIndexSignatureParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexSignatureParameterFields { binding, type_annotation, @@ -14,6 +12,6 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsPropertyParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsPropertyParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsPropertyParameterFields { modifiers, formal_parameter, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [modifiers.format(), space_token(), formal_parameter.format()] ] } diff --git a/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs b/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs index 2a05e21a7aa..cdbd9f98d24 100644 --- a/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs +++ b/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsThisParameter, TsThisParameterFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsThisParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsThisParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsThisParameterFields { this_token, type_annotation, } = node.as_fields(); - formatted![formatter, [this_token.format(), type_annotation.format()]] + write![f, [this_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs b/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs index 1a850cb092d..caa13381808 100644 --- a/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs +++ b/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs @@ -1,29 +1,26 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsTypeParameter, TsTypeParameterFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeParameterFields { name, constraint, default, } = node.as_fields(); - formatted![ - formatter, - [ - name.format(), - constraint - .format() - .with_or_empty(|constraint| formatted![formatter, [space_token(), constraint]]), - default - .format() - .with_or_empty(|default| formatted![formatter, [space_token(), default]]) - ] - ] + write!(f, [name.format()])?; + + if let Some(constraint) = constraint { + write!(f, [space_token(), constraint.format()])?; + } + + if let Some(default) = default { + write!(f, [space_token(), default.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs b/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs index d1e6512e6e8..c78f3790578 100644 --- a/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs +++ b/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs @@ -1,25 +1,22 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsTypeParameters, TsTypeParametersFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeParameters, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeParameters, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeParametersFields { items, r_angle_token, l_angle_token, } = node.as_fields(); - formatter - .delimited( - &l_angle_token?, - formatted![formatter, [items.format()]]?, - &r_angle_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_angle_token?, &items.format(), &r_angle_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs index 844814b770b..3616047df2b 100644 --- a/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs @@ -1,6 +1,7 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsConstructorSignatureClassMember; use rome_js_syntax::TsConstructorSignatureClassMemberFields; @@ -9,8 +10,8 @@ impl FormatNodeFields { fn format_fields( node: &TsConstructorSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsConstructorSignatureClassMemberFields { modifiers, name, @@ -18,18 +19,17 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), name.format(), parameters.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/extends_clause.rs b/crates/rome_js_formatter/src/ts/classes/extends_clause.rs index 6dda4b34f65..c6b866da05f 100644 --- a/crates/rome_js_formatter/src/ts/classes/extends_clause.rs +++ b/crates/rome_js_formatter/src/ts/classes/extends_clause.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsExtendsClause, TsExtendsClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExtendsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsExtendsClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExtendsClauseFields { extends_token, types, @@ -15,22 +13,16 @@ impl FormatNodeFields for FormatNodeRule { let extends_token = extends_token.format().memoized(); let types = types.format().memoized(); - Ok(group_elements(formatted![ - formatter, - [ - if_group_breaks(block_indent(formatted![ - formatter, - [ - &extends_token, - space_token(), - soft_block_indent(formatted![formatter, [&types]]?) - ] - ]?)), - if_group_fits_on_single_line(formatted![ - formatter, - [&extends_token, space_token(), &types] - ]?), - ] - ]?)) + write!( + f, + [group_elements(&format_args!( + if_group_breaks(&block_indent(&format_args![ + &extends_token, + space_token(), + soft_block_indent(&types) + ])), + if_group_fits_on_single_line(&format_args![&extends_token, space_token(), &types]), + ))] + ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs index fa8686c6c7f..ddffefa4b37 100644 --- a/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs @@ -1,15 +1,14 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; + +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::{TsGetterSignatureClassMember, TsGetterSignatureClassMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsGetterSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsGetterSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsGetterSignatureClassMemberFields { modifiers, get_token, @@ -20,11 +19,10 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), get_token.format(), @@ -33,9 +31,9 @@ impl FormatNodeFields l_paren_token.format(), r_paren_token.format(), return_type.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs index e09dfc6ed56..65461a01a88 100644 --- a/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs @@ -1,14 +1,12 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsIndexSignatureClassMember; use rome_js_syntax::TsIndexSignatureClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsIndexSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexSignatureClassMemberFields { modifiers, l_brack_token, @@ -18,20 +16,19 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsMethodSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsMethodSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsMethodSignatureClassMemberFields { modifiers, async_token, @@ -21,24 +19,23 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), async_token .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), + .with_or_empty(|token, f| write![f, [token, space_token()]]), space_token(), name.format(), question_mark_token.format(), type_parameters.format(), parameters.format(), return_type_annotation.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs index c87f1b41f2c..bfe13fee821 100644 --- a/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs @@ -1,5 +1,7 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; + +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::{TsPropertySignatureClassMember, TsPropertySignatureClassMemberFields}; @@ -8,8 +10,8 @@ impl FormatNodeFields { fn format_fields( node: &TsPropertySignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsPropertySignatureClassMemberFields { modifiers, name, @@ -17,18 +19,17 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), name.format(), property_annotation.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs index f40351ff9f3..a6b3ca93641 100644 --- a/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsSetterSignatureClassMember, TsSetterSignatureClassMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsSetterSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsSetterSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsSetterSignatureClassMemberFields { modifiers, set_token, @@ -20,28 +18,25 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - let set_token = set_token.format(); - let name = name.format(); - let l_paren_token = l_paren_token.format(); - let parameters = parameter.format(); - let r_paren_token = r_paren_token.format(); - - format_with_semicolon( - formatter, - formatted![ - formatter, + let setter = format_with(|f| { + write!( + f, [ modifiers.format(), space_token(), - set_token, + set_token.format(), space_token(), - name, - l_paren_token, - parameters, - r_paren_token, + name.format(), + l_paren_token.format(), + parameter.format(), + r_paren_token.format(), ] - ]?, - semicolon_token, + ) + }); + + write!( + f, + [FormatWithSemicolon::new(&setter, semicolon_token.as_ref())] ) } } diff --git a/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs index 72855f8aec1..94290709e0c 100644 --- a/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs @@ -1,16 +1,14 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsDeclareFunctionDeclaration; use rome_js_syntax::TsDeclareFunctionDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDeclareFunctionDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsDeclareFunctionDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsDeclareFunctionDeclarationFields { async_token, function_token, @@ -21,15 +19,14 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, + let declaration = format_with(|f| { + if let Some(async_token) = &async_token { + write!(f, [async_token.format(), space_token()])?; + } + + write!( + f, [ - async_token.format().with_or_empty(|async_token| formatted![ - formatter, - [async_token, space_token()] - ]), function_token.format(), space_token(), id.format(), @@ -37,8 +34,15 @@ impl FormatNodeFields parameters.format(), return_type_annotation.format(), ] - ]?, - semicolon_token, + ) + }); + + write!( + f, + [FormatWithSemicolon::new( + &declaration, + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs index ee6f4071d00..5e4f1bd611b 100644 --- a/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs @@ -1,14 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; + +use crate::formatter::FormatSeparatedExtension; use crate::utils::has_leading_newline; use crate::FormatNodeFields; use rome_js_syntax::{TsEnumDeclaration, TsEnumDeclarationFields}; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsEnumDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsEnumDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsEnumDeclarationFields { const_token, enum_token, @@ -18,37 +18,36 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - let has_newline = has_leading_newline(members.syntax()); - let list = formatter - .delimited( - &l_curly_token?, - join_elements( - if has_newline { - hard_line_break() - } else { - soft_line_break_or_space() - }, - formatter.format_separated(&members, || token(","))?, - ), - &r_curly_token?, - ) - .soft_block_spaces() - .finish()?; + if let Some(const_token) = const_token { + write!(f, [const_token.format(), space_token()])?; + } - formatted![ - formatter, + write!( + f, [ - const_token.format().with_or_empty(|const_token| formatted![ - formatter, - [const_token, space_token()] - ]), - enum_token - .format() - .with(|enum_token| formatted![formatter, [enum_token, space_token()]]), - id.format() - .with(|id| formatted![formatter, [id, space_token()]]), - list + enum_token.format(), + space_token(), + id.format(), + space_token() ] - ] + )?; + + let has_newline = has_leading_newline(members.syntax()); + + let members = format_with(|f| { + f.join_with(&if has_newline { + hard_line_break() + } else { + soft_line_break_or_space() + }) + .entries(members.format_separated(token(","))) + .finish() + }); + + write!( + f, + [f.delimited(&l_curly_token?, &members, &r_curly_token?,) + .soft_block_spaces()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs index 3774679182d..c6f3a3762ad 100644 --- a/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs @@ -1,21 +1,20 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::TsExternalModuleDeclaration; use rome_js_syntax::TsExternalModuleDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExternalModuleDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsExternalModuleDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsExternalModuleDeclarationFields { body, module_token, source, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ module_token.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs index 4f980e3e97d..853ed038a2d 100644 --- a/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs @@ -1,18 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::TsGlobalDeclaration; use rome_js_syntax::TsGlobalDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsGlobalDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsGlobalDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsGlobalDeclarationFields { global_token, body } = node.as_fields(); - formatted![ - formatter, - [global_token.format(), space_token(), body.format()] - ] + write![f, [global_token.format(), space_token(), body.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs index d012518cdbf..80d9ea7b5f1 100644 --- a/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs @@ -1,14 +1,12 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsImportEqualsDeclaration; use rome_js_syntax::TsImportEqualsDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsImportEqualsDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsImportEqualsDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsImportEqualsDeclarationFields { import_token, type_token, @@ -18,24 +16,23 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsInterfaceDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsInterfaceDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsInterfaceDeclarationFields { interface_token, id, @@ -17,27 +16,27 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsModuleDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsModuleDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsModuleDeclarationFields { module_or_namespace, name, body, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ module_or_namespace.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs index 6755e425aa3..8beb7278433 100644 --- a/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsTypeAliasDeclaration, TsTypeAliasDeclarationFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeAliasDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeAliasDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAliasDeclarationFields { type_token, binding_identifier, @@ -17,11 +15,10 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsAsExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsAsExpression, f: &mut JsFormatter) -> FormatResult<()> { let TsAsExpressionFields { ty, as_token, expression, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ expression.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs b/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs index b7f4cfcaa38..46465b2e885 100644 --- a/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs +++ b/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNameWithTypeArguments, TsNameWithTypeArgumentsFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNameWithTypeArguments, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNameWithTypeArguments, f: &mut JsFormatter) -> FormatResult<()> { let TsNameWithTypeArgumentsFields { name, type_arguments, } = node.as_fields(); - formatted![formatter, [name.format(), type_arguments.format()]] + write![f, [name.format(), type_arguments.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs b/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs index 90a541ec0d4..2fbd0bcf967 100644 --- a/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs +++ b/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsNonNullAssertionExpression; use rome_js_syntax::TsNonNullAssertionExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNonNullAssertionExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNonNullAssertionExpression, f: &mut JsFormatter) -> FormatResult<()> { let TsNonNullAssertionExpressionFields { expression, excl_token, } = node.as_fields(); - formatted![formatter, [expression.format(), excl_token.format()]] + write![f, [expression.format(), excl_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs b/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs index 54595a54a03..5dd935ee72b 100644 --- a/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs +++ b/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs @@ -6,8 +6,8 @@ use rome_js_syntax::{TsTemplateChunkElement, TsTemplateChunkElementFields}; impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &TsTemplateChunkElement, - formatter: &JsFormatter, - ) -> FormatResult { + formatter: &mut JsFormatter, + ) -> FormatResult<()> { let TsTemplateChunkElementFields { template_chunk_token, } = node.as_fields(); diff --git a/crates/rome_js_formatter/src/ts/expressions/template_element.rs b/crates/rome_js_formatter/src/ts/expressions/template_element.rs index efef8dec4da..19e5c30fdd6 100644 --- a/crates/rome_js_formatter/src/ts/expressions/template_element.rs +++ b/crates/rome_js_formatter/src/ts/expressions/template_element.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::TsTemplateElement; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTemplateElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTemplateElement, formatter: &mut JsFormatter) -> FormatResult<()> { format_template_literal(TemplateElement::Ts(node.clone()), formatter) } } diff --git a/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs b/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs index b7a20aa71d4..a7809944c9f 100644 --- a/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsTemplateLiteralType; use rome_js_syntax::TsTemplateLiteralTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTemplateLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTemplateLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsTemplateLiteralTypeFields { l_tick_token, elements, r_tick_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_tick_token.format(), elements.format(), diff --git a/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs b/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs index 73d84f677e1..fc311dc6152 100644 --- a/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs +++ b/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs @@ -1,25 +1,24 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeArguments, TsTypeArgumentsFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeArguments, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeArguments, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeArgumentsFields { l_angle_token, ts_type_argument_list, r_angle_token, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [f.delimited( &l_angle_token?, - formatted![formatter, [ts_type_argument_list.format()]]?, + &ts_type_argument_list.format(), &r_angle_token?, ) - .soft_block_indent() - .finish() + .soft_block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs b/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs index d2fb1611b64..97bb5f58ec9 100644 --- a/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs +++ b/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsTypeAssertionExpression; use rome_js_syntax::TsTypeAssertionExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeAssertionExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeAssertionExpression, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAssertionExpressionFields { l_angle_token, ty, @@ -15,17 +13,11 @@ impl FormatNodeFields for FormatNodeRule for FormatTsEnumMemberList { type Context = JsFormatContext; - fn format(node: &TsEnumMemberList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &TsEnumMemberList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs index 9e6fabfe346..737fd09f120 100644 --- a/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs @@ -1,18 +1,15 @@ use crate::generated::FormatTsIndexSignatureModifierList; use crate::prelude::*; use crate::utils::sort_modifiers_by_precedence; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsIndexSignatureModifierList; impl FormatRule for FormatTsIndexSignatureModifierList { type Context = JsFormatContext; - fn format( - node: &TsIndexSignatureModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn format(node: &TsIndexSignatureModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs b/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs index bcd97b66514..6509ecf23d6 100644 --- a/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs @@ -1,48 +1,24 @@ use crate::generated::FormatTsIntersectionTypeElementList; use crate::prelude::*; +use crate::ts::lists::union_type_variant_list::FormatTypeVariant; use rome_js_syntax::TsIntersectionTypeElementList; use rome_rowan::AstSeparatedList; impl FormatRule for FormatTsIntersectionTypeElementList { type Context = JsFormatContext; - fn format( - node: &TsIntersectionTypeElementList, - formatter: &JsFormatter, - ) -> FormatResult { - let mut elements = Vec::with_capacity(node.len()); + fn format(node: &TsIntersectionTypeElementList, f: &mut JsFormatter) -> FormatResult<()> { let last_index = node.len().saturating_sub(1); - for (index, item) in node.elements().enumerate() { - let ty = formatted![formatter, [item.node().format()]]?; - let separator = item.trailing_separator()?; - - let separator = match separator { - Some(token) => { - if index == last_index { - formatter.format_replaced(token, empty_element()) - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token.format(), space_token()] - ]? - } - } - None => { - if index == last_index { - empty_element() - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token("&"), space_token()] - ]? - } - } - }; - - elements.push(format_elements![group_elements(ty), separator]); - } - - Ok(concat_elements(elements)) + f.join() + .entries( + node.elements() + .enumerate() + .map(|(index, item)| FormatTypeVariant { + last: index == last_index, + element: item, + }), + ) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs index cf0c6084eec..017c8312d8c 100644 --- a/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::TsMethodSignatureModifierList; impl FormatRule for FormatTsMethodSignatureModifierList { type Context = JsFormatContext; - fn format( - node: &TsMethodSignatureModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn format(node: &TsMethodSignatureModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs index 93931f07f21..d788db7e7c5 100644 --- a/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::TsPropertyParameterModifierList; impl FormatRule for FormatTsPropertyParameterModifierList { type Context = JsFormatContext; - fn format( - node: &TsPropertyParameterModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn format(node: &TsPropertyParameterModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs index b3323a5a977..2bacd46a4bc 100644 --- a/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::TsPropertySignatureModifierList; impl FormatRule for FormatTsPropertySignatureModifierList { type Context = JsFormatContext; - fn format( - node: &TsPropertySignatureModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn format(node: &TsPropertySignatureModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/template_element_list.rs b/crates/rome_js_formatter/src/ts/lists/template_element_list.rs index a70379e72e3..3a1743754ad 100644 --- a/crates/rome_js_formatter/src/ts/lists/template_element_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/template_element_list.rs @@ -6,14 +6,13 @@ use rome_rowan::AstNodeList; impl FormatRule for FormatTsTemplateElementList { type Context = JsFormatContext; - fn format( - node: &TsTemplateElementList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(concat_elements( - formatter - .format_all(node.iter().formatted())? - .map(group_elements), - )) + fn format(node: &TsTemplateElementList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join(); + + for item in node { + join.entry(&group_elements(&item.format())); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs b/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs index 69e4d29dd59..741b2f7919c 100644 --- a/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs @@ -1,3 +1,4 @@ +use crate::formatter::FormatSeparatedExtension; use crate::generated::FormatTsTupleTypeElementList; use crate::prelude::*; use rome_js_syntax::TsTupleTypeElementList; @@ -5,13 +6,9 @@ use rome_js_syntax::TsTupleTypeElementList; impl FormatRule for FormatTsTupleTypeElementList { type Context = JsFormatContext; - fn format( - node: &TsTupleTypeElementList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn format(node: &TsTupleTypeElementList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs b/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs index 045effad023..a46435e2da5 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs @@ -1,4 +1,4 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatTsTypeArgumentList; use crate::prelude::*; use rome_js_syntax::TsTypeArgumentList; @@ -6,15 +6,15 @@ use rome_js_syntax::TsTypeArgumentList; impl FormatRule for FormatTsTypeArgumentList { type Context = JsFormatContext; - fn format(node: &TsTypeArgumentList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Disallowed), - )?, - )) + fn format(node: &TsTypeArgumentList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries( + node.format_separated_with_options( + token(","), + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Disallowed), + ), + ) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_list.rs b/crates/rome_js_formatter/src/ts/lists/type_list.rs index abb5903906a..f7287fd7de2 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_list.rs @@ -1,4 +1,4 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatTsTypeList; use crate::prelude::*; use rome_js_syntax::TsTypeList; @@ -6,16 +6,16 @@ use rome_js_syntax::TsTypeList; impl FormatRule for FormatTsTypeList { type Context = JsFormatContext; - fn format(node: &TsTypeList, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsTypeList, f: &mut JsFormatter) -> FormatResult<()> { // the grouping will be applied by the parent - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Disallowed), - )?, - )) + f.join_with(&soft_line_break_or_space()) + .entries( + node.format_separated_with_options( + token(","), + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Disallowed), + ), + ) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_member_list.rs b/crates/rome_js_formatter/src/ts/lists/type_member_list.rs index 9fc6d21509c..dec35871142 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_member_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_member_list.rs @@ -1,44 +1,62 @@ use crate::generated::FormatTsTypeMemberList; use crate::prelude::*; -use rome_js_syntax::TsTypeMemberList; +use rome_formatter::{write, Buffer, VecBuffer}; +use rome_js_syntax::{TsAnyTypeMember, TsTypeMemberList}; +use rome_rowan::support::elements; use rome_rowan::AstNodeList; impl FormatRule for FormatTsTypeMemberList { type Context = JsFormatContext; - fn format(node: &TsTypeMemberList, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsTypeMemberList, f: &mut JsFormatter) -> FormatResult<()> { let items = node.iter(); let last_index = items.len().saturating_sub(1); - let items = items - .enumerate() - .map(|(index, element)| { - let formatted_element = formatted![formatter, [element.format()]]?; - - let is_verbatim = matches!( - formatted_element.last_element(), - Some(FormatElement::Verbatim(_)) - ); - - let separator = if !is_verbatim { - // Children don't format the separator on purpose, so it's up to the parent - this node, - // to decide to print their separator - if index == last_index { - if_group_breaks(token(";")) - } else { - token(";") - } - } else { - empty_element() - }; - - Ok(format_elements![ - group_elements(formatted_element), - separator - ]) - }) - .collect::>>()?; - - Ok(join_elements(soft_line_break_or_space(), items)) + f.join_with(&soft_line_break_or_space()) + .entries(items.enumerate().map(|(index, member)| TsTypeMemberItem { + last: index == last_index, + member, + })) + .finish() + } +} + +struct TsTypeMemberItem { + last: bool, + member: TsAnyTypeMember, +} + +impl Format for TsTypeMemberItem { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.member.format()])?; + + let formatted_element = buffer.into_document().into_element(); + + let is_verbatim = matches!( + formatted_element.last_element(), + Some(FormatElement::Verbatim(_)) + ); + + write!( + f, + [group_elements(&format_once(|f| { + f.write_element(formatted_element); + Ok(()) + }))] + )?; + + if !is_verbatim { + // Children don't format the separator on purpose, so it's up to the parent - this node, + // to decide to print their separator + if self.last { + write!(f, [if_group_breaks(&token(";"))])?; + } else { + write!(f, [token(";")])?; + } + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs b/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs index faca23cf2e0..c639a661b2a 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs @@ -1,4 +1,4 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; +use crate::formatter::{FormatSeparatedExtension, FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatTsTypeParameterList; use crate::prelude::*; use rome_js_syntax::TsTypeParameterList; @@ -7,7 +7,7 @@ use rome_rowan::AstSeparatedList; impl FormatRule for FormatTsTypeParameterList { type Context = JsFormatContext; - fn format(node: &TsTypeParameterList, formatter: &JsFormatter) -> FormatResult { + fn format(node: &TsTypeParameterList, f: &mut JsFormatter) -> FormatResult<()> { // nodes and formatter are not aware of the source type (TSX vs TS), which means we can't // exactly pin point the exact case. // @@ -19,13 +19,12 @@ impl FormatRule for FormatTsTypeParameterList { } else { TrailingSeparator::default() }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated_with_options( + token(","), FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs b/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs index ff0f4a3b956..0132a1cac07 100644 --- a/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs @@ -1,48 +1,57 @@ use crate::generated::FormatTsUnionTypeVariantList; use crate::prelude::*; -use rome_js_syntax::TsUnionTypeVariantList; -use rome_rowan::AstSeparatedList; +use rome_formatter::write; +use rome_js_syntax::{JsLanguage, TsType, TsUnionTypeVariantList}; +use rome_rowan::{AstSeparatedElement, AstSeparatedList}; impl FormatRule for FormatTsUnionTypeVariantList { type Context = JsFormatContext; - fn format( - node: &TsUnionTypeVariantList, - formatter: &JsFormatter, - ) -> FormatResult { - let mut elements = Vec::with_capacity(node.len()); + fn format(node: &TsUnionTypeVariantList, f: &mut JsFormatter) -> FormatResult<()> { let last_index = node.len().saturating_sub(1); - for (index, item) in node.elements().enumerate() { - let ty = formatted![formatter, [item.node().format()]]?; - let separator = item.trailing_separator()?; - - let separator = match separator { - Some(token) => { - if index == last_index { - formatter.format_replaced(token, empty_element()) - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token.format(), space_token()] - ]? - } + f.join() + .entries( + node.elements() + .enumerate() + .map(|(index, item)| FormatTypeVariant { + last: index == last_index, + element: item, + }), + ) + .finish() + } +} + +pub struct FormatTypeVariant { + pub last: bool, + pub element: AstSeparatedElement, +} + +impl Format for FormatTypeVariant { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + write!(f, [group_elements(&self.element.node().format())])?; + + let separator = self.element.trailing_separator()?; + + match separator { + Some(token) => { + if self.last { + write!(f, [f.format_replaced(token, &empty_element())])?; + } else { + write![ + f, + [soft_line_break_or_space(), token.format(), space_token()] + ]?; } - None => { - if index == last_index { - empty_element() - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token("|"), space_token()] - ]? - } + } + None => { + if !self.last { + write![f, [soft_line_break_or_space(), token("|"), space_token()]]?; } - }; - - elements.push(format_elements![group_elements(ty), separator]); + } } - Ok(concat_elements(elements)) + Ok(()) } } diff --git a/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs b/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs index 1ce3cf7dbcf..735e4408eaa 100644 --- a/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs +++ b/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs @@ -1,14 +1,12 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsExportAsNamespaceClause; use rome_js_syntax::TsExportAsNamespaceClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExportAsNamespaceClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsExportAsNamespaceClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExportAsNamespaceClauseFields { as_token, namespace_token, @@ -16,19 +14,18 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsExportAssignmentClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsExportAssignmentClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExportAssignmentClauseFields { eq_token, expression, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [eq_token.format(), space_token(), expression.format(),] - ]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(eq_token.format(), space_token(), expression.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs b/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs index 0fbab86effa..846db764496 100644 --- a/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs +++ b/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsExportDeclareClause; use rome_js_syntax::TsExportDeclareClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExportDeclareClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsExportDeclareClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExportDeclareClauseFields { declare_token, declaration, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [declare_token.format(), space_token(), declaration.format(),] ] } diff --git a/crates/rome_js_formatter/src/ts/module/import_type.rs b/crates/rome_js_formatter/src/ts/module/import_type.rs index cd99f1f5d86..a16f37d1769 100644 --- a/crates/rome_js_formatter/src/ts/module/import_type.rs +++ b/crates/rome_js_formatter/src/ts/module/import_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::utils::FormatLiteralStringToken; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsImportType; use rome_js_syntax::TsImportTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsImportType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsImportType, f: &mut JsFormatter) -> FormatResult<()> { let TsImportTypeFields { typeof_token, import_token, @@ -16,12 +17,13 @@ impl FormatNodeFields for FormatNodeRule { type_arguments, } = node.as_fields(); - formatted![ - formatter, + if let Some(typeof_token) = typeof_token { + write!(f, [typeof_token.format(), space_token()])?; + } + + write![ + f, [ - typeof_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), import_token.format(), l_paren_token.format(), FormatLiteralStringToken::from_string(&argument_token?), diff --git a/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs b/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs index 74d8ba22320..98a56ad9b79 100644 --- a/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs +++ b/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs @@ -1,15 +1,13 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsImportTypeQualifier; use rome_js_syntax::TsImportTypeQualifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsImportTypeQualifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsImportTypeQualifier, f: &mut JsFormatter) -> FormatResult<()> { let TsImportTypeQualifierFields { dot_token, right } = node.as_fields(); - formatted![formatter, [dot_token.format(), right.format(),]] + write![f, [dot_token.format(), right.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/statements/declare_statement.rs b/crates/rome_js_formatter/src/ts/statements/declare_statement.rs index 0f3301881ed..9b1a061d41f 100644 --- a/crates/rome_js_formatter/src/ts/statements/declare_statement.rs +++ b/crates/rome_js_formatter/src/ts/statements/declare_statement.rs @@ -1,19 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsDeclareStatement; use rome_js_syntax::TsDeclareStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDeclareStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsDeclareStatement, f: &mut JsFormatter) -> FormatResult<()> { let TsDeclareStatementFields { declaration, declare_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [declare_token.format(), space_token(), declaration.format()] ] } diff --git a/crates/rome_js_formatter/src/ts/types/any_type.rs b/crates/rome_js_formatter/src/ts/types/any_type.rs index df62af9fc13..4c54b3ec4a9 100644 --- a/crates/rome_js_formatter/src/ts/types/any_type.rs +++ b/crates/rome_js_formatter/src/ts/types/any_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsAnyType, TsAnyTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsAnyType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsAnyType, f: &mut JsFormatter) -> FormatResult<()> { let TsAnyTypeFields { any_token } = node.as_fields(); - formatted![formatter, [any_token.format()]] + write![f, [any_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/array_type.rs b/crates/rome_js_formatter/src/ts/types/array_type.rs index a9eaa0f056a..ef50873de40 100644 --- a/crates/rome_js_formatter/src/ts/types/array_type.rs +++ b/crates/rome_js_formatter/src/ts/types/array_type.rs @@ -1,16 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsArrayType, TsArrayTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsArrayType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsArrayType, f: &mut JsFormatter) -> FormatResult<()> { let TsArrayTypeFields { l_brack_token, element_type, r_brack_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ element_type.format(), l_brack_token.format(), diff --git a/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs b/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs index 1ec738d56e7..bc2d7adef1a 100644 --- a/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs +++ b/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsAssertsReturnType; use rome_js_syntax::TsAssertsReturnTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAssertsReturnType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsAssertsReturnType, f: &mut JsFormatter) -> FormatResult<()> { let TsAssertsReturnTypeFields { parameter_name, asserts_token, predicate, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ asserts_token.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs b/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs index 089defb8f66..e33eb7a0252 100644 --- a/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBigIntLiteralType, TsBigIntLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsBigIntLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsBigIntLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsBigIntLiteralTypeFields { minus_token, literal_token, } = node.as_fields(); - formatted![formatter, [minus_token.format(), literal_token.format()]] + write![f, [minus_token.format(), literal_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/bigint_type.rs b/crates/rome_js_formatter/src/ts/types/bigint_type.rs index e9814f8b5d3..4b8b3488433 100644 --- a/crates/rome_js_formatter/src/ts/types/bigint_type.rs +++ b/crates/rome_js_formatter/src/ts/types/bigint_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBigintType, TsBigintTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsBigintType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsBigintType, f: &mut JsFormatter) -> FormatResult<()> { let TsBigintTypeFields { bigint_token } = node.as_fields(); - formatted![formatter, [bigint_token.format()]] + write![f, [bigint_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs b/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs index da0edc3857a..f9ef758492c 100644 --- a/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBooleanLiteralType, TsBooleanLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsBooleanLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsBooleanLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsBooleanLiteralTypeFields { literal } = node.as_fields(); - formatted![formatter, [literal.format()]] + write![f, [literal.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/boolean_type.rs b/crates/rome_js_formatter/src/ts/types/boolean_type.rs index b71a8e6100c..8511fa33602 100644 --- a/crates/rome_js_formatter/src/ts/types/boolean_type.rs +++ b/crates/rome_js_formatter/src/ts/types/boolean_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBooleanType, TsBooleanTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsBooleanType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsBooleanType, f: &mut JsFormatter) -> FormatResult<()> { let TsBooleanTypeFields { boolean_token } = node.as_fields(); - formatted![formatter, [boolean_token.format()]] + write![f, [boolean_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/conditional_type.rs b/crates/rome_js_formatter/src/ts/types/conditional_type.rs index 56b0857e97e..770eb8e215d 100644 --- a/crates/rome_js_formatter/src/ts/types/conditional_type.rs +++ b/crates/rome_js_formatter/src/ts/types/conditional_type.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::TsConditionalType; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsConditionalType, - formatter: &JsFormatter, - ) -> FormatResult { - format_conditional(Conditional::Type(node.clone()), formatter, false) + fn format_fields(node: &TsConditionalType, formatter: &mut JsFormatter) -> FormatResult<()> { + format_conditional(&Conditional::Type(node.clone()), formatter, false) } } diff --git a/crates/rome_js_formatter/src/ts/types/constructor_type.rs b/crates/rome_js_formatter/src/ts/types/constructor_type.rs index 36018f046ae..bd7d787ff88 100644 --- a/crates/rome_js_formatter/src/ts/types/constructor_type.rs +++ b/crates/rome_js_formatter/src/ts/types/constructor_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsConstructorType; use rome_js_syntax::TsConstructorTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsConstructorType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsConstructorType, f: &mut JsFormatter) -> FormatResult<()> { let TsConstructorTypeFields { abstract_token, new_token, @@ -17,12 +15,13 @@ impl FormatNodeFields for FormatNodeRule { return_type, } = node.as_fields(); - formatted![ - formatter, + if let Some(abstract_token) = abstract_token { + write!(f, [abstract_token.format(), space_token()])?; + } + + write![ + f, [ - abstract_token - .format() - .with_or_empty(|element| formatted![formatter, [element, space_token()]]), new_token.format(), type_parameters.format(), parameters.format(), diff --git a/crates/rome_js_formatter/src/ts/types/function_type.rs b/crates/rome_js_formatter/src/ts/types/function_type.rs index 9d49ba38036..24a59280870 100644 --- a/crates/rome_js_formatter/src/ts/types/function_type.rs +++ b/crates/rome_js_formatter/src/ts/types/function_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsFunctionType; use rome_js_syntax::TsFunctionTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsFunctionType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsFunctionType, f: &mut JsFormatter) -> FormatResult<()> { let TsFunctionTypeFields { parameters, fat_arrow_token, @@ -15,8 +13,8 @@ impl FormatNodeFields for FormatNodeRule { return_type, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ type_parameters.format(), parameters.format(), diff --git a/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs b/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs index 59a11ba3518..675c080da62 100644 --- a/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs +++ b/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsIndexedAccessType; use rome_js_syntax::TsIndexedAccessTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexedAccessType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsIndexedAccessType, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexedAccessTypeFields { object_type, l_brack_token, index_type, r_brack_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ object_type.format(), l_brack_token.format(), diff --git a/crates/rome_js_formatter/src/ts/types/infer_type.rs b/crates/rome_js_formatter/src/ts/types/infer_type.rs index 9baec0bd2ee..8c3688d6b69 100644 --- a/crates/rome_js_formatter/src/ts/types/infer_type.rs +++ b/crates/rome_js_formatter/src/ts/types/infer_type.rs @@ -1,15 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsInferType, TsInferTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsInferType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsInferType, f: &mut JsFormatter) -> FormatResult<()> { let TsInferTypeFields { infer_token, type_parameter, } = node.as_fields(); - let infer = infer_token.format(); - let type_parameter = type_parameter.format(); - formatted![formatter, [infer, space_token(), type_parameter]] + write![ + f, + [infer_token.format(), space_token(), type_parameter.format()] + ] } } diff --git a/crates/rome_js_formatter/src/ts/types/intersection_type.rs b/crates/rome_js_formatter/src/ts/types/intersection_type.rs index e076ac8e912..12502b37c32 100644 --- a/crates/rome_js_formatter/src/ts/types/intersection_type.rs +++ b/crates/rome_js_formatter/src/ts/types/intersection_type.rs @@ -1,35 +1,50 @@ +use crate::formatter::FormatTrimmedToken; use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsIntersectionType; use rome_js_syntax::TsIntersectionTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIntersectionType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsIntersectionType, f: &mut JsFormatter) -> FormatResult<()> { let TsIntersectionTypeFields { leading_separator_token, types, } = node.as_fields(); - let leading_separator_token = match leading_separator_token { - Some(token) => { - // The SyntaxToken is converted into a FormatElement using - // Token::from to strip the token's trivia pieces which are - // then reinserted in format_replaced outside of the - // if_group_breaks block to avoid removing comments when the - // group does not break - let replaced = - if_group_breaks(format_elements![Token::from(&token), space_token()]); - formatter.format_replaced(&token, replaced) + let leading_separator_token = format_once(|f| { + match leading_separator_token { + Some(token) => { + // The SyntaxToken is converted into a FormatElement using + // Token::from to strip the token's trivia pieces which are + // then reinserted in format_replaced outside of the + // if_group_breaks block to avoid removing comments when the + // group does not break + write!( + f, + [f.format_replaced( + &token, + &if_group_breaks(&format_args!( + FormatTrimmedToken::new(&token), + space_token() + )) + )] + ) + } + None => write!( + f, + [if_group_breaks(&format_args![token("&"), space_token()])] + ), } - None => if_group_breaks(format_elements![token("&"), space_token()]), - }; + }); - Ok(group_elements(indent(formatted![ - formatter, - [soft_line_break(), leading_separator_token, types.format(),] - ]?))) + write!( + f, + [group_elements(&indent(&format_args!( + soft_line_break(), + leading_separator_token, + types.format() + )))] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/mapped_type.rs b/crates/rome_js_formatter/src/ts/types/mapped_type.rs index 5be5baa2010..970c82f821c 100644 --- a/crates/rome_js_formatter/src/ts/types/mapped_type.rs +++ b/crates/rome_js_formatter/src/ts/types/mapped_type.rs @@ -1,10 +1,11 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsMappedType, TsMappedTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsMappedType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsMappedType, f: &mut JsFormatter) -> FormatResult<()> { let TsMappedTypeFields { l_curly_token, readonly_modifier, @@ -20,40 +21,33 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [f.delimited( &l_curly_token?, - format_with_semicolon( - formatter, - formatted![ - formatter, - [ - readonly_modifier - .format() - .with_or_empty(|readonly| formatted![ - formatter, - [readonly, space_token()] - ]), - l_brack_token.format(), - property_name.format(), - space_token(), - in_token.format(), - space_token(), - keys_type.format(), - as_clause.format().with_or_empty(|clause| formatted![ - formatter, - [space_token(), clause] - ]), - r_brack_token.format(), - optional_modifier.format(), - mapped_type.format(), - ] - ]?, - semicolon_token, - )?, + &FormatWithSemicolon::new( + &format_args!( + readonly_modifier + .format() + .with_or_empty(|readonly, f| write![f, [readonly, space_token()]]), + l_brack_token.format(), + property_name.format(), + space_token(), + in_token.format(), + space_token(), + keys_type.format(), + as_clause + .format() + .with_or_empty(|clause, f| write![f, [space_token(), clause]]), + r_brack_token.format(), + optional_modifier.format(), + mapped_type.format(), + ), + semicolon_token.as_ref(), + ), &r_curly_token?, ) - .block_indent() - .finish() + .block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/never_type.rs b/crates/rome_js_formatter/src/ts/types/never_type.rs index 1502d7e75fe..5e0984a3b19 100644 --- a/crates/rome_js_formatter/src/ts/types/never_type.rs +++ b/crates/rome_js_formatter/src/ts/types/never_type.rs @@ -1,10 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNeverType, TsNeverTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsNeverType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsNeverType, f: &mut JsFormatter) -> FormatResult<()> { let TsNeverTypeFields { never_token } = node.as_fields(); - formatted![formatter, [never_token.format()]] + write![f, [never_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs b/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs index 6888d623504..9347b8271a2 100644 --- a/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs +++ b/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNonPrimitiveType, TsNonPrimitiveTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNonPrimitiveType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNonPrimitiveType, f: &mut JsFormatter) -> FormatResult<()> { let TsNonPrimitiveTypeFields { object_token } = node.as_fields(); - formatted![formatter, [object_token.format()]] + write![f, [object_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/null_literal_type.rs b/crates/rome_js_formatter/src/ts/types/null_literal_type.rs index 2528f2e50af..953054b724c 100644 --- a/crates/rome_js_formatter/src/ts/types/null_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/null_literal_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNullLiteralType, TsNullLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNullLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNullLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsNullLiteralTypeFields { literal_token } = node.as_fields(); - formatted![formatter, [literal_token.format()]] + write![f, [literal_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/number_literal_type.rs b/crates/rome_js_formatter/src/ts/types/number_literal_type.rs index 8c83046c20d..763ce81c186 100644 --- a/crates/rome_js_formatter/src/ts/types/number_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/number_literal_type.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNumberLiteralType, TsNumberLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNumberLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsNumberLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsNumberLiteralTypeFields { minus_token, literal_token, } = node.as_fields(); - formatted![formatter, [minus_token.format(), literal_token.format()]] + write![f, [minus_token.format(), literal_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/number_type.rs b/crates/rome_js_formatter/src/ts/types/number_type.rs index 72808591d63..e47b18fce1b 100644 --- a/crates/rome_js_formatter/src/ts/types/number_type.rs +++ b/crates/rome_js_formatter/src/ts/types/number_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNumberType, TsNumberTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsNumberType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsNumberType, f: &mut JsFormatter) -> FormatResult<()> { let TsNumberTypeFields { number_token } = node.as_fields(); - formatted![formatter, [number_token.format()]] + write![f, [number_token.format()]] } } 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 71478c28041..5b1b12b60a2 100644 --- a/crates/rome_js_formatter/src/ts/types/object_type.rs +++ b/crates/rome_js_formatter/src/ts/types/object_type.rs @@ -1,10 +1,11 @@ use crate::prelude::*; use crate::utils::has_leading_newline; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsObjectType, TsObjectTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsObjectType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsObjectType, f: &mut JsFormatter) -> FormatResult<()> { let TsObjectTypeFields { l_curly_token, members, @@ -12,23 +13,21 @@ impl FormatNodeFields for FormatNodeRule { } = node.as_fields(); if has_leading_newline(members.syntax()) { - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [members.format()]]?, - &r_curly_token?, - ) - .block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .block_indent() + ] + ) } else { - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [members.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + f.delimited(&l_curly_token?, &members.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } } diff --git a/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs b/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs index 62a10f36c65..637e8210d06 100644 --- a/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs +++ b/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs @@ -1,26 +1,21 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsParenthesizedType; use rome_js_syntax::TsParenthesizedTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsParenthesizedType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsParenthesizedType, f: &mut JsFormatter) -> FormatResult<()> { let TsParenthesizedTypeFields { l_paren_token, ty, r_paren_token, } = node.as_fields(); - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [ty.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [f.delimited(&l_paren_token?, &ty.format(), &r_paren_token?,) + .soft_block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs b/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs index 11501ff6d18..1f22cda2d0a 100644 --- a/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs +++ b/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsPredicateReturnType; use rome_js_syntax::TsPredicateReturnTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsPredicateReturnType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsPredicateReturnType, f: &mut JsFormatter) -> FormatResult<()> { let TsPredicateReturnTypeFields { parameter_name, is_token, ty, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ parameter_name.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/types/reference_type.rs b/crates/rome_js_formatter/src/ts/types/reference_type.rs index c784dd3618a..7915a29dcc7 100644 --- a/crates/rome_js_formatter/src/ts/types/reference_type.rs +++ b/crates/rome_js_formatter/src/ts/types/reference_type.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsReferenceType, TsReferenceTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsReferenceType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsReferenceType, f: &mut JsFormatter) -> FormatResult<()> { let TsReferenceTypeFields { name, type_arguments, } = node.as_fields(); - formatted![formatter, [name.format(), type_arguments.format()]] + write![f, [name.format(), type_arguments.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/string_literal_type.rs b/crates/rome_js_formatter/src/ts/types/string_literal_type.rs index a86d8b44a08..5d526587349 100644 --- a/crates/rome_js_formatter/src/ts/types/string_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/string_literal_type.rs @@ -1,18 +1,13 @@ use crate::prelude::*; use crate::utils::FormatLiteralStringToken; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsStringLiteralType, TsStringLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsStringLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsStringLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsStringLiteralTypeFields { literal_token } = node.as_fields(); - formatted![ - formatter, - [FormatLiteralStringToken::from_string(&literal_token?)] - ] + write!(f, [FormatLiteralStringToken::from_string(&literal_token?)]) } } diff --git a/crates/rome_js_formatter/src/ts/types/string_type.rs b/crates/rome_js_formatter/src/ts/types/string_type.rs index ed6a36f3ef8..a2909cbaf67 100644 --- a/crates/rome_js_formatter/src/ts/types/string_type.rs +++ b/crates/rome_js_formatter/src/ts/types/string_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsStringType, TsStringTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsStringType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsStringType, f: &mut JsFormatter) -> FormatResult<()> { let TsStringTypeFields { string_token } = node.as_fields(); - formatted![formatter, [string_token.format()]] + write![f, [string_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/symbol_type.rs b/crates/rome_js_formatter/src/ts/types/symbol_type.rs index 043abbb8edf..7fb8add5039 100644 --- a/crates/rome_js_formatter/src/ts/types/symbol_type.rs +++ b/crates/rome_js_formatter/src/ts/types/symbol_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsSymbolType, TsSymbolTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsSymbolType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsSymbolType, f: &mut JsFormatter) -> FormatResult<()> { let TsSymbolTypeFields { symbol_token } = node.as_fields(); - formatted![formatter, [symbol_token.format()]] + write![f, [symbol_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/this_type.rs b/crates/rome_js_formatter/src/ts/types/this_type.rs index d14490e810c..a38836f4485 100644 --- a/crates/rome_js_formatter/src/ts/types/this_type.rs +++ b/crates/rome_js_formatter/src/ts/types/this_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsThisType, TsThisTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsThisType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsThisType, f: &mut JsFormatter) -> FormatResult<()> { let TsThisTypeFields { this_token } = node.as_fields(); - formatted![formatter, [this_token.format()]] + write![f, [this_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/tuple_type.rs b/crates/rome_js_formatter/src/ts/types/tuple_type.rs index 87b66088313..7267e20ed46 100644 --- a/crates/rome_js_formatter/src/ts/types/tuple_type.rs +++ b/crates/rome_js_formatter/src/ts/types/tuple_type.rs @@ -1,22 +1,22 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTupleType, TsTupleTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsTupleType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsTupleType, f: &mut JsFormatter) -> FormatResult<()> { let TsTupleTypeFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - formatter - .delimited( - &l_brack_token?, - formatted![formatter, [elements.format()]]?, - &r_brack_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + f.delimited(&l_brack_token?, &elements.format(), &r_brack_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/type_operator_type.rs b/crates/rome_js_formatter/src/ts/types/type_operator_type.rs index f4630774919..b4c107d6194 100644 --- a/crates/rome_js_formatter/src/ts/types/type_operator_type.rs +++ b/crates/rome_js_formatter/src/ts/types/type_operator_type.rs @@ -1,22 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeOperatorType, TsTypeOperatorTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeOperatorType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsTypeOperatorType, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeOperatorTypeFields { operator_token, ty } = node.as_fields(); - formatted![ - formatter, - [ - operator_token - .format() - .with(|operator| { formatted![formatter, [operator, space_token()]] }), - ty.format() - ] - ] + write![f, [operator_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/typeof_type.rs b/crates/rome_js_formatter/src/ts/types/typeof_type.rs index 9f8dc5064d8..5b645a85dbd 100644 --- a/crates/rome_js_formatter/src/ts/types/typeof_type.rs +++ b/crates/rome_js_formatter/src/ts/types/typeof_type.rs @@ -1,16 +1,22 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeofType, TsTypeofTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsTypeofType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsTypeofType, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeofTypeFields { typeof_token, expression_name, } = node.as_fields(); - let r#typeof = typeof_token.format(); - let expression_name = expression_name.format(); - formatted![formatter, [r#typeof, space_token(), expression_name]] + write![ + f, + [ + typeof_token.format(), + space_token(), + expression_name.format() + ] + ] } } diff --git a/crates/rome_js_formatter/src/ts/types/undefined_type.rs b/crates/rome_js_formatter/src/ts/types/undefined_type.rs index f4ef90134c9..2c0ae955e79 100644 --- a/crates/rome_js_formatter/src/ts/types/undefined_type.rs +++ b/crates/rome_js_formatter/src/ts/types/undefined_type.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsUndefinedType, TsUndefinedTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsUndefinedType, - formatter: &JsFormatter, - ) -> FormatResult { + fn format_fields(node: &TsUndefinedType, f: &mut JsFormatter) -> FormatResult<()> { let TsUndefinedTypeFields { undefined_token } = node.as_fields(); - formatted![formatter, [undefined_token.format()]] + write![f, [undefined_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/union_type.rs b/crates/rome_js_formatter/src/ts/types/union_type.rs index 7d8b169b10e..a49ca24c054 100644 --- a/crates/rome_js_formatter/src/ts/types/union_type.rs +++ b/crates/rome_js_formatter/src/ts/types/union_type.rs @@ -1,48 +1,67 @@ +use crate::formatter::FormatTrimmedToken; use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::TsUnionType; use rome_js_syntax::TsUnionTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsUnionType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsUnionType, f: &mut JsFormatter) -> FormatResult<()> { let TsUnionTypeFields { leading_separator_token, types, } = node.as_fields(); - let leading_separator_token = match leading_separator_token { - Some(token) => { - // The SyntaxToken is converted into a FormatElement using - // Token::from to strip the token's trivia pieces which are - // then reinserted informat_replaced outside of the - // if_group_breaks block to avoid removing comments when the - // group does not break - let replaced = - if_group_breaks(format_elements![Token::from(&token), space_token()]); - formatter.format_replaced(&token, replaced) + let leading_separator_token = format_once(|f| { + match leading_separator_token { + Some(token) => { + // The SyntaxToken is converted into a FormatElement using + // Token::from to strip the token's trivia pieces which are + // then reinserted informat_replaced outside of the + // if_group_breaks block to avoid removing comments when the + // group does not break + write!( + f, + [f.format_replaced( + &token, + &if_group_breaks(&format_args!( + FormatTrimmedToken::new(&token), + space_token() + )) + )] + ) + } + None => write!( + f, + [if_group_breaks(&format_args![token("|"), space_token()])] + ), } - None => if_group_breaks(format_elements![token("|"), space_token()]), - }; + }); - let types = formatted![formatter, [types.format()]]?; + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [types.format()])?; + + let types = buffer.into_document().into_element(); // Push trailing comments for the union out of the group (and indent block), // so any potential line break doesn't influence the formatting of the type itself let (leading_comments, types, trailing_comments) = types.split_trivia(); - formatted![ - formatter, + write![ + f, [ - group_elements(indent(formatted![ - formatter, - [ - soft_line_break(), - leading_separator_token, - leading_comments, - types, - ] - ]?)), - trailing_comments + group_elements(&indent(&format_args![ + soft_line_break(), + format_once(|f| { + f.write_element(leading_comments); + f.write_element(types); + Ok(()) + }) + ])), + format_once(|f| { + f.write_element(trailing_comments); + Ok(()) + }) ] ] } diff --git a/crates/rome_js_formatter/src/ts/types/unknown_type.rs b/crates/rome_js_formatter/src/ts/types/unknown_type.rs index cd1a041f266..81ef3133ace 100644 --- a/crates/rome_js_formatter/src/ts/types/unknown_type.rs +++ b/crates/rome_js_formatter/src/ts/types/unknown_type.rs @@ -1,10 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsUnknownType, TsUnknownTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsUnknownType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsUnknownType, f: &mut JsFormatter) -> FormatResult<()> { let TsUnknownTypeFields { unknown_token } = node.as_fields(); - formatted![formatter, [unknown_token.format()]] + + write![f, [unknown_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/void_type.rs b/crates/rome_js_formatter/src/ts/types/void_type.rs index 91b7a946e00..a6797e15427 100644 --- a/crates/rome_js_formatter/src/ts/types/void_type.rs +++ b/crates/rome_js_formatter/src/ts/types/void_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsVoidType, TsVoidTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsVoidType, formatter: &JsFormatter) -> FormatResult { + fn format_fields(node: &TsVoidType, f: &mut JsFormatter) -> FormatResult<()> { let TsVoidTypeFields { void_token } = node.as_fields(); - formatted![formatter, [void_token.format()]] + write![f, [void_token.format()]] } } diff --git a/crates/rome_js_formatter/src/utils/array.rs b/crates/rome_js_formatter/src/utils/array.rs index aea61101c22..cabc343682c 100644 --- a/crates/rome_js_formatter/src/utils/array.rs +++ b/crates/rome_js_formatter/src/utils/array.rs @@ -1,6 +1,7 @@ use crate::prelude::*; - use crate::AsFormat; +use rome_formatter::FormatWithRule; +use rome_formatter::{format_args, write}; use rome_js_syntax::{ JsAnyArrayAssignmentPatternElement, JsAnyArrayBindingPatternElement, JsAnyArrayElement, JsLanguage, @@ -8,10 +9,7 @@ use rome_js_syntax::{ use rome_rowan::{AstNode, AstSeparatedList}; /// Utility function to print array-like nodes (array expressions, array bindings and assignment patterns) -pub(crate) fn format_array_node( - node: &N, - formatter: &JsFormatter, -) -> FormatResult +pub(crate) fn format_array_node(node: &N, f: &mut JsFormatter) -> FormatResult<()> where N: AstSeparatedList, for<'a> I: ArrayNodeElement + AsFormat<'a>, @@ -19,48 +17,48 @@ where // Specifically do not use format_separated as arrays need separators // inserted after holes regardless of the formatting since this makes a // semantic difference + + let mut join = f.join_nodes_with_soft_line(); let last_index = node.len().saturating_sub(1); - let results = node - .elements() - .enumerate() - .map(|(index, element)| { - let node = element.node()?; - let separator_mode = node.separator_mode(); - let is_disallow = matches!(separator_mode, TrailingSeparatorMode::Disallow); - let is_force = matches!(separator_mode, TrailingSeparatorMode::Force); + for (index, element) in node.elements().enumerate() { + let node = element.node()?; + let separator_mode = node.separator_mode(); + + let is_disallow = matches!(separator_mode, TrailingSeparatorMode::Disallow); + let is_force = matches!(separator_mode, TrailingSeparatorMode::Force); - let formatted_element = formatted![formatter, [node.format()]]?; - let separator = if is_disallow { - // Trailing separators are disallowed, replace it with an empty element - if let Some(separator) = element.trailing_separator()? { - formatter.format_replaced(separator, empty_element()) + join.entry( + node.syntax(), + &format_with(|f| { + write!(f, [group_elements(&node.format())])?; + + if is_disallow { + // Trailing separators are disallowed, replace it with an empty element + if let Some(separator) = element.trailing_separator()? { + write!(f, [f.format_replaced(separator, &empty_element())])?; + } + } else if is_force || index != last_index { + // In forced separator mode or if this element is not the last in the list, print the separator + match element.trailing_separator()? { + Some(trailing) => write!(f, [trailing.format()])?, + None => write!(f, [token(",")])?, + }; + } else if let Some(separator) = element.trailing_separator()? { + write!( + f, + [f.format_replaced(separator, &if_group_breaks(&token(",")))] + )?; } else { - empty_element() - } - } else if is_force || index != last_index { - // In forced separator mode or if this element is not the last in the list, print the separator - formatted![ - formatter, - [&element - .trailing_separator() - .format() - .or_format(|| token(","))] - ]? - } else if let Some(separator) = element.trailing_separator()? { - formatter.format_replaced(separator, if_group_breaks(token(","))) - } else { - if_group_breaks(token(",")) - }; + write!(f, [if_group_breaks(&token(","))])?; + }; - Ok(( - node.syntax().clone(), - format_elements![group_elements(formatted_element), separator], - )) - }) - .collect::>>()?; + Ok(()) + }), + ); + } - Ok(join_elements_soft_line(results)) + join.finish() } /// Determines if a trailing separator should be inserted after an array element diff --git a/crates/rome_js_formatter/src/utils/binary_like_expression.rs b/crates/rome_js_formatter/src/utils/binary_like_expression.rs index de7b1e4f94f..4ce9ddf22c7 100644 --- a/crates/rome_js_formatter/src/utils/binary_like_expression.rs +++ b/crates/rome_js_formatter/src/utils/binary_like_expression.rs @@ -1,10 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::{ JsAnyExpression, JsAnyInProperty, JsBinaryExpression, JsBinaryOperator, JsInExpression, JsInstanceofExpression, JsLanguage, JsLogicalExpression, JsLogicalOperator, JsPrivateName, JsSyntaxKind, JsSyntaxKind::*, JsSyntaxNode, JsSyntaxToken, }; +use rome_rowan::support::elements; use rome_rowan::{AstNode, SyntaxResult}; use std::cmp::Ordering; use std::fmt::Debug; @@ -95,8 +97,8 @@ use std::iter::FusedIterator; /// which is what we wanted since the beginning! pub(crate) fn format_binary_like_expression( expression: JsAnyBinaryLikeExpression, - formatter: &JsFormatter, -) -> FormatResult { + f: &mut JsFormatter, +) -> FormatResult<()> { let mut flatten_items = FlattenItems::default(); let current_node = expression.syntax().clone(); @@ -110,7 +112,7 @@ pub(crate) fn format_binary_like_expression( flatten_items.format_binary_expression_right_hand_side( left, Some(parent_operator), - formatter, + f, )?; } else { // Leaf binary like expression. Format the left hand side. @@ -119,10 +121,12 @@ pub(crate) fn format_binary_like_expression( let left = parent.left()?; let has_comments = left.syntax().has_comments_direct(); - let formatted = formatted![formatter, [left]]?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [left])?; flatten_items.items.push(FlattenItem::regular( - formatted, + buffer.into_element(), Some(parent_operator), has_comments.into(), )); @@ -133,10 +137,12 @@ pub(crate) fn format_binary_like_expression( // Format the top most binary like expression if let Some(root) = left { - flatten_items.format_binary_expression_right_hand_side(root, None, formatter)?; + flatten_items.format_binary_expression_right_hand_side(root, None, f)?; } - flatten_items.take_format_element(¤t_node, formatter) + let element = flatten_items.take_format_element(¤t_node, f)?; + f.write_element(element); + Ok(()) } /// Small wrapper to identify the operation of an expression and deduce their precedence @@ -169,7 +175,7 @@ fn format_with_or_without_parenthesis( parent_operator: BinaryLikeOperator, node: &JsSyntaxNode, formatted_node: FormatElement, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<(FormatElement, bool)> { let compare_to = match JsAnyExpression::cast(node.clone()) { Some(JsAnyExpression::JsLogicalExpression(logical)) => { @@ -206,22 +212,23 @@ fn format_with_or_without_parenthesis( let result = if operation_is_higher { let (leading, content, trailing) = formatted_node.split_trivia(); - let formatted = formatted![ - formatter, - [ - leading, - group_elements(formatted![ - formatter, - [ - token("("), - soft_block_indent(formatted![formatter, [content, trailing]]?), - token(")") - ] - ]?) - ] + let mut buffer = VecBuffer::new(f.state_mut()); + + buffer.write_element(leading); + write![ + buffer, + [group_elements(&format_args![ + token("("), + soft_block_indent(&format_once(|f| { + f.write_element(content); + f.write_element(trailing); + Ok(()) + })), + token(")") + ])] ]?; - (formatted, true) + (buffer.into_element(), true) } else { (formatted_node, false) }; @@ -297,14 +304,14 @@ impl FlattenItems { &mut self, expression: JsAnyBinaryLikeExpression, parent_operator: Option, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { let should_flatten = expression.can_flatten()?; if should_flatten { - self.flatten_right_hand_side(expression, parent_operator, formatter) + self.flatten_right_hand_side(expression, parent_operator, f) } else { - self.format_new_binary_like_group(expression, parent_operator, formatter) + self.format_new_binary_like_group(expression, parent_operator, f) } } @@ -313,17 +320,20 @@ impl FlattenItems { &mut self, binary_like_expression: JsAnyBinaryLikeExpression, parent_operator: Option, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { let right = binary_like_expression.right()?; let has_comments = right.syntax().has_comments_direct(); - let right_formatted = formatted![formatter, [right.format()]]?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [right.format()])?; + let right_formatted = buffer.into_element(); let (formatted_node, _) = format_with_or_without_parenthesis( binary_like_expression.operator()?, right.syntax(), right_formatted, - formatter, + f, )?; let flatten_item = @@ -340,7 +350,7 @@ impl FlattenItems { &mut self, binary_like_expression: JsAnyBinaryLikeExpression, parent_operator: Option, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { if let Some(last) = self.items.last_mut() { // Remove any line breaks and the trailing operator so that the operator/trailing aren't part @@ -353,9 +363,9 @@ impl FlattenItems { let operator = binary_like_expression.operator()?; let operator_token = binary_like_expression.operator_token()?; - let left_formatted = self.take_format_element(left.syntax(), formatter)?; + let left_formatted = self.take_format_element(left.syntax(), f)?; let (left_formatted, _) = - format_with_or_without_parenthesis(operator, left.syntax(), left_formatted, formatter)?; + format_with_or_without_parenthesis(operator, left.syntax(), left_formatted, f)?; let operator_has_trailing_comments = operator_token.has_trailing_comments(); let mut left_item = FlattenItem::regular( @@ -372,13 +382,13 @@ impl FlattenItems { let right = binary_like_expression.right()?; + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [right.format()])?; + let formatted_node = buffer.into_element(); + // Format the right node - let (formatted_right, parenthesized) = format_with_or_without_parenthesis( - operator, - right.syntax(), - formatted![formatter, [right.format()]]?, - formatter, - )?; + let (formatted_right, parenthesized) = + format_with_or_without_parenthesis(operator, right.syntax(), formatted_node, f)?; let parent_operator_has_comments = parent_operator .as_ref() @@ -415,64 +425,86 @@ impl FlattenItems { fn take_format_element( &mut self, current_node: &JsSyntaxNode, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult { - let can_hard_group = can_hard_group(&self.items); - let len = self.items.len(); - - let mut groups = self - .items - .drain(..) - .enumerate() - // groups not like ["something &&", "something &&" ] - // we want to add a space between them in case they don't break - .map(|(index, element)| { - let operator = match &element.operator { - Some(operator) => { - // SAFETY: `syntax_token.format` never returns MissingToken. - formatted![formatter, [space_token(), operator.format()]].unwrap() - } - None => empty_element(), - }; - - let terminator = match &element.terminator { - // the last element doesn't need a space - TrailingTerminator::None if index + 1 == len => empty_element(), - TrailingTerminator::None => empty_element(), - TrailingTerminator::HardLineBreak => hard_line_break(), - }; - - format_elements![element.formatted, operator, terminator] - }); - - if can_hard_group { - // we bail early if group doesn't need to be broken. We don't need to do further checks - return Ok(join_elements(space_token(), groups)); - } - - let formatted = if is_inside_parenthesis(current_node) { - join_elements(soft_line_break_or_space(), groups) - } else if should_not_indent_if_parent_indents(current_node) { - group_elements(join_elements(soft_line_break_or_space(), groups)) - } else if should_indent_if_parent_inlines(current_node) { - // in order to correctly break, we need to check if the parent created a group - // that breaks or not. In order to do that , we need to create two conditional groups - // that behave differently depending on the situation - soft_line_indent_or_space(group_elements(join_elements( - soft_line_break_or_space(), - groups, - ))) - } else { - // if none of the previous conditions is met, - // we take take out the first element from the rest of group, then we hard group the "head" - // and we indent the rest of the groups in a new line - let head = groups.next().unwrap(); - let rest = join_elements(soft_line_break_or_space(), groups); - - format_elements![head, group_elements(soft_line_indent_or_space(rest))] - }; + let mut buffer = VecBuffer::new(f.state_mut()); + + write!( + buffer, + [format_once(|f| { + let can_hard_group = can_hard_group(&self.items); + + let mut groups = self.items.drain(..).map(|group| { + format_once(move |f| { + // groups not like ["something &&", "something &&" ] + // we want to add a space between them in case they don't break + + f.write_element(group.formatted); + + if let Some(operator) = group.operator { + write!(f, [space_token(), operator.format()])?; + } + + match group.terminator { + TrailingTerminator::None => (), + TrailingTerminator::HardLineBreak => write!(f, [hard_line_break()])?, + }; + + Ok(()) + }) + }); + + if can_hard_group { + // we bail early if group doesn't need to be broken. We don't need to do further checks + f.join_with(&space_token()).entries(groups).finish() + } else if is_inside_parenthesis(current_node) { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + } else if should_not_indent_if_parent_indents(current_node) { + write!( + f, + [group_elements(&format_once(|f| { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + }))] + ) + } else if should_indent_if_parent_inlines(current_node) { + // in order to correctly break, we need to check if the parent created a group + // that breaks or not. In order to do that , we need to create two conditional groups + // that behave differently depending on the situation + write!( + f, + [soft_line_indent_or_space(&group_elements(&format_once( + |f| { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + } + )))] + ) + } else { + // if none of the previous conditions is met, + // we take take out the first element from the rest of group, then we hard group the "head" + // and we indent the rest of the groups in a new line + write!(f, [groups.next().unwrap()])?; + + write!( + f, + [group_elements(&soft_line_indent_or_space(&format_once( + |f| { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + } + )))] + ) + } + })] + )?; - Ok(formatted) + Ok(buffer.into_element()) } } @@ -866,16 +898,14 @@ impl AstNode for JsAnyBinaryLikeLeftExpression { } } -impl Format for JsAnyBinaryLikeLeftExpression { - type Context = JsFormatContext; - - fn format(&self, formatter: &JsFormatter) -> FormatResult { +impl Format for JsAnyBinaryLikeLeftExpression { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { match self { JsAnyBinaryLikeLeftExpression::JsAnyExpression(expression) => { - formatted![formatter, [expression.format()]] + write![f, [expression.format()]] } JsAnyBinaryLikeLeftExpression::JsPrivateName(private_name) => { - formatted![formatter, [private_name.format()]] + write![f, [private_name.format()]] } } } diff --git a/crates/rome_js_formatter/src/utils/format_conditional.rs b/crates/rome_js_formatter/src/utils/format_conditional.rs index 15367b454b3..42b9f2071dd 100644 --- a/crates/rome_js_formatter/src/utils/format_conditional.rs +++ b/crates/rome_js_formatter/src/utils/format_conditional.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::{JsAnyExpression, JsConditionalExpression, TsConditionalType, TsType}; use rome_rowan::AstNode; @@ -27,32 +28,13 @@ impl Conditional { } } - fn into_format_element( - self, - formatter: &JsFormatter, - parent_is_conditional: bool, - ) -> FormatResult { - let (head, body) = match self { - Conditional::Expression(_) => ( - self.format_head(formatter)?, - self.format_body(formatter, parent_is_conditional)?, - ), - Conditional::Type(_) => ( - self.format_head(formatter)?, - self.format_body(formatter, parent_is_conditional)?, - ), - }; - - formatted![formatter, [head, body]] - } - - fn format_head(&self, formatter: &JsFormatter) -> FormatResult { + fn format_head(&self, f: &mut JsFormatter) -> FormatResult<()> { match self { Conditional::Expression(expr) => { - formatted![formatter, [expr.test()?.format(), space_token(),]] + write![f, [expr.test()?.format(), space_token(),]] } - Conditional::Type(t) => formatted![ - formatter, + Conditional::Type(t) => write![ + f, [ t.check_type()?.format(), space_token(), @@ -86,64 +68,77 @@ impl Conditional { } } - fn format_body( - &self, - formatter: &JsFormatter, - parent_is_conditional: bool, - ) -> FormatResult { - let mut left_or_right_is_conditional = false; + fn format_body(&self, f: &mut JsFormatter, parent_is_conditional: bool) -> FormatResult<()> { let consequent = self.consequent_to_conditional()?; let alternate = self.alternate_to_conditional()?; + let left_or_right_is_conditional = alternate.is_some() || consequent.is_some(); - let consequent = if let Some(consequent) = consequent { - left_or_right_is_conditional = true; - let consequent = format_conditional(consequent, formatter, true)?; - self.format_with_consequent(formatter, Some(consequent))? - } else { - self.format_with_consequent(formatter, None)? - }; + let format_consequent = + format_with(|f| self.format_with_consequent(f, consequent.as_ref())); - let alternate = if let Some(alternate) = alternate { - left_or_right_is_conditional = true; - let alternate = format_conditional(alternate, formatter, true)?; - self.format_with_alternate(formatter, Some(alternate))? - } else { - self.format_with_alternate(formatter, None)? - }; + let format_alternate = format_with(|f| self.format_with_alternate(f, alternate.as_ref())); let body = if left_or_right_is_conditional || parent_is_conditional { - indent(formatted![ - formatter, - [hard_line_break(), consequent, hard_line_break(), alternate] - ]?) + write!( + f, + [indent(&format_args![ + hard_line_break(), + format_consequent, + hard_line_break(), + format_alternate + ])] + )?; } else { - group_elements(formatted![ - formatter, - [space_token(), consequent, space_token(), alternate] - ]?) + write!( + f, + [group_elements(&format_args![ + space_token(), + format_consequent, + space_token(), + format_alternate + ])] + )?; }; - Ok(body) + + Ok(()) } fn format_with_consequent( &self, - formatter: &JsFormatter, - consequent: Option, - ) -> FormatResult { - match self { - Conditional::Expression(expr) => { - if let Some(consequent) = consequent { - formatted![ - formatter, - [ - expr.question_mark_token().format(), - space_token(), - consequent + f: &mut JsFormatter, + consequent: Option<&Conditional>, + ) -> FormatResult<()> { + match consequent { + Some(consequent) => { + let format_consequent = format_with(|f| format_conditional(consequent, f, true)); + + match self { + Conditional::Expression(expr) => { + write![ + f, + [ + expr.question_mark_token().format(), + space_token(), + format_consequent + ] ] - ] - } else { - formatted![ - formatter, + } + Conditional::Type(ty) => { + write![ + f, + [ + ty.question_mark_token().format(), + space_token(), + format_consequent + ] + ] + } + } + } + None => match self { + Conditional::Expression(expr) => { + write![ + f, [ expr.question_mark_token().format(), space_token(), @@ -151,16 +146,9 @@ impl Conditional { ] ] } - } - Conditional::Type(ty) => { - if let Some(consequent) = consequent { - formatted![ - formatter, - [ty.question_mark_token().format(), space_token(), consequent] - ] - } else { - formatted![ - formatter, + Conditional::Type(ty) => { + write![ + f, [ ty.question_mark_token().format(), space_token(), @@ -168,50 +156,53 @@ impl Conditional { ] ] } - } + }, } } fn format_with_alternate( &self, - formatter: &JsFormatter, - alternate: Option, - ) -> FormatResult { - match self { - Conditional::Expression(expr) => { - if let Some(alternate) = alternate { - formatted![ - formatter, - [expr.colon_token().format(), space_token(), alternate] - ] - } else { - formatted![ - formatter, - [ - expr.colon_token().format(), - space_token(), - expr.alternate().format() + f: &mut JsFormatter, + alternate: Option<&Conditional>, + ) -> FormatResult<()> { + match alternate { + Some(alternate) => { + let format_alternate = format_with(|f| format_conditional(alternate, f, true)); + + match self { + Conditional::Expression(expr) => { + write![ + f, + [expr.colon_token().format(), space_token(), format_alternate] ] - ] + } + Conditional::Type(ty) => { + write![ + f, + [ty.colon_token().format(), space_token(), format_alternate] + ] + } } } - Conditional::Type(ty) => { - if let Some(alternate) = alternate { - formatted![ - formatter, - [ty.colon_token().format(), space_token(), alternate] + + None => match self { + Conditional::Expression(expr) => write![ + f, + [ + expr.colon_token().format(), + space_token(), + expr.alternate().format() ] - } else { - formatted![ - formatter, - [ - ty.colon_token().format(), - space_token(), - ty.false_type().format() - ] + ], + Conditional::Type(ty) => write![ + f, + [ + ty.colon_token().format(), + space_token(), + ty.false_type().format() ] - } - } + ], + }, } } } @@ -224,9 +215,10 @@ impl Conditional { /// - [rome_js_syntax::TsConditionalType] /// - [rome_js_syntax::JsConditionalExpression] pub fn format_conditional( - conditional: Conditional, - formatter: &JsFormatter, + conditional: &Conditional, + f: &mut JsFormatter, parent_is_conditional: bool, -) -> FormatResult { - conditional.into_format_element(formatter, parent_is_conditional) +) -> FormatResult<()> { + conditional.format_head(f)?; + conditional.format_body(f, parent_is_conditional) } diff --git a/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs b/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs index 025985745fd..9344188070f 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs @@ -5,7 +5,6 @@ use rome_js_syntax::{ JsThisExpression, }; use rome_rowan::{AstNode, SyntaxResult}; -use std::fmt; use std::fmt::Debug; #[derive(Clone)] diff --git a/crates/rome_js_formatter/src/utils/member_chain/groups.rs b/crates/rome_js_formatter/src/utils/member_chain/groups.rs index bc15dd53345..beda6dbe18c 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/groups.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/groups.rs @@ -1,13 +1,16 @@ use crate::prelude::*; use crate::utils::member_chain::flatten_item::FlattenItem; use crate::utils::member_chain::simple_argument::SimpleArgument; + +use rome_formatter::formatter::FormatState; +use rome_formatter::{format, Buffer, VecBuffer}; use rome_js_syntax::JsCallExpression; use rome_rowan::{AstSeparatedList, SyntaxResult}; use std::mem; #[derive(Clone)] /// Handles creation of groups while scanning the flatten items -pub(crate) struct Groups<'f> { +pub(crate) struct Groups { /// If the current group is inside an expression statement. /// /// This information is important when evaluating the break of the groups. @@ -17,23 +20,22 @@ pub(crate) struct Groups<'f> { /// keeps track of the current group that is being created/updated current_group: Vec, - /// instance of the formatter - formatter: &'f JsFormatter, - /// This is a threshold of when we should start breaking the groups /// /// By default, it's 2, meaning that we start breaking after the second group. cutoff: u8, + + context: JsFormatContext, } -impl<'f> Groups<'f> { - pub fn new(formatter: &'f JsFormatter, in_expression_statement: bool) -> Self { +impl Groups { + pub fn new(in_expression_statement: bool, context: JsFormatContext) -> Self { Self { - formatter, in_expression_statement, groups: Vec::new(), current_group: Vec::new(), cutoff: 2, + context, } } @@ -101,8 +103,24 @@ impl<'f> Groups<'f> { /// Format groups on multiple lines pub fn into_joined_hard_line_groups(self) -> FormatElement { - let formatted_groups = self.into_formatted_groups(); - join_elements(hard_line_break(), formatted_groups) + let elements = format!( + JsFormatContext::default(), + [format_once(|f| { + let formatted_groups = self.into_formatted_groups(); + + f.join_with(&hard_line_break()) + .entries(formatted_groups.into_iter().map(|e| { + format_once(|f| { + f.write_element(e); + Ok(()) + }) + })) + .finish() + })] + ) + .unwrap(); + + elements.into_format_element() } /// Creates two different versions of the formatted groups, one that goes in one line @@ -146,7 +164,7 @@ impl<'f> Groups<'f> { /// This is an heuristic needed to check when the first element of the group /// Should be part of the "head" or the "tail". fn should_not_wrap(&self, first_group: &HeadGroup) -> SyntaxResult { - let tab_with = self.formatter.state().tab_width(); + let tab_with = self.context.tab_width(); let has_computed_property = if self.groups.len() > 1 { // SAFETY: guarded by the previous check let group = &self.groups[0]; diff --git a/crates/rome_js_formatter/src/utils/member_chain/mod.rs b/crates/rome_js_formatter/src/utils/member_chain/mod.rs index 0782a4d6069..61151e98ba5 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/mod.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/mod.rs @@ -5,6 +5,7 @@ mod simple_argument; use crate::prelude::*; use crate::utils::member_chain::flatten_item::FlattenItem; use crate::utils::member_chain::groups::{Groups, HeadGroup}; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::{ JsCallExpression, JsComputedMemberExpression, JsExpressionStatement, JsStaticMemberExpression, }; @@ -117,16 +118,13 @@ use rome_rowan::AstNode; /// ``` /// /// [Prettier applies]: https://github.com/prettier/prettier/blob/main/src/language-js/print/member-chain.js -pub fn format_call_expression( - syntax_node: &JsSyntaxNode, - formatter: &JsFormatter, -) -> FormatResult { +pub fn format_call_expression(syntax_node: &JsSyntaxNode, f: &mut JsFormatter) -> FormatResult<()> { let mut flattened_items = vec![]; let parent_is_expression_statement = syntax_node.parent().map_or(false, |parent| { JsExpressionStatement::can_cast(parent.kind()) }); - flatten_call_expression(&mut flattened_items, syntax_node.clone(), formatter)?; + flatten_call_expression(&mut flattened_items, syntax_node.clone(), f)?; // Count the number of CallExpression in the chain, // will be used later to decide on how to format it @@ -146,8 +144,7 @@ pub fn format_call_expression( // `flattened_items` now contains only the nodes that should have a sequence of // `[ StaticMemberExpression -> AnyNode + JsCallExpression ]` - let mut rest_of_groups = - compute_groups(flattened_items, parent_is_expression_statement, formatter)?; + let mut rest_of_groups = compute_groups(flattened_items, parent_is_expression_statement, f)?; // Here we check if the first element of Groups::groups can be moved inside the head. // If so, then we extract it and concatenate it together with the head. @@ -156,7 +153,7 @@ pub fn format_call_expression( head_group.expand_group(group_to_merge); } - format_groups(calls_count, head_group, rest_of_groups) + format_groups(calls_count, head_group, rest_of_groups, f) } /// Retrieves the index where we want to calculate the first group. @@ -234,10 +231,10 @@ fn compute_first_group_index(flatten_items: &[FlattenItem]) -> usize { fn compute_groups( flatten_items: impl Iterator, in_expression_statement: bool, - formatter: &JsFormatter, + f: &JsFormatter, ) -> FormatResult { let mut has_seen_call_expression = false; - let mut groups = Groups::new(formatter, in_expression_statement); + let mut groups = Groups::new(in_expression_statement, *f.context()); for item in flatten_items { let has_trailing_comments = item.as_syntax().has_trailing_comments(); @@ -288,30 +285,32 @@ fn format_groups( calls_count: usize, head_group: HeadGroup, groups: Groups, -) -> FormatResult { + f: &mut JsFormatter, +) -> FormatResult<()> { // TODO use Alternatives once available + f.write_element(head_group.into_format_element()); + if groups.groups_should_break(calls_count)? { - Ok(format_elements![ - head_group.into_format_element(), - indent(format_elements![ + write!( + f, + [indent(&format_args!( hard_line_break(), - groups.into_joined_hard_line_groups() - ]) - ]) + format_once(|f| { + f.write_element(groups.into_joined_hard_line_groups()); + Ok(()) + }) + ))] + ) } else { let chain = groups.into_format_elements(); - - Ok(format_elements![ - head_group.into_format_element(), + if !chain.is_empty() { // TODO This line suffix boundary shouldn't be needed but currently is because comments // can move over node boundaries. Follow up when re-working member chain formatting - if chain.is_empty() { - empty_element() - } else { - line_suffix_boundary() - }, - chain - ]) + write!(f, [line_suffix_boundary()])?; + } + + f.write_element(chain); + Ok(()) } } @@ -320,61 +319,71 @@ fn format_groups( fn flatten_call_expression( queue: &mut Vec, node: JsSyntaxNode, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { match node.kind() { JsSyntaxKind::JS_CALL_EXPRESSION => { let call_expression = JsCallExpression::cast(node).unwrap(); let callee = call_expression.callee()?; - flatten_call_expression(queue, callee.syntax().clone(), formatter)?; - let formatted = vec![formatted![ - formatter, + flatten_call_expression(queue, callee.syntax().clone(), f)?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!( + buffer, [ call_expression.optional_chain_token().format(), call_expression.type_arguments().format(), call_expression.arguments().format() ] - ]?]; + )?; - queue.push(FlattenItem::CallExpression(call_expression, formatted)); + queue.push(FlattenItem::CallExpression( + call_expression, + buffer.into_vec(), + )); } JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION => { let static_member = JsStaticMemberExpression::cast(node).unwrap(); let object = static_member.object()?; - flatten_call_expression(queue, object.syntax().clone(), formatter)?; - let formatted = vec![formatted![ - formatter, + flatten_call_expression(queue, object.syntax().clone(), f)?; + + let mut buffer = VecBuffer::new(f.state_mut()); + let formatted = write![ + buffer, [ static_member.operator_token().format(), static_member.member().format(), ] - ]?]; - queue.push(FlattenItem::StaticMember(static_member, formatted)); + ]?; + queue.push(FlattenItem::StaticMember(static_member, buffer.into_vec())); } JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION => { let computed_expression = JsComputedMemberExpression::cast(node).unwrap(); let object = computed_expression.object()?; - flatten_call_expression(queue, object.syntax().clone(), formatter)?; - let formatted = vec![formatted!( - formatter, + flatten_call_expression(queue, object.syntax().clone(), f)?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!( + buffer, [ computed_expression.optional_chain_token().format(), computed_expression.l_brack_token().format(), computed_expression.member().format(), computed_expression.r_brack_token().format(), ] - )?]; + )?; queue.push(FlattenItem::ComputedExpression( computed_expression, - formatted, + buffer.into_vec(), )); } _ => { - let formatted = formatted![formatter, [node.format()]]?; - queue.push(FlattenItem::Node(node, formatted)); + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [node.format()])?; + queue.push(FlattenItem::Node(node, buffer.into_element())); } } diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index f3a6b9ef524..1d35ae20e48 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -12,7 +12,7 @@ use crate::prelude::*; pub(crate) use binary_like_expression::{format_binary_like_expression, JsAnyBinaryLikeExpression}; pub(crate) use format_conditional::{format_conditional, Conditional}; pub(crate) use member_chain::format_call_expression; -use rome_formatter::normalize_newlines; +use rome_formatter::{format_args, normalize_newlines, write, Buffer, VecBuffer}; use rome_js_syntax::suppression::{has_suppressions_category, SuppressionCategory}; use rome_js_syntax::{ JsAnyExpression, JsAnyFunction, JsAnyStatement, JsInitializerClause, JsLanguage, @@ -20,11 +20,10 @@ use rome_js_syntax::{ TsTemplateElementFields, TsType, }; use rome_js_syntax::{JsSyntaxKind, JsSyntaxNode, JsSyntaxToken}; -use rome_rowan::{AstNode, AstNodeList}; +use rome_rowan::{AstNode, AstNodeList, SyntaxResult, SyntaxToken}; use std::borrow::Cow; use std::fmt; -use crate::options::{JsFormatOptions, QuoteStyle}; pub(crate) use simple::*; pub(crate) use string_utils::*; @@ -34,41 +33,67 @@ pub(crate) use string_utils::*; /// We can have two kind of separators: `,`, `;` or ASI. /// Because of how the grammar crafts the nodes, the parent will add the separator to the node. /// So here, we create - on purpose - an empty node. -pub(crate) fn format_type_member_separator( - separator_token: Option, - formatter: &JsFormatter, -) -> FormatElement { - if let Some(separator) = separator_token { - formatter.format_replaced(&separator, empty_element()) - } else { - empty_element() +pub(crate) struct FormatTypeMemberSeparator<'a> { + token: Option<&'a JsSyntaxToken>, +} + +impl<'a> FormatTypeMemberSeparator<'a> { + pub fn new(token: Option<&'a JsSyntaxToken>) -> Self { + Self { token } + } +} + +impl Format for FormatTypeMemberSeparator<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(separator) = self.token { + write!(f, [f.format_replaced(&separator, &empty_element())]) + } else { + Ok(()) + } } } /// Utility function to format the node [rome_js_syntax::JsInitializerClause] -pub(crate) fn format_initializer_clause( - formatter: &JsFormatter, - initializer: Option, -) -> FormatResult { - formatted![ - formatter, - [initializer - .format() - .with_or_empty(|initializer| { formatted![formatter, [space_token(), initializer]] })] - ] +pub struct FormatInitializerClause<'a> { + initializer: Option<&'a JsInitializerClause>, } -pub(crate) fn format_interpreter( - interpreter: Option, - formatter: &JsFormatter, -) -> FormatResult { - formatted![ - formatter, - [interpreter.format().with_or( - |interpreter| formatted![formatter, [interpreter, empty_line()]], - empty_element, - )] - ] +impl<'a> FormatInitializerClause<'a> { + pub fn new(initializer: Option<&'a JsInitializerClause>) -> Self { + Self { initializer } + } +} + +impl Format for FormatInitializerClause<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(initializer) = self.initializer { + write!(f, [space_token(), initializer.format()]) + } else { + Ok(()) + } + } +} + +pub struct FormatInterpreterToken<'a> { + token: Option<&'a JsSyntaxToken>, +} + +impl<'a> FormatInterpreterToken<'a> { + pub fn new(interpreter_token: Option<&'a JsSyntaxToken>) -> Self { + Self { + token: interpreter_token, + } + } +} + +impl Format for FormatInterpreterToken<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(interpreter) = self.token { + write!(f, [interpreter.format(), empty_line()]) + } else { + Ok(()) + } + } } /// Returns true if this node contains "printable" trivias: comments @@ -124,18 +149,26 @@ pub(crate) fn has_leading_newline(node: &JsSyntaxNode) -> bool { /// /// This will place the head element inside a [hard_group_elements], but /// the body will broken out of flat printing if its a single statement -pub(crate) fn format_head_body_statement( - formatter: &JsFormatter, - head: FormatElement, - body: JsAnyStatement, -) -> FormatResult { - if matches!(body, JsAnyStatement::JsBlockStatement(_)) { - formatted![formatter, [head, space_token(), body.format(),]] - } else if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - // Force semicolon insertion if the body is empty - formatted![formatter, [head, body.format(), token(";"),]] - } else { - formatted![formatter, [head, space_token(), body.format(),]] +pub struct FormatBodyStatement<'a> { + body: &'a JsAnyStatement, +} + +impl<'a> FormatBodyStatement<'a> { + pub fn new(statement: &'a JsAnyStatement) -> Self { + Self { body: statement } + } +} + +impl Format for FormatBodyStatement<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + match self.body { + JsAnyStatement::JsEmptyStatement(body) => { + write!(f, [body.format(), token(";")]) + } + body => { + write!(f, [space_token(), body.format()]) + } + } } } @@ -158,28 +191,29 @@ where } /// Utility to format -pub(crate) fn format_template_chunk( - chunk: JsSyntaxToken, - formatter: &JsFormatter, -) -> FormatResult { +pub(crate) fn format_template_chunk(chunk: JsSyntaxToken, f: &mut JsFormatter) -> FormatResult<()> { // Per https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#sec-static-semantics-trv: // In template literals, the '\r' and '\r\n' line terminators are normalized to '\n' - Ok(formatter.format_replaced( - &chunk, - FormatElement::from(Token::from_syntax_token_cow_slice( - normalize_newlines(chunk.text_trimmed(), ['\r']), + + write!( + f, + [f.format_replaced( &chunk, - chunk.text_trimmed_range().start(), - )), - )) + &syntax_token_cow_slice( + normalize_newlines(chunk.text_trimmed(), ['\r']), + &chunk, + chunk.text_trimmed_range().start(), + ) + )] + ) } /// Function to format template literals and template literal types pub(crate) fn format_template_literal( literal: TemplateElement, - formatter: &JsFormatter, -) -> FormatResult { - literal.into_format_element(formatter) + formatter: &mut JsFormatter, +) -> FormatResult<()> { + write!(formatter, [literal]) } pub(crate) enum TemplateElement { @@ -187,53 +221,60 @@ pub(crate) enum TemplateElement { Ts(TsTemplateElement), } -impl TemplateElement { - pub fn into_format_element(self, formatter: &JsFormatter) -> FormatResult { +impl Format for TemplateElement { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { let expression_is_plain = self.is_plain_expression()?; let has_comments = self.has_comments(); let should_hard_group = expression_is_plain && !has_comments; - let (dollar_curly_token, middle, r_curly_token) = match self { - TemplateElement::Js(template_element) => { - let JsTemplateElementFields { - dollar_curly_token, - expression, - r_curly_token, - } = template_element.as_fields(); - - let dollar_curly_token = dollar_curly_token?; - let expression = formatted![formatter, [expression.format()]]?; - let r_curly_token = r_curly_token?; - - (dollar_curly_token, expression, r_curly_token) + let content = format_with(|f| { + match self { + TemplateElement::Js(template) => { + write!(f, [template.expression().format()])?; + } + TemplateElement::Ts(template) => { + write!(f, [template.ty().format()])?; + } } - TemplateElement::Ts(template_element) => { - let TsTemplateElementFields { - ty, - r_curly_token, - dollar_curly_token, - } = template_element.as_fields(); - - let dollar_curly_token = dollar_curly_token?; - let ty = formatted![formatter, [ty.format()]]?; - let r_curly_token = r_curly_token?; - (dollar_curly_token, ty, r_curly_token) - } - }; - - let middle = format_elements![middle, line_suffix_boundary()]; + write!(f, [line_suffix_boundary()]) + }); if should_hard_group { write!( - formatter, - [dollar_curly_token.format(), middle, r_curly_token.format()] - )?; + f, + [ + self.dollar_curly_token().format(), + content, + self.r_curly_token().format() + ] + ) } else { - formatter - .delimited(&dollar_curly_token, middle, &r_curly_token) - .soft_block_indent() - .finish() + write!( + f, + [f.delimited( + &self.dollar_curly_token()?, + &content, + &self.r_curly_token()? + ) + .soft_block_indent()] + ) + } + } +} + +impl TemplateElement { + fn dollar_curly_token(&self) -> SyntaxResult { + match self { + TemplateElement::Js(template) => template.dollar_curly_token(), + TemplateElement::Ts(template) => template.dollar_curly_token(), + } + } + + fn r_curly_token(&self) -> SyntaxResult { + match self { + TemplateElement::Js(template) => template.r_curly_token(), + TemplateElement::Ts(template) => template.r_curly_token(), } } @@ -362,27 +403,42 @@ impl FormatPrecedence { /// Format a some code followed by an optional semicolon, and performs /// semicolon insertion if it was missing in the input source and the /// preceeding element wasn't an unknown node -pub(crate) fn format_with_semicolon( - formatter: &mut JsFormatter, - content: FormatElement, - semicolon: Option, -) -> FormatResult<()> { - let is_unknown = match content.last_element() { - Some(FormatElement::Verbatim(elem)) => elem.is_unknown(), - _ => false, - }; +pub struct FormatWithSemicolon<'a> { + content: &'a dyn Format, + semicolon: Option<&'a JsSyntaxToken>, +} - write!( - formatter, - [ - content, - semicolon.format().or_format(if is_unknown { - |f| Ok(()) - } else { - |f| write!(f, [token(";")]) - }) - ] - ) +impl<'a> FormatWithSemicolon<'a> { + pub fn new( + content: &'a dyn Format, + semicolon: Option<&'a JsSyntaxToken>, + ) -> Self { + Self { content, semicolon } + } +} + +impl Format for FormatWithSemicolon<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.content])?; + + let content = buffer.into_document().into_element(); + + let is_unknown = match content.last_element() { + Some(FormatElement::Verbatim(elem)) => elem.is_unknown(), + _ => false, + }; + + f.write_element(content); + + if let Some(semicolon) = self.semicolon { + write!(f, [semicolon.format()])?; + } else if !is_unknown { + write!(f, [token(";")])?; + } + Ok(()) + } } /// A call like expression is one of: diff --git a/crates/rome_js_formatter/src/utils/string_utils.rs b/crates/rome_js_formatter/src/utils/string_utils.rs index 39b1c36e7f5..96a91f1f76f 100644 --- a/crates/rome_js_formatter/src/utils/string_utils.rs +++ b/crates/rome_js_formatter/src/utils/string_utils.rs @@ -1,6 +1,7 @@ use crate::context::QuoteStyle; use crate::prelude::*; use crate::utils::string_utils::CharSignal::AlreadyPrinted; +use rome_formatter::{format_args, write, Buffer}; use rome_js_syntax::JsSyntaxToken; use std::borrow::Cow; @@ -61,21 +62,21 @@ impl<'token> FormatLiteralStringToken<'token> { } } -impl Format for FormatLiteralStringToken<'_> { - type Context = JsFormatContext; - - fn format(&self, formatter: &JsFormatter) -> FormatResult { - let chosen_quote_style = formatter.state().quote_style(); +impl Format for FormatLiteralStringToken<'_> { + fn format(&self, f: &mut JsFormatter) -> FormatResult<()> { + let chosen_quote_style = f.context().quote_style(); let token = self.token(); let mut string_cleaner = LiteralStringNormaliser::new(self, chosen_quote_style); let content = string_cleaner.clean_text(); - Ok(formatter.format_replaced( - token, - Token::from_syntax_token_cow_slice(content, token, token.text_trimmed_range().start()) - .into(), - )) + write!( + f, + [f.format_replaced( + token, + &syntax_token_cow_slice(content, token, token.text_trimmed_range().start()) + )] + ) } } @@ -254,7 +255,7 @@ impl<'token> LiteralStringNormaliser<'token> { Cow::Owned(s) => { // content is owned, meaning we allocated a new string, // so we force replacing quotes, regardless - let final_content = format!( + let final_content = std::format!( "{}{}{}", preferred_quote.as_char(), s.as_str(), @@ -474,7 +475,7 @@ impl<'token> LiteralStringNormaliser<'token> { if raw_content_has_quotes { Cow::Borrowed(original_content) } else if original_content.starts_with(other_quote) { - Cow::Owned(format!( + Cow::Owned(std::format!( "{}{}{}", preferred_quote.as_char(), content_to_use.into(), @@ -508,7 +509,7 @@ mod tests { #[quickcheck] fn to_ascii_lowercase_cow_returns_owned_when_some_chars_are_not_lowercase(txt: AsciiString) { - let txt = format!("{}A", txt); //guarantees at least one uppercase letter + let txt = std::format!("{}A", txt); //guarantees at least one uppercase letter assert!(matches!(txt.to_ascii_lowercase_cow(), Cow::Owned(s) if s == txt.to_lowercase())); } } diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_function.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_function.js.snap.new new file mode 100644 index 00000000000..f811391df0d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_function.js.snap.new @@ -0,0 +1,31 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: arrow_function.js +--- +# Input +() => {} +async () => {} +(foo) => {} +(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,ccccccccccccccccccccccccccccc) => {} + + +() => (1,3,4); +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +() => {}; +async () => {}; +(foo) => {}; +( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, + ccccccccccccccccccccccccccccc, +) => {}; +() => (1, 3, 4); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap.new new file mode 100644 index 00000000000..81acded12de --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/arrow_nested.js.snap.new @@ -0,0 +1,89 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: arrow_nested.js +--- +# Input +Seq(typeDef.interface.groups).forEach(group => + Seq(group.members).forEach((member, memberName) => + markdownDoc( + member.doc, + { typePath: typePath.concat(memberName.slice(1)), + signatures: member.signatures } + ) + ) +) + +const promiseFromCallback = fn => + new Promise((resolve, reject) => + fn((err, result) => { + if (err) return reject(err); + return resolve(result); + }) + ); + +runtimeAgent.getProperties( + objectId, + false, // ownProperties + false, // accessorPropertiesOnly + false, // generatePreview + (error, properties, internalProperties) => { + return 1 + }, +); + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +Seq( + typeDef.interface.groups, +).forEach( + ( + group, + ) => + Seq( + group.members, + ).forEach( + ( + member, + memberName, + ) => + markdownDoc( + member.doc, + { + typePath: typePath.concat(memberName.slice(1)), + signatures: member.signatures, + }, + ), + ), +); +const promiseFromCallback = ( + fn, +) => + new Promise( + ( + resolve, + reject, + ) => + fn((err, result) => { + if (err) { + return reject(err); + } + return resolve(result); + },), + ); +runtimeAgent.getProperties( + objectId, + false, // ownProperties + false, // accessorPropertiesOnly + false, // generatePreview + (error, properties, internalProperties) => { + return 1; + }, +); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap.new new file mode 100644 index 00000000000..4e1fe97637b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/call.js.snap.new @@ -0,0 +1,118 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: call.js +--- +# Input +const testResults = results.testResults.map(testResult => + formatResult(testResult, formatter, reporter) + ); + +it('mocks regexp instances', () => { + expect( + // () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), + ).not.toThrow(); +}); + +expect(() => asyncRequest({ url: "/test-endpoint" })) + // .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ url: "/test-endpoint-but-with-a-long-url" })) + // .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ url: "/test-endpoint-but-with-a-suuuuuuuuper-long-url" })) + // .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ type: "foo", url: "/test-endpoint" })) + .not.toThrowError(); + +expect(() => asyncRequest({ type: "foo", url: "/test-endpoint-but-with-a-long-url" })) + .not.toThrowError(); + +const a = Observable + .fromPromise(axiosInstance.post('/carts/mine')) + .map((response) => response.data) + +const b = Observable.fromPromise(axiosInstance.get(url)) + .map((response) => response.data) + +func( + veryLoooooooooooooooooooooooongName, + veryLooooooooooooooooooooooooongName => + veryLoooooooooooooooongName.something() +); + +const composition = (ViewComponent, ContainerComponent) => + class extends React.Component { + static propTypes = {}; + }; + +romise.then(result => result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail"); + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +const testResults = results.testResults.map( + (testResult) => formatResult(testResult, formatter, reporter), +); +it( + "mocks regexp instances", + () => { + expect( + // () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), + ).not.toThrow(); + }, +); +expect(() => asyncRequest({ url: "/test-endpoint" })); +// .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ url: "/test-endpoint-but-with-a-long-url" })); +// .toThrowError(/Required parameter/); + +expect( + () => asyncRequest({ url: "/test-endpoint-but-with-a-suuuuuuuuper-long-url" }), +); +// .toThrowError(/Required parameter/); + +expect( + () => asyncRequest({ type: "foo", url: "/test-endpoint" }), +).not.toThrowError(); +expect( + () => asyncRequest({ type: "foo", url: "/test-endpoint-but-with-a-long-url" }), +).not.toThrowError(); +const a = Observable.fromPromise( + axiosInstance.post("/carts/mine"), +).map((response) => response.data); +const b = Observable.fromPromise( + axiosInstance.get(url), +).map((response) => response.data); +func( + veryLoooooooooooooooooooooooongName, + ( + veryLooooooooooooooooooooooooongName, + ) => veryLoooooooooooooooongName.something(), +); +const composition = ( + ViewComponent, + ContainerComponent, +) => + class extends React.Component { + static propTypes = {}; + }; +romise.then( + ( + result, + ) => + result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", +); + + +## Lines exceeding width of 80 characters + + 52: result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", + diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/currying.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/arrow/currying.js.snap.new new file mode 100644 index 00000000000..ad5eefa633b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/currying.js.snap.new @@ -0,0 +1,46 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: currying.js +--- +# Input +const fn = b => c => d => { + return 3; +}; + +const foo = (a, b) => c => d => { + return 3; +}; + +const bar = a => b => c => a + b + c + +const mw = store => next => action => { + return next(action) +} + +const middleware = options => (req, res, next) => { + // ... +}; + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +const fn = (b) => (c) => (d) => { + return 3; +}; +const foo = (a, b) => (c) => (d) => { + return 3; +}; +const bar = (a) => (b) => (c) => a + b + c; +const mw = (store) => (next) => (action) => { + return next(action); +}; +const middleware = (options) => (req, res, next) => { + // ... +}; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap.new new file mode 100644 index 00000000000..305f04e0800 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/arrow/params.js.snap.new @@ -0,0 +1,418 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: params.js +--- +# Input +fooooooooooooooooooooooooooooooooooooooooooooooooooo(action => next => + dispatch(action), +); + +foo( + ({ + a, + + b + }) => {} +); + +foo( + ({ + a, + b + + }) => {} +); + +foo( + ({ + a, + b + }) => {} +); + +foo( + a, + ({ + a, + + b + }) => {} +) + +foo( + ({ + a, + + b + }) => a +); + +foo( + ({ + a, + b + }) => a +); + +foo( + ({ + a, + b + + }) => a +); + +foo( + ({ + a: { + a, + + b + } + }) => {} +); + +foo( + ({ + a: { + b: { + c, + + d + } + } + }) => {} +); + +foo( + ({ + a: { + b: { + c: { + d, + + e + } + } + } + }) => {} +); + +foo( + ({ + a: { + a, + + b + } + }) => a +); + +foo( + ({ + a: { + b: { + c, + + d + } + } + }) => a +); + +foo( + ({ + a: { + b: { + c: { + d, + + e + } + } + } + }) => a +); + +foo( + ([ + { + a: { + b: { + c: { + d, + + e + } + } + } + } + ]) => {} +); + +foo( + ([ + ...{ + a: { + b: { + c: { + d, + + e + } + } + } + } + ]) => {} +); + +foo( + ( + n = { + a: { + b: { + c: { + d, + + e + } + } + } + } + ) => {} +); + +foo( + ({ + x: [ + { + a, + + b + } + ] + }) => {} +); + +foo( + ( + a = [ + { + a, + + b + } + ] + ) => a +); + +foo( + ([ + [ + { + a, + + b + } + ] + ]) => {} +); + +foo( + ([ + [ + [ + [ + { + a, + b: { + c, + d: { + e, + + f + } + } + } + ] + ] + ] + ]) => {} +); + +foo( + ( + ...{ + a, + + b + } + ) => {} +); + +foo( + ( + ...[ + { + a, + + b + } + ] + ) => {} +); + +foo( + ([ + ...[ + { + a, + + b + } + ] + ]) => {} +); + +foo( + ( + a = [{ + a, + + b + }] + ) => {} +); + +foo( + ( + a = (({ + a, + + b + }) => {})() + ) => {} +); + +foo( + ( + a = f({ + a, + + b + }) + ) => {} +); + +foo( + ( + a = ({ + a, + + b + }) => {} + ) => {} +); + +foo( + ( + a = 1 + + f({ + a, + + b + }) + ) => {} +); + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +fooooooooooooooooooooooooooooooooooooooooooooooooooo( + (action) => (next) => dispatch(action), +); +foo(({ a, b }) => {}); +foo(({ a, b }) => {}); +foo(({ a, b }) => {}); +foo(a, ({ a, b }) => {}); +foo(({ a, b }) => a); +foo(({ a, b }) => a); +foo(({ a, b }) => a); +foo(({ a: { a, b } }) => {}); +foo(({ a: { b: { c, d } } }) => {}); +foo(({ a: { b: { c: { d, e } } } }) => {}); +foo(({ a: { a, b } }) => a); +foo(({ a: { b: { c, d } } }) => a); +foo(({ a: { b: { c: { d, e } } } }) => a); +foo(([{ a: { b: { c: { d, e } } } }]) => {}); +foo(([...{ a: { b: { c: { d, e } } } }]) => {}); +foo( + ( + n = { + a: { + b: { + c: { + d, + + e, + }, + }, + }, + }, + ) => {}, +); +foo(({ x: [{ a, b }] }) => {}); +foo( + ( + a = [ + { + a, + + b, + }, + ], + ) => a, +); +foo(([[{ a, b }]]) => {}); +foo(([[[[{ a, b: { c, d: { e, f } } }]]]]) => {}); +foo((...{ a, b }) => {}); +foo((...[{ a, b }]) => {}); +foo(([...[{ a, b }]]) => {}); +foo( + ( + a = [ + { + a, + + b, + }, + ], + ) => {}, +); +foo((a = (({ a, b }) => {})()) => {}); +foo( + ( + a = f({ + a, + + b, + },), + ) => {}, +); +foo((a = ({ a, b }) => {}) => {}); +foo( + ( + a = 1 + f({ + a, + + b, + },), + ) => {}, +); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/assignment/assignment.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/assignment/assignment.js.snap.new new file mode 100644 index 00000000000..a3900728769 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/assignment/assignment.js.snap.new @@ -0,0 +1,79 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: assignment.js +--- +# Input +a = b +a += b +a -= b +a *= b +a /= b +a %= b +a <<= b +a >>= b +a >>>= b +a &= b +a |= b +a ^= b +a &&= b +a ||= b +a ??= b +a **= b +a.b = c.#d +a[ b ] = c[ d ] +;( a ) = b +;[a, b = "b", ...c] = d +;[fooooooooooooooooooooooooooooooooooooooooooooooooo, barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr, bazzzzzzzzzzzzzzzzzzzzzzzzzz] = d +;({a,b=c,d:e,f:g=h,...j} = x) +;({aaaaaaaaaa,bbbbbbbbbb=cccccccccc,dddddddddd:eeeeeeeeee,ffffffffff:gggggggggg=hhhhhhhhhh,...jjjjjjjjjj} = x); + +(s||(s=Object.create(null)))[i]=!0; +(s||(s=Object.create(null))).test=!0; + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +a = b; +a += b; +a -= b; +a *= b; +a /= b; +a %= b; +a <<= b; +a >>= b; +a >>>= b; +a &= b; +a |= b; +a ^= b; +a &&= b; +a ||= b; +a ??= b; +a **= b; +a.b = c.#d; +a[b] = c[d]; +(a) = b; +[a, b = "b", ...c] = d; +[ + fooooooooooooooooooooooooooooooooooooooooooooooooo, + barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr, + bazzzzzzzzzzzzzzzzzzzzzzzzzz, +] = d; +({ a, b = c, d: e, f: g = h, ...j } = x); +( + { + aaaaaaaaaa, + bbbbbbbbbb = cccccccccc, + dddddddddd: eeeeeeeeee, + ffffffffff: gggggggggg = hhhhhhhhhh, + ...jjjjjjjjjj + } = x +); +(s || (s = Object.create(null)))[i] = !0; +(s || (s = Object.create(null))).test = !0; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/binding/identifier_binding.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/binding/identifier_binding.js.snap.new new file mode 100644 index 00000000000..833bfcd9463 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/binding/identifier_binding.js.snap.new @@ -0,0 +1,22 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: identifier_binding.js +--- +# Input +let x = y + +let abcde = "very long value that will cause a line break", fghij = "this should end up on the next line" + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +let x = y; +let abcde = "very long value that will cause a line break", + fghij = "this should end up on the next line"; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/class/class.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/class/class.js.snap.new new file mode 100644 index 00000000000..4d2b7657700 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/class/class.js.snap.new @@ -0,0 +1,129 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: class.js +--- +# Input +class Foo extends Boar { + static { // some comment + this.a = "test"; + } + constructor(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, c = d) { + super(); + } + + static get sg() { + + } + + get g() { + + } + + set gg(a) { + + } + + method() { + return "ipsum"; + } + + async asyncMethod() {} + + * generatorMethod (){} + + static staticMethod() { + return "bar" + } + + async * asyncGeneratorMethod (){} + + static async staticAsyncMethod (){} + + static * staticGeneratorMethod (){} + + static async *staticAsyncGeneratorMethod() {} + + static foo; + + new_prop = 5 + + #a = b + + double_semicolon = [5,3,4];; +} + +x = class { +} + +x = class foo extends Boar { +} + +x = class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa extends bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb { +} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +class Foo extends Boar { + static { + this.a = // some comment + "test"; + } + constructor( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, + c = d, + ) { + super(); + } + + static get sg() {} + + get g() {} + + set gg(a) {} + + method() { + return "ipsum"; + } + + async asyncMethod() {} + + *generatorMethod() {} + + static staticMethod() { + return "bar"; + } + + async *asyncGeneratorMethod() {} + + static async staticAsyncMethod() {} + + static *staticGeneratorMethod() {} + + static async *staticAsyncGeneratorMethod() {} + + static foo; + + new_prop = 5; + + #a = b; + + double_semicolon = [5, 3, 4]; +} +x = class {}; +x = class foo extends Boar {}; +x = + class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa extends bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}; + + +## Lines exceeding width of 80 characters + + 51: class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa extends bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/class/class_comments.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/class/class_comments.js.snap.new new file mode 100644 index 00000000000..52a44230ad0 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/class/class_comments.js.snap.new @@ -0,0 +1,29 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: class_comments.js +--- +# Input +class A extends B { // leading comment + constructor() { + super(); + } + + // trailing comment +} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +class A extends B { + constructor() { + // leading comment + super(); + } + // trailing comment +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/export/class_clause.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/export/class_clause.js.snap.new new file mode 100644 index 00000000000..c62e5c50cef --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/export/class_clause.js.snap.new @@ -0,0 +1,30 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: class_clause.js +--- +# Input +// another comment +export class A { // small comment + constructor() { + } +} + + +export default class +B {} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +// another comment +export class A { + constructor() {} // small comment +} +export default class B {} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/export/from_clause.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/export/from_clause.js.snap.new new file mode 100644 index 00000000000..bfde7d22fff --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/export/from_clause.js.snap.new @@ -0,0 +1,31 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: from_clause.js +--- +# Input +export * from "hey" + +export * as something_bad_will_happen from "something_bad_might_not_happen" + +export * as something_bad_will_happen from "something_bad_might_not_happen" assert { "type": "json", "type2": "json3"} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +export * from "hey"; +export * as something_bad_will_happen from "something_bad_might_not_happen"; +export * as something_bad_will_happen from "something_bad_might_not_happen" assert { + "type": "json", + "type2": "json3", +}; + + +## Lines exceeding width of 80 characters + + 3: export * as something_bad_will_happen from "something_bad_might_not_happen" assert { + diff --git a/crates/rome_js_formatter/tests/specs/js/module/export/function_clause.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/export/function_clause.js.snap.new new file mode 100644 index 00000000000..04cec78e885 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/export/function_clause.js.snap.new @@ -0,0 +1,26 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: function_clause.js +--- +# Input +export function f() { + + +} + + +export default function ff() { + +} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +export function f() {} +export default function ff() {} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/export/variable_declaration.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/export/variable_declaration.js.snap.new new file mode 100644 index 00000000000..d82a3a15329 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/export/variable_declaration.js.snap.new @@ -0,0 +1,22 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: variable_declaration.js +--- +# Input +export let a, d, c; + +export const foofoofoofoofoofoofoo = "ahah", barbarbarbarbarbarbar = {}, loremloremloremloremlorem = [] +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +export let a, d, c; +export const foofoofoofoofoofoofoo = "ahah", + barbarbarbarbarbarbar = {}, + loremloremloremloremlorem = []; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/binary_expression.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/expression/binary_expression.js.snap.new new file mode 100644 index 00000000000..f768bd5b8b0 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/binary_expression.js.snap.new @@ -0,0 +1,70 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: binary_expression.js +--- +# Input +a + b +a < b +a > b +a <= b +a >= b +a == b +a === b +a != b +a !== b +a + b +a - b +a * b +a / b +a % b +a ** b +a << b +a >> b +a >>> b +a & b +a | b +a ^ b +a in b +a instanceof b + +a + b * c > 65; +a + b * c > 65 + 5; +2 > 65 << 5 + 3 >> 3; +2 > 4 + 4 * 24 % 3 << 23; +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +a + b; +a < b; +a > b; +a <= b; +a >= b; +a == b; +a === b; +a != b; +a !== b; +a + b; +a - b; +a * b; +a / b; +a % b; +a ** b; +a << b; +a >> b; +a >>> b; +a & b; +a | b; +a ^ b; +a in b; +a instanceof b; +(a + (b * c)) > 65; +(a + (b * c)) > (65 + 5); +2 > (65 << 5 + 3 >> 3); +2 > (4 + (4 * 24 % 3) << 23); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/conditional_expression.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/expression/conditional_expression.js.snap.new new file mode 100644 index 00000000000..8dde280918c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/conditional_expression.js.snap.new @@ -0,0 +1,43 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: conditional_expression.js +--- +# Input +a ? b : c +d + ? (e + f) + : (g + h) + +somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName + +somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName + +somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +a ? b : c; +d ? (e + f) : (g + h); +somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName; +somethingThatsAReallyLongPropName + ? somethingThatsAReallyLongPropName + ? somethingThatsAReallyLongPropName + : somethingThatsAReallyLongPropName + : somethingThatsAReallyLongPropName; +somethingThatsAReallyLongPropName + ? somethingThatsAReallyLongPropName + : somethingThatsAReallyLongPropName + ? somethingThatsAReallyLongPropName + : somethingThatsAReallyLongPropName; + + +## Lines exceeding width of 80 characters + + 3: somethingThatsAReallyLongPropName ? somethingThatsAReallyLongPropName : somethingThatsAReallyLongPropName; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/logical_expression.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/expression/logical_expression.js.snap.new new file mode 100644 index 00000000000..5b6d754e969 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/logical_expression.js.snap.new @@ -0,0 +1,302 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: logical_expression.js +--- +# Input +x ?? y; +x || y; +x && y; + + +lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem && lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem && lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem && lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem; + + +if (something && elsewhere && happy && thoughts && something && elsewhere && happy && thoughts && somethingsomethingsomethingsomethin) {} + +do { + +} while (something && elsewhere && happy && thoughts && something && elsewhere && happy && thoughts && somethingsomethingsomethingsomethin) + +switch (something && elsewhere && happy && thoughts && something && elsewhere && happy && thoughts && somethingsomethingsomethingsomethin) { + default: {} +} + +while (something && elsewhere && happy && thoughts && something && elsewhere && happy && thoughts && somethingsomethingsomethingsomethin) {} + +(something && elsewhere && happy && thoughts) + +function a() { + return something && elsewhere && happy && thoughts && somethingsomethingsomethingsomething && thoughts && somethingsomethingsomethingsomething; +} + +const a = () => aa && bb && +something && +somethingsomethingsomethingsomething; + +const a = () => aa && bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething && somethingsomethingsomethingsomething && somethingsomethingsomethingsomething; + + +const a = aa && bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething; + + +const a = x + y + + +{ something && lsewhere && +happy && +thoughts && dldldlldldldldldldldl && dldldlldldldldldldldl +} + +if ( somethingsomethingsomethingsomethin && somethingsomethingsomethingsomethin || somethingsomethingsomethingsomethin && somethingsomethingsomethingsomethin) {} + + +undefined === function () { + throw undefined; +}; + +const b = `${(veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFoo + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar)}`; + + +const a = + aa && + bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething || + aa && + bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething; + + +( + lorem && // foo + ipsum +); + +( + lorem && call_function(1, 3) // foo +); + +( + lorem && + // foo + (3 + 6 == 9) +); + + +let a = a || b && c; + +let foo = one && two || three && four || five && six; + +// Implicitly parenthesized && and || requires parens +foo && bar || baz; + + +a instanceof Number instanceof String instanceof Boolean instanceof Number instanceof String instanceof Boolean instanceof Number instanceof String instanceof Boolean; + +a in LongClassName in LongClassName in LongClassName in LongClassName in LongClassName in LongClassName in LongClassName in LongClassName in LongClassName; + + +veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFoo instanceof String && veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar instanceof Number || veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar instanceof Boolean + + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +x ?? y; +x || y; +x && y; +lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem && + lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem && + lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem && + lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem_lorem; +if ( + something && + elsewhere && + happy && + thoughts && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomethin +) { +} +do {} while ( + something && + elsewhere && + happy && + thoughts && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomethin +); +switch ( + something && + elsewhere && + happy && + thoughts && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomethin +) { + default: { + } +} +while ( + something && + elsewhere && + happy && + thoughts && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomethin +) {} +(something && elsewhere && happy && thoughts); +function a() { + return something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething && + thoughts && + somethingsomethingsomethingsomething; +} +const a = () => aa && bb && something && somethingsomethingsomethingsomething; +const a = () => + aa && + bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething && + somethingsomethingsomethingsomething && + somethingsomethingsomethingsomething; +const a = + aa && + bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething; +const a = x + y; +{ + something && + lsewhere && + happy && + thoughts && + dldldlldldldldldldldl && + dldldlldldldldldldldl; +} +if ( + ( + somethingsomethingsomethingsomethin && somethingsomethingsomethingsomethin + ) || ( + somethingsomethingsomethingsomethin && somethingsomethingsomethingsomethin + ) +) { +} +undefined === function () { + throw undefined; +}; +const b = `${ + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFoo + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar +}`; +const a = ( + aa && + bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething +) || ( + aa && + bb && + something && + elsewhere && + happy && + thoughts && + somethingsomethingsomethingsomething +); +( + lorem && // foo + ipsum +); +( + lorem && call_function(1, 3) // foo +); +( + lorem && + // foo + ((3 + 6) == 9) +); +let a = a || (b && c); +let foo = (one && two) || (three && four) || (five && six); +// Implicitly parenthesized && and || requires parens +(foo && bar) || baz; +a instanceof + Number instanceof + String instanceof + Boolean instanceof + Number instanceof + String instanceof + Boolean instanceof + Number instanceof + String instanceof + Boolean; +a in + LongClassName in + LongClassName in + LongClassName in + LongClassName in + LongClassName in + LongClassName in + LongClassName in + LongClassName in + LongClassName; +( + ( + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFoo instanceof String + ) && ( + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar instanceof Number + ) +) || ( + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar instanceof Boolean +); + + +## Lines exceeding width of 80 characters + + 106: veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongFoo + veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongBar + diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap.new new file mode 100644 index 00000000000..ad48d503ac9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/member-chain/inline-merge.js.snap.new @@ -0,0 +1,38 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: inline-merge.js +--- +# Input +_.flatMap(this.visibilityHandlers, fn => fn()) + .concat(this.record.resolved_legacy_visrules) + .filter(Boolean) + +Object + .keys( + availableLocales({ + test: true + }) +) + .forEach(locale => { + // ... + }); +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +_.flatMap(this.visibilityHandlers, (fn) => fn()) + .concat(this.record.resolved_legacy_visrules) + .filter(Boolean); +Object.keys( + availableLocales({ + test: true, + },), +).forEach((locale) => { + // ... +},); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/sequence_expression.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/expression/sequence_expression.js.snap.new new file mode 100644 index 00000000000..61e3b163f6b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/sequence_expression.js.snap.new @@ -0,0 +1,87 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: sequence_expression.js +--- +# Input +a,b + +const f = () => ( + ____________first, ____________second, ____________third, ____________third, ____________third, ____________third, ____________third + +); + +( + ____________first, ____________second, ____________third, ____________third, ____________third, ____________third, ____________third + +) + +function a() { + return ____________first, ____________second, ____________third, ____________third, ____________third, ____________third, ____________third +} + +const object ={ + something: ( + ____________first, ____________second, ____________third, ____________third, ____________third, ____________third, ____________third + ) + +} + +aLongIdentifierName, + aLongIdentifierName, + aLongIdentifierName, + aLongIdentifierName; +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +a, b; +const f = () => ( + ____________first, + ____________second, + ____________third, + ____________third, + ____________third, + ____________third, + ____________third +); +( + ____________first, + ____________second, + ____________third, + ____________third, + ____________third, + ____________third, + ____________third +); +function a() { + return ( + ____________first, + ____________second, + ____________third, + ____________third, + ____________third, + ____________third, + ____________third + ); +} +const object = { + something: ( + ____________first, + ____________second, + ____________third, + ____________third, + ____________third, + ____________third, + ____________third + ), +}; +aLongIdentifierName, + aLongIdentifierName, + aLongIdentifierName, + aLongIdentifierName; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/expression/static_member_expression.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/expression/static_member_expression.js.snap.new new file mode 100644 index 00000000000..e8fdd1bdf84 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/expression/static_member_expression.js.snap.new @@ -0,0 +1,45 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: static_member_expression.js +--- +# Input +a.b +a?.b +a.#b +a?.#b +a?.b.#c +a?.#b.c().d + +lorem.ipsum(); +lorem.ipsum().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong(); +lorem()[0]().ipsum().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong(); + + +something()[1]()[3]().items.item.what_else[3]().something().something().then().catcht().else().what_the_hell(); +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +a.b; +a?.b; +a.#b; +a?.#b; +a?.b.#c; +a?.#b.c().d; +lorem.ipsum(); +lorem.ipsum().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong(); +lorem()[0]().ipsum().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong(); +something()[1]()[3]().items.item.what_else[3]().something().something().then().catcht().else().what_the_hell(); + + +## Lines exceeding width of 80 characters + + 8: lorem.ipsum().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong(); + 9: lorem()[0]().ipsum().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong().looooooooooooooooooooooooooong(); + 10: something()[1]()[3]().items.item.what_else[3]().something().something().then().catcht().else().what_the_hell(); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap.new new file mode 100644 index 00000000000..f8141893a4a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/function/function.js.snap.new @@ -0,0 +1,75 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: function.js +--- +# Input +function foo() { +} +async function foo(a) { + await x +} +x = function() { +} +x = async function* foo(a) { +} +function Foo() { + if (!new.target) { } +} +function* Foo() { + yield + yield x + yield* x + yield aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + yield* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +} +function foo() { + let [ref, setRef] = useState(); + + useEffect(() => { + setRef() + }); + + return ref; +} + +function directives() { + "use strict"; +} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +function foo() {} +async function foo(a) { + await x; +} +x = function () {}; +x = async function* foo(a) {}; +function Foo() { + if (!new.target) { + } +} +function* Foo() { + yield; + yield x; + yield* x; + yield aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; + yield* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; +} +function foo() { + let [ref, setRef] = useState(); + useEffect(() => { + setRef(); + },); + return ref; +} +function directives() { + "use strict"; +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/import/bare_import.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/import/bare_import.js.snap.new new file mode 100644 index 00000000000..9f8f780cccd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/import/bare_import.js.snap.new @@ -0,0 +1,59 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: bare_import.js +--- +# Input +import "very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_"; +import "very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long" assert { type : "json"} +import "short" assert { + + type : "json" +} + +import "very_long_import_very_long_import_very" assert { + // something good is here + "type": /****/ "json" + } + +import "very_long_import_very_long_import_very" assert { + // something good is here + "type": /****/ "json", + "type2": /****/ "json", + "type3": /****/ "json", + "type4": /****/ "json", + "typetypetypetypetypetypetypetypetypetypetype": /****/ "typetypetypetypetypetypetypetypetypetypetypetypetypetype", + } +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +import "very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_"; +import "very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long" assert { + type: "json", +}; +import "short" assert { type: "json" }; +import "very_long_import_very_long_import_very" assert { + // something good is here + "type": /****/ "json", +}; +import "very_long_import_very_long_import_very" assert { + // something good is here + "type": /****/ "json", + "type2": /****/ "json", + "type3": /****/ "json", + "type4": /****/ "json", + "typetypetypetypetypetypetypetypetypetypetype": /****/ "typetypetypetypetypetypetypetypetypetypetypetypetypetype", +}; + + +## Lines exceeding width of 80 characters + + 1: import "very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_"; + 2: import "very_long_import_very_long_import_very_long_import_very_long_import_very_long_import_very_long" assert { + 16: "typetypetypetypetypetypetypetypetypetypetype": /****/ "typetypetypetypetypetypetypetypetypetypetypetypetypetype", + diff --git a/crates/rome_js_formatter/tests/specs/js/module/import/import_specifiers.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/import/import_specifiers.js.snap.new new file mode 100644 index 00000000000..93bc69a2ca0 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/import/import_specifiers.js.snap.new @@ -0,0 +1,64 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: import_specifiers.js +--- +# Input +import { hey } from "hey" +import { hey } from "hey"; +import { + apple, +banana } from "fruits"; +import {test} from "foo.json" assert { for: "for" } +import { // some funky comment + loooooooooooooooooooong as moreeeeeeloooooooooooooooooooong, + loooooooooooooooooooong2 as moreeeeeeloooooooooooooooooooong2, +// some other comment +} from "test"; +import { + loooooooooooooooooooong3 as moreeeeeeloooooooooooooooooooong3 + // some funky comment +} from "test"; + +import {loooooooooooooooooooong3,loooooooooooooooooooong5,loooooooooooooooooooong6 } from "boo" +import { f as x, default as w, "a-b-c" as y } from "b"; + +import loooooooooooooooooooong7, { loooooooooooooooooooong8, loooooooooooooooooooong9, loooooooooooooooooooong10} from "module" +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +import { hey } from "hey"; +import { hey } from "hey"; +import { apple, banana } from "fruits"; +import { test } from "foo.json" assert { for: "for" }; +import { + loooooooooooooooooooong as moreeeeeeloooooooooooooooooooong, // some funky comment + loooooooooooooooooooong2 as moreeeeeeloooooooooooooooooooong2, + // some other comment +} from "test"; +import { + loooooooooooooooooooong3 as moreeeeeeloooooooooooooooooooong3, + // some funky comment +} from "test"; +import { + loooooooooooooooooooong3, + loooooooooooooooooooong5, + loooooooooooooooooooong6, +} from "boo"; +import { f as x, default as w, "a-b-c" as y } from "b"; +import loooooooooooooooooooong7, { + loooooooooooooooooooong8, + loooooooooooooooooooong9, + loooooooooooooooooooong10, +} from "module"; + + +## Lines exceeding width of 80 characters + + 6: loooooooooooooooooooong as moreeeeeeloooooooooooooooooooong, // some funky comment + diff --git a/crates/rome_js_formatter/tests/specs/js/module/interpreter.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/interpreter.js.snap.new new file mode 100644 index 00000000000..8aabdd741ac --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/interpreter.js.snap.new @@ -0,0 +1,23 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: interpreter.js +--- +# Input +#!/usr/bin/env node +console.log(1) + +console.log(1) +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +#!/usr/bin/env node + +console.log(1); +console.log(1); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/invalid/block_stmt_err.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/invalid/block_stmt_err.js.snap.new new file mode 100644 index 00000000000..2a5bad8386f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/invalid/block_stmt_err.js.snap.new @@ -0,0 +1,34 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: block_stmt_err.js +--- +# Input +{ + let x= 10; + let y = 100; + + if (test) { + let z = 110; + } else +} + +let recovered = "no" + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +{ + let x = 10; + let y = 100; + if (test) { + let z = 110; + } else +} +let recovered = "no"; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/newlines.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/newlines.js.snap.new new file mode 100644 index 00000000000..42c359e11fa --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/newlines.js.snap.new @@ -0,0 +1,145 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: newlines.js +--- +# Input +"directive"; +// comment +"directive"; + +"directive"; + + +"directive"; + + +statement(); +// comment +statement(); + +statement(); + + +statement(); + + +; + + + +switch(a) { + case 1: + break; + // comment + case 2: + break; + + case 3: + break; + + + case 3: + break; + +} + + +class Test { + item; + // comment + item2; + + item3; + + + item4; + +} + + +const array = [ + 1, + // comment + 2, + + 3, + + + 4, + +]; + + +const object = { + key1: 1, + // comment + key2: 2, + + key3: 3, + + + key4: 4, + +}; + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +"directive"; +// comment +"directive"; +"directive"; +"directive"; + +statement(); +// comment +statement(); +statement(); +statement(); +switch (a) { + case 1: + break; + // comment + case 2: + break; + + case 3: + break; + + case 3: + break; +} +class Test { + item; + // comment + item2; + + item3; + + item4; +} +const array = [ + 1, + // comment + 2, + + 3, + + 4, +]; +const object = { + key1: 1, + // comment + key2: 2, + + key3: 3, + + key4: 4, +}; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/object/computed_member.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/object/computed_member.js.snap.new new file mode 100644 index 00000000000..ed95e74e8f0 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/object/computed_member.js.snap.new @@ -0,0 +1,72 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: computed_member.js +--- +# Input +const foo = {}; + +foo["bar"] = true; +foo["foo-bar"] = true; +foo.bar["bar"]["lorem_ispsum"].foo["lorem-ipsum"] = true; + +a[ b ] +c?.[ d ] + +x["very"]["long"]["chain"]["of"]["computed"]["members"]["that"]["goes"]["on"]["for"]["ever"]["I"]["mean"]["it"]["for"]["ever"]["and"]["even"]["longer"]["than"]["that"] + +x.very.long.chain.of.static.members.that.goes.on.for.ever.I.mean.it.for.ever["and"].even.longer.than.that.and["rofefefeeffeme"].doesnt.supportit + +x.very.long.chain.of.static.members.that.goes.on.for.ever.I.mean.it.for.ever[and()].even.longer.than.that.and["rofefefeefefme"].doesnt.supportit + +x[b["test"]] + + +a[("test")] + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +const foo = {}; +foo["bar"] = true; +foo["foo-bar"] = true; +foo.bar["bar"]["lorem_ispsum"].foo["lorem-ipsum"] = true; +a[b]; +c?.[d]; +x[ + "very" +][ + "long" +][ + "chain" +][ + "of" +][ + "computed" +][ + "members" +][ + "that" +][ + "goes" +][ + "on" +][ + "for" +][ + "ever" +]["I"]["mean"]["it"]["for"]["ever"]["and"]["even"]["longer"]["than"]["that"]; +x.very.long.chain.of.static.members.that.goes.on.for.ever.I.mean.it.for.ever[ + "and" +].even.longer.than.that.and["rofefefeeffeme"].doesnt.supportit; +x.very.long.chain.of.static.members.that.goes.on.for.ever.I.mean.it.for.ever[ + and() +].even.longer.than.that.and["rofefefeefefme"].doesnt.supportit; +x[b["test"]]; +a["test"]; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/object/object.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/object/object.js.snap.new new file mode 100644 index 00000000000..30bcb4a009c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/object/object.js.snap.new @@ -0,0 +1,73 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: object.js +--- +# Input +let a = { + ...spread, + + foo() { + }, + + *foo() { + }, + + async *foo(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccccccc) { + }, + + [fooooooooooooooooooooooooooooooooooooooooooooooooo()]: () => { + }, + + [foo()]: { + + }, + + ...spread, +} + +const x = {apple: "banana"}; + +const y = { + apple: "banana", +}; + +({a, b, c} = {a: 'apple', b: 'banana', c: 'coconut'}); + +({ + a, b, c} = {a: 'apple', b: 'banana', c: 'coconut'}); + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +let a = { + ...spread, + + foo() {}, + + *foo() {}, + + async *foo( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, + cccccccccccccccccccccccccccccc, + ) {}, + + [fooooooooooooooooooooooooooooooooooooooooooooooooo()]: () => {}, + + [foo()]: {}, + + ...spread, +}; +const x = { apple: "banana" }; +const y = { + apple: "banana", +}; +({ a, b, c } = { a: "apple", b: "banana", c: "coconut" }); +({ a, b, c } = { a: "apple", b: "banana", c: "coconut" }); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/object/object_comments.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/object/object_comments.js.snap.new new file mode 100644 index 00000000000..e901f68d765 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/object/object_comments.js.snap.new @@ -0,0 +1,23 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: object_comments.js +--- +# Input +let a = { // leading comment + "type": "bar" + // trailing comment +} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +let a = { + "type": "bar", // leading comment + // trailing comment +}; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/parentheses/parentheses.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/parentheses/parentheses.js.snap.new new file mode 100644 index 00000000000..03ccbe96d84 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/parentheses/parentheses.js.snap.new @@ -0,0 +1,65 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: parentheses.js +--- +# Input +(foo++)?.(); +async () => { + (await foo)?.(); +} +(+foo)?.(); ++(+foo); +class Foo extends (+Bar) {} +class Foo extends (Bar ?? Baz) {} +const foo = class extends (Bar ?? Baz) {} +;(1) +;(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); + +(b + c)``; + +const foo = { ...(a || b) }; + +async function *f() { + await (a || b); + yield (a && b); +} + +const a = () => ({}?.() && a); + +(list || list2)?.[(list || list2)]; +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +(foo++)?.(); +async () => { + (await foo)?.(); +}; +(+foo)?.(); ++(+foo); +class Foo extends (+Bar) {} +class Foo extends (Bar ?? Baz) {} +const foo = class extends (Bar ?? Baz) {}; +(1); +( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +); +(b + c)``; +const foo = { ...(a || b) }; +async function* f() { + await (a || b); + yield (a && b); +} +const a = () => ({}?.() && a); +(list || list2)?.[(list || list2)]; + + +## Lines exceeding width of 80 characters + + 12: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/do_while.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/do_while.js.snap.new new file mode 100644 index 00000000000..3a8a5b6488e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/do_while.js.snap.new @@ -0,0 +1,38 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: do_while.js +--- +# Input +do { +var foo = 4 +} + +while (something) + + +do { // trailing + var foo = 4 +} + +while (something) + + +do; while(true); +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +do { + var foo = 4; +} while (something); +do { + var foo = 4; // trailing +} while (something); +do; +while (true); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/empty_blocks.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/empty_blocks.js.snap.new new file mode 100644 index 00000000000..7c2cffd94db --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/empty_blocks.js.snap.new @@ -0,0 +1,73 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: empty_blocks.js +--- +# Input +// Line break before closing `}` +if (true) {} +if (true) {} else {} + +for (x in []) {} +for (x of []) {} + + + +switch ("test") {} + +switch ("test") { + case "test": {} +} + +test: {} + +try { +} catch { +} finally { +} + +// No Line breaks +class Test {} + +function test() {} + +for (;;) {} +while (true) {} +do {} while (true); +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +// Line break before closing `}` +if (true) { +} +if (true) { +} else { +} +for (x in []) { +} +for (x of []) { +} +switch ("test") { +} +switch ("test") { + case "test": { + } +} +test: { +} +try { +} catch { +} finally { +} +// No Line breaks +class Test {} +function test() {} +for (;;) {} +while (true) {} +do {} while (true); + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/for_in.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/for_in.js.snap.new new file mode 100644 index 00000000000..da33da5fa72 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/for_in.js.snap.new @@ -0,0 +1,34 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: for_in.js +--- +# Input +for (a in b) {} + +for (aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks in aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks) { +} + +for (a in b) { // trailing + } +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +for (a in b) { +} +for (aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks in aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks) { +} +for (a in b) { + // trailing +} + + +## Lines exceeding width of 80 characters + + 3: for (aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks in aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks) { + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/for_of.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/for_of.js.snap.new new file mode 100644 index 00000000000..768c3ce8e8a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/for_of.js.snap.new @@ -0,0 +1,37 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: for_of.js +--- +# Input +for (a of b) {} + +for (let a of b) {} + +for (const aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks of aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks) { +} + +for await ( const a of b ) {} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +for (a of b) { +} +for (let a of b) { +} +for (const aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks of aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks) { +} +for await (const a of b) { +} + + +## Lines exceeding width of 80 characters + + 5: for (const aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks of aVeryLongVariableNameToEnforceLineBreaksaVeryLongVariableNameToEnforceLineBreaks) { + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/if_chain.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/if_chain.js.snap.new new file mode 100644 index 00000000000..451a3f69c68 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/if_chain.js.snap.new @@ -0,0 +1,33 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: if_chain.js +--- +# Input +if(1)1;else if(2)2;else 3; + +if(very_long_condition_1) very_long_statement_1(); else if (very_long_condition_2) very_long_statement_2(); else very_long_statement_3(); + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +if (1) { + 1; +} else if (2) { + 2; +} else { + 3; +} +if (very_long_condition_1) { + very_long_statement_1(); +} else if (very_long_condition_2) { + very_long_statement_2(); +} else { + very_long_statement_3(); +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap.new new file mode 100644 index 00000000000..5f4bb43cf24 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/if_else.js.snap.new @@ -0,0 +1,126 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: if_else.js +--- +# Input +if(a); +if(a); else ; + +if (Math.random() > 0.5) { + console.log(1) +} else if (Math.random() > 0.5) { + console.log(2) +} else { + console.log(3) +} + +if (Math.random() > 0.5) { + console.log(1) +} +else if (Math.random() > 0.5) { + console.log(2) +} +else { + console.log(3) +} + +if (Math.random() > 0.5) { + console.log(1) +} +// wow +else if (Math.random() > 0.5) { + console.log(2) +} +// so cool +else { + console.log(3) +} + +if ( + true) { + let y = 20; +} else { + let x= 10; +} + +if (aVeryLongVeriableNameSoThatTheConditionBreaksAcrossMultipleLinesAndIDontKnow) { + + + +} else { + + +} + +if (true) { + + +} + +if (true) { + // trailing + +} else { // trailing + +} + +if (true) that(); else; + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +if (a); +if (a); +else; +if (Math.random() > 0.5) { + console.log(1); +} else if (Math.random() > 0.5) { + console.log(2); +} else { + console.log(3); +} +if (Math.random() > 0.5) { + console.log(1); +} else if (Math.random() > 0.5) { + console.log(2); +} else { + console.log(3); +} +if (Math.random() > 0.5) { + console.log(1); +} +// wow +else if (Math.random() > 0.5) { + console.log(2); +} +// so cool +else { + console.log(3); +} +if (true) { + let y = 20; +} else { + let x = 10; +} +if ( + aVeryLongVeriableNameSoThatTheConditionBreaksAcrossMultipleLinesAndIDontKnow +) { +} else { +} +if (true) { +} +if (true) { + // trailing +} else { + // trailing +} +if (true) { + that(); +} else; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/return.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/return.js.snap.new new file mode 100644 index 00000000000..90fd30a94d3 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/return.js.snap.new @@ -0,0 +1,28 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: return.js +--- +# Input +function f1() { + return 1 +} + +function f2() { + return 1,3,4 +} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +function f1() { + return 1; +} +function f2() { + return (1, 3, 4); +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/switch.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/switch.js.snap.new new file mode 100644 index 00000000000..05eba3ce686 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/switch.js.snap.new @@ -0,0 +1,51 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: switch.js +--- +# Input +switch (key) { + case // comment + value: + + case value: + // fallthrough + + case value: + break; + + default: + break; + + +} + +switch ("test") { + case "test": {} +} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +switch (key) { + case value: // comment + + case value: + // fallthrough + + case value: + break; + + default: + break; +} +switch ("test") { + case "test": { + } +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/throw.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/throw.js.snap.new new file mode 100644 index 00000000000..2279b385714 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/throw.js.snap.new @@ -0,0 +1,21 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: throw.js +--- +# Input +throw "Something"; + +throw false + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +throw "Something"; +throw false; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/try_catch_finally.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/try_catch_finally.js.snap.new new file mode 100644 index 00000000000..05ecfd3f874 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/try_catch_finally.js.snap.new @@ -0,0 +1,64 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: try_catch_finally.js +--- +# Input +try { + var foo = 4 +} catch { + var foo = 4 +} + +try { + var foo = 4 +} catch (e) { + var foo = 4 +} + + +try { + var foo = 4 +} finally { + var foo = 4 +} + +try { + var foo = 4 +} catch { + var foo = 4 +} finally { + var foo = 4 +} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +try { + var foo = 4; +} catch { + var foo = 4; +} +try { + var foo = 4; +} catch (e) { + var foo = 4; +} +try { + var foo = 4; +} finally { + var foo = 4; +} +try { + var foo = 4; +} catch { + var foo = 4; +} finally { + var foo = 4; +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/statement/while_loop.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/statement/while_loop.js.snap.new new file mode 100644 index 00000000000..78359b19bf4 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/statement/while_loop.js.snap.new @@ -0,0 +1,61 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: while_loop.js +--- +# Input +while (true) { var foo = 4 } + +while + + + ( + true + +) { var foo = 4; } +while (true) {} + +while (true) { + continue; +} + +tour: while (true) { + continue tour; +} + +while (true) { + break; +} + +tour: while (true) { + break tour; +} + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +while (true) { + var foo = 4; +} +while (true) { + var foo = 4; +} +while (true) {} +while (true) { + continue; +} +tour: while (true) { + continue tour; +} +while (true) { + break; +} +tour: while (true) { + break tour; +} + diff --git a/crates/rome_js_formatter/tests/specs/js/module/string/string.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/string/string.js.snap.new new file mode 100644 index 00000000000..93ada448d74 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/string/string.js.snap.new @@ -0,0 +1,189 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: string.js +--- +# Input +import hey from "hey" +import hey from "hey"; +import "x" assert { type: "json" } +import "foo" assert { "type": "json" }; +import foo from "foo.json" assert { type: "json" }; +import foo from "foo.json" assert { + + type: + "json" }; +import foo2 from "foo.json" assert { "type": "json", type: "html", "type": "js" }; +import a, * as b from "foo" + +const foo = {}; + +foo["bar"] = true; +foo["foo-bar"] = true; +foo.bar["bar"]["lorem_ispsum"].foo["lorem-ipsum"] = true; + +a[ b ] +c?.[ d ] + +let a = { // leading comment + "type": "bar" + // trailing comment +} + +class Foo extends Boar { + static { // some comment + this.a = "test"; + } + + method() { + return "ipsum"; + } + + static staticMethod() { + return "bar" + } +} + +export * from "hey" + +export * as something_bad_will_happen from "something_bad_might_not_happen" + +export * as something_bad_will_happen from "something_bad_might_not_happen" assert { "type": "json", "type2": "json3"} + + +// this one should switch to use single quotes +("content '' \"\"\" "); + +// this one should switch to use double quotes +('content \'\' " '); + +// you should keep all the character as they are +("content \\' \\' "); + +// you should remove the escape +("content \'\' ") +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +import hey from "hey"; +import hey from "hey"; +import "x" assert { type: "json" }; +import "foo" assert { "type": "json" }; +import foo from "foo.json" assert { type: "json" }; +import foo from "foo.json" assert { type: "json" }; +import foo2 from "foo.json" assert { + "type": "json", + type: "html", + "type": "js", +}; +import a, * as b from "foo"; +const foo = {}; +foo["bar"] = true; +foo["foo-bar"] = true; +foo.bar["bar"]["lorem_ispsum"].foo["lorem-ipsum"] = true; +a[b]; +c?.[d]; +let a = { + "type": "bar", // leading comment + // trailing comment +}; +class Foo extends Boar { + static { + this.a = // some comment + "test"; + } + + method() { + return "ipsum"; + } + + static staticMethod() { + return "bar"; + } +} +export * from "hey"; +export * as something_bad_will_happen from "something_bad_might_not_happen"; +export * as something_bad_will_happen from "something_bad_might_not_happen" assert { + "type": "json", + "type2": "json3", +}; +// this one should switch to use single quotes +('content \'\' """ '); +// this one should switch to use double quotes +("content '' \" "); +// you should keep all the character as they are +("content \\' \\' "); +// you should remove the escape +("content '' "); + + +## Lines exceeding width of 80 characters + + 39: export * as something_bad_will_happen from "something_bad_might_not_happen" assert { +## Output 2 +----- +Indent style: Tab +Line width: 80 +Quote style: Single Quotes +----- +import hey from 'hey'; +import hey from 'hey'; +import 'x' assert { type: 'json' }; +import 'foo' assert { 'type': 'json' }; +import foo from 'foo.json' assert { type: 'json' }; +import foo from 'foo.json' assert { type: 'json' }; +import foo2 from 'foo.json' assert { + 'type': 'json', + type: "html", + "type": "js", +}; +import a, * as b from 'foo'; +const foo = {}; +foo['bar'] = true; +foo['foo-bar'] = true; +foo.bar['bar']['lorem_ispsum'].foo['lorem-ipsum'] = true; +a[b]; +c?.[d]; +let a = { + 'type': 'bar', // leading comment + // trailing comment +}; +class Foo extends Boar { + static { + this.a = // some comment + 'test'; + } + + method() { + return 'ipsum'; + } + + static staticMethod() { + return 'bar'; + } +} +export * from 'hey'; +export * as something_bad_will_happen from 'something_bad_might_not_happen'; +export * as something_bad_will_happen from 'something_bad_might_not_happen' assert { + 'type': 'json', + 'type2': 'json3', +}; +// this one should switch to use single quotes +('content \'\' """ '); +// this one should switch to use double quotes +("content '' \" "); +// you should keep all the character as they are +("content \\' \\' "); +// you should remove the escape +("content '' "); + + +## Lines exceeding width of 80 characters + + 39: export * as something_bad_will_happen from 'something_bad_might_not_happen' assert { + diff --git a/crates/rome_js_formatter/tests/specs/js/module/suppression.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/suppression.js.snap.new new file mode 100644 index 00000000000..312d062a3bf --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/suppression.js.snap.new @@ -0,0 +1,68 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: suppression.js +--- +# Input +// rome-ignore format: the following if should print inline +if(true) statement(); + +/** rome-ignore format: the following if should print inline */ +if (true) statement(); + +/** + * rome-ignore format: the following if should print inline + */ +if (true) statement(); + +const expr = +// rome-ignore format: the array should not be formatted +[ + (2*n)/(r-l), 0, (r+l)/(r-l), 0, + 0, (2*n)/(t-b), (t+b)/(t-b), 0, + 0, 0, -(f+n)/(f-n), -(2*f*n)/(f-n), + 0, 0, -1, 0, +]; + +const expr2 = { + key: + // rome-ignore format: only skip formatting the value + 'single quoted string' +} + +let a = + // rome-ignore format: test +function () {} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +// rome-ignore format: the following if should print inline +if(true) statement(); +/** rome-ignore format: the following if should print inline */ +if (true) statement(); +/** + * rome-ignore format: the following if should print inline + */ +if (true) statement(); +const expr = +// rome-ignore format: the array should not be formatted +[ + (2*n)/(r-l), 0, (r+l)/(r-l), 0, + 0, (2*n)/(t-b), (t+b)/(t-b), 0, + 0, 0, -(f+n)/(f-n), -(2*f*n)/(f-n), + 0, 0, -1, 0, +]; +const expr2 = { + key: + // rome-ignore format: only skip formatting the value + 'single quoted string', +}; +let a = +// rome-ignore format: test +function () {}; + diff --git a/crates/rome_js_formatter/tests/specs/js/module/template/template.js.snap.new b/crates/rome_js_formatter/tests/specs/js/module/template/template.js.snap.new new file mode 100644 index 00000000000..2da444da905 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/module/template/template.js.snap.new @@ -0,0 +1,129 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: template.js +--- +# Input +`something`; + +tag`something` +`something ${ " hello" }`; + +`something ${ () => { var hey; const looooooooooong_expression = "loooooooooong_expression" }} something else ${ ehy }`; + `something ${ () => { var hey; const looooooooooong_expression = "loooooooooong_expression"; return hey; }} something else ${ ehy }`; + + +`test + abcd ${input} +output +`; + +`test + abcd ${ () => { var hey; const looooooooooong_expression = "loooooooooong_expression"; return hey; }} +output +`; + +// don't break +const bar =`but where will ${this.fanta} wrap ${baz} ${"hello"} template literal? ${bar.ff.sss} long long long long ${foo.[3]} long long long long long long`; + +const foo = `but where will ${a && b && bar || c && d && g} wrap long long long long long long`; + +const foo = `but where will ${lorem && loremlorem && loremlorem || loremc && lorem && loremlorem} wrap long long long long long long`; + +const a = ` +let expression_is_simple = is_plain_expression(&expression)?; +${loooooong || loooooong || loooooong || loooooong || loooooong || loooooong || loooooong || loooooong } +let expression_is_simple = is_plain_expression(&expression)?; +`; + +const foo = `but where will ${ + // with comment + this.fanta} wrap long long long long long long`; + +`
${this.set && this.set.artist + /* avoid console errors if `this.set` is undefined */}
`; + +`
${ /* avoid console errors if `this.set` is undefined */ + this.set && this.set.artist}
`; + +`${// $FlowFixMe found when converting React.createClass to ES6 +ExampleStory.getFragment('story')} +`; +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +`something`; +tag`something``something ${" hello"}`; +`something ${() => { + var hey; + const looooooooooong_expression = "loooooooooong_expression"; +}} something else ${ehy}`; +`something ${() => { + var hey; + const looooooooooong_expression = "loooooooooong_expression"; + return hey; +}} something else ${ehy}`; +`test + abcd ${input} +output +`; +`test + abcd ${() => { + var hey; + const looooooooooong_expression = "loooooooooong_expression"; + return hey; +}} +output +`; +// don't break +const bar =`but where will ${this.fanta} wrap ${baz} ${"hello"} template literal? ${bar.ff.sss} long long long long ${foo.[3]} long long long long long long`; +const foo = `but where will ${ + (a && b && bar) || (c && d && g) +} wrap long long long long long long`; +const foo = `but where will ${ + (lorem && loremlorem && loremlorem) || (loremc && lorem && loremlorem) +} wrap long long long long long long`; +const a = ` +let expression_is_simple = is_plain_expression(&expression)?; +${ + loooooong || + loooooong || + loooooong || + loooooong || + loooooong || + loooooong || + loooooong || + loooooong +} +let expression_is_simple = is_plain_expression(&expression)?; +`; +const foo = `but where will ${ + // with comment + this.fanta +} wrap long long long long long long`; +`
${ + this.set && this.set.artist + /* avoid console errors if `this.set` is undefined */ +}
`; +`
${ + /* avoid console errors if `this.set` is undefined */ this.set && this.set.artist +}
`; +`${ + ExampleStory.getFragment( + // $FlowFixMe found when converting React.createClass to ES6 + "story", + ) +} +`; + + +## Lines exceeding width of 80 characters + + 25: const bar =`but where will ${this.fanta} wrap ${baz} ${"hello"} template literal? ${bar.ff.sss} long long long long ${foo.[3]} long long long long long long`; + 55: /* avoid console errors if `this.set` is undefined */ this.set && this.set.artist + diff --git a/crates/rome_js_formatter/tests/specs/js/script/with.js.snap.new b/crates/rome_js_formatter/tests/specs/js/script/with.js.snap.new new file mode 100644 index 00000000000..a9ed54e3a49 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/js/script/with.js.snap.new @@ -0,0 +1,27 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: with.js +--- +# Input +with ( b) + +{ + 5 +} + +with({}) {} +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +with (b) { + 5; +} +with ({}) { +} + diff --git a/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap.new b/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap.new new file mode 100644 index 00000000000..cc794441f63 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/jsx/attributes.jsx.snap.new @@ -0,0 +1,116 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: attributes.jsx +--- +# Input + + ; + + ; + + let a = ; + + ; +
; + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +; +; +let a = ; +; +
; + + +## Lines exceeding width of 80 characters + + 9: fontFamily: "ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace", + 30: fontFamily: "ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace", + diff --git a/crates/rome_js_formatter/tests/specs/jsx/self_closing.jsx.snap.new b/crates/rome_js_formatter/tests/specs/jsx/self_closing.jsx.snap.new new file mode 100644 index 00000000000..d2569cfc116 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/jsx/self_closing.jsx.snap.new @@ -0,0 +1,37 @@ +--- +source: crates/rome_js_formatter/tests/spec_test.rs +assertion_line: 257 +expression: self_closing.jsx +--- +# Input +; + +; + +; +; +; + + + +============================= +# Outputs +## Output 1 +----- +Indent style: Tab +Line width: 80 +Quote style: Double Quotes +----- +; +; +; +; +; +; + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap.new new file mode 100644 index 00000000000..3367c5ec8b5 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-args.js.snap.new @@ -0,0 +1,42 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: numbers-in-args.js +--- +# Input +```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,76,41,65,84,35, + 97,90,75,24,88,45,23,75,63,86,24,39,9,51,33,40,58,17,49,86,63,59,97,91, + 98,99,5,69,51,44,34,69,17,91,27,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 + ] +); + +``` + +# Output +```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, + 76, 41, 65, 84, 35, 97, 90, 75, 24, 88, 45, 23, 75, 63, 86, 24, 39, 9, 51, 33, + 40, 58, 17, 49, 86, 63, 59, 97, 91, 98, 99, 5, 69, 51, 44, 34, 69, 17, 91, 27, + 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/arrays/numbers-in-assignment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-assignment.js.snap.new new file mode 100644 index 00000000000..4ccd21ab179 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-in-assignment.js.snap.new @@ -0,0 +1,42 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: numbers-in-assignment.js +--- +# Input +```js +bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers = [ + 1, + 2, + 3, + 4, + 5 +]; + +bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers2 = [ + 66,57,45,47,33,53,82,81,76,78,10,78,15,98,24,29,32,27,28,76,41,65,84,35, + 97,90,75,24,88,45,23,75,63,86,24,39,9,51,33,40,58,17,49,86,63,59,97,91, + 98,99,5,69,51,44,34,69,17,91,27,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 +]; + +``` + +# Output +```js +bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers = + [1, 2, 3, 4, 5]; +bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers2 = + [ + 66, 57, 45, 47, 33, 53, 82, 81, 76, 78, 10, 78, 15, 98, 24, 29, 32, 27, 28, + 76, 41, 65, 84, 35, 97, 90, 75, 24, 88, 45, 23, 75, 63, 86, 24, 39, 9, 51, + 33, 40, 58, 17, 49, 86, 63, 59, 97, 91, 98, 99, 5, 69, 51, 44, 34, 69, 17, + 91, 27, 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/arrays/numbers-negative-comment-after-minus.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative-comment-after-minus.js.snap.new new file mode 100644 index 00000000000..ac2305225e5 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative-comment-after-minus.js.snap.new @@ -0,0 +1,92 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: numbers-negative-comment-after-minus.js +--- +# Input +```js +const numbers = [-2017,-506252,-744011292,-7224,-70.4,-83353.6,-708.4,-174023963.52,-40385,-// comment1 +380014, +-253951682,-728,-15.84,-2058467564.56,-43,-33,-85134845,-67092,-1,-78820379,-2371.6,-16,7, +// comment2 +-62454,-4282239912, +-10816495.36,0.88,-100622682,8.8,-67087.68000000001,-3758276,-25.5211,-54,-1184265243,-46073628,-280423.44, +-41833463,-27961.12,-305.36,-199875.28]; + +c = [ + - /**/ 66, 66, 57, 45, 47, 33, 53, 82, 81, 76, 66, 57, 45, 47, 33, 53, 82, 81, 223323 +]; + +``` + +# Output +```js +const numbers = [ + -2017, + -506252, + -744011292, + -7224, + -70.4, + -83353.6, + -708.4, + -174023963.52, + -40385, + -380014, // comment1 + -253951682, + -728, + -15.84, + -2058467564.56, + -43, + -33, + -85134845, + -67092, + -1, + -78820379, + -2371.6, + -16, + 7, + // comment2 + -62454, + -4282239912, + -10816495.36, + 0.88, + -100622682, + 8.8, + -67087.68000000001, + -3758276, + -25.5211, + -54, + -1184265243, + -46073628, + -280423.44, + -41833463, + -27961.12, + -305.36, + -199875.28, +]; +c = + [ + - /**/ 66, + 66, + 57, + 45, + 47, + 33, + 53, + 82, + 81, + 76, + 66, + 57, + 45, + 47, + 33, + 53, + 82, + 81, + 223323, + ]; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative.js.snap.new new file mode 100644 index 00000000000..d00f0f42864 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-negative.js.snap.new @@ -0,0 +1,78 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: numbers-negative.js +--- +# Input +```js +const numbers1 = [-2017,-506252,-744011292,-7224,-70.4,-83353.6,-708.4,-174023963.52,-40385, +// comment1 +-380014, +-253951682,-728,-15.84,-2058467564.56,-43,-33,-85134845,-67092,-1,-78820379,-2371.6,-16,7, +// comment2 +-62454,-4282239912, +-10816495.36,0.88,-100622682,8.8,-67087.68000000001,-3758276,-25.5211,-54,-1184265243,-46073628,-280423.44, +-41833463,-27961.12,-305.36,-199875.28]; + +const numbers2 = [-234, -342 // comment3 +, -223, -333333.33,12345] + +``` + +# Output +```js +const numbers1 = [ + -2017, + -506252, + -744011292, + -7224, + -70.4, + -83353.6, + -708.4, + -174023963.52, + -40385, + // comment1 + -380014, + -253951682, + -728, + -15.84, + -2058467564.56, + -43, + -33, + -85134845, + -67092, + -1, + -78820379, + -2371.6, + -16, + 7, + // comment2 + -62454, + -4282239912, + -10816495.36, + 0.88, + -100622682, + 8.8, + -67087.68000000001, + -3758276, + -25.5211, + -54, + -1184265243, + -46073628, + -280423.44, + -41833463, + -27961.12, + -305.36, + -199875.28, +]; +const numbers2 = [ + -234, + -342, // comment3 + -223, + -333333.33, + 12345, +]; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-with-holes.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-with-holes.js.snap.new new file mode 100644 index 00000000000..cd26ef43cd8 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers-with-holes.js.snap.new @@ -0,0 +1,72 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: numbers-with-holes.js +--- +# Input +```js +const numberWithHoles1 = [ + 7234932941, + 7234932722, + 7234932312, + // comment before a hole 1 + , + 7234932841, + , + 7234932843, + , + // comment after a hole 1 + 7234932436, +]; + +const numberWithHoles2 = [ + 0x234932941, + 0x234932722, + 0x234932312, + + // comment before a hole 2 + , + 0x234932841, + , + 0x234932843, + , + + // comment after a hole 2 + 0x234932436, +]; + +``` + +# Output +```js +const numberWithHoles1 = [ + 7234932941, + 7234932722, + 7234932312, + // comment before a hole 1 + , + 7234932841, + , + 7234932843, + , + // comment after a hole 1 + 7234932436, +]; +const numberWithHoles2 = [ + 0x234932941, + 0x234932722, + 0x234932312, + // comment before a hole 2 + , + 0x234932841, + , + 0x234932843, + , + + // comment after a hole 2 + 0x234932436, +]; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers2.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers2.js.snap.new new file mode 100644 index 00000000000..8f62dcbc578 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrays/numbers2.js.snap.new @@ -0,0 +1,98 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: numbers2.js +--- +# Input +```js +const userIds1 = [ + 7234932941, + 7234932722, + 7234932312, + 7234932933, +]; + +const userIds2 = [ + 7234932941, + 7234932722, + 7234932312, + 7234932933, + 7234932841, + 7234932166, + 7234932843, + 7234932978, + 7234932436, +]; + +const userIds3 = [ + 7234932941, + 7234932722, + 7234932312, + 7234932933, + 7234932841, + 7234932166, + 7234932843, + + 7234932978, + 7234932436, +]; + +const userIds4 = [ + 7234932941, + 7234932722, + 7234932312, + 7234932933, + 7234932841, + 7234932166, + // comment 1 + 7234932843, + + 7234932978, + + // comment 2 + 7234932436, + // comment 3 +]; + + +``` + +# Output +```js +const userIds1 = [7234932941, 7234932722, 7234932312, 7234932933]; +const userIds2 = [ + 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, + 7234932843, 7234932978, 7234932436, +]; +const userIds3 = [ + 7234932941, + 7234932722, + 7234932312, + 7234932933, + 7234932841, + 7234932166, + 7234932843, + + 7234932978, + 7234932436, +]; +const userIds4 = [ + 7234932941, + 7234932722, + 7234932312, + 7234932933, + 7234932841, + 7234932166, + // comment 1 + 7234932843, + + 7234932978, + + // comment 2 + 7234932436, + // comment 3 +]; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/arrow-call/arrow_call.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/arrow-call/arrow_call.js.snap.new new file mode 100644 index 00000000000..6492fb9251d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/arrow-call/arrow_call.js.snap.new @@ -0,0 +1,105 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: arrow_call.js +--- +# Input +```js +const testResults = results.testResults.map(testResult => + formatResult(testResult, formatter, reporter) +); + +it('mocks regexp instances', () => { + expect( + () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), + ).not.toThrow(); +}); + +expect(() => asyncRequest({ url: "/test-endpoint" })) + .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ url: "/test-endpoint-but-with-a-long-url" })) + .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ url: "/test-endpoint-but-with-a-suuuuuuuuper-long-url" })) + .toThrowError(/Required parameter/); + +expect(() => asyncRequest({ type: "foo", url: "/test-endpoint" })) + .not.toThrowError(); + +expect(() => asyncRequest({ type: "foo", url: "/test-endpoint-but-with-a-long-url" })) + .not.toThrowError(); + +const a = Observable + .fromPromise(axiosInstance.post('/carts/mine')) + .map((response) => response.data) + +const b = Observable.fromPromise(axiosInstance.get(url)) + .map((response) => response.data) + +func( + veryLoooooooooooooooooooooooongName, + veryLooooooooooooooooooooooooongName => + veryLoooooooooooooooongName.something() +); + +promise.then(result => result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail"); + +``` + +# Output +```js +const testResults = results.testResults.map( + (testResult) => formatResult(testResult, formatter, reporter), +); +it( + "mocks regexp instances", + () => { + expect( + () => moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)), + ).not.toThrow(); + }, +); +expect( + () => asyncRequest({ url: "/test-endpoint" }), +).toThrowError(/Required parameter/); +expect( + () => asyncRequest({ url: "/test-endpoint-but-with-a-long-url" }), +).toThrowError(/Required parameter/); +expect( + () => + asyncRequest({ url: "/test-endpoint-but-with-a-suuuuuuuuper-long-url" },), +).toThrowError(/Required parameter/); +expect( + () => asyncRequest({ type: "foo", url: "/test-endpoint" }), +).not.toThrowError(); +expect( + () => + asyncRequest({ type: "foo", url: "/test-endpoint-but-with-a-long-url" },), +).not.toThrowError(); +const a = Observable.fromPromise( + axiosInstance.post("/carts/mine"), +).map((response) => response.data); +const b = Observable.fromPromise( + axiosInstance.get(url), +).map((response) => response.data); +func( + veryLoooooooooooooooooooooooongName, + ( + veryLooooooooooooooooooooooooongName, + ) => veryLoooooooooooooooongName.something(), +); +promise.then( + ( + result, + ) => + result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", +); + +``` + +# Lines exceeding max width of 80 characters +``` + 45: result.veryLongVariable.veryLongPropertyName > someOtherVariable ? "ok" : "fail", +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/function.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/function.js.snap.new new file mode 100644 index 00000000000..6d9a052f23a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/function.js.snap.new @@ -0,0 +1,121 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: function.js +--- +# Input +```js +f1 = ( + a = + //comment + b +) => {}; + +f2 = ( + a = //comment + b +) => {}; + +f3 = ( + a = + b //comment +) => {}; + +f4 = // Comment + () => {}; + +f5 = + + // Comment + + () => {} + +f6 = /* comment */ + + // Comment + + () => {} + +let f1 = ( + a = + //comment + b +) => {}; + +let f2 = ( + a = //comment + b +) => {}; + +let f3 = ( + a = + b //comment +) => {}; + +let f4 = // Comment + () => {}; + +let f5 = + + // Comment + + () => {} + +let f6 = /* comment */ + + // Comment + + () => {} + +``` + +# Output +```js +f1 = + ( + a = + //comment + b, + ) => {}; +f2 = + ( + a = b, //comment + ) => {}; +f3 = + ( + a = b, //comment + ) => {}; +f4 = // Comment +() => {}; +f5 = + // Comment + + () => {}; +f6 = /* comment */ + // Comment + + () => {}; +let f1 = ( + a = + //comment + b, +) => {}; +let f2 = ( + a = b, //comment +) => {}; +let f3 = ( + a = b, //comment +) => {}; +let f4 = () => {}; // Comment +let f5 = +// Comment + +() => {}; +let f6 = /* comment */ +// Comment + +() => {}; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/identifier.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/identifier.js.snap.new new file mode 100644 index 00000000000..d217f86a172 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment-comments/identifier.js.snap.new @@ -0,0 +1,29 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: identifier.js +--- +# Input +```js +const kochabCooieGameOnOboleUnweave = // ??? + annularCooeedSplicesWalksWayWay; + +const bifornCringerMoshedPerplexSawder = // !!! + glimseGlyphsHazardNoopsTieTie + + averredBathersBoxroomBuggyNurl - + anodyneCondosMalateOverateRetinol; + +``` + +# Output +```js +const kochabCooieGameOnOboleUnweave = annularCooeedSplicesWalksWayWay; // ??? +const bifornCringerMoshedPerplexSawder = glimseGlyphsHazardNoopsTieTie + averredBathersBoxroomBuggyNurl - anodyneCondosMalateOverateRetinol; // !!! + +``` + +# Lines exceeding max width of 80 characters +``` + 2: const bifornCringerMoshedPerplexSawder = glimseGlyphsHazardNoopsTieTie + averredBathersBoxroomBuggyNurl - anodyneCondosMalateOverateRetinol; // !!! +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/binaryish.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/binaryish.js.snap.new new file mode 100644 index 00000000000..b07cb7893e9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/binaryish.js.snap.new @@ -0,0 +1,43 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: binaryish.js +--- +# Input +```js +const computedDescriptionLines = (showConfirm && + descriptionLinesConfirming) || + (focused && !loading && descriptionLinesFocused) || + descriptionLines; + +const computedDescriptionLines2 = (showConfirm && // comment + descriptionLinesConfirming) || // comment + (focused && !loading && descriptionLinesFocused) || // comment + descriptionLines // comment + +computedDescriptionLines = (focused && + !loading && + descriptionLinesFocused) || + descriptionLines; + +``` + +# Output +```js +const computedDescriptionLines = + (showConfirm && descriptionLinesConfirming) || + (focused && !loading && descriptionLinesFocused) || + descriptionLines; +const computedDescriptionLines2 = + ( + showConfirm && // comment + descriptionLinesConfirming + ) || // comment + (focused && !loading && descriptionLinesFocused) || // comment + descriptionLines; // comment +computedDescriptionLines = + (focused && !loading && descriptionLinesFocused) || descriptionLines; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap.new new file mode 100644 index 00000000000..05616e42845 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/call-with-template.js.snap.new @@ -0,0 +1,38 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: call-with-template.js +--- +# Input +```js +const result = template(` + if (SOME_VAR === "") {} +`)({ + SOME_VAR: value, +}); + +const output = + template(`function f() %%A%%`)({ + A: t.blockStatement([]), + }); + +``` + +# Output +```js +const result = template( + ` + if (SOME_VAR === "") {} +`, +)({ + SOME_VAR: value, +},); +const output = template( + `function f() %%A%%`, +)({ + A: t.blockStatement([]), +},); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/chain.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/chain.js.snap.new new file mode 100644 index 00000000000..45507afb033 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/chain.js.snap.new @@ -0,0 +1,72 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: chain.js +--- +# Input +```js +let bifornCringerMoshedPerplexSawder= +askTrovenaBeenaDependsRowans= +glimseGlyphsHazardNoopsTieTie= +averredBathersBoxroomBuggyNurl= +anodyneCondosMalateOverateRetinol= +annularCooeedSplicesWalksWayWay= +kochabCooieGameOnOboleUnweave; + +bifornCringerMoshedPerplexSawder = + askTrovenaBeenaDependsRowans = + glimseGlyphsHazardNoopsTieTie = + x = + averredBathersBoxroomBuggyNurl = + anodyneCondosMal(sdsadsa,dasdas,asd(()=>sdf)).ateOverateRetinol = + annularCooeedSplicesWalksWayWay = + kochabCooieGameOnOboleUnweave; + +bifornCringerMoshedPerplexSawder = + askTrovenaBeenaDependsRowans = + glimseGlyphsHazardNoopsTieTie = + x = + averredBathersBoxroomBuggyNurl = + anodyneCondosMal(sdsadsa,dasdas,asd(()=>sdf)).ateOverateRetinol = + annularCooeedSplicesWalksWayWay = + kochabCooieGameOnOboleUnweave+kochabCooieGameOnOboleUnweave; + +a=b=c; + +``` + +# Output +```js +let bifornCringerMoshedPerplexSawder = askTrovenaBeenaDependsRowans = + glimseGlyphsHazardNoopsTieTie = + averredBathersBoxroomBuggyNurl = + anodyneCondosMalateOverateRetinol = + annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave; +bifornCringerMoshedPerplexSawder = + askTrovenaBeenaDependsRowans = + glimseGlyphsHazardNoopsTieTie = + x = + averredBathersBoxroomBuggyNurl = + anodyneCondosMal( + sdsadsa, + dasdas, + asd(() => sdf), + ).ateOverateRetinol = + annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave; +bifornCringerMoshedPerplexSawder = + askTrovenaBeenaDependsRowans = + glimseGlyphsHazardNoopsTieTie = + x = + averredBathersBoxroomBuggyNurl = + anodyneCondosMal( + sdsadsa, + dasdas, + asd(() => sdf), + ).ateOverateRetinol = + annularCooeedSplicesWalksWayWay = + kochabCooieGameOnOboleUnweave + kochabCooieGameOnOboleUnweave; +a = b = c; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring-heuristic.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring-heuristic.js.snap.new new file mode 100644 index 00000000000..7add79cf92b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring-heuristic.js.snap.new @@ -0,0 +1,67 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: destructuring-heuristic.js +--- +# Input +```js +{{ + const { + id, + static: isStatic, + method: isMethod, + methodId, + getId, + setId, + } = privateNamesMap.get(name); + + const { + id1, + method: isMethod1, + methodId1 + } = privateNamesMap.get(name); + + const { + id2, + method: isMethod2, + methodId2 + } = privateNamesMap.get(bifornCringerMoshedPerplexSawder); + + const { + id3, + method: isMethod3, + methodId3 + } = anodyneCondosMalateOverateRetinol.get(bifornCringerMoshedPerplexSawder); +}} + +``` + +# Output +```js +{ + { + const { + id, + static: isStatic, + method: isMethod, + methodId, + getId, + setId, + } = privateNamesMap.get(name); + const { id1, method: isMethod1, methodId1 } = privateNamesMap.get(name); + const { + id2, + method: isMethod2, + methodId2, + } = privateNamesMap.get(bifornCringerMoshedPerplexSawder); + const { + id3, + method: isMethod3, + methodId3, + } = anodyneCondosMalateOverateRetinol.get(bifornCringerMoshedPerplexSawder); + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring.js.snap.new new file mode 100644 index 00000000000..32b452f34e0 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/destructuring.js.snap.new @@ -0,0 +1,40 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: destructuring.js +--- +# Input +```js +let { + bottom: offsetBottom, + left: offsetLeft, + right: offsetRight, + top: offsetTop, +} = getPressRectOffset == null ? DEFAULT_PRESS_RECT : getPressRectOffset(); + +const { accessibilityModule: FooAccessibilityModule, accessibilityModule: FooAccessibilityModule2, accessibilityModule: FooAccessibilityModule3, accessibilityModule: FooAccessibilityModule4, + } = foo || {}; + +({ prop: toAssign = "default" } = { prop: "propval" }); + +``` + +# Output +```js +let { + bottom: offsetBottom, + left: offsetLeft, + right: offsetRight, + top: offsetTop, +} = getPressRectOffset == null ? DEFAULT_PRESS_RECT : getPressRectOffset(); +const { + accessibilityModule: FooAccessibilityModule, + accessibilityModule: FooAccessibilityModule2, + accessibilityModule: FooAccessibilityModule3, + accessibilityModule: FooAccessibilityModule4, +} = foo || {}; +({ prop: toAssign = "default" } = { prop: "propval" }); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-10218.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-10218.js.snap.new new file mode 100644 index 00000000000..64441879da4 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-10218.js.snap.new @@ -0,0 +1,34 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-10218.js +--- +# Input +```js +const _id1 = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty._id; + +const {_id2} = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; + +const {_id:id3} = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; + +``` + +# Output +```js +const _id1 = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty._id; +const { + _id2, +} = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; +const { + _id: id3, +} = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; + +``` + +# Lines exceeding max width of 80 characters +``` + 1: const _id1 = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty._id; + 4: } = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; + 7: } = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-1966.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-1966.js.snap.new new file mode 100644 index 00000000000..69073a3b666 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-1966.js.snap.new @@ -0,0 +1,30 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-1966.js +--- +# Input +```js +const aVeryLongNameThatGoesOnAndOn = this.someOtherObject.someOtherNestedObject.someLongFunctionName(); + +this.someObject.someOtherNestedObject = this.someOtherObject.whyNotNestAnotherOne.someLongFunctionName(); + +this.isaverylongmethodexpression.withmultiplelevels = this.isanotherverylongexpression.thatisalsoassigned = 0; + +``` + +# Output +```js +const aVeryLongNameThatGoesOnAndOn = this.someOtherObject.someOtherNestedObject.someLongFunctionName(); +this.someObject.someOtherNestedObject = + this.someOtherObject.whyNotNestAnotherOne.someLongFunctionName(); +this.isaverylongmethodexpression.withmultiplelevels = + this.isanotherverylongexpression.thatisalsoassigned = 0; + +``` + +# Lines exceeding max width of 80 characters +``` + 1: const aVeryLongNameThatGoesOnAndOn = this.someOtherObject.someOtherNestedObject.someLongFunctionName(); +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-2482-1.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-2482-1.js.snap.new new file mode 100644 index 00000000000..ed63d9609cf --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-2482-1.js.snap.new @@ -0,0 +1,41 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-2482-1.js +--- +# Input +```js +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes; + +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + 'a very long string for illustrative purposes'.length; + +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes(); + +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes.length; + +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes + 1; + + +``` + +# Output +```js +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes; +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + "a very long string for illustrative purposes".length; +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes(); +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes.length; +aParticularlyLongAndObnoxiousNameForIllustrativePurposes = + anotherVeryLongNameForIllustrativePurposes + 1; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap.new new file mode 100644 index 00000000000..489f710ef75 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-6922.js.snap.new @@ -0,0 +1,69 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-6922.js +--- +# Input +```js +async function f() { + const { data, status } = await request.delete( + `/account/${accountId}/documents/${type}/${documentNumber}`, + { validateStatus: () => true } + ); + return { data, status }; +} + +const data1 = request.delete( + '----------------------------------------------', + { validateStatus: () => true } +); + +const data2 = request.delete( + '----------------------------------------------x', + { validateStatus: () => true } +); + +const data3 = request.delete( + '----------------------------------------------xx', + { validateStatus: () => true } +); + +const data4 = request.delete( + '----------------------------------------------xxx', + { validateStatus: () => true } +); + +``` + +# Output +```js +async function f() { + const { + data, + status, + } = await request.delete( + `/account/${accountId}/documents/${type}/${documentNumber}`, + { validateStatus: () => true }, + ); + return { data, status }; +} +const data1 = request.delete( + "----------------------------------------------", + { validateStatus: () => true }, +); +const data2 = request.delete( + "----------------------------------------------x", + { validateStatus: () => true }, +); +const data3 = request.delete( + "----------------------------------------------xx", + { validateStatus: () => true }, +); +const data4 = request.delete( + "----------------------------------------------xxx", + { validateStatus: () => true }, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-7961.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-7961.js.snap.new new file mode 100644 index 00000000000..8233d6137d1 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-7961.js.snap.new @@ -0,0 +1,27 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-7961.js +--- +# Input +```js +// works as expected +something.veeeeeery.looooooooooooooooooooooooooong = some.other.rather.long.chain; + +// does not work if it ends with a function call +something.veeeeeery.looooooooooooooooooooooooooong = some.other.rather.long.chain.functionCall(); + +``` + +# Output +```js +// works as expected +something.veeeeeery.looooooooooooooooooooooooooong = + some.other.rather.long.chain; +// does not work if it ends with a function call +something.veeeeeery.looooooooooooooooooooooooooong = + some.other.rather.long.chain.functionCall(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-8218.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-8218.js.snap.new new file mode 100644 index 00000000000..88364ea31e6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/issue-8218.js.snap.new @@ -0,0 +1,27 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-8218.js +--- +# Input +```js +const pendingIndicators = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues; + +const pendingIndicatorz = + shield.alarmGeneratorConfiguration.getPendingVersionColumnValues(); + +``` + +# Output +```js +const pendingIndicators = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues; +const pendingIndicatorz = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues(); + +``` + +# Lines exceeding max width of 80 characters +``` + 1: const pendingIndicators = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues; + 2: const pendingIndicatorz = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues(); +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap.new new file mode 100644 index 00000000000..2a94a12d4df --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/lone-arg.js.snap.new @@ -0,0 +1,53 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: lone-arg.js +--- +# Input +```js +let vgChannel = pointPositionDefaultRef({ + model, + defaultPos, + channel, +})() + +let vgChannel2 = pointPositionDefaultRef({ model, + defaultPos, + channel, +})() + +const bifornCringerMoshedPerplexSawderGlyphsHa = + someBigFunctionName("foo")("bar"); + +if (true) { + node.id = this.flowParseTypeAnnotatableIdentifier(/*allowPrimitiveOverride*/ true); +} + +const bifornCringerMoshedPerplexSawderGlyphsHb = someBigFunctionName(`foo +`)("bar"); + +``` + +# Output +```js +let vgChannel = pointPositionDefaultRef({ + model, + defaultPos, + channel, +},)(); +let vgChannel2 = pointPositionDefaultRef({ model, defaultPos, channel })(); +const bifornCringerMoshedPerplexSawderGlyphsHa = someBigFunctionName( + "foo", +)("bar"); +if (true) { + node.id = + this.flowParseTypeAnnotatableIdentifier( /*allowPrimitiveOverride*/ true); +} +const bifornCringerMoshedPerplexSawderGlyphsHb = someBigFunctionName( + `foo +`, +)("bar"); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/assignment/sequence.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/sequence.js.snap.new new file mode 100644 index 00000000000..1d6f335a2f5 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/assignment/sequence.js.snap.new @@ -0,0 +1,29 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: sequence.js +--- +# Input +```js +for ((i = 0), (len = arr.length); i < len; i++) { + console.log(arr[i]) +} + +for (i = 0, len = arr.length; i < len; i++) { + console.log(arr[i]) +} + +``` + +# Output +```js +for ((i = 0), (len = arr.length); i < len; i++) { + console.log(arr[i]); +} +for (i = 0, len = arr.length; i < len; i++) { + console.log(arr[i]); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/async-do-expressions/async-do-expressions.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/async-do-expressions/async-do-expressions.js.snap.new new file mode 100644 index 00000000000..bb9858219c8 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/async-do-expressions/async-do-expressions.js.snap.new @@ -0,0 +1,165 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: async-do-expressions.js +--- +# Input +```js +async do { + 1; +}; + +(async do {}); + +let x = async do { + if (foo()) { f() } + else if (bar()) { g() } + else { h() } +}; + +async do { + await 42 +} + +function iter() { + return async do { + return 1; + } +}; + +let x = async do { + let tmp = f(); + tmp * tmp + 1 +}; + +``` + +# Output +```js +async; +do { + 1; +}; +(async +do {}); +let x = async; +do { + if (foo()) { f() } + else if (bar()) { g() } + else { h() } +}; +async; +do { + await 42 +} + +function iter() { + return async do { + return 1; + } +}; +let x = async; +do { + let tmp = f(); + tmp * tmp + 1 +}; + +``` + +# Errors +``` +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ async-do-expressions.js:1:7 + │ +1 │ async do { + │ ------^^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ async-do-expressions.js:3:2 + │ +3 │ }; + │ ^ unexpected + +error[SyntaxError]: expected `')'` but instead found `do` + ┌─ async-do-expressions.js:5:8 + │ +5 │ (async do {}); + │ ^^ unexpected + +error[SyntaxError]: expected `while` but instead found `)` + ┌─ async-do-expressions.js:5:13 + │ +5 │ (async do {}); + │ ^ unexpected + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ async-do-expressions.js:7:15 + │ +7 │ let x = async do { + │ --------------^^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ async-do-expressions.js:11:2 + │ +11 │ }; + │ ^ unexpected + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ async-do-expressions.js:13:7 + │ +13 │ async do { + │ ------^^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: expected `while` but instead found `function` + ┌─ async-do-expressions.js:17:1 + │ +17 │ function iter() { + │ ^^^^^^^^ unexpected + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ async-do-expressions.js:18:16 + │ +18 │ return async do { + │ -------------^^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: expected `while` but instead found `}` + ┌─ async-do-expressions.js:21:1 + │ +21 │ }; + │ ^ unexpected + +error[SyntaxError]: expected `')'` but instead found `;` + ┌─ async-do-expressions.js:21:2 + │ +21 │ }; + │ ^ unexpected + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ async-do-expressions.js:23:15 + │ +23 │ let x = async do { + │ --------------^^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ async-do-expressions.js:26:2 + │ +26 │ }; + │ ^ unexpected + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/async/async-iteration.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/async/async-iteration.js.snap.new new file mode 100644 index 00000000000..622d487fabd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/async/async-iteration.js.snap.new @@ -0,0 +1,34 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: async-iteration.js +--- +# Input +```js + +async function * a() { + yield* b(); +} + +class X { + async * b() { + yield* a(); + } +} + +``` + +# Output +```js +async function* a() { + yield* b(); +} +class X { + async *b() { + yield* a(); + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/async/conditional-expression.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/async/conditional-expression.js.snap.new new file mode 100644 index 00000000000..bfed2ba37cd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/async/conditional-expression.js.snap.new @@ -0,0 +1,40 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: conditional-expression.js +--- +# Input +```js +async function f() { + const result = typeof fn === 'function' ? await fn() : null; +} + +(async function() { + console.log( + await (true ? Promise.resolve("A") : Promise.resolve("B")) + ); +})() + +async function f2() { + await (spellcheck && spellcheck.setChecking(false)); + await spellcheck && spellcheck.setChecking(false) +} + +``` + +# Output +```js +async function f() { + const result = typeof fn === "function" ? await fn() : null; +} +(async function () { + console.log(await (true ? Promise.resolve("A") : Promise.resolve("B"))); +})(); +async function f2() { + await (spellcheck && spellcheck.setChecking(false)); + await spellcheck && spellcheck.setChecking(false); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/async/parens.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/async/parens.js.snap.new new file mode 100644 index 00000000000..8a2c42fc12a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/async/parens.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: parens.js +--- +# Input +```js +async function *f(){ await (yield x); } + +async function f2(){ await (() => {}); } + +``` + +# Output +```js +async function* f() { + await (yield x); +} +async function f2() { + await (() => {}); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/class-properties.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/class-properties.js.snap.new new file mode 100644 index 00000000000..c4848e353e3 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/class-properties.js.snap.new @@ -0,0 +1,64 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: class-properties.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-class-properties + +class Bork { + //Property initializer syntax + instanceProperty = "bork"; + boundFunction = () => { + return this.instanceProperty; + }; + + //Static class properties + static staticProperty = "babelIsCool"; + static staticFunction = function() { + return Bork.staticProperty; + }; + } + + let myBork = new Bork; + + //Property initializers are not on the prototype. + console.log(myBork.__proto__.boundFunction); // > undefined + + //Bound functions are bound to the class instance. + console.log(myBork.boundFunction.call(undefined)); // > "bork" + + //Static function exists on the class. + console.log(Bork.staticFunction()); // > "babelIsCool" + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-class-properties + +class Bork { + //Property initializer syntax + instanceProperty = "bork"; + boundFunction = () => { + return this.instanceProperty; + }; + + //Static class properties + static staticProperty = "babelIsCool"; + static staticFunction = function () { + return Bork.staticProperty; + }; +} +let myBork = new Bork(); +//Property initializers are not on the prototype. +console.log(myBork.__proto__.boundFunction); // > undefined +//Bound functions are bound to the class instance. +console.log(myBork.boundFunction.call(undefined)); // > "bork" +//Static function exists on the class. +console.log(Bork.staticFunction()); // > "babelIsCool" + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decimal.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decimal.js.snap.new new file mode 100644 index 00000000000..ef180dc66d6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decimal.js.snap.new @@ -0,0 +1,371 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: decimal.js +--- +# Input +```js +// https://github.com/babel/babel/pull/11640 + +100m; +9223372036854775807m; +0.m; +3.1415926535897932m; +100.000m; +.1m; +({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); +1.m; +100m; +9223372036854775807m; +100.m; + +// Invalid decimal +2e9m; +016432m; +089m; + +// https://github.com/tc39/proposal-decimal +.1m + .2m === .3m; +2.00m; +-0m; +typeof 1m === "bigdecimal"; +typeof 1m === "decimal128"; + + +``` + +# Output +```js +// https://github.com/babel/babel/pull/11640 + +100m +9223372036854775807m +0.m +3.1415926535897932m +100.000m +.1m +({ 0m: 0, .1m() {}, get +0.2m() +{ +} +, set 3m(_) +{ +} +, async 4m() +{ +} +, *.5m() +{ +} +}) +1.m +100m +9223372036854775807m +100.m +// Invalid decimal +2e9m +016432m +089m +// https://github.com/tc39/proposal-decimal +.1m + .2m === .3m +2.00m +-0m; +typeof 1m === "bigdecimal"; +typeof 1m === "decimal128"; + +``` + +# Errors +``` +error[SyntaxError]: expected a statement but instead found '100m' + ┌─ decimal.js:3:1 + │ +3 │ 100m; + │ ^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '9223372036854775807m' + ┌─ decimal.js:4:1 + │ +4 │ 9223372036854775807m; + │ ^^^^^^^^^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '0.m' + ┌─ decimal.js:5:1 + │ +5 │ 0.m; + │ ^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '3.1415926535897932m' + ┌─ decimal.js:6:1 + │ +6 │ 3.1415926535897932m; + │ ^^^^^^^^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '100.000m' + ┌─ decimal.js:7:1 + │ +7 │ 100.000m; + │ ^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '.1m' + ┌─ decimal.js:8:1 + │ +8 │ .1m; + │ ^^^ Expected a statement here + +error[SyntaxError]: expected a property, a shorthand property, a getter, a setter, or a method but instead found '0m' + ┌─ decimal.js:9:4 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^ Expected a property, a shorthand property, a getter, a setter, or a method here + +error[SyntaxError]: expected a property, a shorthand property, a getter, a setter, or a method but instead found '.1m() {' + ┌─ decimal.js:9:11 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^^^^^^ Expected a property, a shorthand property, a getter, a setter, or a method here + +error[SyntaxError]: expected `')'` but instead found `0.2m` + ┌─ decimal.js:9:25 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^^^ unexpected + +error[SyntaxError]: expected a statement but instead found ', set 3m(_)' + ┌─ decimal.js:9:33 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found ', async 4m()' + ┌─ decimal.js:9:46 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found ', *.5m()' + ┌─ decimal.js:9:61 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '})' + ┌─ decimal.js:9:73 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '1.m' + ┌─ decimal.js:10:1 + │ +10 │ 1.m; + │ ^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '100m' + ┌─ decimal.js:11:1 + │ +11 │ 100m; + │ ^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '9223372036854775807m' + ┌─ decimal.js:12:1 + │ +12 │ 9223372036854775807m; + │ ^^^^^^^^^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '100.m' + ┌─ decimal.js:13:1 + │ +13 │ 100.m; + │ ^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '2e9m' + ┌─ decimal.js:16:1 + │ +16 │ 2e9m; + │ ^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '016432m' + ┌─ decimal.js:17:1 + │ +17 │ 016432m; + │ ^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '089m' + ┌─ decimal.js:18:1 + │ +18 │ 089m; + │ ^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '.1m + .2m === .3m' + ┌─ decimal.js:21:1 + │ +21 │ .1m + .2m === .3m; + │ ^^^^^^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '2.00m' + ┌─ decimal.js:22:1 + │ +22 │ 2.00m; + │ ^^^^^ Expected a statement here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:3:4 + │ +3 │ 100m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:4:20 + │ +4 │ 9223372036854775807m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:5:3 + │ +5 │ 0.m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:6:19 + │ +6 │ 3.1415926535897932m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:7:8 + │ +7 │ 100.000m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:8:3 + │ +8 │ .1m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:9:5 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:9:13 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:9:28 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:9:40 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:9:55 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:9:66 + │ +9 │ ({ 0m: 0, .1m() {}, get 0.2m(){}, set 3m(_){}, async 4m() {}, *.5m() {} }); + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:10:3 + │ +10 │ 1.m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:11:4 + │ +11 │ 100m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:12:20 + │ +12 │ 9223372036854775807m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:13:5 + │ +13 │ 100.m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:16:4 + │ +16 │ 2e9m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:17:7 + │ +17 │ 016432m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:18:4 + │ +18 │ 089m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:21:3 + │ +21 │ .1m + .2m === .3m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:21:9 + │ +21 │ .1m + .2m === .3m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:21:17 + │ +21 │ .1m + .2m === .3m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:22:5 + │ +22 │ 2.00m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:23:3 + │ +23 │ -0m; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:24:9 + │ +24 │ typeof 1m === "bigdecimal"; + │ ^ an identifier cannot appear here + +error: numbers cannot be followed by identifiers directly after + ┌─ decimal.js:25:9 + │ +25 │ typeof 1m === "decimal128"; + │ ^ an identifier cannot appear here + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decorators.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decorators.js.snap.new new file mode 100644 index 00000000000..572c6125fea --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/decorators.js.snap.new @@ -0,0 +1,69 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: decorators.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-decorators + +@annotation +class MyClass { } + +function annotation(target) { + target.annotated = true; +} + +@isTestable(true) +class MyClass { } + +function isTestable(value) { + return function decorator(target) { + target.isTestable = value; + } +} + +class C { + @enumerable(false) + method() { } +} + +function enumerable(value) { + return function (target, key, descriptor) { + descriptor.enumerable = value; + return descriptor; + } +} + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-decorators + +@annotation +class MyClass {} +function annotation(target) { + target.annotated = true; +} +@isTestable(true) +class MyClass {} +function isTestable(value) { + return function decorator(target) { + target.isTestable = value; + }; +} +class C { + @enumerable(false) + method() {} +} +function enumerable(value) { + return function (target, key, descriptor) { + descriptor.enumerable = value; + return descriptor; + }; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/function-sent.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/function-sent.js.snap.new new file mode 100644 index 00000000000..492ea461262 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/function-sent.js.snap.new @@ -0,0 +1,46 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: function-sent.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-function-sent + +function* generator() { + console.log("Sent", function.sent); + console.log("Yield", yield); +} + +const iterator = generator(); +iterator.next(1); // Logs "Sent 1" +iterator.next(2); // Logs "Yield 2" + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-function-sent + +function* generator() { + console.log("Sent", function.sent); + console.log("Yield", yield); +} +const iterator = generator(); +iterator.next(1); // Logs "Sent 1" +iterator.next(2); // Logs "Yield 2" + +``` + +# Errors +``` +error[SyntaxError]: expected a parenthesis '(' but instead found '.' + ┌─ function-sent.js:4:33 + │ +4 │ console.log("Sent", function.sent); + │ ^ Expected a parenthesis '(' here + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/logical-assignment-operators.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/logical-assignment-operators.js.snap.new new file mode 100644 index 00000000000..9feeb8e8aaf --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/logical-assignment-operators.js.snap.new @@ -0,0 +1,29 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: logical-assignment-operators.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-logical-assignment-operators + +a ||= b; +obj.a.b ||= c; + +a &&= b; +obj.a.b &&= c; + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-logical-assignment-operators + +a ||= b; +obj.a.b ||= c; +a &&= b; +obj.a.b &&= c; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/object-rest-spread.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/object-rest-spread.js.snap.new new file mode 100644 index 00000000000..e6da062f971 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/object-rest-spread.js.snap.new @@ -0,0 +1,33 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: object-rest-spread.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread + +let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; +console.log(x); // 1 +console.log(y); // 2 +console.log(z); // { a: 3, b: 4 } + +let n = { x, y, ...z }; +console.log(n); // { x: 1, y: 2, a: 3, b: 4 } + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread + +let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; +console.log(x); // 1 +console.log(y); // 2 +console.log(z); // { a: 3, b: 4 } +let n = { x, y, ...z }; +console.log(n); // { x: 1, y: 2, a: 3, b: 4 } + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/optional-catch-binding.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/optional-catch-binding.js.snap.new new file mode 100644 index 00000000000..c9ab375bdbe --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/optional-catch-binding.js.snap.new @@ -0,0 +1,45 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: optional-catch-binding.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-optional-catch-binding + +try { + throw 0; +} catch { + doSomethingWhichDoesNotCareAboutTheValueThrown(); +} + +try { + throw 0; +} catch { + doSomethingWhichDoesNotCareAboutTheValueThrown(); +} finally { + doSomeCleanup(); +} + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-optional-catch-binding + +try { + throw 0; +} catch { + doSomethingWhichDoesNotCareAboutTheValueThrown(); +} +try { + throw 0; +} catch { + doSomethingWhichDoesNotCareAboutTheValueThrown(); +} finally { + doSomeCleanup(); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/partial-application.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/partial-application.js.snap.new new file mode 100644 index 00000000000..dde4a805292 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/partial-application.js.snap.new @@ -0,0 +1,143 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: partial-application.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-partial-application + +function add(x, y) { return x + y; } + +const addOne = add(1, ?); // apply from the left +addOne(2); // 3 + +const addTen = add(?, 10); // apply from the right +addTen(2); // 12 + +let newScore = player.score + |> add(7, ?) + |> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`. + +f(x, ?) // partial application from left +f(?, x) // partial application from right +f(?, x, ?) // partial application for any arg +o.f(x, ?) // partial application from left +o.f(?, x) // partial application from right +o.f(?, x, ?) // partial application for any arg +super.f(?) // partial application allowed for call on |SuperProperty| + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-partial-application + +function add(x, y) { + return x + y; +} +const addOne = add(1, ?); // apply from the left +addOne(2); // 3 +const addTen = add(?, 10); // apply from the right +addTen(2); // 12 +let newScore = player.score + |> add(7, ?) + |> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`. +f(x, ?); // partial application from left +f(?, x); // partial application from right +f(?, x, ?); // partial application for any arg +o.f(x, ?); // partial application from left +o.f(?, x); // partial application from right +o.f(?, x, ?); // partial application for any arg +super.f(?); // partial application allowed for call on |SuperProperty| + +``` + +# Errors +``` +error[SyntaxError]: expected an expression but instead found '?' + ┌─ partial-application.js:5:23 + │ +5 │ const addOne = add(1, ?); // apply from the left + │ ^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?, 10' + ┌─ partial-application.js:8:20 + │ +8 │ const addTen = add(?, 10); // apply from the right + │ ^^^^^ Expected an expression here + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ partial-application.js:12:4 + │ +12 │ |> add(7, ?) + │ ^ This operator requires a left hand side value + +error[SyntaxError]: expected an expression but instead found '?' + ┌─ partial-application.js:12:13 + │ +12 │ |> add(7, ?) + │ ^ Expected an expression here + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ partial-application.js:13:4 + │ +13 │ |> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`. + │ ^ This operator requires a left hand side value + +error[SyntaxError]: expected an expression but instead found '?' + ┌─ partial-application.js:13:20 + │ +13 │ |> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`. + │ ^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?' + ┌─ partial-application.js:15:6 + │ +15 │ f(x, ?) // partial application from left + │ ^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?, x' + ┌─ partial-application.js:16:3 + │ +16 │ f(?, x) // partial application from right + │ ^^^^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?, x, ?' + ┌─ partial-application.js:17:3 + │ +17 │ f(?, x, ?) // partial application for any arg + │ ^^^^^^^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?' + ┌─ partial-application.js:18:8 + │ +18 │ o.f(x, ?) // partial application from left + │ ^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?, x' + ┌─ partial-application.js:19:5 + │ +19 │ o.f(?, x) // partial application from right + │ ^^^^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?, x, ?' + ┌─ partial-application.js:20:5 + │ +20 │ o.f(?, x, ?) // partial application for any arg + │ ^^^^^^^ Expected an expression here + +error[SyntaxError]: expected an expression but instead found '?' + ┌─ partial-application.js:21:9 + │ +21 │ super.f(?) // partial application allowed for call on |SuperProperty| + │ ^ Expected an expression here + + +``` + +# Lines exceeding max width of 80 characters +``` + 12: |> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`. +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-fsharp.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-fsharp.js.snap.new new file mode 100644 index 00000000000..e698ba6e504 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-fsharp.js.snap.new @@ -0,0 +1,150 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: pipeline-operator-fsharp.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-pipeline-operator +// https://github.com/valtech-nyc/proposal-fsharp-pipelines + +promise + |> await + |> x => doubleSay(x, ', ') + |> capitalize + |> x => x + '!' + |> x => new User.Message(x) + |> x => stream.write(x) + |> await + |> console.log; + +const result = exclaim(capitalize(doubleSay("hello"))); +result //=> "Hello, hello!" + +const result = "hello" + |> doubleSay + |> capitalize + |> exclaim; + +result //=> "Hello, hello!" + +const person = { score: 25 }; + +const newScore = person.score + |> double + |> n => add(7, n) + |> n => boundScore(0, 100, n); + +newScore //=> 57 + +// As opposed to: +let newScore = boundScore(0, 100, add(7, double(person.score))); + +``` + +# Output +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-pipeline-operator +// https://github.com/valtech-nyc/proposal-fsharp-pipelines + +promise + |> await + |> x +=> doubleSay(x, ', ') + |> capitalize + |> x => x + '!' + |> x => new User.Message(x) + |> x => stream.write(x) + |> await + |> console.log +const result = exclaim(capitalize(doubleSay("hello"))); +result; //=> "Hello, hello!" +const result = "hello" + |> doubleSay + |> capitalize + |> exclaim; +result; //=> "Hello, hello!" +const person = { score: 25 }; +const newScore = person.score + |> double + |> n +=> add(7, n) + |> n => boundScore(0, 100, n) +newScore; //=> 57 +// As opposed to: +let newScore = boundScore(0, 100, add(7, double(person.score))); + +``` + +# Errors +``` +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:5:4 + │ +5 │ |> await + │ ^ This operator requires a left hand side value + +error[SyntaxError]: expected an unary expression but instead found '|' + ┌─ pipeline-operator-fsharp.js:6:3 + │ +6 │ |> x => doubleSay(x, ', ') + │ ^ Expected an unary expression here + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:6:4 + │ +6 │ |> x => doubleSay(x, ', ') + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ pipeline-operator-fsharp.js:6:8 + │ +4 │ ┌ promise +5 │ │ |> await +6 │ │ |> x => doubleSay(x, ', ') + │ │ ^^ An explicit or implicit semicolon is expected here... + │ └─────────' ...Which is required to end this statement + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:18:4 + │ +18 │ |> doubleSay + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:19:4 + │ +19 │ |> capitalize + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:20:4 + │ +20 │ |> exclaim; + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:27:4 + │ +27 │ |> double + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-fsharp.js:28:4 + │ +28 │ |> n => add(7, n) + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ pipeline-operator-fsharp.js:28:8 + │ +26 │ ┌ const newScore = person.score +27 │ │ |> double +28 │ │ |> n => add(7, n) + │ │ ^^ An explicit or implicit semicolon is expected here... + │ └───────' ...Which is required to end this statement + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-minimal.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-minimal.js.snap.new new file mode 100644 index 00000000000..a568319e197 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/pipeline-operator-minimal.js.snap.new @@ -0,0 +1,61 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: pipeline-operator-minimal.js +--- +# Input +```js +// https://babeljs.io/docs/en/babel-plugin-proposal-pipeline-operator +// https://github.com/tc39/proposal-pipeline-operator/ + +let result = exclaim(capitalize(doubleSay("hello"))); +result //=> "Hello, hello!" + +let result = "hello" + |> doubleSay + |> capitalize + |> exclaim; + +result //=> "Hello, hello!" + +``` + +# Output +```js +// https://github.com/tc39/proposal-pipeline-operator/ + +// https://babeljs.io/docs/en/babel-plugin-proposal-pipeline-operator +let result = exclaim(capitalize(doubleSay("hello"))); +result; //=> "Hello, hello!" +let result = "hello" + |> doubleSay + |> capitalize + |> exclaim; +result; //=> "Hello, hello!" + +``` + +# Errors +``` +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-minimal.js:8:4 + │ +8 │ |> doubleSay + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-minimal.js:9:4 + │ +9 │ |> capitalize + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline-operator-minimal.js:10:4 + │ +10 │ |> exclaim; + │ ^ This operator requires a left hand side value + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/record-tuple-record.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/record-tuple-record.js.snap.new new file mode 100644 index 00000000000..680314f81f9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/record-tuple-record.js.snap.new @@ -0,0 +1,93 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: record-tuple-record.js +--- +# Input +```js +const record1 = #{ + a: 1, + b: 2, + c: 3, +}; + +const record2 = #{...record1, b: 5}; + +``` + +# Output +```js +const record1 = # +{ + a: 1, b; + : 2, + c: 3, +} +const record2 = # +{ + ...record1, b: 5 +} + +``` + +# Errors +``` +error[SyntaxError]: expected an identifier but instead found '{' + ┌─ record-tuple-record.js:1:18 + │ +1 │ const record1 = #{ + │ ^ Expected an identifier here + +error[SyntaxError]: Private names are only allowed on the left side of a 'in' expression + ┌─ record-tuple-record.js:1:17 + │ +1 │ const record1 = #{ + │ ^ + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ record-tuple-record.js:1:18 + │ +1 │ const record1 = #{ + │ -----------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ record-tuple-record.js:3:6 + │ +2 │ a: 1, + │ ┌────────' +3 │ │ b: 2, + │ │ ^ An explicit or implicit semicolon is expected here... + │ └──────' ...Which is required to end this statement + +error[SyntaxError]: expected an identifier but instead found '{' + ┌─ record-tuple-record.js:7:18 + │ +7 │ const record2 = #{...record1, b: 5}; + │ ^ Expected an identifier here + +error[SyntaxError]: Private names are only allowed on the left side of a 'in' expression + ┌─ record-tuple-record.js:7:17 + │ +7 │ const record2 = #{...record1, b: 5}; + │ ^ + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ record-tuple-record.js:7:18 + │ +7 │ const record2 = #{...record1, b: 5}; + │ -----------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: expected an expression but instead found '...record1, b: 5' + ┌─ record-tuple-record.js:7:19 + │ +7 │ const record2 = #{...record1, b: 5}; + │ ^^^^^^^^^^^^^^^^ Expected an expression here + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/v8intrinsic.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/v8intrinsic.js.snap.new new file mode 100644 index 00000000000..dd7485c783c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/babel-plugins/v8intrinsic.js.snap.new @@ -0,0 +1,96 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: v8intrinsic.js +--- +# Input +```js +// https://github.com/babel/babel/pull/10148 + +%DebugPrint(foo); + + +// Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/in-bind-expression/options.json +// ::%DebugPrint(null) + +// Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/in-member-expression/options.json +// a.%DebugPrint(); + +// Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/not-in-call-expression/options.json +// const i = %DebugPrint; +// i(foo); + +// https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/not-in-call-expression/options.json +// %DebugPrint?.(null) + +new %DebugPrint(null); + +function *foo() { + yield %StringParseInt("42", 10) +} + +foo%bar() + +``` + +# Output +```js +// https://github.com/babel/babel/pull/10148 + +%DebugPrint(foo) +// Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/in-bind-expression/options.json +// ::%DebugPrint(null) + +// Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/in-member-expression/options.json +// a.%DebugPrint(); + +// Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/not-in-call-expression/options.json +// const i = %DebugPrint; +// i(foo); + +// https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/not-in-call-expression/options.json +// %DebugPrint?.(null) + +new %DebugPrint(null); +function* foo() { + yield; + %StringParseInt("42", 10) +} +foo % bar(); + +``` + +# Errors +``` +error[SyntaxError]: expected a statement but instead found '%DebugPrint(foo)' + ┌─ v8intrinsic.js:3:1 + │ +3 │ %DebugPrint(foo); + │ ^^^^^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected an expression but instead found '%' + ┌─ v8intrinsic.js:19:5 + │ +19 │ new %DebugPrint(null); + │ ^ Expected an expression here + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ v8intrinsic.js:22:9 + │ +22 │ yield %StringParseInt("42", 10) + │ ------^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + + +``` + +# Lines exceeding max width of 80 characters +``` + 4: // Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/in-bind-expression/options.json + 7: // Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/in-member-expression/options.json + 10: // Invalid code https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/not-in-call-expression/options.json + 14: // https://github.com/JLHwung/babel/blob/c1a3cbfd65e08b7013fd6f8c62add8cb10b4b169/packages/babel-parser/test/fixtures/v8intrinsic/_errors/not-in-call-expression/options.json +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/arrow.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/arrow.js.snap.new new file mode 100644 index 00000000000..706335691cc --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/arrow.js.snap.new @@ -0,0 +1,63 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: arrow.js +--- +# Input +```js +function f() { + const appEntities = getAppEntities(loadObject).filter( + entity => entity && entity.isInstallAvailable() && !entity.isQueue() && entity.isDisabled() + ) +} + +function f2() { + const appEntities = getAppEntities(loadObject).map( + entity => entity && entity.isInstallAvailable() && !entity.isQueue() && entity.isDisabled() && { + id: entity.id + } + ) +} + +((x) => x) + ''; +'' + ((x) => x); + +``` + +# Output +```js +function f() { + const appEntities = getAppEntities( + loadObject, + ).filter( + ( + entity, + ) => + entity && + entity.isInstallAvailable() && + !entity.isQueue() && + entity.isDisabled(), + ); +} +function f2() { + const appEntities = getAppEntities( + loadObject, + ).map( + ( + entity, + ) => + entity && + entity.isInstallAvailable() && + !entity.isQueue() && + entity.isDisabled() && + { + id: entity.id, + }, + ); +} +((x) => x) + ""; +"" + ((x) => x); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/bitwise-flags.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/bitwise-flags.js.snap.new new file mode 100644 index 00000000000..5d95b735a5e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/bitwise-flags.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: bitwise-flags.js +--- +# Input +```js +const FLAG_A = 1 << 0; +const FLAG_B = 1 << 1; +const FLAG_C = 1 << 2; + +const all = FLAG_A | FLAG_B | FLAG_C; + +``` + +# Output +```js +const FLAG_A = 1 << 0; +const FLAG_B = 1 << 1; +const FLAG_C = 1 << 2; +const all = FLAG_A | FLAG_B | FLAG_C; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/call.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/call.js.snap.new new file mode 100644 index 00000000000..1b54a05d1fe --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/call.js.snap.new @@ -0,0 +1,129 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: call.js +--- +# Input +```js +( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)(); + +( + aa && + bb && + cc && + dd && + ee +)(); + +( + aaaaaaaaaaaaaaaaaaaaaaaaa + + bbbbbbbbbbbbbbbbbbbbbbbbb + + ccccccccccccccccccccccccc + + ddddddddddddddddddddddddd + + eeeeeeeeeeeeeeeeeeeeeeeee +)(); + +( + aa + + bb + + cc + + dd + + ee +)(); + +( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)()()(); + +( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +); + +``` + +# Output +```js +( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)(); +(aa && bb && cc && dd && ee)(); +( + aaaaaaaaaaaaaaaaaaaaaaaaa + + bbbbbbbbbbbbbbbbbbbbbbbbb + + ccccccccccccccccccccccccc + + ddddddddddddddddddddddddd + + eeeeeeeeeeeeeeeeeeeeeeeee +)(); +(aa + bb + cc + dd + ee)(); +( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)()()(); +( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee +)( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee, +)( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee, +)( + aaaaaaaaaaaaaaaaaaaaaaaaa && + bbbbbbbbbbbbbbbbbbbbbbbbb && + ccccccccccccccccccccccccc && + ddddddddddddddddddddddddd && + eeeeeeeeeeeeeeeeeeeeeeeee, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/comment.js.snap.new new file mode 100644 index 00000000000..421ba2ead77 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/comment.js.snap.new @@ -0,0 +1,121 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment.js +--- +# Input +```js +a = ( + // Comment 1 + (Math.random() * (yRange * (1 - minVerticalFraction))) + + (minVerticalFraction * yRange) +) - offset; + +a + + a + + a + // comment + a + + a; + +a && + longLongLongLongLongLongLongLongLong && + longLongLongLongLongLongLongLongLong && // comment + longLongLongLongLongLongLongLongLong && + longLongLongLongLongLongLongLongLong + +a || + longLongLongLongLongLongLongLongLong || + longLongLongLongLongLongLongLongLong || // comment + longLongLongLongLongLongLongLongLong || + longLongLongLongLongLongLongLongLong + +var a = x(abifornCringerMoshedPerplexSawder ++ kochabCooieGameOnOboleUnweave // f ++ glimseGlyphsHazardNoopsTieTie+bifornCringerMoshedPerplexSawder); + +foo[ + a + + a + // comment + a + + bar[ + b + + b + + b + // comment + b + + b + ] +]; + +!( + a + + a + // comment + a + + !( + b + + b + + b + // comment + b + + b + ) +); + +``` + +# Output +```js +a = + ( + // Comment 1 + ( + Math.random() * (yRange * (1 - minVerticalFraction)) + ) + (minVerticalFraction * yRange) + ) - offset; +a + + a + + a + // comment + a + + a; +a && + longLongLongLongLongLongLongLongLong && + longLongLongLongLongLongLongLongLong && // comment + longLongLongLongLongLongLongLongLong && + longLongLongLongLongLongLongLongLong; +a || + longLongLongLongLongLongLongLongLong || + longLongLongLongLongLongLongLongLong || // comment + longLongLongLongLongLongLongLongLong || + longLongLongLongLongLongLongLongLong; +var a = x( + abifornCringerMoshedPerplexSawder + + kochabCooieGameOnOboleUnweave + // f + glimseGlyphsHazardNoopsTieTie + + bifornCringerMoshedPerplexSawder, +); +foo[ + a + + a + // comment + a + + bar[ + b + + b + + b + // comment + b + + b + ] +]; +!( + a + + a + // comment + a + + !( + b + + b + + b + // comment + b + + b + ) +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/equality.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/equality.js.snap.new new file mode 100644 index 00000000000..462b9a5a55f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/equality.js.snap.new @@ -0,0 +1,33 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: equality.js +--- +# Input +```js +x == y == z; +x != y == z; +x == y != z; +x != y != z; + +x === y === z; +x !== y === z; +x === y !== z; +x !== y !== z; + +``` + +# Output +```js +x == y == z; +x != y == z; +x == y != z; +x != y != z; +x === y === z; +x !== y === z; +x === y !== z; +x !== y !== z; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/if.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/if.js.snap.new new file mode 100644 index 00000000000..95448831b26 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/if.js.snap.new @@ -0,0 +1,40 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: if.js +--- +# Input +```js +if (this.hasPlugin("dynamicImports") && this.lookahead().type) {} + +if (this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft) {} + +if (this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft.right) {} + +if (VeryVeryVeryVeryVeryVeryVeryVeryLong === VeryVeryVeryVeryVeryVeryVeryVeryLong) { +} + +``` + +# Output +```js +if (this.hasPlugin("dynamicImports") && this.lookahead().type) { +} +if ( + this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft +) { +} +if ( + this.hasPlugin( + "dynamicImports", + ) && this.lookahead().type === tt.parenLeft.right +) { +} +if ( + VeryVeryVeryVeryVeryVeryVeryVeryLong === VeryVeryVeryVeryVeryVeryVeryVeryLong +) { +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-jsx.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-jsx.js.snap.new new file mode 100644 index 00000000000..2fcae9ead93 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-jsx.js.snap.new @@ -0,0 +1,36 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: inline-jsx.js +--- +# Input +```js +const user = renderedUser ||
; + +const user2 = renderedUser || shouldRenderUser &&
; + +const avatar = hasAvatar && ; + +const avatar2 = (hasAvatar || showPlaceholder) && ; + +``` + +# Output +```js +const user = renderedUser ||
; +const user2 = renderedUser || ( + shouldRenderUser &&
+); +const avatar = hasAvatar && ; +const avatar2 = ( + hasAvatar || showPlaceholder +) && ; + +``` + +# Lines exceeding max width of 80 characters +``` + 1: const user = renderedUser ||
; + 3: shouldRenderUser &&
+``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-object-array.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-object-array.js.snap.new new file mode 100644 index 00000000000..bdd73dcfc02 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/inline-object-array.js.snap.new @@ -0,0 +1,202 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: inline-object-array.js +--- +# Input +```js +prevState = prevState || { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: '', + selectedCatalog: null, +}; + +prevState = prevState || + defaultState || { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: '', + selectedCatalog: null, + }; + +prevState = prevState || + defaultState && { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: '', + selectedCatalog: null, + }; + +prevState = prevState || useDefault && defaultState || { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: '', + selectedCatalog: null, + }; + +this.steps = steps || [ + { + name: 'mock-module', + path: '/nux/mock-module', + }, +]; + +this.steps = steps || checkStep && [ + { + name: 'mock-module', + path: '/nux/mock-module', + }, +]; + +this.steps = steps && checkStep || [ + { + name: 'mock-module', + path: '/nux/mock-module', + }, +]; + +const create = () => { + const result = doSomething(); + return ( + shouldReturn && + result.ok && { + status: "ok", + createdAt: result.createdAt, + updatedAt: result.updatedAt + } + ); +} + +const create2 = () => { + const result = doSomething(); + return ( + shouldReturn && result.ok && result || { + status: "ok", + createdAt: result.createdAt, + updatedAt: result.updatedAt + } + ); +} + +const obj = { + state: shouldHaveState && + stateIsOK && { + loadState: LOADED, + opened: false + }, + loadNext: stateIsOK && hasNext || { + skipNext: true + }, + loaded: true +} + +``` + +# Output +```js +prevState = + prevState || { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: "", + selectedCatalog: null, + }; +prevState = + prevState || + defaultState || + { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: "", + selectedCatalog: null, + }; +prevState = + prevState || ( + defaultState && { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: "", + selectedCatalog: null, + } + ); +prevState = + prevState || + (useDefault && defaultState) || + { + catalogs: [], + loadState: LOADED, + opened: false, + searchQuery: "", + selectedCatalog: null, + }; +this.steps = + steps || [ + { + name: "mock-module", + path: "/nux/mock-module", + }, + ]; +this.steps = + steps || ( + checkStep && [ + { + name: "mock-module", + path: "/nux/mock-module", + }, + ] + ); +this.steps = + ( + steps && checkStep + ) || [ + { + name: "mock-module", + path: "/nux/mock-module", + }, + ]; +const create = () => { + const result = doSomething(); + return ( + shouldReturn && + result.ok && + { + status: "ok", + createdAt: result.createdAt, + updatedAt: result.updatedAt, + } + ); +}; +const create2 = () => { + const result = doSomething(); + return ( + (shouldReturn && result.ok && result) || { + status: "ok", + createdAt: result.createdAt, + updatedAt: result.updatedAt, + } + ); +}; +const obj = { + state: shouldHaveState && + stateIsOK && + { + loadState: LOADED, + opened: false, + }, + loadNext: (stateIsOK && hasNext) || { + skipNext: true, + }, + loaded: true, +}; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/jsx_parent.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/jsx_parent.js.snap.new new file mode 100644 index 00000000000..98659d093c5 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/jsx_parent.js.snap.new @@ -0,0 +1,79 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: jsx_parent.js +--- +# Input +```js +
; + +
+ {!isJellyfishEnabled && + diffUpdateMessageInput != null && + this.state.isUpdateMessageEmpty} +
; + +
; + +
+ {!isJellyfishEnabled && + diffUpdateMessageInput != null &&
Text
} +
; + +
+ {!isJellyfishEnabled && + diffUpdateMessageInput != null && child ||
Text
} +
; + +``` + +# Output +```js +
; +
+ {!isJellyfishEnabled && + diffUpdateMessageInput != null && + this.state.isUpdateMessageEmpty} +
; +
; +
+ {!isJellyfishEnabled && + diffUpdateMessageInput != null &&
Text
} +
; +
+ {!isJellyfishEnabled && + diffUpdateMessageInput != null && child ||
Text
} +
; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/math.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/math.js.snap.new new file mode 100644 index 00000000000..551aeefd11c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/math.js.snap.new @@ -0,0 +1,56 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: math.js +--- +# Input +```js +x + y / z; +x / y + z; + +x * y % z; +x / y % z; +x % y * z; +x % y / z; + +x % y % z; + +x << y >> z; +x >>> y << z; +x >>> y >>> z; +x + y >> z; + +x | y & z; +x & y | z; +x ^ y ^ z; +x & y & z; +x | y | z; +x & y >> z; +x << y | z; + +``` + +# Output +```js +x + (y / z); +(x / y) + z; +x * y % z; +x / y % z; +x % y * z; +x % y / z; +x % y % z; +x << y >> z; +x >>> y << z; +x >>> y >>> z; +x + y >> z; +x | y & z; +x & y | z; +x ^ y ^ z; +x & y & z; +x | y | z; +x & y >> z; +x << y | z; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/return.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/return.js.snap.new new file mode 100644 index 00000000000..f784114052b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/return.js.snap.new @@ -0,0 +1,48 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: return.js +--- +# Input +```js +function foo() { + return this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft.right; +} + +function foo2() { + return this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft.right + ? true + : false; +} + +function foo3() { + return this.calculate().compute().first.numberOfThings > this.calculate().compute().last.numberOfThings + ? true + : false; +} + +``` + +# Output +```js +function foo() { + return this.hasPlugin( + "dynamicImports", + ) && this.lookahead().type === tt.parenLeft.right; +} +function foo2() { + return this.hasPlugin( + "dynamicImports", + ) && this.lookahead().type === tt.parenLeft.right ? true : false; +} +function foo3() { + return this.calculate().compute().first.numberOfThings > this.calculate().compute().last.numberOfThings ? true : false; +} + +``` + +# Lines exceeding max width of 80 characters +``` + 12: return this.calculate().compute().first.numberOfThings > this.calculate().compute().last.numberOfThings ? true : false; +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap.new new file mode 100644 index 00000000000..b1f985924d9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary-expressions/short-right.js.snap.new @@ -0,0 +1,49 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: short-right.js +--- +# Input +```js +this._cumulativeHeights && + Math.abs( + this._cachedItemHeight(this._firstVisibleIndex + i) - + this._provider.fastHeight(i + this._firstVisibleIndex), + ) > + 1 + +foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( + aaaaaaaaaaaaaaaaaaa +) + + a; + +const isPartOfPackageJSON = dependenciesArray.indexOf( + dependencyWithOutRelativePath.split('/')[0], +) !== -1; + +defaultContent.filter(defaultLocale => { + // ... +})[0] || null; + +``` + +# Output +```js +this._cumulativeHeights && Math.abs( + this._cachedItemHeight( + this._firstVisibleIndex + i, + ) - this._provider.fastHeight(i + this._firstVisibleIndex), +) > 1; +foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( + aaaaaaaaaaaaaaaaaaa, +) + a; +const isPartOfPackageJSON = dependenciesArray.indexOf( + dependencyWithOutRelativePath.split("/")[0], +) !== -1; +defaultContent.filter((defaultLocale) => { + // ... +},)[0] || null; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/binary_math/parens.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/binary_math/parens.js.snap.new new file mode 100644 index 00000000000..88c3e2d81a2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/binary_math/parens.js.snap.new @@ -0,0 +1,55 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: parens.js +--- +# Input +```js +const result = (a + b) >>> 1; +var sizeIndex = ((index - 1) >>> level) & MASK; +var from = offset > left ? 0 : (left - offset) >> level; +var to = ((right - offset) >> level) + 1; +if (rawIndex < 1 << (list._level + SHIFT)) {} +var res = size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); +sign = 1 - (2 * (b[3] >> 7)); +exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127; +mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; + +2 / 3 * 10 / 2 + 2; +const rotateX = ((RANGE / rect.height) * refY - RANGE / 2) * getXMultiplication(rect.width); +const rotateY = ((RANGE / rect.width) * refX - RANGE / 2) * getYMultiplication(rect.width); + +a % 10 - 5; +a * b % 10; +a % 10 > 5; +a % 10 == 0; + +``` + +# Output +```js +const result = (a + b) >>> 1; +var sizeIndex = ((index - 1) >>> level) & MASK; +var from = offset > left ? 0 : (left - offset) >> level; +var to = ((right - offset) >> level) + 1; +if (rawIndex < (1 << (list._level + SHIFT))) { +} +var res = size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); +sign = 1 - (2 * (b[3] >> 7)); +exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127; +mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; +(2 / 3 * 10 / 2) + 2; +const rotateX = ( + ((RANGE / rect.height) * refY) - (RANGE / 2) +) * getXMultiplication(rect.width); +const rotateY = ( + ((RANGE / rect.width) * refX) - (RANGE / 2) +) * getYMultiplication(rect.width); +(a % 10) - 5; +a * b % 10; +(a % 10) > 5; +(a % 10) == 0; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/bind-expressions/method_chain.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/bind-expressions/method_chain.js.snap.new new file mode 100644 index 00000000000..612f0af584d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/bind-expressions/method_chain.js.snap.new @@ -0,0 +1,72 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: method_chain.js +--- +# Input +```js +import {interval} from 'rxjs/observable/interval'; +import {filter} from 'rxjs/operator/filter'; +import {take} from 'rxjs/operator/take'; +import {map} from 'rxjs/operator/map'; +import {throttle} from 'rxjs/operator/throttle'; +import {takeUntil} from 'rxjs/operator/takeUntil'; + +function test(observable) { + return observable + ::filter(data => data.someTest) + ::throttle(() => + interval(10) + ::take(1) + ::takeUntil(observable::filter(data => someOtherTest)) + ) + ::map(someFunction); +} + +``` + +# Output +```js +import { interval } from "rxjs/observable/interval"; +import { filter } from "rxjs/operator/filter"; +import { take } from "rxjs/operator/take"; +import { map } from "rxjs/operator/map"; +import { throttle } from "rxjs/operator/throttle"; +import { takeUntil } from "rxjs/operator/takeUntil"; +function test(observable) { + return observable; + ::filter(data => data.someTest) + ::throttle(() => + interval(10) + ::take(1) + ::takeUntil(observable::filter(data => someOtherTest)) + ) + ::map(someFunction) +} + +``` + +# Errors +``` +error[SyntaxError]: expected a statement but instead found '::filter(data => data.someTest) + ::throttle(() => + interval(10) + ::take(1) + ::takeUntil(observable::filter(data => someOtherTest)) + ) + ::map(someFunction)' + ┌─ method_chain.js:10:9 + │ +10 │ ┌ ::filter(data => data.someTest) +11 │ │ ::throttle(() => +12 │ │ interval(10) +13 │ │ ::take(1) +14 │ │ ::takeUntil(observable::filter(data => someOtherTest)) +15 │ │ ) +16 │ │ ::map(someFunction); + │ └───────────────────────────^ Expected a statement here + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap.new new file mode 100644 index 00000000000..86b44e586af --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/break.js.snap.new @@ -0,0 +1,105 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: break.js +--- +# Input +```js +h(f(g(() => { + a +}))) + +deepCopyAndAsyncMapLeavesA( + { 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 } +) + +function someFunction(url) { + return get(url) + .then( + json => dispatch(success(json)), + error => dispatch(failed(error)) + ); +} + +const mapChargeItems = fp.flow( + l => l < 10 ? l: 1, + l => Immutable.Range(l).toMap() +); + +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); + }, + [] +); + + +``` + +# Output +```js +h( + f( + g(() => { + a; + },), + ), +); +deepCopyAndAsyncMapLeavesA( + { 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 }, +); +function someFunction(url) { + return get( + url, + ).then((json) => dispatch(success(json)), (error) => dispatch(failed(error))); +} +const mapChargeItems = fp.flow( + (l) => l < 10 ? l : 1, + (l) => Immutable.Range(l).toMap(), +); +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); + }, + [], +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap.new new file mode 100644 index 00000000000..51715db3dcd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/break-calls/reduce.js.snap.new @@ -0,0 +1,34 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: reduce.js +--- +# Input +```js +const [ first1 ] = array.reduce( + () => [accumulator, element, accumulator, element], + [fullName] +); + +const [ first2 ] = array.reduce( + (accumulator, element, ) => [accumulator, element], + [fullName] +); + +``` + +# Output +```js +const [ + first1, +] = 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/class-comment/superclass.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/class-comment/superclass.js.snap.new new file mode 100644 index 00000000000..19710d86582 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/class-comment/superclass.js.snap.new @@ -0,0 +1,91 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: superclass.js +--- +# Input +```js +class A // comment 1 + // comment 2 + extends B {} + +class A1 extends B // comment1 +// comment2 +// comment3 +{} + +class A2 /* a */ extends B {} +class A3 extends B /* a */ {} +class A4 extends /* a */ B {} + +(class A5 // comment 1 + // comment 2 + extends B {}); + +(class A6 extends B // comment1 +// comment2 +// comment3 +{}); + +(class A7 /* a */ extends B {}); +(class A8 extends B /* a */ {}); +(class A9 extends /* a */ B {}); + +class a extends b // comment +{ + constructor() {} +} + +class c extends d +// comment2 +{ + constructor() {} +} + +class C2 // comment +extends Base +{ foo(){} } + +``` + +# Output +```js +class A // comment 1 +// comment 2 +extends B {} +class A1 extends B // comment3 // comment1 +// comment2 +{} +class A2 /* a */ extends B {} +class A3 extends B /* a */ {} +class A4 extends /* a */ B {} +( + class A5 // comment 1 + // comment 2 + extends B {} +); +( + class A6 extends B // comment3 // comment1 + // comment2 + {} +); +(class A7 /* a */ extends B {}); +(class A8 extends B /* a */ {}); +(class A9 extends /* a */ B {}); +class a extends b { + // comment + constructor() {} +} +class c extends d +// comment2 +{ + constructor() {} +} +class C2 extends Base { + // comment + foo() {} +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/class-extends/complex.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/class-extends/complex.js.snap.new new file mode 100644 index 00000000000..eca00be3a8e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/class-extends/complex.js.snap.new @@ -0,0 +1,50 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: complex.js +--- +# Input +```js +class loooooooooooooooooooong1 extends foooooooo(foooooooo(foooooooo(foooooooo(foooooooo(foooooooo(foooooooo(foooooooo()))))))) {} + +class loooooooooooooooooooong2 extends function (make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} {} + +class loooooooooooooooooooong3 extends class { + cconstructor(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; + } +} {} + +``` + +# Output +```js +class loooooooooooooooooooong1 extends foooooooo( + foooooooo(foooooooo(foooooooo(foooooooo(foooooooo(foooooooo(foooooooo())))))), +) {} +class loooooooooooooooooooong2 extends function (make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} {} +class loooooooooooooooooooong3 extends class { + cconstructor(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; + } +} {} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/class-static-block/class-static-block.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/class-static-block/class-static-block.js.snap.new new file mode 100644 index 00000000000..a783ab7df8f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/class-static-block/class-static-block.js.snap.new @@ -0,0 +1,69 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: class-static-block.js +--- +# Input +```js +class C { + static #x = 42; + static y; + static { + try { + this.y = doSomethingWith(this.#x); + } catch { + this.y = "unknown"; + } + } +} + +class Foo { + static {} +} + +class A1 { + static { + foo; + } +} + +class A2 { + static { + foo; + bar; + } +} + +``` + +# Output +```js +class C { + static #x = 42; + static y; + static { + try { + this.y = doSomethingWith(this.#x); + } catch { + this.y = "unknown"; + } + } +} +class Foo { + static {} +} +class A1 { + static { + foo; + } +} +class A2 { + static { + foo; + bar; + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/classes-private-fields/private_fields.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/classes-private-fields/private_fields.js.snap.new new file mode 100644 index 00000000000..10aaeb45631 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/classes-private-fields/private_fields.js.snap.new @@ -0,0 +1,127 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: private_fields.js +--- +# Input +```js +class A { #x; #y; } +class B { #x = 0; #y = 1; } + +class C { + static #x; + static #y = 1; +} + +class D { + #x + #y +} + +class Point { + #x = 1; + #y = 2; + + constructor(x = 0, y = 0) { + this.#x = +x; + this.#y = +y; + } + + get x() { return this.#x } + set x(value) { this.#x = +value } + + get y() { return this.#y } + set y(value) { this.#y = +value } + + equals(p) { return this.#x === p.#x && this.#y === p.#y } + + toString() { return `Point<${ this.#x },${ this.#y }>` } +} + +class E { + async #a() {} + #b() {} + get #c() {} + set #c(bar) {} + *#d() {} + async *#e() {} + get #f() {} + set #f(taz) {} +} + +class F { + #func(id, { blog: { title } }) { + return id + title; + } +} + +``` + +# Output +```js +class A { + #x; + #y; +} +class B { + #x = 0; + #y = 1; +} +class C { + static #x; + static #y = 1; +} +class D { + #x; + #y; +} +class Point { + #x = 1; + #y = 2; + + constructor(x = 0, y = 0) { + this.#x = +x; + this.#y = +y; + } + + get x() { + return this.#x; + } + set x(value) { + this.#x = +value; + } + + get y() { + return this.#y; + } + set y(value) { + this.#y = +value; + } + + equals(p) { + return this.#x === p.#x && this.#y === p.#y; + } + + toString() { + return `Point<${this.#x},${this.#y}>`; + } +} +class E { + async #a() {} + #b() {} + get #c() {} + set #c(bar) {} + *#d() {} + async *#e() {} + get #f() {} + set #f(taz) {} +} +class F { + #func(id, { blog: { title } }) { + return id + title; + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/classes/assignment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/classes/assignment.js.snap.new new file mode 100644 index 00000000000..345e4d04e99 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/classes/assignment.js.snap.new @@ -0,0 +1,83 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: assignment.js +--- +# Input +```js +aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = class extends ( + aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg1 +) { + method () { + console.log("foo"); + } +}; + +foo = class extends bar { + method() { + console.log("foo"); + } +}; + +aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = class extends bar { + method() { + console.log("foo"); + } +}; + +foo = class extends aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 { + method() { + console.log("foo"); + } +}; + +module.exports = class A extends B { + method () { + console.log("foo"); + } +}; + +``` + +# Output +```js +aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = + class extends ( + aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg1 + ) { + method() { + console.log("foo"); + } + }; +foo = + class extends bar { + method() { + console.log("foo"); + } + }; +aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = + class extends bar { + method() { + console.log("foo"); + } + }; +foo = + class extends aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 { + method() { + console.log("foo"); + } + }; +module.exports = + class A extends B { + method() { + console.log("foo"); + } + }; + +``` + +# Lines exceeding max width of 80 characters +``` + 22: class extends aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 { +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/classes/empty.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/classes/empty.js.snap.new new file mode 100644 index 00000000000..87bdb7d6971 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/classes/empty.js.snap.new @@ -0,0 +1,39 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: empty.js +--- +# Input +```js +class A1 { + // comment +} + +class A2 { // comment +} + +class A3 { +} + +class A4 { + m() {} +} + +``` + +# Output +```js +class A1 { + // comment +} +class A2 { + // comment +} +class A3 {} +class A4 { + m() {} +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/classes/method.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/classes/method.js.snap.new new file mode 100644 index 00000000000..502d4866476 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/classes/method.js.snap.new @@ -0,0 +1,33 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: method.js +--- +# Input +```js + +class C { + name/*comment*/() { + } +}; + + +({ + name/*comment*/() { + } +}); + +``` + +# Output +```js +class C { + name /*comment*/ () {} +} +({ + name /*comment*/ () {}, +}); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/classes/property.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/classes/property.js.snap.new new file mode 100644 index 00000000000..0a7ad8adf11 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/classes/property.js.snap.new @@ -0,0 +1,54 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: property.js +--- +# Input +```js +class A { + foobar = + // comment to break + 1 + + // comment to break again + 2; +} + +class B { + someInstanceProperty = this.props.foofoofoofoofoofoo && + this.props.barbarbarbar; + + someInstanceProperty2 = { foo: this.props.foofoofoofoofoofoo && + this.props.barbarbarbar }; + + someInstanceProperty3 = + "foo"; +} + +``` + +# Output +```js +class A { + foobar = + // comment to break + 1 + + // comment to break again + 2; +} +class B { + someInstanceProperty = this.props.foofoofoofoofoofoo && this.props.barbarbarbar; + + someInstanceProperty2 = { + foo: this.props.foofoofoofoofoofoo && this.props.barbarbarbar, + }; + + someInstanceProperty3 = "foo"; +} + +``` + +# Lines exceeding max width of 80 characters +``` + 9: someInstanceProperty = this.props.foofoofoofoofoofoo && this.props.barbarbarbar; +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/closure-compiler-type-cast.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/closure-compiler-type-cast.js.snap.new new file mode 100644 index 00000000000..48188cf1ee4 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/closure-compiler-type-cast.js.snap.new @@ -0,0 +1,131 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: closure-compiler-type-cast.js +--- +# Input +```js +// test to make sure comments are attached correctly +let inlineComment = /* some comment */ ( + someReallyLongFunctionCall(withLots, ofArguments)); + +let object = { + key: /* some comment */ (someReallyLongFunctionCall(withLots, ofArguments)) +}; + +// preserve parens only for type casts +let assignment = /** @type {string} */ (getValue()); +let value = /** @type {string} */ (this.members[0]).functionCall(); + +functionCall(1 + /** @type {string} */ (value), /** @type {!Foo} */ ({})); + +function returnValue() { + return /** @type {!Array.} */ (['hello', 'you']); +} + +// Only numberOrString is typecast +var newArray = /** @type {array} */ (numberOrString).map(x => x); +var newArray = /** @type {array} */ ((numberOrString)).map(x => x); +var newArray = test(/** @type {array} */ (numberOrString).map(x => x)); +var newArray = test(/** @type {array} */ ((numberOrString)).map(x => x)); + +// The numberOrString.map CallExpression is typecast +var newArray = /** @type {array} */ (numberOrString.map(x => x)); +var newArray = /** @type {array} */ ((numberOrString).map(x => x)); +var newArray = test(/** @type {array} */ (numberOrString.map(x => x))); +var newArray = test(/** @type {array} */ ((numberOrString).map(x => x))); + +test(/** @type {number} */(num) + 1); +test(/** @type {!Array} */(arrOrString).length + 1); +test(/** @type {!Array} */((arrOrString)).length + 1); + +const data = functionCall( + arg1, + arg2, + /** @type {{height: number, width: number}} */ (arg3)); + +const style = /** @type {{ + width: number, + height: number, + marginTop: number, + marginLeft: number, + marginRight: number, + marginBottom: number, +}} */ ({ + width, + height, + ...margins, +}); + +const style2 =/** + * @type {{ + * width: number, + * }} +*/({ + width, +}); + + +``` + +# Output +```js +// test to make sure comments are attached correctly +let inlineComment = /* some comment */ ( + someReallyLongFunctionCall(withLots, ofArguments) +); +let object = { + key: /* some comment */ (someReallyLongFunctionCall(withLots, ofArguments)), +}; +// preserve parens only for type casts +let assignment = /** @type {string} */ (getValue()); +let value = /** @type {string} */ (this.members[0]).functionCall(); +functionCall( + 1 + /** @type {string} */ + (value), /** @type {!Foo} */ + ({}), +); +function returnValue() { + return /** @type {!Array.} */ (["hello", "you"]); +} +// Only numberOrString is typecast +var newArray = /** @type {array} */ (numberOrString).map((x) => x); +var newArray = /** @type {array} */ ((numberOrString)).map((x) => x); +var newArray = test( /** @type {array} */ (numberOrString).map((x) => x)); +var newArray = test( /** @type {array} */ ((numberOrString)).map((x) => x)); +// The numberOrString.map CallExpression is typecast +var newArray = /** @type {array} */ (numberOrString.map((x) => x)); +var newArray = /** @type {array} */ ((numberOrString).map((x) => x)); +var newArray = test( /** @type {array} */ (numberOrString.map((x) => x))); +var newArray = test( /** @type {array} */ ((numberOrString).map((x) => x))); +test( /** @type {number} */ (num) + 1); +test( /** @type {!Array} */ (arrOrString).length + 1); +test( /** @type {!Array} */ ((arrOrString)).length + 1); +const data = functionCall( + arg1, + arg2, + /** @type {{height: number, width: number}} */ (arg3), +); +const style = /** @type {{ + width: number, + height: number, + marginTop: number, + marginLeft: number, + marginRight: number, + marginBottom: number, +}} */ ({ + width, + height, + ...margins, +}); +const style2 = /** + * @type {{ + * width: number, + * }} +*/ ({ + width, +}); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-in-the-middle.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-in-the-middle.js.snap.new new file mode 100644 index 00000000000..e950d469e97 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-in-the-middle.js.snap.new @@ -0,0 +1,37 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment-in-the-middle.js +--- +# Input +```js +var a = +/** + * bla bla bla + * @type {string | + * number + * } +* bla bla bla + */ +//2 + ((window['s'])).toString(); +console.log(a.foo()); + +``` + +# Output +```js +var a = //2 +/** + * bla bla bla + * @type {string | + * number + * } +* bla bla bla + */ +((window["s"])).toString(); +console.log(a.foo()); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-placement.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-placement.js.snap.new new file mode 100644 index 00000000000..9572bf4d674 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/comment-placement.js.snap.new @@ -0,0 +1,47 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment-placement.js +--- +# Input +```js +const foo1 = /** @type {string} */ + (value); + +const foo2 = + /** @type {string} */ + (value); + +const foo3 = + + /** @type {string} */ + (value); + + +const foo4 = + /** @type {string} */(value); + +const foo5 = + /** @type {string} */ ( + value + ); + +``` + +# Output +```js +const foo1 = /** @type {string} */ (value); +const foo2 = +/** @type {string} */ +(value); +const foo3 = +/** @type {string} */ +(value); +const foo4 = +/** @type {string} */ (value); +const foo5 = +/** @type {string} */ (value); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/iife.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/iife.js.snap.new new file mode 100644 index 00000000000..086ec8b9be6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/iife.js.snap.new @@ -0,0 +1,42 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: iife.js +--- +# Input +```js +const helpers1 = /** @type {Helpers} */ (( + (helpers = {}) => helpers +)()); + +const helpers2 = /** @type {Helpers} */ (( + function() { return something } +)()); + +// TODO: @param is misplaced https://github.com/prettier/prettier/issues/5850 +const helpers = /** @type {Helpers} */ (( + /** @param {Partial} helpers */ + (helpers = {}) => helpers +)()); + +``` + +# Output +```js +const helpers1 = /** @type {Helpers} */ (((helpers = {}) => helpers)()); +const helpers2 = /** @type {Helpers} */ ( + (function () { + return something; + })() +); +// TODO: @param is misplaced https://github.com/prettier/prettier/issues/5850 +const helpers = /** @type {Helpers} */ ( + ( + /** @param {Partial} helpers */ + (helpers = {}) => helpers + )() +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-4124.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-4124.js.snap.new new file mode 100644 index 00000000000..f01b81e0a14 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-4124.js.snap.new @@ -0,0 +1,44 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-4124.js +--- +# Input +```js +/** @type {Object} */(myObject.property).someProp = true; +(/** @type {Object} */(myObject.property)).someProp = true; + +const prop = /** @type {Object} */(myObject.property).someProp; + +const test = /** @type (function (*): ?|undefined) */ + (goog.partial(NewThing.onTemplateChange, rationaleField, typeField)); + +const test = /** @type (function (*): ?|undefined) */ (goog.partial(NewThing.onTemplateChange, rationaleField, typeField)); + +const model = /** @type {?{getIndex: Function}} */ (model); + +const foo = /** @type {string} */ + (bar); + +const test = /** @type (function (*): ?|undefined) */ (foo); + +``` + +# Output +```js +/** @type {Object} */ (myObject.property).someProp = true; +( /** @type {Object} */ (myObject.property)).someProp = true; +const prop = /** @type {Object} */ (myObject.property).someProp; +const test = /** @type (function (*): ?|undefined) */ ( + goog.partial(NewThing.onTemplateChange, rationaleField, typeField) +); +const test = /** @type (function (*): ?|undefined) */ ( + goog.partial(NewThing.onTemplateChange, rationaleField, typeField) +); +const model = /** @type {?{getIndex: Function}} */ (model); +const foo = /** @type {string} */ (bar); +const test = /** @type (function (*): ?|undefined) */ (foo); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-8045.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-8045.js.snap.new new file mode 100644 index 00000000000..4a00dfbb16d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/issue-8045.js.snap.new @@ -0,0 +1,67 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-8045.js +--- +# Input +```js +const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ (fooBarBaz); + +function jsdocCastInReturn() { + return /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ (fooBarBaz); +} + +const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ + (fooBarBaz); + +function jsdocCastInReturn() { + return (/** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ + (fooBarBaz)); +} + +const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ + (fooBarBaz); + +function jsdocCastInReturn() { + return (/** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ + (fooBarBaz)); +} + +``` + +# Output +```js +const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( + fooBarBaz +); +function jsdocCastInReturn() { + return /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( + fooBarBaz + ); +} +const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( + fooBarBaz +); +function jsdocCastInReturn() { + return ( + /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ (fooBarBaz) + ); +} +const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( + fooBarBaz +); +function jsdocCastInReturn() { + return ( + /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ (fooBarBaz) + ); +} + +``` + +# Lines exceeding max width of 80 characters +``` + 1: const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( + 9: const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( + 17: const myLongVariableName = /** @type {ThisIsAVeryLongTypeThatShouldTriggerLineWrapping} */ ( +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/nested.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/nested.js.snap.new new file mode 100644 index 00000000000..07bdb632f40 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/nested.js.snap.new @@ -0,0 +1,31 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: nested.js +--- +# Input +```js +foo = /** @type {!Foo} */ (/** @type {!Baz} */ (baz).bar ); + +const BarImpl = /** @type {BarConstructor} */ ( + /** @type {unknown} */ + (function Bar() { + throw new Error("Internal error: Illegal constructor"); + }) +); + +``` + +# Output +```js +foo = /** @type {!Foo} */ ( /** @type {!Baz} */ (baz).bar); +const BarImpl = /** @type {BarConstructor} */ ( + /** @type {unknown} */ + (function Bar() { + throw new Error("Internal error: Illegal constructor"); + }) +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap.new new file mode 100644 index 00000000000..ff0475aaf7d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/non-casts.js.snap.new @@ -0,0 +1,49 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: non-casts.js +--- +# Input +```js +/* @type { } */ +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); + +``` + +# Output +```js +/* @type { } */ +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-closure-typecast/object-with-comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/object-with-comment.js.snap.new new file mode 100644 index 00000000000..72dfb346f8e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/object-with-comment.js.snap.new @@ -0,0 +1,38 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: object-with-comment.js +--- +# Input +```js +const objectWithComment = /** @type MyType */ ( + /* comment */ + { + foo: bar + } +); + +const objectWithComment2 = /** @type MyType */ ( /* comment */ { + foo: bar + } +); + +``` + +# Output +```js +const objectWithComment = /** @type MyType */ ( + /* comment */ + { + foo: bar, + } +); +const objectWithComment2 = /** @type MyType */ ( + /* comment */ { + foo: bar, + } +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/ways-to-specify-type.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/ways-to-specify-type.js.snap.new new file mode 100644 index 00000000000..6311ee5cc13 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-closure-typecast/ways-to-specify-type.js.snap.new @@ -0,0 +1,41 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: ways-to-specify-type.js +--- +# Input +```js +const curlyBraces = /** @type {string} */ (foo); +const curlyBraces2 = /**@type {string} */ (foo); +const noWhitespace = /** @type{string} */ (foo); +const noWhitespace2 = /**@type{string} */ (foo); +const noBraces = /** @type string */ (foo); +const parens = /** @type (string | number) */ (foo); + +// Prettier just searches for "@type" and doesn't check the syntax of types. +const v1 = /** @type {} */ (value); +const v2 = /** @type {}} */ (value); +const v3 = /** @type } */ (value); +const v4 = /** @type { */ (value); +const v5 = /** @type {{} */ (value); + +``` + +# Output +```js +const curlyBraces = /** @type {string} */ (foo); +const curlyBraces2 = /**@type {string} */ (foo); +const noWhitespace = /** @type{string} */ (foo); +const noWhitespace2 = /**@type{string} */ (foo); +const noBraces = /** @type string */ (foo); +const parens = /** @type (string | number) */ (foo); +// Prettier just searches for "@type" and doesn't check the syntax of types. +const v1 = /** @type {} */ (value); +const v2 = /** @type {}} */ (value); +const v3 = /** @type } */ (value); +const v4 = /** @type { */ (value); +const v5 = /** @type {{} */ (value); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments-pipeline-own-line/pipeline_own_line.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments-pipeline-own-line/pipeline_own_line.js.snap.new new file mode 100644 index 00000000000..d508a273b8a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments-pipeline-own-line/pipeline_own_line.js.snap.new @@ -0,0 +1,159 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: pipeline_own_line.js +--- +# Input +```js +function pipeline() { + 0 + // Comment + |> x +} + +bifornCringerMoshedPerplexSawder( + askTrovenaBeenaDependsRowans, + glimseGlyphsHazardNoopsTieTie, + averredBathersBoxroomBuggyNurl +) // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; + +bifornCringerMoshedPerplexSawder( + askTrovenaBeenaDependsRowans, + glimseGlyphsHazardNoopsTieTie +) +|> foo // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; + +bifornCringerMoshedPerplexSawder[ + askTrovenaBeenaDependsRowans + + glimseGlyphsHazardNoopsTieTie + + averredBathersBoxroomBuggyNurl +] // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; + +bifornCringerMoshedPerplexSawder[ + askTrovenaBeenaDependsRowans + + glimseGlyphsHazardNoopsTieTie + + averredBathersBoxroomBuggyNurl +] +|> foo // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; + +``` + +# Output +```js +function pipeline() { + 0 + // Comment + |> x +} +bifornCringerMoshedPerplexSawder( + askTrovenaBeenaDependsRowans, + glimseGlyphsHazardNoopsTieTie, + averredBathersBoxroomBuggyNurl +) // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; +bifornCringerMoshedPerplexSawder( + askTrovenaBeenaDependsRowans, + glimseGlyphsHazardNoopsTieTie +) +|> foo // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; +bifornCringerMoshedPerplexSawder[ + askTrovenaBeenaDependsRowans + + glimseGlyphsHazardNoopsTieTie + + averredBathersBoxroomBuggyNurl +] // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; +bifornCringerMoshedPerplexSawder[ + askTrovenaBeenaDependsRowans + + glimseGlyphsHazardNoopsTieTie + + averredBathersBoxroomBuggyNurl +] +|> foo // comment +|> kochabCooieGameOnOboleUnweave +|> glimseGlyphsHazardNoopsTieTie; + +``` + +# Errors +``` +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:4:3 + │ +4 │ |> x + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:12:2 + │ +12 │ |> kochabCooieGameOnOboleUnweave + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:13:2 + │ +13 │ |> glimseGlyphsHazardNoopsTieTie; + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:19:2 + │ +19 │ |> foo // comment + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:20:2 + │ +20 │ |> kochabCooieGameOnOboleUnweave + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:21:2 + │ +21 │ |> glimseGlyphsHazardNoopsTieTie; + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:28:2 + │ +28 │ |> kochabCooieGameOnOboleUnweave + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:29:2 + │ +29 │ |> glimseGlyphsHazardNoopsTieTie; + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:36:2 + │ +36 │ |> foo // comment + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:37:2 + │ +37 │ |> kochabCooieGameOnOboleUnweave + │ ^ This operator requires a left hand side value + +error[SyntaxError]: Expected an expression for the left hand side of the `>` operator. + ┌─ pipeline_own_line.js:38:2 + │ +38 │ |> glimseGlyphsHazardNoopsTieTie; + │ ^ This operator requires a left hand side value + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap.new new file mode 100644 index 00000000000..19985246aaa --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/arrow.js.snap.new @@ -0,0 +1,21 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: arrow.js +--- +# Input +```js +const fn = (/*event, data*/) => doSomething(); + +const fn2 = (/*event, data*/) => doSomething(anything); + +``` + +# Output +```js +const fn = ( /*event, data*/ ) => doSomething(); +const fn2 = ( /*event, data*/ ) => doSomething(anything); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/assignment-pattern.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/assignment-pattern.js.snap.new new file mode 100644 index 00000000000..29ad221d7ae --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/assignment-pattern.js.snap.new @@ -0,0 +1,27 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: assignment-pattern.js +--- +# Input +```js +const { a /* comment */ = 1 } = b; + +const { c = 1 /* comment */ } = d; + +let {d //comment += b} = c + +``` + +# Output +```js +const { a /* comment */ = 1 } = b; +const { c = 1 /* comment */ } = d; +let { + d = b, //comment +} = c; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-block-comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-block-comments.js.snap.new new file mode 100644 index 00000000000..22fe0f710ec --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-block-comments.js.snap.new @@ -0,0 +1,104 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: binary-expressions-block-comments.js +--- +# Input +```js +a = b || /** Comment */ +c; + +a = b /** Comment */ || +c; + +a = b || /** TODO this is a very very very very long comment that makes it go > 80 columns */ +c; + +a = b /** TODO this is a very very very very long comment that makes it go > 80 columns */ || +c; + +a = b || /** TODO this is a very very very very long comment that makes it go > 80 columns */ c; + +a = b && /** Comment */ +c; + +a = b /** Comment */ && +c; + +a = b && /** TODO this is a very very very very long comment that makes it go > 80 columns */ +c; + +a = b /** TODO this is a very very very very long comment that makes it go > 80 columns */ && +c; + +a = b && /** TODO this is a very very very very long comment that makes it go > 80 columns */ c; + +a = b + /** Comment */ +c; + +a = b /** Comment */ + +c; + +a = b + /** TODO this is a very very very very long comment that makes it go > 80 columns */ +c; + +a = b /** TODO this is a very very very very long comment that makes it go > 80 columns */ + +c; + +a = b + /** TODO this is a very very very very long comment that makes it go > 80 columns */ c; +``` + +# Output +```js +a = + b || /** Comment */ + c; +a = b /** Comment */ || c; +a = + b || /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; +a = + b /** TODO this is a very very very very long comment that makes it go > 80 columns */ || c; +a = + b || /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; +a = + b && /** Comment */ + c; +a = b /** Comment */ && c; +a = + b && /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; +a = + b /** TODO this is a very very very very long comment that makes it go > 80 columns */ && c; +a = + b && /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; +a = + b + /** Comment */ + c; +a = b /** Comment */ + c; +a = + b + /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; +a = + b /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; +a = + b + /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; + +``` + +# Lines exceeding max width of 80 characters +``` + 6: b || /** TODO this is a very very very very long comment that makes it go > 80 columns */ + 9: b /** TODO this is a very very very very long comment that makes it go > 80 columns */ || c; + 11: b || /** TODO this is a very very very very long comment that makes it go > 80 columns */ + 18: b && /** TODO this is a very very very very long comment that makes it go > 80 columns */ + 21: b /** TODO this is a very very very very long comment that makes it go > 80 columns */ && c; + 23: b && /** TODO this is a very very very very long comment that makes it go > 80 columns */ + 30: b + /** TODO this is a very very very very long comment that makes it go > 80 columns */ + 33: b /** TODO this is a very very very very long comment that makes it go > 80 columns */ + c; + 35: b + /** TODO this is a very very very very long comment that makes it go > 80 columns */ +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-single-comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-single-comments.js.snap.new new file mode 100644 index 00000000000..9023b554ecd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions-single-comments.js.snap.new @@ -0,0 +1,56 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: binary-expressions-single-comments.js +--- +# Input +```js +a = b || // Comment +c; + +a = b || // TODO this is a very very very very long comment that makes it go > 80 columns +c; + +a = b && // Comment +c; + +a = b && // TODO this is a very very very very long comment that makes it go > 80 columns +c; + +a = b + // Comment +c; + +a = b + // TODO this is a very very very very long comment that makes it go > 80 columns +c; +``` + +# Output +```js +a = + b || // Comment + c; +a = + b || // TODO this is a very very very very long comment that makes it go > 80 columns + c; +a = + b && // Comment + c; +a = + b && // TODO this is a very very very very long comment that makes it go > 80 columns + c; +a = + b + // Comment + c; +a = + b + // TODO this is a very very very very long comment that makes it go > 80 columns + c; + +``` + +# Lines exceeding max width of 80 characters +``` + 5: b || // TODO this is a very very very very long comment that makes it go > 80 columns + 11: b && // TODO this is a very very very very long comment that makes it go > 80 columns + 17: b + // TODO this is a very very very very long comment that makes it go > 80 columns +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions.js.snap.new new file mode 100644 index 00000000000..b69b8856306 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/binary-expressions.js.snap.new @@ -0,0 +1,147 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: binary-expressions.js +--- +# Input +```js +function addition() { + 0 + // Comment + + x +} + +function multiplication() { + 0 + // Comment + * x +} + +function division() { + 0 + // Comment + / x +} + +function substraction() { + 0 + // Comment + - x +} + +function remainder() { + 0 + // Comment + % x +} + +function exponentiation() { + 0 + // Comment + ** x +} + +function leftShift() { + 0 + // Comment + << x +} + +function rightShift() { + 0 + // Comment + >> x +} + +function unsignedRightShift() { + 0 + // Comment + >>> x +} + +function bitwiseAnd() { + 0 + // Comment + & x +} + +function bitwiseOr() { + 0 + // Comment + | x +} + +function bitwiseXor() { + 0 + // Comment + ^ x +} + +``` + +# Output +```js +function addition() { + 0 + // Comment + + x; +} +function multiplication() { + 0 + // Comment + * x; +} +function division() { + 0 + // Comment + / x; +} +function substraction() { + 0 + // Comment + - x; +} +function remainder() { + 0 + // Comment + % x; +} +function exponentiation() { + 0 + // Comment + ** x; +} +function leftShift() { + 0 + // Comment + << x; +} +function rightShift() { + 0 + // Comment + >> x; +} +function unsignedRightShift() { + 0 + // Comment + >>> x; +} +function bitwiseAnd() { + 0 + // Comment + & x; +} +function bitwiseOr() { + 0 + // Comment + | x; +} +function bitwiseXor() { + 0 + // Comment + ^ x; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/break-continue-statements.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/break-continue-statements.js.snap.new new file mode 100644 index 00000000000..e680c0dcc38 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/break-continue-statements.js.snap.new @@ -0,0 +1,37 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: break-continue-statements.js +--- +# Input +```js +for (;;) { + break /* comment */; + continue /* comment */; +} + +loop: for (;;) { + break /* comment */ loop; + break loop /* comment */; + continue /* comment */ loop; + continue loop /* comment */; +} + +``` + +# Output +```js +for (;;) { + break /* comment */ ; + continue /* comment */ ; +} +loop: for (;;) { + break /* comment */ loop; + break loop /* comment */ ; + continue /* comment */ loop; + continue loop /* comment */ ; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap.new new file mode 100644 index 00000000000..9d8b394dcdc --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/call_comment.js.snap.new @@ -0,0 +1,54 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: call_comment.js +--- +# Input +```js +render( // Warm any cache + , + container +); + +React.render( // Warm any cache + , + container +); + +render?.( // Warm any cache + , + container +); + +``` + +# Output +```js +render( + , + container, +); +React.render( + , + container, +); +render?.( + , + container, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/class.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/class.js.snap.new new file mode 100644 index 00000000000..4fc1d985b30 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/class.js.snap.new @@ -0,0 +1,35 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: class.js +--- +# Input +```js +// #8718 +class C { + ma() {} /* D */ /* E */ + mb() {} +} + +class D { + ma() {} /* D */ /* E */ /* F */ + mb() {} +} + +``` + +# Output +```js +// #8718 +class C { + ma() {} /* D */ /* E */ + mb() {} +} +class D { + ma() {} /* D */ /* E */ /* F */ + mb() {} +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap.new new file mode 100644 index 00000000000..211775c07e2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling.js.snap.new @@ -0,0 +1,38 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: dangling.js +--- +# Input +```js +var a = {/* dangling */}; +var b = { + // dangling +}; +var b = [/* dangling */]; +function d() { + /* dangling */ +} +new Thing(/* dangling */); +Thing(/* dangling */); +export /* dangling */{}; + +``` + +# Output +```js +var a = { /* dangling */ }; +var b = { + // dangling +}; +var b = [ /* dangling */ ]; +function d() { + /* dangling */ +} +new Thing( /* dangling */ ); +Thing( /* dangling */ ); +export /* dangling */ { }; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap.new new file mode 100644 index 00000000000..61717c66730 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_array.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: dangling_array.js +--- +# Input +```js +expect(() => {}).toTriggerReadyStateChanges([ + // Nothing. +]); + +[1 /* first comment */, 2 /* second comment */, 3]; + +``` + +# Output +```js +expect(() => {},).toTriggerReadyStateChanges([ + // Nothing. +],); +[1 /* first comment */ , 2 /* second comment */ , 3]; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_for.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_for.js.snap.new new file mode 100644 index 00000000000..b3fc80b50ed --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dangling_for.js.snap.new @@ -0,0 +1,22 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: dangling_for.js +--- +# Input +```js +for // comment +(;;); + +for /* comment */(;;); + +``` + +# Output +```js +for (;;); // comment +for /* comment */ (;;); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap.new new file mode 100644 index 00000000000..53812852ca2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/dynamic_imports.js.snap.new @@ -0,0 +1,45 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: dynamic_imports.js +--- +# Input +```js +import(/* Hello */ 'something') + +import('something' /* Hello */) + +import(/* Hello */ 'something' /* Hello */) + +import('something' /* Hello */ + 'else') + +import( + /* Hello */ + 'something' + /* Hello */ +) + +wrap( + import(/* Hello */ + 'something' + ) +) + +``` + +# Output +```js +import( /* Hello */ "something"); +import("something" /* Hello */ ); +import( /* Hello */ "something" /* Hello */ ); +import("something" /* Hello */ + "else"); +import( + /* Hello */ + "something", + /* Hello */ +); +wrap(import( /* Hello */ "something")); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/emoji.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/emoji.js.snap.new new file mode 100644 index 00000000000..6268d3c92d9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/emoji.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: emoji.js +--- +# Input +```js +/* #2091 */ + +const test = '💖' +// This comment +// should not get collapsed + +``` + +# Output +```js +/* #2091 */ + +const test = "💖"; // should not get collapsed +// This comment + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/export.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/export.js.snap.new new file mode 100644 index 00000000000..75e38c75c1d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/export.js.snap.new @@ -0,0 +1,55 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: export.js +--- +# Input +```js +export //comment +{} + +export /* comment */ {}; + +const foo = '' +export { + foo // comment +} + +const bar = '' +export { + // comment + bar +} + +const fooo = '' +const barr = '' +export { + fooo, // comment + barr, // comment +} + +``` + +# Output +```js +export { }; //comment +export /* comment */ { }; +const foo = ""; +export { + foo, // comment +}; +const bar = ""; +export { + // comment + bar, +}; +const fooo = ""; +const barr = ""; +export { + fooo, // comment + barr, // comment +}; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap.new new file mode 100644 index 00000000000..73224e9d039 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/function-declaration.js.snap.new @@ -0,0 +1,133 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: function-declaration.js +--- +# Input +```js +function a(/* comment */) {} // comment +function b() {} // comment +function c(/* comment */ argA, argB, argC) {} // comment +call((/*object*/ row) => {}); +KEYPAD_NUMBERS.map(num => ( // Buttons 0-9 +
+)); + +function f1 /* f */() {} +function f2 (/* args */) {} +function f3 () /* returns */ {} +function f4 /* f */(/* args */) /* returns */ {} + +function f5 /* f */(/* a */ a) {} +function f6 /* f */(a /* a */) {} +function f7 /* f */(/* a */ a) /* returns */ {} + +const obj = { + f1 /* f */() {}, + f2 (/* args */) {}, + f3 () /* returns */ {}, + f4 /* f */(/* args */) /* returns */ {}, +}; + +(function f /* f */() {})(); +(function f (/* args */) {})(); +(function f () /* returns */ {})(); +(function f /* f */(/* args */) /* returns */ {})(); + +class C1 { + f/* f */() {} +} +class C2 { + f(/* args */) {} +} +class C3 { + f() /* returns */ {} +} +class C4 { + f/* f */(/* args */) /* returns */ {} +} + +function foo1() +// this is a function +{ + return 42 +} + +function foo2() // this is a function +{ + return 42 +} + +function foo3() { // this is a function + return 42 +} + +function foo4() { + // this is a function + return 42; +} + +``` + +# Output +```js +function a( /* comment */ ) {} // comment +function b() {} // comment +function c( /* comment */ argA, argB, argC) {} // comment +call(( /*object*/ row) => {}); +KEYPAD_NUMBERS.map( + ( + num, + ) => ( +
// Buttons 0-9 + ), +); +function f1 /* f */ () {} +function f2( /* args */ ) {} +function f3() /* returns */ {} +function f4 /* f */ ( /* args */ ) /* returns */ {} +function f5 /* f */ ( /* a */ a) {} +function f6 /* f */ (a /* a */ ) {} +function f7 /* f */ ( /* a */ a) /* returns */ {} +const obj = { + f1 /* f */ () {}, + f2( /* args */ ) {}, + f3() /* returns */ {}, + f4 /* f */ ( /* args */ ) /* returns */ {}, +}; +(function f /* f */ () {})(); +(function f( /* args */ ) {})(); +(function f() /* returns */ {})(); +(function f /* f */ ( /* args */ ) /* returns */ {})(); +class C1 { + f /* f */ () {} +} +class C2 { + f( /* args */ ) {} +} +class C3 { + f() /* returns */ {} +} +class C4 { + f /* f */ ( /* args */ ) /* returns */ {} +} +function foo1() +// this is a function +{ + return 42; +} +function foo2() { + // this is a function + return 42; +} +function foo3() { + return 42; // this is a function +} +function foo4() { + // this is a function + return 42; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/jsdoc.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/jsdoc.js.snap.new new file mode 100644 index 00000000000..9a52c883752 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/jsdoc.js.snap.new @@ -0,0 +1,69 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: jsdoc.js +--- +# Input +```js +/** @type {any} */ +const x = ( +
+
+
+); + +/** + * @type {object} + */ +() => ( +
+ sajdfpoiasdjfpoiasdjfpoiasdjfpoiadsjfpaoisdjfapsdiofjapioisadfaskfaspiofjp +
+); + +/** + * @type {object} + */ +function HelloWorld() { + return ( +
+ Test +
+ ); +} +``` + +# Output +```js +/** @type {any} */ +const x = ( +
+
+
+); +/** + * @type {object} + */ +() => ( +
+ sajdfpoiasdjfpoiasdjfpoiasdjfpoiadsjfpaoisdjfapsdiofjapioisadfaskfaspiofjp +
+); +/** + * @type {object} + */ +function HelloWorld() { + return ( +
+ Test +
+ ); +} + +``` + +# Lines exceeding max width of 80 characters +``` + 12: sajdfpoiasdjfpoiasdjfpoiasdjfpoiadsjfpaoisdjfapsdiofjapioisadfaskfaspiofjp +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/jsx.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/jsx.js.snap.new new file mode 100644 index 00000000000..be0b20ea2bb --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/jsx.js.snap.new @@ -0,0 +1,242 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: jsx.js +--- +# Input +```js +
+ { + /* comment */ + } +
; + +
+ {/* comment */ + } +
; + +
+ {/* comment +*/ + } +
; + +
+ {a/* comment +*/ + } +
; + +
+ {/* comment +*/ + a + } +
; + +
+ {/* comment */ + } +
; + +
+ {/* comment */} +
; + +
+ { + // single line comment + } +
; + +
+ { + // multiple line comments 1 + // multiple line comments 2 + } +
; + +
+ { + // multiple mixed comments 1 + /* multiple mixed comments 2 */ + /* multiple mixed comments 3 */ + // multiple mixed comments 4 + } +
; + +
+ { + // Some very v ery very very merry (xmas) very very long line to break line width limit + } +
; + +
{/*
Some very v ery very very long line to break line width limit
*/}
; + +
+ {/** + * JSDoc-y comment in JSX. I wonder what will happen to it? + */} +
; + +
+ { + /** + * Another JSDoc comment in JSX. + */ + } +
; + +
{}}> + +
; + +
+ {foo} +
; + +
+ {foo} +
; + +
+ {foo} +
; + +
+ {children} +
; + + + {} + + + +``` + +# Output +```js +
+ { + /* comment */ + } +
; +
+ {/* comment */ + } +
; +
+ {/* comment +*/ + } +
; +
+ {a/* comment +*/ + } +
; +
+ {/* comment +*/ + a + } +
; +
+ {/* comment */ + } +
; +
+ {/* comment */} +
; +
+ { + // single line comment + } +
; +
+ { + // multiple line comments 1 + // multiple line comments 2 + } +
; +
+ { + // multiple mixed comments 1 + /* multiple mixed comments 2 */ + /* multiple mixed comments 3 */ + // multiple mixed comments 4 + } +
; +
+ { + // Some very v ery very very merry (xmas) very very long line to break line width limit + } +
; +
{/*
Some very v ery very very long line to break line width limit
*/}
; +
+ {/** + * JSDoc-y comment in JSX. I wonder what will happen to it? + */} +
; +
+ { + /** + * Another JSDoc comment in JSX. + */ + } +
; +
{}}> + +
; +
+ {foo} +
; +
+ {foo} +
; +
+ {foo} +
; +
+ {children} +
; + + {} + +; + +``` + +# Lines exceeding max width of 80 characters +``` + 54: // Some very v ery very very merry (xmas) very very long line to break line width limit + 57:
{/*
Some very v ery very very long line to break line width limit
*/}
; +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/multi-comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/multi-comments.js.snap.new new file mode 100644 index 00000000000..1e1980806c6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/multi-comments.js.snap.new @@ -0,0 +1,51 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: multi-comments.js +--- +# Input +```js +// #8323 + +import { MapViewProps } from 'react-native-maps'; /* +comment 14 +*/ /* comment1 +10 +*/ /*/ comment 13 */ +/* + comment 9 + ****/ +import * as ts from 'typescript'; + +x; /* +1 */ /* 2 */ + +y + +x; /*1*//*2*/ +y; + +``` + +# Output +```js +// #8323 + +import { MapViewProps } from "react-native-maps"; /* +comment 14 +*/ /* comment1 +10 +*/ /*/ comment 13 */ +/* + comment 9 + ****/ +import * as ts from "typescript"; +x; /* +1 */ /* 2 */ +y; +x; /*1*/ /*2*/ +y; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/preserve-new-line-last.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/preserve-new-line-last.js.snap.new new file mode 100644 index 00000000000..4b5a1085bb1 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/preserve-new-line-last.js.snap.new @@ -0,0 +1,52 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: preserve-new-line-last.js +--- +# Input +```js +function f() { + a + /* eslint-disable */ +} + +function f() { + a + + /* eslint-disable */ +} + +function name() { + // comment1 + func1() + + // comment2 + func2() + + // comment3 why func3 commented + // func3() +} + +``` + +# Output +```js +function f() { + a; + /* eslint-disable */ +} +function f() { + a; + /* eslint-disable */ +} +function name() { + // comment1 + func1(); + // comment2 + func2(); // func3() + // comment3 why func3 commented +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/switch.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/switch.js.snap.new new file mode 100644 index 00000000000..ef9f1a6d5a6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/switch.js.snap.new @@ -0,0 +1,87 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: switch.js +--- +# Input +```js +switch (node && node.type) { + case "Property": + case "MethodDefinition": + prop = node.key; + break; + + case "MemberExpression": + prop = node.property; + break; + + // no default +} + +switch (foo) { + case "bar": + doThing() + + // no default +} + +switch (foo) { + case "bar": //comment + doThing(); //comment + + case "baz": + doOtherThing(); //comment + +} + +switch (foo) { + case "bar": { + doThing(); + } //comment + + case "baz": { + doThing(); + } //comment +} + +``` + +# Output +```js +switch (node && node.type) { + case "Property": + case "MethodDefinition": + prop = node.key; + break; + + case "MemberExpression": + prop = node.property; + break; + // no default +} +switch (foo) { + case "bar": + doThing(); + // no default +} +switch (foo) { + case "bar": + //comment + doThing(); //comment + + case "baz": + doOtherThing(); //comment +} +switch (foo) { + case "bar": { + doThing(); + } //comment + + case "baz": { + doThing(); + } //comment +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/tagged-template-literal.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/tagged-template-literal.js.snap.new new file mode 100644 index 00000000000..a883f60d8b8 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/tagged-template-literal.js.snap.new @@ -0,0 +1,41 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: tagged-template-literal.js +--- +# Input +```js +foo``; // comment + +foo // comment +``; + +foo // comment +` +`; + +foo /* comment */` +`; + +foo /* comment */ +` +`; + +``` + +# Output +```js +foo``; // comment +foo // comment +``; +foo // comment +` +`; +foo /* comment */ ` +`; +foo /* comment */ ` +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/template-literal.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/template-literal.js.snap.new new file mode 100644 index 00000000000..22380afb9f7 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/template-literal.js.snap.new @@ -0,0 +1,41 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: template-literal.js +--- +# Input +```js +` +${a // comment +} + +${b /* comment */} + +${/* comment */ c /* comment */} + +${// comment +d //comment +}; +` + +``` + +# Output +```js +` +${ + a // comment +} + +${b /* comment */ } + +${ /* comment */ c /* comment */ } + +${ + d // comment //comment +}; +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/variable_declarator.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/variable_declarator.js.snap.new new file mode 100644 index 00000000000..429982e7702 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/variable_declarator.js.snap.new @@ -0,0 +1,126 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: variable_declarator.js +--- +# Input +```js +let obj1 = // Comment +{ + key: 'val' +} + +let obj2 // Comment += { + key: 'val' +} + +let obj3 = { // Comment + key: 'val' +} + +let obj4 = { + // Comment + key: 'val' +} + +let obj5 = // Comment +[ + 'val' +] + +let obj6 // Comment += [ + 'val' +] + +let obj7 = [ // Comment + 'val' +] + +let obj8 = [ + // Comment + 'val' +] + +let obj9 = // Comment +`val`; + +let obj10 = // Comment +` +val +val +`; + +let obj11 = // Comment +tag`val`; + +let obj12 = // Comment +tag` +val +val +`; + +let // Comment + foo1 = 'val'; + +let // Comment + foo2 = 'val', + bar = 'val'; + +const foo3 = 123 +// Nothing to see here. +;["2", "3"].forEach(x => console.log(x)) + +``` + +# Output +```js +let obj1 = { + // Comment + key: "val", +}; +let obj2 = { + // Comment + key: "val", +}; +let obj3 = { + key: "val", // Comment +}; +let obj4 = { + // Comment + key: "val", +}; +let obj5 = ["val"]; // Comment +let obj6 = ["val"]; // Comment +let obj7 = [ + "val", // Comment +]; +let obj8 = [ + // Comment + "val", +]; +let obj9 = // Comment +`val`; +let obj10 = // Comment +` +val +val +`; +let obj11 = tag // Comment +`val`; +let obj12 = tag // Comment +` +val +val +`; +let foo1 = "val"; // Comment +let foo2 = "val", bar = "val"; // Comment +const foo3 = 123 +// Nothing to see here. +; +["2", "3"].forEach((x) => console.log(x)); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/comments/while.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/comments/while.js.snap.new new file mode 100644 index 00000000000..4401ff7943a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/comments/while.js.snap.new @@ -0,0 +1,52 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: while.js +--- +# Input +```js +while( + true + // Comment + ) {} + +while(true)// Comment +{} + +while(true){}// Comment + +while(true)/*Comment*/{} + +while( + true // Comment + && true // Comment + ){} + +while(true) {} // comment + +while(true) /* comment */ ++x; + +while(1) // Comment + foo(); + +``` + +# Output +```js +while ( + true + // Comment +) {} +while (true) {} // Comment +while (true) {} // Comment +while (true) /*Comment*/ {} +while ( + true && true // Comment // Comment +) {} +while (true) {} // comment +while (true) /* comment */ ++x; +while (1) foo(); // Comment + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/conditional/comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/conditional/comments.js.snap.new new file mode 100644 index 00000000000..bf21aaa8952 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/conditional/comments.js.snap.new @@ -0,0 +1,195 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comments.js +--- +# Input +```js +var inspect = 4 === util.inspect.length + ? // node <= 0.8.x + (function(v, colors) { + return util.inspect(v, void 0, void 0, colors); + }) + : // node > 0.8.x + (function(v, colors) { + return util.inspect(v, { colors: colors }); + }); + +var inspect = 4 === util.inspect.length + ? // node <= 0.8.x + (function(v, colors) { + return util.inspect(v, void 0, void 0, colors); + }) + : // node > 0.8.x + (function(v, colors) { + return util.inspect(v, { colors: colors }); + }); + +const extractTextPluginOptions = shouldUseRelativeAssetPaths + // Making sure that the publicPath goes back to to build folder. + ? { publicPath: Array(cssFilename.split('/').length).join('../') } : + {}; + +const extractTextPluginOptions2 = shouldUseRelativeAssetPaths + ? // Making sure that the publicPath goes back to to build folder. + { publicPath: Array(cssFilename.split("/").length).join("../") } + : {}; + +const extractTextPluginOptions3 = shouldUseRelativeAssetPaths // Making sure that the publicPath goes back to to build folder. + ? { publicPath: Array(cssFilename.split("/").length).join("../") } + : {}; + +const { configureStore } = process.env.NODE_ENV === "production" + ? require("./configureProdStore") // a + : require("./configureDevStore"); // b + +test /* comment + comment + comment +*/ + ? foo + : bar; + +test + ? /* comment + comment + comment + comment + */ + foo + : bar; + +test + ? /* comment + comment + comment + comment + */ + foo + : test + ? /* comment + comment + comment */ + foo + : bar; + +test + ? /* comment */ + foo + : bar; + +test + ? foo + : /* comment + comment + comment + comment + */ + bar; + +test + ? foo + : /* comment + comment + comment + comment + */ + test + ? foo + : /* comment + comment + comment + */ + bar; + +test + ? foo + : /* comment */ + bar; + +test ? test /* c +c */? foo : bar : bar; + +``` + +# Output +```js +var inspect = 4 === util.inspect.length ? (function (v, colors) { + // node <= 0.8.x + return util.inspect(v, void 0, void 0, colors); +}) : (function (v, colors) { + // node > 0.8.x + return util.inspect(v, { colors: colors }); +}); +var inspect = 4 === util.inspect.length ? (function (v, colors) { + // node <= 0.8.x + return util.inspect(v, void 0, void 0, colors); +}) : (function (v, colors) { + // node > 0.8.x + return util.inspect(v, { colors: colors }); +}); +const extractTextPluginOptions = shouldUseRelativeAssetPaths +// Making sure that the publicPath goes back to to build folder. +? { publicPath: Array(cssFilename.split("/").length).join("../") } : {}; +const extractTextPluginOptions2 = shouldUseRelativeAssetPaths ? { + // Making sure that the publicPath goes back to to build folder. + publicPath: Array(cssFilename.split("/").length).join("../"), +} : {}; +const extractTextPluginOptions3 = shouldUseRelativeAssetPaths ? { + // Making sure that the publicPath goes back to to build folder. + publicPath: Array(cssFilename.split("/").length).join("../"), +} : {}; +const { + configureStore, +} = process.env.NODE_ENV === "production" ? require( + "./configureProdStore", +) : require("./configureDevStore"); // a // b +test /* comment + comment + comment +*/ ? foo : bar; +test ? /* comment + comment + comment + comment + */ foo : bar; +test + ? /* comment + comment + comment + comment + */ foo + : test + ? /* comment + comment + comment */ foo + : bar; +test ? /* comment */ foo : bar; +test ? foo : /* comment + comment + comment + comment + */ bar; +test + ? foo + : /* comment + comment + comment + comment + */ test + ? foo + : /* comment + comment + comment + */ bar; +test ? foo : /* comment */ bar; +test + ? test /* c +c */ + ? foo + : bar + : bar; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-4.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-4.js.snap.new new file mode 100644 index 00000000000..f0781e67916 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-4.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: cursor-4.js +--- +# Input +```js + + + const y = 5 + + + + const z = 9 + +``` + +# Output +```js +const y = 5; +const z = 9; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-7.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-7.js.snap.new new file mode 100644 index 00000000000..fb9939fc6fc --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/cursor/cursor-7.js.snap.new @@ -0,0 +1,22 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: cursor-7.js +--- +# Input +```js +const y = 5 + + +const z = 9 + +``` + +# Output +```js +const y = 5; +const z = 9; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/after_export.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/after_export.js.snap.new new file mode 100644 index 00000000000..e1f90b41503 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/after_export.js.snap.new @@ -0,0 +1,46 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: after_export.js +--- +# Input +```js +export @decorator class Foo {} + +export default @decorator class {} + +``` + +# Output +```js +export +@decorator class Foo {} +export default +@decorator class {} + +``` + +# Errors +``` +error[SyntaxError]: expected a class, a function, or a variable declaration but instead found '@' + ┌─ after_export.js:1:8 + │ +1 │ export @decorator class Foo {} + │ ^ Expected a class, a function, or a variable declaration here + +error[SyntaxError]: expected an expression but instead found '@' + ┌─ after_export.js:3:16 + │ +3 │ export default @decorator class {} + │ ^ Expected an expression here + +error[SyntaxError]: class declarations must have a name + ┌─ after_export.js:3:27 + │ +3 │ export default @decorator class {} + │ ^^^^^^ + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/before_export.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/before_export.js.snap.new new file mode 100644 index 00000000000..2dd33d95362 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/decorators-export/before_export.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: before_export.js +--- +# Input +```js +@decorator +export class Foo {} + +@decorator +export default class {} + +``` + +# Output +```js +@decorator +export class Foo {} +@decorator +export default class {} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/decorators/classes.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/classes.js.snap.new new file mode 100644 index 00000000000..ee738728d78 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/classes.js.snap.new @@ -0,0 +1,72 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: classes.js +--- +# Input +```js +@deco class Foo {} + +@deco export class Bar {} + +@deco export default class Baz {} + +const foo = @deco class { + // +}; + +const bar = + @deco + class { + // + }; + +``` + +# Output +```js +@deco class Foo {} +@deco export class Bar {} +@deco export default class Baz {} +const foo = +@deco class { + // +} +const bar = +@deco + class { + // + } + +``` + +# Errors +``` +error[SyntaxError]: expected an expression, or an assignment but instead found '@' + ┌─ classes.js:7:13 + │ +7 │ const foo = @deco class { + │ ^ Expected an expression, or an assignment here + +error[SyntaxError]: class declarations must have a name + ┌─ classes.js:7:19 + │ +7 │ const foo = @deco class { + │ ^^^^^^ + +error[SyntaxError]: expected an expression, or an assignment but instead found '@' + ┌─ classes.js:12:3 + │ +12 │ @deco + │ ^ Expected an expression, or an assignment here + +error[SyntaxError]: class declarations must have a name + ┌─ classes.js:13:3 + │ +13 │ class { + │ ^^^^^^ + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/decorators/mobx.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/mobx.js.snap.new new file mode 100644 index 00000000000..0edf4a8e95f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/mobx.js.snap.new @@ -0,0 +1,124 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: mobx.js +--- +# Input +```js +import {observable} from "mobx"; + +@observer class OrderLine { + @observable price:number = 0; + @observable amount:number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed @computed @computed @computed @computed @computed @computed get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent) => this.count--; + + @action handleSomething = (event: React.ChangeEvent) => doSomething(); +} + +``` + +# Output +```js +import { observable } from "mobx"; +@observer class OrderLine { + @observable price:number = 0; + @observable amount:number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed @computed @computed @computed @computed @computed @computed get total() { + return this.price * this.amount; + } + + @action handleDecrease = ( + event: React.ChangeEvent, + ) => this.count--; + + @action handleSomething = ( + event: React.ChangeEvent, + ) => doSomething(); +} + +``` + +# Errors +``` +error[SyntaxError]: return types can only be used in TypeScript files + ┌─ mobx.js:4:20 + │ +4 │ @observable price:number = 0; + │ ^^^^^^^ remove this type annotation + +error[SyntaxError]: return types can only be used in TypeScript files + ┌─ mobx.js:5:21 + │ +5 │ @observable amount:number = 1; + │ ^^^^^^^ remove this type annotation + +error[SyntaxError]: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax. + ┌─ mobx.js:33:34 + │ +33 │ @action handleDecrease = (event: React.ChangeEvent) => this.count--; + │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeScript only syntax + +error[SyntaxError]: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax. + ┌─ mobx.js:35:35 + │ +35 │ @action handleSomething = (event: React.ChangeEvent) => doSomething(); + │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeScript only syntax + + +``` + +# Lines exceeding max width of 80 characters +``` + 28: @computed @computed @computed @computed @computed @computed @computed get total() { +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/decorators/multiple.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/multiple.js.snap.new new file mode 100644 index 00000000000..fbe12f5d41d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/multiple.js.snap.new @@ -0,0 +1,83 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: multiple.js +--- +# Input +```js +const dog = { + @readonly + @nonenumerable + @doubledValue + legs: 4, + + @readonly + @nonenumerable + @doubledValue + eyes: 2 +}; + +const foo = { + @multipleDecorators @inline @theyWontAllFitInOneline aVeryLongPropName: "A very long string as value" +}; + +``` + +# Output +```js +const dog = { +@readonly + @nonenumerable + @doubledValue + legs: 4, +@readonly + @nonenumerable + @doubledValue +eyes: 2; +} +const foo = { +@multipleDecorators @inline @theyWontAllFitInOneline aVeryLongPropName: ("A very long string as value"); +} + +``` + +# Errors +``` +error[SyntaxError]: expected a property, a shorthand property, a getter, a setter, or a method but instead found '@' + ┌─ multiple.js:2:3 + │ +2 │ @readonly + │ ^ Expected a property, a shorthand property, a getter, a setter, or a method here + +error[SyntaxError]: expected an expression but instead found '@' + ┌─ multiple.js:7:3 + │ +7 │ @readonly + │ ^ Expected an expression here + +error[SyntaxError]: expected a statement but instead found '}' + ┌─ multiple.js:11:1 + │ +11 │ }; + │ ^ Expected a statement here + +error[SyntaxError]: expected a property, a shorthand property, a getter, a setter, or a method but instead found '@' + ┌─ multiple.js:14:3 + │ +14 │ @multipleDecorators @inline @theyWontAllFitInOneline aVeryLongPropName: "A very long string as value" + │ ^ Expected a property, a shorthand property, a getter, a setter, or a method here + +error[SyntaxError]: expected a statement but instead found '}' + ┌─ multiple.js:15:1 + │ +15 │ }; + │ ^ Expected a statement here + + +``` + +# Lines exceeding max width of 80 characters +``` + 12: @multipleDecorators @inline @theyWontAllFitInOneline aVeryLongPropName: ("A very long string as value"); +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/decorators/redux.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/redux.js.snap.new new file mode 100644 index 00000000000..88cb133cd88 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/decorators/redux.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: redux.js +--- +# Input +```js +@connect(mapStateToProps, mapDispatchToProps) +export class MyApp extends React.Component {} + +@connect(state => ({ todos: state.todos })) +export class Home extends React.Component {} + +``` + +# Output +```js +@connect(mapStateToProps, mapDispatchToProps) +export class MyApp extends React.Component {} +@connect(state => ({ todos: state.todos })) +export class Home extends React.Component {} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/destructuring-ignore/ignore.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/destructuring-ignore/ignore.js.snap.new new file mode 100644 index 00000000000..802957f8013 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/destructuring-ignore/ignore.js.snap.new @@ -0,0 +1,94 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: ignore.js +--- +# Input +```js +const { + // prettier-ignore + bar = 1, +} = foo + +const { + _, + // prettier-ignore + bar2 = 1, +} = foo + +/* comments */ +const { + // prettier-ignore + bar3 = 1, // comment +} = foo + +const { + // prettier-ignore + bar4 = 1, /* comment */ +} = foo + +const { + // prettier-ignore + bar5 = /* comment */ 1, +} = foo + +/* RestElement */ +const { + // prettier-ignore + ...bar6 +} = foo + +// Nested +const { + baz: { + // prettier-ignore + foo2 = [1, 2, 3] +}, + // prettier-ignore + bar7 = 1, +} = foo + +``` + +# Output +```js +const { + // prettier-ignore + bar = 1, +} = foo; +const { + _, + // prettier-ignore + bar2 = 1, +} = foo; +/* comments */ +const { + // prettier-ignore + bar3 = 1, // comment +} = foo; +const { + // prettier-ignore + bar4 = 1, /* comment */ +} = foo; +const { + // prettier-ignore + bar5 = /* comment */ 1, +} = foo; +/* RestElement */ +const { + // prettier-ignore + ...bar6 +} = foo; +// Nested +const { + baz: { + // prettier-ignore + foo2 = [1, 2, 3], + }, + // prettier-ignore + bar7 = 1, +} = foo; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/destructuring/destructuring.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/destructuring/destructuring.js.snap.new new file mode 100644 index 00000000000..86eb60f3ab2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/destructuring/destructuring.js.snap.new @@ -0,0 +1,103 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: destructuring.js +--- +# Input +```js +const [one, two = null, three = null] = arr; +a = ([s=1,]) => 1 +const { children, ...props } = this.props + +const { user: { firstName, lastName } } = this.props; + +const { + name: { first, last }, + organisation: { address: { street: orgStreetAddress, postcode: orgPostcode } } +} = user; + +function f({ data: { name } }) {} + +const UserComponent = function({ + name: { first, last }, + organisation: { address: { street: orgStreetAddress, postcode: orgPostcode } }, +}) { + return +}; + +const { a, b, c, d: { e } } = someObject; + +try { + // code +} catch ({ data: { message }}) { + // code +} + +try { + // code +} catch ({ data: { message: { errors }}}) { + // code +} + +const obj = { + func(id, { blog: { title } }) { + return id + title; + }, +}; + +class A { + func(id, { blog: { title } }) { + return id + title; + } +} + +``` + +# Output +```js +const [one, two = null, three = null] = arr; +a = ([s = 1]) => 1; +const { children, ...props } = this.props; +const { user: { firstName, lastName } } = this.props; +const { + name: { first, last }, + organisation: { + address: { street: orgStreetAddress, postcode: orgPostcode }, + }, +} = user; +function f({ data: { name } }) {} +const UserComponent = function ( + { + name: { first, last }, + organisation: { + address: { street: orgStreetAddress, postcode: orgPostcode }, + }, + }, +) { + return; +}; +const { a, b, c, d: { e } } = someObject; +try { + // code +} catch ({ data: { message } }) { + // code +} +try { + // code +} catch ({ data: { message: { errors } } }) { + // code +} +const obj = { + func(id, { blog: { title } }) { + return id + title; + }, +}; +class A { + func(id, { blog: { title } }) { + return id + title; + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/directives/newline.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/directives/newline.js.snap.new new file mode 100644 index 00000000000..d2f56c769d2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/directives/newline.js.snap.new @@ -0,0 +1,29 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: newline.js +--- +# Input +```js +/* @flow */ + +"use strict"; + +import a from "a"; + +a(); + +``` + +# Output +```js +/* @flow */ + +"use strict"; + +import a from "a"; +a(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/directives/test.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/directives/test.js.snap.new new file mode 100644 index 00000000000..26b277a4879 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/directives/test.js.snap.new @@ -0,0 +1,60 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: test.js +--- +# Input +```js +"use strict"; + +function f1() { + "use strict"; +} + +function f2() { + 'ngInject'; + Object.assign(this, { $log, $uibModal }); +} + +function f3() { + + 'ngInject'; + + Object.assign(this, { $log, $uibModal }); + +} + +function f4() { + 'ngInject'; + + + Object.assign(this, { $log, $uibModal }); +} + +``` + +# Output +```js +"use strict"; + +function f1() { + "use strict"; +} +function f2() { + "ngInject"; + Object.assign(this, { $log, $uibModal }); +} +function f3() { + "ngInject"; + + Object.assign(this, { $log, $uibModal }); +} +function f4() { + "ngInject"; + + Object.assign(this, { $log, $uibModal }); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/do/call-arguments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/do/call-arguments.js.snap.new new file mode 100644 index 00000000000..39bdc0065f9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/do/call-arguments.js.snap.new @@ -0,0 +1,189 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: call-arguments.js +--- +# Input +```js +// from https://github.com/babel/babel/pull/13122/ +expect( + do { + var bar = "foo"; + if (!bar) throw new Error( + "unreachable" + ) + bar; + } +).toBe("foo"); +expect(bar).toBe("foo"); + +var x = do { + var bar = "foo"; + if (!bar) throw new Error( + "unreachable" + ) + bar; +}; + +expect( + do { + var bar = "foo"; + bar; + } +).toBe("foo"); +expect(bar).toBe("foo"); + +var x = do { + var bar = "foo"; + bar; +}; + +expect( + () => do { + () => { + var bar = "foo"; + }; + bar; + } +).toThrow(ReferenceError); + +``` + +# Output +```js +// from https://github.com/babel/babel/pull/13122/ +expect( +do { + var bar = "foo"; + if (!bar) throw new Error( + "unreachable" + ) + bar; + } +) +.toBe("foo") +expect(bar).toBe("foo"); +var x = +do { + var bar = "foo"; + if (!bar) throw new Error( + "unreachable" + ) + bar; +}; +expect( +do { + var bar = "foo"; + bar; + } +) +.toBe("foo") +expect(bar).toBe("foo"); +var x = +do { + var bar = "foo"; + bar; +}; +expect( + () => do { + () => { + var bar = "foo"; + }; +bar; +} +).toThrow(ReferenceError) + +``` + +# Errors +``` +error[SyntaxError]: expected an expression but instead found 'do' + ┌─ call-arguments.js:3:3 + │ +3 │ do { + │ ^^ Expected an expression here + +error[SyntaxError]: expected `while` but instead found `)` + ┌─ call-arguments.js:10:1 + │ +10 │ ).toBe("foo"); + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found '.toBe("foo")' + ┌─ call-arguments.js:10:2 + │ +10 │ ).toBe("foo"); + │ ^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected an expression, or an assignment but instead found 'do' + ┌─ call-arguments.js:13:9 + │ +13 │ var x = do { + │ ^^ Expected an expression, or an assignment here + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ call-arguments.js:19:2 + │ +19 │ }; + │ ^ unexpected + +error[SyntaxError]: expected an expression but instead found 'do' + ┌─ call-arguments.js:22:3 + │ +22 │ do { + │ ^^ Expected an expression here + +error[SyntaxError]: expected `while` but instead found `)` + ┌─ call-arguments.js:26:1 + │ +26 │ ).toBe("foo"); + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found '.toBe("foo")' + ┌─ call-arguments.js:26:2 + │ +26 │ ).toBe("foo"); + │ ^^^^^^^^^^^^ Expected a statement here + +error[SyntaxError]: expected an expression, or an assignment but instead found 'do' + ┌─ call-arguments.js:29:9 + │ +29 │ var x = do { + │ ^^ Expected an expression, or an assignment here + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ call-arguments.js:32:2 + │ +32 │ }; + │ ^ unexpected + +error[SyntaxError]: expected a function body, or an expression but instead found 'do' + ┌─ call-arguments.js:35:9 + │ +35 │ () => do { + │ ^^ Expected a function body, or an expression here + +error[SyntaxError]: expected `,` but instead found `(` + ┌─ call-arguments.js:36:5 + │ +36 │ () => { + │ ^ unexpected + +error[SyntaxError]: expected `,` but instead found `;` + ┌─ call-arguments.js:38:6 + │ +38 │ }; + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found '} +).toThrow(ReferenceError)' + ┌─ call-arguments.js:40:3 + │ +40 │ ┌ } +41 │ │ ).toThrow(ReferenceError); + │ └─────────────────────────^ Expected a statement here + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/do/do.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/do/do.js.snap.new new file mode 100644 index 00000000000..4e38b7f7244 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/do/do.js.snap.new @@ -0,0 +1,298 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: do.js +--- +# Input +```js +const envSpecific = { + domain: + do { + if(env === 'production') 'https://abc.mno.com/'; + else if(env === 'development') 'http://localhost:4000'; + } +}; + +let x = do { + let tmp = f(); + tmp * tmp + 1 +}; + +let y = do { + if (foo()) { f() } + else if (bar()) { g() } + else { h() } +}; + +function foo() { + return ( + + ); +} + +(do {}); +(do {} + 1); +(1 + do {}); +() => do {}; + +(do { + switch(0) { + case 0: "foo"; + case 1: break; + } +}); + +() => do { + var obj = { foo: "bar", bar: "foo" }; + for (var key in obj) { + obj[key]; + } +}; + +``` + +# Output +```js +const envSpecific = { + domain: + do { + if(env === 'production') 'https://abc.mno.com/'; +else +if (env === "development") { + ("http://localhost:4000"); +} +} +} +let x = +do { + let tmp = f(); + tmp * tmp + 1 +}; +let y = +do { + if (foo()) { f() } + else if (bar()) { g() } + else { h() } +}; +function foo() { + return ( + + ); +} +( +do {}); +( +do {} + 1); +(1 + +do {}); +() => +do {}; +( +do { + switch(0) { + case 0: "foo"; + case 1: break; + } +}); +() => +do { + var obj = { foo: "bar", bar: "foo" }; + for (var key in obj) { + obj[key]; + } +}; + +``` + +# Errors +``` +error[SyntaxError]: expected an expression, or an assignment but instead found 'do' + ┌─ do.js:3:5 + │ +3 │ do { + │ ^^ Expected an expression, or an assignment here + +error[SyntaxError]: expected `:` but instead found `{` + ┌─ do.js:3:8 + │ +3 │ do { + │ ^ unexpected + +error[SyntaxError]: expected `,` but instead found `===` + ┌─ do.js:4:14 + │ +4 │ if(env === 'production') 'https://abc.mno.com/'; + │ ^^^ unexpected + +error[SyntaxError]: expected a function body but instead found ''https://abc.mno.com/'' + ┌─ do.js:4:32 + │ +4 │ if(env === 'production') 'https://abc.mno.com/'; + │ ^^^^^^^^^^^^^^^^^^^^^^ Expected a function body here + +error[SyntaxError]: expected `:` but instead found `;` + ┌─ do.js:4:54 + │ +4 │ if(env === 'production') 'https://abc.mno.com/'; + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found 'else' + ┌─ do.js:5:7 + │ +5 │ else if(env === 'development') 'http://localhost:4000'; + │ ^^^^ Expected a statement here + +error[SyntaxError]: expected a statement but instead found '} +}' + ┌─ do.js:6:5 + │ +6 │ ┌ } +7 │ │ }; + │ └─^ Expected a statement here + +error[SyntaxError]: expected an expression, or an assignment but instead found 'do' + ┌─ do.js:9:9 + │ +9 │ let x = do { + │ ^^ Expected an expression, or an assignment here + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ do.js:12:2 + │ +12 │ }; + │ ^ unexpected + +error[SyntaxError]: expected an expression, or an assignment but instead found 'do' + ┌─ do.js:14:9 + │ +14 │ let y = do { + │ ^^ Expected an expression, or an assignment here + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ do.js:18:2 + │ +18 │ }; + │ ^ unexpected + +error[SyntaxError]: expected `'}'` but instead found `do` + ┌─ do.js:25:9 + │ +25 │ do { + │ ^^ unexpected + +error[SyntaxError]: expected `'}'` but instead found `if` + ┌─ do.js:26:11 + │ +26 │ if (loggedIn) { + │ ^^ unexpected + +error[SyntaxError]: expected `')'` but instead found `do` + ┌─ do.js:37:2 + │ +37 │ (do {}); + │ ^^ unexpected + +error[SyntaxError]: expected `while` but instead found `)` + ┌─ do.js:37:7 + │ +37 │ (do {}); + │ ^ unexpected + +error[SyntaxError]: expected `')'` but instead found `do` + ┌─ do.js:38:2 + │ +38 │ (do {} + 1); + │ ^^ unexpected + +error[SyntaxError]: expected `while` but instead found `+` + ┌─ do.js:38:8 + │ +38 │ (do {} + 1); + │ ^ unexpected + +error[SyntaxError]: expected an expression but instead found 'do' + ┌─ do.js:39:6 + │ +39 │ (1 + do {}); + │ ^^ Expected an expression here + +error[SyntaxError]: expected `while` but instead found `)` + ┌─ do.js:39:11 + │ +39 │ (1 + do {}); + │ ^ unexpected + +error[SyntaxError]: expected a function body, or an expression but instead found 'do' + ┌─ do.js:40:7 + │ +40 │ () => do {}; + │ ^^ Expected a function body, or an expression here + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ do.js:40:12 + │ +40 │ () => do {}; + │ ^ unexpected + +error[SyntaxError]: expected `')'` but instead found `do` + ┌─ do.js:42:2 + │ +42 │ (do { + │ ^^ unexpected + +error[SyntaxError]: expected `while` but instead found `)` + ┌─ do.js:47:2 + │ +47 │ }); + │ ^ unexpected + +error[SyntaxError]: expected a function body, or an expression but instead found 'do' + ┌─ do.js:49:7 + │ +49 │ () => do { + │ ^^ Expected a function body, or an expression here + +error[SyntaxError]: expected `while` but instead found `;` + ┌─ do.js:54:2 + │ +54 │ }; + │ ^ unexpected + +error: Unexpected token. Did you mean `{'}'}` or `}`? + ┌─ do.js:31:9 + │ +31 │ } + │ ^ + +error: Unexpected token. Did you mean `{'}'}` or `}`? + ┌─ do.js:32:7 + │ +32 │ } + │ ^ + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap.new new file mode 100644 index 00000000000..f4433eeadf2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/empty-paren-comment/empty_paren_comment.js.snap.new @@ -0,0 +1,49 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: empty_paren_comment.js +--- +# Input +```js +let f1 = (/* ... */) => {} +(function (/* ... */) {})(/* ... */) +function f2(/* ... */) {} + +const obj = { + f(/* ... */) {}, + f: (/* ... */) => {}, + f: function(/* ... */) {}, + f: function f(/* ... */) {} +} + +f(/* ... */); +f(a, /* ... */); +f(a, /* ... */ b); +f(/* ... */ a, b); + +let f3 = () => import(a /* ... */); +let f4 = () => doThing(a, /* ... */ b); + +``` + +# Output +```js +let f1 = ( /* ... */ ) => {}; +(function ( /* ... */ ) {})( /* ... */ ); +function f2( /* ... */ ) {} +const obj = { + f( /* ... */ ) {}, + f: ( /* ... */ ) => {}, + f: function ( /* ... */ ) {}, + f: function f( /* ... */ ) {}, +}; +f( /* ... */ ); +f(a /* ... */ ); +f(a, /* ... */ b); +f( /* ... */ a, b); +let f3 = () => import(a /* ... */ ); +let f4 = () => doThing(a, /* ... */ b); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap.new new file mode 100644 index 00000000000..f4d2ea1ca9f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/first-argument-expansion/test.js.snap.new @@ -0,0 +1,299 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: test.js +--- +# Input +```js +setTimeout(function() { + thing(); +}, 500); + +["a","b","c"].reduce(function(item, thing) { + return thing + " " + item; +}, "letters:") + +func(() => { + thing(); +}, identifier); + +func(function() { + thing(); +}, this.props.timeout * 1000); + +func((that) => { + thing(); +}, this.props.getTimeout()); + +func(() => { + thing(); +}, true); + +func(() => { + thing(); +}, null); + +func(() => { + thing(); +}, undefined); + +func(() => { + thing(); +}, /regex.*?/); + +func(() => { + thing(); +}, 1 ? 2 : 3); + +func(function() { + return thing() +}, 1 ? 2 : 3); + +func(() => { + thing(); +}, something() ? someOtherThing() : somethingElse(true, 0)); + + +func(() => { + thing(); +}, something(longArgumentName, anotherLongArgumentName) ? someOtherThing() : somethingElse(true, 0)); + + +func(() => { + thing(); +}, something(longArgumentName, anotherLongArgumentName, anotherLongArgumentName, anotherLongArgumentName) ? someOtherThing() : somethingElse(true, 0)); + +compose((a) => { + return a.thing; +}, b => b * b); + +somthing.reduce(function(item, thing) { + return thing.blah = item; +}, {}) + +somthing.reduce(function(item, thing) { + return thing.push(item); +}, []) + +reallyLongLongLongLongLongLongLongLongLongLongLongLongLongLongMethod((f, g, h) => { + return f.pop(); +}, true); + +// Don't do the rest of these + +func(function() { + thing(); +}, true, false); + +func(() => { + thing(); +}, {yes: true, cats: 5}); + +compose((a) => { + return a.thing; +}, b => { + return b + ""; +}); + +compose((a) => { + return a.thing; +}, b => [1, 2, 3, 4, 5]); + +renderThing(a => +
Content. So much to say. Oh my. Are we done yet?
+,args); + +setTimeout( + // Something + function() { + thing(); + }, + 500 +); + +setTimeout(/* blip */ function() { + thing(); +}, 500); + +func((args) => { + execute(args); +}, result => result && console.log("success")) + +``` + +# Output +```js +setTimeout( + function () { + thing(); + }, + 500, +); +[ + "a", "b", "c", +].reduce( + function (item, thing) { + return thing + " " + item; + }, + "letters:", +); +func( + () => { + thing(); + }, + identifier, +); +func( + function () { + thing(); + }, + this.props.timeout * 1000, +); +func( + (that) => { + thing(); + }, + this.props.getTimeout(), +); +func( + () => { + thing(); + }, + true, +); +func( + () => { + thing(); + }, + null, +); +func( + () => { + thing(); + }, + undefined, +); +func( + () => { + thing(); + }, + /regex.*?/, +); +func( + () => { + thing(); + }, + 1 ? 2 : 3, +); +func( + function () { + return thing(); + }, + 1 ? 2 : 3, +); +func( + () => { + thing(); + }, + something() ? someOtherThing() : somethingElse(true, 0), +); +func( + () => { + thing(); + }, + something( + longArgumentName, + anotherLongArgumentName, + ) ? someOtherThing() : somethingElse(true, 0), +); +func( + () => { + thing(); + }, + something( + longArgumentName, + anotherLongArgumentName, + anotherLongArgumentName, + anotherLongArgumentName, + ) ? someOtherThing() : somethingElse(true, 0), +); +compose( + (a) => { + return a.thing; + }, + (b) => b * b, +); +somthing.reduce( + function (item, thing) { + return thing.blah = item; + }, + {}, +); +somthing.reduce( + function (item, thing) { + return thing.push(item); + }, + [], +); +reallyLongLongLongLongLongLongLongLongLongLongLongLongLongLongMethod( + (f, g, h) => { + return f.pop(); + }, + true, +); +// Don't do the rest of these + +func( + function () { + thing(); + }, + true, + false, +); +func( + () => { + thing(); + }, + { yes: true, cats: 5 }, +); +compose( + (a) => { + return a.thing; + }, + (b) => { + return b + ""; + }, +); +compose( + (a) => { + return a.thing; + }, + (b) => [1, 2, 3, 4, 5], +); +renderThing( + (a) =>
Content. So much to say. Oh my. Are we done yet?
, + args, +); +setTimeout( + // Something + function () { + thing(); + }, + 500, +); +setTimeout( + /* blip */ function () { + thing(); + }, + 500, +); +func( + (args) => { + execute(args); + }, + (result) => result && console.log("success"), +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for-await/for-await.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for-await/for-await.js.snap.new new file mode 100644 index 00000000000..443b802b938 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for-await/for-await.js.snap.new @@ -0,0 +1,49 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: for-await.js +--- +# Input +```js +async function foo() { + for await (num of asyncIterable) { + console.log(num); + } + for await (num of asyncGeneratorFunc()) { + console.log(num); + } +} + +(async () => { + for await (num of asyncIterable) { + console.log(num); + } + for await (const x of delegate_yield()) { + x; + } +})(); + +``` + +# Output +```js +async function foo() { + for await (num of asyncIterable) { + console.log(num); + } + for await (num of asyncGeneratorFunc()) { + console.log(num); + } +} +(async () => { + for await (num of asyncIterable) { + console.log(num); + } + for await (const x of delegate_yield()) { + x; + } +})(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for-of/async-identifier.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for-of/async-identifier.js.snap.new new file mode 100644 index 00000000000..8cdab015b9f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for-of/async-identifier.js.snap.new @@ -0,0 +1,35 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: async-identifier.js +--- +# Input +```js +for ((async) of []); +for ((foo) of async); +for ((foo) of []) async; + +async function f() { + for await (async of []); + for await ((async) of []); + for await ((foo) of async); + for await ((foo) of []) async; +} + +``` + +# Output +```js +for ((async) of []); +for ((foo) of async); +for ((foo) of []) async; +async function f() { + for await (async of []); + for await ((async) of []); + for await ((foo) of async); + for await ((foo) of []) async; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for/comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for/comment.js.snap.new new file mode 100644 index 00000000000..ee87651adae --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for/comment.js.snap.new @@ -0,0 +1,75 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment.js +--- +# Input +```js +for (x +/*a*/ +in //b +y) //c +; + +for (x in /*a*/ //b +y); //c + +for (x /*a*/ in y); //b //c + +for (x +//a +in y); + +for(x in +//a +y); + +for (x +/*a*/ +of //b +y) //c +; + +for (x of /*a*/ //b +y); //c + +for (x /*a*/ of y); //b //c + +for (x +//a +of y); + +for(x of +//a +y); + +``` + +# Output +```js +for (x +/*a*/ +in y); //b //c +for (x in /*a*/ y); //b //c +for (x /*a*/ in y); //b //c +for (x +//a +in y); +for (x in +//a +y); +for (x +/*a*/ +of y); //b //c +for (x of /*a*/ y); //b //c +for (x /*a*/ of y); //b //c +for (x +//a +of y); +for (x of +//a +y); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-1.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-1.js.snap.new new file mode 100644 index 00000000000..ce577bbc472 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-1.js.snap.new @@ -0,0 +1,209 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: continue-and-break-comment-1.js +--- +# Input +```js +for(;;) { + continue // comment + ; +} + +for (;;) { + break // comment + ; +} + +for (const f of []) { + continue // comment + ; +} + +for (const f of []) { + break // comment + ; +} + +for (const f in {}) { + continue // comment + ; +} + +for (const f in {}) { + break // comment + ; +} + +while(true) { + continue // comment + ; +} + +while (true) { + break // comment + ; +} + +do { + continue // comment + ; +} while(true); + + +do { + break // comment + ; +} while(true); + +label1: for (;;) { + continue label1 // comment + ; +} + +label2: { + break label2 // comment + ; +}; + +for(;;) { + continue /* comment */ + ; +} + +for (;;) { + break /* comment */ + ; +} + +for (const f of []) { + continue /* comment */ + ; +} + +for (const f of []) { + break /* comment */ + ; +} + +for (const f in {}) { + continue /* comment */ + ; +} + +for (const f in {}) { + break /* comment */ + ; +} + +while(true) { + continue /* comment */ + ; +} + +while (true) { + break /* comment */ + ; +} + +do { + continue /* comment */ + ; +} while(true); + + +do { + break /* comment */ + ; +} while(true); + +label1: for (;;) { + continue label1 /* comment */ + ; +} + +label2: { + break label2 /* comment */ + ; +}; + +``` + +# Output +```js +for (;;) { + continue; // comment +} +for (;;) { + break; // comment +} +for (const f of []) { + continue; // comment +} +for (const f of []) { + break; // comment +} +for (const f in {}) { + continue; // comment +} +for (const f in {}) { + break; // comment +} +while (true) { + continue; // comment +} +while (true) { + break; // comment +} +do { + continue; // comment +} while (true); +do { + break; // comment +} while (true); +label1: for (;;) { + continue label1; // comment +} +label2: { + break label2; // comment +} +for (;;) { + continue /* comment */ ; +} +for (;;) { + break /* comment */ ; +} +for (const f of []) { + continue /* comment */ ; +} +for (const f of []) { + break /* comment */ ; +} +for (const f in {}) { + continue /* comment */ ; +} +for (const f in {}) { + break /* comment */ ; +} +while (true) { + continue /* comment */ ; +} +while (true) { + break /* comment */ ; +} +do { + continue /* comment */ ; +} while (true); +do { + break /* comment */ ; +} while (true); +label1: for (;;) { + continue label1 /* comment */ ; +} +label2: { + break label2 /* comment */ ; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-2.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-2.js.snap.new new file mode 100644 index 00000000000..cf59ca01bfd --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-2.js.snap.new @@ -0,0 +1,281 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: continue-and-break-comment-2.js +--- +# Input +```js +for(;;) { + continue + // comment + ; +} + +for (;;) { + break + // comment + ; +} + +for (const f of []) { + continue + // comment + ; +} + +for (const f of []) { + break + // comment + ; +} + +for (const f in {}) { + continue + // comment + ; +} + +for (const f in {}) { + break + // comment + ; +} + +while(true) { + continue + // comment + ; +} + +while (true) { + break + // comment + ; +} + +do { + continue + // comment + ; +} while(true); + + +do { + break + // comment + ; +} while(true); + +label1: for (;;) { + continue label1 + // comment + ; +} + +label2: { + break label2 + // comment + ; +}; + +for(;;) { + continue + /* comment */ + ; +} + +for (;;) { + break + /* comment */ + ; +} + +for (const f of []) { + continue + /* comment */ + ; +} + +for (const f of []) { + break + /* comment */ + ; +} + +for (const f in {}) { + continue + /* comment */ + ; +} + +for (const f in {}) { + break + /* comment */ + ; +} + +while(true) { + continue + /* comment */ + ; +} + +while (true) { + break + /* comment */ + ; +} + +do { + continue + /* comment */ + ; +} while(true); + + +do { + break + /* comment */ + ; +} while(true); + +label1: for (;;) { + continue label1 + /* comment */ + ; +} + +label2: { + break label2 + /* comment */ + ; +}; + +``` + +# Output +```js +for (;;) { + continue + // comment + ; +} +for (;;) { + break + // comment + ; +} +for (const f of []) { + continue + // comment + ; +} +for (const f of []) { + break + // comment + ; +} +for (const f in {}) { + continue + // comment + ; +} +for (const f in {}) { + break + // comment + ; +} +while (true) { + continue + // comment + ; +} +while (true) { + break + // comment + ; +} +do { + continue + // comment + ; +} while (true); +do { + break + // comment + ; +} while (true); +label1: for (;;) { + continue label1 + // comment + ; +} +label2: { + break label2 + // comment + ; +} +for (;;) { + continue + /* comment */ + ; +} +for (;;) { + break + /* comment */ + ; +} +for (const f of []) { + continue + /* comment */ + ; +} +for (const f of []) { + break + /* comment */ + ; +} +for (const f in {}) { + continue + /* comment */ + ; +} +for (const f in {}) { + break + /* comment */ + ; +} +while (true) { + continue + /* comment */ + ; +} +while (true) { + break + /* comment */ + ; +} +do { + continue + /* comment */ + ; +} while (true); +do { + break + /* comment */ + ; +} while (true); +label1: for (;;) { + continue label1 + /* comment */ + ; +} +label2: { + break label2 + /* comment */ + ; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-without-blocks.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-without-blocks.js.snap.new new file mode 100644 index 00000000000..773b7455ca3 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for/continue-and-break-comment-without-blocks.js.snap.new @@ -0,0 +1,169 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: continue-and-break-comment-without-blocks.js +--- +# Input +```js +for(;;) continue +// comment +; + +for (;;) break +// comment +; + +for (const f of []) continue +// comment +; + +for (const f of []) break +// comment +; + +for (const f in {}) continue +// comment +; + +for (const f in {}) break +// comment +; + +for(;;) continue // comment +; + +for (;;) break // comment +; + +for (const f of []) continue // comment +; + +for (const f of []) break // comment +; + +for (const f in {}) continue // comment +; + +for (const f in {}) break // comment +; + +for(;;) continue /* comment */ +; + +for (;;) break /* comment */ +; + +for (const f of []) continue /* comment */ +; + +for (const f of []) break /* comment */ +; + +for (const f in {}) continue /* comment */ +; + +for (const f in {}) break /* comment */ +; + +for(;;) continue +/* comment */ +; + +for (;;) break +/* comment */ +; + +for (const f of []) continue +/* comment */ +; + +for (const f of []) break +/* comment */ +; + +for (const f in {}) continue +/* comment */ +; + +for (const f in {}) break +/* comment */ +; + +label1: for (;;) continue label1 /* comment */ +; + +label1: for (;;) continue label1 +/* comment */ +; + +label1: for (;;) continue label1 // comment +; + +label1: for (;;) continue label1 +// comment +; + +``` + +# Output +```js +for (;;) continue +// comment +; +for (;;) break +// comment +; +for (const f of []) continue +// comment +; +for (const f of []) break +// comment +; +for (const f in {}) continue +// comment +; +for (const f in {}) break +// comment +; +for (;;) continue; // comment +for (;;) break; // comment +for (const f of []) continue; // comment +for (const f of []) break; // comment +for (const f in {}) continue; // comment +for (const f in {}) break; // comment +for (;;) continue /* comment */ ; +for (;;) break /* comment */ ; +for (const f of []) continue /* comment */ ; +for (const f of []) break /* comment */ ; +for (const f in {}) continue /* comment */ ; +for (const f in {}) break /* comment */ ; +for (;;) continue +/* comment */ +; +for (;;) break +/* comment */ +; +for (const f of []) continue +/* comment */ +; +for (const f of []) break +/* comment */ +; +for (const f in {}) continue +/* comment */ +; +for (const f in {}) break +/* comment */ +; +label1: for (;;) continue label1 /* comment */ ; +label1: for (;;) continue label1 +/* comment */ +; +label1: for (;;) continue label1; // comment +label1: for (;;) continue label1 +// comment +; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/for/for.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/for/for.js.snap.new new file mode 100644 index 00000000000..e9406001090 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/for/for.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: for.js +--- +# Input +```js +for (;;) {} +for (var i = 0; i < 10; ++i) {} + +for (;;) 0; +for (var i = 0; i < 10; ++i) 0; + +``` + +# Output +```js +for (;;) {} +for (var i = 0; i < 10; ++i) {} +for (;;) 0; +for (var i = 0; i < 10; ++i) 0; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap.new new file mode 100644 index 00000000000..c7306a2dce6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/function-first-param/function_expression.js.snap.new @@ -0,0 +1,70 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: function_expression.js +--- +# Input +```js +//https://github.com/prettier/prettier/issues/3002 +beep.boop().baz("foo", +{ + some: { + thing: { + nested: true + } + } +}, +{ 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); + + client.close(); + done(); +}); +``` + +# Output +```js +//https://github.com/prettier/prettier/issues/3002 +beep.boop().baz( + "foo", + { + some: { + thing: { + nested: true, + }, + }, + }, + { 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); + client.close(); + done(); + }, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap.new new file mode 100644 index 00000000000..521e63b86da --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/array.js.snap.new @@ -0,0 +1,89 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: array.js +--- +# Input +```js +function excludeFirstFiveResults([first, second, third, fourth, fifth, ...rest]) { + return rest; +} + +function excludeFirstFiveResults2([first, second, third, fourth, fifth, ...rest] = DEFAULT_FIVE_RESULTS) { + return rest; +} + +function excludeFirstFiveResults3([firstResult, secondResult, thirdResult, fourthResult, fifthResult, ...rest] = [1, 2, 3, 4, 5]) { + return rest; +} + +const excludeFirstFiveResults5 = ([first, second, third, fourth, fifth, ...rest]) => { + return rest; +} + +class A { + excludeFirstFiveResults([first, second, third, fourth, fifth, ...restOfResults]) { + return restOfResults; + } +} + +promise.then(([firstResult, secondResult, thirdResult, fourthResult, fifthResult, ...rest]) => { + return rest; +}); + +``` + +# Output +```js +function excludeFirstFiveResults( + [first, second, third, fourth, fifth, ...rest], +) { + return rest; +} +function excludeFirstFiveResults2( + [first, second, third, fourth, fifth, ...rest] = DEFAULT_FIVE_RESULTS, +) { + return rest; +} +function excludeFirstFiveResults3( + [ + firstResult, + secondResult, + thirdResult, + fourthResult, + fifthResult, + ...rest + ] = [1, 2, 3, 4, 5], +) { + return rest; +} +const excludeFirstFiveResults5 = ( + [first, second, third, fourth, fifth, ...rest], +) => { + return rest; +}; +class A { + excludeFirstFiveResults( + [first, second, third, fourth, fifth, ...restOfResults], + ) { + return restOfResults; + } +} +promise.then( + ( + [ + firstResult, + secondResult, + thirdResult, + fourthResult, + fifthResult, + ...rest + ], + ) => { + return rest; + }, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/object.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/object.js.snap.new new file mode 100644 index 00000000000..76e8161f9e1 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/function-single-destructuring/object.js.snap.new @@ -0,0 +1,134 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: object.js +--- +# Input +```js +function StatelessFunctionalComponent({ + isActive, + onFiltersUpdated, + onSelect, + onSubmitAndDeselect, + onCancel, + searchFilters, + title, + items, +}) { + return
+} + +function StatelessFunctionalComponent2({ + isActive = true, + onFiltersUpdated = () => null, + onSelect = () => null, + onSubmitAndDeselect = () => null, + onCancel = () => null, + searchFilters = null, + title = '', + items = [], +} = {}) { + return
+} + +function StatelessFunctionalComponent3( + { + isActive, + onFiltersUpdated = () => null, + onSelect = () => null, + onSubmitAndDeselect = () => null, + onCancel = () => null, + searchFilters = null, + title = '', + items = [], + } = { + isActive: true + } +) { + return
+} + + +class C { + StatelessFunctionalComponent({ + isActive, + onFiltersUpdated, + onSelect, + onSubmitAndDeselect, + onCancel, + searchFilters, + title, + items, + }) { + return
+ } +} + +``` + +# Output +```js +function StatelessFunctionalComponent( + { + isActive, + onFiltersUpdated, + onSelect, + onSubmitAndDeselect, + onCancel, + searchFilters, + title, + items, + }, +) { + return
; +} +function StatelessFunctionalComponent2( + { + isActive = true, + onFiltersUpdated = () => null, + onSelect = () => null, + onSubmitAndDeselect = () => null, + onCancel = () => null, + searchFilters = null, + title = "", + items = [], + } = {}, +) { + return
; +} +function StatelessFunctionalComponent3( + { + isActive, + onFiltersUpdated = () => null, + onSelect = () => null, + onSubmitAndDeselect = () => null, + onCancel = () => null, + searchFilters = null, + title = "", + items = [], + } = { + isActive: true, + }, +) { + return
; +} +class C { + StatelessFunctionalComponent( + { + isActive, + onFiltersUpdated, + onSelect, + onSubmitAndDeselect, + onCancel, + searchFilters, + title, + items, + }, + ) { + return
; + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/functional_compose.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/functional_compose.js.snap.new new file mode 100644 index 00000000000..fc962ecb3e2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/functional_compose.js.snap.new @@ -0,0 +1,80 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: functional_compose.js +--- +# Input +```js +compose( + sortBy(x => x), + flatten, + map(x => [x, x*2]) +); + +somelib.compose( + sortBy(x => x), + flatten, + map(x => [x, x*2]) +); + +composeFlipped( + sortBy(x => x), + flatten, + map(x => [x, x*2]) +); + +somelib.composeFlipped( + sortBy(x => x), + flatten, + map(x => [x, x*2]) +); + +// no regression (#4602) +const hasValue = hasOwnProperty(a, b); + +this.compose(sortBy(x => x), flatten); +this.a.b.c.compose(sortBy(x => x), flatten); +someObj.someMethod(this.field.compose(a, b)); + +class A extends B { + compose() { + super.compose(sortBy(x => x), flatten); + } +} + +this.subscriptions.add( + this.componentUpdates + .pipe(startWith(this.props), distinctUntilChanged(isEqual)) + .subscribe(props => { + + }) + ) + +``` + +# Output +```js +compose(sortBy((x) => x), flatten, map((x) => [x, x * 2])); +somelib.compose(sortBy((x) => x), flatten, map((x) => [x, x * 2])); +composeFlipped(sortBy((x) => x), flatten, map((x) => [x, x * 2])); +somelib.composeFlipped(sortBy((x) => x), flatten, map((x) => [x, x * 2])); +// no regression (#4602) +const hasValue = hasOwnProperty(a, b); +this.compose(sortBy((x) => x), flatten); +this.a.b.c.compose(sortBy((x) => x), flatten); +someObj.someMethod(this.field.compose(a, b)); +class A extends B { + compose() { + super.compose(sortBy((x) => x), flatten); + } +} +this.subscriptions.add( + this.componentUpdates.pipe( + startWith(this.props), + distinctUntilChanged(isEqual), + ).subscribe((props) => {},), +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap.new new file mode 100644 index 00000000000..01f56911486 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls-with-comments.js.snap.new @@ -0,0 +1,111 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: pipe-function-calls-with-comments.js +--- +# Input +```js +// input with some comments added to avoid reformatting + +(() => { + pipe( + // add a descriptive comment here + timelines, + everyCommitTimestamps, + A.sort(ordDate), + A.head + ); + + pipe( + // add a descriptive comment here + serviceEventFromMessage(msg), + TE.chain( + flow( + // add a descriptive comment here + publishServiceEvent(analytics), + TE.mapLeft(nackFromError) + ) + ) + )() + .then(messageResponse(logger, msg)) + .catch((err) => { + 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 + Changelog.timestampOfFirstCommit([[commit]]), + O.toUndefined + ); + + chain( + flow( + // add a descriptive comment here + getUploadUrl, + E.mapLeft(Errors.unknownError), + TE.fromEither + ) + ); +})(); + +``` + +# Output +```js +// input with some comments added to avoid reformatting + +(() => { + pipe( + // add a descriptive comment here + timelines, + everyCommitTimestamps, + A.sort(ordDate), + A.head, + ); + pipe( + // add a descriptive comment here + serviceEventFromMessage(msg), + TE.chain( + flow( + // add a descriptive comment here + publishServiceEvent(analytics), + TE.mapLeft(nackFromError), + ), + ), + )() + .then(messageResponse(logger, msg)) + .catch((err) => { + 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 + Changelog.timestampOfFirstCommit([[commit]]), + O.toUndefined, + ); + chain( + flow( + // add a descriptive comment here + getUploadUrl, + E.mapLeft(Errors.unknownError), + TE.fromEither, + ), + ); +})(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap.new new file mode 100644 index 00000000000..3d4592e664a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/pipe-function-calls.js.snap.new @@ -0,0 +1,73 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: pipe-function-calls.js +--- +# Input +```js +(() => { + pipe( + timelines, + everyCommitTimestamps, + A.sort(ordDate), + A.head + ); + + pipe( + serviceEventFromMessage(msg), + TE.chain( + flow( + publishServiceEvent(analytics), + TE.mapLeft(nackFromError) + ) + ) + )() + .then(messageResponse(logger, msg)) + .catch((err) => { + logger.error( + pipe( + O.fromNullable(err.stack), + O.getOrElse(constant(err.message)) + ) + ); + process.exit(1); + }); + + pipe( + Changelog.timestampOfFirstCommit([[commit]]), + O.toUndefined + ); + + chain( + flow( + getUploadUrl, + E.mapLeft(Errors.unknownError), + TE.fromEither + ) + ); +})(); + +``` + +# Output +```js +(() => { + pipe(timelines, everyCommitTimestamps, A.sort(ordDate), A.head); + pipe( + serviceEventFromMessage(msg), + TE.chain(flow(publishServiceEvent(analytics), TE.mapLeft(nackFromError))), + )() + .then(messageResponse(logger, msg)) + .catch((err) => { + logger.error( + pipe(O.fromNullable(err.stack), O.getOrElse(constant(err.message))), + ); + process.exit(1); + },); + pipe(Changelog.timestampOfFirstCommit([[commit]]), O.toUndefined); + chain(flow(getUploadUrl, E.mapLeft(Errors.unknownError), TE.fromEither)); +})(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/ramda_compose.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/ramda_compose.js.snap.new new file mode 100644 index 00000000000..bf9770d6dd3 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/ramda_compose.js.snap.new @@ -0,0 +1,102 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: ramda_compose.js +--- +# Input +```js +var classyGreeting = (firstName, lastName) => + "The name's " + lastName + ", " + firstName + " " + lastName; +var yellGreeting = R.compose(R.toUpper, classyGreeting); +yellGreeting("James", "Bond"); //=> "THE NAME'S BOND, JAMES BOND" + +R.compose(Math.abs, R.add(1), R.multiply(2))(-4); //=> 7 + +// get :: String -> Object -> Maybe * +var get = R.curry((propName, obj) => Maybe(obj[propName])); + +// getStateCode :: Maybe String -> Maybe String +var getStateCode = R.composeK( + R.compose(Maybe.of, R.toUpper), + get("state"), + get("address"), + get("user") +); +getStateCode({ user: { address: { state: "ny" } } }); //=> Maybe.Just("NY") +getStateCode({}); //=> Maybe.Nothing() + +var db = { + users: { + JOE: { + name: "Joe", + followers: ["STEVE", "SUZY"] + } + } +}; + +// We'll pretend to do a db lookup which returns a promise +var lookupUser = userId => Promise.resolve(db.users[userId]); +var lookupFollowers = user => Promise.resolve(user.followers); +lookupUser("JOE").then(lookupFollowers); + +// followersForUser :: String -> Promise [UserId] +var followersForUser = R.composeP(lookupFollowers, lookupUser); +followersForUser("JOE").then(followers => console.log("Followers:", followers)); +// Followers: ["STEVE","SUZY"] + +const mapStateToProps = state => ({ + users: R.compose( R.filter(R.propEq('status', 'active')), + R.values)(state.users) +}); + +``` + +# Output +```js +var classyGreeting = ( + firstName, + lastName, +) => "The name's " + lastName + ", " + firstName + " " + lastName; +var yellGreeting = R.compose(R.toUpper, classyGreeting); +yellGreeting("James", "Bond"); //=> "THE NAME'S BOND, JAMES BOND" +R.compose(Math.abs, R.add(1), R.multiply(2))(-4); //=> 7 +// get :: String -> Object -> Maybe * +var get = R.curry((propName, obj) => Maybe(obj[propName])); +// getStateCode :: Maybe String -> Maybe String +var getStateCode = R.composeK( + R.compose(Maybe.of, R.toUpper), + get("state"), + get("address"), + get("user"), +); +getStateCode({ user: { address: { state: "ny" } } },); //=> Maybe.Just("NY") +getStateCode({},); //=> Maybe.Nothing() +var db = { + users: { + JOE: { + name: "Joe", + followers: ["STEVE", "SUZY"], + }, + }, +}; +// We'll pretend to do a db lookup which returns a promise +var lookupUser = (userId) => Promise.resolve(db.users[userId]); +var lookupFollowers = (user) => Promise.resolve(user.followers); +lookupUser("JOE").then(lookupFollowers); +// followersForUser :: String -> Promise [UserId] +var followersForUser = R.composeP(lookupFollowers, lookupUser); +followersForUser( + "JOE", +).then((followers) => console.log("Followers:", followers)); +// Followers: ["STEVE","SUZY"] + +const mapStateToProps = (state) => ({ + users: R.compose( + R.filter(R.propEq("status", "active")), + R.values, + )(state.users), +}); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/redux_compose.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/redux_compose.js.snap.new new file mode 100644 index 00000000000..17463781fe9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/redux_compose.js.snap.new @@ -0,0 +1,37 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: redux_compose.js +--- +# Input +```js +import { createStore, applyMiddleware, compose } from 'redux'; +import thunk from 'redux-thunk'; +import DevTools from './containers/DevTools'; +import reducer from '../reducers'; + +const store = createStore( + reducer, + compose( + applyMiddleware(thunk), + DevTools.instrument() + ) +) + + +``` + +# Output +```js +import { createStore, applyMiddleware, compose } from "redux"; +import thunk from "redux-thunk"; +import DevTools from "./containers/DevTools"; +import reducer from "../reducers"; +const store = createStore( + reducer, + compose(applyMiddleware(thunk), DevTools.instrument()), +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/reselect_createselector.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/reselect_createselector.js.snap.new new file mode 100644 index 00000000000..b8922d90b6f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/reselect_createselector.js.snap.new @@ -0,0 +1,38 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: reselect_createselector.js +--- +# Input +```js +import { createSelector } from 'reselect'; + +const foo = createSelector( + getIds, + getObjects, + (ids, objects) => ids.map(id => objects[id]) +); + +const bar = createSelector( + [getIds, getObjects], + (ids, objects) => ids.map(id => objects[id]) +); + +``` + +# Output +```js +import { createSelector } from "reselect"; +const foo = createSelector( + getIds, + getObjects, + (ids, objects) => ids.map((id) => objects[id]), +); +const bar = createSelector( + [getIds, getObjects], + (ids, objects) => ids.map((id) => objects[id]), +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/rxjs_pipe.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/rxjs_pipe.js.snap.new new file mode 100644 index 00000000000..556c5baeff3 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/functional-composition/rxjs_pipe.js.snap.new @@ -0,0 +1,35 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: rxjs_pipe.js +--- +# Input +```js +import { range } from 'rxjs/observable/range'; +import { map, filter, scan } from 'rxjs/operators'; + +const source$ = range(0, 10); + +source$.pipe( + filter(x => x % 2 === 0), + map(x => x + x), + scan((acc, x) => acc + x, 0) +) +.subscribe(x => console.log(x)) + +``` + +# Output +```js +import { range } from "rxjs/observable/range"; +import { map, filter, scan } from "rxjs/operators"; +const source$ = range(0, 10); +source$.pipe( + filter((x) => (x % 2) === 0), + map((x) => x + x), + scan((acc, x) => acc + x, 0), +).subscribe((x) => console.log(x)); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/generator/anonymous.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/generator/anonymous.js.snap.new new file mode 100644 index 00000000000..c8de832fde6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/generator/anonymous.js.snap.new @@ -0,0 +1,51 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: anonymous.js +--- +# Input +```js +const f1 = function* () { + yield 0; +}; + +const f2 = function * () { + yield 0; +}; + +const f3 = function* () { +}; + +(function* () { + yield 0; +}); + +(function * () { + yield 0; +}); + +(function* () { +}); + +``` + +# Output +```js +const f1 = function* () { + yield 0; +}; +const f2 = function* () { + yield 0; +}; +const f3 = function* () {}; +(function* () { + yield 0; +}); +(function* () { + yield 0; +}); +(function* () {}); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/generator/function-name-starts-with-get.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/generator/function-name-starts-with-get.js.snap.new new file mode 100644 index 00000000000..3bd0aaac903 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/generator/function-name-starts-with-get.js.snap.new @@ -0,0 +1,29 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: function-name-starts-with-get.js +--- +# Input +```js +// https://github.com/meriyah/meriyah/issues/164 + +function get() {} + +function* getData() { + return yield get(); +} + +``` + +# Output +```js +// https://github.com/meriyah/meriyah/issues/164 + +function get() {} +function* getData() { + return yield get(); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/if/comment_before_else.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/if/comment_before_else.js.snap.new new file mode 100644 index 00000000000..327f9c3d821 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/if/comment_before_else.js.snap.new @@ -0,0 +1,45 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment_before_else.js +--- +# Input +```js +if (cond) { + stuff; +} /* comment */ else if (cond) { + stuff; +} +// comment +else { + stuff; +} + +if (cond) stuff; +// comment +else stuff; + +``` + +# Output +```js +if (cond) { + stuff; +} /* comment */ else if (cond) { + stuff; +} +// comment +else { + stuff; +} +if (cond) { + stuff; +} +// comment +else { + stuff; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/if/else.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/if/else.js.snap.new new file mode 100644 index 00000000000..049e87dcbf4 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/if/else.js.snap.new @@ -0,0 +1,56 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: else.js +--- +# Input +```js +// Both functions below should be formatted exactly the same + +function f() { + if (position) + return {name: pair}; + else + return {name: pair.substring(0, position), value: pair.substring(position + 1)}; +} + +function f() { + if (position) + return {name: pair}; + else + return { + name: pair.substring(0, position), + value: pair.substring(position + 1) + }; +} + +``` + +# Output +```js +// Both functions below should be formatted exactly the same + +function f() { + if (position) { + return { name: pair }; + } else { + return { + name: pair.substring(0, position), + value: pair.substring(position + 1), + }; + } +} +function f() { + if (position) { + return { name: pair }; + } else { + return { + name: pair.substring(0, position), + value: pair.substring(position + 1), + }; + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/if/expr_and_same_line_comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/if/expr_and_same_line_comments.js.snap.new new file mode 100644 index 00000000000..574390f228c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/if/expr_and_same_line_comments.js.snap.new @@ -0,0 +1,76 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: expr_and_same_line_comments.js +--- +# Input +```js +if (a === 0) doSomething(); // comment A1 +else if (a === 1) doSomethingElse(); // comment B1 +else if (a === 2) doSomethingElse(); // comment C1 + +if (a === 0) doSomething(); /* comment A2 */ +else if (a === 1) doSomethingElse(); /* comment B2 */ +else if (a === 2) doSomethingElse(); /* comment C2 */ + +if (a === 0) expr; // comment A3 +else if (a === 1) expr; // comment B3 +else if (a === 2) expr; // comment C3 + +if (a === 0) expr; /* comment A4 */ +else if (a === 1) expr; /* comment B4 */ +else if (a === 2) expr; /* comment C4 */ + +if (a === 0) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 +else if (a === 1) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment B5 +else if (a === 2) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 + +``` + +# Output +```js +if (a === 0) { + doSomething(); // comment A1 +} else if (a === 1) { + doSomethingElse(); // comment B1 +} else if (a === 2) { + doSomethingElse(); // comment C1 +} +if (a === 0) { + doSomething(); /* comment A2 */ +} else if (a === 1) { + doSomethingElse(); /* comment B2 */ +} else if (a === 2) { + doSomethingElse(); /* comment C2 */ +} +if (a === 0) { + expr; // comment A3 +} else if (a === 1) { + expr; // comment B3 +} else if (a === 2) { + expr; // comment C3 +} +if (a === 0) { + expr; /* comment A4 */ +} else if (a === 1) { + expr; /* comment B4 */ +} else if (a === 2) { + expr; /* comment C4 */ +} +if (a === 0) { + looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 +} else if (a === 1) { + looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment B5 +} else if (a === 2) { + looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 +} + +``` + +# Lines exceeding max width of 80 characters +``` + 30: looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 + 32: looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment B5 + 34: looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/if/if_comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/if/if_comments.js.snap.new new file mode 100644 index 00000000000..1870d411998 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/if/if_comments.js.snap.new @@ -0,0 +1,125 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: if_comments.js +--- +# Input +```js +async function f1() { + if (untrackedChoice === 0) /* Cancel */ { + return null; + } else if (untrackedChoice === 1) /* Add */ { + await repository.addAll(Array.from(untrackedChanges.keys())); + shouldAmend = true; + } else if (untrackedChoice === 2) /* Allow Untracked */ { + allowUntracked = true; + } +} + +async function f2() { + if (untrackedChoice === 0) /* Cancel */ + null; + else if (untrackedChoice === 1) /* Add */ + shouldAmend = true; + else if (untrackedChoice === 2) /* Allow Untracked */ + allowUntracked = true; +} + +async function f3() { + if (untrackedChoice === 0) /* Cancel */ // Cancel + null; + else if (untrackedChoice === 1) /* Add */ // Add + shouldAmend = true; + else if (untrackedChoice === 2) /* Allow Untracked */ // Allow Untracked + allowUntracked = true; +} + +async function f4() { + if (untrackedChoice === 0) + /* Cancel */ { + return null; + } + else if (untrackedChoice === 1) + /* Add */ { + await repository.addAll(Array.from(untrackedChanges.keys())); + shouldAmend = true; + } + else if (untrackedChoice === 2) + /* Allow Untracked */ { + allowUntracked = true; + } +} + +async function f5() { + if (untrackedChoice === 0) { + /* Cancel */ return null; + } else if (untrackedChoice === 1) { + /* Add */ await repository.addAll(Array.from(untrackedChanges.keys())); + shouldAmend = true; + } else if (untrackedChoice === 2) { + /* Allow Untracked */ allowUntracked = true; + } +} + +``` + +# Output +```js +async function f1() { + if (untrackedChoice === 0) /* Cancel */ { + return null; + } else if (untrackedChoice === 1) /* Add */ { + await repository.addAll(Array.from(untrackedChanges.keys())); + shouldAmend = true; + } else if (untrackedChoice === 2) /* Allow Untracked */ { + allowUntracked = true; + } +} +async function f2() { + if (untrackedChoice === 0) /* Cancel */ { + null; + } else if (untrackedChoice === 1) /* Add */ { + shouldAmend = true; + } else if (untrackedChoice === 2) /* Allow Untracked */ { + allowUntracked = true; + } +} +async function f3() { + if (untrackedChoice === 0) /* Cancel */ { + // Cancel + null; + } else if (untrackedChoice === 1) /* Add */ { + // Add + shouldAmend = true; + } else if (untrackedChoice === 2) /* Allow Untracked */ { + // Allow Untracked + allowUntracked = true; + } +} +async function f4() { + if (untrackedChoice === 0) + /* Cancel */ { + return null; + } else if (untrackedChoice === 1) + /* Add */ { + await repository.addAll(Array.from(untrackedChanges.keys())); + shouldAmend = true; + } else if (untrackedChoice === 2) + /* Allow Untracked */ { + allowUntracked = true; + } +} +async function f5() { + if (untrackedChoice === 0) { + /* Cancel */ return null; + } else if (untrackedChoice === 1) { + /* Add */ await repository.addAll(Array.from(untrackedChanges.keys())); + shouldAmend = true; + } else if (untrackedChoice === 2) { + /* Allow Untracked */ allowUntracked = true; + } +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/if/trailing_comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/if/trailing_comment.js.snap.new new file mode 100644 index 00000000000..502cb2846f7 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/if/trailing_comment.js.snap.new @@ -0,0 +1,43 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: trailing_comment.js +--- +# Input +```js +if (code === 92 /* '\' */) {} +if (code === 92 /* '\' */ /* '\' */) {} + +if (code === 92) /* '\' */ {} +if (code === 92) { /* '\' */ } + +if ( + 1 + // Comment +) { + a; +} + +``` + +# Output +```js +if (code === 92 /* '\' */ ) { +} +if (code === 92 /* '\' */ /* '\' */ ) { +} +if (code === 92) /* '\' */ { +} +if (code === 92) { + /* '\' */ +} +if ( + 1 + // Comment +) { + a; +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap.new new file mode 100644 index 00000000000..65f1619ce78 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore-2.js.snap.new @@ -0,0 +1,53 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: ignore-2.js +--- +# Input +```js +// #8736 + +function HelloWorld() { + return ( +
+ test +
+ ); +} + +a =
+a =
+a =
+a =
+a =
+ +``` + +# Output +```js +// #8736 + +function HelloWorld() { + return ( +
+ test +
+ ); +} +a =
; +a =
; +a =
; +a =
; +a =
; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore.js.snap.new new file mode 100644 index 00000000000..3b2c4d35147 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/ignore.js.snap.new @@ -0,0 +1,127 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: ignore.js +--- +# Input +```js +function a() { + // prettier-ignore + var fnString = + '"' + this.USE + ' ' + this.STRICT + '";\n' + + this.filterPrefix() + + 'var fn=' + this.generateFunction('fn', 's,l,a,i') + + extra + + this.watchFns() + + 'return fn;'; + + // prettier-ignore + const identity = Matrix.create( + 1, 0, 0, + 0, 1, 0, + 0, 0, 0 + ); + + // Let's make sure that this comment doesn't interfere + + // prettier-ignore + const commentsWithPrettierIgnore = { + "ewww": + "gross-formatting", + }; + + function giveMeSome() { + a( a ); // prettier-ignore + // shouldn't I return something? :shrug: + } + + // prettier-ignore + console.error( + 'In order to use ' + prompt + ', you need to configure a ' + + 'few environment variables to be able to commit to the ' + + 'repository. Follow those steps to get you setup:\n' + + '\n' + + 'Go to https://github.com/settings/tokens/new\n' + + ' - Fill "Token description" with "' + prompt + ' for ' + + repoSlug + '"\n' + + ' - Check "public_repo"\n' + + ' - Press "Generate Token"\n' + + '\n' + + 'In a different tab, go to https://travis-ci.org/' + + repoSlug + '/settings\n' + + ' - Make sure "Build only if .travis.yml is present" is ON\n' + + ' - Fill "Name" with "GITHUB_USER" and "Value" with the name of the ' + + 'account you generated the token with. Press "Add"\n' + + '\n' + + 'Once this is done, commit anything to the repository to restart ' + + 'Travis and it should work :)' + ); +} + +const response = { + // prettier-ignore + '_text': 'Turn on the lights', + intent: 'lights', +}; + +``` + +# Output +```js +function a() { + // prettier-ignore + var fnString = + '"' + this.USE + ' ' + this.STRICT + '";\n' + + this.filterPrefix() + + 'var fn=' + this.generateFunction('fn', 's,l,a,i') + + extra + + this.watchFns() + + 'return fn;'; + // prettier-ignore + const identity = Matrix.create( + 1, 0, 0, + 0, 1, 0, + 0, 0, 0 + ); + // Let's make sure that this comment doesn't interfere + + // prettier-ignore + const commentsWithPrettierIgnore = { + "ewww": + "gross-formatting", + }; + function giveMeSome() { + a(a); // prettier-ignore + // shouldn't I return something? :shrug: + } + // prettier-ignore + console.error( + 'In order to use ' + prompt + ', you need to configure a ' + + 'few environment variables to be able to commit to the ' + + 'repository. Follow those steps to get you setup:\n' + + '\n' + + 'Go to https://github.com/settings/tokens/new\n' + + ' - Fill "Token description" with "' + prompt + ' for ' + + repoSlug + '"\n' + + ' - Check "public_repo"\n' + + ' - Press "Generate Token"\n' + + '\n' + + 'In a different tab, go to https://travis-ci.org/' + + repoSlug + '/settings\n' + + ' - Make sure "Build only if .travis.yml is present" is ON\n' + + ' - Fill "Name" with "GITHUB_USER" and "Value" with the name of the ' + + 'account you generated the token with. Press "Add"\n' + + '\n' + + 'Once this is done, commit anything to the repository to restart ' + + 'Travis and it should work :)' + ); +} +const response = { + // prettier-ignore + '_text': 'Turn on the lights', + intent: "lights", +}; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/issue-10661.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/issue-10661.js.snap.new new file mode 100644 index 00000000000..07ebf43bae2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/issue-10661.js.snap.new @@ -0,0 +1,70 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-10661.js +--- +# Input +```js +verylongidentifierthatwillwrap123123123123123( + a.b + // prettier-ignore + // Some other comment here + .c +); + +call( + // comment + a. + // prettier-ignore + b +) + +call( + a( +/* +this won't get formatted too, +because the prettier-ignore comment is attached as MemberExpression leading comment +*/ +1, +2.0000, 3 +) + // prettier-ignore + .c +) + +``` + +# Output +```js +verylongidentifierthatwillwrap123123123123123( + a.b // Some other comment here + // prettier-ignore + .c, +); +call( + // comment + a. + // prettier-ignore + b, +); +call( + a( + /* +this won't get formatted too, +because the prettier-ignore comment is attached as MemberExpression leading comment +*/ + 1, + 2.0000, + 3, + ) + // prettier-ignore + .c, +); + +``` + +# Lines exceeding max width of 80 characters +``` + 16: because the prettier-ignore comment is attached as MemberExpression leading comment +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/ignore/semi/directive.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/semi/directive.js.snap.new new file mode 100644 index 00000000000..beb6b75fa6d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/ignore/semi/directive.js.snap.new @@ -0,0 +1,33 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: directive.js +--- +# Input +```js +// prettier-ignore +'use strict'; +[].forEach(); + +function foo() { +// prettier-ignore +'use strict'; +[].forEach(); +} + +``` + +# Output +```js +// prettier-ignore +'use strict'; +[].forEach(); +function foo() { + // prettier-ignore +'use strict'; + [].forEach(); +} + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/import-assertions/empty.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/import-assertions/empty.js.snap.new new file mode 100644 index 00000000000..7364d15677f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/import-assertions/empty.js.snap.new @@ -0,0 +1,28 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: empty.js +--- +# Input +```js +export * as foo from "foo.json" +export * as bar from "bar.json" assert { } +export * as baz from "baz.json" assert { /* comment */ } + +import * as foo from "foo.json" +import * as bar from "bar.json" assert { } +import * as baz from "baz.json" assert { /* comment */ } +``` + +# Output +```js +export * as foo from "foo.json"; +export * as bar from "bar.json" assert { }; +export * as baz from "baz.json" assert { /* comment */ }; +import * as foo from "foo.json"; +import * as bar from "bar.json" assert { }; +import * as baz from "baz.json" assert { /* comment */ }; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/import/empty-import.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/import/empty-import.js.snap.new new file mode 100644 index 00000000000..c0f62a76572 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/import/empty-import.js.snap.new @@ -0,0 +1,18 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: empty-import.js +--- +# Input +```js +import { } from '@types/googlemaps'; + +``` + +# Output +```js +import { } from "@types/googlemaps"; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/in/arrow-function.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/in/arrow-function.js.snap.new new file mode 100644 index 00000000000..1e4a34a0390 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/in/arrow-function.js.snap.new @@ -0,0 +1,21 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: arrow-function.js +--- +# Input +```js +const x = () => [].includes(true) || "ontouchend" in document + +const y = () => [] in x + +``` + +# Output +```js +const x = () => [].includes(true) || ("ontouchend" in document); +const y = () => [] in x; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap.new new file mode 100644 index 00000000000..328f9a93b77 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/break-parent.js.snap.new @@ -0,0 +1,69 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: break-parent.js +--- +# Input +```js +({ + processors: [ + 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 + }) + :
; + +``` + +# Output +```js +({ + processors: [ + 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, +},) :
; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap.new new file mode 100644 index 00000000000..a27cfd0cd4d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/empty-object.js.snap.new @@ -0,0 +1,62 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: empty-object.js +--- +# Input +```js +func(first, second, third, fourth, fifth, aReallyLongArgumentsListToForceItToBreak, { + // comment +}) + +func({ + // comment +}) + +func( + {} // comment +) + +func( + {} + // comment +) + +func( + // comment + {} +) + +``` + +# Output +```js +func( + first, + second, + third, + fourth, + fifth, + aReallyLongArgumentsListToForceItToBreak, + { + // comment + }, +); +func({ + // comment +},); +func( + {}, // comment +); +func( + {}, + // comment +); +func( + // comment + {}, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap.new new file mode 100644 index 00000000000..f0c82f6b00c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/function-expression.js.snap.new @@ -0,0 +1,55 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: function-expression.js +--- +# Input +```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'); + } + ); +} + +function mySagas2() { + return effects.takeEvery( + rexpress.actionTypes.REQUEST_START, + function({ id }) { + console.log(id); + } + ); +} + +``` + +# 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"); + }, + ); +} +function mySagas2() { + 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/object.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/object.js.snap.new new file mode 100644 index 00000000000..b99d9044539 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/last-argument-expansion/object.js.snap.new @@ -0,0 +1,54 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: object.js +--- +# Input +```js +const formatData = pipe( + zip, + map(([ ref, data ]) => ({ + nodeId: ref.nodeId.toString(), + ...attributeFromDataValue(ref.attributeId, data) + })), + groupBy(prop('nodeId')), + map(mergeAll), + values +); + +export const setProp = y => ({ + ...y, + a: 'very, very, very long very, very long text' +}); + +export const log = y => { + console.log('very, very, very long very, very long text') +}; + +``` + +# Output +```js +const formatData = pipe( + zip, + map( + ([ref, data]) => ({ + nodeId: ref.nodeId.toString(), + ...attributeFromDataValue(ref.attributeId, data), + }), + ), + groupBy(prop("nodeId")), + map(mergeAll), + values, +); +export const setProp = (y) => ({ + ...y, + a: "very, very, very long very, very long text", +}); +export const log = (y) => { + console.log("very, very, very long very, very long text"); +}; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/line-suffix-boundary/boundary.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/line-suffix-boundary/boundary.js.snap.new new file mode 100644 index 00000000000..6a945a9b438 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/line-suffix-boundary/boundary.js.snap.new @@ -0,0 +1,72 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: boundary.js +--- +# Input +```js +`${ +a + // a + a +} + +${a // comment +} + +${b /* comment */} + +${/* comment */ c /* comment */} + +${// comment +d //comment +} + +${// $FlowFixMe found when converting React.createClass to ES6 +ExampleStory.getFragment('story')} +`; + +
+{ExampleStory.getFragment('story') // $FlowFixMe found when converting React.createClass to ES6 +} +
; + +``` + +# Output +```js +`${ + a + // a + a +} + +${ + a // comment +} + +${b /* comment */ } + +${ /* comment */ c /* comment */ } + +${ + d // comment //comment +} + +${ + ExampleStory.getFragment( + // $FlowFixMe found when converting React.createClass to ES6 + "story", + ) +} +`; +
+{ExampleStory.getFragment('story') // $FlowFixMe found when converting React.createClass to ES6 +} +
; + +``` + +# Lines exceeding max width of 80 characters +``` + 26: {ExampleStory.getFragment('story') // $FlowFixMe found when converting React.createClass to ES6 +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/line/windows.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/line/windows.js.snap.new new file mode 100644 index 00000000000..1312b3f1ce9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/line/windows.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: windows.js +--- +# Input +```js +const vscode = require("vscode"); +const {getDir, getActiveFile, uint8arrayToString} = require("./utils"); + +let outChannel; +let _commands; + +``` + +# Output +```js +const vscode = require("vscode"); +const { getDir, getActiveFile, uint8arrayToString } = require("./utils"); +let outChannel; +let _commands; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/literal/number.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/literal/number.js.snap.new new file mode 100644 index 00000000000..139fe36e1eb --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/literal/number.js.snap.new @@ -0,0 +1,182 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: number.js +--- +# Input +```js +// parentheses around numeric literal should be preserved +function test5() { + return (100).toString(); +} + +0 +1 + +0.1 +1.1 + +.1 +1. + +0b1 +0B1 +0o1 +0O1 +0x1 +0X1 + +0x123abcdef456ABCDEF +0X123abcdef456ABCDEF +0xdeadbeef; + +0b111000 +0b000111 +0B111000 +0B000111 +0o111000 +0o000111 +0O111000 +0O000111 +0x111000 +0x000111 +0X111000 +0X000111 + +1e1 +1e+1 +1e-1 +1.e1 +.1e1 +1.1e1 +1.1e0010 +.1e+0010 +.1e-0010 + +1E1 +1E+1 +1E-1 +1.E1 +.1E1 +1.1E1 +1.1E0010 +.1E+0010 +.1E-0010 + +0.5e0 +0.5e00 +0.5e+0 +0.5e+00 +0.5e-0 +0.5e-00 + +1 +1.00500 +1.0 +1.5 +1.50 +0 +0.00500 +0.0 +0.0000 +.0 +500600.001230045000 +1.00500e60 +1.0e60 +0.00500e60 +0.0e60 +0.0000e60 +.0e60 +0.e60 +0e60 +500600.001230045000e60 +10 +9700 +10e100 + +``` + +# Output +```js +// parentheses around numeric literal should be preserved +function test5() { + return (100).toString(); +} +0; +1; +0.1; +1.1; +.1; +1.; +0b1; +0B1; +0o1; +0O1; +0x1; +0X1; +0x123abcdef456ABCDEF; +0X123abcdef456ABCDEF; +0xdeadbeef; +0b111000; +0b000111; +0B111000; +0B000111; +0o111000; +0o000111; +0O111000; +0O000111; +0x111000; +0x000111; +0X111000; +0X000111; +1e1; +1e+1; +1e-1; +1.e1; +.1e1; +1.1e1; +1.1e0010; +.1e+0010; +.1e-0010; +1E1; +1E+1; +1E-1; +1.E1; +.1E1; +1.1E1; +1.1E0010; +.1E+0010; +.1E-0010; +0.5e0; +0.5e00; +0.5e+0; +0.5e+00; +0.5e-0; +0.5e-00; +1; +1.00500; +1.0; +1.5; +1.50; +0; +0.00500; +0.0; +0.0000; +.0; +500600.001230045000; +1.00500e60; +1.0e60; +0.00500e60; +0.0e60; +0.0000e60; +.0e60; +0.e60; +0e60; +500600.001230045000e60; +10; +9700; +10e100; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/logical-assignment/logical-assignment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/logical-assignment/logical-assignment.js.snap.new new file mode 100644 index 00000000000..bb8feab7592 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/logical-assignment/logical-assignment.js.snap.new @@ -0,0 +1,113 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: logical-assignment.js +--- +# Input +```js +a ||= b; + +a &&= "foo"; +b ||= "foo"; +c ??= "foo"; + +d &&= 42; +e ||= 42; +f ??= 42; + +a.baz &&= result.baz; +b.baz ||= result.baz; +c.baz ??= result.baz; + +a.foo["baz"] &&= result.foo.baz; +b.foo["baz"] ||= result.foo.baz; +c.foo["baz"] ??= result.foo.baz; + +a.foo.bar().baz &&= result.foo.bar().baz; +b.foo.bar().baz ||= result.foo.bar().baz; +b.baz ||= result.baz; +c.baz ??= result.baz; + +(results ||= []).push(100); +(results &&= []).push(100); +(results ??= []).push(100); + +if ((thing &&= thing.original)) { +} +if ((thing &&= defaultValue)) { +} +if ((thing ||= defaultValue)) { +} +if ((thing ??= defaultValue)) { +} + +f ||= (a) => a; +f &&= (a) => a; +f ??= (a) => a; + +f ||= (f.toString(), (a) => a); +f &&= (f.toString(), (a) => a); +f ??= (f.toString(), (a) => a); + +(results ||= results1 ||= []).push(100); +(results &&= results1 &&= []).push(100); +(results ??= results1 ??= []).push(100); + +obj[incr()] ||= incr(); +oobj["obj"][incr()] ||= incr(); +obj[incr()] &&= incr(); +oobj["obj"][incr()] &&= incr(); +obj[incr()] ??= incr(); +oobj["obj"][incr()] ??= incr(); + +``` + +# Output +```js +a ||= b; +a &&= "foo"; +b ||= "foo"; +c ??= "foo"; +d &&= 42; +e ||= 42; +f ??= 42; +a.baz &&= result.baz; +b.baz ||= result.baz; +c.baz ??= result.baz; +a.foo["baz"] &&= result.foo.baz; +b.foo["baz"] ||= result.foo.baz; +c.foo["baz"] ??= result.foo.baz; +a.foo.bar().baz &&= result.foo.bar().baz; +b.foo.bar().baz ||= result.foo.bar().baz; +b.baz ||= result.baz; +c.baz ??= result.baz; +(results ||= []).push(100); +(results &&= []).push(100); +(results ??= []).push(100); +if ((thing &&= thing.original)) { +} +if ((thing &&= defaultValue)) { +} +if ((thing ||= defaultValue)) { +} +if ((thing ??= defaultValue)) { +} +f ||= (a) => a; +f &&= (a) => a; +f ??= (a) => a; +f ||= (f.toString(), (a) => a); +f &&= (f.toString(), (a) => a); +f ??= (f.toString(), (a) => a); +(results ||= results1 ||= []).push(100); +(results &&= results1 &&= []).push(100); +(results ??= results1 ??= []).push(100); +obj[incr()] ||= incr(); +oobj["obj"][incr()] ||= incr(); +obj[incr()] &&= incr(); +oobj["obj"][incr()] &&= incr(); +obj[incr()] ??= incr(); +oobj["obj"][incr()] ??= incr(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/logical_expressions/logical_expression_operators.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/logical_expressions/logical_expression_operators.js.snap.new new file mode 100644 index 00000000000..a105efa07db --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/logical_expressions/logical_expression_operators.js.snap.new @@ -0,0 +1,75 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: logical_expression_operators.js +--- +# Input +```js +// Same operators do not require parens +(foo && bar) && baz; +foo && (bar && baz); +foo && ((bar && baz) && qux); +foo && (bar && (baz && qux)); +foo && (bar && ((baz && qux) && xyz)); +foo && (bar && (baz && (qux && xyz))); + +(foo || bar) || baz; +foo || (bar || baz); +foo || ((bar || baz) || qux); +foo || (bar || (baz || qux)); +foo || (bar || ((baz || qux) || xyz)); +foo || (bar || (baz || (qux || xyz))); + +(foo ?? bar) ?? baz; +foo ?? (bar ?? baz); +foo ?? ((bar ?? baz) ?? qux); +foo ?? (bar ?? (baz ?? qux)); +foo ?? (bar ?? ((baz ?? qux) ?? xyz)); +foo ?? (bar ?? (baz ?? (qux ?? xyz))); + +// Explicitly parenthesized && and || requires parens +(foo && bar) || baz; +(foo || bar) && baz; + +foo && (bar || baz); +foo || (bar && baz); + +// Implicitly parenthesized && and || requires parens +foo && bar || baz; +foo || bar && baz; + +``` + +# Output +```js +// Same operators do not require parens +(foo && bar) && baz; +foo && (bar && baz); +foo && ((bar && baz) && qux); +foo && (bar && (baz && qux)); +foo && (bar && ((baz && qux) && xyz)); +foo && (bar && (baz && (qux && xyz))); +(foo || bar) || baz; +foo || (bar || baz); +foo || ((bar || baz) || qux); +foo || (bar || (baz || qux)); +foo || (bar || ((baz || qux) || xyz)); +foo || (bar || (baz || (qux || xyz))); +(foo ?? bar) ?? baz; +foo ?? (bar ?? baz); +foo ?? ((bar ?? baz) ?? qux); +foo ?? (bar ?? (baz ?? qux)); +foo ?? (bar ?? ((baz ?? qux) ?? xyz)); +foo ?? (bar ?? (baz ?? (qux ?? xyz))); +// Explicitly parenthesized && and || requires parens +(foo && bar) || baz; +(foo || bar) && baz; +foo && (bar || baz); +foo || (bar && baz); +// Implicitly parenthesized && and || requires parens +(foo && bar) || baz; +foo || (bar && baz); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap.new new file mode 100644 index 00000000000..508a48104d6 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/member/expand.js.snap.new @@ -0,0 +1,91 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: expand.js +--- +# Input +```js +const veryVeryVeryVeryVeryVeryVeryLong = doc.expandedStates[doc.expandedStates.length - 1]; +const small = doc.expandedStates[doc.expandedStates.length - 1]; + +const promises = [ + promise.resolve().then(console.log).catch(err => { + console.log(err) + return null + }), + redis.fetch(), + other.fetch(), +]; + +const promises2 = [ + promise.resolve().veryLongFunctionCall().veryLongFunctionCall().then(console.log).catch(err => { + console.log(err) + return null + }), + redis.fetch(), + other.fetch(), +]; + +window.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token +}).initVerify("foo_container"); + +window.something.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token +}).initVerify("foo_container"); + +window.FooClient.something.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token +}).initVerify("foo_container"); + +``` + +# Output +```js +const veryVeryVeryVeryVeryVeryVeryLong = doc.expandedStates[ + doc.expandedStates.length - 1 +]; +const small = doc.expandedStates[doc.expandedStates.length - 1]; +const promises = [ + promise + .resolve() + .then(console.log) + .catch((err) => { + console.log(err); + return null; + },), + redis.fetch(), + other.fetch(), +]; +const promises2 = [ + promise + .resolve() + .veryLongFunctionCall() + .veryLongFunctionCall() + .then(console.log) + .catch((err) => { + console.log(err); + return null; + },), + redis.fetch(), + other.fetch(), +]; +window.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, +},).initVerify("foo_container"); +window.something.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, +},).initVerify("foo_container"); +window.FooClient.something.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, +},).initVerify("foo_container"); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/member/logical.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/member/logical.js.snap.new new file mode 100644 index 00000000000..5cc4d33a647 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/member/logical.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: logical.js +--- +# Input +```js +(veryLongVeryLongVeryLong || e).prop; + +(veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError).prop; + +``` + +# Output +```js +(veryLongVeryLongVeryLong || e).prop; +( + veryLongVeryLongVeryLong || + anotherVeryLongVeryLongVeryLong || + veryVeryVeryLongError +).prop; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap.new new file mode 100644 index 00000000000..79bbfb366d1 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-call.js.snap.new @@ -0,0 +1,141 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: break-last-call.js +--- +# Input +```js +export default store => { + return callApi(endpoint, schema).then( + response => next(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'}, + ], + }); +}); + +``` + +# Output +```js +export default (store) => { + return callApi( + endpoint, + schema, + ).then( + ( + response, + ) => + next( + 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", + }, + ], + },); + }, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-member.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-member.js.snap.new new file mode 100644 index 00000000000..aae55f9dcbc --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-last-member.js.snap.new @@ -0,0 +1,78 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: break-last-member.js +--- +# Input +```js +SomeVeryLongUpperCaseConstant.someVeryLongCallExpression().some_very_long_member_expression +weNeedToReachTheEightyCharacterLimitXXXXXXXXXXXXXXXXX.someNode + .childrenInAnArray[0]; +superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered; +superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered[0]; + +expect( + findDOMNode(component.instance()).getElementsByClassName(styles.inner)[0].style.paddingRight +).toBe('1000px'); + +const { course, conflicts = [], index, scheduleId, studentId, something } = a.this.props; + +const { course2, conflicts2 = [], index2, scheduleId2, studentId2, something2 } = this.props; + +const { + updated, + author: { identifier: ownerId }, + location, + category: categories, +} = rawAd.entry; + +``` + +# Output +```js +SomeVeryLongUpperCaseConstant.someVeryLongCallExpression().some_very_long_member_expression; +weNeedToReachTheEightyCharacterLimitXXXXXXXXXXXXXXXXX.someNode.childrenInAnArray[ + 0 +]; +superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered; +superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered[ + 0 +]; +expect( + findDOMNode( + component.instance(), + ).getElementsByClassName(styles.inner)[0].style.paddingRight, +).toBe("1000px"); +const { + course, + conflicts = [], + index, + scheduleId, + studentId, + something, +} = a.this.props; +const { + course2, + conflicts2 = [], + index2, + scheduleId2, + studentId2, + something2, +} = this.props; +const { + updated, + author: { identifier: ownerId }, + location, + category: categories, +} = rawAd.entry; + +``` + +# Lines exceeding max width of 80 characters +``` + 1: SomeVeryLongUpperCaseConstant.someVeryLongCallExpression().some_very_long_member_expression; + 2: weNeedToReachTheEightyCharacterLimitXXXXXXXXXXXXXXXXX.someNode.childrenInAnArray[ + 5: superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered; + 6: superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered[ +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-multiple.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-multiple.js.snap.new new file mode 100644 index 00000000000..880f5619149 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/break-multiple.js.snap.new @@ -0,0 +1,24 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: break-multiple.js +--- +# Input +```js +object.foo().bar().baz(); + +foo().bar().baz(); + +foo().bar.baz(); + +``` + +# Output +```js +object.foo().bar().baz(); +foo().bar().baz(); +foo().bar.baz(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap.new new file mode 100644 index 00000000000..9d6b2385098 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/comment.js.snap.new @@ -0,0 +1,125 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment.js +--- +# Input +```js +function f() { + return observableFromSubscribeFunction() + // Debounce manually rather than using editor.onDidStopChanging so that the debounce time is + // configurable. + .debounceTime(debounceInterval); +} + +_.a(a) + /* very very very very very very very long such that it is longer than 80 columns */ + .a() + +_.a( + a +)/* very very very very very very very long such that it is longer than 80 columns */ +.a(); + +_.a( + a +) /* very very very very very very very long such that it is longer than 80 columns */.a(); + +Something + // $FlowFixMe(>=0.41.0) + .getInstance(this.props.dao) + .getters() + +// Warm-up first +measure() + .then(() => { + SomethingLong(); + }); + +measure() // Warm-up first + .then(() => { + SomethingLong(); + }); + +const configModel = this.baseConfigurationService.getCache().consolidated // global/default values (do NOT modify) + .merge(this.cachedWorkspaceConfig); + +this.doWriteConfiguration(target, value, options) // queue up writes to prevent race conditions + .then(() => null, + error => { + return options.donotNotifyError ? TPromise.wrapError(error) : this.onError(error, target, value); + }); + +ret = __DEV__ ? + // $FlowFixMe: this type differs according to the env +vm.runInContext(source, ctx) +: a + +angular.module('AngularAppModule') + // Hello, I am comment. + .constant('API_URL', 'http://localhost:8080/api'); + +``` + +# Output +```js +function f() { + return observableFromSubscribeFunction() // configurable. + // Debounce manually rather than using editor.onDidStopChanging so that the debounce time is + .debounceTime(debounceInterval); +} +_.a(a) +/* very very very very very very very long such that it is longer than 80 columns */ +.a(); +_.a( + a, +) /* very very very very very very very long such that it is longer than 80 columns */ .a(); +_.a( + a, +) /* very very very very very very very long such that it is longer than 80 columns */ .a(); +Something +// $FlowFixMe(>=0.41.0) +.getInstance(this.props.dao).getters(); +// 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) + this.cachedWorkspaceConfig, +); +this.doWriteConfiguration( + target, + value, + options, +) // queue up writes to prevent race conditions +.then( + () => null, + (error) => { + return options.donotNotifyError ? TPromise.wrapError( + error, + ) : this.onError(error, target, value); + }, +); +ret = + __DEV__ ? + // $FlowFixMe: this type differs according to the env + vm.runInContext(source, ctx) : a; +angular.module("AngularAppModule") +// Hello, I am comment. +.constant("API_URL", "http://localhost:8080/api"); + +``` + +# Lines exceeding max width of 80 characters +``` + 3: // Debounce manually rather than using editor.onDidStopChanging so that the debounce time is + 7: /* very very very very very very very long such that it is longer than 80 columns */ + 11: ) /* very very very very very very very long such that it is longer than 80 columns */ .a(); + 14: ) /* very very very very very very very long such that it is longer than 80 columns */ .a(); +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap.new new file mode 100644 index 00000000000..aaa98fc17d9 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/computed-merge.js.snap.new @@ -0,0 +1,45 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: computed-merge.js +--- +# Input +```js +[].forEach(key => { + 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) + .catch(() => b); + +``` + +# Output +```js +[].forEach((key) => { + 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) + .catch(() => b); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/conditional.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/conditional.js.snap.new new file mode 100644 index 00000000000..739f5f49b6b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/conditional.js.snap.new @@ -0,0 +1,62 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: conditional.js +--- +# Input +```js +(a ? b : c).d(); + +(a ? b : c).d().e(); + +(a ? b : c).d().e().f(); + +(valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(this.defaultUser)) +.map(); + +(valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(this.defaultUser)) +.map().filter(); + +(valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(defaultUser)) +.map(); + +object[valid + ? helper.responseBody(this.currentUser) + : helper.responseBody(defaultUser)] +.map(); + +``` + +# Output +```js +(a ? b : c).d(); +(a ? b : c).d().e(); +(a ? b : c).d().e().f(); +( + valid ? helper.responseBody( + this.currentUser, + ) : helper.responseBody(this.defaultUser) +).map(); +( + valid ? helper.responseBody( + this.currentUser, + ) : helper.responseBody(this.defaultUser) +).map().filter(); +( + valid ? helper.responseBody( + this.currentUser, + ) : helper.responseBody(defaultUser) +).map(); +object[valid ? helper.responseBody( + this.currentUser, +) : helper.responseBody(defaultUser)].map(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/cypress.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/cypress.js.snap.new new file mode 100644 index 00000000000..3fc0e265fd5 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/cypress.js.snap.new @@ -0,0 +1,25 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: cypress.js +--- +# Input +```js +cy.get('option:first') + .should('be.selected') + .and('have.value', 'Metallica') + +cy.get(".ready") + .should("have.text", "FOO") + .should("have.css", "color", "#aaa"); + +``` + +# Output +```js +cy.get("option:first").should("be.selected").and("have.value", "Metallica"); +cy.get(".ready").should("have.text", "FOO").should("have.css", "color", "#aaa"); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/d3.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/d3.js.snap.new new file mode 100644 index 00000000000..0b82ac7ad96 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/d3.js.snap.new @@ -0,0 +1,51 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: d3.js +--- +# Input +```js +d3.select('body') + .append('circle') + .at({ width: 30, fill: '#f0f' }) + .st({ fontWeight: 600 }) + +const myScale = d3.scaleLinear() + .domain([1950, 1980]) + .range([0, width]) + +not.d3.select('body') + .append('circle') + .at({ width: 30, fill: '#f0f' }) + .st({ fontWeight: 600 }) + +not.d3.scaleLinear() + .domain([1950, 1980]) + .range([0, width]) + +``` + +# Output +```js +d3 + .select("body") + .append("circle") + .at({ width: 30, fill: "#f0f" },) + .st({ fontWeight: 600 },); +const myScale = d3 + .scaleLinear() + .domain([1950, 1980],) + .range([0, width],); +not.d3 + .select("body") + .append("circle") + .at({ width: 30, fill: "#f0f" },) + .st({ fontWeight: 600 },); +not.d3 + .scaleLinear() + .domain([1950, 1980],) + .range([0, width],); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap.new new file mode 100644 index 00000000000..12f70990ca4 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/first_long.js.snap.new @@ -0,0 +1,90 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: first_long.js +--- +# Input +```js +export default function theFunction(action$, store) { + return action$.ofType(THE_ACTION).switchMap(action => Observable + .webSocket({ + url: THE_URL, + more: stuff(), + evenMore: stuff({ + value1: true, + value2: false, + value3: false + }) + }) + .filter(data => theFilter(data)) + .map(({ theType, ...data }) => theMap(theType, data)) + .retryWhen(errors => errors)); +} + +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; + const metadataId = metadata.id; + const metadataModule = metadata.module; + if (metadataId && metadataModule) { + fileMetadata[H.ID] = metadataId; + setModule(metadataId, metadataModule); + } + fileMetadata[H.DEPENDENCIES] = metadata.dependencies || []; + } + ); +} + +``` + +# Output +```js +export default function theFunction(action$, store) { + return action$.ofType( + THE_ACTION, + ).switchMap( + ( + action, + ) => + Observable.webSocket({ + url: THE_URL, + more: stuff(), + evenMore: stuff({ + value1: true, + value2: false, + value3: false, + },), + },) + .filter((data) => theFilter(data)) + .map(({ theType, ...data }) => theMap(theType, data)) + .retryWhen((errors) => errors), + ); +} +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; + const metadataId = metadata.id; + const metadataModule = metadata.module; + if (metadataId && metadataModule) { + fileMetadata[H.ID] = metadataId; + 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.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap.new new file mode 100644 index 00000000000..cacc208e734 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/inline_merge.js.snap.new @@ -0,0 +1,48 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: inline_merge.js +--- +# Input +```js +Object.keys( + availableLocales({ + test: true + }) +) +.forEach(locale => { + // ... +}); + +this.layoutPartsToHide = this.utils.hashset( + _.flatMap(this.visibilityHandlers, fn => fn()) + .concat(this.record.resolved_legacy_visrules) + .filter(Boolean) +); + +var jqxhr = $.ajax("example.php") + .done(doneFn) + .fail(failFn); + +``` + +# Output +```js +Object.keys( + availableLocales({ + test: true, + },), +).forEach((locale) => { + // ... +},); +this.layoutPartsToHide = + this.utils.hashset( + _.flatMap(this.visibilityHandlers, (fn) => fn()) + .concat(this.record.resolved_legacy_visrules) + .filter(Boolean), + ); +var jqxhr = $.ajax("example.php").done(doneFn).fail(failFn); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-11298.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-11298.js.snap.new new file mode 100644 index 00000000000..91189ca0395 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-11298.js.snap.new @@ -0,0 +1,21 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-11298.js +--- +# Input +```js +foo1(/𠮟𠮟𠮟/).foo2(bar).foo3(baz); + +foo1(/叱叱叱/).foo2(bar).foo3(baz); + +``` + +# Output +```js +foo1(/𠮟𠮟𠮟/).foo2(bar).foo3(baz); +foo1(/叱叱叱/).foo2(bar).foo3(baz); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3594.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3594.js.snap.new new file mode 100644 index 00000000000..5daa91d63af --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3594.js.snap.new @@ -0,0 +1,31 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-3594.js +--- +# Input +```js +const fetched = fetch("/foo"); +fetched + .then(response => response.json()) + .then(json => processThings(json.data.things)); + +let column = new Column(null, conn) + .table(data.table) + .json(data.column); + +``` + +# Output +```js +const fetched = fetch("/foo"); +fetched.then( + (response) => response.json(), +).then((json) => processThings(json.data.things)); +let column = new Column(null, conn) + .table(data.table) + .json(data.column); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3621.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3621.js.snap.new new file mode 100644 index 00000000000..9eaf6e2f46c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-3621.js.snap.new @@ -0,0 +1,36 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-3621.js +--- +# Input +```js +const palindrome = str => { + const s = str.toLowerCase().replace(/[\W_]/g, ''); + return s === s.split('').reverse().join(''); +}; + +const apiCurrencies = api().currencies().all() + +expect(cells.at(1).render().text()).toBe('link text1') +expect(cells.at(2).render().text()).toBe('link text2') +expect(cells.at(3).render().text()).toBe('link text3') +expect(cells.at(4).render().text()).toBe('link text4') + +``` + +# Output +```js +const palindrome = (str) => { + const s = str.toLowerCase().replace(/[\W_]/g, ""); + return s === s.split("").reverse().join(""); +}; +const apiCurrencies = api().currencies().all(); +expect(cells.at(1).render().text()).toBe("link text1"); +expect(cells.at(2).render().text()).toBe("link text2"); +expect(cells.at(3).render().text()).toBe("link text3"); +expect(cells.at(4).render().text()).toBe("link text4"); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap.new new file mode 100644 index 00000000000..22b3e22e8d5 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/issue-4125.js.snap.new @@ -0,0 +1,326 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-4125.js +--- +# Input +```js +// examples from https://github.com/prettier/prettier/issues/4125 + +const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex"); + +req.checkBody('id').isInt().optional(); +req.checkBody('name').notEmpty().optional(); + +const x = moment().add(1, 'day').valueOf() + +// should stay on one line: +const y = obj.foo(1).foo(2).foo(3); +const z = obj.foo(-1).foo(import('2')).foo(!x).check(/[A-Z]/); + +// better on multiple lines: +somePromise.then(format).then((val)=>doSomething(val)).catch((err)=>handleError(err)) + +// you can still force multi-line chaining with a comment: +const sha256_2 = (data) => + crypto // breakme + .createHash("sha256") + .update(data) + .digest("hex"); + +// examples from https://github.com/prettier/prettier/pull/4765 + +if ($(el).attr("href").includes("/wiki/")) { +} + +if ($(el).attr("href").includes("/wiki/")) { + if ($(el).attr("xyz").includes("/whatever/")) { + if ($(el).attr("hello").includes("/world/")) { + } + } +} + +const parseNumbers = s => s.split('').map(Number).sort() + +function palindrome(a, b) { + return a.slice().reverse().join(',') === b.slice().sort().join(','); +} + +// examples from https://github.com/prettier/prettier/issues/1565 + +d3.select("body").selectAll("p").data([1, 2, 3]).enter().style("color", "white"); + +Object.keys(props).filter(key => key in own === false).reduce((a, key) => { + a[key] = props[key]; + return a; +}, {}) + +point().x(4).y(3).z(6).plot(); + +assert.equal(this.$().text().trim(), '1000'); + +something().then(() => doSomethingElse()).then(result => dontForgetThisAsWell(result)) + +db.branch( + db.table('users').filter({ email }).count(), + db.table('users').filter({ email: 'a@b.com' }).count(), + db.table('users').insert({ email }), + db.table('users').filter({ email }), +) + +sandbox.stub(config, 'get').withArgs('env').returns('dev') + +const date = moment.utc(userInput).hour(0).minute(0).second(0) + +fetchUser(id) + .then(fetchAccountForUser) + .catch(handleFetchError) + +fetchUser(id) // + .then(fetchAccountForUser) + .catch(handleFetchError) + +// examples from https://github.com/prettier/prettier/issues/3107 + +function HelloWorld() { + window.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, + }).initVerify('foo_container'); + + fejax.ajax({ + url: '/verification/', + dataType: 'json', + }).then( + (data) => { + this.setState({ isLoading: false }); + this.initWidget(data); + }, + (data) => { + this.logImpression('foo_fetch_error', data); + Flash.error(I18n.t('offline_identity.foo_issue')); + }, + ); +} + +action$.ofType(ActionTypes.SEARCHED_USERS) + .map(action => action.payload.query) + .filter(q => !!q) + .switchMap(q => + Observable.timer(800) // debounce + .takeUntil(action$.ofType(ActionTypes.CLEARED_SEARCH_RESULTS)) + .mergeMap(() => + Observable.merge( + Observable.of(replace(`?q=${q}`)), + ajax + .getJSON(`https://api.github.com/search/users?q=${q}`) + .map(res => res.items) + .map(receiveUsers) + ) + ) + ); + +window.FooClient + .setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, + }) + .initVerify('foo_container'); + +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) +const a3 = x.d('').e(`${123}`).f(g) +const a4 = x.h(i.j).k(l()).m([n, o]) +class X { + y() { + const j = x.a(this).b(super.cde()).f(/g/).h(new i()).j(); + } +} + +// should break when call expressions get complex +x.a().b([c, [d, [e]]]).f() +x.a().b(c(d(e()))).f() +x.a().b(`${c(d())}`).f() + +xyz.a().b().c(a(a(b(c(d().p).p).p).p)) + +var l = base + .replace(/^\w*:\/\//, '') + .replace(/\/$/, '') + .split('/').length + + +``` + +# Output +```js +// examples from https://github.com/prettier/prettier/issues/4125 + +const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex"); +req.checkBody("id").isInt().optional(); +req.checkBody("name").notEmpty().optional(); +const x = moment().add(1, "day").valueOf(); +// should stay on one line: +const y = obj.foo(1).foo(2).foo(3); +const z = obj.foo(-1).foo(import("2")).foo(!x).check(/[A-Z]/); +// better on multiple lines: +somePromise + .then(format) + .then((val) => doSomething(val)) + .catch((err) => handleError(err)); +// you can still force multi-line chaining with a comment: +const sha256_2 = ( + data, +) => + crypto // breakme + .createHash("sha256").update(data).digest("hex"); +// examples from https://github.com/prettier/prettier/pull/4765 + +if ($(el).attr("href").includes("/wiki/")) { +} +if ($(el).attr("href").includes("/wiki/")) { + if ($(el).attr("xyz").includes("/whatever/")) { + if ($(el).attr("hello").includes("/world/")) { + } + } +} +const parseNumbers = (s) => s.split("").map(Number).sort(); +function palindrome(a, b) { + return a.slice().reverse().join(",") === b.slice().sort().join(","); +} +// examples from https://github.com/prettier/prettier/issues/1565 + +d3 + .select("body") + .selectAll("p") + .data([1, 2, 3],) + .enter() + .style("color", "white"); +Object.keys(props) + .filter((key) => (key in own) === false) + .reduce( + (a, key) => { + a[key] = props[key]; + return a; + }, + {}, + ); +point().x(4).y(3).z(6).plot(); +assert.equal(this.$().text().trim(), "1000"); +something() + .then(() => doSomethingElse()) + .then((result) => dontForgetThisAsWell(result)); +db.branch( + db.table("users").filter({ email }).count(), + db + .table("users") + .filter({ email: "a@b.com" },) + .count(), + db.table("users").insert({ email }), + db.table("users").filter({ email }), +); +sandbox.stub(config, "get").withArgs("env").returns("dev"); +const date = moment.utc(userInput).hour(0).minute(0).second(0); +fetchUser(id).then(fetchAccountForUser).catch(handleFetchError); +fetchUser( + id, +) // +.then(fetchAccountForUser).catch(handleFetchError); +// examples from https://github.com/prettier/prettier/issues/3107 + +function HelloWorld() { + window.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, + },).initVerify("foo_container"); + fejax.ajax({ + url: "/verification/", + dataType: "json", + },).then( + (data) => { + this.setState({ isLoading: false },); + this.initWidget(data); + }, + (data) => { + this.logImpression("foo_fetch_error", data); + Flash.error(I18n.t("offline_identity.foo_issue")); + }, + ); +} +action$ + .ofType(ActionTypes.SEARCHED_USERS) + .map((action) => action.payload.query) + .filter((q) => !!q) + .switchMap( + ( + q, + ) => + Observable.timer(800) + // debounce + .takeUntil(action$.ofType(ActionTypes.CLEARED_SEARCH_RESULTS)) + .mergeMap( + () => + Observable.merge( + Observable.of(replace(`?q=${q}`)), + ajax + .getJSON(`https://api.github.com/search/users?q=${q}`) + .map((res) => res.items) + .map(receiveUsers), + ), + ), + ); +window.FooClient.setVars({ + locale: getFooLocale({ page }), + authorizationToken: data.token, +},).initVerify("foo_container"); +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); +const a3 = x.d("").e(`${123}`).f(g); +const a4 = x + .h(i.j) + .k(l()) + .m([n, o],); +class X { + y() { + const j = x + .a(this) + .b(super.cde()) + .f(/g/) + .h(new i()) + .j(); + } +} +// should break when call expressions get complex +x + .a() + .b([c, [d, [e]]],) + .f(); +x + .a() + .b(c(d(e()))) + .f(); +x + .a() + .b(`${c(d())}`) + .f(); +xyz + .a() + .b() + .c(a(a(b(c(d().p).p).p).p)); +var l = base.replace(/^\w*:\/\//, "").replace(/\/$/, "").split("/").length; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/logical.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/logical.js.snap.new new file mode 100644 index 00000000000..6050ef3f247 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/logical.js.snap.new @@ -0,0 +1,56 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: logical.js +--- +# Input +```js +const someLongVariableName = (idx( + this.props, + props => props.someLongPropertyName +) || [] +).map(edge => edge.node); + +(veryLongVeryLongVeryLong || e).map(tickets => + TicketRecord.createFromSomeLongString()); + +(veryLongVeryLongVeryLong || e).map(tickets => + TicketRecord.createFromSomeLongString()).filter(obj => !!obj); + +(veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError).map(tickets => + TicketRecord.createFromSomeLongString()); + +(veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError).map(tickets => + TicketRecord.createFromSomeLongString()).filter(obj => !!obj); + +``` + +# Output +```js +const someLongVariableName = ( + idx(this.props, (props) => props.someLongPropertyName) || [] +).map((edge) => edge.node); +( + veryLongVeryLongVeryLong || e +).map((tickets) => TicketRecord.createFromSomeLongString()); +( + veryLongVeryLongVeryLong || e +).map( + (tickets) => TicketRecord.createFromSomeLongString(), +).filter((obj) => !!obj); +( + veryLongVeryLongVeryLong || + anotherVeryLongVeryLongVeryLong || + veryVeryVeryLongError +).map((tickets) => TicketRecord.createFromSomeLongString()); +( + veryLongVeryLongVeryLong || + anotherVeryLongVeryLongVeryLong || + veryVeryVeryLongError +).map( + (tickets) => TicketRecord.createFromSomeLongString(), +).filter((obj) => !!obj); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap.new new file mode 100644 index 00000000000..48bf3a6337c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/multiple-members.js.snap.new @@ -0,0 +1,101 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: multiple-members.js +--- +# Input +```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" + }); + } + }); + }); +} + +wrapper.find('SomewhatLongNodeName').prop('longPropFunctionName')().then(function() { + doSomething(); +}); + +wrapper.find('SomewhatLongNodeName').prop('longPropFunctionName')('argument').then(function() { + doSomething(); +}); + +wrapper.find('SomewhatLongNodeName').prop('longPropFunctionName', 'second argument that pushes this group past 80 characters')('argument').then(function() { + doSomething(); +}); + +wrapper.find('SomewhatLongNodeName').prop('longPropFunctionName')('argument', 'second argument that pushes this group past 80 characters').then(function() { + doSomething(); +}); + +``` + +# 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", + },); + } + }, + ); + }, + ); +} +wrapper + .find("SomewhatLongNodeName") + .prop("longPropFunctionName")() + .then(function () { + doSomething(); + },); +wrapper + .find("SomewhatLongNodeName") + .prop("longPropFunctionName")("argument") + .then(function () { + doSomething(); + },); +wrapper + .find("SomewhatLongNodeName") + .prop( + "longPropFunctionName", + "second argument that pushes this group past 80 characters", + )("argument") + .then(function () { + doSomething(); + },); +wrapper + .find("SomewhatLongNodeName") + .prop( + "longPropFunctionName", + )("argument", "second argument that pushes this group past 80 characters") + .then(function () { + doSomething(); + },); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap.new new file mode 100644 index 00000000000..d387cbda082 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/object-literal.js.snap.new @@ -0,0 +1,45 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: object-literal.js +--- +# Input +```js +of("test") + .pipe(throwIfEmpty()) + .subscribe({ + error(err) { + thrown = err; + } + }); + +of("test") + .pipe(throwIfEmpty()) + .subscribe({ + get foo() { + bar(); + } + }); + +``` + +# Output +```js +of("test") + .pipe(throwIfEmpty()) + .subscribe({ + error(err) { + thrown = err; + }, + },); +of("test") + .pipe(throwIfEmpty()) + .subscribe({ + get foo() { + bar(); + }, + },); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/pr-7889.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/pr-7889.js.snap.new new file mode 100644 index 00000000000..4939d0d692e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/pr-7889.js.snap.new @@ -0,0 +1,49 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: pr-7889.js +--- +# Input +```js +const Profile = view.with({ name: (state) => state.name }).as((props) => ( +
+

Hello, {props.name}

+
+)) + +const Profile2 = view.with({ name }).as((props) => ( +
+

Hello, {props.name}

+
+)) + +``` + +# Output +```js +const Profile = view.with({ + name: (state) => state.name, +},).as( + ( + props, + ) => ( +
+

Hello, {props.name}

+
+ ), +); +const Profile2 = view.with({ + name, +},).as( + ( + props, + ) => ( +
+

Hello, {props.name}

+
+ ), +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/simple-args.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/simple-args.js.snap.new new file mode 100644 index 00000000000..a34db6ca43e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/simple-args.js.snap.new @@ -0,0 +1,21 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: simple-args.js +--- +# Input +```js +const fieldsToSend = _(["id", extra]).without("transition").uniq(); + +console.log(values.filter(isValid).map(extractId).slice(-5, -1)); + +``` + +# Output +```js +const fieldsToSend = _(["id", extra]).without("transition").uniq(); +console.log(values.filter(isValid).map(extractId).slice(-5, -1)); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/square_0.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/square_0.js.snap.new new file mode 100644 index 00000000000..98d8fa4459b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/square_0.js.snap.new @@ -0,0 +1,31 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: square_0.js +--- +# Input +```js +const version = someLongString + .split('jest version =') + .pop() + .split(EOL)[0] + .trim(); + +const component = find('.org-lclp-edit-copy-url-banner__link')[0] + .getAttribute('href') + .indexOf(this.landingPageLink); + +``` + +# Output +```js +const version = someLongString.split( + "jest version =", +).pop().split(EOL)[0].trim(); +const component = find(".org-lclp-edit-copy-url-banner__link")[0] + .getAttribute("href") + .indexOf(this.landingPageLink); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/test.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/test.js.snap.new new file mode 100644 index 00000000000..5677258db35 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/method-chain/test.js.snap.new @@ -0,0 +1,26 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: test.js +--- +# Input +```js +method().then(x => x) + ["abc"](x => x) + [abc](x => x); + +({}.a().b()); +({}).a().b(); + +``` + +# Output +```js +method() + .then((x) => x)["abc"]((x) => x)[abc]((x) => x); +({}.a().b()); +({}).a().b(); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/comments.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/comments.js.snap.new new file mode 100644 index 00000000000..7233222d1e7 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/comments.js.snap.new @@ -0,0 +1,71 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comments.js +--- +# Input +```js +const m = /*A1*/ module /*A2*/ { /*A3*/ + /*A4*/ + export const foo = "foo"; + export { foo }; /*A5*/ + /*A6*/ +}/*A7*/;/*A8*/ + +const m2 = module/* B1 */{ + /* B2 */ +}; + +``` + +# Output +```js +const m = /*A1*/ module /*A2*/ ; +{ + /*A3*/ /*A4*/ + export const foo = "foo"; + export { foo }; /*A5*/ + /*A6*/ +} /*A7*/ +/*A8*/ +const m2 = module /* B1 */ ; +{ + /* B2 */ +} + +``` + +# Errors +``` +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ comments.js:1:32 + │ +1 │ const m = /*A1*/ module /*A2*/ { /*A3*/ + │ -------------------------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ comments.js:3:3 + │ +3 │ export const foo = "foo"; + │ ^^^^^^^^^^^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ comments.js:4:3 + │ +4 │ export { foo }; /*A5*/ + │ ^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ comments.js:8:26 + │ +8 │ const m2 = module/* B1 */{ + │ -------------------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/module-blocks.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/module-blocks.js.snap.new new file mode 100644 index 00000000000..e813a3b91e0 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/module-blocks.js.snap.new @@ -0,0 +1,295 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: module-blocks.js +--- +# Input +```js +module { await 3 }; + +class B { + #p() { + module { + class C { [this.#p]; } + }; + } +} + +const m = module { + export const foo = "foo"; + export { foo }; +}; + +module { + export { foo } +}; + +const m = module {}; + +const worker = new Worker(module { + export const foo = "foo"; +}); + +let m = module { + module { + export let foo = "foo"; + }; +}; + +const m = module { export const foo = "foo" }; + +let moduleBlock = module { export let y = 1; }; + +foo(module { export let foo = "foo"; }); + +let m = module { /* foo */ }; + +``` + +# Output +```js +module; +{ + await 3; +} +class B { + #p() { + module; + { + class C { + [this.#p]; + } + } + } +} +const m = module; +{ + export const foo = "foo"; + export { foo }; +} +module; +{ + export { foo } +} +const m = module; +{ +} +const worker = new Worker(module { + export const foo = "foo"; +}) +let m = module; +{ + module; + { + export let foo = "foo"; + } +} +const m = module; +{ + export const foo = "foo" +} +let moduleBlock = module; +{ + export let y = 1; +} +foo(module { export let foo = "foo"; +}) +let m = module; +{ + /* foo */ +} + +``` + +# Errors +``` +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:1:8 + │ +1 │ module { await 3 }; + │ -------^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:5:12 + │ +5 │ module { + │ -------^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:11:18 + │ +11 │ const m = module { + │ -----------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ module-blocks.js:12:3 + │ +12 │ export const foo = "foo"; + │ ^^^^^^^^^^^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ module-blocks.js:13:3 + │ +13 │ export { foo }; + │ ^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:16:8 + │ +16 │ module { + │ -------^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ module-blocks.js:17:3 + │ +17 │ export { foo } + │ ^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:20:24 + │ +20 │ const m = module {}; + │ -----------------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: expected `,` but instead found `{` + ┌─ module-blocks.js:22:34 + │ +22 │ const worker = new Worker(module { + │ ^ unexpected + +error[SyntaxError]: expected `:` but instead found `const` + ┌─ module-blocks.js:23:10 + │ +23 │ export const foo = "foo"; + │ ^^^^^ unexpected + +error[SyntaxError]: expected `:` but instead found `foo` + ┌─ module-blocks.js:23:16 + │ +23 │ export const foo = "foo"; + │ ^^^ unexpected + +error[SyntaxError]: expected `,` but instead found `;` + ┌─ module-blocks.js:23:27 + │ +23 │ export const foo = "foo"; + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found '})' + ┌─ module-blocks.js:24:1 + │ +24 │ }); + │ ^^ Expected a statement here + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:26:16 + │ +26 │ let m = module { + │ ---------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:27:10 + │ +27 │ module { + │ -------^ + │ │ │ + │ │ An explicit or implicit semicolon is expected here... + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ module-blocks.js:28:5 + │ +28 │ export let foo = "foo"; + │ ^^^^^^^^^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:32:18 + │ +32 │ const m = module { export const foo = "foo" }; + │ -----------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ module-blocks.js:32:20 + │ +32 │ const m = module { export const foo = "foo" }; + │ ^^^^^^^^^^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:34:26 + │ +34 │ let moduleBlock = module { export let y = 1; }; + │ -------------------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ module-blocks.js:34:28 + │ +34 │ let moduleBlock = module { export let y = 1; }; + │ ^^^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: expected `,` but instead found `{` + ┌─ module-blocks.js:36:12 + │ +36 │ foo(module { export let foo = "foo"; }); + │ ^ unexpected + +error[SyntaxError]: expected `:` but instead found `let` + ┌─ module-blocks.js:36:21 + │ +36 │ foo(module { export let foo = "foo"; }); + │ ^^^ unexpected + +error[SyntaxError]: expected `,` but instead found `foo` + ┌─ module-blocks.js:36:25 + │ +36 │ foo(module { export let foo = "foo"; }); + │ ^^^ unexpected + +error[SyntaxError]: Did you mean to use a `:`? An `=` can only follow a property name when the containing object literal is part of a destructuring pattern. + ┌─ module-blocks.js:36:29 + │ +36 │ foo(module { export let foo = "foo"; }); + │ ^ + +error[SyntaxError]: expected `,` but instead found `;` + ┌─ module-blocks.js:36:36 + │ +36 │ foo(module { export let foo = "foo"; }); + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found '})' + ┌─ module-blocks.js:36:38 + │ +36 │ foo(module { export let foo = "foo"; }); + │ ^^ Expected a statement here + +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ module-blocks.js:38:16 + │ +38 │ let m = module { /* foo */ }; + │ ---------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/range.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/range.js.snap.new new file mode 100644 index 00000000000..05fcb10221b --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/range.js.snap.new @@ -0,0 +1,79 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: range.js +--- +# Input +```js +let moduleBlock = module { export let y = 1; +}; + +foo(module { export let foo = "foo"; }) + +``` + +# Output +```js +let moduleBlock = module { + export let y = 1; +} +foo(module { export let foo = "foo"; }) + +``` + +# Errors +``` +error[SyntaxError]: Expected a semicolon or an implicit semicolon after a statement, but found none + ┌─ range.js:1:26 + │ +1 │ let moduleBlock = module { export let y = 1; + │ -------------------------^ An explicit or implicit semicolon is expected here... + │ │ + │ ...Which is required to end this statement + +error[SyntaxError]: Illegal use of an export declaration not at the top level + ┌─ range.js:1:29 + │ +1 │ let moduleBlock = module { export let y = 1; + │ ^^^^^^^^^^^^^^^^^ move this declaration to the top level + +error[SyntaxError]: expected `,` but instead found `{` + ┌─ range.js:4:12 + │ +4 │ foo(module { export let foo = "foo"; }) + │ ^ unexpected + +error[SyntaxError]: expected `:` but instead found `let` + ┌─ range.js:4:21 + │ +4 │ foo(module { export let foo = "foo"; }) + │ ^^^ unexpected + +error[SyntaxError]: expected `,` but instead found `foo` + ┌─ range.js:4:25 + │ +4 │ foo(module { export let foo = "foo"; }) + │ ^^^ unexpected + +error[SyntaxError]: Did you mean to use a `:`? An `=` can only follow a property name when the containing object literal is part of a destructuring pattern. + ┌─ range.js:4:29 + │ +4 │ foo(module { export let foo = "foo"; }) + │ ^ + +error[SyntaxError]: expected `,` but instead found `;` + ┌─ range.js:4:36 + │ +4 │ foo(module { export let foo = "foo"; }) + │ ^ unexpected + +error[SyntaxError]: expected a statement but instead found '})' + ┌─ range.js:4:38 + │ +4 │ foo(module { export let foo = "foo"; }) + │ ^^ Expected a statement here + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/worker.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/worker.js.snap.new new file mode 100644 index 00000000000..448f0da409f --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/module-blocks/worker.js.snap.new @@ -0,0 +1,85 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: worker.js +--- +# Input +```js +let worker = new Worker(module { + onmessage = function({data}) { + let mod = import(data); + postMessage(mod.fn()); + } +}, {type: "module"}); + +let worker = new Worker(module { + onmessage = function({data}) { + let mod = import(data); + postMessage(mod.fn()); + } +}, {type: "module", foo: "bar" }); + +worker.postMessage(module { export function fn() { return "hello!" } }); + +``` + +# Output +```js +let worker = new Worker(module { + onmessage = function({data}) { + let mod = import(data); + postMessage(mod.fn()); + } +}, {type: "module"}); +let worker = new Worker(module { + onmessage = function({data}) { + let mod = import(data); + postMessage(mod.fn()); + } +}, {type: "module", foo: "bar" }); +worker.postMessage(module { export function fn() { return "hello!" } }); + +``` + +# Errors +``` +error[SyntaxError]: expected `,` but instead found `{` + ┌─ worker.js:1:32 + │ +1 │ let worker = new Worker(module { + │ ^ unexpected + +error[SyntaxError]: Did you mean to use a `:`? An `=` can only follow a property name when the containing object literal is part of a destructuring pattern. + ┌─ worker.js:2:13 + │ +2 │ onmessage = function({data}) { + │ ^ + +error[SyntaxError]: expected `,` but instead found `{` + ┌─ worker.js:8:32 + │ +8 │ let worker = new Worker(module { + │ ^ unexpected + +error[SyntaxError]: Did you mean to use a `:`? An `=` can only follow a property name when the containing object literal is part of a destructuring pattern. + ┌─ worker.js:9:13 + │ +9 │ onmessage = function({data}) { + │ ^ + +error[SyntaxError]: expected `,` but instead found `{` + ┌─ worker.js:15:27 + │ +15 │ worker.postMessage(module { export function fn() { return "hello!" } }); + │ ^ unexpected + +error[SyntaxError]: expected `:` but instead found `function` + ┌─ worker.js:15:36 + │ +15 │ worker.postMessage(module { export function fn() { return "hello!" } }); + │ ^^^^^^^^ unexpected + + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-comments/comment-inside.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-comments/comment-inside.js.snap.new new file mode 100644 index 00000000000..664f954b44e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-comments/comment-inside.js.snap.new @@ -0,0 +1,137 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: comment-inside.js +--- +# Input +```js +// #9274 +html` +
+ ${this.set && this.set.artist + /* avoid console errors if `this.set` is undefined */} +
+`; + +html`${ + foo + /* comment */ +}`; +html` +${ + foo + /* comment */ +} +`; + + +graphql`${ + foo + /* comment */ +}`; +graphql` +${ + foo + /* comment */ +} +`; + + +css`${ + foo + /* comment */ +}`; +css` +${ + foo + /* comment */ +} +`; + +markdown`${ + foo + /* comment */ +}`; +markdown` +${ + foo + /* comment */ +} +`; + +// https://github.com/prettier/prettier/pull/9278#issuecomment-700589195 +expr1 = html` +
+ ${x(foo, // fg + bar + )}
+`; + +``` + +# Output +```js +// #9274 +html` +
+ ${ + this.set && this.set.artist + /* avoid console errors if `this.set` is undefined */ +} +
+`; +html`${ + foo + /* comment */ +}`; +html` +${ + foo + /* comment */ +} +`; +graphql`${ + foo + /* comment */ +}`; +graphql` +${ + foo + /* comment */ +} +`; +css`${ + foo + /* comment */ +}`; +css` +${ + foo + /* comment */ +} +`; +markdown`${ + foo + /* comment */ +}`; +markdown` +${ + foo + /* comment */ +} +`; +// https://github.com/prettier/prettier/pull/9278#issuecomment-700589195 +expr1 = + html` +
+ ${ + x( + foo, // fg + bar, + ) + }
+`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/colons-after-substitutions2.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/colons-after-substitutions2.js.snap.new new file mode 100644 index 00000000000..b256f9eea9d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/colons-after-substitutions2.js.snap.new @@ -0,0 +1,60 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: colons-after-substitutions2.js +--- +# Input +```js +const Icon = styled.div` + height: 48px; + + ${Link}:nth-child(2) { + fill: rebeccapurple; + } +`; + +const Icon2 = styled.div` + height: 48px; + + ${Link}:empty:before{ + fill: rebeccapurple; + } +`; + +const Icon3 = styled.div` + height: 48px; + + ${Link}:not(:first-child) { + fill: rebeccapurple; + } +`; + +``` + +# Output +```js +const Icon = styled.div` + height: 48px; + + ${Link}:nth-child(2) { + fill: rebeccapurple; + } +`; +const Icon2 = styled.div` + height: 48px; + + ${Link}:empty:before{ + fill: rebeccapurple; + } +`; +const Icon3 = styled.div` + height: 48px; + + ${Link}:not(:first-child) { + fill: rebeccapurple; + } +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-11797.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-11797.js.snap.new new file mode 100644 index 00000000000..de2ff189d29 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-11797.js.snap.new @@ -0,0 +1,42 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-11797.js +--- +# Input +```js +const paragraph1 = css` + font-size: 12px; + transform: ${vert ? 'translateY' : 'translateX'}(${translation + handleOffset}px); +`; + +const paragraph2 = css` + transform: ${expr}(30px); +`; + +const paragraph3 = css` + transform: ${expr} (30px); +`; + +``` + +# Output +```js +const paragraph1 = css` + font-size: 12px; + transform: ${vert ? "translateY" : "translateX"}(${translation + handleOffset}px); +`; +const paragraph2 = css` + transform: ${expr}(30px); +`; +const paragraph3 = css` + transform: ${expr} (30px); +`; + +``` + +# Lines exceeding max width of 80 characters +``` + 3: transform: ${vert ? "translateY" : "translateX"}(${translation + handleOffset}px); +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2636.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2636.js.snap.new new file mode 100644 index 00000000000..bc6fa542c7a --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2636.js.snap.new @@ -0,0 +1,49 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-2636.js +--- +# Input +```js +export const ButtonWrapper = styled.button` + ${base} + ${hover} + ${opaque} + ${block} + ${active} + ${disabled} + ${outline} + ${dashed} + ${spacing} +`; + +export const ButtonWrapper2 = styled.button` + ${base} ${hover} ${opaque} ${block} ${active} ${disabled} ${outline} ${dashed} ${spacing} +`; + +``` + +# Output +```js +export const ButtonWrapper = styled.button` + ${base} + ${hover} + ${opaque} + ${block} + ${active} + ${disabled} + ${outline} + ${dashed} + ${spacing} +`; +export const ButtonWrapper2 = styled.button` + ${base} ${hover} ${opaque} ${block} ${active} ${disabled} ${outline} ${dashed} ${spacing} +`; + +``` + +# Lines exceeding max width of 80 characters +``` + 13: ${base} ${hover} ${opaque} ${block} ${active} ${disabled} ${outline} ${dashed} ${spacing} +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2883.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2883.js.snap.new new file mode 100644 index 00000000000..5fe66dac2e2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-2883.js.snap.new @@ -0,0 +1,48 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-2883.js +--- +# Input +```js +export const foo = css` +&.foo .${bar}::before,&.foo[value="hello"] .${bar}::before { + position: absolute; +} +`; + +export const foo2 = css` +a.${bar}:focus,a.${bar}:hover { + color: red; +} +`; + +export const global = css` +button.${foo}.${bar} { + color: #fff; +} +`; + +``` + +# Output +```js +export const foo = css` +&.foo .${bar}::before,&.foo[value="hello"] .${bar}::before { + position: absolute; +} +`; +export const foo2 = css` +a.${bar}:focus,a.${bar}:hover { + color: red; +} +`; +export const global = css` +button.${foo}.${bar} { + color: #fff; +} +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-5961.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-5961.js.snap.new new file mode 100644 index 00000000000..71f4d668f77 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-5961.js.snap.new @@ -0,0 +1,85 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-5961.js +--- +# Input +```js +const Steps = styled.div` + @media (min-width: 1px) { + ${Step}:nth-child(odd) {} + } +`; + +const Steps2 = styled.div` + @media (min-width: ${breakpoints.lg}) { + ${Step} { + margin-bottom: 90px; + } + + ${Step}:nth-child(odd) { + ${StepItemDescription} { + grid-row: 1; + grid-column: 3 / span 3; + } + ${Image} { + grid-row: 1; + grid-column: 7 / span 6; + } + } + + ${Step}:nth-child(even) { + ${Image} { + grid-row: 1; + grid-column: 3 / span 6; + } + ${StepItemDescription} { + grid-row: 1; + grid-column: 10 / span 3; + } + } + } +`; + +``` + +# Output +```js +const Steps = styled.div` + @media (min-width: 1px) { + ${Step}:nth-child(odd) {} + } +`; +const Steps2 = styled.div` + @media (min-width: ${breakpoints.lg}) { + ${Step} { + margin-bottom: 90px; + } + + ${Step}:nth-child(odd) { + ${StepItemDescription} { + grid-row: 1; + grid-column: 3 / span 3; + } + ${Image} { + grid-row: 1; + grid-column: 7 / span 6; + } + } + + ${Step}:nth-child(even) { + ${Image} { + grid-row: 1; + grid-column: 3 / span 6; + } + ${StepItemDescription} { + grid-row: 1; + grid-column: 10 / span 3; + } + } + } +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-9072.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-9072.js.snap.new new file mode 100644 index 00000000000..d22a28f095e --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/issue-9072.js.snap.new @@ -0,0 +1,40 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: issue-9072.js +--- +# Input +```js +const style1 = css` + width:${size+10}${sizeUnit}; + border:${size/10} ${sizeUnit} solid ${color}; +`; + +const style2 = css` + width: ${size + 10}${sizeUnit}; + border: ${size / 10} ${sizeUnit} solid ${color}; +`; + +const style3 = css` + foo: ${foo}${bar} ${baz}; +`; + +``` + +# Output +```js +const style1 = css` + width:${size + 10}${sizeUnit}; + border:${size / 10} ${sizeUnit} solid ${color}; +`; +const style2 = css` + width: ${size + 10}${sizeUnit}; + border: ${size / 10} ${sizeUnit} solid ${color}; +`; +const style3 = css` + foo: ${foo}${bar} ${baz}; +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components-multiple-expressions.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components-multiple-expressions.js.snap.new new file mode 100644 index 00000000000..123ae3002ef --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components-multiple-expressions.js.snap.new @@ -0,0 +1,54 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: styled-components-multiple-expressions.js +--- +# Input +```js +const Header = styled.div` + ${something()} + & > ${Child}:not(:first-child) { +margin-left:5px; +} +` + +const Header2 = styled.div` + ${something()} + & > ${Child}${Child2}:not(:first-child) { +margin-left:5px; +} +` + +styled.div`${foo}-idle { }` + +styled.div`${foo}-0-idle { }` + +styled.div` +font-family: "${a}", "${b}"; +` + +``` + +# Output +```js +const Header = styled.div` + ${something()} + & > ${Child}:not(:first-child) { +margin-left:5px; +} +`; +const Header2 = styled.div` + ${something()} + & > ${Child}${Child2}:not(:first-child) { +margin-left:5px; +} +`; +styled.div`${foo}-idle { }`; +styled.div`${foo}-0-idle { }`; +styled.div` +font-family: "${a}", "${b}"; +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components.js.snap.new new file mode 100644 index 00000000000..bceef5dc8c2 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/styled-components.js.snap.new @@ -0,0 +1,517 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: styled-components.js +--- +# Input +```js +const ListItem1 = styled.li``; + +const ListItem2 = styled.li` `; + +const Dropdown = styled.div`position: relative;` + +const Button = styled.button` + color: palevioletred ; + + font-size : 1em ; +`; + +const TomatoButton = Button.extend` + color : tomato ; + +border-color : tomato + ; + +`; + +Button.extend.attr({})` +border-color : black; +` + +styled(ExistingComponent)` + color : papayawhip ; background-color: firebrick`; + + +styled.button.attr({})` +border : rebeccapurple`; + +styled(ExistingComponent).attr({})` +border : rebeccapurple`; + +styled.div` + color: ${props => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${props => props.small ? 'font-size: 0.8em;' : ''}; +` + +styled.div` + color: ${props => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${props => props.small ? 'font-size: 0.8em;' : ''} +` + +styled.div` + /* prettier-ignore */ + color: ${props => props.theme.colors.paragraph}; + ${props => props.small ? 'font-size: 0.8em;' : ''}; +` + +styled.div` + color: ${props => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${props => props.small ? 'font-size: 0.8em;' : ''}; + /* prettier-ignore */ + ${props => props.red ? 'color: red;' : ''}; +` + +styled.div` + /* prettier-ignore */ + color: ${props => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${props => props.small ? 'font-size: 0.8em;' : ''}; + /* prettier-ignore */ + ${props => props.red ? 'color: red;' : ''}; + /* prettier-ignore */ +` + +styled.div` + ${sanitize} ${fonts} + html { + margin: 0; + } +` + +styled.div` + ${bar} + baz +` + +styled.span` + foo + ${bar} + baz +` + +styled.div` + foo + ${bar} + ${baz} +` + +styled.span` + ${foo} + ${bar} +` + +styled.div` + ${foo} bar +` + +styled.span` + ${foo} ${bar} + baz: ${foo} +` + +styled.span` +${foo}; +${bar}; +` + +styled.span` +${foo}: ${bar}; +` + +styled.span` +${foo}: ${bar} +` + +styled.span` +${foo}: +${bar} +` + +styled.span` +${foo}: +${bar}; +` + +styled.a` + ${feedbackCountBlockCss} + text-decoration: none; + + ${FeedbackCount} { + margin: 0; + } +` + +const StyledComponent1 = styled.div` + ${anInterpolation} + /* a comment */ + + .aRule { + color: red + } +`; + +const StyledComponent2 = styled.div` + ${anInterpolation} + + /* a comment */ + + .aRule { + color: red + } +`; + +const Direction = styled.span` + ${({ up }) => up && `color: ${color.positive};`} + ${({ down }) => down && `color: ${color.negative};`} +`; + +const Direction2 = styled.span` + ${({ up }) => up && `color: ${color.positive}`}; + ${({ down }) => down && `color: ${color.negative}`}; +`; + +const mixin = css` + color: ${props => props.color}; + ${props => props.otherProperty}: ${props => props.otherValue}; +`; + +const foo = styled.div` + display: flex; + ${props => props.useMixin && mixin} +`; + +const Single1 = styled.div` + color: red +`; + +const Single2 = styled.div` + color: red; +`; + +const Dropdown2 = styled.div` + /* A comment to avoid the prettier issue: https://github.com/prettier/prettier/issues/2291 */ + position: relative; +`; + +const bar = styled.div` + border-radius: 50%; + border: 5px solid rgba(var(--green-rgb), 0); + display: inline-block; + height: 40px; + width: 40px; + + ${props => + (props.complete || props.inProgress) && + css` + border-color: rgba(var(--green-rgb), 0.15); + `} + + div { + background-color: var(--purpleTT); + border-radius: 50%; + border: 4px solid rgba(var(--purple-rgb), 0.2); + color: var(--purpleTT); + display: inline-flex; + + ${props => + props.complete && + css` + background-color: var(--green); + border-width: 7px; + `} + + ${props => + (props.complete || props.inProgress) && + css` + border-color: var(--green); + `} + } +`; + +const A = styled.a` + display: inline-block; + color: #fff; + ${props => props.a &&css` + display: none; + `} + height: 30px; +`; + +const Foo = styled.p` + max-width: 980px; + ${mediaBreakpointOnlyXs` + && { + font-size: 0.8rem; + } + `} + + &.bottom { + margin-top: 3rem; + } +`; + +styled(A)` + // prettier-ignore + @media (aaaaaaaaaaaaa) { + z-index: ${(props) => (props.isComplete ? '1' : '0')}; + } +`; + +const StyledDiv = styled.div` + ${props => getSize(props.$size.xs)} + ${props => getSize(props.$size.sm, 'sm')} + ${props => getSize(props.$size.md, 'md')} +`; + +``` + +# Output +```js +const ListItem1 = styled.li``; +const ListItem2 = styled.li` `; +const Dropdown = styled.div`position: relative;`; +const Button = styled.button` + color: palevioletred ; + + font-size : 1em ; +`; +const TomatoButton = Button.extend` + color : tomato ; + +border-color : tomato + ; + +`; +Button.extend.attr({},)` +border-color : black; +`; +styled(ExistingComponent)` + color : papayawhip ; background-color: firebrick`; +styled.button.attr({},)` +border : rebeccapurple`; +styled(ExistingComponent).attr({},)` +border : rebeccapurple`; +styled.div` + color: ${(props) => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${(props) => props.small ? "font-size: 0.8em;" : ""}; +`; +styled.div` + color: ${(props) => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${(props) => props.small ? "font-size: 0.8em;" : ""} +`; +styled.div` + /* prettier-ignore */ + color: ${(props) => props.theme.colors.paragraph}; + ${(props) => props.small ? "font-size: 0.8em;" : ""}; +`; +styled.div` + color: ${(props) => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${(props) => props.small ? "font-size: 0.8em;" : ""}; + /* prettier-ignore */ + ${(props) => props.red ? "color: red;" : ""}; +`; +styled.div` + /* prettier-ignore */ + color: ${(props) => props.theme.colors.paragraph}; + /* prettier-ignore */ + ${(props) => props.small ? "font-size: 0.8em;" : ""}; + /* prettier-ignore */ + ${(props) => props.red ? "color: red;" : ""}; + /* prettier-ignore */ +`; +styled.div` + ${sanitize} ${fonts} + html { + margin: 0; + } +`; +styled.div` + ${bar} + baz +`; +styled.span` + foo + ${bar} + baz +`; +styled.div` + foo + ${bar} + ${baz} +`; +styled.span` + ${foo} + ${bar} +`; +styled.div` + ${foo} bar +`; +styled.span` + ${foo} ${bar} + baz: ${foo} +`; +styled.span` +${foo}; +${bar}; +`; +styled.span` +${foo}: ${bar}; +`; +styled.span` +${foo}: ${bar} +`; +styled.span` +${foo}: +${bar} +`; +styled.span` +${foo}: +${bar}; +`; +styled.a` + ${feedbackCountBlockCss} + text-decoration: none; + + ${FeedbackCount} { + margin: 0; + } +`; +const StyledComponent1 = styled.div` + ${anInterpolation} + /* a comment */ + + .aRule { + color: red + } +`; +const StyledComponent2 = styled.div` + ${anInterpolation} + + /* a comment */ + + .aRule { + color: red + } +`; +const Direction = styled.span` + ${({ up }) => up && `color: ${color.positive};`} + ${({ down }) => down && `color: ${color.negative};`} +`; +const Direction2 = styled.span` + ${({ up }) => up && `color: ${color.positive}`}; + ${({ down }) => down && `color: ${color.negative}`}; +`; +const mixin = css` + color: ${(props) => props.color}; + ${(props) => props.otherProperty}: ${(props) => props.otherValue}; +`; +const foo = styled.div` + display: flex; + ${(props) => props.useMixin && mixin} +`; +const Single1 = styled.div` + color: red +`; +const Single2 = styled.div` + color: red; +`; +const Dropdown2 = styled.div` + /* A comment to avoid the prettier issue: https://github.com/prettier/prettier/issues/2291 */ + position: relative; +`; +const bar = styled.div` + border-radius: 50%; + border: 5px solid rgba(var(--green-rgb), 0); + display: inline-block; + height: 40px; + width: 40px; + + ${ + ( + props, + ) => + (props.complete || props.inProgress) && css` + border-color: rgba(var(--green-rgb), 0.15); + ` +} + + div { + background-color: var(--purpleTT); + border-radius: 50%; + border: 4px solid rgba(var(--purple-rgb), 0.2); + color: var(--purpleTT); + display: inline-flex; + + ${ + ( + props, + ) => + props.complete && css` + background-color: var(--green); + border-width: 7px; + ` +} + + ${ + ( + props, + ) => + (props.complete || props.inProgress) && css` + border-color: var(--green); + ` +} + } +`; +const A = styled.a` + display: inline-block; + color: #fff; + ${ + ( + props, + ) => + props.a && css` + display: none; + ` +} + height: 30px; +`; +const Foo = styled.p` + max-width: 980px; + ${ + mediaBreakpointOnlyXs` + && { + font-size: 0.8rem; + } + ` +} + + &.bottom { + margin-top: 3rem; + } +`; +styled(A)` + // prettier-ignore + @media (aaaaaaaaaaaaa) { + z-index: ${(props) => (props.isComplete ? "1" : "0")}; + } +`; +const StyledDiv = styled.div` + ${(props) => getSize(props.$size.xs)} + ${(props) => getSize(props.$size.sm, "sm")} + ${(props) => getSize(props.$size.md, "md")} +`; + +``` + +# Lines exceeding max width of 80 characters +``` + 153: /* A comment to avoid the prettier issue: https://github.com/prettier/prettier/issues/2291 */ +``` + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/var.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/var.js.snap.new new file mode 100644 index 00000000000..fd0ab43ce3c --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-css/var.js.snap.new @@ -0,0 +1,64 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: var.js +--- +# Input +```js +const Something = styled.div` + background: var(--${one}); /* ... */ + border: 1px solid var(--${two}); /* ... */ +`; + +const StyledPurchaseCard = styled(Card)` + min-width: 200px; + background-color: var(--${props => props.color}); + color: #fff; +`; + +const v1 = css` +prop: var(--global--color--${props.variant}); +`; + +const v2 = css` + background-color: var(--global--color--${props.variant}); + + &:hover { + background-color: var(--global--color--${props.variant}__one); + } + ` + +export const StyledComponent = styled.div` + grid-area: area-${props => props.propName}; +` + +``` + +# Output +```js +const Something = styled.div` + background: var(--${one}); /* ... */ + border: 1px solid var(--${two}); /* ... */ +`; +const StyledPurchaseCard = styled(Card)` + min-width: 200px; + background-color: var(--${(props) => props.color}); + color: #fff; +`; +const v1 = css` +prop: var(--global--color--${props.variant}); +`; +const v2 = css` + background-color: var(--global--color--${props.variant}); + + &:hover { + background-color: var(--global--color--${props.variant}__one); + } + `; +export const StyledComponent = styled.div` + grid-area: area-${(props) => props.propName}; +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/escape.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/escape.js.snap.new new file mode 100644 index 00000000000..8549229879d --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/escape.js.snap.new @@ -0,0 +1,96 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: escape.js +--- +# Input +```js +gql` + "\`foo\` mutation payload." + type FooPayload { + bar: String + } +` + +gql` +type Project { + "Pattern: \`\${project}\`" + pattern: String + """ + Pattern: \`\${project}\` + """ + pattern: String + + # Also: Escaping the first parentheses... + "Pattern: \`$\{project}\`" + pattern: String + # Or escaping the first and second parentheses... + "Pattern: \`$\{project\}\`" + pattern: String +} +` + +gql` + """ + - \` + - \\\` + - \\ a + - \\\\ + - $ + - \$ + - \${ + - \\\${ + - \u1234 + """ + type A { + a + } +` + +``` + +# Output +```js +gql` + "\`foo\` mutation payload." + type FooPayload { + bar: String + } +`; +gql` +type Project { + "Pattern: \`\${project}\`" + pattern: String + """ + Pattern: \`\${project}\` + """ + pattern: String + + # Also: Escaping the first parentheses... + "Pattern: \`$\{project}\`" + pattern: String + # Or escaping the first and second parentheses... + "Pattern: \`$\{project\}\`" + pattern: String +} +`; +gql` + """ + - \` + - \\\` + - \\ a + - \\\\ + - $ + - \$ + - \${ + - \\\${ + - \u1234 + """ + type A { + a + } +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/expressions.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/expressions.js.snap.new new file mode 100644 index 00000000000..83a7e134991 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/expressions.js.snap.new @@ -0,0 +1,51 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: expressions.js +--- +# Input +```js +graphql(schema, ` +query allPartsByManufacturerName($name: String!) { + allParts(filter:{manufacturer: {name: $name}}) { +... PartAll +}} +${fragments.all} +`) + +const veryLongVariableNameToMakeTheLineBreak = graphql(schema, ` +query allPartsByManufacturerName($name: String!) { + allParts(filter:{manufacturer: {name: $name}}) { +... PartAll +}} +${fragments.all} +`) + +``` + +# Output +```js +graphql( + schema, + ` +query allPartsByManufacturerName($name: String!) { + allParts(filter:{manufacturer: {name: $name}}) { +... PartAll +}} +${fragments.all} +`, +); +const veryLongVariableNameToMakeTheLineBreak = graphql( + schema, + ` +query allPartsByManufacturerName($name: String!) { + allParts(filter:{manufacturer: {name: $name}}) { +... PartAll +}} +${fragments.all} +`, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/react-relay.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/react-relay.js.snap.new new file mode 100644 index 00000000000..376362daefc --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-graphql/react-relay.js.snap.new @@ -0,0 +1,48 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: react-relay.js +--- +# Input +```js +const { graphql } = require("react-relay"); + +graphql` + mutation MarkReadNotificationMutation( + $input + : MarkReadNotificationData! + ) +{ markReadNotification(data: $input ) { notification {seenState} } } +`; + +graphql.experimental` + mutation MarkReadNotificationMutation( + $input + : MarkReadNotificationData! + ) +{ markReadNotification(data: $input ) { notification {seenState} } } +`; + +``` + +# Output +```js +const { graphql } = require("react-relay"); +graphql` + mutation MarkReadNotificationMutation( + $input + : MarkReadNotificationData! + ) +{ markReadNotification(data: $input ) { notification {seenState} } } +`; +graphql.experimental` + mutation MarkReadNotificationMutation( + $input + : MarkReadNotificationData! + ) +{ markReadNotification(data: $input ) { notification {seenState} } } +`; + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/html-template-literals.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/html-template-literals.js.snap.new new file mode 100644 index 00000000000..66645b4d872 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/html-template-literals.js.snap.new @@ -0,0 +1,76 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: html-template-literals.js +--- +# Input +```js +const nestedFun = /* HTML */ `${outerExpr(1)} + `; + +const nestedFun2 = /* HTML */ `${outerExpr(1)} + `; + +setFoo( + html`
one
+
two
+
three
`, + secondArgument +); + +setFoo( + html`
+
nested
+
+
two
+
three
`, + secondArgument +); + +setFoo( + html`
+
nested
+
`, + secondArgument +); + +``` + +# Output +```js +const nestedFun = /* HTML */ `${outerExpr(1)} + `; +const nestedFun2 = /* HTML */ `${outerExpr(1)} + `; +setFoo( + html`
one
+
two
+
three
`, + secondArgument, +); +setFoo( + html`
+
nested
+
+
two
+
three
`, + secondArgument, +); +setFoo( + html`
+
nested
+
`, + secondArgument, +); + +``` + + diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new new file mode 100644 index 00000000000..87c4d630b77 --- /dev/null +++ b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new @@ -0,0 +1,212 @@ +--- +source: crates/rome_js_formatter/tests/prettier_tests.rs +assertion_line: 182 +expression: lit-html.js +--- +# Input +```js +import { LitElement, html } from '@polymer/lit-element'; + +class MyElement extends LitElement { + static get properties() { + return { + mood: { type: String } + }; + } + + constructor() { + super(); + this.mood = 'happy'; + } + + render() { + return html` + + + Web Components are ${ + this.mood + + }! + `; + } +} + +customElements.define('my-element', MyElement); + +const someHtml1 = html`
hello ${world}
`; +const someHtml2 = /* HTML */ `
hello ${world}
`; + +html`` + +html``; + +html` <${Footer} >footer content ` + +html`
` + +html` +
+` + +html`onetwothree`; + +function HelloWorld() { + return html` +

Bar List

+ ${bars.map(bar => html` +

${bar}

+ `)} + `; +} + +const trickyParens = html``; +const nestedFun = /* HTML */ `${outerExpr( 1 )} `; + +const closingScriptTagShouldBeEscapedProperly = /* HTML */ ` + +`; + +const closingScriptTag2 = /* HTML */ ``; +const nestedFun = /* HTML */ `${outerExpr( + 1, +)} `; +const closingScriptTagShouldBeEscapedProperly = /* HTML */ ` + +`; +const closingScriptTag2 = /* HTML */ ``; - -const nestedFun2 = /* HTML */ `${outerExpr(1)} - `; - -setFoo( - html`
one
-
two
-
three
`, - secondArgument -); - -setFoo( - html`
-
nested
-
-
two
-
three
`, - secondArgument -); - -setFoo( - html`
-
nested
-
`, - secondArgument -); - -``` - -# Output -```js -const nestedFun = /* HTML */ `${outerExpr(1)} - `; -const nestedFun2 = /* HTML */ `${outerExpr(1)} - `; -setFoo( - html`
one
-
two
-
three
`, - secondArgument, -); -setFoo( - html`
-
nested
-
-
two
-
three
`, - secondArgument, -); -setFoo( - html`
-
nested
-
`, - secondArgument, -); - -``` - - diff --git a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new b/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new deleted file mode 100644 index 87c4d630b77..00000000000 --- a/crates/rome_js_formatter/tests/specs/prettier/js/multiparser-html/lit-html.js.snap.new +++ /dev/null @@ -1,212 +0,0 @@ ---- -source: crates/rome_js_formatter/tests/prettier_tests.rs -assertion_line: 182 -expression: lit-html.js ---- -# Input -```js -import { LitElement, html } from '@polymer/lit-element'; - -class MyElement extends LitElement { - static get properties() { - return { - mood: { type: String } - }; - } - - constructor() { - super(); - this.mood = 'happy'; - } - - render() { - return html` - - - Web Components are ${ - this.mood - - }! - `; - } -} - -customElements.define('my-element', MyElement); - -const someHtml1 = html`
hello ${world}
`; -const someHtml2 = /* HTML */ `
hello ${world}
`; - -html`` - -html``; - -html` <${Footer} >footer content ` - -html`
` - -html` -
-` - -html`onetwothree`; - -function HelloWorld() { - return html` -

Bar List

- ${bars.map(bar => html` -

${bar}

- `)} - `; -} - -const trickyParens = html``; -const nestedFun = /* HTML */ `${outerExpr( 1 )} `; - -const closingScriptTagShouldBeEscapedProperly = /* HTML */ ` - -`; - -const closingScriptTag2 = /* HTML */ ``; -const nestedFun = /* HTML */ `${outerExpr( - 1, -)} `; -const closingScriptTagShouldBeEscapedProperly = /* HTML */ ` - -`; -const closingScriptTag2 = /* HTML */ `