Fix parentheses around return type annotations (#13381)

This commit is contained in:
Micha Reiser 2024-09-20 09:23:53 +02:00 committed by GitHub
parent 7c2011599f
commit 531ebf6dff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 1487 additions and 296 deletions

View file

@ -8,6 +8,7 @@ use crate::expression::parentheses::{
};
use crate::expression::CallChainLayout;
use crate::prelude::*;
use crate::preview::is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled;
#[derive(Default)]
pub struct FormatExprSubscript {
@ -103,19 +104,25 @@ impl NeedsParentheses for ExprSubscript {
} else {
match self.value.needs_parentheses(self.into(), context) {
OptionalParentheses::BestFit => {
if parent.as_stmt_function_def().is_some_and(|function_def| {
function_def
.returns
.as_deref()
.and_then(Expr::as_subscript_expr)
== Some(self)
}) {
// Don't use the best fitting layout for return type annotation because it results in the
// return type expanding before the parameters.
OptionalParentheses::Never
} else {
OptionalParentheses::BestFit
if let Some(function) = parent.as_stmt_function_def() {
if function.returns.as_deref().is_some_and(|returns| {
AnyNodeRef::ptr_eq(returns.into(), self.into())
}) {
if is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled(context) &&
function.parameters.is_empty() && !context.comments().has(&*function.parameters) {
// Apply the `optional_parentheses` layout when the subscript
// is in a return type position of a function without parameters.
// This ensures the subscript is parenthesized if it has a very
// long name that goes over the line length limit.
return OptionalParentheses::Multiline
}
// Don't use the best fitting layout for return type annotation because it results in the
// return type expanding before the parameters.
return OptionalParentheses::Never;
}
}
OptionalParentheses::BestFit
}
parentheses => parentheses,
}