Make Buffer::write_element non-failable (#6613)

This commit is contained in:
Micha Reiser 2023-08-16 15:13:07 +02:00 committed by GitHub
parent 86ccdcc9d9
commit daac31d2b9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 115 additions and 215 deletions

View file

@ -1,7 +1,7 @@
use super::{write, Arguments, FormatElement};
use crate::format_element::Interned;
use crate::prelude::LineMode;
use crate::{Format, FormatResult, FormatState};
use crate::{FormatResult, FormatState};
use rustc_hash::FxHashMap;
use std::any::{Any, TypeId};
use std::fmt::Debug;
@ -25,11 +25,11 @@ 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::StaticText { text: "test"});
///
/// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText { text: "test" }]);
/// ```
fn write_element(&mut self, element: FormatElement) -> FormatResult<()>;
fn write_element(&mut self, element: FormatElement);
/// Returns a slice containing all elements written into this buffer.
///
@ -135,8 +135,8 @@ impl BufferSnapshot {
impl<W: Buffer<Context = Context> + ?Sized, Context> Buffer for &mut W {
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
(**self).write_element(element)
fn write_element(&mut self, element: FormatElement) {
(**self).write_element(element);
}
fn elements(&self) -> &[FormatElement] {
@ -218,10 +218,8 @@ impl<Context> DerefMut for VecBuffer<'_, Context> {
impl<Context> Buffer for VecBuffer<'_, Context> {
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
fn write_element(&mut self, element: FormatElement) {
self.elements.push(element);
Ok(())
}
fn elements(&self) -> &[FormatElement] {
@ -252,140 +250,6 @@ Make sure that you take and restore the snapshot in order and that this snapshot
}
}
/// This struct wraps an existing buffer and emits a preamble text when the first text is written.
///
/// This can be useful if you, for example, want to write some content if what gets written next isn't empty.
///
/// # Examples
///
/// ```
/// use ruff_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write};
/// use ruff_formatter::prelude::*;
///
/// struct Preamble;
///
/// impl Format<SimpleFormatContext> for Preamble {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [text("# heading"), hard_line_break()])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// {
/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble);
///
/// write!(&mut with_preamble, [text("this text will be on a new line")])?;
/// }
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
/// assert_eq!("# heading\nthis text will be on a new line", formatted.print()?.as_code());
///
/// # Ok(())
/// # }
/// ```
///
/// The pre-amble does not get written if no content is written to the buffer.
///
/// ```
/// use ruff_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write};
/// use ruff_formatter::prelude::*;
///
/// struct Preamble;
///
/// impl Format<SimpleFormatContext> for Preamble {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [text("# heading"), hard_line_break()])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
/// {
/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble);
/// }
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
/// assert_eq!("", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub struct PreambleBuffer<'buf, Preamble, Context> {
/// The wrapped buffer
inner: &'buf mut dyn Buffer<Context = Context>,
/// The pre-amble to write once the first content gets written to this buffer.
preamble: Preamble,
/// Whether some content (including the pre-amble) has been written at this point.
empty: bool,
}
impl<'buf, Preamble, Context> PreambleBuffer<'buf, Preamble, Context> {
pub fn new(inner: &'buf mut dyn Buffer<Context = Context>, preamble: Preamble) -> Self {
Self {
inner,
preamble,
empty: true,
}
}
/// Returns `true` if the preamble has been written, `false` otherwise.
pub fn did_write_preamble(&self) -> bool {
!self.empty
}
}
impl<Preamble, Context> Buffer for PreambleBuffer<'_, Preamble, Context>
where
Preamble: Format<Context>,
{
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
if self.empty {
write!(self.inner, [&self.preamble])?;
self.empty = false;
}
self.inner.write_element(element)
}
fn elements(&self) -> &[FormatElement] {
self.inner.elements()
}
fn state(&self) -> &FormatState<Self::Context> {
self.inner.state()
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
self.inner.state_mut()
}
fn snapshot(&self) -> BufferSnapshot {
BufferSnapshot::Any(Box::new(PreambleBufferSnapshot {
inner: self.inner.snapshot(),
empty: self.empty,
}))
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
let snapshot = snapshot.unwrap_any::<PreambleBufferSnapshot>();
self.empty = snapshot.empty;
self.inner.restore_snapshot(snapshot.inner);
}
}
struct PreambleBufferSnapshot {
inner: BufferSnapshot,
empty: bool,
}
/// Buffer that allows you inspecting elements as they get written to the formatter.
pub struct Inspect<'inner, Context, Inspector> {
inner: &'inner mut dyn Buffer<Context = Context>,
@ -404,9 +268,9 @@ where
{
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
fn write_element(&mut self, element: FormatElement) {
(self.inspector)(&element);
self.inner.write_element(element)
self.inner.write_element(element);
}
fn elements(&self) -> &[FormatElement] {
@ -566,9 +430,9 @@ fn clean_interned(
impl<Context> Buffer for RemoveSoftLinesBuffer<'_, Context> {
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
fn write_element(&mut self, element: FormatElement) {
let element = match element {
FormatElement::Line(LineMode::Soft) => return Ok(()),
FormatElement::Line(LineMode::Soft) => return,
FormatElement::Line(LineMode::SoftOrSpace) => FormatElement::Space,
FormatElement::Interned(interned) => {
FormatElement::Interned(self.clean_interned(&interned))
@ -576,7 +440,7 @@ impl<Context> Buffer for RemoveSoftLinesBuffer<'_, Context> {
element => element,
};
self.inner.write_element(element)
self.inner.write_element(element);
}
fn elements(&self) -> &[FormatElement] {
@ -653,15 +517,13 @@ pub trait BufferExtensions: Buffer + Sized {
}
/// Writes a sequence of elements into this buffer.
fn write_elements<I>(&mut self, elements: I) -> FormatResult<()>
fn write_elements<I>(&mut self, elements: I)
where
I: IntoIterator<Item = FormatElement>,
{
for element in elements {
self.write_element(element)?;
self.write_element(element);
}
Ok(())
}
}
@ -690,8 +552,8 @@ where
}
#[inline]
pub fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
self.buffer.write_element(element)
pub fn write_element(&mut self, element: FormatElement) {
self.buffer.write_element(element);
}
pub fn stop(self) -> Recorded<'buf> {

View file

@ -203,7 +203,8 @@ impl Line {
impl<Context> Format<Context> for Line {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Line(self.mode))
f.write_element(FormatElement::Line(self.mode));
Ok(())
}
}
@ -266,7 +267,8 @@ pub struct StaticText {
impl<Context> Format<Context> for StaticText {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::StaticText { text: self.text })
f.write_element(FormatElement::StaticText { text: self.text });
Ok(())
}
}
@ -326,7 +328,8 @@ pub struct SourcePosition(TextSize);
impl<Context> Format<Context> for SourcePosition {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::SourcePosition(self.0))
f.write_element(FormatElement::SourcePosition(self.0));
Ok(())
}
}
@ -346,12 +349,14 @@ pub struct DynamicText<'a> {
impl<Context> Format<Context> for DynamicText<'_> {
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::SourcePosition(source_position));
}
f.write_element(FormatElement::DynamicText {
text: self.text.to_string().into_boxed_str(),
})
});
Ok(())
}
}
@ -419,7 +424,9 @@ where
f.write_element(FormatElement::SourceCodeSlice {
slice,
contains_newlines,
})
});
Ok(())
}
}
@ -466,9 +473,11 @@ pub struct LineSuffix<'a, Context> {
impl<Context> Format<Context> for LineSuffix<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartLineSuffix))?;
f.write_element(FormatElement::Tag(StartLineSuffix));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndLineSuffix))
f.write_element(FormatElement::Tag(EndLineSuffix));
Ok(())
}
}
@ -513,7 +522,9 @@ pub struct LineSuffixBoundary;
impl<Context> Format<Context> for LineSuffixBoundary {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::LineSuffixBoundary)
f.write_element(FormatElement::LineSuffixBoundary);
Ok(())
}
}
@ -598,9 +609,11 @@ pub struct FormatLabelled<'a, Context> {
impl<Context> Format<Context> for FormatLabelled<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartLabelled(self.label_id)))?;
f.write_element(FormatElement::Tag(StartLabelled(self.label_id)));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndLabelled))
f.write_element(FormatElement::Tag(EndLabelled));
Ok(())
}
}
@ -639,7 +652,9 @@ pub struct Space;
impl<Context> Format<Context> for Space {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Space)
f.write_element(FormatElement::Space);
Ok(())
}
}
@ -695,9 +710,11 @@ pub struct Indent<'a, Context> {
impl<Context> Format<Context> for Indent<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartIndent))?;
f.write_element(FormatElement::Tag(StartIndent));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndIndent))
f.write_element(FormatElement::Tag(EndIndent));
Ok(())
}
}
@ -766,9 +783,11 @@ pub struct Dedent<'a, Context> {
impl<Context> Format<Context> for Dedent<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartDedent(self.mode)))?;
f.write_element(FormatElement::Tag(StartDedent(self.mode)));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndDedent))
f.write_element(FormatElement::Tag(EndDedent));
Ok(())
}
}
@ -951,9 +970,11 @@ pub struct Align<'a, Context> {
impl<Context> Format<Context> for Align<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartAlign(tag::Align(self.count))))?;
f.write_element(FormatElement::Tag(StartAlign(tag::Align(self.count))));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndAlign))
f.write_element(FormatElement::Tag(EndAlign));
Ok(())
}
}
@ -1171,7 +1192,7 @@ impl<Context> Format<Context> for BlockIndent<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let snapshot = f.snapshot();
f.write_element(FormatElement::Tag(StartIndent))?;
f.write_element(FormatElement::Tag(StartIndent));
match self.mode {
IndentMode::Soft => write!(f, [soft_line_break()])?,
@ -1192,7 +1213,7 @@ impl<Context> Format<Context> for BlockIndent<'_, Context> {
return Ok(());
}
f.write_element(FormatElement::Tag(EndIndent))?;
f.write_element(FormatElement::Tag(EndIndent));
match self.mode {
IndentMode::Soft => write!(f, [soft_line_break()]),
@ -1404,11 +1425,13 @@ impl<Context> Format<Context> for Group<'_, Context> {
f.write_element(FormatElement::Tag(StartGroup(
tag::Group::new().with_id(self.group_id).with_mode(mode),
)))?;
)));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndGroup))
f.write_element(FormatElement::Tag(EndGroup));
Ok(())
}
}
@ -1536,9 +1559,11 @@ impl<Context> Format<Context> for ConditionalGroup<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartConditionalGroup(
tag::ConditionalGroup::new(self.condition),
)))?;
)));
f.write_fmt(Arguments::from(&self.content))?;
f.write_element(FormatElement::Tag(EndConditionalGroup))
f.write_element(FormatElement::Tag(EndConditionalGroup));
Ok(())
}
}
@ -1596,7 +1621,9 @@ pub struct ExpandParent;
impl<Context> Format<Context> for ExpandParent {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::ExpandParent)
f.write_element(FormatElement::ExpandParent);
Ok(())
}
}
@ -1838,9 +1865,11 @@ impl<Context> Format<Context> for IfGroupBreaks<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartConditionalContent(
Condition::new(self.mode).with_group_id(self.group_id),
)))?;
)));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndConditionalContent))
f.write_element(FormatElement::Tag(EndConditionalContent));
Ok(())
}
}
@ -1960,9 +1989,11 @@ pub struct IndentIfGroupBreaks<'a, Context> {
impl<Context> Format<Context> for IndentIfGroupBreaks<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartIndentIfGroupBreaks(self.group_id)))?;
f.write_element(FormatElement::Tag(StartIndentIfGroupBreaks(self.group_id)));
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndIndentIfGroupBreaks))
f.write_element(FormatElement::Tag(EndIndentIfGroupBreaks));
Ok(())
}
}
@ -2050,9 +2081,11 @@ impl<Context> Format<Context> for FitsExpanded<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartFitsExpanded(
tag::FitsExpanded::new().with_condition(self.condition),
)))?;
)));
f.write_fmt(Arguments::from(&self.content))?;
f.write_element(FormatElement::Tag(EndFitsExpanded))
f.write_element(FormatElement::Tag(EndFitsExpanded));
Ok(())
}
}
@ -2306,10 +2339,10 @@ pub struct FillBuilder<'fmt, 'buf, Context> {
impl<'a, 'buf, Context> FillBuilder<'a, 'buf, Context> {
pub(crate) fn new(fmt: &'a mut Formatter<'buf, Context>) -> Self {
let result = fmt.write_element(FormatElement::Tag(StartFill));
fmt.write_element(FormatElement::Tag(StartFill));
Self {
result,
result: Ok(()),
fmt,
empty: true,
}
@ -2338,14 +2371,15 @@ impl<'a, 'buf, Context> FillBuilder<'a, 'buf, Context> {
if self.empty {
self.empty = false;
} else {
self.fmt.write_element(FormatElement::Tag(StartEntry))?;
self.fmt.write_element(FormatElement::Tag(StartEntry));
separator.fmt(self.fmt)?;
self.fmt.write_element(FormatElement::Tag(EndEntry))?;
self.fmt.write_element(FormatElement::Tag(EndEntry));
}
self.fmt.write_element(FormatElement::Tag(StartEntry))?;
self.fmt.write_element(FormatElement::Tag(StartEntry));
entry.fmt(self.fmt)?;
self.fmt.write_element(FormatElement::Tag(EndEntry))
self.fmt.write_element(FormatElement::Tag(EndEntry));
Ok(())
});
self
@ -2353,8 +2387,10 @@ impl<'a, 'buf, Context> FillBuilder<'a, 'buf, Context> {
/// Finishes the output and returns any error encountered
pub fn finish(&mut self) -> FormatResult<()> {
if self.result.is_ok() {
self.fmt.write_element(FormatElement::Tag(EndFill));
}
self.result
.and_then(|_| self.fmt.write_element(FormatElement::Tag(EndFill)))
}
}
@ -2394,9 +2430,9 @@ impl<Context> Format<Context> for BestFitting<'_, Context> {
let mut formatted_variants = Vec::with_capacity(variants.len());
for variant in variants {
buffer.write_element(FormatElement::Tag(StartEntry))?;
buffer.write_element(FormatElement::Tag(StartEntry));
buffer.write_fmt(Arguments::from(variant))?;
buffer.write_element(FormatElement::Tag(EndEntry))?;
buffer.write_element(FormatElement::Tag(EndEntry));
formatted_variants.push(buffer.take_vec().into_boxed_slice());
}
@ -2412,6 +2448,8 @@ impl<Context> Format<Context> for BestFitting<'_, Context> {
}
};
f.write_element(element)
f.write_element(element);
Ok(())
}
}

