mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-29 21:35:58 +00:00
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:
parent
ecd4b4d943
commit
9a817a2922
25 changed files with 699 additions and 149 deletions
|
@ -1,12 +1,12 @@
|
|||
use ruff_formatter::{format_args, write};
|
||||
use ruff_python_ast::AnyNodeRef;
|
||||
use ruff_python_ast::{ElifElseClause, StmtIf};
|
||||
use ruff_python_ast::{AnyNodeRef, ElifElseClause, StmtIf};
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
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(Default)]
|
||||
pub struct FormatStmtIf;
|
||||
|
@ -35,13 +35,22 @@ impl FormatNodeRule<StmtIf> for FormatStmtIf {
|
|||
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks),
|
||||
],
|
||||
),
|
||||
clause_body(body, trailing_colon_comment),
|
||||
clause_body(
|
||||
body,
|
||||
SuiteKind::other(elif_else_clauses.is_empty()),
|
||||
trailing_colon_comment
|
||||
),
|
||||
]
|
||||
)?;
|
||||
|
||||
let mut last_node = body.last().unwrap().into();
|
||||
for clause in elif_else_clauses {
|
||||
format_elif_else_clause(clause, f, Some(last_node))?;
|
||||
format_elif_else_clause(
|
||||
clause,
|
||||
f,
|
||||
Some(last_node),
|
||||
SuiteKind::other(clause == elif_else_clauses.last().unwrap()),
|
||||
)?;
|
||||
last_node = clause.body.last().unwrap().into();
|
||||
}
|
||||
|
||||
|
@ -55,6 +64,7 @@ pub(crate) fn format_elif_else_clause(
|
|||
item: &ElifElseClause,
|
||||
f: &mut PyFormatter,
|
||||
last_node: Option<AnyNodeRef>,
|
||||
suite_kind: SuiteKind,
|
||||
) -> FormatResult<()> {
|
||||
let ElifElseClause {
|
||||
range: _,
|
||||
|
@ -93,7 +103,7 @@ pub(crate) fn format_elif_else_clause(
|
|||
}),
|
||||
)
|
||||
.with_leading_comments(leading_comments, last_node),
|
||||
clause_body(body, trailing_colon_comment),
|
||||
clause_body(body, suite_kind, trailing_colon_comment),
|
||||
f.options()
|
||||
.source_map_generation()
|
||||
.is_enabled()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue