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

Commit

Permalink
Documentation and naming
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser committed Sep 16, 2022
1 parent 83ef769 commit 873b9a9
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 18 deletions.
57 changes: 57 additions & 0 deletions crates/rome_formatter/src/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,63 @@ impl<Context> std::fmt::Debug for BlockIndent<'_, Context> {
}
}

/// Adds spaces around the content if its enclosing group fits on a line, otherwise indents the content and separates it by line breaks.
///
/// # Examples
///
/// Adds line breaks and indents the content if the enclosing group doesn't fit on the line.
///
/// ```
/// use rome_formatter::{format, format_args, LineWidth, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// let context = SimpleFormatContext::new(SimpleFormatOptions {
/// line_width: LineWidth::try_from(10).unwrap(),
/// ..SimpleFormatOptions::default()
/// });
///
/// let elements = format!(context, [
/// group(&format_args![
/// text("{"),
/// soft_line_indent_or_spaced(&format_args![
/// text("aPropertyThatExceeds"),
/// text(":"),
/// space(),
/// text("'line width'"),
/// ]),
/// text("}")
/// ])
/// ]).unwrap();
///
/// assert_eq!(
/// "{\n\taPropertyThatExceeds: 'line width'\n}",
/// elements.print().as_code()
/// );
/// ```
///
/// Adds spaces around the content if the group fits on the line
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// let elements = format!(SimpleFormatContext::default(), [
/// group(&format_args![
/// text("{"),
/// soft_line_indent_or_spaced(&format_args![
/// text("a"),
/// text(":"),
/// space(),
/// text("5"),
/// ]),
/// text("}")
/// ])
/// ]).unwrap();
///
/// assert_eq!(
/// "{ a: 5 }",
/// elements.print().as_code()
/// );
/// ```
pub fn soft_line_indent_or_spaced<Context>(
content: &impl Format<Context>,
) -> SoftLineIndentOrSpaced<Context> {
Expand Down
1 change: 1 addition & 0 deletions crates/rome_formatter/src/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ impl<Context> Formatter<'_, Context>
where
Context: CstFormatContext,
{
/// Returns the comments from the context.
pub fn comments(&self) -> &Comments<Context::Language> {
self.context().comments()
}
Expand Down
2 changes: 1 addition & 1 deletion crates/rome_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub mod prelude;
pub mod printed_tokens;
pub mod printer;
mod source_map;
pub mod token;
pub mod trivia;
mod verbatim;

use crate::formatter::Formatter;
Expand Down
2 changes: 1 addition & 1 deletion crates/rome_formatter/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ pub use crate::format_element::*;
pub use crate::format_extensions::{FormatOptional as _, MemoizeFormat, Memoized};
pub use crate::formatter::Formatter;
pub use crate::printer::PrinterOptions;
pub use crate::token::{
pub use crate::trivia::{
format_dangling_comments, format_leading_comments, format_only_if_breaks, format_removed,
format_replaced, format_trailing_comments, format_trimmed_token,
};
Expand Down
3 changes: 2 additions & 1 deletion crates/rome_formatter/src/source_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,13 +382,14 @@ pub struct TransformSourceMapBuilder {
}

impl TransformSourceMapBuilder {
/// Creates a new builder for a source map that maps positions back to the passed `root` tree.
/// Creates a new builder.
pub fn new() -> Self {
Self {
..Default::default()
}
}

/// Creates a new builder for a document with the given source.
pub fn with_source(source: String) -> Self {
Self {
source_text: source,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
//! Provides builders for comments and skipped token trivia.

use crate::prelude::*;
use crate::{
write, Argument, Arguments, CommentKind, CommentStyle, CstFormatContext, FormatRefWithRule,
GroupId, SourceComment, TextRange, VecBuffer,
comments::{CommentKind, CommentStyle},
write, Argument, Arguments, CstFormatContext, FormatRefWithRule, GroupId, SourceComment,
TextRange, VecBuffer,
};
use rome_rowan::{Language, SyntaxNode, SyntaxToken};

///! Provides builders for formatting a CST.

/// Formats the leading comments of `node`
pub const fn format_leading_comments<L: Language>(
node: &SyntaxNode<L>,
Expand Down Expand Up @@ -134,6 +135,7 @@ where
}
}

/// Formats the dangling comments of `node`.
pub const fn format_dangling_comments<L: Language>(
node: &SyntaxNode<L>,
) -> FormatDanglingComments<L> {
Expand All @@ -157,16 +159,51 @@ pub enum FormatDanglingComments<'a, L: Language> {

#[derive(Copy, Clone, Debug)]
pub enum DanglingIndentMode {
/// Writes every comment on its own line and indents them with a block indent.
///
/// # Examples
/// ```ignore
/// [
/// /* comment */
/// ]
///
/// [
/// /* comment */
/// /* multiple */
/// ]
/// ```
Block,

/// Writes every comment on its own line and indents them with a soft line indent.
/// Guarantees to write a line break if the last formatted comment is a [line](CommentKind::Line) comment.
///
/// # Examples
///
/// ```ignore
/// [/* comment */]
///
/// [
/// /* comment */
/// /* other */
/// ]
///
/// [
/// // line
/// ]
/// ```
Soft,

/// Writes every comment on its own line.
None,
}

impl<L: Language> FormatDanglingComments<'_, L> {
/// Indents the comments with a [block](DanglingIndentMode::Block) indent.
pub fn with_block_indent(self) -> Self {
self.with_indent_mode(DanglingIndentMode::Block)
}

/// Indents the comments with a [soft block](DanglingIndentMode::Soft) indent.
pub fn with_soft_block_indent(self) -> Self {
self.with_indent_mode(DanglingIndentMode::Soft)
}
Expand Down Expand Up @@ -239,10 +276,10 @@ where
}
}

/// Formats a token without its leading or trailing trivia
/// Formats a token without its skipped token trivia
///
/// ## Warning
/// It's your responsibility to format leading or trailing comments and skipped trivia.
/// It's your responsibility to format any skipped trivia.
pub const fn format_trimmed_token<L: Language>(token: &SyntaxToken<L>) -> FormatTrimmedToken<L> {
FormatTrimmedToken { token }
}
Expand All @@ -261,10 +298,7 @@ where
syntax_token_text_slice(self.token, trimmed_range).fmt(f)
}
}
/// Formats the leading and trailing trivia of a removed token.
///
/// Formats all leading and trailing comments up to the first line break or skipped token trivia as a trailing
/// comment of the previous token. The remaining trivia is then printed as leading trivia of the next token.
/// Formats the skipped token trivia of a removed token and marks the token as tracked.
pub const fn format_removed<L>(token: &SyntaxToken<L>) -> FormatRemoved<L>
where
L: Language,
Expand Down Expand Up @@ -295,7 +329,7 @@ where

/// Print out a `token` from the original source with a different `content`.
///
/// This will print the trivia that belong to `token` to `content`;
/// This will print the skipped token trivia that belong to `token` to `content`;
/// `token` is then marked as consumed by the formatter.
pub fn format_replaced<'a, 'content, L, Context>(
token: &'a SyntaxToken<L>,
Expand All @@ -310,7 +344,7 @@ where
}
}

/// Formats a token's leading and trailing trivia but uses the provided content instead
/// Formats a token's skipped token trivia but uses the provided content instead
/// of the token in the formatted output.
#[derive(Copy, Clone)]
pub struct FormatReplaced<'a, 'content, L, C>
Expand All @@ -335,7 +369,7 @@ where
}
}

