Insert empty line between suite and alternative branch after def/class (#12294)

When there is a function or class definition at the end of a suite
followed by the beginning of an alternative block, we have to insert a
single empty line between them.

In the if-else-statement example below, we insert an empty line after
the `foo` in the if-block, but none after the else-block `foo`, since in
the latter case the enclosing suite already adds empty lines.

```python
if sys.version_info >= (3, 10):
    def foo():
        return "new"
else:
    def foo():
        return "old"
class Bar:
    pass
```

To do so, we track whether the current suite is the last one in the
current statement with a new option on the suite kind.

Fixes #12199

---------

Co-authored-by: Micha Reiser <micha@reiser.io>
This commit is contained in:
konsti 2024-07-15 12:59:33 +02:00 committed by GitHub
parent ecd4b4d943
commit 9a817a2922
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 699 additions and 149 deletions

View file

@ -2,6 +2,7 @@ use ruff_python_ast::ElifElseClause;
use crate::prelude::*;
use crate::statement::stmt_if::format_elif_else_clause;
use crate::statement::suite::SuiteKind;
/// Note that this implementation misses the leading newlines before the leading comments because
/// it does not have access to the last node of the previous branch. The `StmtIf` therefore doesn't
@ -11,6 +12,15 @@ pub struct FormatElifElseClause;
impl FormatNodeRule<ElifElseClause> for FormatElifElseClause {
fn fmt_fields(&self, item: &ElifElseClause, f: &mut PyFormatter) -> FormatResult<()> {
format_elif_else_clause(item, f, None)
format_elif_else_clause(
item,
f,
None,
SuiteKind::Other {
// For stability, we can't insert an empty line if we don't know if the outer suite
// also does.
last_suite_in_statement: true,
},
)
}
}

View file

@ -6,9 +6,10 @@ use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::prelude::*;
use crate::statement::clause::{clause_body, clause_header, ClauseHeader};
use crate::statement::suite::SuiteKind;
#[derive(Copy, Clone, Default)]
pub enum ExceptHandlerKind {
pub(crate) enum ExceptHandlerKind {
#[default]
Regular,
Starred,
@ -16,16 +17,18 @@ pub enum ExceptHandlerKind {
#[derive(Default)]
pub struct FormatExceptHandlerExceptHandler {
except_handler_kind: ExceptHandlerKind,
pub(crate) except_handler_kind: ExceptHandlerKind,
pub(crate) last_suite_in_statement: bool,
}
impl FormatRuleWithOptions<ExceptHandlerExceptHandler, PyFormatContext<'_>>
for FormatExceptHandlerExceptHandler
{
type Options = ExceptHandlerKind;
type Options = FormatExceptHandlerExceptHandler;
fn with_options(mut self, options: Self::Options) -> Self {
self.except_handler_kind = options;
self.except_handler_kind = options.except_handler_kind;
self.last_suite_in_statement = options.last_suite_in_statement;
self
}
}
@ -36,6 +39,7 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
item: &ExceptHandlerExceptHandler,
f: &mut PyFormatter,
) -> FormatResult<()> {
let except_handler_kind = self.except_handler_kind;
let ExceptHandlerExceptHandler {
range: _,
type_,
@ -57,7 +61,7 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
f,
[
token("except"),
match self.except_handler_kind {
match except_handler_kind {
ExceptHandlerKind::Regular => None,
ExceptHandlerKind::Starred => Some(token("*")),
}
@ -84,7 +88,11 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
Ok(())
}),
),
clause_body(body, dangling_comments),
clause_body(
body,
SuiteKind::other(self.last_suite_in_statement),
dangling_comments
),
]
)
}

View file

@ -1,4 +1,4 @@
use ruff_formatter::write;
use ruff_formatter::{write, FormatRuleWithOptions};
use ruff_python_ast::AstNode;
use ruff_python_ast::MatchCase;
@ -6,9 +6,21 @@ use crate::builders::parenthesize_if_expands;
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, Parentheses};
use crate::prelude::*;
use crate::statement::clause::{clause_body, clause_header, ClauseHeader};
use crate::statement::suite::SuiteKind;
#[derive(Default)]
pub struct FormatMatchCase;
pub struct FormatMatchCase {
last_suite_in_statement: bool,
}
impl FormatRuleWithOptions<MatchCase, PyFormatContext<'_>> for FormatMatchCase {
type Options = bool;
fn with_options(mut self, options: Self::Options) -> Self {
self.last_suite_in_statement = options;
self
}
}
impl FormatNodeRule<MatchCase> for FormatMatchCase {
fn fmt_fields(&self, item: &MatchCase, f: &mut PyFormatter) -> FormatResult<()> {
@ -63,7 +75,11 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
Ok(())
}),
),
clause_body(body, dangling_item_comments),
clause_body(
body,
SuiteKind::other(self.last_suite_in_statement),
dangling_item_comments
),
]
)
}