Skip to content

Commit

Permalink
Rename DynamicText to Text
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser committed Sep 1, 2023
1 parent e1e047f commit e400e58
Show file tree
Hide file tree
Showing 12 changed files with 56 additions and 70 deletions.
26 changes: 13 additions & 13 deletions crates/ruff_formatter/src/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Context> Format<Context> for StaticText {
impl<Context> Format<Context> for Token {
fn fmt(&self, f: &mut Formatter<Context>) -> 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)
}
Expand Down Expand Up @@ -336,33 +336,33 @@ impl<Context> Format<Context> 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<TextSize>) -> DynamicText {
pub fn text(text: &str, position: Option<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: Option<TextSize>,
}

impl<Context> Format<Context> for DynamicText<'_> {
impl<Context> Format<Context> for Text<'_> {
fn fmt(&self, f: &mut Formatter<Context>) -> 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(),
});

Ok(())
}
}

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)
}
Expand Down Expand Up @@ -2167,7 +2167,7 @@ impl<Context, T> std::fmt::Debug for FormatWith<Context, T> {
/// 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()
/// })),
Expand Down Expand Up @@ -2212,7 +2212,7 @@ where
///
/// struct MyFormat;
///
/// fn generate_values() -> impl Iterator<Item=StaticText> {
/// fn generate_values() -> impl Iterator<Item=Token> {
/// vec![token("1"), token("2"), token("3"), token("4")].into_iter()
/// }
///
Expand Down
13 changes: 5 additions & 8 deletions crates/ruff_formatter/src/format_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<str>` safes 8 bytes over `String`.
text: Box<str>,
},
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -242,7 +239,7 @@ impl FormatElement {
matches!(
self,
FormatElement::SourceCodeSlice { .. }
| FormatElement::DynamicText { .. }
| FormatElement::Text { .. }
| FormatElement::Token { .. }
)
}
Expand All @@ -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,
Expand Down
46 changes: 20 additions & 26 deletions crates/ruff_formatter/src/format_element/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -256,20 +256,20 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
match element {
element @ (FormatElement::Space
| FormatElement::Token { .. }
| FormatElement::DynamicText { .. }
| FormatElement::Text { .. }
| FormatElement::SourceCodeSlice { .. }) => {
fn write_escaped(element: &FormatElement, f: &mut Formatter<IrFormatContext>) {
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())
}
_ => unreachable!(),
};

if text.contains('"') {
f.write_element(FormatElement::DynamicText {
f.write_element(FormatElement::Text {
text: text.replace('"', r#"\""#).into(),
});
} else {
Expand Down Expand Up @@ -322,10 +322,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
FormatElement::SourcePosition(position) => {
write!(
f,
[dynamic_text(
&std::format!("source_position({position:?})"),
None
)]
[text(&std::format!("source_position({position:?})"), None)]
)?;
}

Expand All @@ -352,7 +349,7 @@ impl Format<IrFormatContext<'_>> 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(")")])?;
Expand All @@ -369,7 +366,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
write!(
f,
[
dynamic_text(&std::format!("<interned {index}>"), None),
text(&std::format!("<interned {index}>"), None),
space(),
&&**interned,
]
Expand All @@ -378,10 +375,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
Some(reference) => {
write!(
f,
[dynamic_text(
&std::format!("<ref interned *{reference}>"),
None
)]
[text(&std::format!("<ref interned *{reference}>"), None)]
)?;
}
}
Expand All @@ -401,7 +395,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f,
[
token("<END_TAG_WITHOUT_START<"),
dynamic_text(&std::format!("{:?}", tag.kind()), None),
text(&std::format!("{:?}", tag.kind()), None),
token(">>"),
]
)?;
Expand All @@ -416,9 +410,9 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
token(")"),
soft_line_break_or_space(),
token("ERROR<START_END_TAG_MISMATCH<start: "),
dynamic_text(&std::format!("{start_kind:?}"), None),
text(&std::format!("{start_kind:?}"), None),
token(", end: "),
dynamic_text(&std::format!("{:?}", tag.kind()), None),
text(&std::format!("{:?}", tag.kind()), None),
token(">>")
]
)?;
Expand Down Expand Up @@ -450,7 +444,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f,
[
token("align("),
dynamic_text(&count.to_string(), None),
text(&count.to_string(), None),
token(","),
space(),
]
Expand All @@ -462,7 +456,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f,
[
token("line_suffix("),
dynamic_text(&std::format!("{reserved_width:?}"), None),
text(&std::format!("{reserved_width:?}"), None),
token(","),
space(),
]
Expand All @@ -480,7 +474,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
write!(
f,
[
dynamic_text(&std::format!("\"{group_id:?}\""), None),
text(&std::format!("\"{group_id:?}\""), None),
token(","),
space(),
]
Expand Down Expand Up @@ -526,7 +520,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f,
[
token("indent_if_group_breaks("),
dynamic_text(&std::format!("\"{id:?}\""), None),
text(&std::format!("\"{id:?}\""), None),
token(","),
space(),
]
Expand All @@ -547,7 +541,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
write!(
f,
[
dynamic_text(&std::format!("\"{group_id:?}\""), None),
text(&std::format!("\"{group_id:?}\""), None),
token(","),
space(),
]
Expand All @@ -560,7 +554,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f,
[
token("label("),
dynamic_text(&std::format!("\"{label_id:?}\""), None),
text(&std::format!("\"{label_id:?}\""), None),
token(","),
space(),
]
Expand Down Expand Up @@ -628,7 +622,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
ContentArrayEnd,
token(")"),
soft_line_break_or_space(),
dynamic_text(&std::format!("<START_WITHOUT_END<{top:?}>>"), None),
text(&std::format!("<START_WITHOUT_END<{top:?}>>"), None),
]
)?;
}
Expand Down Expand Up @@ -771,7 +765,7 @@ impl Format<IrFormatContext<'_>> for Condition {
f,
[
token("if_group_fits_on_line("),
dynamic_text(&std::format!("\"{id:?}\""), None),
text(&std::format!("\"{id:?}\""), None),
token(")")
]
),
Expand All @@ -780,7 +774,7 @@ impl Format<IrFormatContext<'_>> for Condition {
f,
[
token("if_group_breaks("),
dynamic_text(&std::format!("\"{id:?}\""), None),
text(&std::format!("\"{id:?}\""), None),
token(")")
]
),
Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_formatter/src/format_extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub trait MemoizeFormat<Context> {
/// 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)])
/// }
/// }
///
Expand Down Expand Up @@ -112,7 +112,7 @@ where
/// write!(f, [
/// token("Count:"),
/// space(),
/// dynamic_text(&std::format!("{current}"), None),
/// text(&std::format!("{current}"), None),
/// hard_line_break()
/// ])?;
///
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ pub type FormatResult<F> = Result<F, FormatError>;
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [
/// hard_line_break(),
/// dynamic_text(&self.0, None),
/// text(&self.0, None),
/// hard_line_break(),
/// ])
/// }
Expand Down
13 changes: 4 additions & 9 deletions crates/ruff_formatter/src/printer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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()
],
Expand All @@ -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\""),
],
});
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_python_formatter/src/comments/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ impl Format<PyFormatContext<'_>> for FormatNormalizedComment<'_> {
write!(
f,
[
dynamic_text(owned, Some(self.range.start())),
text(owned, Some(self.range.start())),
source_position(self.range.end())
]
)
Expand Down
Loading

0 comments on commit e400e58

Please sign in to comment.