Skip to content

Commit

Permalink
Move empty_parenthesized into the parentheses.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Aug 8, 2023
1 parent 404e334 commit 833c02b
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 77 deletions.
52 changes: 0 additions & 52 deletions crates/ruff_python_formatter/src/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use ruff_python_ast::Ranged;
use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{TextRange, TextSize};

use crate::comments::{dangling_comments, trailing_comments, SourceComment};
use crate::context::{NodeLevel, WithNodeLevel};
use crate::prelude::*;
use crate::MagicTrailingComma;
Expand Down Expand Up @@ -209,54 +208,3 @@ impl<'fmt, 'ast, 'buf> JoinCommaSeparatedBuilder<'fmt, 'ast, 'buf> {
})
}
}

/// Format comments inside empty parentheses, brackets or curly braces.
///
/// Empty `()`, `[]` and `{}` are special because there can be dangling comments, and they can be in
/// two positions:
/// ```python
/// x = [ # end-of-line
/// # own line
/// ]
/// ```
/// These comments are dangling because they can't be assigned to any element inside as they would
/// in all other cases.
pub(crate) fn empty_parenthesized_with_dangling_comments(
opening: StaticText,
comments: &[SourceComment],
closing: StaticText,
) -> EmptyWithDanglingComments {
EmptyWithDanglingComments {
opening,
comments,
closing,
}
}

pub(crate) struct EmptyWithDanglingComments<'a> {
opening: StaticText,
comments: &'a [SourceComment],
closing: StaticText,
}

impl<'ast> Format<PyFormatContext<'ast>> for EmptyWithDanglingComments<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> {
let end_of_line_split = self
.comments
.partition_point(|comment| comment.line_position().is_end_of_line());
debug_assert!(self.comments[end_of_line_split..]
.iter()
.all(|comment| comment.line_position().is_own_line()));
write!(
f,
[group(&format_args![
self.opening,
// end-of-line comments
trailing_comments(&self.comments[..end_of_line_split]),
// own line comments, which need to be indented
soft_block_indent(&dangling_comments(&self.comments[end_of_line_split..])),
self.closing
])]
)
}
}
8 changes: 5 additions & 3 deletions crates/ruff_python_formatter/src/expression/expr_dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ use ruff_python_ast::Ranged;
use ruff_python_ast::{Expr, ExprDict};
use ruff_text_size::TextRange;

use crate::builders::empty_parenthesized_with_dangling_comments;
use crate::comments::leading_comments;
use crate::expression::parentheses::{parenthesized, NeedsParentheses, OptionalParentheses};
use crate::expression::parentheses::{
empty_parenthesized, parenthesized, NeedsParentheses, OptionalParentheses,
};
use crate::prelude::*;
use crate::FormatNodeRule;

Expand Down Expand Up @@ -69,7 +70,8 @@ impl FormatNodeRule<ExprDict> for FormatExprDict {
let dangling = comments.dangling_comments(item);

if values.is_empty() {
return empty_parenthesized_with_dangling_comments(text("{"), dangling, text("}"))
return empty_parenthesized("{", "}")
.with_dangling_comments(dangling)
.fmt(f);
}

Expand Down
10 changes: 6 additions & 4 deletions crates/ruff_python_formatter/src/expression/expr_list.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use ruff_formatter::prelude::{format_with, text};
use ruff_formatter::prelude::format_with;
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::{ExprList, Ranged};

use crate::builders::empty_parenthesized_with_dangling_comments;
use crate::expression::parentheses::{parenthesized, NeedsParentheses, OptionalParentheses};
use crate::expression::parentheses::{
empty_parenthesized, parenthesized, NeedsParentheses, OptionalParentheses,
};
use crate::prelude::*;
use crate::FormatNodeRule;

Expand All @@ -22,7 +23,8 @@ impl FormatNodeRule<ExprList> for FormatExprList {
let dangling = comments.dangling_comments(item);

if elts.is_empty() {
return empty_parenthesized_with_dangling_comments(text("["), dangling, text("]"))
return empty_parenthesized("[", "]")
.with_dangling_comments(dangling)
.fmt(f);
}

Expand Down
9 changes: 6 additions & 3 deletions crates/ruff_python_formatter/src/expression/expr_tuple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ use ruff_python_ast::ExprTuple;
use ruff_python_ast::{Expr, Ranged};
use ruff_text_size::TextRange;

use crate::builders::{empty_parenthesized_with_dangling_comments, parenthesize_if_expands};
use crate::expression::parentheses::{parenthesized, NeedsParentheses, OptionalParentheses};
use crate::builders::parenthesize_if_expands;
use crate::expression::parentheses::{
empty_parenthesized, parenthesized, NeedsParentheses, OptionalParentheses,
};
use crate::prelude::*;

#[derive(Eq, PartialEq, Debug, Default)]
Expand Down Expand Up @@ -117,7 +119,8 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
// In all other cases comments get assigned to a list element
match elts.as_slice() {
[] => {
return empty_parenthesized_with_dangling_comments(text("("), dangling, text(")"))
return empty_parenthesized("(", ")")
.with_dangling_comments(dangling)
.fmt(f);
}
[single] => match self.parentheses {
Expand Down
70 changes: 69 additions & 1 deletion crates/ruff_python_formatter/src/expression/parentheses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::Ranged;
use ruff_python_trivia::{first_non_trivia_token, SimpleToken, SimpleTokenKind, SimpleTokenizer};

use crate::comments::{dangling_open_parenthesis_comments, SourceComment};
use crate::comments::{
dangling_comments, dangling_open_parenthesis_comments, trailing_comments, SourceComment,
};
use crate::context::{NodeLevel, WithNodeLevel};
use crate::prelude::*;

Expand Down Expand Up @@ -316,6 +318,72 @@ impl<'ast> Format<PyFormatContext<'ast>> for FormatInParenthesesOnlyGroup<'_, 'a
}
}

/// Format comments inside empty parentheses, brackets or curly braces.
///
/// Empty `()`, `[]` and `{}` are special because there can be dangling comments, and they can be in
/// two positions:
/// ```python
/// x = [ # end-of-line
/// # own line
/// ]
/// ```
/// These comments are dangling because they can't be assigned to any element inside as they would
/// in all other cases.
pub(crate) fn empty_parenthesized<'content>(
left: &'static str,
right: &'static str,
) -> FormatEmptyParenthesized<'content> {
FormatEmptyParenthesized {
left,
comments: &[],
right,
}
}

