Add formatting for MatchCase (#6360)

## Summary

This PR adds formatting support for `MatchCase` node with subs for the
`Pattern`
nodes.

## Test Plan

Added test cases for case node handling with comments, newlines.

resolves: #6299
This commit is contained in:
Dhruv Manilawala 2023-08-11 19:20:25 +05:30 committed by GitHub
parent 8b24238d19
commit c434bdd2bd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 256 additions and 29 deletions

View file

@ -1,8 +1,7 @@
use ruff_formatter::{write, Buffer, FormatResult};
use ruff_python_ast::MatchCase;
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::comments::trailing_comments;
use crate::not_yet_implemented_custom_text;
use crate::prelude::*;
use crate::{FormatNodeRule, PyFormatter};
@ -19,6 +18,9 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
body,
} = item;
let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item);
write!(
f,
[
@ -39,17 +41,21 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
)?;
if let Some(guard) = guard {
write!(
f,
[
space(),
text("if"),
space(),
maybe_parenthesize_expression(guard, item, Parenthesize::IfBreaks)
]
)?;
write!(f, [space(), text("if"), space(), guard.format()])?;
}
write!(f, [text(":"), block_indent(&body.format())])
write!(
f,
[
text(":"),
trailing_comments(dangling_item_comments),
block_indent(&body.format())
]
)
}
fn fmt_dangling_comments(&self, _node: &MatchCase, _f: &mut PyFormatter) -> FormatResult<()> {
// Handled as part of `fmt_fields`
Ok(())
}
}