Introduce parenthesized helper (#5565)

This commit is contained in:
Micha Reiser 2023-07-07 11:28:25 +02:00 committed by GitHub
parent bf4b96c5de
commit 40ddc1604c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 60 additions and 64 deletions

View file

@ -1,10 +1,11 @@
use crate::builders::PyFormatterExtensions; use crate::builders::PyFormatterExtensions;
use crate::comments::{dangling_comments, Comments}; use crate::comments::{dangling_comments, Comments};
use crate::expression::parentheses::{ use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize, default_expression_needs_parentheses, parenthesized, NeedsParentheses, Parentheses,
Parenthesize,
}; };
use crate::{AsFormat, FormatNodeRule, PyFormatter}; use crate::{AsFormat, FormatNodeRule, PyFormatter};
use ruff_formatter::prelude::{format_with, group, soft_block_indent, text}; use ruff_formatter::prelude::{format_with, group, text};
use ruff_formatter::{write, Buffer, FormatResult}; use ruff_formatter::{write, Buffer, FormatResult};
use rustpython_parser::ast::ExprCall; use rustpython_parser::ast::ExprCall;
@ -56,7 +57,6 @@ impl FormatNodeRule<ExprCall> for FormatExprCall {
f, f,
[ [
func.format(), func.format(),
text("("),
// The outer group is for things like // The outer group is for things like
// ```python // ```python
// get_collection( // get_collection(
@ -73,8 +73,7 @@ impl FormatNodeRule<ExprCall> for FormatExprCall {
// ) // )
// ``` // ```
// TODO(konstin): Doesn't work see wrongly formatted test // TODO(konstin): Doesn't work see wrongly formatted test
&group(&soft_block_indent(&group(&all_args))), parenthesized("(", &group(&all_args), ")")
text(")")
] ]
) )
} }

View file

@ -1,6 +1,7 @@
use crate::comments::{dangling_node_comments, leading_comments, Comments}; use crate::comments::{dangling_node_comments, leading_comments, Comments};
use crate::expression::parentheses::{ use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize, default_expression_needs_parentheses, parenthesized, NeedsParentheses, Parentheses,
Parenthesize,
}; };
use crate::prelude::*; use crate::prelude::*;
use crate::FormatNodeRule; use crate::FormatNodeRule;
@ -86,14 +87,7 @@ impl FormatNodeRule<ExprDict> for FormatExprDict {
joiner.finish() joiner.finish()
}); });
write!( parenthesized("{", &format_pairs, "}").fmt(f)
f,
[group(&format_args![
text("{"),
soft_block_indent(&format_pairs),
text("}")
])]
)
} }
fn fmt_dangling_comments(&self, _node: &ExprDict, _f: &mut PyFormatter) -> FormatResult<()> { fn fmt_dangling_comments(&self, _node: &ExprDict, _f: &mut PyFormatter) -> FormatResult<()> {

View file

@ -1,6 +1,7 @@
use crate::comments::{dangling_comments, CommentLinePosition, Comments}; use crate::comments::{dangling_comments, CommentLinePosition, Comments};
use crate::expression::parentheses::{ use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize, default_expression_needs_parentheses, parenthesized, NeedsParentheses, Parentheses,
Parenthesize,
}; };
use crate::prelude::*; use crate::prelude::*;
use crate::FormatNodeRule; use crate::FormatNodeRule;
@ -54,14 +55,7 @@ impl FormatNodeRule<ExprList> for FormatExprList {
let items = format_with(|f| f.join_comma_separated().nodes(elts.iter()).finish()); let items = format_with(|f| f.join_comma_separated().nodes(elts.iter()).finish());
write!( parenthesized("[", &items, "]").fmt(f)
f,
[group(&format_args![
text("["),
soft_block_indent(&items),
text("]")
])]
)
} }
fn fmt_dangling_comments(&self, _node: &ExprList, _f: &mut PyFormatter) -> FormatResult<()> { fn fmt_dangling_comments(&self, _node: &ExprList, _f: &mut PyFormatter) -> FormatResult<()> {

View file

@ -1,12 +1,11 @@
use crate::comments::Comments; use crate::comments::Comments;
use crate::expression::parentheses::{ use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize, default_expression_needs_parentheses, parenthesized, NeedsParentheses, Parentheses,
Parenthesize,
}; };
use crate::{FormatNodeRule, FormattedIterExt, PyFormatter}; use crate::prelude::*;
use ruff_formatter::prelude::{ use crate::FormatNodeRule;
format_with, group, if_group_breaks, soft_block_indent, soft_line_break_or_space, text, use ruff_formatter::format_args;
};
use ruff_formatter::{format_args, write, Buffer, FormatResult};
use rustpython_parser::ast::ExprSet; use rustpython_parser::ast::ExprSet;
#[derive(Default)] #[derive(Default)]
@ -23,14 +22,8 @@ impl FormatNodeRule<ExprSet> for FormatExprSet {
.entries(elts.iter().formatted()) .entries(elts.iter().formatted())
.finish() .finish()
}); });
write!(
f, parenthesized("{", &format_args![joined, if_group_breaks(&text(","))], "}").fmt(f)
[group(&format_args![
text("{"),
soft_block_indent(&format_args![joined, if_group_breaks(&text(",")),]),
text("}")
])]
)
} }
} }

