Indent for multiline | patterns

This commit is contained in:
Richard Feldman 2022-07-03 22:17:13 -04:00
parent 872efa9724
commit 244a501433
No known key found for this signature in database
GPG key ID: 7E4127D1E4241798
3 changed files with 21 additions and 17 deletions

View file

@ -710,10 +710,15 @@ fn fmt_when<'a, 'buf>(
if index != 0 {
if is_multiline_patterns {
buf.newline();
buf.indent(indent + INDENT);
// Indent an extra level for the `|`;
// otherwise it'll be at the start of the line,
// and will be incorrectly parsed as a pattern
buf.indent(indent + INDENT + INDENT);
buf.push('|');
} else {
buf.push_str(" |");
}
buf.push_str(" |");
buf.spaces(1);
}

View file

@ -162,10 +162,6 @@ impl<'a> Formattable for Pattern<'a> {
// Space
SpaceBefore(sub_pattern, spaces) => {
if has_inline_comment(spaces.iter()) {
buf.spaces(1);
}
if !sub_pattern.is_multiline() {
fmt_comments_only(buf, spaces.iter(), NewlineAt::Bottom, indent)
} else {
@ -177,7 +173,7 @@ impl<'a> Formattable for Pattern<'a> {
SpaceAfter(sub_pattern, spaces) => {
sub_pattern.format_with_options(buf, parens, newlines, indent);
if has_inline_comment(spaces.iter()) {
if starts_with_inline_comment(spaces.iter()) {
buf.spaces(1);
}
@ -206,8 +202,11 @@ impl<'a> Formattable for Pattern<'a> {
}
}
fn has_inline_comment<'a, I: IntoIterator<Item = &'a CommentOrNewline<'a>>>(spaces: I) -> bool {
spaces
.into_iter()
.any(|space| matches!(space, CommentOrNewline::LineComment(_)))
fn starts_with_inline_comment<'a, I: IntoIterator<Item = &'a CommentOrNewline<'a>>>(
spaces: I,
) -> bool {
match spaces.into_iter().next() {
Some(space) => matches!(space, CommentOrNewline::LineComment(_)),
None => false,
}
}

View file

@ -3379,7 +3379,7 @@ mod test_fmt {
r#"
when 0 is
1 # comment
| 2 -> "a"
| 2 -> "a"
_ -> "b"
"#
));
@ -3477,18 +3477,18 @@ mod test_fmt {
r#"
when b is
1
| 2
| 3 ->
| 2
| 3 ->
4
5 | 6 | 7 ->
8
9
| 10 -> 11
| 10 -> 11
12 | 13 ->
when c is
14 | 15 -> 16
17
| 18 -> 19
| 18 -> 19
20 -> 21
"#
),
@ -3510,7 +3510,7 @@ mod test_fmt {
when b is
3 -> 4
9
| 8 -> 9
| 8 -> 9
"#
),
);