Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow at most two lines between top-level elements #247

Merged
merged 9 commits into from
Feb 21, 2025
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

# Development version

- We now allow up to 2 lines between top-level elements of a file. This makes it possible to separate long scripts into visually distinct sections (#40).

- Unary formulas (i.e. anonymous functions) like `~ .x + 1` now add a space between the `~` and the right-hand side, unless the right-hand side is very simple, like `~foo` or `~1` (#235).

- Semicolons at the very start or very end of a file no longer cause the parser to panic (#238).
Expand Down
21 changes: 21 additions & 0 deletions crates/air_r_formatter/src/formatter_ext.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use biome_formatter::prelude::{hard_line_break, Formatter, Line};

use crate::joiner_ext::{EmptyLines, JoinNodesBuilderExt};

pub trait FormatterExt<'buf, Context> {
/// Specialized version of `join_nodes_with_hardline()` that allows up to 2
/// hard lines.
fn join_nodes_with_hardline_ext<'a>(
&'a mut self,
empty_lines: EmptyLines,
) -> JoinNodesBuilderExt<'a, 'buf, Line, Context>;
}

impl<'buf, Context> FormatterExt<'buf, Context> for Formatter<'buf, Context> {
fn join_nodes_with_hardline_ext<'a>(
&'a mut self,
empty_lines: EmptyLines,
) -> JoinNodesBuilderExt<'a, 'buf, Line, Context> {
JoinNodesBuilderExt::new(hard_line_break(), empty_lines, self)
}
}
110 changes: 110 additions & 0 deletions crates/air_r_formatter/src/joiner_ext.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use biome_formatter::{prelude::*, write, Format, FormatResult};
use biome_rowan::{Language, SyntaxNode};

/// The maximum number of empty lines allowed between elements
#[derive(Debug, Clone, Copy, Default)]
pub enum EmptyLines {
#[default]
Single,
Double,
}

/// Version of `JoinNodesBuilder` that can be configured to respect up to two lines between inputs.
/// From https://github.com/biomejs/biome/blob/main/crates/biome_formatter/src/comments/builder.rs
#[must_use = "must eventually call `finish()` on Format builders"]
pub struct JoinNodesBuilderExt<'fmt, 'buf, Separator, Context> {
result: FormatResult<()>,
/// The separator to insert between nodes. Either a soft or hard line break
separator: Separator,
fmt: &'fmt mut Formatter<'buf, Context>,
has_elements: bool,
empty_lines: EmptyLines,
}

impl<'fmt, 'buf, Separator, Context> JoinNodesBuilderExt<'fmt, 'buf, Separator, Context> {
pub(crate) fn new(
separator: Separator,
empty_lines: EmptyLines,
fmt: &'fmt mut Formatter<'buf, Context>,
) -> Self {
Self {
result: Ok(()),
separator,
fmt,
has_elements: false,
empty_lines,
}
}
}

impl<Separator, Context> JoinNodesBuilderExt<'_, '_, Separator, Context>
where
Separator: Format<Context>,
{
/// Adds a new node with the specified formatted content to the output, respecting any new lines
/// that appear before the node in the input source.
pub fn entry<L: Language>(&mut self, node: &SyntaxNode<L>, content: &dyn Format<Context>) {
self.result = self.result.and_then(|_| {
if self.has_elements {
let n_lines = get_lines_before(node);

match self.empty_lines {
EmptyLines::Single => {
if n_lines > 1 {
write!(self.fmt, [empty_line()])?;
} else {
self.separator.fmt(self.fmt)?;
}
}
// AIR: This branch is the main difference with the upstream variant.
// We use Biome's `empty_line()` to compress an arbitrary number of
// empty lines down to one, and then we force one more newline in.
// Note that if empty lines follow the element rather than
// precede it, this compression will not work as expected.
EmptyLines::Double =>
{
#[allow(clippy::comparison_chain)]
if n_lines > 2 {
write!(self.fmt, [empty_line(), text("\n")])?;
} else if n_lines == 2 {
write!(self.fmt, [empty_line()])?;
} else {
self.separator.fmt(self.fmt)?;
}
}
}
}

self.has_elements = true;

write!(self.fmt, [content])
});
}

/// Writes an entry without adding a separating line break or empty line.
pub fn entry_no_separator(&mut self, content: &dyn Format<Context>) {
self.result = self.result.and_then(|_| {
self.has_elements = true;

write!(self.fmt, [content])
})
}

/// Adds an iterator of entries to the output. Each entry is a `(node, content)` tuple.
pub fn entries<L, F, I>(&mut self, entries: I) -> &mut Self
where
L: Language,
F: Format<Context>,
I: IntoIterator<Item = (SyntaxNode<L>, F)>,
{
for (node, content) in entries {
self.entry(&node, &content)
}

self
}

pub fn finish(&mut self) -> FormatResult<()> {
self.result
}
}
2 changes: 2 additions & 0 deletions crates/air_r_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub mod comments;
pub mod context;
mod cst;
pub mod either;
pub mod formatter_ext;
pub mod joiner_ext;
mod prelude;
mod r;
pub(crate) mod separated;
Expand Down
8 changes: 7 additions & 1 deletion crates/air_r_formatter/src/r/auxiliary/root.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::joiner_ext::EmptyLines;
use crate::prelude::*;
use crate::r::lists::expression_list::FormatRExpressionListOptions;
use air_r_syntax::RRoot;
use air_r_syntax::RRootFields;
use air_r_syntax::RSyntaxNode;
Expand Down Expand Up @@ -28,11 +30,15 @@ impl FormatNodeRule<RRoot> for FormatRRoot {
eof_token,
} = node.as_fields();

