From fc06d584d0ab9f4e08a2d28b5ea731897232a78f Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Fri, 23 Sep 2022 08:19:04 +0200 Subject: [PATCH] Rename `Signal` to `Tag` --- crates/rome_formatter/src/arguments.rs | 6 +- crates/rome_formatter/src/builders.rs | 66 +++--- crates/rome_formatter/src/format_element.rs | 60 +++--- .../src/format_element/document.rs | 108 +++++----- .../src/format_element/{signal.rs => tag.rs} | 76 +++---- crates/rome_formatter/src/lib.rs | 69 ++++--- crates/rome_formatter/src/prelude.rs | 2 +- .../rome_formatter/src/printer/call_stack.rs | 36 ++-- crates/rome_formatter/src/printer/mod.rs | 188 ++++++++---------- crates/rome_formatter/src/printer/queue.rs | 72 +++---- crates/rome_formatter/src/trivia.rs | 6 +- crates/rome_formatter/src/verbatim.rs | 6 +- .../src/js/expressions/template_element.rs | 6 +- .../src/jsx/lists/child_list.rs | 14 +- .../src/ts/lists/type_member_list.rs | 2 +- crates/rome_js_formatter/src/utils/mod.rs | 13 +- xtask/contributors/src/main.rs | 2 +- 17 files changed, 353 insertions(+), 379 deletions(-) rename crates/rome_formatter/src/format_element/{signal.rs => tag.rs} (71%) diff --git a/crates/rome_formatter/src/arguments.rs b/crates/rome_formatter/src/arguments.rs index 480b1e60316..db7d2f46c91 100644 --- a/crates/rome_formatter/src/arguments.rs +++ b/crates/rome_formatter/src/arguments.rs @@ -121,7 +121,7 @@ impl<'fmt, Context> From<&'fmt Argument<'fmt, Context>> for Arguments<'fmt, Cont #[cfg(test)] mod tests { - use crate::format_element::signal::Signal; + use crate::format_element::tag::Tag; use crate::prelude::*; use crate::{format_args, write, FormatState, VecBuffer}; @@ -150,10 +150,10 @@ mod tests { FormatElement::Text(Text::Static { text: "a" }), FormatElement::Space, // Group - FormatElement::Signal(Signal::StartGroup(None)), + FormatElement::Tag(Tag::StartGroup(None)), FormatElement::Text(Text::Static { text: "(" }), FormatElement::Text(Text::Static { text: ")" }), - FormatElement::Signal(Signal::EndGroup) + FormatElement::Tag(Tag::EndGroup) ] ); } diff --git a/crates/rome_formatter/src/builders.rs b/crates/rome_formatter/src/builders.rs index d9cae1b1ce3..6ad608a97ae 100644 --- a/crates/rome_formatter/src/builders.rs +++ b/crates/rome_formatter/src/builders.rs @@ -1,5 +1,5 @@ -use crate::format_element::signal::{Condition, Signal}; -use crate::prelude::signal::{DedentMode, LabelId}; +use crate::format_element::tag::{Condition, Tag}; +use crate::prelude::tag::{DedentMode, LabelId}; use crate::prelude::*; use crate::{format_element, write, Argument, Arguments, GroupId, TextRange, TextSize}; use crate::{Buffer, VecBuffer}; @@ -8,7 +8,7 @@ use std::borrow::Cow; use std::cell::Cell; use std::marker::PhantomData; use std::num::NonZeroU8; -use Signal::*; +use Tag::*; /// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line. /// It's omitted if the enclosing `Group` fits on a single line. @@ -433,9 +433,9 @@ pub struct LineSuffix<'a, Context> { impl Format for LineSuffix<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartLineSuffix))?; + f.write_element(FormatElement::Tag(StartLineSuffix))?; Arguments::from(&self.content).fmt(f)?; - f.write_element(FormatElement::Signal(EndLineSuffix)) + f.write_element(FormatElement::Tag(EndLineSuffix)) } } @@ -487,7 +487,7 @@ impl Format for LineSuffixBoundary { /// Marks some content with a label. /// /// This does not directly influence how this content will be printed, but some -/// parts of the formatter may inspect the [labelled element](Signal::Label) +/// parts of the formatter may inspect the [labelled element](Tag::StartLabelled) /// using [FormatElements::has_label]. /// /// ## Examples @@ -550,9 +550,9 @@ pub struct FormatLabelled<'a, Context> { impl Format for FormatLabelled<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartLabelled(self.label_id)))?; + f.write_element(FormatElement::Tag(StartLabelled(self.label_id)))?; Arguments::from(&self.content).fmt(f)?; - f.write_element(FormatElement::Signal(EndLabelled)) + f.write_element(FormatElement::Tag(EndLabelled)) } } @@ -647,9 +647,9 @@ pub struct Indent<'a, Context> { impl Format for Indent<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartIndent))?; + f.write_element(FormatElement::Tag(StartIndent))?; Arguments::from(&self.content).fmt(f)?; - f.write_element(FormatElement::Signal(EndIndent)) + f.write_element(FormatElement::Tag(EndIndent)) } } @@ -718,9 +718,9 @@ pub struct Dedent<'a, Context> { impl Format for Dedent<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartDedent(self.mode)))?; + f.write_element(FormatElement::Tag(StartDedent(self.mode)))?; Arguments::from(&self.content).fmt(f)?; - f.write_element(FormatElement::Signal(EndDedent)) + f.write_element(FormatElement::Tag(EndDedent)) } } @@ -903,9 +903,9 @@ pub struct Align<'a, Context> { impl Format for Align<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartAlign(signal::Align(self.count))))?; + f.write_element(FormatElement::Tag(StartAlign(tag::Align(self.count))))?; Arguments::from(&self.content).fmt(f)?; - f.write_element(FormatElement::Signal(EndAlign)) + f.write_element(FormatElement::Tag(EndAlign)) } } @@ -1123,7 +1123,7 @@ impl Format for BlockIndent<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { let snapshot = f.snapshot(); - f.write_element(FormatElement::Signal(StartIndent))?; + f.write_element(FormatElement::Tag(StartIndent))?; match self.mode { IndentMode::Soft => write!(f, [soft_line_break()])?, @@ -1144,7 +1144,7 @@ impl Format for BlockIndent<'_, Context> { return Ok(()); } - f.write_element(FormatElement::Signal(EndIndent))?; + f.write_element(FormatElement::Tag(EndIndent))?; match self.mode { IndentMode::Soft => write!(f, [soft_line_break()]), @@ -1336,8 +1336,8 @@ impl Group<'_, Context> { /// line or contains any hard line breaks. /// /// The formatter writes a [FormatElement::ExpandParent], forcing any enclosing group to expand, if `should_expand` is `true`. - /// It also omits the [`start`](Signal::StartGroup) and [`end`](Signal::EndGroup) signals because the group would be forced to expand anyway. - /// The [`start`](Signal::StartGroup) and [`end`](Signal::EndGroup) signals are only written if the `group_id` specified with [Group::with_group_id] isn't [None] + /// It also omits the [`start`](Tag::StartGroup) and [`end`](Tag::EndGroup) tags because the group would be forced to expand anyway. + /// The [`start`](Tag::StartGroup) and [`end`](Tag::EndGroup) tags are only written if the `group_id` specified with [Group::with_group_id] isn't [None] /// because other IR elements may reference the group with that group id and the printer may panic /// if no group with the given id is present in the document. pub fn should_expand(mut self, should_expand: bool) -> Self { @@ -1356,7 +1356,7 @@ impl Format for Group<'_, Context> { let write_group = !self.should_expand || self.group_id.is_some(); if write_group { - f.write_element(FormatElement::Signal(Signal::StartGroup(self.group_id)))?; + f.write_element(FormatElement::Tag(Tag::StartGroup(self.group_id)))?; } if self.should_expand { @@ -1366,7 +1366,7 @@ impl Format for Group<'_, Context> { Arguments::from(&self.content).fmt(f)?; if write_group { - f.write_element(FormatElement::Signal(Signal::EndGroup))?; + f.write_element(FormatElement::Tag(Tag::EndGroup))?; } Ok(()) @@ -1667,11 +1667,11 @@ impl IfGroupBreaks<'_, Context> { impl Format for IfGroupBreaks<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartConditionalContent( + 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::Signal(EndConditionalContent)) + f.write_element(FormatElement::Tag(EndConditionalContent)) } } @@ -1791,11 +1791,9 @@ pub struct IndentIfGroupBreaks<'a, Context> { impl Format for IndentIfGroupBreaks<'_, Context> { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - f.write_element(FormatElement::Signal(StartIndentIfGroupBreaks( - self.group_id, - )))?; + f.write_element(FormatElement::Tag(StartIndentIfGroupBreaks(self.group_id)))?; Arguments::from(&self.content).fmt(f)?; - f.write_element(FormatElement::Signal(EndIndentIfGroupBreaks)) + f.write_element(FormatElement::Tag(EndIndentIfGroupBreaks)) } } @@ -2146,7 +2144,7 @@ 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::Signal(StartFill)); + let result = fmt.write_element(FormatElement::Tag(StartFill)); Self { result, @@ -2178,14 +2176,14 @@ impl<'a, 'buf, Context> FillBuilder<'a, 'buf, Context> { if self.empty { self.empty = false; } else { - self.fmt.write_element(FormatElement::Signal(StartEntry))?; + self.fmt.write_element(FormatElement::Tag(StartEntry))?; separator.fmt(self.fmt)?; - self.fmt.write_element(FormatElement::Signal(EndEntry))?; + self.fmt.write_element(FormatElement::Tag(EndEntry))?; } - self.fmt.write_element(FormatElement::Signal(StartEntry))?; + self.fmt.write_element(FormatElement::Tag(StartEntry))?; entry.fmt(self.fmt)?; - self.fmt.write_element(FormatElement::Signal(EndEntry)) + self.fmt.write_element(FormatElement::Tag(EndEntry)) }); self @@ -2194,7 +2192,7 @@ impl<'a, 'buf, Context> FillBuilder<'a, 'buf, Context> { /// Finishes the output and returns any error encountered pub fn finish(&mut self) -> FormatResult<()> { self.result - .and_then(|_| self.fmt.write_element(FormatElement::Signal(EndFill))) + .and_then(|_| self.fmt.write_element(FormatElement::Tag(EndFill))) } } @@ -2232,9 +2230,9 @@ impl Format for BestFitting<'_, Context> { let mut formatted_variants = Vec::with_capacity(variants.len()); for variant in variants { - buffer.write_element(FormatElement::Signal(StartEntry))?; + buffer.write_element(FormatElement::Tag(StartEntry))?; buffer.write_fmt(Arguments::from(variant))?; - buffer.write_element(FormatElement::Signal(EndEntry))?; + buffer.write_element(FormatElement::Tag(EndEntry))?; formatted_variants.push(buffer.take_vec().into_boxed_slice()); } diff --git a/crates/rome_formatter/src/format_element.rs b/crates/rome_formatter/src/format_element.rs index 44eff0fe926..04bd3da33e6 100644 --- a/crates/rome_formatter/src/format_element.rs +++ b/crates/rome_formatter/src/format_element.rs @@ -1,9 +1,9 @@ pub mod document; -pub mod signal; +pub mod tag; -use crate::format_element::signal::{LabelId, Signal}; +use crate::format_element::tag::{LabelId, Tag}; -use crate::{SignalKind, TextSize}; +use crate::{TagKind, TextSize}; #[cfg(target_pointer_width = "64")] use rome_rowan::static_assert; use rome_rowan::SyntaxTokenText; @@ -41,8 +41,8 @@ pub enum FormatElement { /// Line breaks inside of a best fitting don't propagate to parent groups. BestFitting(BestFitting), - /// A signal that marks the start/end of some content to which some special formatting is applied. - Signal(Signal), + /// A [Tag] that marks the start/end of some content to which some special formatting is applied. + Tag(Tag), } impl std::fmt::Debug for FormatElement { @@ -59,7 +59,7 @@ impl std::fmt::Debug for FormatElement { FormatElement::Interned(interned) => { fmt.debug_list().entries(interned.deref()).finish() } - FormatElement::Signal(signal) => fmt.debug_tuple("Signal").field(signal).finish(), + FormatElement::Tag(tag) => fmt.debug_tuple("Tag").field(tag).finish(), } } } @@ -248,23 +248,23 @@ impl Deref for Text { } impl FormatElement { - /// Returns `true` if self is a [FormatElement::Signal] - pub const fn is_signal(&self) -> bool { - matches!(self, FormatElement::Signal(_)) + /// Returns `true` if self is a [FormatElement::Tag] + pub const fn is_tag(&self) -> bool { + matches!(self, FormatElement::Tag(_)) } - /// Returns `true` if self is a [FormatElement::Signal] and `Signal::is_start` is `true`. - pub const fn is_start_signal(&self) -> bool { + /// Returns `true` if self is a [FormatElement::Tag] and [Tag::is_start] is `true`. + pub const fn is_start_tag(&self) -> bool { match self { - FormatElement::Signal(signal) => signal.is_start(), + FormatElement::Tag(tag) => tag.is_start(), _ => false, } } - /// Returns `true` if self is a [FormatElement::Signal] and `Signal::is_end` is `true`. - pub const fn is_end_signal(&self) -> bool { + /// Returns `true` if self is a [FormatElement::Tag] and [Tag::is_end] is `true`. + pub const fn is_end_tag(&self) -> bool { match self { - FormatElement::Signal(signal) => signal.is_end(), + FormatElement::Tag(tag) => tag.is_end(), _ => false, } } @@ -279,28 +279,26 @@ impl FormatElements for FormatElement { FormatElement::Interned(interned) => interned.will_break(), FormatElement::LineSuffixBoundary | FormatElement::Space - | FormatElement::Signal(_) + | FormatElement::Tag(_) | FormatElement::BestFitting(_) => false, } } fn has_label(&self, label_id: LabelId) -> bool { match self { - FormatElement::Signal(Signal::StartLabelled(actual)) => *actual == label_id, + FormatElement::Tag(Tag::StartLabelled(actual)) => *actual == label_id, FormatElement::Interned(interned) => interned.deref().has_label(label_id), _ => false, } } - fn start_signal(&self, _: SignalKind) -> Option<&Signal> { + fn start_tag(&self, _: TagKind) -> Option<&Tag> { None } - fn end_signal(&self, kind: SignalKind) -> Option<&Signal> { + fn end_tag(&self, kind: TagKind) -> Option<&Tag> { match self { - FormatElement::Signal(signal) if signal.kind() == kind && signal.is_end() => { - Some(signal) - } + FormatElement::Tag(tag) if tag.kind() == kind && tag.is_end() => Some(tag), _ => None, } } @@ -383,14 +381,14 @@ pub trait FormatElements { /// Returns true if the element has the given label. fn has_label(&self, label: LabelId) -> bool; - /// Returns the start signal of `kind` if: - /// * the last element is an end signal of `kind`. - /// * there's a matching start signal in this document (may not be true if this slice is an interned element and the `start` is in the document storing the interned element). - fn start_signal(&self, kind: SignalKind) -> Option<&Signal>; + /// Returns the start tag of `kind` if: + /// * the last element is an end tag of `kind`. + /// * there's a matching start tag in this document (may not be true if this slice is an interned element and the `start` is in the document storing the interned element). + fn start_tag(&self, kind: TagKind) -> Option<&Tag>; - /// Returns the end signal if: - /// * the last element is an end signal of `kind` - fn end_signal(&self, kind: SignalKind) -> Option<&Signal>; + /// Returns the end tag if: + /// * the last element is an end tag of `kind` + fn end_tag(&self, kind: TagKind) -> Option<&Tag>; } #[cfg(test)] @@ -412,14 +410,14 @@ mod tests { static_assert!(std::mem::size_of::() == 8usize); #[cfg(target_pointer_width = "64")] -static_assert!(std::mem::size_of::() == 8usize); +static_assert!(std::mem::size_of::() == 8usize); #[cfg(target_pointer_width = "64")] static_assert!(std::mem::size_of::() == 24usize); #[cfg(not(debug_assertions))] #[cfg(target_pointer_width = "64")] -static_assert!(std::mem::size_of::() == 16usize); +static_assert!(std::mem::size_of::() == 16usize); // Increasing the size of FormatElement has serious consequences on runtime performance and memory footprint. // Is there a more efficient way to encode the data to avoid increasing its size? Can the information diff --git a/crates/rome_formatter/src/format_element/document.rs b/crates/rome_formatter/src/format_element/document.rs index 1d37c61c0d9..4fa41649ff7 100644 --- a/crates/rome_formatter/src/format_element/document.rs +++ b/crates/rome_formatter/src/format_element/document.rs @@ -1,5 +1,5 @@ -use super::signal::Signal; -use crate::format_element::signal::DedentMode; +use super::tag::Tag; +use crate::format_element::tag::DedentMode; use crate::prelude::*; use crate::printer::LineEnding; use crate::{format, write}; @@ -87,18 +87,18 @@ impl FormatOptions for IrFormatOptions { impl Format for &[FormatElement] { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - use Signal::*; + use Tag::*; write!(f, [ContentArrayStart])?; - let mut signal_stack = Vec::new(); + let mut tag_stack = Vec::new(); let mut first_element = true; let mut in_text = false; let mut iter = self.iter().peekable(); while let Some(element) = iter.next() { - if !first_element && !in_text && !element.is_end_signal() { + if !first_element && !in_text && !element.is_end_tag() { // Write a separator between every two elements write!(f, [text(","), soft_line_break_or_space()])?; } @@ -157,7 +157,7 @@ impl Format for &[FormatElement] { FormatElement::BestFitting(best_fitting) => { write!(f, [text("best_fitting([")])?; f.write_elements([ - FormatElement::Signal(StartIndent), + FormatElement::Tag(StartIndent), FormatElement::Line(LineMode::Hard), ])?; @@ -166,7 +166,7 @@ impl Format for &[FormatElement] { } f.write_elements([ - FormatElement::Signal(EndIndent), + FormatElement::Tag(EndIndent), FormatElement::Line(LineMode::Hard), ])?; @@ -205,22 +205,22 @@ impl Format for &[FormatElement] { } } - FormatElement::Signal(signal) => { - if signal.is_start() { + FormatElement::Tag(tag) => { + if tag.is_start() { first_element = true; - signal_stack.push(signal.kind()); + tag_stack.push(tag.kind()); } - // Handle documents with mismatching start/end or superfluous end signals + // Handle documents with mismatching start/end or superfluous end tags else { - match signal_stack.pop() { + match tag_stack.pop() { None => { - // Only write the end signal without any indent to ensure the output document is valid. + // Only write the end tag without any indent to ensure the output document is valid. write!( f, [ - text(">"), @@ -229,21 +229,21 @@ impl Format for &[FormatElement] { first_element = false; continue; } - Some(start_kind) if start_kind != signal.kind() => { + Some(start_kind) if start_kind != tag.kind() => { write!( f, [ ContentArrayEnd, text(")"), soft_line_break_or_space(), - text("ERROR>") @@ -258,7 +258,7 @@ impl Format for &[FormatElement] { } } - match signal { + match tag { StartIndent => { write!(f, [text("indent(")])?; } @@ -272,7 +272,7 @@ impl Format for &[FormatElement] { write!(f, [text(label), text("(")])?; } - StartAlign(signal::Align(count)) => { + StartAlign(tag::Align(count)) => { write!( f, [ @@ -367,7 +367,7 @@ impl Format for &[FormatElement] { } StartEntry => { - // handled after the match for all start signals + // handled after the match for all start tags } EndEntry => write!(f, [ContentArrayEnd])?, @@ -385,14 +385,14 @@ impl Format for &[FormatElement] { } }; - if signal.is_start() { + if tag.is_start() { write!(f, [ContentArrayStart])?; } } } } - while let Some(top) = signal_stack.pop() { + while let Some(top) = tag_stack.pop() { write!( f, [ @@ -415,13 +415,13 @@ struct ContentArrayStart; impl Format for ContentArrayStart { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - use Signal::*; + use Tag::*; write!(f, [text("[")])?; f.write_elements([ - FormatElement::Signal(StartGroup(None)), - FormatElement::Signal(StartIndent), + FormatElement::Tag(StartGroup(None)), + FormatElement::Tag(StartIndent), FormatElement::Line(LineMode::Soft), ]) } @@ -431,11 +431,11 @@ struct ContentArrayEnd; impl Format for ContentArrayEnd { fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { - use Signal::*; + use Tag::*; f.write_elements([ - FormatElement::Signal(EndIndent), + FormatElement::Tag(EndIndent), FormatElement::Line(LineMode::Soft), - FormatElement::Signal(EndGroup), + FormatElement::Tag(EndGroup), ])?; write!(f, [text("]")]) @@ -444,17 +444,17 @@ impl Format for ContentArrayEnd { impl FormatElements for [FormatElement] { fn will_break(&self) -> bool { - use Signal::*; + use Tag::*; let mut ignore_depth = 0usize; for element in self { match element { // Line suffix // Ignore if any of its content breaks - FormatElement::Signal(StartLineSuffix) => { + FormatElement::Tag(StartLineSuffix) => { ignore_depth += 1; } - FormatElement::Signal(EndLineSuffix) => { + FormatElement::Tag(EndLineSuffix) => { ignore_depth -= 1; } FormatElement::Interned(interned) if ignore_depth == 0 => { @@ -480,24 +480,24 @@ impl FormatElements for [FormatElement] { .map_or(false, |element| element.has_label(expected)) } - fn start_signal(&self, kind: SignalKind) -> Option<&Signal> { - // Assert that the document ends at a signal with the specified kind; - let _ = self.end_signal(kind)?; + fn start_tag(&self, kind: TagKind) -> Option<&Tag> { + // Assert that the document ends at a tag with the specified kind; + let _ = self.end_tag(kind)?; fn traverse_slice<'a>( slice: &'a [FormatElement], - kind: SignalKind, + kind: TagKind, depth: &mut usize, - ) -> Option<&'a Signal> { + ) -> Option<&'a Tag> { for element in slice.iter().rev() { match element { - FormatElement::Signal(signal) if signal.kind() == kind => { - if signal.is_start() { + FormatElement::Tag(tag) if tag.kind() == kind => { + if tag.is_start() { if *depth == 0 { // Invalid document return None; } else if *depth == 1 { - return Some(signal); + return Some(tag); } else { *depth -= 1; } @@ -531,8 +531,8 @@ impl FormatElements for [FormatElement] { traverse_slice(self, kind, &mut depth) } - fn end_signal(&self, kind: SignalKind) -> Option<&Signal> { - self.last().and_then(|element| element.end_signal(kind)) + fn end_tag(&self, kind: TagKind) -> Option<&Tag> { + self.last().and_then(|element| element.end_tag(kind)) } } @@ -581,23 +581,23 @@ mod tests { #[test] fn display_invalid_document() { - use Signal::*; + use Tag::*; let document = Document::from(vec![ FormatElement::Text(Text::Static { text: "[" }), - FormatElement::Signal(StartGroup(None)), - FormatElement::Signal(StartIndent), + FormatElement::Tag(StartGroup(None)), + FormatElement::Tag(StartIndent), FormatElement::Line(LineMode::Soft), FormatElement::Text(Text::Static { text: "a" }), // Close group instead of indent - FormatElement::Signal(EndGroup), + FormatElement::Tag(EndGroup), FormatElement::Line(LineMode::Soft), - FormatElement::Signal(EndIndent), + FormatElement::Tag(EndIndent), FormatElement::Text(Text::Static { text: "]" }), - // End signal without start - FormatElement::Signal(EndIndent), - // Start signal without an end - FormatElement::Signal(StartIndent), + // End tag without start + FormatElement::Tag(EndIndent), + // Start tag without an end + FormatElement::Tag(StartIndent), ]); assert_eq!( @@ -606,11 +606,11 @@ mod tests { "[", group([ indent([soft_line_break, "a"]) - ERROR>, + ERROR>, soft_line_break ]) - ERROR>, - "]">, + ERROR>, + "]">, indent([]) > ]"# diff --git a/crates/rome_formatter/src/format_element/signal.rs b/crates/rome_formatter/src/format_element/tag.rs similarity index 71% rename from crates/rome_formatter/src/format_element/signal.rs rename to crates/rome_formatter/src/format_element/tag.rs index 326580148ec..c546152cc8e 100644 --- a/crates/rome_formatter/src/format_element/signal.rs +++ b/crates/rome_formatter/src/format_element/tag.rs @@ -5,20 +5,20 @@ use std::any::type_name; use std::any::TypeId; use std::num::NonZeroU8; -/// Signal marking the start and end of some content to which some special formatting should be applied. +/// A Tag marking the start and end of some content to which some special formatting should be applied. /// -/// Signals always come in pairs of a start and an end signal and the styling defined by this signal -/// will be applied to all elements in between the start/end signals. +/// Tags always come in pairs of a start and an end tag and the styling defined by this tag +/// will be applied to all elements in between the start/end tags. #[derive(Clone, Debug, Eq, PartialEq)] -pub enum Signal { +pub enum Tag { /// Indents the content one level deeper, see [crate::indent] for documentation and examples. StartIndent, EndIndent, - /// Variant of [SignalKind::Indent] that indents content by a number of spaces. For example, `Align(2)` + /// Variant of [TagKind::Indent] that indents content by a number of spaces. For example, `Align(2)` /// indents any content following a line break by an additional two spaces. /// - /// Nesting (Aligns)[SignalKind::Align] has the effect that all except the most inner align are handled as (Indent)[SignalKind::Indent]. + /// Nesting (Aligns)[TagKind::Align] has the effect that all except the most inner align are handled as (Indent)[TagKind::Indent]. StartAlign(Align), EndAlign, @@ -40,7 +40,7 @@ pub enum Signal { StartConditionalContent(Condition), EndConditionalContent, - /// Optimized version of [Signal::StartConditionalContent] for the case where some content + /// Optimized version of [Tag::StartConditionalContent] for the case where some content /// should be indented if the specified group breaks. StartIndentIfGroupBreaks(GroupId), EndIndentIfGroupBreaks, @@ -51,7 +51,7 @@ pub enum Signal { StartFill, EndFill, - /// Entry inside of a [Signal::StartFill] + /// Entry inside of a [Tag::StartFill] StartEntry, EndEntry, @@ -71,55 +71,55 @@ pub enum Signal { EndLabelled, } -impl Signal { - /// Returns `true` if `self` is any start signal. +impl Tag { + /// Returns `true` if `self` is any start tag. pub const fn is_start(&self) -> bool { matches!( self, - Signal::StartIndent - | Signal::StartAlign(_) - | Signal::StartDedent(_) - | Signal::StartGroup(_) - | Signal::StartConditionalContent(_) - | Signal::StartIndentIfGroupBreaks(_) - | Signal::StartFill - | Signal::StartEntry - | Signal::StartLineSuffix - | Signal::StartVerbatim(_) - | Signal::StartLabelled(_) + Tag::StartIndent + | Tag::StartAlign(_) + | Tag::StartDedent(_) + | Tag::StartGroup(_) + | Tag::StartConditionalContent(_) + | Tag::StartIndentIfGroupBreaks(_) + | Tag::StartFill + | Tag::StartEntry + | Tag::StartLineSuffix + | Tag::StartVerbatim(_) + | Tag::StartLabelled(_) ) } - /// Returns `true` if `self` is any end signal. + /// Returns `true` if `self` is any end tag. pub const fn is_end(&self) -> bool { !self.is_start() } - pub const fn kind(&self) -> SignalKind { - use Signal::*; + pub const fn kind(&self) -> TagKind { + use Tag::*; match self { - StartIndent | EndIndent => SignalKind::Indent, - StartAlign(_) | EndAlign => SignalKind::Align, - StartDedent(_) | EndDedent => SignalKind::Dedent, - StartGroup(_) | EndGroup => SignalKind::Group, - StartConditionalContent(_) | EndConditionalContent => SignalKind::ConditionalContent, - StartIndentIfGroupBreaks(_) | EndIndentIfGroupBreaks => SignalKind::IndentIfGroupBreaks, - StartFill | EndFill => SignalKind::Fill, - StartEntry | EndEntry => SignalKind::Entry, - StartLineSuffix | EndLineSuffix => SignalKind::LineSuffix, - StartVerbatim(_) | EndVerbatim => SignalKind::Verbatim, - StartLabelled(_) | EndLabelled => SignalKind::Labelled, + StartIndent | EndIndent => TagKind::Indent, + StartAlign(_) | EndAlign => TagKind::Align, + StartDedent(_) | EndDedent => TagKind::Dedent, + StartGroup(_) | EndGroup => TagKind::Group, + StartConditionalContent(_) | EndConditionalContent => TagKind::ConditionalContent, + StartIndentIfGroupBreaks(_) | EndIndentIfGroupBreaks => TagKind::IndentIfGroupBreaks, + StartFill | EndFill => TagKind::Fill, + StartEntry | EndEntry => TagKind::Entry, + StartLineSuffix | EndLineSuffix => TagKind::LineSuffix, + StartVerbatim(_) | EndVerbatim => TagKind::Verbatim, + StartLabelled(_) | EndLabelled => TagKind::Labelled, } } } -/// The kind of a signal. +/// The kind of a [Tag]. /// -/// Each start end signal pair has its own signal kind. +/// Each start end tag pair has its own [tag kind](TagKind). #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum SignalKind { +pub enum TagKind { Indent, Align, Dedent, diff --git a/crates/rome_formatter/src/lib.rs b/crates/rome_formatter/src/lib.rs index d024f655d05..cd315fbe6c9 100644 --- a/crates/rome_formatter/src/lib.rs +++ b/crates/rome_formatter/src/lib.rs @@ -40,7 +40,7 @@ mod verbatim; use crate::formatter::Formatter; use crate::group_id::UniqueGroupIdBuilder; -use crate::prelude::{syntax_token_cow_slice, SignalKind}; +use crate::prelude::{syntax_token_cow_slice, TagKind}; use crate::format_element::document::Document; #[cfg(debug_assertions)] @@ -383,25 +383,25 @@ pub enum InvalidDocumentError { /// ... /// EndGroup /// ``` - StartEndSignalMismatch { - start_kind: SignalKind, - end_kind: SignalKind, + StartEndTagMismatch { + start_kind: TagKind, + end_kind: TagKind, }, - /// End signal without a corresponding start signal. + /// End tag without a corresponding start tag. /// /// ```plain /// Text /// EndGroup /// ``` - StartSignalMissing { kind: SignalKind }, + StartTagMissing { kind: TagKind }, - /// Expected a specific start signal but instead is: + /// Expected a specific start tag but instead is: /// * at the end of the document - /// * at another start signal - /// * at an end signal + /// * at another start tag + /// * at an end tag ExpectedStart { - expected_start: SignalKind, + expected_start: TagKind, actual: ActualStart, }, } @@ -409,14 +409,14 @@ pub enum InvalidDocumentError { #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum ActualStart { - /// The actual element is not a signal. + /// The actual element is not a tag. Content, - /// The actual element was a start signal of another kind. - Start(SignalKind), + /// The actual element was a start tag of another kind. + Start(TagKind), - /// The actual element is an end signal instead of a start signal. - End(SignalKind), + /// The actual element is an end tag instead of a start tag. + End(TagKind), /// Reached the end of the document EndOfDocument, @@ -425,38 +425,37 @@ pub enum ActualStart { impl std::fmt::Display for InvalidDocumentError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - InvalidDocumentError::StartEndSignalMismatch { + InvalidDocumentError::StartEndTagMismatch { start_kind, end_kind, } => { std::write!( f, - "Expected end signal of kind {start_kind:?} but found {end_kind:?}." + "Expected end tag of kind {start_kind:?} but found {end_kind:?}." ) } - InvalidDocumentError::StartSignalMissing { kind } => { - std::write!( - f, - "End signal of kind {kind:?} without matching start signal." - ) + InvalidDocumentError::StartTagMissing { kind } => { + std::write!(f, "End tag of kind {kind:?} without matching start tag.") } InvalidDocumentError::ExpectedStart { expected_start, actual, - } => match actual { - ActualStart::EndOfDocument => { - std::write!(f, "Expected start signal of kind {expected_start:?} but at the end of document.") - } - ActualStart::Start(start) => { - std::write!(f, "Expected start signal of kind {expected_start:?} but found start signal of kind {start:?}.") - } - ActualStart::End(end) => { - std::write!(f, "Expected start signal of kind {expected_start:?} but found end signal of kind {end:?}.") - } - ActualStart::Content => { - std::write!(f, "Expected start signal of kind {expected_start:?} but found non-signal element.") + } => { + match actual { + ActualStart::EndOfDocument => { + std::write!(f, "Expected start tag of kind {expected_start:?} but at the end of document.") + } + ActualStart::Start(start) => { + std::write!(f, "Expected start tag of kind {expected_start:?} but found start tag of kind {start:?}.") + } + ActualStart::End(end) => { + std::write!(f, "Expected start tag of kind {expected_start:?} but found end tag of kind {end:?}.") + } + ActualStart::Content => { + std::write!(f, "Expected start tag of kind {expected_start:?} but found non-tag element.") + } } - }, + } } } } diff --git a/crates/rome_formatter/src/prelude.rs b/crates/rome_formatter/src/prelude.rs index 0dec7ae7933..1a3a276a991 100644 --- a/crates/rome_formatter/src/prelude.rs +++ b/crates/rome_formatter/src/prelude.rs @@ -11,7 +11,7 @@ pub use crate::trivia::{ pub use crate::verbatim::{format_suppressed_node, format_unknown_node, format_verbatim_node}; pub use crate::format_element::document::Document; -pub use crate::format_element::signal::{LabelId, Signal, SignalKind}; +pub use crate::format_element::tag::{LabelId, Tag, TagKind}; pub use crate::{ best_fitting, dbg_write, format, format_args, write, Buffer as _, BufferExtensions, Format, diff --git a/crates/rome_formatter/src/printer/call_stack.rs b/crates/rome_formatter/src/printer/call_stack.rs index 16946600e74..243dbe6fa94 100644 --- a/crates/rome_formatter/src/printer/call_stack.rs +++ b/crates/rome_formatter/src/printer/call_stack.rs @@ -1,4 +1,4 @@ -use crate::format_element::signal::SignalKind; +use crate::format_element::tag::TagKind; use crate::format_element::PrintMode; use crate::printer::stack::{Stack, StackedStack}; use crate::printer::Indention; @@ -9,7 +9,7 @@ use std::num::NonZeroU8; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub(super) enum StackFrameKind { Root, - Signal(SignalKind), + Tag(TagKind), } #[derive(Copy, Clone, Eq, PartialEq, Debug)] @@ -83,8 +83,8 @@ impl Default for PrintElementArgs { /// Call stack that stores the [PrintElementCallArgs]. /// -/// New [PrintElementCallArgs] are pushed onto the stack for every [`start`](Signal::is_start) [`Signal`](FormatElement::Signal) -/// and popped when reaching the corresponding [`end`](Signal::is_end) [`Signal`](FormatElement::Signal). +/// New [PrintElementCallArgs] are pushed onto the stack for every [`start`](Tag::is_start) [`Tag`](FormatElement::Tag) +/// and popped when reaching the corresponding [`end`](Tag::is_end) [`Tag`](FormatElement::Tag). pub(super) trait CallStack { type Stack: Stack + Debug; @@ -92,21 +92,21 @@ pub(super) trait CallStack { fn stack_mut(&mut self) -> &mut Self::Stack; - /// Pops the call arguments at the top and asserts that they correspond to a start signal of `kind`. + /// Pops the call arguments at the top and asserts that they correspond to a start tag of `kind`. /// /// Returns `Ok` with the arguments if the kind of the top stack frame matches `kind`, otherwise /// returns `Err`. - fn pop(&mut self, kind: SignalKind) -> PrintResult { + fn pop(&mut self, kind: TagKind) -> PrintResult { let last = self.stack_mut().pop(); match last { Some(StackFrame { - kind: StackFrameKind::Signal(actual_kind), + kind: StackFrameKind::Tag(actual_kind), args, }) if actual_kind == kind => Ok(args), // Start / End kind don't match Some(StackFrame { - kind: StackFrameKind::Signal(expected_kind), + kind: StackFrameKind::Tag(expected_kind), .. }) => Err(PrintError::InvalidDocument(Self::invalid_document_error( kind, @@ -135,12 +135,12 @@ pub(super) trait CallStack { #[cold] fn invalid_document_error( - end_kind: SignalKind, - start_kind: Option, + end_kind: TagKind, + start_kind: Option, ) -> InvalidDocumentError { match start_kind { - None => InvalidDocumentError::StartSignalMissing { kind: end_kind }, - Some(start_kind) => InvalidDocumentError::StartEndSignalMismatch { + None => InvalidDocumentError::StartTagMissing { kind: end_kind }, + Some(start_kind) => InvalidDocumentError::StartEndTagMismatch { start_kind, end_kind, }, @@ -155,8 +155,8 @@ pub(super) trait CallStack { .args } - /// Returns the [SignalKind] of the current stack frame or [None] if this is the root stack frame. - fn top_kind(&self) -> Option { + /// Returns the [TagKind] of the current stack frame or [None] if this is the root stack frame. + fn top_kind(&self) -> Option { match self .stack() .top() @@ -164,14 +164,14 @@ pub(super) trait CallStack { .kind { StackFrameKind::Root => None, - StackFrameKind::Signal(kind) => Some(kind), + StackFrameKind::Tag(kind) => Some(kind), } } - /// Creates a new stack frame for a [FormatElement::Signal] of `kind` with `args` as the call arguments. - fn push(&mut self, kind: SignalKind, args: PrintElementArgs) { + /// Creates a new stack frame for a [FormatElement::Tag] of `kind` with `args` as the call arguments. + fn push(&mut self, kind: TagKind, args: PrintElementArgs) { self.stack_mut().push(StackFrame { - kind: StackFrameKind::Signal(kind), + kind: StackFrameKind::Tag(kind), args, }) } diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index f27987cc2d0..db94982a4fc 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -13,9 +13,9 @@ use crate::{ }; use crate::format_element::document::Document; -use crate::format_element::signal::Condition; -use crate::prelude::signal::{DedentMode, Signal, SignalKind, VerbatimKind}; -use crate::prelude::Signal::EndFill; +use crate::format_element::tag::Condition; +use crate::prelude::tag::{DedentMode, Tag, TagKind, VerbatimKind}; +use crate::prelude::Tag::EndFill; use crate::printer::call_stack::{ CallStack, FitsCallStack, PrintCallStack, PrintElementArgs, StackFrame, }; @@ -82,7 +82,7 @@ impl<'a> Printer<'a> { queue: &mut PrintQueue<'a>, element: &'a FormatElement, ) -> PrintResult<()> { - use Signal::*; + use Tag::*; let args = stack.top(); @@ -203,12 +203,12 @@ impl<'a> Printer<'a> { queue.extend_back(content); } - FormatElement::Signal(StartGroup(id)) => { + FormatElement::Tag(StartGroup(id)) => { let group_mode = match args.mode() { PrintMode::Flat if self.state.measured_group_fits => { // A parent group has already verified that this group fits on a single line // Thus, just continue in flat mode - stack.push(SignalKind::Group, args); + stack.push(TagKind::Group, args); PrintMode::Flat } // The printer is either in expanded mode or it's necessary to re-measure if the group fits @@ -216,9 +216,9 @@ impl<'a> Printer<'a> { _ => { // Measure to see if the group fits up on a single line. If that's the case, // print the group in "flat" mode, otherwise continue in expanded mode - stack.push(SignalKind::Group, args.with_print_mode(PrintMode::Flat)); + stack.push(TagKind::Group, args.with_print_mode(PrintMode::Flat)); let fits = fits_on_line(AllPredicate, queue, stack, self)?; - stack.pop(SignalKind::Group)?; + stack.pop(TagKind::Group)?; let mode = if fits { self.state.measured_group_fits = true; @@ -227,7 +227,7 @@ impl<'a> Printer<'a> { PrintMode::Expanded }; - stack.push(SignalKind::Group, args.with_print_mode(mode)); + stack.push(TagKind::Group, args.with_print_mode(mode)); mode } @@ -238,44 +238,44 @@ impl<'a> Printer<'a> { } } - FormatElement::Signal(StartFill) => { - stack.push(SignalKind::Fill, args); + FormatElement::Tag(StartFill) => { + stack.push(TagKind::Fill, args); self.print_fill_entries(queue, stack)?; } - FormatElement::Signal(StartIndent) => { + FormatElement::Tag(StartIndent) => { stack.push( - SignalKind::Indent, + TagKind::Indent, args.increment_indent_level(self.options.indent_style()), ); } - FormatElement::Signal(StartDedent(mode)) => { + FormatElement::Tag(StartDedent(mode)) => { let args = match mode { DedentMode::Level => args.decrement_indent(), DedentMode::Root => args.reset_indent(), }; - stack.push(SignalKind::Dedent, args); + stack.push(TagKind::Dedent, args); } - FormatElement::Signal(StartAlign(align)) => { - stack.push(SignalKind::Align, args.set_indent_align(align.count())); + FormatElement::Tag(StartAlign(align)) => { + stack.push(TagKind::Align, args.set_indent_align(align.count())); } - FormatElement::Signal(StartConditionalContent(Condition { mode, group_id })) => { + FormatElement::Tag(StartConditionalContent(Condition { mode, group_id })) => { let group_mode = match group_id { None => args.mode(), Some(id) => self.state.group_modes.unwrap_print_mode(*id, element), }; if group_mode != *mode { - queue.skip_content(SignalKind::ConditionalContent); + queue.skip_content(TagKind::ConditionalContent); } else { - stack.push(SignalKind::ConditionalContent, args); + stack.push(TagKind::ConditionalContent, args); } } - FormatElement::Signal(StartIndentIfGroupBreaks(group_id)) => { + FormatElement::Tag(StartIndentIfGroupBreaks(group_id)) => { let group_mode = self.state.group_modes.unwrap_print_mode(*group_id, element); let args = match group_mode { @@ -283,16 +283,16 @@ impl<'a> Printer<'a> { PrintMode::Expanded => args.increment_indent_level(self.options.indent_style), }; - stack.push(SignalKind::IndentIfGroupBreaks, args); + stack.push(TagKind::IndentIfGroupBreaks, args); } - FormatElement::Signal(StartLineSuffix) => { + FormatElement::Tag(StartLineSuffix) => { self.state .line_suffixes - .extend(args, queue.iter_content(SignalKind::LineSuffix)); + .extend(args, queue.iter_content(TagKind::LineSuffix)); } - FormatElement::Signal(StartVerbatim(kind)) => { + FormatElement::Tag(StartVerbatim(kind)) => { if let VerbatimKind::Verbatim { length } = kind { self.state.verbatim_markers.push(TextRange::at( TextSize::from(self.state.buffer.len() as u32), @@ -300,14 +300,14 @@ impl<'a> Printer<'a> { )); } - stack.push(SignalKind::Verbatim, args); + stack.push(TagKind::Verbatim, args); } - FormatElement::Signal(signal @ (StartLabelled(_) | StartEntry)) => { - stack.push(signal.kind(), args); + FormatElement::Tag(tag @ (StartLabelled(_) | StartEntry)) => { + stack.push(tag.kind(), args); } - FormatElement::Signal( - signal @ (EndLabelled + FormatElement::Tag( + tag @ (EndLabelled | EndEntry | EndGroup | EndIndent @@ -319,7 +319,7 @@ impl<'a> Printer<'a> { | EndLineSuffix | EndFill), ) => { - stack.pop(signal.kind())?; + stack.pop(tag.kind())?; } }; @@ -356,9 +356,9 @@ impl<'a> Printer<'a> { queue.push(suffix); } LineSuffixEntry::Args(args) => { - stack.push(SignalKind::LineSuffix, args); + stack.push(TagKind::LineSuffix, args); const LINE_SUFFIX_END: &FormatElement = - &FormatElement::Signal(Signal::EndLineSuffix); + &FormatElement::Tag(Tag::EndLineSuffix); queue.push(LINE_SUFFIX_END); } @@ -392,11 +392,8 @@ impl<'a> Printer<'a> { PrintMode::Expanded }; - if !matches!( - variant.first(), - Some(&FormatElement::Signal(Signal::StartEntry)) - ) { - return invalid_start_signal(SignalKind::Entry, variant.first()); + if !matches!(variant.first(), Some(&FormatElement::Tag(Tag::StartEntry))) { + return invalid_start_tag(TagKind::Entry, variant.first()); } // Skip the first element because we want to override the args for the entry and the @@ -404,9 +401,9 @@ impl<'a> Printer<'a> { let content = &variant[1..]; queue.extend_back(content); - stack.push(SignalKind::Entry, args.with_print_mode(mode)); + stack.push(TagKind::Entry, args.with_print_mode(mode)); let variant_fits = fits_on_line(AllPredicate, queue, stack, self)?; - stack.pop(SignalKind::Entry)?; + stack.pop(TagKind::Entry)?; // Remove the content slice because printing needs the variant WITH the start entry let popped_slice = queue.pop_slice(); @@ -441,7 +438,7 @@ impl<'a> Printer<'a> { ) -> PrintResult<()> { let args = stack.top(); - if matches!(queue.top(), Some(FormatElement::Signal(Signal::EndFill))) { + if matches!(queue.top(), Some(FormatElement::Tag(Tag::EndFill))) { // Empty fill return Ok(()); } @@ -465,7 +462,7 @@ impl<'a> Printer<'a> { )?; // Process remaining items, it's a sequence of separator, item, separator, item... - while matches!(queue.top(), Some(FormatElement::Signal(Signal::StartEntry))) { + while matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) { // A line break in expanded mode is always necessary if the current item didn't fit. // otherwise see if both contents fit on the line. let all_fits = if current_fits { @@ -489,7 +486,7 @@ impl<'a> Printer<'a> { self.print_entry(queue, stack, args.with_print_mode(separator_mode))?; // If this was a trailing separator, exit - if !matches!(queue.top(), Some(FormatElement::Signal(Signal::StartEntry))) { + if !matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) { break; } @@ -519,10 +516,10 @@ impl<'a> Printer<'a> { } } - if queue.top() == Some(&FormatElement::Signal(EndFill)) { + if queue.top() == Some(&FormatElement::Tag(EndFill)) { Ok(()) } else { - invalid_end_signal(SignalKind::Fill, stack.top_kind()) + invalid_end_tag(TagKind::Fill, stack.top_kind()) } } @@ -538,17 +535,14 @@ impl<'a> Printer<'a> { { let start_entry = queue.top(); - if !matches!( - start_entry, - Some(&FormatElement::Signal(Signal::StartEntry)) - ) { - return invalid_start_signal(SignalKind::Entry, start_entry); + if !matches!(start_entry, Some(&FormatElement::Tag(Tag::StartEntry))) { + return invalid_start_tag(TagKind::Entry, start_entry); } // Create a virtual group around each fill entry - stack.push(SignalKind::Group, stack.top().with_print_mode(mode)); + stack.push(TagKind::Group, stack.top().with_print_mode(mode)); let fits = fits_on_line(predicate, queue, stack, self)?; - stack.pop(SignalKind::Group)?; + stack.pop(TagKind::Group)?; Ok(fits) } @@ -565,32 +559,29 @@ impl<'a> Printer<'a> { ) -> PrintResult<()> { let start_entry = queue.top(); - if !matches!( - start_entry, - Some(&FormatElement::Signal(Signal::StartEntry)) - ) { - return invalid_start_signal(SignalKind::Entry, start_entry); + if !matches!(start_entry, Some(&FormatElement::Tag(Tag::StartEntry))) { + return invalid_start_tag(TagKind::Entry, start_entry); } let mut depth = 0; while let Some(element) = queue.pop() { match element { - FormatElement::Signal(Signal::StartEntry) => { + FormatElement::Tag(Tag::StartEntry) => { // Handle the start of the first element by pushing the args on the stack. if depth == 0 { depth = 1; - stack.push(SignalKind::Entry, args); + stack.push(TagKind::Entry, args); continue; } depth += 1; } - FormatElement::Signal(Signal::EndEntry) => { + FormatElement::Tag(Tag::EndEntry) => { depth -= 1; // Reached the end entry, pop the entry from the stack and return. if depth == 0 { - stack.pop(SignalKind::Entry)?; + stack.pop(TagKind::Entry)?; return Ok(()); } } @@ -602,7 +593,7 @@ impl<'a> Printer<'a> { self.print_element(stack, queue, element)?; } - invalid_end_signal(SignalKind::Entry, stack.top_kind()) + invalid_end_tag(TagKind::Entry, stack.top_kind()) } fn print_str(&mut self, content: &str) { @@ -871,7 +862,7 @@ fn fits_element_on_line<'a, 'rest>( stack: &mut FitsCallStack<'rest>, options: &PrinterOptions, ) -> PrintResult { - use Signal::*; + use Tag::*; let args = stack.top(); @@ -953,34 +944,34 @@ fn fits_element_on_line<'a, 'rest>( FormatElement::Interned(content) => queue.extend_back(content), - FormatElement::Signal(StartIndent) => { + FormatElement::Tag(StartIndent) => { stack.push( - SignalKind::Indent, + TagKind::Indent, args.increment_indent_level(options.indent_style()), ); } - FormatElement::Signal(StartDedent(mode)) => { + FormatElement::Tag(StartDedent(mode)) => { let args = match mode { DedentMode::Level => args.decrement_indent(), DedentMode::Root => args.reset_indent(), }; - stack.push(SignalKind::Dedent, args); + stack.push(TagKind::Dedent, args); } - FormatElement::Signal(StartAlign(align)) => { - stack.push(SignalKind::Align, args.set_indent_align(align.count())); + FormatElement::Tag(StartAlign(align)) => { + stack.push(TagKind::Align, args.set_indent_align(align.count())); } - FormatElement::Signal(StartGroup(id)) => { - stack.push(SignalKind::Group, args); + FormatElement::Tag(StartGroup(id)) => { + stack.push(TagKind::Group, args); if let Some(id) = id { state.group_modes.insert_print_mode(*id, args.mode()); } } - FormatElement::Signal(StartConditionalContent(condition)) => { + FormatElement::Tag(StartConditionalContent(condition)) => { let group_mode = match condition.group_id { None => args.mode(), Some(group_id) => state @@ -990,13 +981,13 @@ fn fits_element_on_line<'a, 'rest>( }; if group_mode != condition.mode { - queue.skip_content(SignalKind::ConditionalContent); + queue.skip_content(TagKind::ConditionalContent); } else { - stack.push(SignalKind::ConditionalContent, args); + stack.push(TagKind::ConditionalContent, args); } } - FormatElement::Signal(StartIndentIfGroupBreaks(id)) => { + FormatElement::Tag(StartIndentIfGroupBreaks(id)) => { let group_mode = state .group_modes .get_print_mode(*id) @@ -1004,33 +995,33 @@ fn fits_element_on_line<'a, 'rest>( match group_mode { PrintMode::Flat => { - stack.push(SignalKind::IndentIfGroupBreaks, args); + stack.push(TagKind::IndentIfGroupBreaks, args); } PrintMode::Expanded => { stack.push( - SignalKind::IndentIfGroupBreaks, + TagKind::IndentIfGroupBreaks, args.increment_indent_level(options.indent_style()), ); } } } - FormatElement::Signal(StartLineSuffix) => { - queue.skip_content(SignalKind::LineSuffix); + FormatElement::Tag(StartLineSuffix) => { + queue.skip_content(TagKind::LineSuffix); state.has_line_suffix = true; } - FormatElement::Signal(EndLineSuffix) => { - return invalid_end_signal(SignalKind::LineSuffix, stack.top_kind()); + FormatElement::Tag(EndLineSuffix) => { + return invalid_end_tag(TagKind::LineSuffix, stack.top_kind()); } - FormatElement::Signal( - signal @ (StartFill | StartVerbatim(_) | StartLabelled(_) | StartEntry), + FormatElement::Tag( + tag @ (StartFill | StartVerbatim(_) | StartLabelled(_) | StartEntry), ) => { - stack.push(signal.kind(), args); + stack.push(tag.kind(), args); } - FormatElement::Signal( - signal @ (EndFill + FormatElement::Tag( + tag @ (EndFill | EndVerbatim | EndLabelled | EndEntry @@ -1041,7 +1032,7 @@ fn fits_element_on_line<'a, 'rest>( | EndDedent | EndIndent), ) => { - stack.pop(signal.kind())?; + stack.pop(tag.kind())?; } } @@ -1049,28 +1040,25 @@ fn fits_element_on_line<'a, 'rest>( } #[cold] -fn invalid_end_signal( - end_signal: SignalKind, - start_signal: Option, -) -> PrintResult { - Err(PrintError::InvalidDocument(match start_signal { - None => InvalidDocumentError::StartSignalMissing { kind: end_signal }, - Some(kind) => InvalidDocumentError::StartEndSignalMismatch { - start_kind: end_signal, +fn invalid_end_tag(end_tag: TagKind, start_tag: Option) -> PrintResult { + Err(PrintError::InvalidDocument(match start_tag { + None => InvalidDocumentError::StartTagMissing { kind: end_tag }, + Some(kind) => InvalidDocumentError::StartEndTagMismatch { + start_kind: end_tag, end_kind: kind, }, })) } #[cold] -fn invalid_start_signal(expected: SignalKind, actual: Option<&FormatElement>) -> PrintResult { +fn invalid_start_tag(expected: TagKind, actual: Option<&FormatElement>) -> PrintResult { let start = match actual { None => ActualStart::EndOfDocument, - Some(FormatElement::Signal(signal)) => { - if signal.is_start() { - ActualStart::Start(signal.kind()) + Some(FormatElement::Tag(tag)) => { + if tag.is_start() { + ActualStart::Start(tag.kind()) } else { - ActualStart::End(signal.kind()) + ActualStart::End(tag.kind()) } } Some(_) => ActualStart::Content, diff --git a/crates/rome_formatter/src/printer/queue.rs b/crates/rome_formatter/src/printer/queue.rs index a623bff86bd..15c0a79765c 100644 --- a/crates/rome_formatter/src/printer/queue.rs +++ b/crates/rome_formatter/src/printer/queue.rs @@ -1,7 +1,7 @@ -use crate::format_element::signal::SignalKind; -use crate::prelude::Signal; +use crate::format_element::tag::TagKind; +use crate::prelude::Tag; use crate::printer::stack::{Stack, StackedStack}; -use crate::printer::{invalid_end_signal, invalid_start_signal}; +use crate::printer::{invalid_end_tag, invalid_start_tag}; use crate::{FormatElement, PrintResult}; use std::fmt::Debug; use std::iter::FusedIterator; @@ -88,8 +88,8 @@ pub(super) trait Queue<'a> { self.stack_mut().pop() } - /// Skips all content until it finds the corresponding end signal with the given kind. - fn skip_content(&mut self, kind: SignalKind) + /// Skips all content until it finds the corresponding end tag with the given kind. + fn skip_content(&mut self, kind: TagKind) where Self: Sized, { @@ -100,8 +100,8 @@ pub(super) trait Queue<'a> { } } - /// Iterates over all elements until it finds the matching end signal of the specified kind. - fn iter_content<'q>(&'q mut self, kind: SignalKind) -> QueueContentIterator<'a, 'q, Self> + /// Iterates over all elements until it finds the matching end tag of the specified kind. + fn iter_content<'q>(&'q mut self, kind: TagKind) -> QueueContentIterator<'a, 'q, Self> where Self: Sized, { @@ -226,7 +226,7 @@ impl<'a, Q> FusedIterator for QueueIterator<'a, '_, Q> where Q: Queue<'a> {} pub(super) struct QueueContentIterator<'a, 'q, Q: Queue<'a>> { queue: &'q mut Q, - kind: SignalKind, + kind: TagKind, depth: usize, lifetime: PhantomData<&'a ()>, } @@ -235,7 +235,7 @@ impl<'a, 'q, Q> QueueContentIterator<'a, 'q, Q> where Q: Queue<'a>, { - fn new(queue: &'q mut Q, kind: SignalKind) -> Self { + fn new(queue: &'q mut Q, kind: TagKind) -> Self { Self { queue, kind, @@ -263,8 +263,8 @@ where } match top.expect("Missing end signal.") { - element @ FormatElement::Signal(signal) if signal.kind() == self.kind => { - if signal.is_start() { + element @ FormatElement::Tag(tag) if tag.kind() == self.kind => { + if tag.is_start() { self.depth += 1; } else { self.depth -= 1; @@ -303,7 +303,7 @@ impl FitsPredicate for AllPredicate { } } -/// Filter that takes all elements between two matching [Signal::StartEntry] and [Signal::EndEntry] signals. +/// Filter that takes all elements between two matching [Tag::StartEntry] and [Tag::EndEntry] tags. #[derive(Debug)] pub(super) enum SingleEntryPredicate { Entry { depth: usize }, @@ -321,14 +321,14 @@ impl FitsPredicate for SingleEntryPredicate { let result = match self { SingleEntryPredicate::Done => false, SingleEntryPredicate::Entry { depth } => match element { - FormatElement::Signal(Signal::StartEntry) => { + FormatElement::Tag(Tag::StartEntry) => { *depth += 1; true } - FormatElement::Signal(Signal::EndEntry) => { + FormatElement::Tag(Tag::EndEntry) => { if *depth == 0 { - return invalid_end_signal(SignalKind::Entry, None); + return invalid_end_tag(TagKind::Entry, None); } *depth -= 1; @@ -341,7 +341,7 @@ impl FitsPredicate for SingleEntryPredicate { } FormatElement::Interned(_) => true, element if *depth == 0 => { - return invalid_start_signal(SignalKind::Entry, Some(element)); + return invalid_start_tag(TagKind::Entry, Some(element)); } _ => true, }, @@ -353,9 +353,9 @@ impl FitsPredicate for SingleEntryPredicate { /// Queue filter that returns all elements belonging to the separator and the following item of a fill pair. /// -/// The fill element consists of entries where each entry is separated by [Signal::StartEntry] and [Signal::EndEntry]. -/// This filter takes up to two [Signal::StartEntry]/[Signal::StopEntry] but may end after one if -/// it reaches the [Signal::EndFill] element (last item without a separator). +/// The fill element consists of entries where each entry is separated by [Tag::StartEntry] and [Tag::EndEntry]. +/// This filter takes up to two [Tag::StartEntry]/[Tag::StopEntry] but may end after one if +/// it reaches the [Tag::EndFill] element (last item without a separator). #[derive(Debug)] pub(super) enum SeparatorItemPairPredicate { Separator { depth: usize }, @@ -383,14 +383,14 @@ impl FitsPredicate for SeparatorItemPairPredicate { SeparatorItemPairPredicate::Item { depth } | SeparatorItemPairPredicate::Separator { depth } => { match element { - FormatElement::Signal(Signal::StartEntry) => { + FormatElement::Tag(Tag::StartEntry) => { *depth += 1; true } - FormatElement::Signal(Signal::EndEntry) => { + FormatElement::Tag(Tag::EndEntry) => { if *depth == 0 { - return invalid_end_signal(SignalKind::Entry, None); + return invalid_end_tag(TagKind::Entry, None); } *depth -= 1; @@ -406,13 +406,13 @@ impl FitsPredicate for SeparatorItemPairPredicate { true } // No item, trailing separator only - FormatElement::Signal(Signal::EndFill) if *depth == 0 && is_item => { + FormatElement::Tag(Tag::EndFill) if *depth == 0 && is_item => { *self = SeparatorItemPairPredicate::Done; false } FormatElement::Interned(_) => true, element if *depth == 0 => { - return invalid_start_signal(SignalKind::Entry, Some(element)); + return invalid_start_tag(TagKind::Entry, Some(element)); } _ => true, } @@ -427,21 +427,16 @@ impl FitsPredicate for SeparatorItemPairPredicate { #[cfg(test)] mod tests { use crate::format_element::LineMode; - use crate::prelude::Signal; + use crate::prelude::Tag; use crate::printer::queue::{PrintQueue, Queue}; use crate::FormatElement; #[test] fn extend_back_pop_last() { - let mut queue = PrintQueue::new(&[ - FormatElement::Signal(Signal::StartEntry), - FormatElement::Space, - ]); + let mut queue = + PrintQueue::new(&[FormatElement::Tag(Tag::StartEntry), FormatElement::Space]); - assert_eq!( - queue.pop(), - Some(&FormatElement::Signal(Signal::StartEntry)) - ); + assert_eq!(queue.pop(), Some(&FormatElement::Tag(Tag::StartEntry))); queue.extend_back(&[FormatElement::Line(LineMode::SoftOrSpace)]); @@ -456,15 +451,10 @@ mod tests { #[test] fn extend_back_empty_queue() { - let mut queue = PrintQueue::new(&[ - FormatElement::Signal(Signal::StartEntry), - FormatElement::Space, - ]); + let mut queue = + PrintQueue::new(&[FormatElement::Tag(Tag::StartEntry), FormatElement::Space]); - assert_eq!( - queue.pop(), - Some(&FormatElement::Signal(Signal::StartEntry)) - ); + assert_eq!(queue.pop(), Some(&FormatElement::Tag(Tag::StartEntry))); assert_eq!(queue.pop(), Some(&FormatElement::Space)); queue.extend_back(&[FormatElement::Line(LineMode::SoftOrSpace)]); diff --git a/crates/rome_formatter/src/trivia.rs b/crates/rome_formatter/src/trivia.rs index 9ff8dfe76be..48ca05bd3db 100644 --- a/crates/rome_formatter/src/trivia.rs +++ b/crates/rome_formatter/src/trivia.rs @@ -1,6 +1,6 @@ //! Provides builders for comments and skipped token trivia. -use crate::format_element::signal::VerbatimKind; +use crate::format_element::tag::VerbatimKind; use crate::prelude::*; use crate::{ comments::{CommentKind, CommentStyle}, @@ -542,13 +542,13 @@ impl FormatSkippedTokenTrivia<'_, L> { let skipped_range = skipped_range.unwrap_or_else(|| TextRange::empty(self.token.text_range().start())); - f.write_element(FormatElement::Signal(Signal::StartVerbatim( + f.write_element(FormatElement::Tag(Tag::StartVerbatim( VerbatimKind::Verbatim { length: skipped_range.len(), }, )))?; write!(f, [syntax_token_text_slice(self.token, skipped_range)])?; - f.write_element(FormatElement::Signal(Signal::EndVerbatim))?; + f.write_element(FormatElement::Tag(Tag::EndVerbatim))?; // Write whitespace separator between skipped/last comment and token if dangling_comments.is_empty() { diff --git a/crates/rome_formatter/src/verbatim.rs b/crates/rome_formatter/src/verbatim.rs index 340d2dba5d7..60da1b60c43 100644 --- a/crates/rome_formatter/src/verbatim.rs +++ b/crates/rome_formatter/src/verbatim.rs @@ -1,4 +1,4 @@ -use crate::format_element::signal::VerbatimKind; +use crate::format_element::tag::VerbatimKind; use crate::prelude::*; use crate::trivia::{FormatLeadingComments, FormatTrailingComments}; use crate::{write, CstFormatContext}; @@ -58,7 +58,7 @@ where |source_map| source_map.trimmed_source_range(self.node), ); - f.write_element(FormatElement::Signal(Signal::StartVerbatim(self.kind)))?; + f.write_element(FormatElement::Tag(Tag::StartVerbatim(self.kind)))?; fn source_range(f: &Formatter, range: TextRange) -> TextRange where @@ -138,7 +138,7 @@ where write!(f, [FormatTrailingComments::Comments(outside_trimmed_range)])?; } - f.write_element(FormatElement::Signal(Signal::EndVerbatim)) + f.write_element(FormatElement::Tag(Tag::EndVerbatim)) } } diff --git a/crates/rome_js_formatter/src/js/expressions/template_element.rs b/crates/rome_js_formatter/src/js/expressions/template_element.rs index d151fbebb1f..8c2979f4d92 100644 --- a/crates/rome_js_formatter/src/js/expressions/template_element.rs +++ b/crates/rome_js_formatter/src/js/expressions/template_element.rs @@ -1,6 +1,6 @@ use crate::prelude::*; use rome_formatter::format_element::document::Document; -use rome_formatter::prelude::signal::Signal; +use rome_formatter::prelude::tag::Tag; use rome_formatter::printer::{PrintWidth, Printer}; use rome_formatter::{ format_args, write, CstFormatContext, FormatOptions, FormatRuleWithOptions, VecBuffer, @@ -218,13 +218,13 @@ where // Adds as many nested `indent` elements until it reaches the desired indention level. let format_indented = format_with(|f| { for _ in 0..level { - f.write_element(FormatElement::Signal(Signal::StartIndent))?; + f.write_element(FormatElement::Tag(Tag::StartIndent))?; } write!(f, [content])?; for _ in 0..level { - f.write_element(FormatElement::Signal(Signal::EndIndent))?; + f.write_element(FormatElement::Tag(Tag::EndIndent))?; } Ok(()) diff --git a/crates/rome_js_formatter/src/jsx/lists/child_list.rs b/crates/rome_js_formatter/src/jsx/lists/child_list.rs index 1b99403a311..ee9b9027b10 100644 --- a/crates/rome_js_formatter/src/jsx/lists/child_list.rs +++ b/crates/rome_js_formatter/src/jsx/lists/child_list.rs @@ -4,7 +4,7 @@ use crate::utils::jsx::{ JsxRawSpace, JsxSpace, }; use crate::JsFormatter; -use rome_formatter::format_element::signal::Signal; +use rome_formatter::format_element::tag::Tag; use rome_formatter::{format_args, write, CstFormatContext, FormatRuleWithOptions, VecBuffer}; use rome_js_syntax::{JsxAnyChild, JsxChildList}; use std::cell::RefCell; @@ -498,13 +498,13 @@ impl MultilineBuilder { match self.layout { MultilineLayout::Fill => { // Make sure that the separator and content only ever write a single element - buffer.write_element(FormatElement::Signal(Signal::StartEntry))?; + buffer.write_element(FormatElement::Tag(Tag::StartEntry))?; write!(buffer, [content])?; - buffer.write_element(FormatElement::Signal(Signal::EndEntry))?; + buffer.write_element(FormatElement::Tag(Tag::EndEntry))?; - buffer.write_element(FormatElement::Signal(Signal::StartEntry))?; + buffer.write_element(FormatElement::Tag(Tag::StartEntry))?; write!(buffer, [separator])?; - buffer.write_element(FormatElement::Signal(Signal::EndEntry))?; + buffer.write_element(FormatElement::Tag(Tag::EndEntry))?; } MultilineLayout::NoFill => { write!(buffer, [content, separator])?; @@ -535,9 +535,9 @@ impl Format for FormatMultilineChildren { if let Some(elements) = f.intern_vec(self.elements.take()) { match self.layout { MultilineLayout::Fill => f.write_elements([ - FormatElement::Signal(Signal::StartFill), + FormatElement::Tag(Tag::StartFill), elements, - FormatElement::Signal(Signal::EndFill), + FormatElement::Tag(Tag::EndFill), ])?, MultilineLayout::NoFill => f.write_element(elements)?, }; diff --git a/crates/rome_js_formatter/src/ts/lists/type_member_list.rs b/crates/rome_js_formatter/src/ts/lists/type_member_list.rs index 29a2139fdf1..0519a2584f6 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_member_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_member_list.rs @@ -38,7 +38,7 @@ impl Format for TsTypeMemberItem { let mut recording = f.start_recording(); write!(recording, [self.member.format()])?; - is_verbatim = recording.stop().end_signal(SignalKind::Verbatim).is_some(); + is_verbatim = recording.stop().end_tag(TagKind::Verbatim).is_some(); Ok(()) }))] diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 2701f1304b1..480e32d912d 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -198,12 +198,13 @@ impl Format for FormatWithSemicolon<'_> { let written = recording.stop(); - let is_unknown = written - .start_signal(SignalKind::Verbatim) - .map_or(false, |signal| match signal { - Signal::StartVerbatim(kind) => kind.is_unknown(), - _ => unreachable!(), - }); + let is_unknown = + written + .start_tag(TagKind::Verbatim) + .map_or(false, |signal| match signal { + Tag::StartVerbatim(kind) => kind.is_unknown(), + _ => unreachable!(), + }); if let Some(semicolon) = self.semicolon { write!(f, [semicolon.format()])?; diff --git a/xtask/contributors/src/main.rs b/xtask/contributors/src/main.rs index 998693c740e..aa342035979 100644 --- a/xtask/contributors/src/main.rs +++ b/xtask/contributors/src/main.rs @@ -4,7 +4,7 @@ use std::fmt::Write; use xtask::glue::fs2; use xtask::*; -/// A token is needed to run this script. To create a token, go to https://github.com/settings/tokens +/// A token is needed to run this script. To create a token, go to /// and give it read access to the repository. /// /// Only users that have read rights can run this script