From f01d6a55f7283041b67caba36e436a36c3da3f2f Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 6 Jul 2022 16:07:46 -0400 Subject: [PATCH] Fix multiline_binop_conditional_with_comments --- crates/compiler/fmt/src/expr.rs | 32 +++++++++++++++++++++------ crates/compiler/fmt/tests/test_fmt.rs | 21 ++++++++++++++++++ 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/crates/compiler/fmt/src/expr.rs b/crates/compiler/fmt/src/expr.rs index 6db19c4c2e..a290e569ff 100644 --- a/crates/compiler/fmt/src/expr.rs +++ b/crates/compiler/fmt/src/expr.rs @@ -828,10 +828,22 @@ fn fmt_if<'a, 'buf>( match &expr_below { Expr::SpaceAfter(expr_above, spaces_after_expr) => { expr_above.format(buf, return_indent); + + // If any of the spaces is a newline, add a newline at the top. + // Otherwise leave it as just a comment. + let newline_at = if spaces_after_expr + .iter() + .any(|spaces| matches!(spaces, CommentOrNewline::Newline)) + { + NewlineAt::Top + } else { + NewlineAt::None + }; + fmt_comments_only( buf, spaces_after_expr.iter(), - NewlineAt::None, + newline_at, return_indent, ); buf.newline(); @@ -876,12 +888,18 @@ fn fmt_if<'a, 'buf>( Expr::SpaceAfter(expr_above, spaces_above) => { expr_above.format(buf, return_indent); - fmt_comments_only( - buf, - spaces_above.iter(), - NewlineAt::Top, - return_indent, - ); + // If any of the spaces is a newline, add a newline at the top. + // Otherwise leave it as just a comment. + let newline_at = if spaces_above + .iter() + .any(|spaces| matches!(spaces, CommentOrNewline::Newline)) + { + NewlineAt::Top + } else { + NewlineAt::None + }; + + fmt_comments_only(buf, spaces_above.iter(), newline_at, return_indent); buf.newline(); } diff --git a/crates/compiler/fmt/tests/test_fmt.rs b/crates/compiler/fmt/tests/test_fmt.rs index 84e2634c41..c9db54dc62 100644 --- a/crates/compiler/fmt/tests/test_fmt.rs +++ b/crates/compiler/fmt/tests/test_fmt.rs @@ -4037,6 +4037,27 @@ mod test_fmt { )); } + #[test] + fn multiline_binop_conditional_with_comments() { + expr_formats_same(indoc!( + r#" + if + x + + 1 # comment 1 + > 0 # comment 2 + then + y + * 2 # comment 3 + < 1 # comment 4 + else + 42 + "# + )); + } + "# + )); + } + #[test] fn precedence_conflict_greater_than() { expr_formats_same(indoc!(