pub(crate) struct FormatEmptyParenthesized<'content> {
left: &'static str,
comments: &'content [SourceComment],
right: &'static str,
}

impl<'content> FormatEmptyParenthesized<'content> {
/// Inserts any dangling comments that should be placed immediately after the open parenthesis.
/// For example:
/// ```python
/// ( # comment
/// # comment
/// )
/// ```
pub(crate) fn with_dangling_comments(
self,
comments: &'content [SourceComment],
) -> FormatEmptyParenthesized<'content> {
FormatEmptyParenthesized { comments, ..self }
}
}

impl Format<PyFormatContext<'_>> for FormatEmptyParenthesized<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> {
let end_of_line_split = self
.comments
.partition_point(|comment| comment.line_position().is_end_of_line());
debug_assert!(self.comments[end_of_line_split..]
.iter()
.all(|comment| comment.line_position().is_own_line()));
write!(
f,
[group(&format_args![
text(self.left),
// end-of-line comments
trailing_comments(&self.comments[..end_of_line_split]),
// own line comments, which need to be indented
soft_block_indent(&dangling_comments(&self.comments[end_of_line_split..])),
text(self.right)
])]
)
}
}

#[cfg(test)]
mod tests {
use ruff_python_ast::node::AnyNodeRef;
Expand Down
10 changes: 3 additions & 7 deletions crates/ruff_python_formatter/src/other/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ use ruff_python_ast::{Arguments, Expr, Ranged};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{TextRange, TextSize};

use crate::builders::empty_parenthesized_with_dangling_comments;
use crate::expression::expr_generator_exp::GeneratorExpParentheses;
use crate::expression::parentheses::{parenthesized, Parentheses};
use crate::expression::parentheses::{empty_parenthesized, parenthesized, Parentheses};
use crate::prelude::*;
use crate::FormatNodeRule;

Expand All @@ -26,11 +25,8 @@ impl FormatNodeRule<Arguments> for FormatArguments {
let comments = f.context().comments().clone();
return write!(
f,
[empty_parenthesized_with_dangling_comments(
text("("),
comments.dangling_comments(item),
text(")"),
)]
[empty_parenthesized("(", ")")
.with_dangling_comments(comments.dangling_comments(item))]
);
}

Expand Down
9 changes: 2 additions & 7 deletions crates/ruff_python_formatter/src/other/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ use ruff_python_ast::{Parameters, Ranged};
use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{TextRange, TextSize};

use crate::builders::empty_parenthesized_with_dangling_comments;
use crate::comments::{
leading_comments, leading_node_comments, trailing_comments, CommentLinePosition, SourceComment,
};
use crate::context::{NodeLevel, WithNodeLevel};
use crate::expression::parentheses::parenthesized;
use crate::expression::parentheses::{empty_parenthesized, parenthesized};
use crate::prelude::*;
use crate::FormatNodeRule;

Expand Down Expand Up @@ -247,11 +246,7 @@ impl FormatNodeRule<Parameters> for FormatParameters {
// No parameters, format any dangling comments between `()`
write!(
f,
[empty_parenthesized_with_dangling_comments(
text("("),
dangling,
text(")"),
)]
[empty_parenthesized("(", ")").with_dangling_comments(dangling)]
)
} else {
write!(
Expand Down

0 comments on commit 833c02b

Please sign in to comment.