Format PatternMatchAs (#6652)

## Summary

Add formatting for `PatternMatchAs`.

This closes #6641.

## Test Plan

Add tests for comments.
This commit is contained in:
Luc Khai Hai 2023-08-23 08:58:15 +09:00 committed by GitHub
parent 42ff833d00
commit c34a342ab4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 159 additions and 79 deletions

View file

@ -1,19 +1,42 @@
use ruff_formatter::{write, Buffer, FormatResult};
use ruff_python_ast::PatternMatchAs;
use ruff_python_ast::{Pattern, PatternMatchAs};
use crate::{not_yet_implemented_custom_text, FormatNodeRule, PyFormatter};
use crate::expression::parentheses::parenthesized;
use crate::prelude::*;
use crate::{FormatNodeRule, PyFormatter};
#[derive(Default)]
pub struct FormatPatternMatchAs;
impl FormatNodeRule<PatternMatchAs> for FormatPatternMatchAs {
fn fmt_fields(&self, item: &PatternMatchAs, f: &mut PyFormatter) -> FormatResult<()> {
write!(
f,
[not_yet_implemented_custom_text(
"x as NOT_YET_IMPLEMENTED_PatternMatchAs",
item
)]
)
let PatternMatchAs {
range: _,
pattern,
name,
} = item;
if let Some(name) = name {
if let Some(pattern) = pattern {
// Parenthesize nested `PatternMatchAs` like `(a as b) as c`.
if matches!(
pattern.as_ref(),
Pattern::MatchAs(PatternMatchAs {
pattern: Some(_),
..
})
) {
parenthesized("(", &pattern.format(), ")").fmt(f)?;
} else {
pattern.format().fmt(f)?;
}
write!(f, [space(), text("as"), space()])?;
}
name.format().fmt(f)
} else {
debug_assert!(pattern.is_none());
text("_").fmt(f)
}
}
}