From a58e46a0cecacc8b22f2dae33ec8e46dbe989152 Mon Sep 17 00:00:00 2001 From: Denis Bezrukov <6227442+denbezrukov@users.noreply.github.com> Date: Sun, 2 Nov 2025 18:17:38 +0200 Subject: [PATCH 1/2] refactor(formatter): Introduce Token element --- .changeset/lemon-planes-knock.md | 11 + crates/biome_css_formatter/src/comments.rs | 7 +- .../auxiliary/declaration_with_semicolon.rs | 2 +- .../src/css/value/url_value_raw.rs | 4 +- crates/biome_css_formatter/src/lib.rs | 7 +- .../src/utils/string_utils.rs | 4 +- crates/biome_css_formatter/src/verbatim.rs | 4 +- .../src/format_semantic_model.rs | 26 +- crates/biome_formatter/src/arguments.rs | 16 +- crates/biome_formatter/src/buffer.rs | 40 +- crates/biome_formatter/src/builders.rs | 428 +++++++++--------- crates/biome_formatter/src/format_element.rs | 27 +- .../src/format_element/document.rs | 149 +++--- .../biome_formatter/src/format_extensions.rs | 10 +- crates/biome_formatter/src/formatter.rs | 32 +- crates/biome_formatter/src/lib.rs | 10 +- crates/biome_formatter/src/macros.rs | 154 +++---- crates/biome_formatter/src/printer/mod.rs | 287 +++++++----- crates/biome_formatter/src/separated.rs | 4 +- crates/biome_formatter/src/source_map.rs | 2 +- .../biome_graphql_formatter/src/comments.rs | 7 +- .../graphql/auxiliary/union_member_types.rs | 2 +- .../graphql/lists/argument_definition_list.rs | 2 +- .../src/graphql/lists/argument_list.rs | 2 +- .../graphql/lists/list_value_element_list.rs | 2 +- .../graphql/lists/object_value_member_list.rs | 2 +- .../graphql/lists/variable_definition_list.rs | 2 +- .../src/graphql/value/string_value.rs | 14 +- .../biome_graphql_formatter/src/verbatim.rs | 4 +- crates/biome_grit_formatter/src/comments.rs | 9 +- crates/biome_grit_formatter/src/verbatim.rs | 4 +- .../html/auxiliary/self_closing_element.rs | 2 +- .../src/html/auxiliary/string.rs | 4 +- .../src/utils/children.rs | 2 +- .../src/utils/formatters.rs | 2 +- crates/biome_html_formatter/src/verbatim.rs | 6 +- crates/biome_js_formatter/src/comments.rs | 6 +- .../src/context/trailing_commas.rs | 4 +- .../src/js/classes/extends_clause.rs | 6 +- .../expressions/arrow_function_expression.rs | 32 +- .../expressions/bigint_literal_expression.rs | 2 +- .../src/js/expressions/new_expression.rs | 2 +- .../src/js/expressions/unary_expression.rs | 4 +- .../src/js/statements/expression_statement.rs | 6 +- .../src/js/statements/labeled_statement.rs | 2 +- .../src/js/statements/return_statement.rs | 9 +- .../src/jsx/expressions/tag_expression.rs | 4 +- crates/biome_js_formatter/src/lib.rs | 4 +- .../external_module_declaration.rs | 2 +- .../expressions/type_assertion_expression.rs | 4 +- .../src/ts/lists/type_member_list.rs | 6 +- .../src/ts/types/bigint_literal_type.rs | 2 +- .../src/ts/types/union_type.rs | 6 +- crates/biome_js_formatter/src/utils/array.rs | 2 +- .../src/utils/conditional.rs | 8 +- crates/biome_js_formatter/src/utils/jsx.rs | 2 +- .../src/utils/member_chain/groups.rs | 2 +- crates/biome_js_formatter/src/utils/mod.rs | 2 +- .../src/utils/test_each_template.rs | 14 +- crates/biome_js_formatter/src/verbatim.rs | 4 +- .../src/format_semantic_model.rs | 38 +- .../src/format_type_info.rs | 343 +++++++------- .../src/format_jsdoc_comment.rs | 11 +- crates/biome_json_formatter/src/comments.rs | 7 +- crates/biome_json_formatter/src/verbatim.rs | 4 +- .../src/format_module_graph.rs | 96 ++-- 66 files changed, 975 insertions(+), 949 deletions(-) create mode 100644 .changeset/lemon-planes-knock.md diff --git a/.changeset/lemon-planes-knock.md b/.changeset/lemon-planes-knock.md new file mode 100644 index 000000000000..9ffecb931fe6 --- /dev/null +++ b/.changeset/lemon-planes-knock.md @@ -0,0 +1,11 @@ +--- +"@biomejs/biome": patch +--- + +Refactored formatter to use strict `Token` element for better performance. The new `Token` variant is optimized for static, ASCII-only text (keywords, operators, punctuation) with the following constraints: + +- ASCII only (no Unicode characters) +- No newlines (`\n`, `\r`) +- No tab characters (`\t`) + +This enables faster printing and fitting logic by using bulk string operations (`push_str`, `len()`) instead of character-by-character iteration with Unicode width calculations. diff --git a/crates/biome_css_formatter/src/comments.rs b/crates/biome_css_formatter/src/comments.rs index a03b10f6d90e..595ae140c803 100644 --- a/crates/biome_css_formatter/src/comments.rs +++ b/crates/biome_css_formatter/src/comments.rs @@ -33,7 +33,7 @@ impl FormatRule> for FormatCssLeadingComment { // SAFETY: Safe, `is_doc_comment` only returns `true` for multiline comments let first_line = lines.next().unwrap(); - write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?; + write!(f, [text(first_line.trim_end(), source_offset)])?; source_offset += first_line.text_len(); @@ -44,10 +44,7 @@ impl FormatRule> for FormatCssLeadingComment { 1, &format_once(|f| { for line in lines { - write!( - f, - [hard_line_break(), dynamic_text(line.trim(), source_offset)] - )?; + write!(f, [hard_line_break(), text(line.trim(), source_offset)])?; source_offset += line.text_len(); } diff --git a/crates/biome_css_formatter/src/css/auxiliary/declaration_with_semicolon.rs b/crates/biome_css_formatter/src/css/auxiliary/declaration_with_semicolon.rs index a9a2c29ef362..ddfe795ae364 100644 --- a/crates/biome_css_formatter/src/css/auxiliary/declaration_with_semicolon.rs +++ b/crates/biome_css_formatter/src/css/auxiliary/declaration_with_semicolon.rs @@ -21,7 +21,7 @@ impl FormatNodeRule for FormatCssDeclarationWithSem // if semicolon is present, use the token's format to keep the comments write!(f, [semicolon_token.format()]) } else { - write!(f, [text(";")]) + write!(f, [token(";")]) } } } diff --git a/crates/biome_css_formatter/src/css/value/url_value_raw.rs b/crates/biome_css_formatter/src/css/value/url_value_raw.rs index 333dad79a519..bc65b53a0352 100644 --- a/crates/biome_css_formatter/src/css/value/url_value_raw.rs +++ b/crates/biome_css_formatter/src/css/value/url_value_raw.rs @@ -8,12 +8,12 @@ impl FormatNodeRule for FormatCssUrlValueRaw { fn fmt_fields(&self, node: &CssUrlValueRaw, f: &mut CssFormatter) -> FormatResult<()> { let CssUrlValueRawFields { value_token } = node.as_fields(); let value_token = value_token?; - let text = value_token.token_text(); + let token_text = value_token.token_text(); write!( f, [format_replaced( &value_token, - &dynamic_text(text.trim(), value_token.text_trimmed_range().start()) + &text(token_text.trim(), value_token.text_trimmed_range().start()) )] ) } diff --git a/crates/biome_css_formatter/src/lib.rs b/crates/biome_css_formatter/src/lib.rs index 8d75c1fd044d..7ccca83df7f9 100644 --- a/crates/biome_css_formatter/src/lib.rs +++ b/crates/biome_css_formatter/src/lib.rs @@ -316,10 +316,9 @@ impl FormatRule for FormatCssSyntaxToken { let original = token.text_trimmed(); match original.to_ascii_lowercase_cow() { Cow::Borrowed(_) => self.format_trimmed_token_trivia(token, f), - Cow::Owned(lowercase) => write!( - f, - [dynamic_text(&lowercase, token.text_trimmed_range().start())] - ), + Cow::Owned(lowercase) => { + write!(f, [text(&lowercase, token.text_trimmed_range().start())]) + } } } else { self.format_trimmed_token_trivia(token, f) diff --git a/crates/biome_css_formatter/src/utils/string_utils.rs b/crates/biome_css_formatter/src/utils/string_utils.rs index 355a5e5475ba..84fa158a2de8 100644 --- a/crates/biome_css_formatter/src/utils/string_utils.rs +++ b/crates/biome_css_formatter/src/utils/string_utils.rs @@ -9,7 +9,7 @@ use biome_formatter::QuoteStyle; use biome_formatter::token::string::normalize_string; use biome_formatter::{ Format, FormatResult, - prelude::{dynamic_text, write}, + prelude::{text, write}, }; use biome_rowan::SyntaxToken; use biome_string_case::StrLikeExtension; @@ -35,7 +35,7 @@ impl Format for FormatTokenAsLowercase { f, [format_replaced( &self.token, - &dynamic_text(&lowercase, self.token.text_trimmed_range().start()), + &text(&lowercase, self.token.text_trimmed_range().start()), )] ), } diff --git a/crates/biome_css_formatter/src/verbatim.rs b/crates/biome_css_formatter/src/verbatim.rs index 4444b790386f..cbf30eb80645 100644 --- a/crates/biome_css_formatter/src/verbatim.rs +++ b/crates/biome_css_formatter/src/verbatim.rs @@ -2,7 +2,7 @@ use crate::context::CssFormatContext; use biome_css_syntax::{CssLanguage, CssSyntaxNode}; use biome_formatter::format_element::tag::VerbatimKind; use biome_formatter::formatter::Formatter; -use biome_formatter::prelude::{Tag, dynamic_text}; +use biome_formatter::prelude::{Tag, text}; use biome_formatter::trivia::{FormatLeadingComments, FormatTrailingComments}; use biome_formatter::{ Buffer, CstFormatContext, Format, FormatContext, FormatElement, FormatError, FormatResult, @@ -114,7 +114,7 @@ impl Format for FormatCssVerbatimNode<'_> { }, ); - dynamic_text( + text( &normalize_newlines(&original_source, LINE_TERMINATORS), self.node.text_trimmed_range().start(), ) diff --git a/crates/biome_css_semantic/src/format_semantic_model.rs b/crates/biome_css_semantic/src/format_semantic_model.rs index d475f588b6d8..00ebf37dd539 100644 --- a/crates/biome_css_semantic/src/format_semantic_model.rs +++ b/crates/biome_css_semantic/src/format_semantic_model.rs @@ -90,11 +90,11 @@ impl Format for Rule { write!( f, [ - dynamic_text( + text( self.node().syntax().text_trimmed().into_text().text(), self.node().syntax().text_trimmed_range().start() ), - text(":"), + token(":"), space(), &self.specificity(), ] @@ -108,13 +108,13 @@ impl Format for Selector { write!( f, [ - dynamic_text(self.text().into_text().text(), self.range().start()), - text(":"), + text(self.text().into_text().text(), self.range().start()), + token(":"), space(), &self.specificity(), space(), - text(" @ "), - dynamic_text(range.as_str(), TextSize::default()), + token(" @ "), + text(range.as_str(), TextSize::default()), ] ) } @@ -125,15 +125,15 @@ impl Format for Specificity { write!( f, [ - text("("), - dynamic_text(self.0.to_string().as_str(), TextSize::default()), - text(","), + token("("), + text(self.0.to_string().as_str(), TextSize::default()), + token(","), space(), - dynamic_text(self.1.to_string().as_str(), TextSize::default()), - text(","), + text(self.1.to_string().as_str(), TextSize::default()), + token(","), space(), - dynamic_text(self.2.to_string().as_str(), TextSize::default()), - text(")") + text(self.2.to_string().as_str(), TextSize::default()), + token(")") ] ) } diff --git a/crates/biome_formatter/src/arguments.rs b/crates/biome_formatter/src/arguments.rs index aee7689a6b6b..bcac44979b55 100644 --- a/crates/biome_formatter/src/arguments.rs +++ b/crates/biome_formatter/src/arguments.rs @@ -76,7 +76,7 @@ impl Format for Argument<'_, Context> { /// /// # fn main() -> FormatResult<()> { /// let formatted = format!(SimpleFormatContext::default(), [ -/// format_args!(text("a"), space(), text("b")) +/// format_args!(token("a"), space(), token("b")) /// ])?; /// /// assert_eq!("a b", formatted.print()?.as_code()); @@ -140,11 +140,11 @@ mod tests { write!( &mut buffer, [ - text("function"), + token("function"), space(), - text("a"), + token("a"), space(), - group(&format_args!(text("("), text(")"))) + group(&format_args!(token("("), token(")"))) ] ) .unwrap(); @@ -152,14 +152,14 @@ mod tests { assert_eq!( buffer.into_vec(), vec![ - FormatElement::StaticText { text: "function" }, + FormatElement::Token { text: "function" }, FormatElement::Space, - FormatElement::StaticText { text: "a" }, + FormatElement::Token { text: "a" }, FormatElement::Space, // Group FormatElement::Tag(Tag::StartGroup(tag::Group::new())), - FormatElement::StaticText { text: "(" }, - FormatElement::StaticText { text: ")" }, + FormatElement::Token { text: "(" }, + FormatElement::Token { text: ")" }, FormatElement::Tag(Tag::EndGroup) ] ); diff --git a/crates/biome_formatter/src/buffer.rs b/crates/biome_formatter/src/buffer.rs index 06332fbb234e..ee6130ad6309 100644 --- a/crates/biome_formatter/src/buffer.rs +++ b/crates/biome_formatter/src/buffer.rs @@ -27,9 +27,9 @@ pub trait Buffer { /// let mut state = FormatState::new(SimpleFormatContext::default()); /// let mut buffer = VecBuffer::new(&mut state); /// - /// buffer.write_element(FormatElement::StaticText { text: "test"}).unwrap(); + /// buffer.write_element(FormatElement::Token { text: "test"}).unwrap(); /// - /// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText { text: "test" }]); + /// assert_eq!(buffer.into_vec(), vec![FormatElement::Token { text: "test" }]); /// ``` /// fn write_element(&mut self, element: FormatElement) -> FormatResult<()>; @@ -53,9 +53,9 @@ pub trait Buffer { /// let mut state = FormatState::new(SimpleFormatContext::default()); /// let mut buffer = VecBuffer::new(&mut state); /// - /// buffer.write_fmt(format_args!(text("Hello World"))).unwrap(); + /// buffer.write_fmt(format_args!(token("Hello World"))).unwrap(); /// - /// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText{ text: "Hello World" }]); + /// assert_eq!(buffer.into_vec(), vec![FormatElement::Token{ text: "Hello World" }]); /// ``` fn write_fmt(mut self: &mut Self, arguments: Arguments) -> FormatResult<()> { write(&mut self, arguments) @@ -269,7 +269,7 @@ Make sure that you take and restore the snapshot in order and that this snapshot /// /// impl Format for Preamble { /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { -/// write!(f, [text("# heading"), hard_line_break()]) +/// write!(f, [token("# heading"), hard_line_break()]) /// } /// } /// @@ -280,7 +280,7 @@ Make sure that you take and restore the snapshot in order and that this snapshot /// { /// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble); /// -/// write!(&mut with_preamble, [text("this text will be on a new line")])?; +/// write!(&mut with_preamble, [token("this text will be on a new line")])?; /// } /// /// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default()); @@ -300,7 +300,7 @@ Make sure that you take and restore the snapshot in order and that this snapshot /// /// impl Format for Preamble { /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { -/// write!(f, [text("# heading"), hard_line_break()]) +/// write!(f, [token("# heading"), hard_line_break()]) /// } /// } /// @@ -455,11 +455,11 @@ where /// write!( /// buffer, /// [ -/// text("The next soft line or space gets replaced by a space"), +/// token("The next soft line or space gets replaced by a space"), /// soft_line_break_or_space(), -/// text("and the line here"), +/// token("and the line here"), /// soft_line_break(), -/// text("is removed entirely.") +/// token("is removed entirely.") /// ] /// ) /// })] @@ -468,10 +468,10 @@ where /// assert_eq!( /// formatted.document().as_ref(), /// &[ -/// FormatElement::StaticText { text: "The next soft line or space gets replaced by a space" }, +/// FormatElement::Token { text: "The next soft line or space gets replaced by a space" }, /// FormatElement::Space, -/// FormatElement::StaticText { text: "and the line here" }, -/// FormatElement::StaticText { text: "is removed entirely." } +/// FormatElement::Token { text: "and the line here" }, +/// FormatElement::Token { text: "is removed entirely." } /// ] /// ); /// @@ -706,19 +706,19 @@ pub trait BufferExtensions: Buffer + Sized { /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { /// let mut recording = f.start_recording(); /// - /// write!(recording, [text("A")])?; - /// write!(recording, [text("B")])?; + /// write!(recording, [token("A")])?; + /// write!(recording, [token("B")])?; /// - /// write!(recording, [format_with(|f| write!(f, [text("C"), text("D")]))])?; + /// write!(recording, [format_with(|f| write!(f, [token("C"), token("D")]))])?; /// /// let recorded = recording.stop(); /// assert_eq!( /// recorded.deref(), /// &[ - /// FormatElement::StaticText{ text: "A" }, - /// FormatElement::StaticText{ text: "B" }, - /// FormatElement::StaticText{ text: "C" }, - /// FormatElement::StaticText{ text: "D" } + /// FormatElement::Token{ text: "A" }, + /// FormatElement::Token{ text: "B" }, + /// FormatElement::Token{ text: "C" }, + /// FormatElement::Token{ text: "D" } /// ] /// ); /// diff --git a/crates/biome_formatter/src/builders.rs b/crates/biome_formatter/src/builders.rs index 278c7fde95f5..9dea24d0ad9b 100644 --- a/crates/biome_formatter/src/builders.rs +++ b/crates/biome_formatter/src/builders.rs @@ -24,7 +24,7 @@ use std::num::NonZeroU8; /// /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ -/// group(&format_args![text("a,"), soft_line_break(), text("b")]) +/// group(&format_args![token("a,"), soft_line_break(), token("b")]) /// ])?; /// /// assert_eq!( @@ -50,9 +50,9 @@ use std::num::NonZeroU8; /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("a long word,"), +/// token("a long word,"), /// soft_line_break(), -/// text("so that the group doesn't fit on a single line"), +/// token("so that the group doesn't fit on a single line"), /// ]) /// ])?; /// @@ -81,9 +81,9 @@ pub const fn soft_line_break() -> Line { /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("a,"), +/// token("a,"), /// hard_line_break(), -/// text("b"), +/// token("b"), /// hard_line_break() /// ]) /// ])?; @@ -113,9 +113,9 @@ pub const fn hard_line_break() -> Line { /// let elements = format!( /// SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("a,"), +/// token("a,"), /// empty_line(), -/// text("b"), +/// token("b"), /// empty_line() /// ]) /// ])?; @@ -144,9 +144,9 @@ pub const fn empty_line() -> Line { /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("a,"), +/// token("a,"), /// soft_line_break_or_space(), -/// text("b"), +/// token("b"), /// ]) /// ])?; /// @@ -171,9 +171,9 @@ pub const fn empty_line() -> Line { /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("a long word,"), +/// token("a long word,"), /// soft_line_break_or_space(), -/// text("so that the group doesn't fit on a single line"), +/// token("so that the group doesn't fit on a single line"), /// ]) /// ])?; /// @@ -212,12 +212,8 @@ impl std::fmt::Debug for Line { } } -/// 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]. +/// Creates a token that gets written as is to the output. A token must be ASCII only and is not allowed +/// to contain any line breaks or tab characters. /// /// # Examples /// @@ -226,7 +222,7 @@ impl std::fmt::Debug for Line { /// use biome_formatter::prelude::*; /// /// # fn main() -> FormatResult<()> { -/// let elements = format!(SimpleFormatContext::default(), [text("Hello World")])?; +/// let elements = format!(SimpleFormatContext::default(), [token("Hello World")])?; /// /// assert_eq!( /// "Hello World", @@ -245,61 +241,65 @@ impl std::fmt::Debug for Line { /// /// # fn main() -> FormatResult<()> { /// // 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(), [text("\"Hello\\tWorld\"")])?; +/// let elements = format!(SimpleFormatContext::default(), [token("\"Hello\\tWorld\"")])?; /// /// assert_eq!(r#""Hello\tWorld""#, elements.print()?.as_code()); /// # Ok(()) /// # } /// ``` #[inline] -pub fn text(text: &'static str) -> StaticText { - debug_assert_no_newlines(text); +pub fn token(text: &'static str) -> Token { + debug_assert!(text.is_ascii(), "Token must be ASCII text only"); + debug_assert!( + !text.contains(['\n', '\r', '\t']), + "A token should not contain any newlines or tab characters" + ); - StaticText { text } + Token { text } } #[derive(Clone, Copy, Eq, PartialEq)] -pub struct StaticText { +pub struct Token { text: &'static str, } -impl Format for StaticText { +impl Format for Token { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::StaticText { text: self.text }) + f.write_element(FormatElement::Token { text: self.text }) } } -impl std::fmt::Debug for StaticText { +impl std::fmt::Debug for Token { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::write!(f, "StaticToken({})", self.text) + std::write!(f, "Token({})", self.text) } } /// Creates a text from a dynamic string and a range of the input source -pub fn dynamic_text(text: &str, position: TextSize) -> DynamicText<'_> { +pub fn text(text: &str, position: TextSize) -> Text<'_> { debug_assert_no_newlines(text); - DynamicText { text, position } + Text { text, position } } #[derive(Eq, PartialEq)] -pub struct DynamicText<'a> { +pub struct Text<'a> { text: &'a str, position: TextSize, } -impl Format for DynamicText<'_> { +impl Format for Text<'_> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::DynamicText { + f.write_element(FormatElement::Text { text: self.text.to_string().into_boxed_str(), source_position: self.position, }) } } -impl std::fmt::Debug for DynamicText<'_> { +impl std::fmt::Debug for Text<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::write!(f, "DynamicToken({})", self.text) + std::write!(f, "Text({})", self.text) } } @@ -340,7 +340,7 @@ impl Format for SyntaxTokenCowSlice<'_, L> { source_position: self.start, }) } - Cow::Owned(text) => f.write_element(FormatElement::DynamicText { + Cow::Owned(text) => f.write_element(FormatElement::Text { text: text.clone().into_boxed_str(), source_position: self.start, }), @@ -407,9 +407,9 @@ fn debug_assert_no_newlines(text: &str) { /// /// fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ -/// text("a"), -/// line_suffix(&text("c")), -/// text("b") +/// token("a"), +/// line_suffix(&token("c")), +/// token("b") /// ])?; /// /// assert_eq!( @@ -460,11 +460,11 @@ impl std::fmt::Debug for LineSuffix<'_, Context> { /// /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ -/// text("a"), -/// line_suffix(&text("c")), -/// text("b"), +/// token("a"), +/// line_suffix(&token("c")), +/// token("b"), /// line_suffix_boundary(), -/// text("d") +/// token("d") /// ])?; /// /// assert_eq!( @@ -524,7 +524,7 @@ impl Format for LineSuffixBoundary { /// write!(recording, [ /// labelled( /// LabelId::of(MyLabels::Main), -/// &text("'I have a label'") +/// &token("'I have a label'") /// ) /// ])?; /// @@ -533,9 +533,9 @@ impl Format for LineSuffixBoundary { /// let is_labelled = recorded.first().is_some_and(|element| element.has_label(LabelId::of(MyLabels::Main))); /// /// if is_labelled { -/// write!(f, [text(" has label `Main`")]) +/// write!(f, [token(" has label `Main`")]) /// } else { -/// write!(f, [text(" doesn't have label `Main`")]) +/// write!(f, [token(" doesn't have label `Main`")]) /// } /// })] /// )?; @@ -596,7 +596,7 @@ impl std::fmt::Debug for FormatLabelled<'_, Context> { /// /// # fn main() -> FormatResult<()> { /// // 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(), [text("a"), space(), text("b")])?; +/// let elements = format!(SimpleFormatContext::default(), [token("a"), space(), token("b")])?; /// /// assert_eq!("a b", elements.print()?.as_code()); /// # Ok(()) @@ -625,9 +625,9 @@ pub const fn space() -> Space { /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("nineteen_characters"), +/// token("nineteen_characters"), /// soft_line_break(), -/// text("1"), +/// token("1"), /// hard_space(), /// ]) /// ])?; @@ -654,9 +654,9 @@ pub const fn space() -> Space { /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("nineteen_characters"), +/// token("nineteen_characters"), /// soft_line_break(), -/// text("1"), +/// token("1"), /// space(), /// ]) /// ])?; @@ -681,8 +681,8 @@ pub const fn hard_space() -> HardSpace { /// use biome_formatter::prelude::*; /// /// # fn main() -> FormatResult<()> { -/// let elements = format!(SimpleFormatContext::default(), [text("a"), maybe_space(true), text("b")])?; -/// let nospace = format!(SimpleFormatContext::default(), [text("a"), maybe_space(false), text("b")])?; +/// let elements = format!(SimpleFormatContext::default(), [token("a"), maybe_space(true), token("b")])?; +/// let nospace = format!(SimpleFormatContext::default(), [token("a"), maybe_space(false), token("b")])?; /// /// assert_eq!("a b", elements.print()?.as_code()); /// assert_eq!("ab", nospace.print()?.as_code()); @@ -727,16 +727,16 @@ impl Format for HardSpace { /// /// # fn main() -> FormatResult<()> { /// let block = format!(SimpleFormatContext::default(), [ -/// text("switch {"), +/// token("switch {"), /// block_indent(&format_args![ -/// text("default:"), +/// token("default:"), /// indent(&format_args![ /// // this is where we want to use a /// hard_line_break(), -/// text("break;"), +/// token("break;"), /// ]) /// ]), -/// text("}"), +/// token("}"), /// ])?; /// /// assert_eq!( @@ -756,12 +756,12 @@ impl Format for HardSpace { /// let block = format!( /// SimpleFormatContext::default(), /// [ -/// text("root"), +/// token("root"), /// indent(&format_args![align( /// 2, /// &format_args![indent(&format_args![ /// hard_line_break(), -/// text("should be 3 tabs"), +/// token("should be 3 tabs"), /// ])] /// )]) /// ] @@ -817,22 +817,22 @@ impl std::fmt::Debug for Indent<'_, Context> { /// /// # fn main() -> FormatResult<()> { /// let block = format!(SimpleFormatContext::default(), [ -/// text("root"), +/// token("root"), /// align(2, &format_args![ /// hard_line_break(), -/// text("aligned"), +/// token("aligned"), /// dedent(&format_args![ /// hard_line_break(), -/// text("not aligned"), +/// token("not aligned"), /// ]), /// dedent(&indent(&format_args![ /// hard_line_break(), -/// text("Indented, not aligned") +/// token("Indented, not aligned") /// ])) /// ]), /// dedent(&format_args![ /// hard_line_break(), -/// text("Dedent on root level is a no-op.") +/// token("Dedent on root level is a no-op.") /// ]) /// ])?; /// @@ -857,18 +857,18 @@ impl std::fmt::Debug for Indent<'_, Context> { /// let elements = format!( /// context, /// [ -/// text("root"), +/// token("root"), /// indent(&format_args![ /// hard_line_break(), -/// text("Indented"), +/// token("Indented"), /// align( /// 2, /// &format_args![ /// hard_line_break(), -/// text("Indented and aligned"), +/// token("Indented and aligned"), /// dedent(&format_args![ /// hard_line_break(), -/// text("Indented, not aligned"), +/// token("Indented, not aligned"), /// ]), /// ] /// ), @@ -877,18 +877,18 @@ impl std::fmt::Debug for Indent<'_, Context> { /// 2, /// &format_args![ /// hard_line_break(), -/// text("Aligned"), +/// token("Aligned"), /// indent(&format_args![ /// hard_line_break(), -/// text("Aligned, and indented"), +/// token("Aligned, and indented"), /// dedent(&format_args![ /// hard_line_break(), -/// text("aligned, not Intended"), +/// token("aligned, not Intended"), /// ]), /// ]) /// ] /// ), -/// dedent(&format_args![hard_line_break(), text("root level")]) +/// dedent(&format_args![hard_line_break(), token("root level")]) /// ] /// )?; /// assert_eq!( @@ -907,17 +907,17 @@ impl std::fmt::Debug for Indent<'_, Context> { /// let block = format!( /// SimpleFormatContext::default(), /// [ -/// text("root"), +/// token("root"), /// indent(&format_args![align( /// 2, /// &format_args![align( /// 2, /// &format_args![indent(&format_args![ /// hard_line_break(), -/// text("should be 4 tabs"), +/// token("should be 4 tabs"), /// dedent(&format_args![ /// hard_line_break(), -/// text("should be 1 tab and 4 spaces"), +/// token("should be 1 tab and 4 spaces"), /// ]), /// ])] /// ),] @@ -972,23 +972,23 @@ impl std::fmt::Debug for Dedent<'_, Context> { /// /// # fn main() -> FormatResult<()> { /// let block = format!(SimpleFormatContext::default(), [ -/// text("root"), +/// token("root"), /// indent(&format_args![ /// hard_line_break(), -/// text("indent level 1"), +/// token("indent level 1"), /// indent(&format_args![ /// hard_line_break(), -/// text("indent level 2"), +/// token("indent level 2"), /// align(2, &format_args![ /// hard_line_break(), -/// text("two space align"), +/// token("two space align"), /// dedent_to_root(&format_args![ /// hard_line_break(), -/// text("starts at the beginning of the line") +/// token("starts at the beginning of the line") /// ]), /// ]), /// hard_line_break(), -/// text("end indent level 2"), +/// token("end indent level 2"), /// ]) /// ]), /// ])?; @@ -1034,24 +1034,24 @@ where /// /// # fn main() -> FormatResult<()> { /// let block = format!(SimpleFormatContext::default(), [ -/// text("a"), +/// token("a"), /// hard_line_break(), -/// text("?"), +/// token("?"), /// space(), /// align(2, &format_args![ -/// text("function () {"), +/// token("function () {"), /// hard_line_break(), -/// text("}"), +/// token("}"), /// ]), /// hard_line_break(), -/// text(":"), +/// token(":"), /// space(), /// align(2, &format_args![ -/// text("function () {"), -/// block_indent(&text("console.log('test');")), -/// text("}"), +/// token("function () {"), +/// block_indent(&token("console.log('test');")), +/// token("}"), /// ]), -/// text(";") +/// token(";") /// ])?; /// /// assert_eq!( @@ -1085,24 +1085,24 @@ where /// }); /// /// let block = format!(context, [ -/// text("a"), +/// token("a"), /// hard_line_break(), -/// text("?"), +/// token("?"), /// space(), /// align(2, &format_args![ -/// text("function () {"), +/// token("function () {"), /// hard_line_break(), -/// text("}"), +/// token("}"), /// ]), /// hard_line_break(), -/// text(":"), +/// token(":"), /// space(), /// align(2, &format_args![ -/// text("function () {"), -/// block_indent(&text("console.log('test');")), -/// text("}"), +/// token("function () {"), +/// block_indent(&token("console.log('test');")), +/// token("}"), /// ]), -/// text(";") +/// token(";") /// ])?; /// /// assert_eq!( @@ -1168,13 +1168,13 @@ impl std::fmt::Debug for Align<'_, Context> { /// let block = format![ /// SimpleFormatContext::default(), /// [ -/// text("{"), +/// token("{"), /// block_indent(&format_args![ -/// text("let a = 10;"), +/// token("let a = 10;"), /// hard_line_break(), -/// text("let c = a + 5;"), +/// token("let c = a + 5;"), /// ]), -/// text("}"), +/// token("}"), /// ] /// ]?; /// @@ -1213,13 +1213,13 @@ pub fn block_indent(content: &impl Format) -> BlockIndent<'_, /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("'First string',"), +/// token("'First string',"), /// soft_line_break_or_space(), -/// text("'second string',"), +/// token("'second string',"), /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1239,13 +1239,13 @@ pub fn block_indent(content: &impl Format) -> BlockIndent<'_, /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("5,"), +/// token("5,"), /// soft_line_break_or_space(), -/// text("10"), +/// token("10"), /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1284,14 +1284,14 @@ pub fn soft_block_indent(content: &impl Format) -> BlockIndent /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("{"), +/// token("{"), /// soft_block_indent_with_maybe_space(&format_args![ -/// text("aPropertyThatExceeds"), -/// text(":"), +/// token("aPropertyThatExceeds"), +/// token(":"), /// space(), -/// text("'line width'"), +/// token("'line width'"), /// ], false), -/// text("}") +/// token("}") /// ]) /// ])?; /// @@ -1312,14 +1312,14 @@ pub fn soft_block_indent(content: &impl Format) -> BlockIndent /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("{"), +/// token("{"), /// soft_block_indent_with_maybe_space(&format_args![ -/// text("a"), -/// text(":"), +/// token("a"), +/// token(":"), /// space(), -/// text("5"), +/// token("5"), /// ], true), -/// text("}") +/// token("}") /// ]) /// ])?; /// @@ -1339,14 +1339,14 @@ pub fn soft_block_indent(content: &impl Format) -> BlockIndent /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("{"), +/// token("{"), /// soft_block_indent_with_maybe_space(&format_args![ -/// text("a"), -/// text(":"), +/// token("a"), +/// token(":"), /// space(), -/// text("5"), +/// token("5"), /// ], false), -/// text("}") +/// token("}") /// ]) /// ])?; /// @@ -1391,15 +1391,15 @@ pub fn soft_block_indent_with_maybe_space( /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("name"), +/// token("name"), /// space(), -/// text("="), +/// token("="), /// soft_line_indent_or_space(&format_args![ -/// text("firstName"), +/// token("firstName"), /// space(), -/// text("+"), +/// token("+"), /// space(), -/// text("lastName"), +/// token("lastName"), /// ]), /// ]) /// ])?; @@ -1420,10 +1420,10 @@ pub fn soft_block_indent_with_maybe_space( /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("a"), +/// token("a"), /// space(), -/// text("="), -/// soft_line_indent_or_space(&text("10")), +/// token("="), +/// soft_line_indent_or_space(&token("10")), /// ]) /// ])?; /// @@ -1463,15 +1463,15 @@ pub fn soft_line_indent_or_space( /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("name"), +/// token("name"), /// space(), -/// text("="), +/// token("="), /// soft_line_indent_or_hard_space(&format_args![ -/// text("firstName"), +/// token("firstName"), /// space(), -/// text("+"), +/// token("+"), /// space(), -/// text("lastName"), +/// token("lastName"), /// ]), /// ]) /// ])?; @@ -1492,10 +1492,10 @@ pub fn soft_line_indent_or_space( /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("a"), +/// token("a"), /// space(), -/// text("="), -/// soft_line_indent_or_hard_space(&text("10")), +/// token("="), +/// soft_line_indent_or_hard_space(&token("10")), /// ]) /// ])?; /// @@ -1520,11 +1520,11 @@ pub fn soft_line_indent_or_space( /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("value"), +/// token("value"), /// soft_line_break_or_space(), -/// text("="), +/// token("="), /// soft_line_indent_or_hard_space(&format_args![ -/// text("10"), +/// token("10"), /// ]), /// ]) /// ])?; @@ -1630,14 +1630,14 @@ impl std::fmt::Debug for BlockIndent<'_, Context> { /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("{"), +/// token("{"), /// soft_space_or_block_indent(&format_args![ -/// text("aPropertyThatExceeds"), -/// text(":"), +/// token("aPropertyThatExceeds"), +/// token(":"), /// space(), -/// text("'line width'"), +/// token("'line width'"), /// ]), -/// text("}") +/// token("}") /// ]) /// ])?; /// @@ -1657,14 +1657,14 @@ impl std::fmt::Debug for BlockIndent<'_, Context> { /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("{"), +/// token("{"), /// soft_space_or_block_indent(&format_args![ -/// text("a"), -/// text(":"), +/// token("a"), +/// token(":"), /// space(), -/// text("5"), +/// token("5"), /// ]), -/// text("}") +/// token("}") /// ]) /// ])?; /// @@ -1704,15 +1704,15 @@ pub fn soft_space_or_block_indent( /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), +/// token("3"), /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1737,15 +1737,15 @@ pub fn soft_space_or_block_indent( /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("'Good morning! How are you today?',"), +/// token("'Good morning! How are you today?',"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), +/// token("3"), /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1830,16 +1830,16 @@ impl std::fmt::Debug for Group<'_, Context> { /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("'Good morning! How are you today?',"), +/// token("'Good morning! How are you today?',"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// expand_parent(), // Forces the parent to expand /// soft_line_break_or_space(), -/// text("3"), +/// token("3"), /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1884,16 +1884,16 @@ impl Format for ExpandParent { /// # fn main() -> FormatResult<()> { /// let elements = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), -/// if_group_breaks(&text(",")) +/// token("3"), +/// if_group_breaks(&token(",")) /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1919,16 +1919,16 @@ impl Format for ExpandParent { /// /// let elements = format!(context, [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("'A somewhat longer string to force a line break',"), +/// token("'A somewhat longer string to force a line break',"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), -/// if_group_breaks(&text(",")) +/// token("3"), +/// if_group_breaks(&token(",")) /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -1966,16 +1966,16 @@ where /// # fn main() -> FormatResult<()> { /// let formatted = format!(SimpleFormatContext::default(), [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), -/// if_group_fits_on_line(&text(",")) +/// token("3"), +/// if_group_fits_on_line(&token(",")) /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -2000,16 +2000,16 @@ where /// /// let formatted = format!(context, [ /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("'A somewhat longer string to force a line break',"), +/// token("'A somewhat longer string to force a line break',"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), -/// if_group_fits_on_line(&text(",")) +/// token("3"), +/// if_group_fits_on_line(&token(",")) /// ]), -/// text("]"), +/// token("]"), /// ]) /// ])?; /// @@ -2066,21 +2066,21 @@ impl IfGroupBreaks<'_, Context> { /// write!(f, [ /// group( /// &format_args![ - /// text("["), + /// token("["), /// soft_block_indent(&format_with(|f| { /// f.fill() - /// .entry(&soft_line_break_or_space(), &text("1,")) - /// .entry(&soft_line_break_or_space(), &text("234568789,")) - /// .entry(&soft_line_break_or_space(), &text("3456789,")) + /// .entry(&soft_line_break_or_space(), &token("1,")) + /// .entry(&soft_line_break_or_space(), &token("234568789,")) + /// .entry(&soft_line_break_or_space(), &token("3456789,")) /// .entry(&soft_line_break_or_space(), &format_args!( - /// text("["), - /// soft_block_indent(&text("4")), - /// text("]"), - /// if_group_breaks(&text(",")).with_group_id(Some(group_id)) + /// token("["), + /// soft_block_indent(&token("4")), + /// token("]"), + /// if_group_breaks(&token(",")).with_group_id(Some(group_id)) /// )) /// .finish() /// })), - /// text("]") + /// token("]") /// ], /// ).with_group_id(Some(group_id)) /// ]) @@ -2134,9 +2134,9 @@ impl std::fmt::Debug for IfGroupBreaks<'_, Context> { /// let id = f.group_id("head"); /// /// write!(f, [ -/// group(&text("Head")).with_group_id(Some(id)), -/// if_group_breaks(&indent(&text("indented"))).with_group_id(Some(id)), -/// if_group_fits_on_line(&text("indented")).with_group_id(Some(id)) +/// group(&token("Head")).with_group_id(Some(id)), +/// if_group_breaks(&indent(&token("indented"))).with_group_id(Some(id)), +/// if_group_fits_on_line(&token("indented")).with_group_id(Some(id)) /// ]) /// /// # }); @@ -2159,8 +2159,8 @@ impl std::fmt::Debug for IfGroupBreaks<'_, Context> { /// let group_id = f.group_id("header"); /// /// write!(f, [ -/// group(&text("(aLongHeaderThatBreaksForSomeReason) =>")).with_group_id(Some(group_id)), -/// indent_if_group_breaks(&format_args![hard_line_break(), text("a => b")], group_id) +/// group(&token("(aLongHeaderThatBreaksForSomeReason) =>")).with_group_id(Some(group_id)), +/// indent_if_group_breaks(&format_args![hard_line_break(), token("a => b")], group_id) /// ]) /// }); /// @@ -2189,8 +2189,8 @@ impl std::fmt::Debug for IfGroupBreaks<'_, Context> { /// let group_id = f.group_id("header"); /// /// write!(f, [ -/// group(&text("(aLongHeaderThatBreaksForSomeReason) =>")).with_group_id(Some(group_id)), -/// indent_if_group_breaks(&format_args![hard_line_break(), text("a => b")], group_id) +/// group(&token("(aLongHeaderThatBreaksForSomeReason) =>")).with_group_id(Some(group_id)), +/// indent_if_group_breaks(&format_args![hard_line_break(), token("a => b")], group_id) /// ]) /// }); /// @@ -2279,17 +2279,17 @@ impl std::fmt::Debug for FormatWith { /// impl Format for MyFormat { /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [ -/// text("("), +/// token("("), /// block_indent(&format_with(|f| { /// let separator = space(); /// let mut join = f.join_with(&separator); /// /// for item in &self.items { -/// join.entry(&format_with(|f| write!(f, [dynamic_text(item, TextSize::default())]))); +/// join.entry(&format_with(|f| write!(f, [text(item, TextSize::default())]))); /// } /// join.finish() /// })), -/// text(")") +/// token(")") /// ]) /// } /// } @@ -2330,8 +2330,8 @@ where /// /// struct MyFormat; /// -/// fn generate_values() -> impl Iterator { -/// vec![text("1"), text("2"), text("3"), text("4")].into_iter() +/// fn generate_values() -> impl Iterator { +/// vec![token("1"), token("2"), token("3"), token("4")].into_iter() /// } /// /// impl Format for MyFormat { diff --git a/crates/biome_formatter/src/format_element.rs b/crates/biome_formatter/src/format_element.rs index 77c7649f4339..34a4b07b40a1 100644 --- a/crates/biome_formatter/src/format_element.rs +++ b/crates/biome_formatter/src/format_element.rs @@ -26,17 +26,16 @@ pub enum FormatElement { /// Forces the parent group to print in expanded mode. ExpandParent, - /// Token constructed by the formatter from a static string - StaticText { + /// A ASCII only Token that contains no line breaks or tab characters. + Token { text: &'static str, }, - /// Token constructed from the input source as a dynamic - /// string with its start position in the input document. - DynamicText { + /// An arbitrary text that can contain tabs, newlines, and unicode characters. + Text { /// There's no need for the text to be mutable, using `Box` safes 8 bytes over `String`. text: Box, - /// The start position of the dynamic token in the unformatted source code + /// The start position of the text in the unformatted source code source_position: TextSize, }, @@ -71,8 +70,8 @@ impl std::fmt::Debug for FormatElement { Self::Space | Self::HardSpace => write!(fmt, "Space"), Self::Line(mode) => fmt.debug_tuple("Line").field(mode).finish(), Self::ExpandParent => write!(fmt, "ExpandParent"), - Self::StaticText { text } => fmt.debug_tuple("StaticText").field(text).finish(), - Self::DynamicText { text, .. } => fmt.debug_tuple("DynamicText").field(text).finish(), + Self::Token { text } => fmt.debug_tuple("Token").field(text).finish(), + Self::Text { text, .. } => fmt.debug_tuple("Text").field(text).finish(), Self::LocatedTokenText { slice, .. } => { fmt.debug_tuple("LocatedTokenText").field(slice).finish() } @@ -219,7 +218,7 @@ impl FormatElement { pub const fn is_text(&self) -> bool { matches!( self, - Self::LocatedTokenText { .. } | Self::DynamicText { .. } | Self::StaticText { .. } + Self::LocatedTokenText { .. } | Self::Text { .. } | Self::Token { .. } ) } @@ -238,14 +237,18 @@ impl FormatElements for FormatElement { Self::ExpandParent => true, Self::Tag(Tag::StartGroup(group)) => !group.mode().is_flat(), Self::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty), - Self::StaticText { text } => text.contains('\n'), - Self::DynamicText { text, .. } => text.contains('\n'), + + Self::Text { text, .. } => text.contains('\n'), Self::LocatedTokenText { slice, .. } => slice.contains('\n'), Self::Interned(interned) => interned.will_break(), // Traverse into the most flat version because the content is guaranteed to expand when even // the most flat version contains some content that forces a break. Self::BestFitting(best_fitting) => best_fitting.most_flat().will_break(), - Self::LineSuffixBoundary | Self::Space | Self::Tag(_) | Self::HardSpace => false, + Self::LineSuffixBoundary + | Self::Space + | Self::Tag(_) + | Self::HardSpace + | Self::Token { .. } => false, } } diff --git a/crates/biome_formatter/src/format_element/document.rs b/crates/biome_formatter/src/format_element/document.rs index 8dab30b11bfa..82b6f7b1af0e 100644 --- a/crates/biome_formatter/src/format_element/document.rs +++ b/crates/biome_formatter/src/format_element/document.rs @@ -116,11 +116,11 @@ impl Document { // propagate their expansion. false } - FormatElement::StaticText { text } => text.contains('\n'), - FormatElement::DynamicText { text, .. } => text.contains('\n'), + FormatElement::Text { text, .. } => text.contains('\n'), FormatElement::LocatedTokenText { slice, .. } => slice.contains('\n'), FormatElement::ExpandParent | FormatElement::Line(LineMode::Hard | LineMode::Empty) => true, + FormatElement::Token { .. } => false, _ => false, }; @@ -285,7 +285,7 @@ impl Format for &[FormatElement] { while let Some(element) = iter.next() { if !first_element && !in_text && !element.is_end_tag() { // Write a separator between every two elements - write!(f, [text(","), soft_line_break_or_space()])?; + write!(f, [token(","), soft_line_break_or_space()])?; } first_element = false; @@ -293,30 +293,30 @@ impl Format for &[FormatElement] { match element { element @ (FormatElement::Space | FormatElement::HardSpace - | FormatElement::StaticText { .. } - | FormatElement::DynamicText { .. } + | FormatElement::Token { .. } + | FormatElement::Text { .. } | FormatElement::LocatedTokenText { .. }) => { if !in_text { - write!(f, [text("\"")])?; + write!(f, [token("\"")])?; } in_text = true; match element { FormatElement::Space | FormatElement::HardSpace => { - write!(f, [text(" ")])?; + write!(f, [token(" ")])?; } element if element.is_text() => { // escape quotes let new_element = match element { - // except for static text because source_position is unknown - FormatElement::StaticText { .. } => element.clone(), - FormatElement::DynamicText { + // except for token because source_position is unknown + FormatElement::Token { .. } => element.clone(), + FormatElement::Text { text, source_position, } => { let text = text.to_string().replace('"', "\\\""); - FormatElement::DynamicText { + FormatElement::Text { text: text.into(), source_position: *source_position, } @@ -326,7 +326,7 @@ impl Format for &[FormatElement] { source_position, } => { let text = slice.to_string().replace('"', "\\\""); - FormatElement::DynamicText { + FormatElement::Text { text: text.into(), source_position: *source_position, } @@ -341,35 +341,35 @@ impl Format for &[FormatElement] { let is_next_text = iter.peek().is_some_and(|e| e.is_text() || e.is_space()); if !is_next_text { - write!(f, [text("\"")])?; + write!(f, [token("\"")])?; in_text = false; } } FormatElement::Line(mode) => match mode { LineMode::SoftOrSpace => { - write!(f, [text("soft_line_break_or_space")])?; + write!(f, [token("soft_line_break_or_space")])?; } LineMode::Soft => { - write!(f, [text("soft_line_break")])?; + write!(f, [token("soft_line_break")])?; } LineMode::Hard => { - write!(f, [text("hard_line_break")])?; + write!(f, [token("hard_line_break")])?; } LineMode::Empty => { - write!(f, [text("empty_line")])?; + write!(f, [token("empty_line")])?; } }, FormatElement::ExpandParent => { - write!(f, [text("expand_parent")])?; + write!(f, [token("expand_parent")])?; } FormatElement::LineSuffixBoundary => { - write!(f, [text("line_suffix_boundary")])?; + write!(f, [token("line_suffix_boundary")])?; } FormatElement::BestFitting(best_fitting) => { - write!(f, [text("best_fitting([")])?; + write!(f, [token("best_fitting([")])?; f.write_elements([ FormatElement::Tag(StartIndent), FormatElement::Line(LineMode::Hard), @@ -384,7 +384,7 @@ impl Format for &[FormatElement] { FormatElement::Line(LineMode::Hard), ])?; - write!(f, [text("])")])?; + write!(f, [token("])")])?; } FormatElement::Interned(interned) => { @@ -398,10 +398,7 @@ impl Format for &[FormatElement] { write!( f, [ - dynamic_text( - &std::format!(""), - TextSize::default() - ), + text(&std::format!(""), TextSize::default()), space(), &interned.deref(), ] @@ -410,7 +407,7 @@ impl Format for &[FormatElement] { Some(reference) => { write!( f, - [dynamic_text( + [text( &std::format!(""), TextSize::default() )] @@ -432,12 +429,12 @@ impl Format for &[FormatElement] { write!( f, [ - text(">"), + token(">>"), ] )?; first_element = false; @@ -448,19 +445,16 @@ impl Format for &[FormatElement] { f, [ ContentArrayEnd, - text(")"), + token(")"), soft_line_break_or_space(), - text("ERROR>") + token(">>") ] )?; first_element = false; @@ -474,7 +468,7 @@ impl Format for &[FormatElement] { match tag { StartIndent => { - write!(f, [text("indent(")])?; + write!(f, [token("indent(")])?; } StartDedent(mode) => { @@ -483,41 +477,41 @@ impl Format for &[FormatElement] { DedentMode::Root => "dedentRoot", }; - write!(f, [text(label), text("(")])?; + write!(f, [token(label), token("(")])?; } StartAlign(tag::Align(count)) => { write!( f, [ - text("align("), - dynamic_text(&count.to_string(), TextSize::default()), - text(","), + token("align("), + text(&count.to_string(), TextSize::default()), + token(","), space(), ] )?; } StartLineSuffix => { - write!(f, [text("line_suffix(")])?; + write!(f, [token("line_suffix(")])?; } StartVerbatim(_) => { - write!(f, [text("verbatim(")])?; + write!(f, [token("verbatim(")])?; } StartGroup(group) => { - write!(f, [text("group(")])?; + write!(f, [token("group(")])?; if let Some(group_id) = group.id() { write!( f, [ - dynamic_text( + text( &std::format!("\"{group_id:?}\""), TextSize::default() ), - text(","), + token(","), space(), ] )?; @@ -526,10 +520,10 @@ impl Format for &[FormatElement] { match group.mode() { GroupMode::Flat => {} GroupMode::Expand => { - write!(f, [text("expand: true,"), space()])?; + write!(f, [token("expand: true,"), space()])?; } GroupMode::Propagated => { - write!(f, [text("expand: propagated,"), space()])?; + write!(f, [token("expand: propagated,"), space()])?; } } } @@ -538,9 +532,9 @@ impl Format for &[FormatElement] { write!( f, [ - text("indent_if_group_breaks("), - dynamic_text(&std::format!("\"{id:?}\""), TextSize::default()), - text(","), + token("indent_if_group_breaks("), + text(&std::format!("\"{id:?}\""), TextSize::default()), + token(","), space(), ] )?; @@ -549,10 +543,10 @@ impl Format for &[FormatElement] { StartConditionalContent(condition) => { match condition.mode { PrintMode::Flat => { - write!(f, [text("if_group_fits_on_line(")])?; + write!(f, [token("if_group_fits_on_line(")])?; } PrintMode::Expanded => { - write!(f, [text("if_group_breaks(")])?; + write!(f, [token("if_group_breaks(")])?; } } @@ -560,11 +554,11 @@ impl Format for &[FormatElement] { write!( f, [ - dynamic_text( + text( &std::format!("\"{group_id:?}\""), TextSize::default() ), - text(","), + token(","), space(), ] )?; @@ -575,23 +569,20 @@ impl Format for &[FormatElement] { write!( f, [ - text("label("), - dynamic_text( - &std::format!("\"{label_id:?}\""), - TextSize::default() - ), - text(","), + token("label("), + text(&std::format!("\"{label_id:?}\""), TextSize::default()), + token(","), space(), ] )?; } StartFill => { - write!(f, [text("fill(")])?; + write!(f, [token("fill(")])?; } StartEmbedded(_) => { - write!(f, [text("embedded(")])?; + write!(f, [token("embedded(")])?; } StartEntry => { // handled after the match for all start tags @@ -609,7 +600,7 @@ impl Format for &[FormatElement] { | EndDedent(_) | EndVerbatim | EndEmbedded => { - write!(f, [ContentArrayEnd, text(")")])?; + write!(f, [ContentArrayEnd, token(")")])?; } }; @@ -625,9 +616,9 @@ impl Format for &[FormatElement] { f, [ ContentArrayEnd, - text(")"), + token(")"), soft_line_break_or_space(), - dynamic_text( + text( &std::format!(">"), TextSize::default() ), @@ -645,7 +636,7 @@ impl Format for ContentArrayStart { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { use Tag::*; - write!(f, [text("[")])?; + write!(f, [token("[")])?; f.write_elements([ FormatElement::Tag(StartGroup(tag::Group::new())), @@ -666,7 +657,7 @@ impl Format for ContentArrayEnd { FormatElement::Tag(EndGroup), ])?; - write!(f, [text("]")]) + write!(f, [token("]")]) } } @@ -814,11 +805,11 @@ mod tests { write!( f, [group(&format_args![ - text("("), + token("("), soft_block_indent(&format_args![ - text("Some longer content"), + token("Some longer content"), space(), - text("That should ultimately break"), + token("That should ultimately break"), ]) ])] ) @@ -848,16 +839,16 @@ mod tests { use Tag::*; let document = Document::from(vec![ - FormatElement::StaticText { text: "[" }, + FormatElement::Token { text: "[" }, FormatElement::Tag(StartGroup(tag::Group::new())), FormatElement::Tag(StartIndent), FormatElement::Line(LineMode::Soft), - FormatElement::StaticText { text: "a" }, + FormatElement::Token { text: "a" }, // Close group instead of indent FormatElement::Tag(EndGroup), FormatElement::Line(LineMode::Soft), FormatElement::Tag(EndIndent), - FormatElement::StaticText { text: "]" }, + FormatElement::Token { text: "]" }, // End tag without start FormatElement::Tag(EndIndent), // Start tag without an end @@ -894,8 +885,8 @@ mod tests { // ] let interned = Interned::new(vec![FormatElement::ExpandParent, unsafe { FormatElement::BestFitting(BestFittingElement::from_vec_unchecked(vec![ - Box::new([FormatElement::StaticText { text: "a" }]), - Box::new([FormatElement::StaticText { text: "b" }]), + Box::new([FormatElement::Token { text: "a" }]), + Box::new([FormatElement::Token { text: "b" }]), ])) }]); @@ -939,7 +930,7 @@ mod tests { }; let mut document = Document::from(vec![ - FormatElement::DynamicText { + FormatElement::Text { text: "\"foo\"".into(), source_position: TextSize::default(), }, diff --git a/crates/biome_formatter/src/format_extensions.rs b/crates/biome_formatter/src/format_extensions.rs index dbcfaade30eb..b3d200f57cad 100644 --- a/crates/biome_formatter/src/format_extensions.rs +++ b/crates/biome_formatter/src/format_extensions.rs @@ -33,7 +33,7 @@ pub trait MemoizeFormat { /// let value = self.value.get(); /// self.value.set(value + 1); /// - /// write!(f, [dynamic_text(&std::format!("Formatted {value} times."), TextSize::from(0))]) + /// write!(f, [text(&std::format!("Formatted {value} times."), TextSize::from(0))]) /// } /// } /// @@ -110,9 +110,9 @@ where /// let current = self.value.get(); /// /// write!(f, [ - /// text("Count:"), + /// token("Count:"), /// space(), - /// dynamic_text(&std::format!("{current}"), TextSize::default()), + /// text(&std::format!("{current}"), TextSize::default()), /// hard_line_break() /// ])?; /// @@ -127,9 +127,9 @@ where /// let counter_content = counter.inspect(f)?; /// /// if counter_content.will_break() { - /// write!(f, [text("Counter:"), block_indent(&counter)]) + /// write!(f, [token("Counter:"), block_indent(&counter)]) /// } else { - /// write!(f, [text("Counter:"), counter]) + /// write!(f, [token("Counter:"), counter]) /// }?; /// /// write!(f, [counter]) diff --git a/crates/biome_formatter/src/formatter.rs b/crates/biome_formatter/src/formatter.rs index 5a3dd855336d..10d42e24cd27 100644 --- a/crates/biome_formatter/src/formatter.rs +++ b/crates/biome_formatter/src/formatter.rs @@ -55,11 +55,11 @@ impl<'buf, Context> Formatter<'buf, Context> { /// # fn main() -> FormatResult<()> { /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { /// f.join() - /// .entry(&text("a")) + /// .entry(&token("a")) /// .entry(&space()) - /// .entry(&text("+")) + /// .entry(&token("+")) /// .entry(&space()) - /// .entry(&text("b")) + /// .entry(&token("b")) /// .finish() /// })])?; /// @@ -86,11 +86,11 @@ impl<'buf, Context> Formatter<'buf, Context> { /// /// # fn main() -> FormatResult<()> { /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { - /// f.join_with(&format_args!(text(","), space())) - /// .entry(&text("1")) - /// .entry(&text("2")) - /// .entry(&text("3")) - /// .entry(&text("4")) + /// f.join_with(&format_args!(token(","), space())) + /// .entry(&token("1")) + /// .entry(&token("2")) + /// .entry(&token("3")) + /// .entry(&token("4")) /// .finish() /// })])?; /// @@ -159,10 +159,10 @@ impl<'buf, Context> Formatter<'buf, Context> { /// # fn main() -> FormatResult<()> { /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { /// f.fill() - /// .entry(&soft_line_break_or_space(), &text("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) - /// .entry(&soft_line_break_or_space(), &text("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) - /// .entry(&soft_line_break_or_space(), &text("cccccccccccccccccccccccccccccc")) - /// .entry(&soft_line_break_or_space(), &text("dddddddddddddddddddddddddddddd")) + /// .entry(&soft_line_break_or_space(), &token("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) + /// .entry(&soft_line_break_or_space(), &token("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) + /// .entry(&soft_line_break_or_space(), &token("cccccccccccccccccccccccccccccc")) + /// .entry(&soft_line_break_or_space(), &token("dddddddddddddddddddddddddddddd")) /// .finish() /// })])?; /// @@ -180,10 +180,10 @@ impl<'buf, Context> Formatter<'buf, Context> { /// /// # fn main() -> FormatResult<()> { /// let entries = vec![ - /// text("Important: "), - /// text("Please do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you "), - /// text("will"), - /// text(" be reprimanded") + /// token("Important: "), + /// token("Please do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you "), + /// token("will"), + /// token(" be reprimanded") /// ]; /// /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { diff --git a/crates/biome_formatter/src/lib.rs b/crates/biome_formatter/src/lib.rs index b7ce06717186..e9bb5df1315e 100644 --- a/crates/biome_formatter/src/lib.rs +++ b/crates/biome_formatter/src/lib.rs @@ -1147,7 +1147,7 @@ pub type FormatResult = Result; /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [ /// hard_line_break(), -/// dynamic_text(&self.0, TextSize::from(0)), +/// text(&self.0, TextSize::from(0)), /// hard_line_break(), /// ]) /// } @@ -1396,7 +1396,7 @@ where /// let mut state = FormatState::new(SimpleFormatContext::default()); /// let mut buffer = VecBuffer::new(&mut state); /// -/// write!(&mut buffer, [format_args!(text("Hello World"))])?; +/// write!(&mut buffer, [format_args!(token("Hello World"))])?; /// /// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default()); /// @@ -1415,7 +1415,7 @@ where /// let mut state = FormatState::new(SimpleFormatContext::default()); /// let mut buffer = VecBuffer::new(&mut state); /// -/// write!(&mut buffer, [text("Hello World")])?; +/// write!(&mut buffer, [token("Hello World")])?; /// /// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default()); /// @@ -1447,7 +1447,7 @@ pub fn write( /// use biome_formatter::{format, format_args}; /// /// # fn main() -> FormatResult<()> { -/// let formatted = format!(SimpleFormatContext::default(), [&format_args!(text("test"))])?; +/// let formatted = format!(SimpleFormatContext::default(), [&format_args!(token("test"))])?; /// assert_eq!("test", formatted.print()?.as_code()); /// # Ok(()) /// # } @@ -1460,7 +1460,7 @@ pub fn write( /// use biome_formatter::{format}; /// /// # fn main() -> FormatResult<()> { -/// let formatted = format!(SimpleFormatContext::default(), [text("test")])?; +/// let formatted = format!(SimpleFormatContext::default(), [token("test")])?; /// assert_eq!("test", formatted.print()?.as_code()); /// # Ok(()) /// # } diff --git a/crates/biome_formatter/src/macros.rs b/crates/biome_formatter/src/macros.rs index 1426784fa196..ed488fee8ee9 100644 --- a/crates/biome_formatter/src/macros.rs +++ b/crates/biome_formatter/src/macros.rs @@ -16,7 +16,7 @@ /// /// # fn main() -> FormatResult<()> { /// let formatted = format!(SimpleFormatContext::default(), [ -/// format_args!(text("Hello World")) +/// format_args!(token("Hello World")) /// ])?; /// /// assert_eq!("Hello World", formatted.print()?.as_code()); @@ -52,15 +52,15 @@ macro_rules! format_args { /// # fn main() -> FormatResult<()> { /// let mut state = FormatState::new(SimpleFormatContext::default()); /// let mut buffer = VecBuffer::new(&mut state); -/// write!(&mut buffer, [text("Hello"), space()])?; -/// write!(&mut buffer, [text("World")])?; +/// write!(&mut buffer, [token("Hello"), space()])?; +/// write!(&mut buffer, [token("World")])?; /// /// assert_eq!( /// buffer.into_vec(), /// vec![ -/// FormatElement::StaticText { text: "Hello" }, +/// FormatElement::Token { text: "Hello" }, /// FormatElement::Space, -/// FormatElement::StaticText { text: "World" }, +/// FormatElement::Token { text: "World" }, /// ] /// ); /// # Ok(()) @@ -86,10 +86,10 @@ macro_rules! write { /// let mut state = FormatState::new(SimpleFormatContext::default()); /// let mut buffer = VecBuffer::new(&mut state); /// -/// dbg_write!(buffer, [text("Hello")])?; -/// // ^-- prints: [src/main.rs:7][0] = StaticToken("Hello") +/// dbg_write!(buffer, [token("Hello")])?; +/// // ^-- prints: [src/main.rs:7][0] = Token("Hello") /// -/// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText { text: "Hello" }]); +/// assert_eq!(buffer.into_vec(), vec![FormatElement::Token { text: "Hello" }]); /// # Ok(()) /// # } /// ``` @@ -126,14 +126,14 @@ macro_rules! dbg_write { /// use biome_formatter::prelude::*; /// use biome_formatter::format; /// -/// let formatted = format!(SimpleFormatContext::default(), [text("("), text("a"), text(")")]).unwrap(); +/// let formatted = format!(SimpleFormatContext::default(), [token("("), token("a"), token(")")]).unwrap(); /// /// assert_eq!( /// formatted.into_document(), /// Document::from(vec![ -/// FormatElement::StaticText { text: "(" }, -/// FormatElement::StaticText { text: "a" }, -/// FormatElement::StaticText { text: ")" }, +/// FormatElement::Token { text: "(" }, +/// FormatElement::Token { text: "a" }, +/// FormatElement::Token { text: ")" }, /// ]) /// ); /// ``` @@ -160,49 +160,49 @@ macro_rules! format { /// let formatted = format!( /// SimpleFormatContext::default(), /// [ -/// text("aVeryLongIdentifier"), +/// token("aVeryLongIdentifier"), /// best_fitting!( /// // Everything fits on a single line /// format_args!( -/// text("("), +/// token("("), /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), +/// token("3"), /// ]), -/// text("]") +/// token("]") /// ]), -/// text(")") +/// token(")") /// ), /// /// // Breaks after `[`, but prints all elements on a single line /// format_args!( -/// text("("), -/// text("["), -/// block_indent(&text("1, 2, 3")), -/// text("]"), -/// text(")"), +/// token("("), +/// token("["), +/// block_indent(&token("1, 2, 3")), +/// token("]"), +/// token(")"), /// ), /// /// // Breaks after `[` and prints each element on a single line /// format_args!( -/// text("("), +/// token("("), /// block_indent(&format_args![ -/// text("["), +/// token("["), /// block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// hard_line_break(), -/// text("2,"), +/// token("2,"), /// hard_line_break(), -/// text("3"), +/// token("3"), /// ]), -/// text("]"), +/// token("]"), /// ]), -/// text(")") +/// token(")") /// ) /// ) /// ] @@ -251,38 +251,38 @@ macro_rules! format { /// best_fitting!( /// // Prints the method call on the line but breaks the array. /// format_args!( -/// text("expect(a).toMatch("), +/// token("expect(a).toMatch("), /// group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), +/// token("3"), /// ]), -/// text("]") +/// token("]") /// ]).should_expand(true), -/// text(")") +/// token(")") /// ), /// /// // Breaks after `(` /// format_args!( -/// text("expect(a).toMatch("), +/// token("expect(a).toMatch("), /// group(&soft_block_indent( /// &group(&format_args![ -/// text("["), +/// token("["), /// soft_block_indent(&format_args![ -/// text("1,"), +/// token("1,"), /// soft_line_break_or_space(), -/// text("2,"), +/// token("2,"), /// soft_line_break_or_space(), -/// text("3"), +/// token("3"), /// ]), -/// text("]") +/// token("]") /// ]).should_expand(true), /// )).should_expand(true), -/// text(")") +/// token(")") /// ), /// ) /// ] @@ -337,12 +337,13 @@ macro_rules! best_fitting { mod tests { use crate::prelude::*; use crate::{FormatState, SimpleFormatOptions, VecBuffer, write}; + use biome_rowan::TextSize; struct TestFormat; impl Format<()> for TestFormat { fn fmt(&self, f: &mut Formatter<()>) -> FormatResult<()> { - write!(f, [text("test")]) + write!(f, [token("test")]) } } @@ -355,7 +356,7 @@ mod tests { assert_eq!( buffer.into_vec(), - vec![FormatElement::StaticText { text: "test" }] + vec![FormatElement::Token { text: "test" }] ); } @@ -366,18 +367,18 @@ mod tests { write![ &mut buffer, - [text("a"), space(), text("simple"), space(), TestFormat] + [token("a"), space(), token("simple"), space(), TestFormat] ] .unwrap(); assert_eq!( buffer.into_vec(), vec![ - FormatElement::StaticText { text: "a" }, + FormatElement::Token { text: "a" }, FormatElement::Space, - FormatElement::StaticText { text: "simple" }, + FormatElement::Token { text: "simple" }, FormatElement::Space, - FormatElement::StaticText { text: "test" } + FormatElement::Token { text: "test" } ] ); } @@ -391,43 +392,44 @@ mod tests { let formatted_best_fitting = format!( SimpleFormatContext::default(), [ - text("aVeryLongIdentifier"), + token("aVeryLongIdentifier"), soft_line_break_or_space(), best_fitting![ format_args![text( - "Something that will not fit on a line with 30 character print width." + "Something that will not fit on a line with 30 character print width.", + TextSize::default() )], format_args![ group(&format_args![ - text("Start"), + token("Start"), soft_line_break(), group(&soft_block_indent(&format_args![ - text("1,"), + token("1,"), soft_line_break_or_space(), - text("2,"), + token("2,"), soft_line_break_or_space(), - text("3"), + token("3"), ])), soft_line_break_or_space(), soft_block_indent(&format_args![ - text("1,"), + token("1,"), soft_line_break_or_space(), - text("2,"), + token("2,"), soft_line_break_or_space(), group(&format_args!( - text("A,"), + token("A,"), soft_line_break_or_space(), - text("B") + token("B") )), soft_line_break_or_space(), - text("3") + token("3") ]), soft_line_break_or_space(), - text("End") + token("End") ]) .should_expand(true) ], - format_args!(text("Most"), hard_line_break(), text("Expanded")) + format_args!(token("Most"), hard_line_break(), token("Expanded")) ] ] ) @@ -438,34 +440,34 @@ mod tests { let formatted_normal_list = format!( SimpleFormatContext::default(), [ - text("aVeryLongIdentifier"), + token("aVeryLongIdentifier"), soft_line_break_or_space(), format_args![ - text("Start"), + token("Start"), soft_line_break(), &group(&soft_block_indent(&format_args![ - text("1,"), + token("1,"), soft_line_break_or_space(), - text("2,"), + token("2,"), soft_line_break_or_space(), - text("3"), + token("3"), ])), soft_line_break_or_space(), &soft_block_indent(&format_args![ - text("1,"), + token("1,"), soft_line_break_or_space(), - text("2,"), + token("2,"), soft_line_break_or_space(), group(&format_args!( - text("A,"), + token("A,"), soft_line_break_or_space(), - text("B") + token("B") )), soft_line_break_or_space(), - text("3") + token("3") ]), soft_line_break_or_space(), - text("End") + token("End") ], ] ) diff --git a/crates/biome_formatter/src/printer/mod.rs b/crates/biome_formatter/src/printer/mod.rs index 1d758271c062..cf1edae4bb56 100644 --- a/crates/biome_formatter/src/printer/mod.rs +++ b/crates/biome_formatter/src/printer/mod.rs @@ -96,15 +96,15 @@ impl<'a> Printer<'a> { } } - FormatElement::StaticText { text } => self.print_text(text, None), - FormatElement::DynamicText { + FormatElement::Token { text } => self.print_text(Text::Token(text), None), + FormatElement::Text { text, source_position, - } => self.print_text(text, Some(*source_position)), + } => self.print_text(Text::Text(text), Some(*source_position)), FormatElement::LocatedTokenText { slice, source_position, - } => self.print_text(slice, Some(*source_position)), + } => self.print_text(Text::Text(slice), Some(*source_position)), FormatElement::Line(line_mode) => { if args.mode().is_flat() { @@ -128,12 +128,12 @@ impl<'a> Printer<'a> { // Only print a newline if the current line isn't already empty if self.state.line_width > 0 { - self.print_str("\n"); + self.print_char('\n'); } // Print a second line break if this is an empty line if line_mode == &LineMode::Empty && !self.state.has_empty_line { - self.print_str("\n"); + self.print_char('\n'); self.state.has_empty_line = true; } @@ -314,7 +314,7 @@ impl<'a> Printer<'a> { result } - fn print_text(&mut self, text: &str, source_position: Option) { + fn print_text(&mut self, text: Text, source_position: Option) { if !self.state.pending_indent.is_empty() { let (indent_char, repeat_count) = match self.options.indent_style() { IndentStyle::Tab => ('\t', 1), @@ -339,7 +339,9 @@ impl<'a> Printer<'a> { // Print pending spaces if self.state.pending_space { - self.print_str(" "); + self.state.buffer.push(' '); + self.state.line_width += 1; + self.state.has_empty_line = false; self.state.pending_space = false; } @@ -361,10 +363,28 @@ impl<'a> Printer<'a> { dest: self.state.buffer.text_len(), }); - self.print_str(text); + match text { + Text::Token(token) => { + self.state.buffer.push_str(token); + self.state.line_width += token.len(); + // Tokens are never newlines, so always reset has_empty_line + if !token.is_empty() { + self.state.has_empty_line = false; + } + } + Text::Text(text_str) => { + for char in text_str.chars() { + self.print_char(char); + } + } + } if source_position.is_some() { - self.state.source_position += text.text_len(); + let text_str = match text { + Text::Token(s) => s, + Text::Text(s) => s, + }; + self.state.source_position += text_str.text_len(); } self.push_marker(SourceMarker { @@ -702,22 +722,12 @@ impl<'a> Printer<'a> { invalid_end_tag(TagKind::Entry, stack.top_kind()) } - fn print_str(&mut self, content: &str) { - for char in content.chars() { - self.print_char(char); - - self.state.has_empty_line = false; - } - } - fn print_char(&mut self, char: char) { if char == '\n' { self.state .buffer .push_str(self.options.line_ending.as_str()); - self.state.generated_line += 1; - self.state.generated_column = 0; self.state.line_width = 0; // Fit's only tests if groups up to the first line break fit. @@ -725,7 +735,6 @@ impl<'a> Printer<'a> { self.state.measured_group_fits = false; } else { self.state.buffer.push(char); - self.state.generated_column += 1; let char_width = if char == '\t' { self.options.indent_width().value() as usize @@ -734,10 +743,19 @@ impl<'a> Printer<'a> { }; self.state.line_width += char_width; + self.state.has_empty_line = false; } } } +#[derive(Copy, Clone, Debug)] +enum Text<'a> { + /// ASCII only text that contains no line breaks or tab characters. + Token(&'a str), + /// Arbitrary text. May contain `\n` line breaks, tab characters, or unicode characters. + Text(&'a str), +} + #[derive(Copy, Clone, Debug)] enum FillPairLayout { /// The item, separator, and next item fit. Print the first item and the separator in flat mode. @@ -766,8 +784,6 @@ struct PrinterState<'a> { pending_indent: Indention, pending_space: bool, measured_group_fits: bool, - generated_line: usize, - generated_column: usize, line_width: usize, has_empty_line: bool, line_suffixes: LineSuffixes<'a>, @@ -1118,9 +1134,11 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> { } } - FormatElement::StaticText { text } => return Ok(self.fits_text(text)), - FormatElement::DynamicText { text, .. } => return Ok(self.fits_text(text)), - FormatElement::LocatedTokenText { slice, .. } => return Ok(self.fits_text(slice)), + FormatElement::Token { text } => return Ok(self.fits_text(Text::Token(text))), + FormatElement::Text { text, .. } => return Ok(self.fits_text(Text::Text(text))), + FormatElement::LocatedTokenText { slice, .. } => { + return Ok(self.fits_text(Text::Text(slice))); + } FormatElement::LineSuffixBoundary => { if self.state.has_line_suffix { @@ -1270,7 +1288,7 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> { Ok(Fits::Maybe) } - fn fits_text(&mut self, text: &str) -> Fits { + fn fits_text(&mut self, text: Text) -> Fits { let indent = std::mem::take(&mut self.state.pending_indent); self.state.line_width += indent.level() as usize * self.options().indent_width().value() as usize @@ -1280,21 +1298,28 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> { self.state.line_width += 1; } - for c in text.chars() { - let char_width = match c { - '\t' => self.options().indent_width.value() as usize, - '\n' => { - return if self.must_be_flat - || self.state.line_width > self.options().print_width.into() - { - Fits::No - } else { - Fits::Yes + match text { + Text::Token(token) => { + self.state.line_width += token.len(); + } + Text::Text(text_str) => { + for c in text_str.chars() { + let char_width = match c { + '\t' => self.options().indent_width.value() as usize, + '\n' => { + return if self.must_be_flat + || self.state.line_width > self.options().print_width.into() + { + Fits::No + } else { + Fits::Yes + }; + } + c => c.width().unwrap_or(0), }; + self.state.line_width += char_width; } - c => c.width().unwrap_or(0), - }; - self.state.line_width += char_width; + } } if self.state.line_width > self.options().print_width.into() { @@ -1398,6 +1423,7 @@ mod tests { use crate::prelude::*; use crate::printer::{PrintWidth, Printer, PrinterOptions}; use crate::{Document, FormatState, IndentStyle, Printed, VecBuffer, format_args, write}; + use biome_rowan::TextSize; fn format(root: &dyn Format) -> Printed { format_with_options( @@ -1438,10 +1464,10 @@ mod tests { fn it_prints_a_group_on_a_single_line_if_it_fits() { let result = format(&FormatArrayElements { items: vec![ - &text("\"a\""), - &text("\"b\""), - &text("\"c\""), - &text("\"d\""), + &token("\"a\""), + &token("\"b\""), + &token("\"c\""), + &token("\"d\""), ], }); @@ -1451,17 +1477,17 @@ mod tests { #[test] fn it_tracks_the_indent_for_each_token() { let formatted = format(&format_args!( - text("a"), + token("a"), soft_block_indent(&format_args!( - text("b"), + token("b"), soft_block_indent(&format_args!( - text("c"), - soft_block_indent(&format_args!(text("d"), soft_line_break(), text("d"),)), - text("c"), + token("c"), + soft_block_indent(&format_args!(token("d"), soft_line_break(), token("d"),)), + token("c"), )), - text("b"), + token("b"), )), - text("a") + token("a") )); assert_eq!( @@ -1486,9 +1512,12 @@ a"#, let result = format_with_options( &format_args![ - text("function main() {"), - block_indent(&text("let x = `This is a multiline\nstring`;")), - text("}"), + token("function main() {"), + block_indent(&text( + "let x = `This is a multiline\nstring`;", + TextSize::default() + )), + token("}"), hard_line_break() ], options, @@ -1509,9 +1538,12 @@ a"#, let result = format_with_options( &format_args![ - text("function main() {"), - block_indent(&text("let x = `This is a multiline\nstring`;")), - text("}"), + token("function main() {"), + block_indent(&text( + "let x = `This is a multiline\nstring`;", + TextSize::default() + )), + token("}"), hard_line_break() ], options, @@ -1532,9 +1564,12 @@ a"#, let result = format_with_options( &format_args![ - text("function main() {"), - block_indent(&text("let x = `This is a multiline\nstring`;")), - text("}"), + token("function main() {"), + block_indent(&text( + "let x = `This is a multiline\nstring`;", + TextSize::default() + )), + token("}"), hard_line_break() ], options, @@ -1560,8 +1595,11 @@ a"#, fn it_breaks_a_group_if_a_string_contains_a_newline() { let result = format(&FormatArrayElements { items: vec![ - &text("`This is a string spanning\ntwo lines`"), - &text("\"b\""), + &text( + "`This is a string spanning\ntwo lines`", + TextSize::default(), + ), + &token("\"b\""), ], }); @@ -1576,7 +1614,7 @@ two lines`, } #[test] fn it_breaks_a_group_if_it_contains_a_hard_line_break() { - let result = format(&group(&format_args![text("a"), block_indent(&text("b"))])); + let result = format(&group(&format_args![token("a"), block_indent(&token("b"))])); assert_eq!("a\n b\n", result.as_code()) } @@ -1585,17 +1623,17 @@ two lines`, fn it_breaks_parent_groups_if_they_dont_fit_on_a_single_line() { let result = format(&FormatArrayElements { items: vec![ - &text("\"a\""), - &text("\"b\""), - &text("\"c\""), - &text("\"d\""), + &token("\"a\""), + &token("\"b\""), + &token("\"c\""), + &token("\"d\""), &FormatArrayElements { items: vec![ - &text("\"0123456789\""), - &text("\"0123456789\""), - &text("\"0123456789\""), - &text("\"0123456789\""), - &text("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), ], }, ], @@ -1624,7 +1662,7 @@ two lines`, let result = format_with_options( &FormatArrayElements { - items: vec![&text("'a'"), &text("'b'"), &text("'c'"), &text("'d'")], + items: vec![&token("'a'"), &token("'b'"), &token("'c'"), &token("'d'")], }, options, ); @@ -1635,11 +1673,11 @@ two lines`, #[test] fn it_prints_consecutive_hard_lines_as_one() { let result = format(&format_args![ - text("a"), + token("a"), hard_line_break(), hard_line_break(), hard_line_break(), - text("b"), + token("b"), ]); assert_eq!("a\nb", result.as_code()) @@ -1648,11 +1686,11 @@ two lines`, #[test] fn it_prints_consecutive_empty_lines_as_one() { let result = format(&format_args![ - text("a"), + token("a"), empty_line(), empty_line(), empty_line(), - text("b"), + token("b"), ]); assert_eq!("a\n\nb", result.as_code()) @@ -1661,12 +1699,12 @@ two lines`, #[test] fn it_prints_consecutive_mixed_lines_as_one() { let result = format(&format_args![ - text("a"), + token("a"), empty_line(), hard_line_break(), empty_line(), hard_line_break(), - text("b"), + token("b"), ]); assert_eq!("a\n\nb", result.as_code()) @@ -1683,37 +1721,37 @@ two lines`, // These all fit on the same line together .entry( &soft_line_break_or_space(), - &format_args!(text("1"), text(",")), + &format_args!(token("1"), token(",")), ) .entry( &soft_line_break_or_space(), - &format_args!(text("2"), text(",")), + &format_args!(token("2"), token(",")), ) .entry( &soft_line_break_or_space(), - &format_args!(text("3"), text(",")), + &format_args!(token("3"), token(",")), ) // This one fits on a line by itself, .entry( &soft_line_break_or_space(), - &format_args!(text("723493294"), text(",")), + &format_args!(token("723493294"), token(",")), ) // fits without breaking .entry( &soft_line_break_or_space(), &group(&format_args!( - text("["), - soft_block_indent(&text("5")), - text("],") + token("["), + soft_block_indent(&token("5")), + token("],") )), ) // this one must be printed in expanded mode to fit .entry( &soft_line_break_or_space(), &group(&format_args!( - text("["), - soft_block_indent(&text("123456789")), - text("]"), + token("["), + soft_block_indent(&token("123456789")), + token("]"), )), ) .finish() @@ -1735,27 +1773,27 @@ two lines`, fn line_suffix_printed_at_end() { let printed = format(&format_args![ group(&format_args![ - text("["), + token("["), soft_block_indent(&format_with(|f| { f.fill() .entry( &soft_line_break_or_space(), - &format_args!(text("1"), text(",")), + &format_args!(token("1"), token(",")), ) .entry( &soft_line_break_or_space(), - &format_args!(text("2"), text(",")), + &format_args!(token("2"), token(",")), ) .entry( &soft_line_break_or_space(), - &format_args!(text("3"), if_group_breaks(&text(","))), + &format_args!(token("3"), if_group_breaks(&token(","))), ) .finish() })), - text("]") + token("]") ]), - text(";"), - &line_suffix(&format_args![space(), text("// trailing"), space()]) + token(";"), + &line_suffix(&format_args![space(), token("// trailing"), space()]) ]); assert_eq!(printed.as_code(), "[1, 2, 3]; // trailing") @@ -1768,15 +1806,15 @@ two lines`, f, [ group(&format_args![ - text("The referenced group breaks."), + token("The referenced group breaks."), hard_line_break() ]) .with_group_id(Some(group_id)), group(&format_args![ - text("This group breaks because:"), + token("This group breaks because:"), soft_line_break_or_space(), - if_group_fits_on_line(&text("This content fits but should not be printed.")).with_group_id(Some(group_id)), - if_group_breaks(&text("It measures with the 'if_group_breaks' variant because the referenced group breaks and that's just way too much text.")).with_group_id(Some(group_id)), + if_group_fits_on_line(&token("This content fits but should not be printed.")).with_group_id(Some(group_id)), + if_group_breaks(&token("It measures with the 'if_group_breaks' variant because the referenced group breaks and that's just way too much text.")).with_group_id(Some(group_id)), ]) ] ) @@ -1799,7 +1837,7 @@ two lines`, write!( f, [ - group(&text("Group with id-2")).with_group_id(Some(id_2)), + group(&token("Group with id-2")).with_group_id(Some(id_2)), hard_line_break() ] )?; @@ -1807,7 +1845,7 @@ two lines`, write!( f, [ - group(&text("Group with id-1 does not fit on the line because it exceeds the line width of 80 characters by")).with_group_id(Some(id_1)), + group(&token("Group with id-1 does not fit on the line because it exceeds the line width of 80 characters by")).with_group_id(Some(id_1)), hard_line_break() ] )?; @@ -1815,9 +1853,9 @@ two lines`, write!( f, [ - if_group_fits_on_line(&text("Group 2 fits")).with_group_id(Some(id_2)), + if_group_fits_on_line(&token("Group 2 fits")).with_group_id(Some(id_2)), hard_line_break(), - if_group_breaks(&text("Group 1 breaks")).with_group_id(Some(id_1)) + if_group_breaks(&token("Group 1 breaks")).with_group_id(Some(id_1)) ] ) }); @@ -1842,11 +1880,14 @@ Group 1 breaks"# let result = format_with_options( &format_args![group(&format_args!( - text("("), + token("("), soft_line_break(), - text("This is a string\n containing a newline"), + text( + "This is a string\n containing a newline", + TextSize::default() + ), soft_line_break(), - text(")") + token(")") ))], options, ); @@ -1866,9 +1907,9 @@ Group 1 breaks"# let result = format_with_options_and_indentation( &format_args![group(&format_args!( - text("Hello world"), + token("Hello world"), soft_line_break(), - text("Hello world") + token("Hello world") ))], options, 1, @@ -1888,37 +1929,37 @@ Group 1 breaks"# // These all fit on the same line together .entry( &soft_line_break_or_space(), - &format_args!(text("1"), text(",")), + &format_args!(token("1"), token(",")), ) .entry( &soft_line_break_or_space(), - &format_args!(text("2"), text(",")), + &format_args!(token("2"), token(",")), ) .entry( &soft_line_break_or_space(), - &format_args!(text("3"), text(",")), + &format_args!(token("3"), token(",")), ) // This one fits on a line by itself, .entry( &soft_line_break_or_space(), - &format_args!(text("723493294"), text(",")), + &format_args!(token("723493294"), token(",")), ) // fits without breaking .entry( &soft_line_break_or_space(), &group(&format_args!( - text("["), - soft_block_indent(&text("5")), - text("],") + token("["), + soft_block_indent(&token("5")), + token("],") )), ) // this one must be printed in expanded mode to fit .entry( &soft_line_break_or_space(), &group(&format_args!( - text("["), - soft_block_indent(&text("123456789")), - text("]"), + token("["), + soft_block_indent(&token("123456789")), + token("]"), )), ) .finish() @@ -1945,15 +1986,15 @@ Group 1 breaks"# write!( f, [group(&format_args!( - text("["), + token("["), soft_block_indent(&format_args!( format_with(|f| f - .join_with(format_args!(text(","), soft_line_break_or_space())) + .join_with(format_args!(token(","), soft_line_break_or_space())) .entries(&self.items) .finish()), - if_group_breaks(&text(",")), + if_group_breaks(&token(",")), )), - text("]") + token("]") ))] ) } diff --git a/crates/biome_formatter/src/separated.rs b/crates/biome_formatter/src/separated.rs index 01cc109e75df..7502527ad9bc 100644 --- a/crates/biome_formatter/src/separated.rs +++ b/crates/biome_formatter/src/separated.rs @@ -100,12 +100,12 @@ where TrailingSeparator::Allowed => { write!( f, - [if_group_breaks(&text(self.separator)) + [if_group_breaks(&token(self.separator)) .with_group_id(self.options.group_id)] )?; } TrailingSeparator::Mandatory => { - text(self.separator).fmt(f)?; + token(self.separator).fmt(f)?; } TrailingSeparator::Omit | TrailingSeparator::Disallowed => { /* no op */ } } diff --git a/crates/biome_formatter/src/source_map.rs b/crates/biome_formatter/src/source_map.rs index c0415a5bc2b9..c5d7a6a0ef9e 100644 --- a/crates/biome_formatter/src/source_map.rs +++ b/crates/biome_formatter/src/source_map.rs @@ -211,7 +211,7 @@ impl TransformSourceMap { /// in the original, untransformed source code. /// /// The printer creates a source map that allows mapping positions from the newly formatted document - /// back to the locations of the tree. However, the source positions stored in [crate::FormatElement::DynamicText] + /// back to the locations of the tree. However, the source positions stored in [crate::FormatElement::Text] /// and [crate::FormatElement::LocatedTokenText] are relative to the transformed tree /// and not the original tree passed to [crate::format_node]. /// diff --git a/crates/biome_graphql_formatter/src/comments.rs b/crates/biome_graphql_formatter/src/comments.rs index 8ae97377b431..f26a8de489a5 100644 --- a/crates/biome_graphql_formatter/src/comments.rs +++ b/crates/biome_graphql_formatter/src/comments.rs @@ -29,7 +29,7 @@ impl FormatRule> for FormatGraphqlLeadingComment // SAFETY: Safe, `is_doc_comment` only returns `true` for multiline comments let first_line = lines.next().unwrap(); - write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?; + write!(f, [text(first_line.trim_end(), source_offset)])?; source_offset += first_line.text_len(); @@ -40,10 +40,7 @@ impl FormatRule> for FormatGraphqlLeadingComment 1, &format_once(|f| { for line in lines { - write!( - f, - [hard_line_break(), dynamic_text(line.trim(), source_offset)] - )?; + write!(f, [hard_line_break(), text(line.trim(), source_offset)])?; source_offset += line.text_len(); } diff --git a/crates/biome_graphql_formatter/src/graphql/auxiliary/union_member_types.rs b/crates/biome_graphql_formatter/src/graphql/auxiliary/union_member_types.rs index 89a594ad4c77..9e5268fac117 100644 --- a/crates/biome_graphql_formatter/src/graphql/auxiliary/union_member_types.rs +++ b/crates/biome_graphql_formatter/src/graphql/auxiliary/union_member_types.rs @@ -60,7 +60,7 @@ impl Format for FormatTypeLeadingSeparator<'_> { let content = format_with(|f| { write!( f, - [soft_line_break_or_space(), text(self.separator), space()] + [soft_line_break_or_space(), token(self.separator), space()] ) }); diff --git a/crates/biome_graphql_formatter/src/graphql/lists/argument_definition_list.rs b/crates/biome_graphql_formatter/src/graphql/lists/argument_definition_list.rs index 4f3b68372355..335112409074 100644 --- a/crates/biome_graphql_formatter/src/graphql/lists/argument_definition_list.rs +++ b/crates/biome_graphql_formatter/src/graphql/lists/argument_definition_list.rs @@ -21,7 +21,7 @@ impl FormatRule for FormatGraphqlArgumentDefiniti write!(f, [node.format()])?; if index != last_index { - write!(f, [if_group_fits_on_line(&text(","))])?; + write!(f, [if_group_fits_on_line(&token(","))])?; } Ok(()) diff --git a/crates/biome_graphql_formatter/src/graphql/lists/argument_list.rs b/crates/biome_graphql_formatter/src/graphql/lists/argument_list.rs index 0b8f4a53833a..7537c0268312 100644 --- a/crates/biome_graphql_formatter/src/graphql/lists/argument_list.rs +++ b/crates/biome_graphql_formatter/src/graphql/lists/argument_list.rs @@ -17,7 +17,7 @@ impl FormatRule for FormatGraphqlArgumentList { write!(f, [node.format()])?; if index != last_index { - write!(f, [if_group_fits_on_line(&text(","))])?; + write!(f, [if_group_fits_on_line(&token(","))])?; } Ok(()) diff --git a/crates/biome_graphql_formatter/src/graphql/lists/list_value_element_list.rs b/crates/biome_graphql_formatter/src/graphql/lists/list_value_element_list.rs index 8b755bf70ed1..62258d813b5e 100644 --- a/crates/biome_graphql_formatter/src/graphql/lists/list_value_element_list.rs +++ b/crates/biome_graphql_formatter/src/graphql/lists/list_value_element_list.rs @@ -12,7 +12,7 @@ impl FormatRule for FormatGraphqlListValueElementLi f: &mut GraphqlFormatter, ) -> FormatResult<()> { f.join_with(&format_args!( - if_group_fits_on_line(&format_args![text(","), space()]), + if_group_fits_on_line(&format_args![token(","), space()]), soft_line_break(), )) .entries(node.iter().formatted()) diff --git a/crates/biome_graphql_formatter/src/graphql/lists/object_value_member_list.rs b/crates/biome_graphql_formatter/src/graphql/lists/object_value_member_list.rs index 65cd07862589..a7bc7ae1bd9e 100644 --- a/crates/biome_graphql_formatter/src/graphql/lists/object_value_member_list.rs +++ b/crates/biome_graphql_formatter/src/graphql/lists/object_value_member_list.rs @@ -12,7 +12,7 @@ impl FormatRule for FormatGraphqlObjectValueMember f: &mut GraphqlFormatter, ) -> FormatResult<()> { f.join_with(&format_args!( - if_group_fits_on_line(&format_args![text(","), space()]), + if_group_fits_on_line(&format_args![token(","), space()]), soft_line_break(), )) .entries(node.iter().formatted()) diff --git a/crates/biome_graphql_formatter/src/graphql/lists/variable_definition_list.rs b/crates/biome_graphql_formatter/src/graphql/lists/variable_definition_list.rs index 11feccd7a1e2..cab02239e674 100644 --- a/crates/biome_graphql_formatter/src/graphql/lists/variable_definition_list.rs +++ b/crates/biome_graphql_formatter/src/graphql/lists/variable_definition_list.rs @@ -11,7 +11,7 @@ impl FormatRule for FormatGraphqlVariableDefiniti f: &mut GraphqlFormatter, ) -> FormatResult<()> { f.join_with(&format_args!( - if_group_fits_on_line(&format_args![text(","), space()]), + if_group_fits_on_line(&format_args![token(","), space()]), soft_line_break(), )) .entries(node.iter().formatted()) diff --git a/crates/biome_graphql_formatter/src/graphql/value/string_value.rs b/crates/biome_graphql_formatter/src/graphql/value/string_value.rs index 858eb157940c..1507ce1fea50 100644 --- a/crates/biome_graphql_formatter/src/graphql/value/string_value.rs +++ b/crates/biome_graphql_formatter/src/graphql/value/string_value.rs @@ -13,8 +13,8 @@ impl FormatNodeRule for FormatGraphqlStringValue { } = node.as_fields(); if node.is_block() { - let token = graphql_string_literal_token?; - let text_trimmed = token.text_trimmed(); + let string_token = graphql_string_literal_token?; + let text_trimmed = string_token.text_trimmed(); // Extract the content of the block string // by removing the triple quotes let raw_content = &text_trimmed[3..text_trimmed.len() - 3]; @@ -37,10 +37,10 @@ impl FormatNodeRule for FormatGraphqlStringValue { let content = format_with(|f| { let mut join = f.join(); // Write the opening triple quotes - join.entry(&text("\"\"\"")); + join.entry(&token("\"\"\"")); join.entry(&hard_line_break()); - let mut start = token.text_trimmed_range().start(); + let mut start = string_token.text_trimmed_range().start(); for line in trimmed_content.lines() { if line.is_empty() || is_blank(line) { // if the line is empty, @@ -50,7 +50,7 @@ impl FormatNodeRule for FormatGraphqlStringValue { } // Write the line with the minimum indentation level removed // SAFETY: min_indent is always less than or equal to the length of the line - join.entry(&dynamic_text(&line[min_indent..], start)); + join.entry(&text(&line[min_indent..], start)); start += line.text_len(); if line.is_empty() { @@ -63,11 +63,11 @@ impl FormatNodeRule for FormatGraphqlStringValue { join.entry(&hard_line_break()); // Write the closing triple quotes - join.entry(&text("\"\"\"")); + join.entry(&token("\"\"\"")); join.finish() }); - FormatGraphqlSyntaxToken.format_replaced(&token, &content, f) + FormatGraphqlSyntaxToken.format_replaced(&string_token, &content, f) } else { write![f, [graphql_string_literal_token.format()]] } diff --git a/crates/biome_graphql_formatter/src/verbatim.rs b/crates/biome_graphql_formatter/src/verbatim.rs index 8061a5ce17dd..3e0922205ac4 100644 --- a/crates/biome_graphql_formatter/src/verbatim.rs +++ b/crates/biome_graphql_formatter/src/verbatim.rs @@ -1,7 +1,7 @@ use crate::context::GraphqlFormatContext; use biome_formatter::format_element::tag::VerbatimKind; use biome_formatter::formatter::Formatter; -use biome_formatter::prelude::{Tag, dynamic_text}; +use biome_formatter::prelude::{Tag, text}; use biome_formatter::trivia::{FormatLeadingComments, FormatTrailingComments}; use biome_formatter::{ Buffer, CstFormatContext, Format, FormatContext, FormatElement, FormatError, FormatResult, @@ -115,7 +115,7 @@ impl Format for FormatGraphqlVerbatimNode<'_> { }, ); - dynamic_text( + text( &normalize_newlines(&original_source, LINE_TERMINATORS), self.node.text_trimmed_range().start(), ) diff --git a/crates/biome_grit_formatter/src/comments.rs b/crates/biome_grit_formatter/src/comments.rs index 47bb991824af..9f0f273e0dd4 100644 --- a/crates/biome_grit_formatter/src/comments.rs +++ b/crates/biome_grit_formatter/src/comments.rs @@ -5,7 +5,7 @@ use biome_formatter::{ FormatResult, FormatRule, comments::{CommentStyle, Comments, SourceComment, is_doc_comment}, prelude::*, - prelude::{Formatter, align, dynamic_text, format_once, hard_line_break}, + prelude::{Formatter, align, format_once, hard_line_break, text}, write, }; use biome_grit_syntax::GritLanguage; @@ -55,7 +55,7 @@ impl FormatRule> for FormatGritLeadingComment { // SAFETY: Safe, `is_doc_comment` only returns `true` for multiline comments let first_line = lines.next().unwrap(); - write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?; + write!(f, [text(first_line.trim_end(), source_offset)])?; source_offset += first_line.text_len(); @@ -66,10 +66,7 @@ impl FormatRule> for FormatGritLeadingComment { 1, &format_once(|f| { for line in lines { - write!( - f, - [hard_line_break(), dynamic_text(line.trim(), source_offset)] - )?; + write!(f, [hard_line_break(), text(line.trim(), source_offset)])?; source_offset += line.text_len(); } diff --git a/crates/biome_grit_formatter/src/verbatim.rs b/crates/biome_grit_formatter/src/verbatim.rs index 5ce557888d68..26887022d1fd 100644 --- a/crates/biome_grit_formatter/src/verbatim.rs +++ b/crates/biome_grit_formatter/src/verbatim.rs @@ -1,7 +1,7 @@ use crate::context::GritFormatContext; use biome_formatter::format_element::tag::VerbatimKind; use biome_formatter::formatter::Formatter; -use biome_formatter::prelude::{Tag, dynamic_text}; +use biome_formatter::prelude::{Tag, text}; use biome_formatter::trivia::{FormatLeadingComments, FormatTrailingComments}; use biome_formatter::{ Buffer, CstFormatContext, Format, FormatContext, FormatElement, FormatError, FormatResult, @@ -115,7 +115,7 @@ impl Format for FormatGraphqlVerbatimNode<'_> { }, ); - dynamic_text( + text( &normalize_newlines(&original_source, LINE_TERMINATORS), self.node.text_trimmed_range().start(), ) diff --git a/crates/biome_html_formatter/src/html/auxiliary/self_closing_element.rs b/crates/biome_html_formatter/src/html/auxiliary/self_closing_element.rs index 67c864e22880..db1694a42da6 100644 --- a/crates/biome_html_formatter/src/html/auxiliary/self_closing_element.rs +++ b/crates/biome_html_formatter/src/html/auxiliary/self_closing_element.rs @@ -58,7 +58,7 @@ impl FormatNodeRule for FormatHtmlSelfClosingElement { if slash_token.is_some() { write!(f, [slash_token.format()])?; } else { - write!(f, [text("/")])?; + write!(f, [token("/")])?; } } // We remove the slash only from void elements diff --git a/crates/biome_html_formatter/src/html/auxiliary/string.rs b/crates/biome_html_formatter/src/html/auxiliary/string.rs index 865be5d320ca..7838d254aab1 100644 --- a/crates/biome_html_formatter/src/html/auxiliary/string.rs +++ b/crates/biome_html_formatter/src/html/auxiliary/string.rs @@ -33,9 +33,9 @@ impl FormatNodeRule for FormatHtmlString { [format_replaced( value, &group(&format_args![ - text("\""), + token("\""), located_token_text(value, range), - text("\""), + token("\""), ]) )] )?; diff --git a/crates/biome_html_formatter/src/utils/children.rs b/crates/biome_html_formatter/src/utils/children.rs index e9d8fbfec59d..41c052cd8831 100644 --- a/crates/biome_html_formatter/src/utils/children.rs +++ b/crates/biome_html_formatter/src/utils/children.rs @@ -168,7 +168,7 @@ pub(crate) struct HtmlRawSpace; impl Format for HtmlRawSpace { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - write!(f, [text(" ")]) + write!(f, [token(" ")]) } } diff --git a/crates/biome_html_formatter/src/utils/formatters.rs b/crates/biome_html_formatter/src/utils/formatters.rs index c516cb423a72..07fcd7c2bf7b 100644 --- a/crates/biome_html_formatter/src/utils/formatters.rs +++ b/crates/biome_html_formatter/src/utils/formatters.rs @@ -27,7 +27,7 @@ impl Format for FormatTokenAsLowercase { f, [format_replaced( &self.token, - &dynamic_text(&lowercase, self.token.text_trimmed_range().start()), + &text(&lowercase, self.token.text_trimmed_range().start()), )] ), } diff --git a/crates/biome_html_formatter/src/verbatim.rs b/crates/biome_html_formatter/src/verbatim.rs index 1bac74b77f7e..9189240d2eec 100644 --- a/crates/biome_html_formatter/src/verbatim.rs +++ b/crates/biome_html_formatter/src/verbatim.rs @@ -4,8 +4,8 @@ use biome_formatter::comments::{CommentKind, SourceComment}; use biome_formatter::format_element::tag::VerbatimKind; use biome_formatter::formatter::Formatter; use biome_formatter::prelude::{ - Tag, dynamic_text, empty_line, expand_parent, format_with, hard_line_break, line_suffix, - should_nestle_adjacent_doc_comments, soft_line_break_or_space, space, + Tag, empty_line, expand_parent, format_with, hard_line_break, line_suffix, + should_nestle_adjacent_doc_comments, soft_line_break_or_space, space, text, }; use biome_formatter::{ @@ -139,7 +139,7 @@ impl Format for FormatHtmlVerbatimNode<'_> { }, ); - dynamic_text( + text( &normalize_newlines(&original_source, LINE_TERMINATORS), self.node.text_trimmed_range().start(), ) diff --git a/crates/biome_js_formatter/src/comments.rs b/crates/biome_js_formatter/src/comments.rs index b978f94d20cc..396517f201f0 100644 --- a/crates/biome_js_formatter/src/comments.rs +++ b/crates/biome_js_formatter/src/comments.rs @@ -40,7 +40,7 @@ impl FormatRule> for FormatJsLeadingComment { // SAFETY: Safe, `is_alignable_comment` only returns `true` for multiline comments let first_line = lines.next().unwrap(); - write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?; + write!(f, [text(first_line.trim_end(), source_offset)])?; source_offset += first_line.text_len(); @@ -53,8 +53,8 @@ impl FormatRule> for FormatJsLeadingComment { f, [ hard_line_break(), - text(" "), - dynamic_text(line.trim(), source_offset) + token(" "), + text(line.trim(), source_offset) ] )?; diff --git a/crates/biome_js_formatter/src/context/trailing_commas.rs b/crates/biome_js_formatter/src/context/trailing_commas.rs index 37a5dc1ad216..7c983f1c1a3a 100644 --- a/crates/biome_js_formatter/src/context/trailing_commas.rs +++ b/crates/biome_js_formatter/src/context/trailing_commas.rs @@ -1,7 +1,7 @@ use crate::prelude::*; use crate::{JsFormatContext, JsFormatOptions}; use biome_deserialize_macros::{Deserializable, Merge}; -use biome_formatter::prelude::{if_group_breaks, text}; +use biome_formatter::prelude::if_group_breaks; use biome_formatter::write; use biome_formatter::{Format, FormatResult}; use std::fmt; @@ -43,7 +43,7 @@ impl Format for FormatTrailingCommas { } if matches!(self, Self::ES5) || f.options().trailing_commas().is_all() { - write!(f, [if_group_breaks(&text(","))])? + write!(f, [if_group_breaks(&token(","))])? } Ok(()) diff --git a/crates/biome_js_formatter/src/js/classes/extends_clause.rs b/crates/biome_js_formatter/src/js/classes/extends_clause.rs index 220181007a92..7ef1534f896f 100644 --- a/crates/biome_js_formatter/src/js/classes/extends_clause.rs +++ b/crates/biome_js_formatter/src/js/classes/extends_clause.rs @@ -35,16 +35,16 @@ impl FormatNodeRule for FormatJsExtendsClause { .is_some_and(|p| p.kind() == JS_ASSIGNMENT_EXPRESSION) { if comments.has_leading_comments(super_class.syntax()) || has_trailing_comments { - write!(f, [text("("), &content, text(")")]) + write!(f, [token("("), &content, token(")")]) } else { let content = content.memoized(); write!( f, [ if_group_breaks(&format_args![ - text("("), + token("("), &soft_block_indent(&content), - text(")"), + token(")"), ]), if_group_fits_on_line(&content) ] diff --git a/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs b/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs index ef69284e8826..192419f773ec 100644 --- a/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs +++ b/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs @@ -109,9 +109,9 @@ impl FormatNodeRule for FormatJsArrowFunctionExpressi formatted_signature, group(&format_args![indent(&format_args![ hard_line_break(), - text("("), + token("("), soft_block_indent(&format_body), - text(")") + token(")") ]),]) ])] ); @@ -122,9 +122,9 @@ impl FormatNodeRule for FormatJsArrowFunctionExpressi formatted_signature, group(&format_args![ space(), - text("("), + token("("), soft_block_indent(&format_body), - text(")") + token(")") ]) ])] ); @@ -155,13 +155,13 @@ impl FormatNodeRule for FormatJsArrowFunctionExpressi group(&format_args![ soft_line_indent_or_hard_space(&format_with(|f| { if should_add_parens { - write!(f, [if_group_fits_on_line(&text("("))])?; + write!(f, [if_group_fits_on_line(&token("("))])?; } write!(f, [format_body])?; if should_add_parens { - write!(f, [if_group_fits_on_line(&text(")"))])?; + write!(f, [if_group_fits_on_line(&token(")"))])?; } Ok(()) @@ -180,13 +180,13 @@ impl FormatNodeRule for FormatJsArrowFunctionExpressi group(&format_args![ soft_line_indent_or_space(&format_with(|f| { if should_add_parens { - write!(f, [if_group_fits_on_line(&text("("))])?; + write!(f, [if_group_fits_on_line(&token("("))])?; } write!(f, [format_body])?; if should_add_parens { - write!(f, [if_group_fits_on_line(&text(")"))])?; + write!(f, [if_group_fits_on_line(&token(")"))])?; } Ok(()) @@ -253,7 +253,7 @@ fn format_signature( let parentheses_not_needed = can_avoid_parentheses(arrow, f); if !parentheses_not_needed { - write!(f, [text("(")])?; + write!(f, [token("(")])?; } if should_hug || parentheses_not_needed { @@ -269,7 +269,7 @@ fn format_signature( } if !parentheses_not_needed { - write!(f, [text(")")])?; + write!(f, [token(")")])?; } } AnyJsArrowFunctionParameters::JsParameters(params) => { @@ -658,18 +658,18 @@ impl Format for ArrowChain { f, [group(&format_args![indent(&format_args![ hard_line_break(), - text("("), + token("("), soft_block_indent(&format_tail_body), - text(")") + token(")") ]),])] )?; } else { write!( f, [group(&format_args![ - text("("), + token("("), soft_block_indent(&format_tail_body), - text(")") + token(")") ])] )?; } @@ -679,9 +679,9 @@ impl Format for ArrowChain { write!( f, [ - if_group_fits_on_line(&text("(")), + if_group_fits_on_line(&token("(")), format_tail_body, - if_group_fits_on_line(&text(")")) + if_group_fits_on_line(&token(")")) ] )?; } else { diff --git a/crates/biome_js_formatter/src/js/expressions/bigint_literal_expression.rs b/crates/biome_js_formatter/src/js/expressions/bigint_literal_expression.rs index 78b037dbbeb5..55b5f0f5aa09 100644 --- a/crates/biome_js_formatter/src/js/expressions/bigint_literal_expression.rs +++ b/crates/biome_js_formatter/src/js/expressions/bigint_literal_expression.rs @@ -27,7 +27,7 @@ impl FormatNodeRule for FormatJsBigintLiteralExpressi f, [format_replaced( &value_token, - &dynamic_text(&lowercase, value_token.text_trimmed_range().start()) + &text(&lowercase, value_token.text_trimmed_range().start()) )] ) } diff --git a/crates/biome_js_formatter/src/js/expressions/new_expression.rs b/crates/biome_js_formatter/src/js/expressions/new_expression.rs index d686c3963520..de55609abd12 100644 --- a/crates/biome_js_formatter/src/js/expressions/new_expression.rs +++ b/crates/biome_js_formatter/src/js/expressions/new_expression.rs @@ -32,7 +32,7 @@ impl FormatNodeRule for FormatJsNewExpression { write!(f, [arguments.format()]) } None => { - write!(f, [text("("), text(")")]) + write!(f, [token("("), token(")")]) } } } diff --git a/crates/biome_js_formatter/src/js/expressions/unary_expression.rs b/crates/biome_js_formatter/src/js/expressions/unary_expression.rs index 7c1c188b2fb5..5444bc428d71 100644 --- a/crates/biome_js_formatter/src/js/expressions/unary_expression.rs +++ b/crates/biome_js_formatter/src/js/expressions/unary_expression.rs @@ -36,9 +36,9 @@ impl FormatNodeRule for FormatJsUnaryExpression { write!( f, [group(&format_args![ - text("("), + token("("), soft_block_indent(&argument.format()), - text(")") + token(")") ])] ) } else { diff --git a/crates/biome_js_formatter/src/js/statements/expression_statement.rs b/crates/biome_js_formatter/src/js/statements/expression_statement.rs index f69c04564cef..f0e0e82bced9 100644 --- a/crates/biome_js_formatter/src/js/statements/expression_statement.rs +++ b/crates/biome_js_formatter/src/js/statements/expression_statement.rs @@ -41,17 +41,17 @@ impl FormatNodeRule for FormatJsExpressionStatement { && !is_after_bogus && (needs_parentheses || needs_semicolon(node)) { - write!(f, [text(";")])?; + write!(f, [token(";")])?; } if needs_parentheses { - write!(f, [text("(")])?; + write!(f, [token("(")])?; } self.fmt_fields(node, f)?; if needs_parentheses { - write!(f, [text(")")])?; + write!(f, [token(")")])?; } Ok(()) diff --git a/crates/biome_js_formatter/src/js/statements/labeled_statement.rs b/crates/biome_js_formatter/src/js/statements/labeled_statement.rs index cb9c22bd9c9f..a5ecbe230007 100644 --- a/crates/biome_js_formatter/src/js/statements/labeled_statement.rs +++ b/crates/biome_js_formatter/src/js/statements/labeled_statement.rs @@ -20,7 +20,7 @@ impl FormatNodeRule for FormatJsLabeledStatement { match body? { AnyJsStatement::JsEmptyStatement(empty) => { // If the body is an empty statement, force semicolon insertion - write!(f, [empty.format(), text(";")]) + write!(f, [empty.format(), token(";")]) } body => { write!(f, [space(), body.format()]) diff --git a/crates/biome_js_formatter/src/js/statements/return_statement.rs b/crates/biome_js_formatter/src/js/statements/return_statement.rs index 684ef012d22c..cd21a1c95020 100644 --- a/crates/biome_js_formatter/src/js/statements/return_statement.rs +++ b/crates/biome_js_formatter/src/js/statements/return_statement.rs @@ -108,14 +108,17 @@ impl Format for FormatReturnOrThrowArgument<'_> { && !matches!(argument, AnyJsExpression::JsxTagExpression(_)) && !is_suppressed { - write!(f, [text("("), &block_indent(&argument.format()), text(")")]) + write!( + f, + [token("("), &block_indent(&argument.format()), token(")")] + ) } else if is_binary_or_sequence_argument(argument) && !is_suppressed { write!( f, [group(&format_args![ - if_group_breaks(&text("(")), + if_group_breaks(&token("(")), soft_block_indent(&argument.format()), - if_group_breaks(&text(")")) + if_group_breaks(&token(")")) ])] ) } else { diff --git a/crates/biome_js_formatter/src/jsx/expressions/tag_expression.rs b/crates/biome_js_formatter/src/jsx/expressions/tag_expression.rs index 1adfeaeb957c..9699eb796b13 100644 --- a/crates/biome_js_formatter/src/jsx/expressions/tag_expression.rs +++ b/crates/biome_js_formatter/src/jsx/expressions/tag_expression.rs @@ -33,7 +33,7 @@ impl FormatNodeRule for FormatJsxTagExpression { let format_inner = format_with(|f| { if !needs_parentheses { - write!(f, [if_group_breaks(&text("("))])?; + write!(f, [if_group_breaks(&token("("))])?; } write!( @@ -46,7 +46,7 @@ impl FormatNodeRule for FormatJsxTagExpression { )?; if !needs_parentheses { - write!(f, [if_group_breaks(&text(")"))])?; + write!(f, [if_group_breaks(&token(")"))])?; } Ok(()) diff --git a/crates/biome_js_formatter/src/lib.rs b/crates/biome_js_formatter/src/lib.rs index ca3978a9c90a..653411ff53b0 100644 --- a/crates/biome_js_formatter/src/lib.rs +++ b/crates/biome_js_formatter/src/lib.rs @@ -373,13 +373,13 @@ where let needs_parentheses = self.needs_parentheses(node); if needs_parentheses { - write!(f, [text("(")])?; + write!(f, [token("(")])?; } self.fmt_fields(node, f)?; if needs_parentheses { - write!(f, [text(")")])?; + write!(f, [token(")")])?; } Ok(()) diff --git a/crates/biome_js_formatter/src/ts/declarations/external_module_declaration.rs b/crates/biome_js_formatter/src/ts/declarations/external_module_declaration.rs index 3b9f444e613f..922e6b1a598c 100644 --- a/crates/biome_js_formatter/src/ts/declarations/external_module_declaration.rs +++ b/crates/biome_js_formatter/src/ts/declarations/external_module_declaration.rs @@ -31,7 +31,7 @@ impl FormatNodeRule for FormatTsExternalModuleDecla write!(f, [space(), body.format()])?; } None if f.options().semicolons().is_always() => { - write!(f, [text(";")])?; + write!(f, [token(";")])?; } None => {} } diff --git a/crates/biome_js_formatter/src/ts/expressions/type_assertion_expression.rs b/crates/biome_js_formatter/src/ts/expressions/type_assertion_expression.rs index 60b278bd4673..3b2e2478bf52 100644 --- a/crates/biome_js_formatter/src/ts/expressions/type_assertion_expression.rs +++ b/crates/biome_js_formatter/src/ts/expressions/type_assertion_expression.rs @@ -50,9 +50,9 @@ impl FormatNodeRule for FormatTsTypeAssertionExpressi format_args![ format_cast, group(&format_args![ - text("("), + token("("), block_indent(&format_expression), - text(")") + token(")") ]) ], format_args![format_cast, format_expression] diff --git a/crates/biome_js_formatter/src/ts/lists/type_member_list.rs b/crates/biome_js_formatter/src/ts/lists/type_member_list.rs index e2866f39f333..1a6f43462819 100644 --- a/crates/biome_js_formatter/src/ts/lists/type_member_list.rs +++ b/crates/biome_js_formatter/src/ts/lists/type_member_list.rs @@ -58,14 +58,14 @@ impl Format for TsTypeMemberItem<'_> { match f.options().semicolons() { Semicolons::Always => { if self.last { - write!(f, [if_group_breaks(&text(";"))])?; + write!(f, [if_group_breaks(&token(";"))])?; } else { - text(";").fmt(f)?; + token(";").fmt(f)?; } } Semicolons::AsNeeded => { if !self.last { - write!(f, [if_group_fits_on_line(&text(";"))])?; + write!(f, [if_group_fits_on_line(&token(";"))])?; } } } diff --git a/crates/biome_js_formatter/src/ts/types/bigint_literal_type.rs b/crates/biome_js_formatter/src/ts/types/bigint_literal_type.rs index 911fb332ea4b..88625181d4a4 100644 --- a/crates/biome_js_formatter/src/ts/types/bigint_literal_type.rs +++ b/crates/biome_js_formatter/src/ts/types/bigint_literal_type.rs @@ -26,7 +26,7 @@ impl FormatNodeRule for FormatTsBigintLiteralType { f, [format_replaced( &literal_token, - &dynamic_text(&lowercase, literal_token.text_trimmed_range().start()) + &text(&lowercase, literal_token.text_trimmed_range().start()) )] ) } diff --git a/crates/biome_js_formatter/src/ts/types/union_type.rs b/crates/biome_js_formatter/src/ts/types/union_type.rs index e09238cc4e03..2df61b08fda2 100644 --- a/crates/biome_js_formatter/src/ts/types/union_type.rs +++ b/crates/biome_js_formatter/src/ts/types/union_type.rs @@ -120,11 +120,11 @@ impl FormatNodeRule for FormatTsUnionType { f, [ indent(&format_args![ - if_group_breaks(&format_args![text("("), soft_line_break()]), + if_group_breaks(&format_args![token("("), soft_line_break()]), types ]), soft_line_break(), - if_group_breaks(&text(")")) + if_group_breaks(&token(")")) ] ) } else if should_indent { @@ -176,7 +176,7 @@ impl Format for FormatTypeSetLeadingSeparator<'_> { if self.leading_soft_line_break_or_space { write!(f, [soft_line_break_or_space()])?; } - write!(f, [text(self.separator), space()]) + write!(f, [token(self.separator), space()]) }); write!(f, [if_group_breaks(&content)]) diff --git a/crates/biome_js_formatter/src/utils/array.rs b/crates/biome_js_formatter/src/utils/array.rs index f3c2eba98daf..da7f787d3999 100644 --- a/crates/biome_js_formatter/src/utils/array.rs +++ b/crates/biome_js_formatter/src/utils/array.rs @@ -45,7 +45,7 @@ where // 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 => text(",").fmt(f)?, + None => token(",").fmt(f)?, }; } else if let Some(separator) = element.trailing_separator()? { match trailing_separator { diff --git a/crates/biome_js_formatter/src/utils/conditional.rs b/crates/biome_js_formatter/src/utils/conditional.rs index 7f459f1c35b2..2863ed98aaa7 100644 --- a/crates/biome_js_formatter/src/utils/conditional.rs +++ b/crates/biome_js_formatter/src/utils/conditional.rs @@ -90,9 +90,9 @@ impl FormatRule for FormatJsAnyConditionalRule { write!( f, [ - if_group_fits_on_line(&text("(")), + if_group_fits_on_line(&token("(")), consequent, - if_group_fits_on_line(&text(")")) + if_group_fits_on_line(&token(")")) ] )?; } else { @@ -802,9 +802,9 @@ impl Format for FormatJsxChainExpression<'_> { write!( f, [ - if_group_breaks(&text("(")), + if_group_breaks(&token("(")), soft_block_indent(&format_expression), - if_group_breaks(&text(")")) + if_group_breaks(&token(")")) ] ) } diff --git a/crates/biome_js_formatter/src/utils/jsx.rs b/crates/biome_js_formatter/src/utils/jsx.rs index 1a8f8bad7a82..cae5860a3d3b 100644 --- a/crates/biome_js_formatter/src/utils/jsx.rs +++ b/crates/biome_js_formatter/src/utils/jsx.rs @@ -183,7 +183,7 @@ impl Format for JsxRawSpace { QuoteStyle::Single => "{' '}", }; - write!(f, [text(jsx_space)]) + write!(f, [token(jsx_space)]) } } diff --git a/crates/biome_js_formatter/src/utils/member_chain/groups.rs b/crates/biome_js_formatter/src/utils/member_chain/groups.rs index 265c2be9d8fa..fda90e44c7cc 100644 --- a/crates/biome_js_formatter/src/utils/member_chain/groups.rs +++ b/crates/biome_js_formatter/src/utils/member_chain/groups.rs @@ -294,7 +294,7 @@ impl Format for FormatMemberChainGroup<'_> { let format_entries = format_with(|f| f.join().entries(group.members.iter()).finish()); if needs_parens { - write!(f, [text("("), format_entries, text(")")]) + write!(f, [token("("), format_entries, token(")")]) } else { write!(f, [format_entries]) } diff --git a/crates/biome_js_formatter/src/utils/mod.rs b/crates/biome_js_formatter/src/utils/mod.rs index b083ffc9a704..babfe236af63 100644 --- a/crates/biome_js_formatter/src/utils/mod.rs +++ b/crates/biome_js_formatter/src/utils/mod.rs @@ -264,7 +264,7 @@ impl Format for FormatSemicolon<'_> { }); if !is_after_bogus { - write!(f, [text(";")])?; + write!(f, [token(";")])?; } Ok(()) diff --git a/crates/biome_js_formatter/src/utils/test_each_template.rs b/crates/biome_js_formatter/src/utils/test_each_template.rs index ab5b053b1412..94ef81d11910 100644 --- a/crates/biome_js_formatter/src/utils/test_each_template.rs +++ b/crates/biome_js_formatter/src/utils/test_each_template.rs @@ -169,7 +169,7 @@ struct EachTemplateSeparator; impl Format for EachTemplateSeparator { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - write!(f, [text("|")]) + write!(f, [token("|")]) } } @@ -290,10 +290,10 @@ impl Format for EachTemplateTable { match element { EachTemplateElement::Column(column) => { - let mut text = column.text.clone(); + let mut column_text = column.text.clone(); - if current_column != 0 && (!is_last_in_row || !text.is_empty()) { - text = std::format!(" {text}"); + if current_column != 0 && (!is_last_in_row || !column_text.is_empty()) { + column_text = std::format!(" {column_text}"); } // align the column based on the maximum column width in the table @@ -312,13 +312,13 @@ impl Format for EachTemplateTable { .into(), ); - text.push_str(&padding); + column_text.push_str(&padding); } - text.push(' '); + column_text.push(' '); } - write!(f, [dynamic_text(&text, column.range.start())])?; + write!(f, [text(&column_text, column.range.start())])?; if !is_last_in_row { write!(f, [EachTemplateSeparator])?; diff --git a/crates/biome_js_formatter/src/verbatim.rs b/crates/biome_js_formatter/src/verbatim.rs index 4a4e415c8f91..0c125cdc21ac 100644 --- a/crates/biome_js_formatter/src/verbatim.rs +++ b/crates/biome_js_formatter/src/verbatim.rs @@ -1,7 +1,7 @@ use crate::context::JsFormatContext; use biome_formatter::format_element::tag::VerbatimKind; use biome_formatter::formatter::Formatter; -use biome_formatter::prelude::{Tag, dynamic_text}; +use biome_formatter::prelude::{Tag, text}; use biome_formatter::trivia::{FormatLeadingComments, FormatTrailingComments}; use biome_formatter::{ Buffer, CstFormatContext, Format, FormatContext, FormatElement, FormatError, FormatResult, @@ -115,7 +115,7 @@ impl Format for FormatJsVerbatimNode<'_> { }, ); - dynamic_text( + text( &normalize_newlines(&original_source, LINE_TERMINATORS), self.node.text_trimmed_range().start(), ) diff --git a/crates/biome_js_semantic/src/format_semantic_model.rs b/crates/biome_js_semantic/src/format_semantic_model.rs index 52993bc0f84b..154c2ba4ddf6 100644 --- a/crates/biome_js_semantic/src/format_semantic_model.rs +++ b/crates/biome_js_semantic/src/format_semantic_model.rs @@ -103,10 +103,10 @@ impl Format for Scope { write!( f, [ - text("id: "), + token("id: "), self.id, - text(" @ "), - dynamic_text(range.as_str(), TextSize::default()), + token(" @ "), + text(range.as_str(), TextSize::default()), hard_line_break() ] )?; @@ -119,14 +119,14 @@ impl Format for Scope { write!( f, [ - text("Scope {"), + token("Scope {"), group(&block_indent(&format_args![ formatted_scope_info, - text("children: ["), + token("children: ["), group(&block_indent(&formatted_children)), - text("]"), + token("]"), ])), - text("}"), + token("}"), hard_line_break(), ] )?; @@ -141,20 +141,20 @@ impl Format for Binding { write!( f, [ - text("id: "), + token("id: "), self.id, - text(" @ "), - dynamic_text(range.as_str(), TextSize::default()), + token(" @ "), + text(range.as_str(), TextSize::default()), hard_line_break() ] )?; - write!(f, [text("scope: "), self.scope().id, hard_line_break()])?; + write!(f, [token("scope: "), self.scope().id, hard_line_break()])?; let full_text = self.syntax().text_trimmed().into_text(); write!( f, [ - text("ident: "), - dynamic_text(&full_text, TextSize::default()), + token("ident: "), + text(&full_text, TextSize::default()), hard_line_break() ] )?; @@ -163,9 +163,9 @@ impl Format for Binding { write!( f, [ - text("Binding {"), + token("Binding {"), group(&block_indent(&formatted_binding_info)), - text("}"), + token("}"), hard_line_break(), ] )?; @@ -176,14 +176,14 @@ impl Format for Binding { impl Format for ScopeId { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - let text = std::format!("ScopeId({})", self.0); - write!(f, [dynamic_text(text.as_str(), TextSize::default())]) + let scope_text = std::format!("ScopeId({})", self.0); + write!(f, [text(scope_text.as_str(), TextSize::default())]) } } impl Format for BindingId { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - let text = std::format!("BindingId({})", self.0); - write!(f, [dynamic_text(text.as_str(), TextSize::default())]) + let binding_text = std::format!("BindingId({})", self.0); + write!(f, [text(binding_text.as_str(), TextSize::default())]) } } diff --git a/crates/biome_js_type_info/src/format_type_info.rs b/crates/biome_js_type_info/src/format_type_info.rs index 4d7a869705c8..c2e8f7471cab 100644 --- a/crates/biome_js_type_info/src/format_type_info.rs +++ b/crates/biome_js_type_info/src/format_type_info.rs @@ -84,19 +84,19 @@ impl std::fmt::Display for TypeData { impl Format for TypeData { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { match self { - Self::Unknown => write!(f, [text("unknown")]), - Self::Global => write!(f, [text("globalThis")]), - Self::BigInt => write!(f, [text("BigInt")]), - Self::Boolean => write!(f, [text("boolean")]), - Self::Null => write!(f, [text("null")]), - Self::Number => write!(f, [text("number")]), - Self::String => write!(f, [text("string")]), - Self::Symbol => write!(f, [text("symbol")]), - Self::Undefined => write!(f, [text("undefined")]), - Self::Conditional => write!(f, [text("conditional")]), + Self::Unknown => write!(f, [token("unknown")]), + Self::Global => write!(f, [token("globalThis")]), + Self::BigInt => write!(f, [token("BigInt")]), + Self::Boolean => write!(f, [token("boolean")]), + Self::Null => write!(f, [token("null")]), + Self::Number => write!(f, [token("number")]), + Self::String => write!(f, [token("string")]), + Self::Symbol => write!(f, [token("symbol")]), + Self::Undefined => write!(f, [token("undefined")]), + Self::Conditional => write!(f, [token("conditional")]), Self::ImportNamespace(module_id) => write!( f, - [dynamic_text( + [text( &std::format!("namespace for {module_id:?}"), TextSize::default() )] @@ -116,7 +116,7 @@ impl Format for TypeData { Self::Literal(ty) => write!(f, [&ty.as_ref()]), Self::InstanceOf(ty) => write!( f, - [&format_args![text("instanceof"), space(), &ty.as_ref()]] + [&format_args![token("instanceof"), space(), &ty.as_ref()]] ), Self::Reference(reference) => write!(f, [reference]), Self::MergedReference(reference) => write!(f, [reference.as_ref()]), @@ -124,18 +124,18 @@ impl Format for TypeData { Self::TypeofType(reference) => { write!( f, - [&format_args![text("typeof"), space(), reference.as_ref()]] + [&format_args![token("typeof"), space(), reference.as_ref()]] ) } Self::TypeofValue(ty) => { - write!(f, [&format_args![text("typeof"), space(), &ty.identifier]]) + write!(f, [&format_args![token("typeof"), space(), &ty.identifier]]) } - Self::AnyKeyword => write!(f, [text("any")]), - Self::NeverKeyword => write!(f, [text("never")]), - Self::ObjectKeyword => write!(f, [text("object")]), - Self::ThisKeyword => write!(f, [text("this")]), - Self::UnknownKeyword => write!(f, [text("unknown")]), - Self::VoidKeyword => write!(f, [text("void")]), + Self::AnyKeyword => write!(f, [token("any")]), + Self::NeverKeyword => write!(f, [token("never")]), + Self::ObjectKeyword => write!(f, [token("object")]), + Self::ThisKeyword => write!(f, [token("this")]), + Self::UnknownKeyword => write!(f, [token("unknown")]), + Self::VoidKeyword => write!(f, [token("void")]), } } } @@ -146,25 +146,25 @@ impl Format for Object { if let Some(prototype) = self.prototype.as_ref() { write!(f, [prototype]) } else { - write!(f, [text("No prototype")]) + write!(f, [token("No prototype")]) } }); write!( f, [&format_args![ - text("Object"), + token("Object"), space(), - text("{"), + token("{"), &group(&block_indent(&format_args![ - text("prototype:"), + token("prototype:"), space(), prototype, hard_line_break(), - text("members:"), + token("members:"), space(), FmtTypeMembers(self.members.as_ref()), ])), - text("}") + token("}") ]] ) } @@ -174,21 +174,15 @@ impl Format for Function { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { let is_async = format_with(|f| { if self.is_async { - write!(f, [&format_args![text("async")]]) + write!(f, [&format_args![token("async")]]) } else { - write!(f, [&format_args![text("sync")]]) + write!(f, [&format_args![token("sync")]]) } }); let name = format_with(|f| { if let Some(name) = &self.name { - write!( - f, - [dynamic_text( - &std::format!("\"{name}\""), - TextSize::default() - )] - ) + write!(f, [text(&std::format!("\"{name}\""), TextSize::default())]) } else { Ok(()) } @@ -199,32 +193,32 @@ impl Format for Function { [&format_args![ is_async, space(), - text("Function"), + token("Function"), space(), name, space(), - text("{"), + token("{"), &group(&soft_block_indent(&format_args![ - text("accepts:"), + token("accepts:"), space(), - text("{"), + token("{"), &group(&block_indent(&format_args![ - text("params:"), + token("params:"), space(), FmtFunctionParameters(&self.parameters), hard_line_break(), - text("type_args:"), + token("type_args:"), space(), FmtTypeReferences(&self.type_parameters), ])), - text("}"), + token("}"), hard_line_break(), - text("returns:"), + token("returns:"), space(), &self.return_type, space(), ])), - text("}"), + token("}"), ]] ) } @@ -255,9 +249,9 @@ impl Format for NamedFunctionParameter { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { let optional = format_with(|f| { if self.is_optional { - write!(f, [&format_args![text("optional")]]) + write!(f, [&format_args![token("optional")]]) } else { - write!(f, [&format_args![text("required")]]) + write!(f, [&format_args![token("required")]]) } }); write!( @@ -266,7 +260,7 @@ impl Format for NamedFunctionParameter { optional, space(), self.name, - text(":"), + token(":"), space(), &self.ty, ]))] @@ -282,10 +276,10 @@ impl Format for PatternFunctionParameter { f, [&format_args![ space(), - text("(bindings:"), + token("(bindings:"), space(), FmtFunctionParameterBindings(&self.bindings), - text(")") + token(")") ]] ) } else { @@ -296,9 +290,9 @@ impl Format for PatternFunctionParameter { write!( f, [&group(&format_args![ - text("..."), + token("..."), bindings, - text(":"), + token(":"), space(), &self.ty, ])] @@ -306,9 +300,9 @@ impl Format for PatternFunctionParameter { } else { let optional = format_with(|f| { if self.is_optional { - write!(f, [&format_args![text("optional")]]) + write!(f, [&format_args![token("optional")]]) } else { - write!(f, [&format_args![text("required")]]) + write!(f, [&format_args![token("required")]]) } }); write!( @@ -317,7 +311,7 @@ impl Format for PatternFunctionParameter { optional, space(), bindings, - text(":"), + token(":"), space(), &self.ty ]))] @@ -332,7 +326,7 @@ impl Format for TypeMember { f, [&format_args![ &self.kind, - text(":"), + token(":"), space(), &group(&soft_block_indent(&self.ty)), ]] @@ -343,22 +337,22 @@ impl Format for TypeMember { impl Format for TypeMemberKind { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { match self { - Self::CallSignature => write!(f, [text("()")]), - Self::Constructor => write!(f, [text("constructor")]), + Self::CallSignature => write!(f, [token("()")]), + Self::Constructor => write!(f, [token("constructor")]), Self::Getter(name) => { let quoted = std::format!("get \"{name}\""); - write!(f, [dynamic_text("ed, TextSize::default())]) + write!(f, [text("ed, TextSize::default())]) } Self::IndexSignature(ty) => { - write!(f, [text("["), ty, text("]")]) + write!(f, [token("["), ty, token("]")]) } Self::Named(name) => { let quoted = std::format!("\"{name}\""); - write!(f, [dynamic_text("ed, TextSize::default())]) + write!(f, [text("ed, TextSize::default())]) } Self::NamedStatic(name) => { let quoted = std::format!("static \"{name}\""); - write!(f, [dynamic_text("ed, TextSize::default())]) + write!(f, [text("ed, TextSize::default())]) } } } @@ -388,7 +382,7 @@ impl Format for TypeofExpression { [&group(&format_args![ &addition.left, soft_line_break_or_space(), - text("+"), + token("+"), soft_line_break_or_space(), &addition.right, ])] @@ -398,26 +392,26 @@ impl Format for TypeofExpression { write!( f, [&format_args![ - text("Await"), - text("("), + token("Await"), + token("("), group(&soft_block_indent(await_expression)), - text(")") + token(")") ]] ) } Self::BitwiseNot(expr) => { - write!(f, [&format_args![text("~"), &expr.argument]]) + write!(f, [&format_args![token("~"), &expr.argument]]) } Self::Call(call) => { write!( f, [&format_args![ - text("Call"), + token("Call"), space(), call.callee, - text("("), + token("("), group(&soft_block_indent(&FmtCallArgumentType(&call.arguments))), - text(")") + token(")") ]] ) } @@ -427,11 +421,11 @@ impl Format for TypeofExpression { [&group(&format_args![ &conditional.test, soft_line_break_or_space(), - text("?"), + token("?"), soft_line_break_or_space(), &conditional.consequent, soft_line_break_or_space(), - text(":"), + token(":"), soft_line_break_or_space(), &conditional.alternate ])] @@ -443,24 +437,24 @@ impl Format for TypeofExpression { f, [&format_args![ destructure.ty, - text("["), - dynamic_text(&index.to_string(), TextSize::default()), - text("]") + token("["), + text(&index.to_string(), TextSize::default()), + token("]") ]] ) } DestructureField::Name(name) => { - write!(f, [&format_args![destructure.ty, text("."), name]]) + write!(f, [&format_args![destructure.ty, token("."), name]]) } DestructureField::RestExcept(names) => { write!( f, [&format_args![ - text("{"), + token("{"), FmtNames(names), - text("..."), + token("..."), destructure.ty, - text("}") + token("}") ]] ) } @@ -468,11 +462,11 @@ impl Format for TypeofExpression { write!( f, [&format_args![ - text("["), - dynamic_text(&std::format!("({index} others)"), TextSize::default()), - text("..."), + token("["), + text(&std::format!("({index} others)"), TextSize::default()), + token("..."), destructure.ty, - text("]") + token("]") ]] ) } @@ -482,7 +476,7 @@ impl Format for TypeofExpression { f, [&format_args![ &expr.object, - dynamic_text(&std::format!("[{}]", expr.index), TextSize::default()), + text(&std::format!("[{}]", expr.index), TextSize::default()), ]] ) } @@ -490,7 +484,7 @@ impl Format for TypeofExpression { write!( f, [&format_args![&group(&format_args![ - text("iterable_value_of"), + token("iterable_value_of"), soft_line_break_or_space(), &expr.ty ])]] @@ -502,7 +496,7 @@ impl Format for TypeofExpression { [&format_args![&group(&format_args![ &expr.left, soft_line_break_or_space(), - text("&&"), + token("&&"), soft_line_break_or_space(), &expr.right ])]] @@ -514,14 +508,14 @@ impl Format for TypeofExpression { [&format_args![&group(&format_args![ &expr.left, soft_line_break_or_space(), - text("||"), + token("||"), soft_line_break_or_space(), &expr.right ])]] ) } Self::New(expr) => { - write!(f, [&format_args![text("new"), space(), &expr.callee]]) + write!(f, [&format_args![token("new"), space(), &expr.callee]]) } Self::NullishCoalescing(expr) => { write!( @@ -529,22 +523,22 @@ impl Format for TypeofExpression { [&format_args![&group(&format_args![ &expr.left, soft_line_break_or_space(), - text("??"), + token("??"), soft_line_break_or_space(), &expr.right ])]] ) } Self::StaticMember(expr) => { - write!(f, [&format_args![&expr.object, text("."), &expr.member]]) + write!(f, [&format_args![&expr.object, token("."), &expr.member]]) } - Self::Super(_) => write!(f, [&format_args![text("super")]]), - Self::This(_) => write!(f, [&format_args![text("this")]]), + Self::Super(_) => write!(f, [&format_args![token("super")]]), + Self::This(_) => write!(f, [&format_args![token("this")]]), Self::Typeof(expr) => { - write!(f, [&format_args![text("typeof"), space(), &expr.argument]]) + write!(f, [&format_args![token("typeof"), space(), &expr.argument]]) } Self::UnaryMinus(expr) => { - write!(f, [&format_args![text("-"), &expr.argument]]) + write!(f, [&format_args![token("-"), &expr.argument]]) } } } @@ -554,7 +548,7 @@ impl Format for GenericTypeParameter { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { let constraint = format_with(|f| { if self.constraint.is_known() { - write!(f, [space(), text("extends"), space(), &self.constraint]) + write!(f, [space(), token("extends"), space(), &self.constraint]) } else { Ok(()) } @@ -562,7 +556,7 @@ impl Format for GenericTypeParameter { let default = format_with(|f| { if self.default.is_known() { - write!(f, [space(), text("="), space(), &self.constraint]) + write!(f, [space(), token("="), space(), &self.constraint]) } else { Ok(()) } @@ -571,7 +565,7 @@ impl Format for GenericTypeParameter { write!( f, [&format_args![ - dynamic_text(&self.name, TextSize::default()), + text(&self.name, TextSize::default()), constraint, default ]] ) @@ -585,7 +579,7 @@ impl Format for TypeReference { write!( f, [&format_args![ - text("unresolved reference"), + token("unresolved reference"), space(), qualifier.as_ref() ]] @@ -596,7 +590,7 @@ impl Format for TypeReference { let id = resolved.id(); if level == TypeResolverLevel::Global { if resolved.index() < NUM_PREDEFINED_TYPES { - write!(f, [text(global_type_name(id))]) + write!(f, [token(global_type_name(id))]) } else { // Start counting from `NUM_PREDEFINED_TYPES` so // snapshots remain stable even if we add new predefined @@ -605,9 +599,9 @@ impl Format for TypeReference { write!( f, [&format_args![ - text("Global"), + token("Global"), space(), - dynamic_text(&std::format!("{id:?}"), TextSize::default()), + text(&std::format!("{id:?}"), TextSize::default()), ]] ) } @@ -616,18 +610,18 @@ impl Format for TypeReference { write!( f, [&format_args![ - dynamic_text(&std::format!("Module({module_id})"), TextSize::default()), + text(&std::format!("Module({module_id})"), TextSize::default()), space(), - dynamic_text(&std::format!("{id:?}"), TextSize::default()), + text(&std::format!("{id:?}"), TextSize::default()), ]] ) } else { write!( f, [&format_args![ - dynamic_text(&std::format!("{level:?}"), TextSize::default()), + text(&std::format!("{level:?}"), TextSize::default()), space(), - dynamic_text(&std::format!("{id:?}"), TextSize::default()), + text(&std::format!("{id:?}"), TextSize::default()), ]] ) } @@ -643,14 +637,14 @@ impl Format for TypeReferenceQualifier { if self.type_parameters.is_empty() { Ok(()) } else { - write!(f, [text("<")])?; + write!(f, [token("<")])?; for (index, param) in self.type_parameters.iter().enumerate() { write!(f, [param])?; if index != self.type_parameters.len() - 1 { - write!(f, [text(","), space()])?; + write!(f, [token(","), space()])?; } } - write!(f, [text(">")]) + write!(f, [token(">")]) } }); @@ -659,7 +653,7 @@ impl Format for TypeReferenceQualifier { f, [&format_args![ space(), - dynamic_text( + text( &std::format!("(scope ID: {})", self.scope_id.index()), TextSize::default() ) @@ -667,14 +661,14 @@ impl Format for TypeReferenceQualifier { ) }); - write!(f, [text("\"")])?; + write!(f, [token("\"")])?; for (index, part) in self.path.iter().enumerate() { - write!(f, [dynamic_text(part, TextSize::default())])?; + write!(f, [text(part, TextSize::default())])?; if index != self.path.len() - 1 { - write!(f, [text(".")])?; + write!(f, [token(".")])?; } } - write!(f, [text("\""), type_args, scope_id])?; + write!(f, [token("\""), type_args, scope_id])?; Ok(()) } } @@ -686,7 +680,7 @@ impl Format for TypeImportQualifier { [ self.symbol, space(), - text("from"), + token("from"), space(), self.resolved_path ] @@ -699,21 +693,21 @@ impl Format for MergedReference { write!( f, [&format_args![ - text("("), - text("type:"), + token("("), + token("type:"), space(), &self.ty, - text(","), + token(","), space(), - text("value:"), + token("value:"), space(), &self.value_ty, - text(","), + token(","), space(), - text("namespace:"), + token("namespace:"), space(), &self.namespace_ty, - text(")") + token(")") ]] ) } @@ -723,13 +717,7 @@ impl Format for Class { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { let name = format_with(|f| { if let Some(name) = &self.name { - write!( - f, - [dynamic_text( - &std::format!("\"{name}\""), - TextSize::default() - )] - ) + write!(f, [text(&std::format!("\"{name}\""), TextSize::default())]) } else { Ok(()) } @@ -738,32 +726,32 @@ impl Format for Class { if let Some(extends) = &self.extends { write!(f, [extends]) } else { - write!(f, [text("none")]) + write!(f, [token("none")]) } }); write!( f, [&format_args![ - text("class"), + token("class"), space(), name, space(), - text("{"), + token("{"), &group(&block_indent(&format_args![ - text("extends:"), + token("extends:"), space(), extends, hard_line_break(), - text("implements:"), + token("implements:"), space(), FmtTypeReferences(self.implements.as_ref()), hard_line_break(), - text("type_args:"), + token("type_args:"), space(), FmtTypeReferences(&self.type_parameters), ])), - text("}") + token("}") ]] ) } @@ -774,25 +762,25 @@ impl Format for Interface { write!( f, [&format_args![ - text("interface"), + token("interface"), space(), - dynamic_text(&std::format!("\"{}\"", self.name), TextSize::default()), + text(&std::format!("\"{}\"", self.name), TextSize::default()), space(), - text("{"), + token("{"), &group(&block_indent(&format_args![ - text("extends:"), + token("extends:"), space(), FmtTypeReferences(self.extends.as_ref()), hard_line_break(), - text("type_args:"), + token("type_args:"), space(), FmtTypeReferences(&self.type_parameters), hard_line_break(), - text("members:"), + token("members:"), space(), FmtTypeMembers(self.members.as_ref()), ])), - text("}") + token("}") ]] ) } @@ -800,23 +788,23 @@ impl Format for Interface { impl Format for Literal { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - write!(f, [&format_args![text("value:"), space()]])?; + write!(f, [&format_args![token("value:"), space()]])?; match self { - Self::BigInt(text) => write!(f, [dynamic_text(text, TextSize::default())]), + Self::BigInt(bigint_text) => write!(f, [text(bigint_text, TextSize::default())]), Self::Boolean(lit) => write!( f, - [dynamic_text( + [text( lit.as_bool().to_string().as_str(), TextSize::default() )] ), Self::Number(lit) => { - write!(f, [dynamic_text(lit.as_str(), TextSize::default())]) + write!(f, [text(lit.as_str(), TextSize::default())]) } Self::Object(obj) => write!(f, [&obj]), - Self::RegExp(text) => write!(f, [dynamic_text(text, TextSize::default())]), - Self::String(lit) => write!(f, [dynamic_text(lit.as_str(), TextSize::default())]), - Self::Template(text) => write!(f, [dynamic_text(text, TextSize::default())]), + Self::RegExp(regexp_text) => write!(f, [text(regexp_text, TextSize::default())]), + Self::String(lit) => write!(f, [text(lit.as_str(), TextSize::default())]), + Self::Template(template_text) => write!(f, [text(template_text, TextSize::default())]), } } } @@ -826,15 +814,15 @@ impl Format for ObjectLiteral { write!( f, [&format_args![ - text("ObjectLiteral"), + token("ObjectLiteral"), space(), - text("{"), + token("{"), &group(&soft_block_indent(&format_args![ - text("members:"), + token("members:"), space(), FmtTypeMembers(self.0.as_ref()) ])), - text("}") + token("}") ]] ) } @@ -846,14 +834,14 @@ impl Format for TypeInstance { if self.type_parameters.is_empty() { Ok(()) } else { - write!(f, [text("<")])?; + write!(f, [token("<")])?; for (index, param) in self.type_parameters.iter().enumerate() { write!(f, [param])?; if index != self.type_parameters.len() - 1 { - write!(f, [text(","), space()])?; + write!(f, [token(","), space()])?; } } - write!(f, [text(">")]) + write!(f, [token(">")]) } }); @@ -867,7 +855,7 @@ impl Format for Union { for (index, reference) in self.0.iter().enumerate() { write!(f, [&format_args![reference]])?; if index != self.0.len() - 1 { - write!(f, [space(), text("|"), space()])?; + write!(f, [space(), token("|"), space()])?; } } Ok(()) @@ -885,7 +873,7 @@ impl Format for ResolvedPath { let value = self.deref(); if let Ok(value) = value { let quoted = std::format!("\"{}\"", value.as_str().replace('\\', "/")); - write!(f, [dynamic_text("ed, TextSize::default())])?; + write!(f, [text("ed, TextSize::default())])?; } Ok(()) @@ -898,13 +886,16 @@ impl Format for ImportSymbol { f: &mut biome_formatter::formatter::Formatter, ) -> FormatResult<()> { let import = format_with(|f| match self { - Self::Default => write!(f, [text("Default")]), + Self::Default => write!(f, [token("Default")]), Self::Named(name) => { - write!(f, [dynamic_text(name, TextSize::default())]) + write!(f, [text(name, TextSize::default())]) } - Self::All => write!(f, [text("All")]), + Self::All => write!(f, [token("All")]), }); - write!(f, [&format_args![text("Import Symbol:"), space(), &import]]) + write!( + f, + [&format_args![token("Import Symbol:"), space(), &import]] + ) } } @@ -914,7 +905,7 @@ struct FmtFunctionParameters<'a>(&'a [FunctionParameter]); impl Format for FmtFunctionParameters<'_> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { if self.0.is_empty() { - return write!(f, [text("[]")]); + return write!(f, [token("[]")]); } let function_parameters = format_with(|f| { @@ -927,7 +918,7 @@ impl Format for FmtFunctionParameters<'_> { }); write!( f, - [&format_args![text("["), &function_parameters, text("]")]] + [&format_args![token("["), &function_parameters, token("]")]] ) } } @@ -941,10 +932,10 @@ impl Format for FmtFunctionParameterBindings<'_> { let function_parameters = format_with(|f| { let separator = - format_with(|f| write!(f, [&format_args![text(","), soft_line_break_or_space()]])); + format_with(|f| write!(f, [&format_args![token(","), soft_line_break_or_space()]])); let mut joiner = f.join_with(separator); for part in self.0 { - joiner.entry(&format_args![&part.name, text(":"), space(), &part.ty]); + joiner.entry(&format_args![&part.name, token(":"), space(), &part.ty]); } joiner.finish() }); @@ -956,11 +947,11 @@ struct FmtTypeMembers<'a>(&'a [TypeMember]); impl Format for FmtTypeMembers<'_> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - write!(f, [text("[")])?; + write!(f, [token("[")])?; let types = format_with(|f| { let separator = - format_with(|f| write!(f, [&format_args![text(","), soft_line_break_or_space()]])); + format_with(|f| write!(f, [&format_args![token(","), soft_line_break_or_space()]])); let mut joiner = f.join_with(separator); for part in self.0 { joiner.entry(&format_args![part]); @@ -969,7 +960,7 @@ impl Format for FmtTypeMembers<'_> { }); write!( f, - [&format_args![group(&soft_block_indent(&types)), text("]")]] + [&format_args![group(&soft_block_indent(&types)), token("]")]] ) } } @@ -978,11 +969,11 @@ struct FmtTypeReferences<'a>(&'a [TypeReference]); impl Format for FmtTypeReferences<'_> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - write!(f, [text("[")])?; + write!(f, [token("[")])?; let references = format_with(|f| { let separator = - format_with(|f| write!(f, [&format_args![text(","), soft_line_break_or_space()]])); + format_with(|f| write!(f, [&format_args![token(","), soft_line_break_or_space()]])); let mut joiner = f.join_with(separator); for part in self.0 { joiner.entry(&format_args![part]); @@ -993,7 +984,7 @@ impl Format for FmtTypeReferences<'_> { f, [&format_args![ group(&soft_block_indent(&references)), - text("]") + token("]") ]] ) } @@ -1001,7 +992,7 @@ impl Format for FmtTypeReferences<'_> { impl Format for Text { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - write!(f, [&format_args![dynamic_text(self, TextSize::default())]]) + write!(f, [&format_args![text(self, TextSize::default())]]) } } @@ -1013,7 +1004,7 @@ impl Format for FmtCallArgumentType<'_> { f: &mut biome_formatter::formatter::Formatter, ) -> FormatResult<()> { if self.0.is_empty() { - return write!(f, [text("No parameters")]); + return write!(f, [token("No parameters")]); } let type_parameters = format_with(|f| { @@ -1021,7 +1012,7 @@ impl Format for FmtCallArgumentType<'_> { for part in self.0 { match part { CallArgumentType::Argument(ty) => joiner.entry(&format_args![ty]), - CallArgumentType::Spread(ty) => joiner.entry(&format_args![text("..."), ty]), + CallArgumentType::Spread(ty) => joiner.entry(&format_args![token("..."), ty]), }; } joiner.finish() @@ -1059,10 +1050,10 @@ where T: Debug, { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - let text = std::format!("{:#?}", self.0); + let verbatim_text = std::format!("{:#?}", self.0); write!( f, - [&format_args![dynamic_text(&text, TextSize::default()),]] + [&format_args![text(&verbatim_text, TextSize::default()),]] ) } } diff --git a/crates/biome_jsdoc_comment/src/format_jsdoc_comment.rs b/crates/biome_jsdoc_comment/src/format_jsdoc_comment.rs index 49ec83f7245c..cbd3d412e52f 100644 --- a/crates/biome_jsdoc_comment/src/format_jsdoc_comment.rs +++ b/crates/biome_jsdoc_comment/src/format_jsdoc_comment.rs @@ -15,10 +15,7 @@ impl Format for JsdocComment { let comment = format_with(|f| { let mut joiner = f.join_with(hard_line_break()); comment.lines().for_each(|line| { - joiner.entry(&format_args![dynamic_text( - line.trim(), - TextSize::default() - ),]); + joiner.entry(&format_args![text(line.trim(), TextSize::default()),]); }); joiner.finish() }); @@ -26,10 +23,10 @@ impl Format for JsdocComment { write!( f, [&format_args![ - text("JsDoc"), - text("("), + token("JsDoc"), + token("("), block_indent(&comment), - text(")") + token(")") ]] ) } diff --git a/crates/biome_json_formatter/src/comments.rs b/crates/biome_json_formatter/src/comments.rs index bfd651727d39..f3adba00227e 100644 --- a/crates/biome_json_formatter/src/comments.rs +++ b/crates/biome_json_formatter/src/comments.rs @@ -30,7 +30,7 @@ impl FormatRule> for FormatJsonLeadingComment { // SAFETY: Safe, `is_alignable_comment` only returns `true` for multiline comments let first_line = lines.next().unwrap(); - write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?; + write!(f, [text(first_line.trim_end(), source_offset)])?; source_offset += first_line.text_len(); @@ -41,10 +41,7 @@ impl FormatRule> for FormatJsonLeadingComment { 1, &format_once(|f| { for line in lines { - write!( - f, - [hard_line_break(), dynamic_text(line.trim(), source_offset)] - )?; + write!(f, [hard_line_break(), text(line.trim(), source_offset)])?; source_offset += line.text_len(); } diff --git a/crates/biome_json_formatter/src/verbatim.rs b/crates/biome_json_formatter/src/verbatim.rs index b56264320175..6be09c9dd8c1 100644 --- a/crates/biome_json_formatter/src/verbatim.rs +++ b/crates/biome_json_formatter/src/verbatim.rs @@ -1,7 +1,7 @@ use crate::context::JsonFormatContext; use biome_formatter::format_element::tag::VerbatimKind; use biome_formatter::formatter::Formatter; -use biome_formatter::prelude::{Tag, dynamic_text}; +use biome_formatter::prelude::{Tag, text}; use biome_formatter::trivia::{FormatLeadingComments, FormatTrailingComments}; use biome_formatter::{ Buffer, CstFormatContext, Format, FormatContext, FormatElement, FormatError, FormatResult, @@ -114,7 +114,7 @@ impl Format for FormatJsonVerbatimNode<'_> { }, ); - dynamic_text( + text( &normalize_newlines(&original_source, LINE_TERMINATORS), self.node.text_trimmed_range().start(), ) diff --git a/crates/biome_module_graph/src/format_module_graph.rs b/crates/biome_module_graph/src/format_module_graph.rs index 1dd567620443..7b5f20081e52 100644 --- a/crates/biome_module_graph/src/format_module_graph.rs +++ b/crates/biome_module_graph/src/format_module_graph.rs @@ -27,7 +27,7 @@ impl Format for JsModuleInfo { ) -> FormatResult<()> { let exports = format_with(|f| { if self.exports.is_empty() { - write!(f, [text("No exports")]) + write!(f, [token("No exports")]) } else { write!(f, [&self.exports]) } @@ -35,7 +35,7 @@ impl Format for JsModuleInfo { let static_imports = format_with(|f| { if self.static_imports.is_empty() { - write!(f, [text("No imports")]) + write!(f, [token("No imports")]) } else { write!(f, [&self.static_imports]) } @@ -44,17 +44,17 @@ impl Format for JsModuleInfo { write!( f, [&format_args![ - text("Exports"), + token("Exports"), space(), - text("{"), + token("{"), &group(&block_indent(&exports)), - text("}"), + token("}"), hard_line_break(), - text("Imports"), + token("Imports"), space(), - text("{"), + token("{"), &group(&block_indent(&static_imports)), - text("}"), + token("}"), ]] ) } @@ -70,21 +70,21 @@ impl Format for Exports { let name = format_with(|f| { write!( f, - [dynamic_text( + [text( &std::format!("{:?}", export_name.text()), TextSize::default() ),] ) }); - let arrow = format_with(|f| write!(f, [&format_args![space(), text("=>"), space()]])); + let arrow = format_with(|f| write!(f, [&format_args![space(), token("=>"), space()]])); let export = format_with(|f| { write!( f, [&format_args![ - text("{"), + token("{"), &group(&block_indent(&format_args![export]),), - text("}") + token("}") ]] ) }); @@ -112,7 +112,7 @@ impl Format for Imports { let name = format_with(|f| { write!( f, - [dynamic_text( + [text( &std::format!("{:?}", import_name.text()), TextSize::default() ),] @@ -123,7 +123,7 @@ impl Format for Imports { f, [&format_args![ space(), - biome_formatter::prelude::text("=>"), + token("=>"), space() ]] ) @@ -133,9 +133,9 @@ impl Format for Imports { write!( f, [&format_args![ - text("{"), + token("{"), &group(&block_indent(&format_args![import]),), - text("}") + token("}") ]] ) }); @@ -157,15 +157,15 @@ impl Format for JsExport { &self, f: &mut biome_formatter::formatter::Formatter, ) -> FormatResult<()> { - write!(f, [text("Export")])?; + write!(f, [token("Export")])?; match self { Self::Own(export) => { write!( f, [&format_args![ - text("OwnExport"), + token("OwnExport"), space(), - text("=>"), + token("=>"), space(), &export ]] @@ -175,9 +175,9 @@ impl Format for JsExport { write!( f, [&format_args![ - text("OwnType"), + token("OwnType"), space(), - text("=>"), + token("=>"), space(), &own_type ]] @@ -187,9 +187,9 @@ impl Format for JsExport { write!( f, [&format_args![ - text("Reexport"), + token("Reexport"), space(), - text("=>"), + token("=>"), space(), &reexport ]] @@ -199,9 +199,9 @@ impl Format for JsExport { write!( f, [&format_args![ - text("ReexportType"), + token("ReexportType"), space(), - text("=>"), + token("=>"), space(), &reexport_type ]] @@ -234,10 +234,10 @@ impl Format for JsBindingData { write!( f, [&format_args![ - text("JSDoc comment:"), + token("JSDoc comment:"), space(), jsdoc, - text(","), + token(","), hard_line_break() ]] ) @@ -250,20 +250,20 @@ impl Format for JsBindingData { write!( f, [&format_args![ - text("Name:"), + token("Name:"), space(), - dynamic_text(&self.name, TextSize::default()), - text(","), + text(&self.name, TextSize::default()), + token(","), hard_line_break(), - text("Type:"), + token("Type:"), space(), &self.ty, - text(","), + token(","), hard_line_break(), jsdoc_comment, - text("Declaration kind:"), + token("Declaration kind:"), space(), - dynamic_text( + text( &std::format!("{:?}", self.declaration_kind), TextSize::default() ), @@ -274,9 +274,9 @@ impl Format for JsBindingData { write!( f, [&format_args![ - text("JsBindingData {"), + token("JsBindingData {"), block_indent(&content), - text("}") + token("}") ],] )?; @@ -302,10 +302,10 @@ impl Format for JsReexport { write!( f, [&format_args![ - text("Reexport"), - text("("), + token("Reexport"), + token("("), block_indent(&content), - text(")") + token(")") ],] )?; @@ -322,17 +322,17 @@ impl Format for JsOwnExport { Self::Binding(binding_id) => write!( f, [&format_args![ - text("JsOwnExport::Binding("), - dynamic_text(&binding_id.index().to_string(), TextSize::default()), - text(")") + token("JsOwnExport::Binding("), + text(&binding_id.index().to_string(), TextSize::default()), + token(")") ]] ), Self::Type(resolved_type_id) => write!( f, [&format_args![ - text("JsOwnExport::Type("), - dynamic_text(&std::format!("{resolved_type_id:?}"), TextSize::default()), - text(")") + token("JsOwnExport::Type("), + text(&std::format!("{resolved_type_id:?}"), TextSize::default()), + token(")") ]] ), } @@ -347,9 +347,9 @@ impl Format for JsImport { write!( f, [&format_args![ - text("Specifier:"), + token("Specifier:"), space(), - dynamic_text( + text( &std::format!("{:?}", self.specifier.text()), TextSize::default() ), @@ -360,7 +360,7 @@ impl Format for JsImport { write!( f, [&format_args![ - text("Resolved path:"), + token("Resolved path:"), space(), self.resolved_path ]] From edd7a45ed58fe74dd10780bc5209207e2f547153 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Mon, 3 Nov 2025 14:39:08 +0000 Subject: [PATCH 2/2] [autofix.ci] apply automated fixes --- crates/biome_module_graph/src/format_module_graph.rs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/crates/biome_module_graph/src/format_module_graph.rs b/crates/biome_module_graph/src/format_module_graph.rs index 7b5f20081e52..c4b7c6ec6961 100644 --- a/crates/biome_module_graph/src/format_module_graph.rs +++ b/crates/biome_module_graph/src/format_module_graph.rs @@ -118,16 +118,7 @@ impl Format for Imports { ),] ) }); - let arrow = format_with(|f| { - write!( - f, - [&format_args![ - space(), - token("=>"), - space() - ]] - ) - }); + let arrow = format_with(|f| write!(f, [&format_args![space(), token("=>"), space()]])); let export = format_with(|f| { write!(