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

@ -8,6 +8,7 @@ use std::borrow::Cow;
use std::cell::Cell;
use std::marker::PhantomData;
use std::num::NonZeroU8;
use std::rc::Rc;
use Tag::*;
/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line.
@ -303,6 +304,34 @@ impl std::fmt::Debug for DynamicText<'_> {
}
}
/// Creates a text from a dynamic string and a range of the input source
pub fn static_text_slice(text: Rc<str>, range: TextRange) -> StaticTextSlice {
debug_assert_no_newlines(&text[range]);
StaticTextSlice { text, range }
}
#[derive(Eq, PartialEq)]
pub struct StaticTextSlice {
text: Rc<str>,
range: TextRange,
}
impl<Context> Format<Context> for StaticTextSlice {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::StaticTextSlice {
text: self.text.clone(),
range: self.range,
})
}
}
impl std::fmt::Debug for StaticTextSlice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::write!(f, "StaticTextSlice({})", &self.text[self.range])
}
}
/// String that is the same as in the input source text if `text` is [`Cow::Borrowed`] or
/// some replaced content if `text` is [`Cow::Owned`].
pub fn syntax_token_cow_slice<'a, L: Language>(