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

@ -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(()),
}
}