Skip to content
This repository has been archived by the owner on Aug 31, 2023. It is now read-only.

refactor(rome_formatter): Flat IR #3160

Merged
merged 5 commits into from
Sep 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions crates/rome_formatter/src/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,14 @@ impl<'fmt, Context> Argument<'fmt, Context> {
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, format_args};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [
/// format_args!(text("a"), space(), text("b"))
/// ]).unwrap();
/// ])?;
///
/// assert_eq!("a b", formatted.print().as_code());
/// assert_eq!("a b", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub struct Arguments<'fmt, Context>(pub &'fmt [Argument<'fmt, Context>]);

Expand Down Expand Up @@ -118,8 +121,9 @@ impl<'fmt, Context> From<&'fmt Argument<'fmt, Context>> for Arguments<'fmt, Cont

#[cfg(test)]
mod tests {
use crate::format_element::tag::Tag;
use crate::prelude::*;
use crate::{format_args, format_element, write, FormatState, VecBuffer};
use crate::{format_args, write, FormatState, VecBuffer};

#[test]
fn test_nesting() {
Expand All @@ -139,17 +143,18 @@ mod tests {
.unwrap();

assert_eq!(
buffer.into_element(),
FormatElement::List(List::new(vec![
buffer.into_vec(),
vec![
FormatElement::Text(Text::Static { text: "function" }),
FormatElement::Space,
FormatElement::Text(Text::Static { text: "a" }),
FormatElement::Space,
FormatElement::Group(format_element::Group::new(vec![
FormatElement::Text(Text::Static { text: "(" }),
FormatElement::Text(Text::Static { text: ")" }),
]))
]))
// Group
FormatElement::Tag(Tag::StartGroup(None)),
FormatElement::Text(Text::Static { text: "(" }),
FormatElement::Text(Text::Static { text: ")" }),
FormatElement::Tag(Tag::EndGroup)
]
);
}
}
91 changes: 41 additions & 50 deletions crates/rome_formatter/src/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use super::{write, Arguments, FormatElement};
use crate::format_element::List;
use crate::{Format, FormatResult, FormatState};
use std::any::{Any, TypeId};
use std::fmt::Debug;
Expand All @@ -23,9 +22,9 @@ pub trait Buffer {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// buffer.write_element(FormatElement::Text( Text::Static { text: "test"})).unwrap();
/// buffer.write_element(FormatElement::Text(Text::Static { text: "test"})).unwrap();
///
/// assert_eq!(buffer.into_element(), FormatElement::Text( Text::Static { text: "test"}));
/// assert_eq!(buffer.into_vec(), vec![FormatElement::Text(Text::Static { text: "test" })]);
/// ```
///
fn write_element(&mut self, element: FormatElement) -> FormatResult<()>;
Expand All @@ -51,7 +50,7 @@ pub trait Buffer {
///
/// buffer.write_fmt(format_args!(text("Hello World"))).unwrap();
///
/// assert_eq!(buffer.into_element(), FormatElement::Text( Text::Static { text: "Hello World"}));
/// assert_eq!(buffer.into_vec(), vec![FormatElement::Text(Text::Static { text: "Hello World" })]);
/// ```
fn write_fmt(mut self: &mut Self, arguments: Arguments<Self::Context>) -> FormatResult<()> {
write(&mut self, arguments)
Expand Down Expand Up @@ -182,31 +181,21 @@ impl<'a, Context> VecBuffer<'a, Context> {
}

/// Creates a buffer with the specified capacity
pub fn with_capacity(capacity: usize, context: &'a mut FormatState<Context>) -> Self {
pub fn with_capacity(capacity: usize, state: &'a mut FormatState<Context>) -> Self {
Self {
state: context,
state,
elements: Vec::with_capacity(capacity),
}
}

/// Consumes the buffer and returns its content as a [`FormatElement`]
pub fn into_element(mut self) -> FormatElement {
self.take_element()
}

/// Consumes the buffer and returns the written [`FormatElement]`s as a vector.
pub fn into_vec(self) -> Vec<FormatElement> {
self.elements
}

/// Takes the elements without consuming self
pub fn take_element(&mut self) -> FormatElement {
if self.len() == 1 {
// Safety: Guaranteed by len check above
self.elements.pop().unwrap()
} else {
FormatElement::List(List::new(std::mem::take(&mut self.elements)))
}
pub fn take_vec(&mut self) -> Vec<FormatElement> {
std::mem::take(&mut self.elements)
}
}

Expand All @@ -228,10 +217,7 @@ impl<Context> Buffer for VecBuffer<'_, Context> {
type Context = Context;

fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
match element {
FormatElement::List(list) => self.elements.extend(list.into_vec()),
element => self.elements.push(element),
}
self.elements.push(element);

Ok(())
}
Expand Down Expand Up @@ -274,9 +260,6 @@ Make sure that you take and restore the snapshot in order and that this snapshot
/// use rome_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write};
/// use rome_formatter::prelude::*;
///
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// struct Preamble;
///
/// impl Format<SimpleFormatContext> for Preamble {
Expand All @@ -285,14 +268,21 @@ Make sure that you take and restore the snapshot in order and that this snapshot
/// }
/// }
///
/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble);
/// # 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")]).unwrap();
/// write!(&mut with_preamble, [text("this text will be on a new line")])?;
/// }
///
/// drop(with_preamble);
/// 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());
///
/// let formatted = Formatted::new(buffer.into_element(), 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.
Expand All @@ -301,9 +291,6 @@ Make sure that you take and restore the snapshot in order and that this snapshot
/// use rome_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write};
/// use rome_formatter::prelude::*;
///
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// struct Preamble;
///
/// impl Format<SimpleFormatContext> for Preamble {
Expand All @@ -312,11 +299,17 @@ Make sure that you take and restore the snapshot in order and that this snapshot
/// }
/// }
///
/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble);
/// drop(with_preamble);
/// # 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(buffer.into_element(), SimpleFormatContext::default());
/// assert_eq!("", formatted.print().as_code());
/// 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
Expand Down Expand Up @@ -351,16 +344,12 @@ where
type Context = Context;

fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
if element.is_empty() {
Ok(())
} else {
if self.empty {
write!(self.inner, [&self.preamble])?;
self.empty = false;
}

self.inner.write_element(element)
if self.empty {
write!(self.inner, [&self.preamble])?;
self.empty = false;
}

self.inner.write_element(element)
}

fn elements(&self) -> &[FormatElement] {
Expand Down Expand Up @@ -459,6 +448,7 @@ pub trait BufferExtensions: Buffer + Sized {
/// use rome_formatter::prelude::*;
/// use rome_formatter::{write, format, SimpleFormatContext};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| {
/// let mut recording = f.start_recording();
///
Expand All @@ -479,10 +469,11 @@ pub trait BufferExtensions: Buffer + Sized {
/// );
///
/// Ok(())
/// })]).unwrap();
///
/// assert_eq!(formatted.print().as_code(), "ABCD");
/// })])?;
///
/// assert_eq!(formatted.print()?.as_code(), "ABCD");
/// # Ok(())
/// # }
/// ```
#[must_use]
fn start_recording(&mut self) -> Recording<Self> {
Expand All @@ -494,7 +485,7 @@ pub trait BufferExtensions: Buffer + Sized {
where
I: IntoIterator<Item = FormatElement>,
{
for element in elements {
for element in elements.into_iter() {
self.write_element(element)?;
}

Expand Down
Loading