Add StaticTextSlice kind to FormatElement enum (#2873)

Given our current parser abstractions, we need the ability to tell `ruff_formatter` to print a pre-defined slice from a fixed string of source code, which we've introduced here as `FormatElement::StaticTextSlice`.
This commit is contained in:
Charlie Marsh 2023-02-14 22:27:52 -05:00 committed by GitHub
parent 746e1d3436
commit 98ea94fdb7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 44 additions and 1 deletions

View file

@ -7,7 +7,7 @@ use std::borrow::Cow;
use crate::{TagKind, TextSize};
#[cfg(target_pointer_width = "64")]
use ruff_rowan::static_assert;
use ruff_rowan::SyntaxTokenText;
use ruff_rowan::{SyntaxTokenText, TextRange};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::rc::Rc;
@ -38,6 +38,9 @@ pub enum FormatElement {
source_position: TextSize,
},
/// Token constructed by slicing a defined range from a static string.
StaticTextSlice { text: Rc<str>, range: TextRange },
/// A token for a text that is taken as is from the source code (input text and formatted representation are identical).
/// Implementing by taking a slice from a `SyntaxToken` to avoid allocating a new string.
SyntaxTokenTextSlice {
@ -75,6 +78,9 @@ impl std::fmt::Debug for FormatElement {
FormatElement::DynamicText { text, .. } => {
fmt.debug_tuple("DynamicText").field(text).finish()
}
FormatElement::StaticTextSlice { text, .. } => {
fmt.debug_tuple("Text").field(text).finish()
}
FormatElement::SyntaxTokenTextSlice { slice, .. } => fmt
.debug_tuple("SyntaxTokenTextSlice")
.field(slice)
@ -225,6 +231,7 @@ impl FormatElement {
matches!(
self,
FormatElement::SyntaxTokenTextSlice { .. }
| FormatElement::StaticTextSlice { .. }
| FormatElement::DynamicText { .. }
| FormatElement::StaticText { .. }
)
@ -243,6 +250,7 @@ impl FormatElements for FormatElement {
FormatElement::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty),
FormatElement::StaticText { text } => text.contains('\n'),
FormatElement::DynamicText { text, .. } => text.contains('\n'),
FormatElement::StaticTextSlice { text, range } => text[*range].contains('\n'),
FormatElement::SyntaxTokenTextSlice { slice, .. } => slice.contains('\n'),
FormatElement::Interned(interned) => interned.will_break(),
// Traverse into the most flat version because the content is guaranteed to expand when even