From 416c5409c26453b31775e4a618de64020694006d Mon Sep 17 00:00:00 2001 From: Albert Meltzer <7529386+kitbellew@users.noreply.github.com> Date: Wed, 15 May 2024 21:28:31 -0700 Subject: [PATCH] FormatOps: in CtrlBodySplits, add consistency Previously, the code was computing splits differently for tokens with a break and without one. Since we could potentially have no-break in the source but format with one, this could introduce non-idempotency. --- .../scala/org/scalafmt/internal/FormatOps.scala | 15 +++++++-------- .../src/test/resources/scalajs/DefDef.stat | 13 ++++++------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatOps.scala index 5126c55d16..54be13ab0e 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatOps.scala @@ -1644,21 +1644,20 @@ class FormatOps( classicNoBreakFunc: => Split, )(nlSplitFunc: Int => Split)(implicit style: ScalafmtConfig): Seq[Split] = checkComment(ft, nlSplitFunc) { x => + def getFolded(isKeep: Boolean) = + foldedNonComment(body, nlSplitFunc, isKeep = isKeep, spaceIndents) style.newlines.getBeforeMultiline match { + case Newlines.fold => getFolded(false) case Newlines.unfold => unfoldedNonComment(body, nlSplitFunc, spaceIndents, false) - case Newlines.classic | Newlines.keep if x.hasBreak => - Seq(nlSplitFunc(0).forThisLine) - case Newlines.classic => Option(classicNoBreakFunc).fold { - foldedNonComment(body, nlSplitFunc, isKeep = true, spaceIndents) - } { func => + case Newlines.classic if x.noBreak => + Option(classicNoBreakFunc).fold(getFolded(true)) { func => val spcSplit = func.forThisLine val nlSplit = nlSplitFunc(spcSplit.getCost(_ + 1, 0)).forThisLine Seq(spcSplit, nlSplit) } - case sh => // fold or keep without break - val isKeep = sh eq Newlines.keep - foldedNonComment(body, nlSplitFunc, isKeep, spaceIndents) + case Newlines.keep if x.noBreak => getFolded(true) + case _ => getFolded(true).filter(_.isNL) // keep/classic with break } } diff --git a/scalafmt-tests/src/test/resources/scalajs/DefDef.stat b/scalafmt-tests/src/test/resources/scalajs/DefDef.stat index 2c08ab02aa..dc321b0273 100644 --- a/scalafmt-tests/src/test/resources/scalajs/DefDef.stat +++ b/scalafmt-tests/src/test/resources/scalajs/DefDef.stat @@ -570,10 +570,9 @@ object a { } } >>> -Idempotency violated -=> Diff (- obtained, + expected) - val registry = -- new js_FinalizationRegistry[js_Date, String, Any]((heldValue: String) => -- ()) -+ new js_FinalizationRegistry[js_Date, String, Any]((heldValue: String) => ()) - } +object a { + def foo = { + val registry = + new js_FinalizationRegistry[js_Date, String, Any]((heldValue: String) => ()) + } +}