View file

@ -251,10 +251,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
| FormatElement::StaticText { .. }
| FormatElement::DynamicText { .. }
| FormatElement::SourceCodeSlice { .. }) => {
fn write_escaped(
element: &FormatElement,
f: &mut Formatter<IrFormatContext>,
) -> FormatResult<()> {
fn write_escaped(element: &FormatElement, f: &mut Formatter<IrFormatContext>) {
let text = match element {
FormatElement::StaticText { text } => text,
FormatElement::DynamicText { text } => text.as_ref(),
@ -267,9 +264,9 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
if text.contains('"') {
f.write_element(FormatElement::DynamicText {
text: text.replace('"', r#"\""#).into(),
})
});
} else {
f.write_element(element.clone())
f.write_element(element.clone());
}
}
@ -284,7 +281,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
write!(f, [text(" ")])?;
}
element if element.is_text() => {
write_escaped(element, f)?;
write_escaped(element, f);
}
_ => unreachable!(),
}
@ -334,7 +331,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f.write_elements([
FormatElement::Tag(StartIndent),
FormatElement::Line(LineMode::Hard),
])?;
]);
for variant in variants {
write!(f, [&**variant, hard_line_break()])?;
@ -343,7 +340,7 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
f.write_elements([
FormatElement::Tag(EndIndent),
FormatElement::Line(LineMode::Hard),
])?;
]);
write!(f, [text("])")])?;
}
@ -631,7 +628,9 @@ impl Format<IrFormatContext<'_>> for ContentArrayStart {
FormatElement::Tag(StartGroup(tag::Group::new())),
FormatElement::Tag(StartIndent),
FormatElement::Line(LineMode::Soft),
])
]);
Ok(())
}
}
@ -644,7 +643,7 @@ impl Format<IrFormatContext<'_>> for ContentArrayEnd {
FormatElement::Tag(EndIndent),
FormatElement::Line(LineMode::Soft),
FormatElement::Tag(EndGroup),
])?;
]);
write!(f, [text("]")])
}