let options = FormatRExpressionListOptions {
empty_lines: EmptyLines::Double,
};

write!(
f,
[
bom_token.format(),
expressions.format(),
expressions.format().with_options(options),
hard_line_break(),
format_removed(&eof_token?),
]
Expand Down
27 changes: 22 additions & 5 deletions crates/air_r_formatter/src/r/lists/expression_list.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
use crate::prelude::*;
use crate::{formatter_ext::FormatterExt, joiner_ext::EmptyLines, prelude::*};
use air_r_syntax::RExpressionList;
use biome_formatter::FormatRuleWithOptions;

#[derive(Debug, Clone, Default)]
pub(crate) struct FormatRExpressionList;
pub(crate) struct FormatRExpressionList {
pub(crate) empty_lines: EmptyLines,
}

#[derive(Default, Debug, Clone)]
pub(crate) struct FormatRExpressionListOptions {
pub(crate) empty_lines: EmptyLines,
}

impl FormatRule<RExpressionList> for FormatRExpressionList {
type Context = RFormatContext;
fn fmt(&self, node: &RExpressionList, f: &mut RFormatter) -> FormatResult<()> {
// This is one of the few cases where we _do_ want to respect empty
// lines from the input, so we can use `join_nodes_with_hardline`.
let mut join = f.join_nodes_with_hardline();
let mut join = f.join_nodes_with_hardline_ext(self.empty_lines);

for rule in node {
join.entry(rule.syntax(), &format_or_verbatim(rule.format()));
Expand All @@ -16,3 +24,12 @@ impl FormatRule<RExpressionList> for FormatRExpressionList {
join.finish()
}
}

impl FormatRuleWithOptions<RExpressionList> for FormatRExpressionList {
type Options = FormatRExpressionListOptions;

fn with_options(mut self, options: Self::Options) -> Self {
self.empty_lines = options.empty_lines;
self
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,7 @@ base_version <-
b_get(brand, "defaults", "bootstrap", "version") %||%
version_default()


# https://github.com/posit-dev/air/issues/220
data <-
starwars |>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ NULL

# fmt: skip file

1 + 1
1+1



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ NULL

# fmt: skip file

1 + 1
1+1



Expand Down Expand Up @@ -51,6 +51,7 @@ NULL

1 + 1


# bar

2
Expand Down
1 change: 1 addition & 0 deletions crates/air_r_formatter/tests/specs/r/pipelines.R.snap
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ mtcars |>
argument_that_is_quite_long = argument_that_is_quite_long
)


# RHS of assignment should stay on same line as the `<-` operator
name <- mtcars |>
mutate(foo = 1) %>%
Expand Down
42 changes: 42 additions & 0 deletions crates/air_r_formatter/tests/specs/r/program.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@




# Up to two lines between elements
1



# Up to two lines between elements

2



# Up to two lines between elements

fn <- function() {
1


# Up to one line between elements
2
}


# Up to two lines between elements
# Currently failing but that doesn't seem too bad: It makes it so that a comment
# is required to stick to its node with at most one empty line.



1



# Up to two lines between elements.
# Currently failing but a trailing comment in the file does not matter too much.
# To change the behaviour of these last two examples we'd have to fully take
# over formatting of trivia in expression list


98 changes: 98 additions & 0 deletions crates/air_r_formatter/tests/specs/r/program.R.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
---
source: crates/air_formatter_test/src/snapshot_builder.rs
info: r/program.R
---
# Input

```R




# Up to two lines between elements
1



# Up to two lines between elements

2



# Up to two lines between elements

fn <- function() {
1


# Up to one line between elements
2
}


# Up to two lines between elements
# Currently failing but that doesn't seem too bad: It makes it so that a comment
# is required to stick to its node with at most one empty line.



1



# Up to two lines between elements.
# Currently failing but a trailing comment in the file does not matter too much.
# To change the behaviour of these last two examples we'd have to fully take
# over formatting of trivia in expression list



```


=============================

# Outputs

## Output 1

-----
Indent style: Space
Indent width: 2
Line ending: LF
Line width: 80
Persistent line breaks: Respect
-----

```R
# Up to two lines between elements
1


# Up to two lines between elements

2


# Up to two lines between elements

fn <- function() {
1

# Up to one line between elements
2
}


# Up to two lines between elements
# Currently failing but that doesn't seem too bad: It makes it so that a comment
# is required to stick to its node with at most one empty line.

1

# Up to two lines between elements.
# Currently failing but a trailing comment in the file does not matter too much.
# To change the behaviour of these last two examples we'd have to fully take
# over formatting of trivia in expression list
```