Support fmt: skip on compound statements (#6593)

This commit is contained in:
Micha Reiser 2023-08-17 08:05:41 +02:00 committed by GitHub
parent 4dc32a00d0
commit fa7442da2f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 1385 additions and 625 deletions

View file

@ -3,9 +3,10 @@ use ruff_python_ast::{MatchCase, Pattern, Ranged};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::TextRange;
use crate::comments::{leading_comments, trailing_comments, SourceComment};
use crate::comments::{leading_comments, SourceComment};
use crate::expression::parentheses::parenthesized;
use crate::prelude::*;
use crate::statement::clause::{clause_header, ClauseHeader};
use crate::{FormatError, FormatNodeRule, PyFormatter};
#[derive(Default)]
@ -23,30 +24,39 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item);
write!(f, [text("case"), space()])?;
let leading_pattern_comments = comments.leading_comments(pattern);
if !leading_pattern_comments.is_empty() {
parenthesized(
"(",
&format_args![leading_comments(leading_pattern_comments), pattern.format()],
")",
)
.fmt(f)?;
} else if is_match_case_pattern_parenthesized(item, pattern, f.context())? {
parenthesized("(", &pattern.format(), ")").fmt(f)?;
} else {
pattern.format().fmt(f)?;
}
if let Some(guard) = guard {
write!(f, [space(), text("if"), space(), guard.format()])?;
}
write!(
f,
[
text(":"),
trailing_comments(dangling_item_comments),
clause_header(
ClauseHeader::MatchCase(item),
dangling_item_comments,
&format_with(|f| {
write!(f, [text("case"), space()])?;
let leading_pattern_comments = comments.leading_comments(pattern);
if !leading_pattern_comments.is_empty() {
parenthesized(
"(",
&format_args![
leading_comments(leading_pattern_comments),
pattern.format()
],
")",
)
.fmt(f)?;
} else if is_match_case_pattern_parenthesized(item, pattern, f.context())? {
parenthesized("(", &pattern.format(), ")").fmt(f)?;
} else {
pattern.format().fmt(f)?;
}
if let Some(guard) = guard {
write!(f, [space(), text("if"), space(), guard.format()])?;
}
Ok(())
}),
),
block_indent(&body.format())
]
)