View file

@ -166,7 +166,7 @@ where
match result {
Ok(Some(elements)) => {
f.write_element(elements.clone())?;
f.write_element(elements.clone());
Ok(())
}

View file

@ -206,8 +206,8 @@ impl<Context> Buffer for Formatter<'_, Context> {
type Context = Context;
#[inline]
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
self.buffer.write_element(element)
fn write_element(&mut self, element: FormatElement) {
self.buffer.write_element(element);
}
fn elements(&self) -> &[FormatElement] {

View file

@ -42,8 +42,7 @@ use crate::format_element::document::Document;
use crate::printer::{Printer, PrinterOptions};
pub use arguments::{Argument, Arguments};
pub use buffer::{
Buffer, BufferExtensions, BufferSnapshot, Inspect, PreambleBuffer, RemoveSoftLinesBuffer,
VecBuffer,
Buffer, BufferExtensions, BufferSnapshot, Inspect, RemoveSoftLinesBuffer, VecBuffer,
};
pub use builders::BestFitting;
pub use source_code::{SourceCode, SourceCodeSlice};

View file

@ -268,7 +268,8 @@ impl<'ast> Format<PyFormatContext<'ast>> for InParenthesesOnlyLineBreak {
f.write_element(FormatElement::Line(match self {
InParenthesesOnlyLineBreak::SoftLineBreak => LineMode::Soft,
InParenthesesOnlyLineBreak::SoftLineBreakOrSpace => LineMode::SoftOrSpace,
}))
}));
Ok(())
}
}
}

View file

@ -184,11 +184,11 @@ impl Format<PyFormatContext<'_>> for NotYetImplementedCustomText<'_> {
tag::VerbatimKind::Verbatim {
length: self.text.text_len(),
},
)))?;
)));
text(self.text).fmt(f)?;
f.write_element(FormatElement::Tag(Tag::EndVerbatim))?;
f.write_element(FormatElement::Tag(Tag::EndVerbatim));
f.context()
.comments()

View file

@ -855,7 +855,7 @@ impl Format<PyFormatContext<'_>> for VerbatimText {
tag::VerbatimKind::Verbatim {
length: self.verbatim_range.len(),
},
)))?;
)));
match normalize_newlines(f.context().locator().slice(self.verbatim_range), ['\r']) {
Cow::Borrowed(_) => {
@ -878,6 +878,7 @@ impl Format<PyFormatContext<'_>> for VerbatimText {
}
}
f.write_element(FormatElement::Tag(Tag::EndVerbatim))
f.write_element(FormatElement::Tag(Tag::EndVerbatim));
Ok(())
}
}