Skip to content

Commit

Permalink
Format PatternMatchOr
Browse files Browse the repository at this point in the history
  • Loading branch information
LaBatata101 authored and MichaReiser committed Aug 28, 2023
1 parent 30ebf7f commit 1983ef7
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 871 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -467,3 +467,37 @@ def foo():
# e
):
pass


match pattern_match_or:
case ( # leading 1
a # trailing 1
# own line 1
| # trailing 2
# own line 2
b # trailing 3
# own line 3
| # trailing 4
# own line 4
c # trailing 5
):
...

case (
(a)
| # trailing
( b )
):
...

case (a|b|c):
...

case foo | bar | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh:
...

case ( # end of line
a | b
# own line
):
...
42 changes: 33 additions & 9 deletions crates/ruff_python_formatter/src/pattern/pattern_match_or.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,46 @@ use ruff_formatter::write;
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::PatternMatchOr;

use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses};
use crate::not_yet_implemented_custom_text;
use crate::comments::leading_comments;
use crate::expression::parentheses::{
in_parentheses_only_soft_line_break_or_space, NeedsParentheses, OptionalParentheses,
};
use crate::prelude::*;

#[derive(Default)]
pub struct FormatPatternMatchOr;

impl FormatNodeRule<PatternMatchOr> for FormatPatternMatchOr {
fn fmt_fields(&self, item: &PatternMatchOr, f: &mut PyFormatter) -> FormatResult<()> {
write!(
f,
[not_yet_implemented_custom_text(
"NOT_YET_IMPLEMENTED_PatternMatchOf | (y)",
item
)]
)
let PatternMatchOr { range: _, patterns } = item;
let inner = format_with(|f: &mut PyFormatter| {
let mut patterns = patterns.iter();
let comments = f.context().comments().clone();

let Some(first) = patterns.next() else {
return Ok(());
};

first.format().fmt(f)?;

for pattern in patterns {
let leading_value_comments = comments.leading(pattern);
// Format the expressions leading comments **before** the operator
if leading_value_comments.is_empty() {
write!(f, [in_parentheses_only_soft_line_break_or_space()])?;
} else {
write!(
f,
[hard_line_break(), leading_comments(leading_value_comments)]
)?;
}
write!(f, [text("|"), space(), pattern.format()])?;
}

Ok(())
});

inner.fmt(f)
}
}

Expand Down
Loading

0 comments on commit 1983ef7

Please sign in to comment.