Use optional parentheses for tuples in return statements (#6875)

This commit is contained in:
Micha Reiser 2023-08-29 08:30:05 +02:00 committed by GitHub
parent 19ccf1d073
commit adb48692d6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 112 additions and 33 deletions

View file

@ -31,6 +31,20 @@ pub enum TupleParentheses {
/// ```
Preserve,
/// The same as [`Self::Default`] except that it uses [`optional_parentheses`] rather than
/// [`parenthesize_if_expands`]. This avoids adding parentheses if breaking any containing parenthesized
/// expression makes the tuple fit.
///
/// Avoids adding parentheses around the tuple because breaking the `sum` call expression is sufficient
/// to make it fit.
///
/// ```python
/// return len(self.nodeseeeeeeeee), sum(
// len(node.parents) for node in self.node_map.values()
// )
/// ```
OptionalParentheses,
/// Handle the special cases where we don't include parentheses at all.
///
/// Black never formats tuple targets of for loops with parentheses if inside a comprehension.
@ -158,7 +172,7 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
.finish()
}
TupleParentheses::Preserve => group(&ExprSequence::new(item)).fmt(f),
TupleParentheses::NeverPreserve => {
TupleParentheses::NeverPreserve | TupleParentheses::OptionalParentheses => {
optional_parentheses(&ExprSequence::new(item)).fmt(f)
}
TupleParentheses::Default => {

View file

@ -1,7 +1,8 @@
use ruff_formatter::write;
use ruff_python_ast::StmtReturn;
use ruff_python_ast::{Expr, StmtReturn};
use crate::comments::{SourceComment, SuppressionKind};
use crate::expression::expr_tuple::TupleParentheses;
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::prelude::*;
@ -12,17 +13,31 @@ pub struct FormatStmtReturn;
impl FormatNodeRule<StmtReturn> for FormatStmtReturn {
fn fmt_fields(&self, item: &StmtReturn, f: &mut PyFormatter) -> FormatResult<()> {
let StmtReturn { range: _, value } = item;
if let Some(value) = value {
write!(
f,
[
text("return"),
space(),
maybe_parenthesize_expression(value, item, Parenthesize::IfBreaks)
]
)
} else {
text("return").fmt(f)
text("return").fmt(f)?;
match value.as_deref() {
Some(Expr::Tuple(tuple)) if !f.context().comments().has_leading(tuple) => {
write!(
f,
[
space(),
tuple
.format()
.with_options(TupleParentheses::OptionalParentheses)
]
)
}
Some(value) => {
write!(
f,
[
space(),
maybe_parenthesize_expression(value, item, Parenthesize::IfBreaks)
]
)
}
None => Ok(()),
}
}