/// Formats the given token only if the group does break and otherwise retains the token's trivia.
/// Formats the given token only if the group does break and otherwise retains the token's skipped token trivia.
pub fn format_only_if_breaks<'a, 'content, L, Content, Context>(
token: &'a SyntaxToken<L>,
content: &'content Content,
Expand All @@ -351,7 +385,7 @@ where
}
}

/// Formats a token with its leading and trailing trivia that only gets printed if its enclosing
/// Formats a token with its skipped token trivia that only gets printed if its enclosing
/// group does break but otherwise gets omitted from the formatted output.
pub struct FormatOnlyIfBreaks<'a, 'content, L, C>
where
Expand Down Expand Up @@ -390,12 +424,14 @@ where
}
}

/// Formats the skipped token trivia of `token`.
pub const fn format_skipped_token_trivia<L: Language>(
token: &SyntaxToken<L>,
) -> FormatSkippedTokenTrivia<L> {
FormatSkippedTokenTrivia { token }
}

/// Formats the skipped token trivia of `token`.
pub struct FormatSkippedTokenTrivia<'a, L: Language> {
token: &'a SyntaxToken<L>,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/rome_formatter/src/verbatim.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::prelude::*;
use crate::token::{FormatLeadingComments, FormatTrailingComments};
use crate::trivia::{FormatLeadingComments, FormatTrailingComments};
use crate::VecBuffer;
use crate::{write, CstFormatContext};
use rome_rowan::{Direction, Language, SyntaxElement, SyntaxNode, TextRange};
Expand Down

0 comments on commit 873b9a9

Please sign in to comment.