diff --git a/crates/ruff_formatter/src/builders.rs b/crates/ruff_formatter/src/builders.rs index c3e1c87aefd86f..f79bd6acc4fae2 100644 --- a/crates/ruff_formatter/src/builders.rs +++ b/crates/ruff_formatter/src/builders.rs @@ -251,29 +251,29 @@ impl std::fmt::Debug for Line { /// # } /// ``` #[inline] -pub fn token(text: &'static str) -> StaticText { +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::Token { text: self.text }); Ok(()) } } -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) } @@ -336,25 +336,25 @@ impl Format for SourcePosition { /// Creates a text from a dynamic string with its optional start-position in the source document. /// This is done by allocating a new string internally. -pub fn dynamic_text(text: &str, position: Option) -> DynamicText { +pub fn text(text: &str, position: Option) -> 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: Option, } -impl Format for DynamicText<'_> { +impl Format for Text<'_> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { if let Some(source_position) = self.position { f.write_element(FormatElement::SourcePosition(source_position)); } - f.write_element(FormatElement::DynamicText { + f.write_element(FormatElement::Text { text: self.text.to_string().into_boxed_str(), }); @@ -362,7 +362,7 @@ impl Format for DynamicText<'_> { } } -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) } @@ -2167,7 +2167,7 @@ impl std::fmt::Debug for FormatWith { /// let mut join = f.join_with(&separator); /// /// for item in &self.items { -/// join.entry(&format_with(|f| write!(f, [dynamic_text(item, None)]))); +/// join.entry(&format_with(|f| write!(f, [text(item, None)]))); /// } /// join.finish() /// })), @@ -2212,7 +2212,7 @@ where /// /// struct MyFormat; /// -/// fn generate_values() -> impl Iterator { +/// fn generate_values() -> impl Iterator { /// vec![token("1"), token("2"), token("3"), token("4")].into_iter() /// } /// diff --git a/crates/ruff_formatter/src/format_element.rs b/crates/ruff_formatter/src/format_element.rs index 47e30b47b04084..ee927292cd40c3 100644 --- a/crates/ruff_formatter/src/format_element.rs +++ b/crates/ruff_formatter/src/format_element.rs @@ -33,9 +33,8 @@ pub enum FormatElement { /// 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. - 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, }, @@ -73,9 +72,7 @@ impl std::fmt::Debug for FormatElement { FormatElement::Line(mode) => fmt.debug_tuple("Line").field(mode).finish(), FormatElement::ExpandParent => write!(fmt, "ExpandParent"), FormatElement::Token { text } => fmt.debug_tuple("Token").field(text).finish(), - FormatElement::DynamicText { text, .. } => { - fmt.debug_tuple("DynamicText").field(text).finish() - } + FormatElement::Text { text, .. } => fmt.debug_tuple("DynamicText").field(text).finish(), FormatElement::SourceCodeSlice { slice, contains_newlines, @@ -242,7 +239,7 @@ impl FormatElement { matches!( self, FormatElement::SourceCodeSlice { .. } - | FormatElement::DynamicText { .. } + | FormatElement::Text { .. } | FormatElement::Token { .. } ) } @@ -259,7 +256,7 @@ impl FormatElements for FormatElement { FormatElement::Tag(Tag::StartGroup(group)) => !group.mode().is_flat(), FormatElement::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty), - FormatElement::DynamicText { text, .. } => text.contains('\n'), + FormatElement::Text { text, .. } => text.contains('\n'), FormatElement::SourceCodeSlice { contains_newlines, .. } => *contains_newlines, diff --git a/crates/ruff_formatter/src/format_element/document.rs b/crates/ruff_formatter/src/format_element/document.rs index fc7c43aa75c5ba..ae6761296c4d15 100644 --- a/crates/ruff_formatter/src/format_element/document.rs +++ b/crates/ruff_formatter/src/format_element/document.rs @@ -104,7 +104,7 @@ impl Document { expands = false; continue; } - FormatElement::DynamicText { text, .. } => text.contains('\n'), + FormatElement::Text { text, .. } => text.contains('\n'), FormatElement::SourceCodeSlice { contains_newlines, .. } => *contains_newlines, @@ -256,12 +256,12 @@ impl Format> for &[FormatElement] { match element { element @ (FormatElement::Space | FormatElement::Token { .. } - | FormatElement::DynamicText { .. } + | FormatElement::Text { .. } | FormatElement::SourceCodeSlice { .. }) => { fn write_escaped(element: &FormatElement, f: &mut Formatter) { let text = match element { FormatElement::Token { text } => text, - FormatElement::DynamicText { text } => text.as_ref(), + FormatElement::Text { text } => text.as_ref(), FormatElement::SourceCodeSlice { slice, .. } => { slice.text(f.context().source_code()) } @@ -269,7 +269,7 @@ impl Format> for &[FormatElement] { }; if text.contains('"') { - f.write_element(FormatElement::DynamicText { + f.write_element(FormatElement::Text { text: text.replace('"', r#"\""#).into(), }); } else { @@ -322,10 +322,7 @@ impl Format> for &[FormatElement] { FormatElement::SourcePosition(position) => { write!( f, - [dynamic_text( - &std::format!("source_position({position:?})"), - None - )] + [text(&std::format!("source_position({position:?})"), None)] )?; } @@ -352,7 +349,7 @@ impl Format> for &[FormatElement] { write!(f, [token("]")])?; if *mode != BestFittingMode::FirstLine { - write!(f, [dynamic_text(&std::format!(", mode: {mode:?}"), None),])?; + write!(f, [text(&std::format!(", mode: {mode:?}"), None),])?; } write!(f, [token(")")])?; @@ -369,7 +366,7 @@ impl Format> for &[FormatElement] { write!( f, [ - dynamic_text(&std::format!(""), None), + text(&std::format!(""), None), space(), &&**interned, ] @@ -378,10 +375,7 @@ impl Format> for &[FormatElement] { Some(reference) => { write!( f, - [dynamic_text( - &std::format!(""), - None - )] + [text(&std::format!(""), None)] )?; } } @@ -401,7 +395,7 @@ impl Format> for &[FormatElement] { f, [ token(">"), ] )?; @@ -416,9 +410,9 @@ impl Format> for &[FormatElement] { token(")"), soft_line_break_or_space(), token("ERROR>") ] )?; @@ -450,7 +444,7 @@ impl Format> for &[FormatElement] { f, [ token("align("), - dynamic_text(&count.to_string(), None), + text(&count.to_string(), None), token(","), space(), ] @@ -462,7 +456,7 @@ impl Format> for &[FormatElement] { f, [ token("line_suffix("), - dynamic_text(&std::format!("{reserved_width:?}"), None), + text(&std::format!("{reserved_width:?}"), None), token(","), space(), ] @@ -480,7 +474,7 @@ impl Format> for &[FormatElement] { write!( f, [ - dynamic_text(&std::format!("\"{group_id:?}\""), None), + text(&std::format!("\"{group_id:?}\""), None), token(","), space(), ] @@ -526,7 +520,7 @@ impl Format> for &[FormatElement] { f, [ token("indent_if_group_breaks("), - dynamic_text(&std::format!("\"{id:?}\""), None), + text(&std::format!("\"{id:?}\""), None), token(","), space(), ] @@ -547,7 +541,7 @@ impl Format> for &[FormatElement] { write!( f, [ - dynamic_text(&std::format!("\"{group_id:?}\""), None), + text(&std::format!("\"{group_id:?}\""), None), token(","), space(), ] @@ -560,7 +554,7 @@ impl Format> for &[FormatElement] { f, [ token("label("), - dynamic_text(&std::format!("\"{label_id:?}\""), None), + text(&std::format!("\"{label_id:?}\""), None), token(","), space(), ] @@ -628,7 +622,7 @@ impl Format> for &[FormatElement] { ContentArrayEnd, token(")"), soft_line_break_or_space(), - dynamic_text(&std::format!(">"), None), + text(&std::format!(">"), None), ] )?; } @@ -771,7 +765,7 @@ impl Format> for Condition { f, [ token("if_group_fits_on_line("), - dynamic_text(&std::format!("\"{id:?}\""), None), + text(&std::format!("\"{id:?}\""), None), token(")") ] ), @@ -780,7 +774,7 @@ impl Format> for Condition { f, [ token("if_group_breaks("), - dynamic_text(&std::format!("\"{id:?}\""), None), + text(&std::format!("\"{id:?}\""), None), token(")") ] ), diff --git a/crates/ruff_formatter/src/format_extensions.rs b/crates/ruff_formatter/src/format_extensions.rs index 4ba5441f644786..6c2aa85e199b9b 100644 --- a/crates/ruff_formatter/src/format_extensions.rs +++ b/crates/ruff_formatter/src/format_extensions.rs @@ -34,7 +34,7 @@ pub trait MemoizeFormat { /// let value = self.value.get(); /// self.value.set(value + 1); /// - /// write!(f, [dynamic_text(&std::format!("Formatted {value} times."), None)]) + /// write!(f, [text(&std::format!("Formatted {value} times."), None)]) /// } /// } /// @@ -112,7 +112,7 @@ where /// write!(f, [ /// token("Count:"), /// space(), - /// dynamic_text(&std::format!("{current}"), None), + /// text(&std::format!("{current}"), None), /// hard_line_break() /// ])?; /// diff --git a/crates/ruff_formatter/src/lib.rs b/crates/ruff_formatter/src/lib.rs index e5ba8e426f4bad..a90788e1e4be08 100644 --- a/crates/ruff_formatter/src/lib.rs +++ b/crates/ruff_formatter/src/lib.rs @@ -455,7 +455,7 @@ pub type FormatResult = Result; /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { /// write!(f, [ /// hard_line_break(), -/// dynamic_text(&self.0, None), +/// text(&self.0, None), /// hard_line_break(), /// ]) /// } diff --git a/crates/ruff_formatter/src/printer/mod.rs b/crates/ruff_formatter/src/printer/mod.rs index 53531f3fbe250f..c732c125e8a9eb 100644 --- a/crates/ruff_formatter/src/printer/mod.rs +++ b/crates/ruff_formatter/src/printer/mod.rs @@ -97,7 +97,7 @@ impl<'a> Printer<'a> { match element { FormatElement::Space => self.print_text(Text::Token(" "), None), FormatElement::Token { text } => self.print_text(Text::Token(text), None), - FormatElement::DynamicText { text } => self.print_text(Text::Text(text), None), + FormatElement::Text { text } => self.print_text(Text::Text(text), None), FormatElement::SourceCodeSlice { slice, .. } => { let text = slice.text(self.source_code); self.print_text(Text::Text(text), Some(slice.range())); @@ -1087,9 +1087,7 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> { } FormatElement::Token { text } => return Ok(self.fits_text(Text::Token(text), args)), - FormatElement::DynamicText { text, .. } => { - return Ok(self.fits_text(Text::Text(text), args)) - } + FormatElement::Text { text, .. } => return Ok(self.fits_text(Text::Text(text), args)), FormatElement::SourceCodeSlice { slice, .. } => { let text = slice.text(self.printer.source_code); return Ok(self.fits_text(Text::Text(text), args)); @@ -1541,10 +1539,7 @@ a"#, let result = format_with_options( &format_args![ token("function main() {"), - block_indent(&dynamic_text( - "let x = `This is a multiline\nstring`;", - None - )), + block_indent(&text("let x = `This is a multiline\nstring`;", None)), token("}"), hard_line_break() ], @@ -1561,7 +1556,7 @@ a"#, fn it_breaks_a_group_if_a_string_contains_a_newline() { let result = format(&FormatArrayElements { items: vec![ - &dynamic_text("`This is a string spanning\ntwo lines`", None), + &text("`This is a string spanning\ntwo lines`", None), &token("\"b\""), ], }); diff --git a/crates/ruff_python_formatter/src/comments/format.rs b/crates/ruff_python_formatter/src/comments/format.rs index e682924284d56c..edfe74588bdba9 100644 --- a/crates/ruff_python_formatter/src/comments/format.rs +++ b/crates/ruff_python_formatter/src/comments/format.rs @@ -434,7 +434,7 @@ impl Format> for FormatNormalizedComment<'_> { write!( f, [ - dynamic_text(owned, Some(self.range.start())), + text(owned, Some(self.range.start())), source_position(self.range.end()) ] ) diff --git a/crates/ruff_python_formatter/src/expression/number.rs b/crates/ruff_python_formatter/src/expression/number.rs index 05ce8a1caeb7e8..8bf6d266a8b321 100644 --- a/crates/ruff_python_formatter/src/expression/number.rs +++ b/crates/ruff_python_formatter/src/expression/number.rs @@ -25,7 +25,7 @@ impl Format> for FormatInt<'_> { match normalized { Cow::Borrowed(_) => source_text_slice(range, ContainsNewlines::No).fmt(f), - Cow::Owned(normalized) => dynamic_text(&normalized, Some(range.start())).fmt(f), + Cow::Owned(normalized) => text(&normalized, Some(range.start())).fmt(f), } } } @@ -50,7 +50,7 @@ impl Format> for FormatFloat<'_> { match normalized { Cow::Borrowed(_) => source_text_slice(range, ContainsNewlines::No).fmt(f), - Cow::Owned(normalized) => dynamic_text(&normalized, Some(range.start())).fmt(f), + Cow::Owned(normalized) => text(&normalized, Some(range.start())).fmt(f), } } } @@ -78,7 +78,7 @@ impl Format> for FormatComplex<'_> { source_text_slice(range.sub_end(TextSize::from(1)), ContainsNewlines::No).fmt(f)?; } Cow::Owned(normalized) => { - dynamic_text(&normalized, Some(range.start())).fmt(f)?; + text(&normalized, Some(range.start())).fmt(f)?; } } diff --git a/crates/ruff_python_formatter/src/expression/string.rs b/crates/ruff_python_formatter/src/expression/string.rs index 528fe9c17b47f4..e6165942ba9f40 100644 --- a/crates/ruff_python_formatter/src/expression/string.rs +++ b/crates/ruff_python_formatter/src/expression/string.rs @@ -326,7 +326,7 @@ impl Format> for FormatStringPart { source_text_slice(self.range(), contains_newlines).fmt(f)?; } Cow::Owned(normalized) => { - dynamic_text(&normalized, Some(self.start())).fmt(f)?; + text(&normalized, Some(self.start())).fmt(f)?; } } self.preferred_quotes.fmt(f) @@ -839,7 +839,7 @@ fn format_docstring(string_part: &FormatStringPart, f: &mut PyFormatter) -> Form if already_normalized { source_text_slice(trimmed_line_range, ContainsNewlines::No).fmt(f)?; } else { - dynamic_text(trim_both, Some(trimmed_line_range.start())).fmt(f)?; + text(trim_both, Some(trimmed_line_range.start())).fmt(f)?; } } offset += first.text_len(); @@ -947,7 +947,7 @@ fn format_docstring_line( let indent_len = count_indentation_like_black(trim_end, f.options().tab_width()) - stripped_indentation; let in_docstring_indent = " ".repeat(indent_len.to_usize()) + trim_end.trim_start(); - dynamic_text(&in_docstring_indent, Some(offset)).fmt(f)?; + text(&in_docstring_indent, Some(offset)).fmt(f)?; } else { // Take the string with the trailing whitespace removed, then also skip the leading // whitespace @@ -957,7 +957,7 @@ fn format_docstring_line( source_text_slice(trimmed_line_range, ContainsNewlines::No).fmt(f)?; } else { // All indents are ascii spaces, so the slicing is correct - dynamic_text( + text( &trim_end[stripped_indentation.to_usize()..], Some(trimmed_line_range.start()), ) diff --git a/crates/ruff_python_formatter/src/lib.rs b/crates/ruff_python_formatter/src/lib.rs index 5ecaf3dd012824..98ab2a19d8e621 100644 --- a/crates/ruff_python_formatter/src/lib.rs +++ b/crates/ruff_python_formatter/src/lib.rs @@ -293,7 +293,7 @@ for converter in connection.ops.get_db_converters( while let Some(word) = words.next() { let is_last = words.peek().is_none(); let format_word = format_with(|f| { - write!(f, [dynamic_text(word, None)])?; + write!(f, [text(word, None)])?; if is_last { write!(f, [token("\"")])?; diff --git a/crates/ruff_python_formatter/src/statement/stmt_import_from.rs b/crates/ruff_python_formatter/src/statement/stmt_import_from.rs index e887778091929f..6f6c87fb8a3ca0 100644 --- a/crates/ruff_python_formatter/src/statement/stmt_import_from.rs +++ b/crates/ruff_python_formatter/src/statement/stmt_import_from.rs @@ -29,7 +29,7 @@ impl FormatNodeRule for FormatStmtImportFrom { [ token("from"), space(), - dynamic_text(&level_str, None), + text(&level_str, None), module.as_ref().map(AsFormat::format), space(), token("import"), diff --git a/crates/ruff_python_formatter/src/verbatim.rs b/crates/ruff_python_formatter/src/verbatim.rs index f50aac90a90e02..f40723de99ee77 100644 --- a/crates/ruff_python_formatter/src/verbatim.rs +++ b/crates/ruff_python_formatter/src/verbatim.rs @@ -871,7 +871,7 @@ impl Format> for VerbatimText { write!( f, [ - dynamic_text(&cleaned, Some(self.verbatim_range.start())), + text(&cleaned, Some(self.verbatim_range.start())), source_position(self.verbatim_range.end()) ] )?;