View file

@ -1,7 +1,8 @@
use crate::builders::optional_parentheses; use crate::builders::optional_parentheses;
use crate::comments::{dangling_node_comments, Comments}; use crate::comments::{dangling_node_comments, Comments};
use crate::expression::parentheses::{ use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize, default_expression_needs_parentheses, parenthesized, NeedsParentheses, Parentheses,
Parenthesize,
}; };
use crate::prelude::*; use crate::prelude::*;
use ruff_formatter::{format_args, write, FormatRuleWithOptions}; use ruff_formatter::{format_args, write, FormatRuleWithOptions};
@ -69,15 +70,8 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
) )
} }
[single] => { [single] => {
write!( // A single element tuple always needs parentheses and a trailing comma
f, parenthesized("(", &format_args![single.format(), &text(",")], ")").fmt(f)
[group(&format_args![
// A single element tuple always needs parentheses and a trailing comma
&text("("),
soft_block_indent(&format_args![single.format(), &text(",")]),
&text(")"),
])]
)
} }
// If the tuple has parentheses, we generally want to keep them. The exception are for // If the tuple has parentheses, we generally want to keep them. The exception are for
// loops, see `TupleParentheses::StripInsideForLoop` doc comment. // loops, see `TupleParentheses::StripInsideForLoop` doc comment.
@ -87,15 +81,7 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
elts if is_parenthesized(*range, elts, f) elts if is_parenthesized(*range, elts, f)
&& self.parentheses != TupleParentheses::StripInsideForLoop => && self.parentheses != TupleParentheses::StripInsideForLoop =>
{ {
write!( parenthesized("(", &ExprSequence::new(elts), ")").fmt(f)
f,
[group(&format_args![
// If there were previously parentheses, keep them
&text("("),
soft_block_indent(&ExprSequence::new(elts)),
&text(")"),
])]
)
} }
elts => optional_parentheses(&ExprSequence::new(elts)).fmt(f), elts => optional_parentheses(&ExprSequence::new(elts)).fmt(f),
} }

View file

@ -1,5 +1,7 @@
use crate::comments::Comments; use crate::comments::Comments;
use crate::prelude::*;
use crate::trivia::{first_non_trivia_token, first_non_trivia_token_rev, Token, TokenKind}; use crate::trivia::{first_non_trivia_token, first_non_trivia_token_rev, Token, TokenKind};
use ruff_formatter::{format_args, write, Argument, Arguments};
use ruff_python_ast::node::AnyNodeRef; use ruff_python_ast::node::AnyNodeRef;
use rustpython_parser::ast::Ranged; use rustpython_parser::ast::Ranged;
@ -119,3 +121,37 @@ pub(crate) fn is_expression_parenthesized(expr: AnyNodeRef, contents: &str) -> b
}) })
) )
} }
pub(crate) fn parenthesized<'content, 'ast, Content>(
left: &'static str,
content: &'content Content,
right: &'static str,
) -> FormatParenthesized<'content, 'ast>
where
Content: Format<PyFormatContext<'ast>>,
{
FormatParenthesized {
left,
content: Argument::new(content),
right,
}
}
pub(crate) struct FormatParenthesized<'content, 'ast> {
left: &'static str,
content: Argument<'content, PyFormatContext<'ast>>,
right: &'static str,
}
impl<'ast> Format<PyFormatContext<'ast>> for FormatParenthesized<'_, 'ast> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> {
write!(
f,
[group(&format_args![
text(self.left),
&soft_block_indent(&Arguments::from(&self.content)),
text(self.right)
])]
)
}
}

View file

@ -10,6 +10,7 @@ use crate::comments::{
CommentLinePosition, SourceComment, CommentLinePosition, SourceComment,
}; };
use crate::context::NodeLevel; use crate::context::NodeLevel;
use crate::expression::parentheses::parenthesized;
use crate::prelude::*; use crate::prelude::*;
use crate::trivia::{first_non_trivia_token, SimpleTokenizer, Token, TokenKind}; use crate::trivia::{first_non_trivia_token, SimpleTokenizer, Token, TokenKind};
use crate::FormatNodeRule; use crate::FormatNodeRule;
@ -179,14 +180,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
] ]
)?; )?;
} else { } else {
write!( parenthesized("(", &group(&format_inner), ")").fmt(f)?;
f,
[group(&format_args!(
text("("),
soft_block_indent(&group(&format_inner)),
text(")")
))]
)?;
} }
f.context_mut().set_node_level(saved_level); f.context_mut().set_node_level(saved_level);