From c134faf9791a1783cc5af0906ca5619ce82e2973 Mon Sep 17 00:00:00 2001 From: Albert Meltzer <7529386+kitbellew@users.noreply.github.com> Date: Wed, 2 Oct 2024 10:42:04 -0700 Subject: [PATCH] RedundantBraces: keep if a comment is attached Also, check comments only for scala2. --- .../org/scalafmt/rewrite/RedundantBraces.scala | 14 +++++++++++--- .../test/resources/rewrite/RedundantBraces-if.stat | 14 ++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantBraces.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantBraces.scala index 12946b11b3..5a6585a176 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantBraces.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantBraces.scala @@ -300,11 +300,19 @@ class RedundantBraces(implicit val ftoks: FormatTokens) session: Session, style: ScalafmtConfig, ): (Replacement, Replacement) = { + @tailrec + def okComment(xft: FormatToken): Boolean = + ftoks.prevNotTrailingComment(xft) match { + case Right(x) => + if ((x eq xft) && x.hasBreak) + !ftoks.isAttachedCommentThenBreak(ftoks.next(ft)) + else !session.isRemovedOnLeft(x, true) || okComment(ftoks.prev(x)) + case _ => false + } val ok = ft.meta.rightOwner match { - case _: Term.Block => ftoks.prevNotTrailingComment(ft).isRight && - !braceSeparatesTwoXmlTokens && + case _: Term.Block => !braceSeparatesTwoXmlTokens && (style.dialect.allowSignificantIndentation || - !elseAfterRightBraceThenpOnLeft) + okComment(ft) && !elseAfterRightBraceThenpOnLeft) case _ => true } if (ok) (left, removeToken) else null diff --git a/scalafmt-tests/shared/src/test/resources/rewrite/RedundantBraces-if.stat b/scalafmt-tests/shared/src/test/resources/rewrite/RedundantBraces-if.stat index 9ec4c789de..bf96ec37ce 100644 --- a/scalafmt-tests/shared/src/test/resources/rewrite/RedundantBraces-if.stat +++ b/scalafmt-tests/shared/src/test/resources/rewrite/RedundantBraces-if.stat @@ -424,9 +424,11 @@ object a { } } >>> -Idempotency violated -=> Diff (- obtained, + expected) - searchIndices() -- // else swallow the termination and wait for pull -+ // else swallow the termination and wait for pull - } +object a { + override def onUpstreamFinish(): Unit = + if (buffer.isEmpty) + completeStage() + else if (isAvailable(out)) { + searchIndices() + } // else swallow the termination and wait for pull +}