diff --git a/.scalafmt.conf b/.scalafmt.conf index fdbea71aa1..5f4e837aff 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -41,6 +41,10 @@ rewrite { } redundantBraces { preset = all + oneStatApply { + parensMaxSpan = 300 + bracesMinSpan = 300 + } } redundantParens { preset = all diff --git a/build.sbt b/build.sbt index 0d6c4bf19a..4cd62ed3cd 100644 --- a/build.sbt +++ b/build.sbt @@ -16,28 +16,30 @@ def isCI = System.getenv("CI") != null def scala212 = "2.12.20" def scala213 = "2.13.15" -inThisBuild(List( - version ~= { dynVer => - if (isCI) dynVer else localSnapshotVersion // only for local publishing - }, - organization := "org.scalameta", - homepage := Some(url("https://github.com/scalameta/scalafmt")), - licenses := - List("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")), - developers := List(Developer( - "olafurpg", - "Ólafur Páll Geirsson", - "olafurpg@gmail.com", - url("https://geirsson.com"), - )), - scalaVersion := scala213, - crossScalaVersions := List(scala213, scala212), - resolvers ++= Resolver.sonatypeOssRepos("releases"), - resolvers ++= Resolver.sonatypeOssRepos("snapshots"), - testFrameworks += new TestFramework("munit.Framework"), - // causes native image issues - dependencyOverrides += "org.jline" % "jline" % "3.28.0", -)) +inThisBuild { + List( + version ~= { dynVer => + if (isCI) dynVer else localSnapshotVersion // only for local publishing + }, + organization := "org.scalameta", + homepage := Some(url("https://github.com/scalameta/scalafmt")), + licenses := + List("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")), + developers := List(Developer( + "olafurpg", + "Ólafur Páll Geirsson", + "olafurpg@gmail.com", + url("https://geirsson.com"), + )), + scalaVersion := scala213, + crossScalaVersions := List(scala213, scala212), + resolvers ++= Resolver.sonatypeOssRepos("releases"), + resolvers ++= Resolver.sonatypeOssRepos("snapshots"), + testFrameworks += new TestFramework("munit.Framework"), + // causes native image issues + dependencyOverrides += "org.jline" % "jline" % "3.28.0", + ) +} name := "scalafmtRoot" publish / skip := true diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 201f330a9b..9a62a81212 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -14,12 +14,10 @@ object Dependencies { val munitV = "1.0.2" val mdocV = mdoc.BuildInfo.version - val scalapb = Def.setting { - ExclusionRule( - organization = "com.thesamet.scalapb", - name = s"scalapb-runtime_${scalaBinaryVersion.value}", - ) - } + val scalapb = Def.setting(ExclusionRule( + organization = "com.thesamet.scalapb", + name = s"scalapb-runtime_${scalaBinaryVersion.value}", + )) val scalametaTestkit = Def.setting("org.scalameta" %%% "testkit" % scalametaV) diff --git a/scalafmt-cli/jvm/src/main/scala/org/scalafmt/cli/CliUtils.scala b/scalafmt-cli/jvm/src/main/scala/org/scalafmt/cli/CliUtils.scala index 08e6c835aa..48634cd290 100644 --- a/scalafmt-cli/jvm/src/main/scala/org/scalafmt/cli/CliUtils.scala +++ b/scalafmt-cli/jvm/src/main/scala/org/scalafmt/cli/CliUtils.scala @@ -9,13 +9,13 @@ private[scalafmt] trait CliUtils { def nailMain(nGContext: NGContext): Unit = { val workingDirectory = AbsoluteFile - .fromPathIfAbsolute(nGContext.getWorkingDirectory).getOrElse { + .fromPathIfAbsolute(nGContext.getWorkingDirectory).getOrElse( throw new IllegalStateException( s"Expected absolute path, " + s"obtained nGContext.getWorkingDirectory = ${nGContext .getWorkingDirectory}", - ) - } + ), + ) val exit = Cli.mainWithOptions( nGContext.getArgs, CliOptions.default.copy(common = diff --git a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/Cli.scala b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/Cli.scala index 4828a711d3..7283ee4b1a 100644 --- a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/Cli.scala +++ b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/Cli.scala @@ -70,15 +70,13 @@ object Cli extends CliUtils { private type MaybeRunner = Either[String, ScalafmtRunner] private def findRunner(options: CliOptions): MaybeRunner = options.hoconOpt - .fold[MaybeRunner] { - Left( - s"""|error: missing Scalafmt configuration file. - |Consider creating '${options.getProposedConfigFile}' - |with the following (other parameters may also be required): - |${getProposedConfigVersion(options)} - |""".stripMargin, - ) - } { + .fold[MaybeRunner](Left( + s"""|error: missing Scalafmt configuration file. + |Consider creating '${options.getProposedConfigFile}' + |with the following (other parameters may also be required): + |${getProposedConfigVersion(options)} + |""".stripMargin, + )) { // Run format using // - `scalafmt-dynamic` if the specified `version` setting doesn't match build version. // - `scalafmt-core` if the specified `version` setting match with build version @@ -101,7 +99,7 @@ object Cli extends CliUtils { options.common.debug.println(s"Using core runner [$stableVersion]") Right(ScalafmtCoreRunner) case Right(v) if isNative => - Left( + Left { s"""|error: invalid Scalafmt version. | |This Scalafmt installation has version '$stableVersion' and the version configured in '${options @@ -113,8 +111,8 @@ object Cli extends CliUtils { | |NOTE: this error happens only when running a native Scalafmt binary. |Scalafmt automatically installs and invokes the correct version of Scalafmt when running on the JVM. - |""".stripMargin, - ) + |""".stripMargin + } case Right(v) => options.common.debug.println(s"Using dynamic runner [$v]") Right(getDynamicRunner()) diff --git a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliArgParser.scala b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliArgParser.scala index f5e5747a4f..5cf4f0dfb1 100644 --- a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliArgParser.scala +++ b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliArgParser.scala @@ -138,11 +138,11 @@ object CliArgParser { |""".stripMargin, ) - checkConfig { c => + checkConfig(c => if (c.config.isDefined && c.configStr.isDefined) failure("may not specify both --config and --config-str") - else success - } + else success, + ) } def buildInfo = s"""|build commit: ${Versions.commit} diff --git a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliOptions.scala b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliOptions.scala index 22908ffd58..d3e98b9f9c 100644 --- a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliOptions.scala +++ b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/CliOptions.scala @@ -121,10 +121,10 @@ case class CliOptions( * @return * A path to a configuration file */ - def configPath: Path = tempConfigPath.getOrElse { + def configPath: Path = tempConfigPath.getOrElse( canonicalConfigFile - .fold(throw new NoSuchFileException("Config file not found"))(_.get) - } + .fold(throw new NoSuchFileException("Config file not found"))(_.get), + ) private[cli] lazy val canonicalConfigFile: Option[Try[Path]] = gitOps .getCanonicalConfigFile(cwd, config) @@ -145,12 +145,9 @@ case class CliOptions( .fold(Configured.ok(baseConfig))(ScalafmtConfig.fromConf(_, baseConfig)) private[cli] lazy val hoconOpt: Option[ConfParsed] = configStr - .map(ConfParsed.fromString(_)).orElse { - canonicalConfigFile.map(_.fold( - x => new ConfParsed(Configured.exception(x)), - ConfParsed.fromPath(_), - )) - } + .map(ConfParsed.fromString(_)).orElse(canonicalConfigFile.map( + _.fold(x => new ConfParsed(Configured.exception(x)), ConfParsed.fromPath(_)), + )) lazy val fileFetchMode: FileFetchMode = mode .getOrElse(if (isGit) GitFiles else RecursiveSearch) diff --git a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/FileFetchMode.scala b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/FileFetchMode.scala index a07ff30901..730b4f167f 100644 --- a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/FileFetchMode.scala +++ b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/FileFetchMode.scala @@ -27,12 +27,12 @@ object FileFetchMode { * RecursiveSearch and GitFiles are the fallback used in the absence of other * options */ - implicit val read: Read[FileFetchMode] = Read.reads { x => + implicit val read: Read[FileFetchMode] = Read.reads(x => if (x.startsWith(diffRefPrefix)) DiffFiles(x.substring(diffRefPrefix.length).trim) else availableModesMap - .getOrElse(x, throw new IllegalArgumentException(s"unknown mode: $x")) - } + .getOrElse(x, throw new IllegalArgumentException(s"unknown mode: $x")), + ) } diff --git a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala index a8b3e270ab..9ed7936072 100644 --- a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala +++ b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala @@ -42,14 +42,12 @@ object ScalafmtCoreRunner extends ScalafmtRunner { val termDisplay = newTermDisplay(options, inputMethods, termDisplayMessage) val exitCode = new AtomicReference(ExitCode.Ok) - Breaks.breakable { - inputMethods.compatPar.foreach { inputMethod => - val code = handleFile(inputMethod, options, adjustedScalafmtConf) - exitCode.getAndUpdate(ExitCode.merge(code, _)) - if (options.check && !code.isOk) Breaks.break - termDisplay.taskProgress(termDisplayMessage) - } - } + Breaks.breakable(inputMethods.compatPar.foreach { inputMethod => + val code = handleFile(inputMethod, options, adjustedScalafmtConf) + exitCode.getAndUpdate(ExitCode.merge(code, _)) + if (options.check && !code.isOk) Breaks.break + termDisplay.taskProgress(termDisplayMessage) + }) termDisplay.completedTask(termDisplayMessage, exitCode.get.isOk) termDisplay.stop() exitCode.get() diff --git a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala index e1118203c2..49b980c02c 100644 --- a/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala +++ b/scalafmt-cli/shared/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala @@ -38,19 +38,17 @@ object ScalafmtDynamicRunner extends ScalafmtRunner { val termDisplay = newTermDisplay(options, inputMethods, termDisplayMessage) val exitCode = new AtomicReference(ExitCode.Ok) - breakable { - inputMethods.compatPar.foreach { inputMethod => - try { - val code = handleFile(inputMethod, session, options) - exitCode.getAndUpdate(ExitCode.merge(code, _)) - } catch { - case e: Error.MisformattedFile => - reporter.error(e.file, e) - if (options.check) break - } - termDisplay.taskProgress(termDisplayMessage) + breakable(inputMethods.compatPar.foreach { inputMethod => + try { + val code = handleFile(inputMethod, session, options) + exitCode.getAndUpdate(ExitCode.merge(code, _)) + } catch { + case e: Error.MisformattedFile => + reporter.error(e.file, e) + if (options.check) break } - } + termDisplay.taskProgress(termDisplayMessage) + }) val exit = ExitCode.merge(exitCode.get, reporter.getExitCode) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AlignToken.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AlignToken.scala index 5d143b18c0..9a8d24695f 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AlignToken.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AlignToken.scala @@ -89,15 +89,15 @@ object AlignToken { class Matcher(val owner: Option[jurPattern], val parents: Seq[jurPattern]) { def matches(tree: meta.Tree): Boolean = owner.forall(check(tree)) && - (parents.isEmpty || tree.parent.exists { p => + (parents.isEmpty || tree.parent.exists(p => parents.forall(check(p)) || - (p match { - case ParamClauseParent(pp) => parents.forall(check(pp)) - case _: meta.Member.SyntaxValuesClause => p.parent - .exists(pp => parents.forall(check(pp))) - case _ => false - }) - }) + (p match { + case ParamClauseParent(pp) => parents.forall(check(pp)) + case _: meta.Member.SyntaxValuesClause => p.parent + .exists(pp => parents.forall(check(pp))) + case _ => false + }), + )) } @inline diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Newlines.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Newlines.scala index 4949f23aae..f3242a9629 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Newlines.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Newlines.scala @@ -261,14 +261,12 @@ case class Newlines( @inline def keepBreak(implicit ft: FT): Boolean = keepBreak(ft.hasBreak) - val breakAfterInfix: AfterInfix = afterInfix.getOrElse { - source match { - case Newlines.unfold => AfterInfix.many - case Newlines.fold => AfterInfix.some - case Newlines.keep => AfterInfix.keep - case Newlines.classic => AfterInfix.keep - } - } + val breakAfterInfix: AfterInfix = afterInfix.getOrElse(source match { + case Newlines.unfold => AfterInfix.many + case Newlines.fold => AfterInfix.some + case Newlines.keep => AfterInfix.keep + case Newlines.classic => AfterInfix.keep + }) val formatInfix: Boolean = breakAfterInfix ne AfterInfix.keep def checkInfixConfig(infixCount: Int): Newlines = @@ -326,9 +324,9 @@ case class Newlines( /* minBreaks has to come first; since we'll be adding blanks, this could * potentially move us into another setting which didn't match before we * we added the blanks; the rest are sorted to put more specific first */ - topLevelStatementBlankLines.filter(x => x.minNest <= x.maxNest).sortBy { - x => (x.minBreaks, x.maxNest, -x.minNest, x.regex.fold(0)(-_.length)) - } + topLevelStatementBlankLines.filter(x => x.minNest <= x.maxNest).sortBy( + x => (x.minBreaks, x.maxNest, -x.minNest, x.regex.fold(0)(-_.length)), + ) @inline def hasTopStatBlankLines = topStatBlankLinesSorted.nonEmpty diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReaderUtil.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReaderUtil.scala index 7c0d5b3ab1..5fd1f64e0f 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReaderUtil.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReaderUtil.scala @@ -41,11 +41,11 @@ object ReaderUtil { ConfError.message(msg) } }) - val encoder = ConfEncoder.instance[T] { value => + val encoder = ConfEncoder.instance[T](value => options.collectFirst { case sourcecode.Text(`value`, source) => Conf.Str(source) - }.getOrElse(Conf.Null()) - } + }.getOrElse(Conf.Null()), + ) new ConfCodecEx(encoder, decoder) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtConfig.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtConfig.scala index 96fdb30599..333e9ae613 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtConfig.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtConfig.scala @@ -210,12 +210,12 @@ case class ScalafmtConfig( private def getConfigViaLayoutInfoFor(absfile: AbsoluteFile)( f: (ProjectFiles.Layout, String) => ScalafmtConfig, - ): Option[ScalafmtConfig] = project.layout.flatMap { layout => + ): Option[ScalafmtConfig] = project.layout.flatMap(layout => layout.getInfo(absfile).map { info => val style = f(layout, info.lang) if (info.isTest) style.forTest else style.forMain - } - } + }, + ) def getConfigFor(filename: String): Try[ScalafmtConfig] = { val absfile = AbsoluteFile(filename) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/BestFirstSearch.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/BestFirstSearch.scala index 486bd5ce2f..41a4637953 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/BestFirstSearch.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/BestFirstSearch.scala @@ -63,11 +63,11 @@ private class BestFirstSearch private (range: Set[Range])(implicit } Some(nextState) } - memo.get(key).orElse { + memo.get(key).orElse( if (isOpt) Some(None) // we wouldn't recurse unless the span was large else if (!start.terminal()) orElse(hadSlb = false) - else slbMemo.get(key).orElse(orElse(hadSlb = true)) - } + else slbMemo.get(key).orElse(orElse(hadSlb = true)), + ) } /** Runs best first search to find lowest penalty split. @@ -168,10 +168,10 @@ private class BestFirstSearch private (range: Set[Range])(implicit } else preFork = false } - actualSplits.foreach { split => + actualSplits.foreach(split => if (optimalFound) sendEvent(split) - else processNextState(getNext(curr, split)) - } + else processNextState(getNext(curr, split)), + ) } } } @@ -293,12 +293,10 @@ private class BestFirstSearch private (range: Set[Range])(implicit initStyle.runner.event(FormatEvent.Routes(routes)) val state = { def run = shortestPath(State.start, Int.MaxValue) - run.getOrElse { - stats.retry.flatMap { x => - stats = x - run.toOption - }.orNull - } + run.getOrElse(stats.retry.flatMap { x => + stats = x + run.toOption + }.orNull) } if (null != state) { stats.complete(state) 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 0992505296..ceca83f86e 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 @@ -181,13 +181,13 @@ class FormatOps( @tailrec def run(tok: FT): Unit = if (tok.idx < end.idx) { - val nextTokOpt = matches(tok).flatMap { closeFt => + val nextTokOpt = matches(tok).flatMap(closeFt => if (tok.left.start >= closeFt.left.end) None else { result = result.append(TokenRange(tok, closeFt)) Some(closeFt) - } - } + }, + ) val nextTok = nextTokOpt.getOrElse(next(tok)) if (nextTok ne tok) run(nextTok) } @@ -250,11 +250,11 @@ class FormatOps( def splitOneArgPerLineAfterCommaOnBreak(exclude: TokenRanges)( comma: FT, ): Policy = Policy ? (comma.right.is[T.Comment] && comma.noBreak) || - delayedBreakPolicy(Policy.End < comma, exclude) { - Policy.onlyFor(comma, prefix = "NL->A[,]") { - getOneArgPerLineSplitsAfterComma(comma.right, _) - } - } + delayedBreakPolicy(Policy.End < comma, exclude)( + Policy.onlyFor(comma, prefix = "NL->A[,]")( + getOneArgPerLineSplitsAfterComma(comma.right, _), + ), + ) private def getOneArgPerLineSplitsAfterComma(r: T, s: Seq[Split]) = if (r.is[T.LeftBrace]) SplitTag.OneArgPerLine.activateOnly(s) @@ -266,9 +266,9 @@ class FormatOps( def templateCurlyOrLastNonTrivial(tpl: Template): FT = templateCurly(tpl.body) .getOrElse(getLastNonTrivial(tpl)) - def templateDerivesOrCurlyOrLastNonTrivial(template: Template)(implicit - ft: FT, - ): FT = findTemplateGroupOnRight(_.getExpireToken)(template) + def templateDerivesOrCurlyOrLastNonTrivial( + template: Template, + )(implicit ft: FT): FT = findTemplateGroupOnRight(_.getExpireToken)(template) .getOrElse(templateCurlyOrLastNonTrivial(template)) private def findTreeInGroup[A]( @@ -285,9 +285,9 @@ class FormatOps( def iter(groups: Seq[Seq[Tree]]): Option[A] = if (isSeqSingle(groups)) // for the last group, return '{' or ':' - findTreeInGroup(groups.head, func) { x => - getHeadOpt(template.body).getOrElse(getLastNonTrivial(x.last)) - } + findTreeInGroup(groups.head, func)(x => + getHeadOpt(template.body).getOrElse(getLastNonTrivial(x.last)), + ) else { // for intermediate groups, return its last token val res = findTreeInGroup(groups.head, func)(tokenAfter) @@ -297,9 +297,9 @@ class FormatOps( } def getBreakBeforeElsePolicy(beforeElse: FT): Policy = Policy - .onlyFor(beforeElse, prefix = "ELSE") { - Decision.onlyNewlinesWithFallback(_, Seq(Split(Newline, 0))) - } + .onlyFor(beforeElse, prefix = "ELSE")( + Decision.onlyNewlinesWithFallback(_, Seq(Split(Newline, 0))), + ) def getBreakBeforeElsePolicy(term: Term.If): Policy = getElseToken(term) .flatMap { case (_, elsOpt) => elsOpt.map(getBreakBeforeElsePolicy) } @@ -445,9 +445,9 @@ class FormatOps( } private def switch(splits: Seq[Split], triggers: T*): Seq[Split] = splits - .map { x => - triggers.foldLeft(x) { case (y, trigger) => y.switch(trigger, false) } - } + .map(x => + triggers.foldLeft(x) { case (y, trigger) => y.switch(trigger, false) }, + ) @tailrec private def findMaybeEnclosingInfix( @@ -917,9 +917,9 @@ class FormatOps( nlSplit(1), ) } - }(template).getOrElse { - Seq(Split(Space, 0)) // shouldn't happen - } + }(template).getOrElse( + Seq(Split(Space, 0)), // shouldn't happen + ) } def binPackParentConstructorSplits( @@ -1066,8 +1066,8 @@ class FormatOps( val lastParens = allParenOwners.map(getLast) val lastParen = lastParens.lastOption.getOrElse(close) - val shouldNotDangle = !style.danglingParentheses - .atVerticalMultilineSite(lpOwner) + val shouldNotDangle = + !style.danglingParentheses.atVerticalMultilineSite(lpOwner) // Since classes and defs aren't the same (see below), we need to // create two (2) OneArgOneLineSplit when dealing with classes. One @@ -1243,9 +1243,10 @@ class FormatOps( .orElse(tokenAfterOpt(term.paramClause).map(getArrowAfter[T.FunctionArrow])) // look for arrow before body, if any, else after cond/pat - def getCaseArrow(term: Case): FT = tokenBeforeOpt(term.body).getOrElse { - getArrowAfter[T.RightArrow](tokenAfter(term.cond.getOrElse(term.pat))) - } + def getCaseArrow(term: Case): FT = tokenBeforeOpt(term.body) + .getOrElse(getArrowAfter[T.RightArrow](tokenAfter( + term.cond.getOrElse(term.pat), + ))) // look for arrow before body, if any, else after cond/pat def getCaseArrow(term: TypeCase): FT = next(tokenAfter(term.pat)) @@ -1643,12 +1644,11 @@ class FormatOps( body: Tree, isKeep: Boolean, spaceIndents: Seq[Indent] = Seq.empty, - )(nlSplitFunc: Int => Split)(implicit - style: ScalafmtConfig, - ft: FT, - ): Seq[Split] = checkComment(nlSplitFunc) { _ => - foldedNonComment(body, nlSplitFunc, isKeep, spaceIndents) - } + )( + nlSplitFunc: Int => Split, + )(implicit style: ScalafmtConfig, ft: FT): Seq[Split] = checkComment( + nlSplitFunc, + )(_ => foldedNonComment(body, nlSplitFunc, isKeep, spaceIndents)) def slbOnly(body: Tree, spaceIndents: Seq[Indent] = Seq.empty)( nlSplitFunc: Int => Split, @@ -1670,9 +1670,9 @@ class FormatOps( case Newlines.unfold => unfoldedNonComment(body, nlSplitFunc, spaceIndents, false) case Newlines.classic if x.noBreak => - Option(classicNoBreakFunc).fold(getFolded(true)) { func => - func.forThisLine +: getFoldedKeepNLOnly - } + Option(classicNoBreakFunc).fold(getFolded(true))(func => + func.forThisLine +: getFoldedKeepNLOnly, + ) case Newlines.keep if x.noBreak => getFolded(true) case _ => getFoldedKeepNLOnly // keep/classic with break } @@ -1767,12 +1767,12 @@ class FormatOps( } private[FormatOps] def onRightOpt(ro: Tree, ft: => FT): Option[SelectLike] = - get(ro) { _ => + get(ro)(_ => nextNonCommentAfter(ft) match { case xft @ FT(_, _: T.KwMatch, _) => Some(next(xft)) case _ => None - } - } + }, + ) def onRightOpt(ft: FT): Option[SelectLike] = onRightOpt(ft.meta.rightOwner, ft) @@ -1841,31 +1841,33 @@ class FormatOps( ft: FT, )(implicit style: ScalafmtConfig): Option[OptionalBracesRegion] = if (!style.dialect.allowSignificantIndentation) None - else Option(ft.left match { - case _: T.Colon => ColonEolImpl - case _: T.KwWith => WithImpl - case _: T.RightArrow => RightArrowImpl - case _: T.RightParen => RightParenImpl - case _: T.KwFor => ForImpl - case _: T.KwWhile => WhileImpl - case _: T.KwDo => DoImpl - case _: T.Equals => EqualsImpl - case _: T.KwTry => TryImpl - case _: T.KwCatch => CatchImpl - case _: T.KwFinally => FinallyImpl - case _: T.KwMatch => MatchImpl - case _: T.KwThen => ThenImpl - case _: T.KwIf => IfImpl - case _: T.KwElse => ElseImpl - case _: T.KwReturn | _: T.ContextArrow | _: T.LeftArrow | _: T.KwThrow | - _: T.KwYield => BlockImpl - case _ => null - }).flatMap { impl => + else Option { + ft.left match { + case _: T.Colon => ColonEolImpl + case _: T.KwWith => WithImpl + case _: T.RightArrow => RightArrowImpl + case _: T.RightParen => RightParenImpl + case _: T.KwFor => ForImpl + case _: T.KwWhile => WhileImpl + case _: T.KwDo => DoImpl + case _: T.Equals => EqualsImpl + case _: T.KwTry => TryImpl + case _: T.KwCatch => CatchImpl + case _: T.KwFinally => FinallyImpl + case _: T.KwMatch => MatchImpl + case _: T.KwThen => ThenImpl + case _: T.KwIf => IfImpl + case _: T.KwElse => ElseImpl + case _: T.KwReturn | _: T.ContextArrow | _: T.LeftArrow | + _: T.KwThrow | _: T.KwYield => BlockImpl + case _ => null + } + }.flatMap { impl => implicit val ift: FT = ft val nft = nextNonComment(ft) - impl.create(nft).filter { ob => - !nft.right.is[T.LeftBrace] || nft.meta.rightOwner.parent != ob.owner - } + impl.create(nft).filter(ob => + !nft.right.is[T.LeftBrace] || nft.meta.rightOwner.parent != ob.owner, + ) } def at(ft: FT)(implicit style: ScalafmtConfig): Boolean = get(ft).nonEmpty @@ -1977,26 +1979,30 @@ class FormatOps( else Some(style.indent.main + style.indent.getSignificant) case _ => None } - Some(new OptionalBracesRegion { - def owner = ac.parent - def splits = Some(args match { - case (tf: Term.FunctionTerm) :: Nil - if !style.newlines.alwaysBeforeCurlyLambdaParams && - // https://dotty.epfl.ch/docs/internals/syntax.html - (tf.paramClause match { // LambdaStart - case tpc @ Term.ParamClause(tp :: Nil, mod) => - mod.isEmpty && tp.mods.isEmpty && tp.decltpe.isEmpty || - isEnclosedWithinParens(tpc) - case _ => true // multiple params are always in parens - }) => - getSplits(ac, forceNL = false, indentOpt = indent) match { - case s +: rs if !s.isNL => funcSplit(tf)(s.fileLine) +: rs - case ss => ss + Some { + new OptionalBracesRegion { + def owner = ac.parent + def splits = Some { + args match { + case (tf: Term.FunctionTerm) :: Nil + if !style.newlines.alwaysBeforeCurlyLambdaParams && + // https://dotty.epfl.ch/docs/internals/syntax.html + (tf.paramClause match { // LambdaStart + case tpc @ Term.ParamClause(tp :: Nil, mod) => + mod.isEmpty && tp.mods.isEmpty && + tp.decltpe.isEmpty || isEnclosedWithinParens(tpc) + case _ => true // multiple params are always in parens + }) => + getSplits(ac, forceNL = false, indentOpt = indent) match { + case s +: rs if !s.isNL => funcSplit(tf)(s.fileLine) +: rs + case ss => ss + } + case _ => getSplits(ac, forceNL = true, indentOpt = indent) } - case _ => getSplits(ac, forceNL = true, indentOpt = indent) - }) - def rightBrace = treeLast(ac) - }) + } + def rightBrace = treeLast(ac) + } + } } } @@ -2262,9 +2268,9 @@ class FormatOps( } } lo match { - case t: Term.Try => t.finallyp.map(createImpl { - isCatchUsingOptionalBraces(t) || isTreeUsingOptionalBraces(t.expr) - }) + case t: Term.Try => t.finallyp.map(createImpl( + isCatchUsingOptionalBraces(t) || isTreeUsingOptionalBraces(t.expr), + )) case t: Term.TryWithHandler => t.finallyp .map(createImpl(isTreeUsingOptionalBraces(t.expr))) case _ => None @@ -2339,13 +2345,13 @@ class FormatOps( if (!isThenPWithOptionalBraces(t)) None else Some(shouldBreakInOptionalBraces(ft, nft)) case _ => Some(true) - }).map { forceNL => + }).map(forceNL => new OptionalBracesRegion { def owner = Some(t) def splits = Some(getSplits(t.elsep, forceNL)) def rightBrace = blockLast(t.elsep) - } - } + }, + ) case _ => None } } @@ -2382,10 +2388,10 @@ class FormatOps( val beforeDot = prevNonCommentSameLine(dot) val policy = Policy.End <= beforeDot ==> Policy.onRight(dot, "NL-NOIND-SELECT") { - case Decision(`beforeDot`, ss) => ss.flatMap { s => + case Decision(`beforeDot`, ss) => ss.flatMap(s => if ((dot eq beforeDot) && !s.isNL) None - else Some(s.deActivateFor(SplitTag.SelectChainFirstNL)) - } + else Some(s.deActivateFor(SplitTag.SelectChainFirstNL)), + ) case Decision(_, ss) => ss .map(_.deActivateFor(SplitTag.SelectChainFirstNL)) } @@ -2425,10 +2431,10 @@ class FormatOps( fileLine: FileLine, style: ScalafmtConfig, ft: FT, - ): Option[WithStats] = head.flatMap { head => + ): Option[WithStats] = head.flatMap(head => if (!isJustBeforeTree(nft)(head)) None - else Some(new WithStats(nft, body, owner, nlOnly, indentOpt)) - } + else Some(new WithStats(nft, body, owner, nlOnly, indentOpt)), + ) } private def getSplitsForIf(nft: FT, t: Term.If)(implicit @@ -2907,11 +2913,11 @@ class FormatOps( def policyWithDelay(policy: Policy) = // force break if multiline and if there's no other break - delayedBreakPolicy(Policy.End >= beforeDelims, exclude) { + delayedBreakPolicy(Policy.End >= beforeDelims, exclude)( Policy.RelayOnSplit { case (s, nextft) => s.isNL && nextft.idx > beforeDelims.idx // don't need anymore - }(policy)(NoPolicy) - } + }(policy)(NoPolicy), + ) (afterDelims.right match { case _: T.Dot => // check if Dot rule includes a break option @@ -2924,10 +2930,10 @@ class FormatOps( cfg.newlines.encloseSelectChains, ) Right(canStartSelectChain(x, nextSelect, expireTree)) - case Newlines.keep => Left(Policy.onlyFor(afterDelims, "BP1L.NL") { + case Newlines.keep => Left(Policy.onlyFor(afterDelims, "BP1L.NL")( Decision.onlyNewlineSplits(_) - .map(_.preActivateFor(SplitTag.SelectChainBinPackNL)) - }) + .map(_.preActivateFor(SplitTag.SelectChainBinPackNL)), + )) case _ => Right(true) } }.getOrElse(Right(false)) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatTokens.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatTokens.scala index dd8d165fc3..622448ebd4 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatTokens.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatTokens.scala @@ -94,12 +94,12 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FT]) def getHeadAndLastIfEnclosed( tokens: Tokens, tree: Tree, - ): Option[(FT, Option[FT])] = getHeadOpt(tokens, tree).map { head => + ): Option[(FT, Option[FT])] = getHeadOpt(tokens, tree).map(head => head -> matchingOptLeft(head).flatMap { other => val last = getLastNonTrivial(tokens, tree) if (last eq other) Some(last) else None - } - } + }, + ) def getHeadAndLastIfEnclosed(tree: Tree): Option[(FT, Option[FT])] = getHeadAndLastIfEnclosed(tree.tokens, tree) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala index 6462529bcf..50060dea13 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala @@ -194,7 +194,7 @@ class FormatWriter(formatOps: FormatOps) { minBlockStats: Int, ): Option[Tree] = { val ob = formatOps.OptionalBraces.get(floc.formatToken)(floc.style) - ob.flatMap(_.owner).filter { + ob.flatMap(_.owner).filter( /* if we add the end marker, it might turn a single-stat expression (or * block) into a multi-stat block and thus potentially change how that * parent expression would have been formatted; so, avoid those cases. @@ -203,8 +203,8 @@ class FormatWriter(formatOps: FormatOps) { case Some(t: Term.Block) => t.stats.lengthCompare(minBlockStats) >= 0 case Some(_: Template.Body | _: Source | _: Pkg.Body) => true case _ => false - } - } + }, + ) } private def checkRemoveEndMarkers(locations: Array[FormatLocation]): Unit = { @@ -379,8 +379,8 @@ class FormatWriter(formatOps: FormatOps) { ) { val addLine = style.newlines.alwaysBeforeElseAfterCurlyIf || (endFt.right match { - case _: T.KwElse | _: T.KwCatch | _: T.KwFinally => !owner.parent - .contains(endFt.meta.rightOwner) + case _: T.KwElse | _: T.KwCatch | _: T.KwFinally => + !owner.parent.contains(endFt.meta.rightOwner) case _ => true }) if (addLine) willAddLines.prepend(end) @@ -1260,50 +1260,50 @@ class FormatWriter(formatOps: FormatOps) { child: Tree, depth: Int, maybeParent: Option[Tree] = None, - )(implicit fl: FormatLocation): (Tree, Int) = maybeParent - .orElse(child.parent) match { - case Some(AlignContainer(p)) => (p, depth) - case Some( - p @ (_: Term.Select | _: Pat.Var | _: Term.ApplyInfix | - _: Template | _: Member.ParamClauseGroup), - ) => getAlignContainerParent(p, depth) - case Some(p: Term.Apply) if (p.argClause.values match { - case (_: Term.Apply) :: Nil => true - case _ => p.fun eq child - }) => getAlignContainerParent(p, depth) - // containers that can be traversed further if on same line - case Some(p @ (_: Case | _: Enumerator)) => - if (isEarlierLine(p)) (p, depth) else getAlignContainerParent(p, depth) - // containers that can be traversed further if lhs single-line - case Some(p @ AlignContainer.WithBody(mods, b)) => - val keepGoing = { - val ptokens = p.tokens - val beg = mods.lastOption - .fold(after(ptokens.head))(m => next(tokenAfter(m))) - val useBody = b.eq(child) || p.eq(child) - val beforeBody = if (useBody) tokenJustBeforeOpt(b) else None - val end = beforeBody.getOrElse(before(ptokens.last)) - getLineDiff(locations, beg, end) == 0 - } - if (keepGoing) getAlignContainerParent(p, depth) else (p, depth) - case Some(p: Term.ForYield) if child ne p.body => (p, depth) - case Some(p: Member.ParamClause) => p.parent match { - // if all on single line, keep going - case Some(q) if onSingleLine(q) => - getAlignContainerParent(p, depth + 1) - // if this one not on single line, use parent as the owner - case Some(q) if !onSingleLine(p) => // skip ParamClauseGroup - val ac = - if (q.is[Member.ParamClauseGroup]) q.parent.getOrElse(q) else q - (ac, depth) - case _ => (p, depth) // this one on single line, but the rest are not - } - case Some(p: Member.SyntaxValuesClause) => - val isEnclosed = isEnclosedInMatching(p) - getAlignContainerParent(p, if (isEnclosed) depth + 1 else depth) - case Some(p) => (p.parent.getOrElse(p), depth) - case _ => (child, depth) - } + )(implicit fl: FormatLocation): (Tree, Int) = + maybeParent.orElse(child.parent) match { + case Some(AlignContainer(p)) => (p, depth) + case Some( + p @ (_: Term.Select | _: Pat.Var | _: Term.ApplyInfix | + _: Template | _: Member.ParamClauseGroup), + ) => getAlignContainerParent(p, depth) + case Some(p: Term.Apply) if (p.argClause.values match { + case (_: Term.Apply) :: Nil => true + case _ => p.fun eq child + }) => getAlignContainerParent(p, depth) + // containers that can be traversed further if on same line + case Some(p @ (_: Case | _: Enumerator)) => + if (isEarlierLine(p)) (p, depth) else getAlignContainerParent(p, depth) + // containers that can be traversed further if lhs single-line + case Some(p @ AlignContainer.WithBody(mods, b)) => + val keepGoing = { + val ptokens = p.tokens + val beg = mods.lastOption + .fold(after(ptokens.head))(m => next(tokenAfter(m))) + val useBody = b.eq(child) || p.eq(child) + val beforeBody = if (useBody) tokenJustBeforeOpt(b) else None + val end = beforeBody.getOrElse(before(ptokens.last)) + getLineDiff(locations, beg, end) == 0 + } + if (keepGoing) getAlignContainerParent(p, depth) else (p, depth) + case Some(p: Term.ForYield) if child ne p.body => (p, depth) + case Some(p: Member.ParamClause) => p.parent match { + // if all on single line, keep going + case Some(q) if onSingleLine(q) => + getAlignContainerParent(p, depth + 1) + // if this one not on single line, use parent as the owner + case Some(q) if !onSingleLine(p) => // skip ParamClauseGroup + val ac = + if (q.is[Member.ParamClauseGroup]) q.parent.getOrElse(q) else q + (ac, depth) + case _ => (p, depth) // this one on single line, but the rest are not + } + case Some(p: Member.SyntaxValuesClause) => + val isEnclosed = isEnclosedInMatching(p) + getAlignContainerParent(p, if (isEnclosed) depth + 1 else depth) + case Some(p) => (p.parent.getOrElse(p), depth) + case _ => (child, depth) + } @tailrec private def getAlignContainer(t: Tree, depth: Int = 0)(implicit @@ -1341,7 +1341,7 @@ class FormatWriter(formatOps: FormatOps) { shiftStateColumnIndent(ftIndex + 1, headStop.shift) } var previousShift = 0 - x.stops.foreach { stop => + x.stops.foreach(stop => if (stop.isActive) { val currentShift = stop.shift val offset = currentShift - previousShift @@ -1349,8 +1349,8 @@ class FormatWriter(formatOps: FormatOps) { builder += stop.ft.meta.idx -> offset previousShift = currentShift } - } - } + }, + ) } } @@ -1457,8 +1457,9 @@ class FormatWriter(formatOps: FormatOps) { } val newImports = stat match { case t: ImportExportStat => - val (idxHead, head) = imports - .fold((idx, t)) { case (i, h, _) => (i, h) } + val (idxHead, head) = imports.fold((idx, t)) { case (i, h, _) => + (i, h) + } if (!isLast) Some((idxHead, head, t)) else { setStats(idxHead, head, t, true) @@ -1508,13 +1509,11 @@ class FormatWriter(formatOps: FormatOps) { override def apply(tree: Tree): Unit = tree match { case t: Source => applySeq(t)(t.stats) case t: Template => applySeqWith(t)(t.body.stats) { stats => - beforeBody(stats) { - _.beforeTemplateBodyIfBreakInParentCtors && { - val beg = leadingComment(t).meta.idx - val end = templateCurlyOrLastNonTrivial(t).meta.idx - locations(beg).leftLineId != locations(end).leftLineId - } - } + beforeBody(stats)(_.beforeTemplateBodyIfBreakInParentCtors && { + val beg = leadingComment(t).meta.idx + val end = templateCurlyOrLastNonTrivial(t).meta.idx + locations(beg).leftLineId != locations(end).leftLineId + }) afterBody(t, stats) } case t: Defn.ExtensionGroup => applySeqWith(t)(t.body match { @@ -1785,15 +1784,16 @@ object FormatWriter { def finalize(endRefIdx: Int): Boolean = newStops.nonEmpty && (line.style.align.allowOverflow || // check overflow - line.noOverflow(curShift) && buffer.forall { bl => + line.noOverflow(curShift) && buffer.forall(bl => bl.style.align.allowOverflow || - bl.stops.reverseIterator.find(_.isActive).forall { bs => - val shiftedColumn = bs.shifted - val idx = newStops - .lastIndexWhere(ns => ns.isActive && ns.shifted <= shiftedColumn) - idx >= 0 && bl.noOverflow(newColumns(idx) - bs.column) - } - }) && { + bl.stops.reverseIterator.find(_.isActive).forall { bs => + val shiftedColumn = bs.shifted + val idx = newStops.lastIndexWhere(ns => + ns.isActive && ns.shifted <= shiftedColumn, + ) + idx >= 0 && bl.noOverflow(newColumns(idx) - bs.column) + }, + )) && { // now we mutate (0 until newStops.length) .foreach(idx => newStops(idx).shifted = newColumns(idx)) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/OptimizationEntities.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/OptimizationEntities.scala index 77cc59ba17..6f4c386b80 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/OptimizationEntities.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/OptimizationEntities.scala @@ -151,10 +151,11 @@ object OptimizationEntities { addDefn[T.KwDef](t.mods, t) addAllStmts(t.body.stats) // special handling for rewritten blocks - case t @ Term.Block(_ :: Nil) if t.tokens.headOption.exists { x => + case t @ Term.Block(_ :: Nil) + if t.tokens.headOption.exists(x => // ignore single-stat block if opening brace was removed - x.is[T.LeftBrace] && ftoks(x).left.ne(x) - } => + x.is[T.LeftBrace] && ftoks(x).left.ne(x), + ) => case t: Term.EnumeratorsBlock => var wasGuard = false t.enums.tail.foreach { x => @@ -180,10 +181,10 @@ object OptimizationEntities { case t @ Term.ArgClause(s :: Nil, _) if !s.isAny[Term.Block, Term.PartialFunction] && !skipBlockSingleStat(s, isInArgClause = true) => - t.tokens.headOption.foreach { x => + t.tokens.headOption.foreach(x => // check for single-stat arg if opening paren was replaced with brace - if (x.is[T.LeftParen] && ftoks(x).left.is[T.LeftBrace]) addOneStmt(s) - } + if (x.is[T.LeftParen] && ftoks(x).left.is[T.LeftBrace]) addOneStmt(s), + ) case Tree.Block(s) => addAllStmts(s) case _ => // Nothing } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Policy.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Policy.scala index 8ed9bde475..76d7263d88 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Policy.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Policy.scala @@ -302,11 +302,11 @@ object Policy { } private object Expire { - def apply(policy: Policy, endPolicy: End.WithPos): Expire = policy - .asUntil(endPolicy) match { - case p: Expire => p - case p => new Expire(p, endPolicy) - } + def apply(policy: Policy, endPolicy: End.WithPos): Expire = + policy.asUntil(endPolicy) match { + case p: Expire => p + case p => new Expire(p, endPolicy) + } } private class Expire private (policy: Policy, endPolicy: End.WithPos) @@ -349,11 +349,11 @@ object Policy { } private object Delay { - def apply(policy: Policy, begPolicy: End.WithPos): Delay = policy - .asAfter(begPolicy) match { - case p: Delay => p - case p => new Delay(p, begPolicy) - } + def apply(policy: Policy, begPolicy: End.WithPos): Delay = + policy.asAfter(begPolicy) match { + case p: Delay => p + case p => new Delay(p, begPolicy) + } } private class Delay private (val policy: Policy, val begPolicy: End.WithPos) @@ -495,12 +495,12 @@ object Policy { private object PredicateDecision { def unapply(d: Decision): Option[Seq[Split]] = { var replaced = false - def applyMap(s: Split): Option[Split] = Option(pred(s)).filter { ss => + def applyMap(s: Split): Option[Split] = Option(pred(s)).filter(ss => (s eq ss) || { replaced = true !ss.isIgnored - } - } + }, + ) val splits = d.splits.flatMap(applyMap) if (replaced) Some(splits) else None } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Router.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Router.scala index 5d562d3bd7..285cb28c27 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Router.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Router.scala @@ -79,11 +79,11 @@ class Router(formatOps: FormatOps) { val penalty = BreakSingleLineInterpolatedString if (style.newlines.inInterpolation eq Newlines.InInterpolation.avoid) Policy.onLeft(end, "INTERP-AVOID-NL", rank = -1) { - case Decision(_, ss) => ss.map { s => + case Decision(_, ss) => ss.map(s => if (s.isNL) s.withPenalty(penalty) else if (s.optimalAt.isEmpty) s - else s.copy(optimalAt = None) - } + else s.copy(optimalAt = None), + ) } else if (!style.newlines.sourceIgnored && !isTripleQuote(m.left.text)) Policy.onLeft(end, "INTERP-KEEP-NONL") { @@ -98,7 +98,7 @@ class Router(formatOps: FormatOps) { } val split = Split(NoSplit, 0, policy = policy) val alignIndents = - if (style.align.stripMargin) findInterpolate(leftOwner).flatMap { ti => + if (style.align.stripMargin) findInterpolate(leftOwner).flatMap(ti => getStripMarginChar(ti).map { pipe => val startsWithPipe = ti.parts.headOption match { case Some(Lit.String(x)) => x.headOption.contains(pipe) @@ -109,8 +109,8 @@ class Router(formatOps: FormatOps) { // -1 because of margin characters | Indent(if (startsWithPipe) -1 else -2, end, After), ) - } - } + }, + ) else None val indents = alignIndents .getOrElse(Seq(Indent(style.indent.main, end, After))) @@ -231,13 +231,13 @@ class Router(formatOps: FormatOps) { case FT(_: T.Equals, _, DefValAssignLeft(rhs)) => maybeGetInfixSplitsBeforeLhs() { def endFt = getLast(rhs) - getSplitsDefValEquals(rhs, endFt) { + getSplitsDefValEquals(rhs, endFt)( if (leftOwner.is[Tree.WithParamClauses]) getSplitsDefEquals(rhs, endFt) else getSplitsValEquals(rhs, endFt)( getSplitsValEqualsClassic(rhs, endFt), - ) - } + ), + ) } // { ... } Blocks @@ -296,11 +296,11 @@ class Router(formatOps: FormatOps) { case _ => getLambdaNone } val (lambdaArrow, lambdaIndent, lambdaNLOnly) = leftOwner match { - case t: Template.Body => t.selfOpt.fold { + case t: Template.Body => t.selfOpt.fold( if (t.parent.parent.isOpt[Term.NewAnonymous]) getLambdaInfo(t.stats) - else getLambdaNone - } { owner => + else getLambdaNone, + ) { owner => val anno = owner.tokens.last val indent = style.indent.main val annoFT = tokens(anno) @@ -393,9 +393,9 @@ class Router(formatOps: FormatOps) { // copy logic from `( ...`, binpack=never, defining `slbSplit` val slbParensPolicy = Policy ? (slbMod eq noSplitMod) || { val beforeClose = prev(close) - Policy.onlyFor(beforeClose, "BracesToParens") { - _.flatMap(s => if (s.isNL) None else Some(s.withMod(NoSplit))) - } + Policy.onlyFor(beforeClose, "BracesToParens")( + _.flatMap(s => if (s.isNL) None else Some(s.withMod(NoSplit))), + ) } val exclude = slbParensExclude.getOrElse(TokenRanges.empty) val slbPolicy = @@ -405,18 +405,18 @@ class Router(formatOps: FormatOps) { case _ => Nil }, ) - val sldPolicy = ownerIfNeedBreakAfterClose.map { p => + val sldPolicy = ownerIfNeedBreakAfterClose.map(p => if (style.newlines.fold) { val pend = getSlbEndOnLeft(getLast(p)) def pendSlb(s: Split) = s .withSingleLine(pend, noSyntaxNL = true, extend = true) - Policy.onlyFor(close, s"RB-ELSE[${pend.idx}]") { ss => + Policy.onlyFor(close, s"RB-ELSE[${pend.idx}]")(ss => if (ss.exists(_.isNL)) ss.map(s => if (s.isNL) s else pendSlb(s)) else ss - .flatMap(s => Seq(pendSlb(s), s.withMod(Newline).withPenalty(1))) - } - } else decideNewlinesOnlyAfterClose(close) - } + .flatMap(s => Seq(pendSlb(s), s.withMod(Newline).withPenalty(1))), + ) + } else decideNewlinesOnlyAfterClose(close), + ) Split(slbMod, 0).withSingleLine( expire, exclude = exclude, @@ -463,12 +463,12 @@ class Router(formatOps: FormatOps) { val fnarrDesc = s"FNARR($nlArrowPenalty;$arrSplit)" slbMod -> Policy.onlyFor(lambdaExpire, fnarrDesc) { ss => var hadNoSplit = false - val nlSplits = ss.flatMap { s => + val nlSplits = ss.flatMap(s => // penalize NL one extra, for closing brace if (s.isNL) Some(s.andPolicy(nlPolicy).withPenalty(nlArrowPenalty)) - else { hadNoSplit = true; None } - } + else { hadNoSplit = true; None }, + ) if (hadNoSplit) arrSplit +: nlSplits else nlSplits } case _ => noSplitMod -> @@ -626,10 +626,10 @@ class Router(formatOps: FormatOps) { // Given decl case FT(_: T.KwGiven, _, FT.LeftOwner(gvn: Stat.GivenLike)) => if (style.newlines.unfold && gvn.paramClauseGroups.nonEmpty) { - val nonSlbPolicy = gvn.paramClauseGroups.flatMap { pcg => + val nonSlbPolicy = gvn.paramClauseGroups.flatMap(pcg => if (pcg.tparamClause.values.isEmpty) pcg.paramClauses - else pcg.tparamClause +: pcg.paramClauses - }.foldLeft(Policy.noPolicy) { case (policy, pc) => + else pcg.tparamClause +: pcg.paramClauses, + ).foldLeft(Policy.noPolicy) { case (policy, pc) => val pcLast = getLast(pc) val pcPolicy = Policy ? pcLast.left.is[T.RightArrow] && decideNewlinesOnlyAfterToken(nextNonCommentSameLine(pcLast)) @@ -778,26 +778,30 @@ class Router(formatOps: FormatOps) { case _ => false } } => - def modification: Modification = Space(leftOwner match { - case _ if left.is[T.Comment] => true - case _: Mod => true - // Add a space between constructor annotations and their parameter lists - // see: - // https://github.com/scalameta/scalafmt/pull/1516 - // https://github.com/scalameta/scalafmt/issues/1528 - case t: Init => t.parent.isOpt[Mod.Annot] - case Term.Name(name) => - style.spaces.afterTripleEquals && name == "===" || - (rightOwner match { - case _: Term.ArgClause => style.spaces.beforeApplyArgInParens(name) - case _: Member.ParamClause => style.spaces.afterSymbolicDefs && - isSymbolicName(name) - case _ => false - }) - case _: Defn.ExtensionGroup => style.spaces.afterKeywordBeforeParen && - soft.KwExtension.matches(left) - case _ => false - }) + def modification: Modification = Space { + leftOwner match { + case _ if left.is[T.Comment] => true + case _: Mod => true + // Add a space between constructor annotations and their parameter lists + // see: + // https://github.com/scalameta/scalafmt/pull/1516 + // https://github.com/scalameta/scalafmt/issues/1528 + case t: Init => t.parent.isOpt[Mod.Annot] + case Term.Name(name) => + style.spaces.afterTripleEquals && name == "===" || + (rightOwner match { + case _: Term.ArgClause => style.spaces + .beforeApplyArgInParens(name) + case _: Member.ParamClause => style.spaces.afterSymbolicDefs && + isSymbolicName(name) + case _ => false + }) + case _: Defn.ExtensionGroup => + style.spaces.afterKeywordBeforeParen && + soft.KwExtension.matches(left) + case _ => false + } + } def baseNoSplit(implicit fileLine: FileLine) = Split(modification, 0) val defn = isParamClauseSite(rightOwner) val defRhs = if (defn) defDefBodyParent(rightOwner) else None @@ -892,11 +896,11 @@ class Router(formatOps: FormatOps) { case Some(p: Member.Apply) => findLastCallArgs(p) case _ => t.argClause } - getSplitsBeforeOpenParen(x, indent, _.beforeOpenParenCallSite) { + getSplitsBeforeOpenParen(x, indent, _.beforeOpenParenCallSite)( rightOwner.parent.collect { case p: Member.Apply => findLastCallArgs(p) - } - } + }, + ) } else None beforeOpenParenSplits.getOrElse(Seq(baseNoSplit)) @@ -1291,25 +1295,25 @@ class Router(formatOps: FormatOps) { val rightIsComment = right.is[T.Comment] def getNoSplit(slbEnd: Option[FT])(implicit fileLine: FileLine) = { val mod = if (rightIsComment) Space.orNL(noBreak()) else noSplitMod - slbEnd.fold(Split(mod, 0)) { x => + slbEnd.fold(Split(mod, 0))(x => Split(mod, 0).withOptimalToken(x, killOnFail = true) - .withPolicy(SingleLineBlock(x, okSLC = true, noSyntaxNL = true)) - } + .withPolicy(SingleLineBlock(x, okSLC = true, noSyntaxNL = true)), + ) } val noSplit = if (nlOnly) Split.ignored else if (slbOrNL) getNoSplit(Some(close)) else { - val opensPolicy = bracketPenalty.map { p => + val opensPolicy = bracketPenalty.map(p => Policy.beforeLeft(close, "PENBP[") { case Decision(ftd @ FT(o: T.LeftBracket, _, m), s) if isParamClauseSite(m.leftOwner) && styleMap.at(o).binPack.bracketDefnSite .exists(_ != BinPack.Site.Never) => if (isRightCommentThenBreak(ftd)) s else s.penalizeNL(p) - } - } + }, + ) getNoSplit(nextComma.map(getSlbEndOnLeft)) .andPolicy((opensPolicy | penalizeBrackets) & noNLPolicy()) } @@ -1380,10 +1384,10 @@ class Router(formatOps: FormatOps) { val newlinesPenalty = 3 + indentLen * bracketPenalty val penalizeNewlinesPolicy = - policyWithExclude(exclude, Policy.End.BeforeLeft, Policy.End.OnLeft) { + policyWithExclude(exclude, Policy.End.BeforeLeft, Policy.End.OnLeft)( new PenalizeAllNewlines(newlinesPenalty) <= - findToken(beforeClose, prev)(x => !RightParenOrBracket(x.left)) - } + findToken(beforeClose, prev)(x => !RightParenOrBracket(x.left)), + ) val (onelineCurryToken, onelinePolicy) = afterFirstArgOneline .map(BinPackOneline.getPolicy(true, sjsExclude)) @@ -1423,14 +1427,14 @@ class Router(formatOps: FormatOps) { val nextComma = if (firstArg.isEmpty) None - else if (!oneline) tokens.findTokenEx(ft) { xft => + else if (!oneline) tokens.findTokenEx(ft)(xft => xft.right match { case close.left | _: T.RightBrace | _: T.RightArrow => null case _: T.Comma => Right(next(xft)) case _: T.LeftBrace => Left(matchingRight(xft)) case _ => Left(next(xft)) - } - }.toOption + }, + ).toOption else if (isSingleArg) None else afterFirstArgOneline.map(next) val opt = nextComma.getOrElse(getSlbEndOnLeft(close)) @@ -1657,13 +1661,13 @@ class Router(formatOps: FormatOps) { style.newlines.sometimesBeforeColonInMethodReturnType ) None else { - val nft = findToken(next(cp), next) { x => + val nft = findToken(next(cp), next)(x => x.right match { case _: T.Comment => x.hasBreak case _: T.RightParen | _: T.RightBracket => false case _ => true - } - } + }, + ) if (nft.right.is[T.Colon]) colonDeclType(nft.meta.rightOwner) .flatMap(getLastNonTrivialOpt) // could be empty tree else None @@ -1722,10 +1726,10 @@ class Router(formatOps: FormatOps) { case _ => defaultSplits } - style.binPack.siteFor(leftOwner) - .fold(altSplits) { case (bp, isCallSite) => - forBinPack(bp, isCallSite).getOrElse(defaultSplits) - } + style.binPack.siteFor(leftOwner).fold(altSplits) { + case (bp, isCallSite) => forBinPack(bp, isCallSite) + .getOrElse(defaultSplits) + } case FT(_, sc: T.Semicolon, _) => val forceBreak = hasBreak() && { @@ -1863,13 +1867,13 @@ class Router(formatOps: FormatOps) { val baseSplits = style.newlines.getSelectChains match { case Newlines.classic => def getNlMod = { - val endSelect = nextDotIfSig.fold { + val endSelect = nextDotIfSig.fold( nextSelect.fold { val ko = indentFewerBraces == Indents.FewerBraces.always && checkFewerBraces(expireTree) if (ko) None else Some(expire) - }(ns => Some(getLastNonTrivial(ns.qual))) - } { nd => + }(ns => Some(getLastNonTrivial(ns.qual))), + ) { nd => val ok = indentFewerBraces == Indents.FewerBraces.never if (ok) Some(nd) else None } @@ -1880,11 +1884,11 @@ class Router(formatOps: FormatOps) { val prevChain = inSelectChain(prevSelect, thisSelect, expireTree) def splitSecondNL( modNoBreaks: ModExt, - )(implicit fileLine: FileLine) = Split(!prevChain, 1) { + )(implicit fileLine: FileLine) = Split(!prevChain, 1)( if (!style.newlines.selectChains.classicKeepAfterFirstBreak) modNoBreaks - else Newline.orMod(hasBreak(), modSpace) - }.onlyFor(SplitTag.SelectChainSecondNL) + else Newline.orMod(hasBreak(), modSpace), + ).onlyFor(SplitTag.SelectChainSecondNL) if (canStartSelectChain(thisSelect, nextSelect, expireTree)) { val chainExpire = if (nextSelect.isEmpty) thisSelect.nameFt else expire @@ -2051,10 +2055,10 @@ class Router(formatOps: FormatOps) { nextSelect.isEmpty && checkFewerBraces(expireTree) if (ok) nlIndent else Indent.empty }(x => if (fbIndent) Indent(indentLen, x, Before) else Indent.Empty) - baseSplits.map { s => + baseSplits.map(s => if (s.isNL) s.withIndent(nlIndent).andFirstPolicy(nlPolicy) - else s.withIndent(spcIndent).andFirstPolicy(spcPolicy) - } + else s.withIndent(spcIndent).andFirstPolicy(spcPolicy), + ) } if (prevSelect.isEmpty) splits @@ -2232,20 +2236,18 @@ class Router(formatOps: FormatOps) { def nlSplitFunc(cost: Int)(implicit l: sourcecode.Line) = Split(Newline2x(ft), cost).withIndent(style.indent.main, expire, After) if (style.newlines.getBeforeMultiline eq Newlines.unfold) CtrlBodySplits - .checkComment(nlSplitFunc) { nft => + .checkComment(nlSplitFunc)(nft => if (nft.right.is[T.LeftBrace]) { val nextFt = nextNonCommentSameLineAfter(nft) val policy = decideNewlinesOnlyAfterToken(nextFt) Seq(Split(Space, 0, policy = policy)) - } else Seq(nlSplitFunc(0)) - } - else CtrlBodySplits.get(body) { - Split(Space, 0).withSingleLineNoOptimal( - expire, - insideBracesBlock(ft, expire), - noSyntaxNL = right.is[T.KwYield], + } else Seq(nlSplitFunc(0)), ) - }(nlSplitFunc) + else CtrlBodySplits.get(body)(Split(Space, 0).withSingleLineNoOptimal( + expire, + insideBracesBlock(ft, expire), + noSyntaxNL = right.is[T.KwYield], + ))(nlSplitFunc) case FT(left, kw @ (_: T.KwElse | _: T.KwYield), _) => if (left.is[T.RightBrace]) Seq(Split(Space, 0)) @@ -2284,9 +2286,9 @@ class Router(formatOps: FormatOps) { .withIndent(style.indent.main, expire, After) if (style.newlines.getBeforeMultiline eq Newlines.unfold) Seq(nlSplitFunc(0)) - else CtrlBodySplits.get(body) { - Split(Space, 0).withSingleLineNoOptimal(expire) - }(nlSplitFunc) + else CtrlBodySplits.get(body)( + Split(Space, 0).withSingleLineNoOptimal(expire), + )(nlSplitFunc) // Type variance case FT(_: T.Ident, right @ (_: T.Ident | _: T.Underscore), _) @@ -2339,13 +2341,13 @@ class Router(formatOps: FormatOps) { case Newlines.keep => Seq(if (hasBreak()) newlineSplit(0, isConfig) else spaceSplit) case _ => - val singleLine = enclosed.forall { x => + val singleLine = enclosed.forall(x => style.newlines.unfold && findTreeWithParent(x) { case _: Template.Body | _: Defn | _: Member.Infix => Some(true) case t: Term.Block if !isEnclosedInBraces(t) => None case _ => Some(false) - }.isEmpty - } + }.isEmpty, + ) Seq( if (!singleLine) spaceSplit else spaceSplitWithoutPolicy.withSingleLine(close).andPolicy( @@ -2385,10 +2387,10 @@ class Router(formatOps: FormatOps) { // postArrowFt points to non-comment after arrowFt // possibly on next line without intervening comments implicit val beforeMultiline = style.newlines.getBeforeMultiline - getClosingIfCaseBodyEnclosedAsBlock(postArrow, owner).fold { + getClosingIfCaseBodyEnclosedAsBlock(postArrow, owner).fold( Policy ? beforeMultiline.in(Newlines.fold, Newlines.keep) || - defaultPolicy - } { rparen => + defaultPolicy, + ) { rparen => val lparen = next(postArrow) val postParen = nextNonCommentSameLine(lparen) val indent = style.indent.main @@ -2476,9 +2478,9 @@ class Router(formatOps: FormatOps) { } val end = getLast(body) val indent = Indent(style.indent.main, end, ExpiresOn.After) - CtrlBodySplits.get(body, Seq(indent)) { - Split(Space, 0).withSingleLineNoOptimal(end) - }(Split(Newline2x(ft), _).withIndent(indent)) + CtrlBodySplits.get(body, Seq(indent))( + Split(Space, 0).withSingleLineNoOptimal(end), + )(Split(Newline2x(ft), _).withIndent(indent)) // Term.ForYield case FT(_: T.KwYield, _, FT.LeftOwner(owner: Term.ForYield)) => @@ -2750,10 +2752,10 @@ class Router(formatOps: FormatOps) { case FT(_: T.Equals, _: T.KwMacro, _) if dialect.allowSignificantIndentation => // scala3 compiler doesn't allow newline before `macro` - splits.map { s => + splits.map(s => if (!s.isNL) s - else s.withMod(Space).andPolicy(decideNewlinesOnlyAfterClose(next(ft))) - } + else s.withMod(Space).andPolicy(decideNewlinesOnlyAfterClose(next(ft))), + ) case _ => splits } } @@ -2781,9 +2783,9 @@ class Router(formatOps: FormatOps) { else if (style.newlines.forceBeforeAssign(ft.meta.leftOwner)) Seq(CtrlBodySplits.withIndent(Split(Newline2x(ft), 0), body, endFt)) else if (style.newlines.shouldForceBeforeMultilineAssign(ft.meta.leftOwner)) - CtrlBodySplits.slbOnly(body, spaceIndents) { x => - CtrlBodySplits.withIndent(Split(Newline2x(ft), x), body, endFt) - } + CtrlBodySplits.slbOnly(body, spaceIndents)(x => + CtrlBodySplits.withIndent(Split(Newline2x(ft), x), body, endFt), + ) else splits private def getSplitsDefEquals(body: Tree, endFt: FT)(implicit @@ -2876,7 +2878,7 @@ class Router(formatOps: FormatOps) { if (!style.align.arrowEnumeratorGenerator) Seq.empty else Seq(Indent(StateColumn, endFt, After)) getSplitsDefValEquals(body, endFt, spaceIndents) { - CtrlBodySplits.get(body, spaceIndents) { + CtrlBodySplits.get(body, spaceIndents)( if (spaceIndents.nonEmpty) Split(Space, 0).withIndents(spaceIndents) else { val noSlb = body match { @@ -2887,8 +2889,8 @@ class Router(formatOps: FormatOps) { if (noSlb) Split(Space, 0) .withOptimalToken(next(ft), killOnFail = false) else Split(Space, 0).withSingleLine(endFt) - } - }(cost => CtrlBodySplits.withIndent(Split(Newline2x(ft), cost), endFt)) + }, + )(cost => CtrlBodySplits.withIndent(Split(Newline2x(ft), cost), endFt)) } } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/State.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/State.scala index 94e9e68fb6..d1caaf4a00 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/State.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/State.scala @@ -71,22 +71,22 @@ final class State( val offset = column - indentation def getUnexpired(modExt: ModExt, indents: Seq[ActualIndent]) = { val extendedEnd = getRelativeToLhsLastLineEnd(modExt.isNL) - (modExt.getActualIndents(offset) ++ indents).flatMap { x => + (modExt.getActualIndents(offset) ++ indents).flatMap(x => if (x.notExpiredBy(tok)) Some(x) else extendedEnd - .map(y => x.copy(expire = y, expiresAt = ExpiresOn.After)) - } + .map(y => x.copy(expire = y, expiresAt = ExpiresOn.After)), + ) } val initialModExt = initialNextSplit.modExt val nextPushes = getUnexpired(initialModExt, pushes) val nextIndent = Indent.getIndent(nextPushes) - initialModExt.altOpt.flatMap { alt => + initialModExt.altOpt.flatMap(alt => if (tok.left.is[T.Comment]) None else if (nextIndent < alt.mod.length + column) None else if (initialModExt.noAltIndent) Some(alt) - else Some(alt.withIndents(initialModExt.indents)) - }.fold((initialNextSplit, nextIndent, nextPushes)) { alt => + else Some(alt.withIndents(initialModExt.indents)), + ).fold((initialNextSplit, nextIndent, nextPushes)) { alt => val altPushes = getUnexpired(alt, pushes) val altIndent = Indent.getIndent(altPushes) val split = initialNextSplit.withMod(alt) @@ -254,10 +254,10 @@ final class State( val owner = optionIfStartsWithLeft(ft.meta.rightOwner) .orElse(optionIfStartsWithLeft(ft.meta.leftOwner)) owner.map { x => - val y = x.parent.flatMap { p => + val y = x.parent.flatMap(p => if (!startsWithLeft(p)) None - else findTreeWithParentSimple(p, false)(startsWithLeft) - } + else findTreeWithParentSimple(p, false)(startsWithLeft), + ) (ft, y.getOrElse(x)) } } @@ -442,19 +442,17 @@ object State { def getColumns(ft: FT, indent: Int, column: Int)(implicit style: ScalafmtConfig, - ): (Int, Int) = getColumns(ft.right, ft.meta.right, column) { + ): (Int, Int) = getColumns(ft.right, ft.meta.right, column)( if (style.assumeStandardLibraryStripMargin) { // 3 for '|' + 2 spaces val adjusted = 3 + (if (style.align.stripMargin) column else indent) _ => adjusted - } else identity - } { - if (style.assumeStandardLibraryStripMargin) { - // 1 for '|' - val adjusted = 1 + indent - _ => adjusted - } else identity - } + } else identity, + )(if (style.assumeStandardLibraryStripMargin) { + // 1 for '|' + val adjusted = 1 + indent + _ => adjusted + } else identity) private def getColumnsFromMultiline( syntax: String, @@ -477,10 +475,9 @@ object State { firstNL: Int, adjustMargin: Int => Int, firstLength: Int, - ): (Int, Int) = pipeOpt - .fold(getColumnsFromMultiline(syntax, firstNL, firstLength))( - getColumnsWithStripMargin(_, syntax, firstNL, adjustMargin, firstLength), - ) + ): (Int, Int) = pipeOpt.fold( + getColumnsFromMultiline(syntax, firstNL, firstLength), + )(getColumnsWithStripMargin(_, syntax, firstNL, adjustMargin, firstLength)) private def getColumnsWithStripMargin( pipe: Char, diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/TokenRange.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/TokenRange.scala index feb731d4f9..f3109b0efc 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/TokenRange.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/TokenRange.scala @@ -27,10 +27,10 @@ class TokenRanges private (val ranges: Seq[TokenRange]) extends AnyVal { new TokenRanges(ranges.map(f)) def excludeCloseDelim(implicit ftoks: FormatTokens): TokenRanges = - new TokenRanges(ranges.flatMap { x => + new TokenRanges(ranges.flatMap(x => if (!x.lt.left.is[T.OpenDelim]) Some(x) - else TokenRange.opt(x.lt, ftoks.prev(x.rt)) - }) + else TokenRange.opt(x.lt, ftoks.prev(x.rt)), + )) def startOfFirstRange(): Option[T] = ranges.lastOption.map(_.lt.left) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/FormatTokensRewrite.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/FormatTokensRewrite.scala index a8d4150133..717f319b46 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/FormatTokensRewrite.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/FormatTokensRewrite.scala @@ -316,10 +316,12 @@ object FormatTokensRewrite { private[rewrite] def claimedRule(ftIdx: Int): Option[Replacement] = claimed .get(ftIdx).map(tokens.apply).filter(_ ne null) - private[rewrite] def claim(ftIdx: Int, repl: Replacement): Int = - justClaim(ftIdx) { - if (repl eq null) null - else (repl.how match { + private[rewrite] def claim(ftIdx: Int, repl: Replacement): Int = justClaim( + ftIdx, + )( + if (repl eq null) null + else ( + repl.how match { case rt: ReplacementType.RemoveAndResurrect => val rtidx = rt.ft.meta.idx def swapWith(oldidx: Int) = Some { @@ -331,8 +333,9 @@ object FormatTokensRewrite { case _ => None } case _ => None - }).getOrElse(repl) - } + } + ).getOrElse(repl), + ) @inline private[rewrite] def claim(repl: Replacement)(implicit ft: FT): Int = diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Imports.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Imports.scala index dc9a80dab8..4899f48602 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Imports.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Imports.scala @@ -372,10 +372,10 @@ object Imports extends RewriteFactory { case t: Importee.Rename => Some(t.name) case t: Importee.Unimport => Some(t.name) case _ => None - }).exists { x => + }).exists(x => // in scala3, `as` doesn't need braces - ctx.tokenTraverser.nextNonTrivialToken(x.tokens.last).is[T.RightArrow] - } + ctx.tokenTraverser.nextNonTrivialToken(x.tokens.last).is[T.RightArrow], + ) protected final def getCommentsAround(tree: Tree): (Seq[T], Option[T]) = { val tokens = tree.tokens @@ -482,12 +482,12 @@ object Imports extends RewriteFactory { else Seq.empty headImportComments ++ getCommentsBefore(x.owner.tokens.head) } - val tailComments = x.selectors.commentAfter.orElse { + val tailComments = x.selectors.commentAfter.orElse( if (newImporteeCount != x.owner.importees.length) None else if (p.importers.lastOption.contains(x.owner)) getCommentAfter(p.tokens.last) - else getCommentAfter(x.owner.tokens.last) - } + else getCommentAfter(x.owner.tokens.last), + ) (headComments ++ x.selectors.commentsBefore, tailComments) case _ => (Seq.empty, None) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/PreferCurlyFors.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/PreferCurlyFors.scala index a236e9bcc9..3246afed62 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/PreferCurlyFors.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/PreferCurlyFors.scala @@ -100,7 +100,7 @@ private class PreferCurlyFors(implicit val ftoks: FormatTokens) private def hasNoLeadingInfix(t: Term.EnumeratorsBlock)(implicit head: FT, - ): Boolean = findTokenWith(nextNonCommentAfter(head), next) { ft => + ): Boolean = findTokenWith(nextNonCommentAfter(head), next)(ft => ft.meta.rightOwner match { case ro: Name if (ro.parent match { case Some(p: Member.Infix) @@ -110,7 +110,7 @@ private class PreferCurlyFors(implicit val ftoks: FormatTokens) }) => Some(false) case `t` if ft.right.is[T.RightParen] => Some(true) // closing delimiter case _ => None - } - }.contains(true) + }, + ).contains(true) } 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 3c78eb1a66..28329e6ef3 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 @@ -144,13 +144,11 @@ class RedundantBraces(implicit val ftoks: FormatTokens) ft: FT, session: Session, style: ScalafmtConfig, - ): Option[Replacement] = Option { - ft.right match { - case _: T.LeftBrace => onLeftBrace - case _: T.LeftParen => onLeftParen - case _ => null - } - } + ): Option[Replacement] = Option(ft.right match { + case _: T.LeftBrace => onLeftBrace + case _: T.LeftParen => onLeftParen + case _ => null + }) override def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FT, @@ -188,20 +186,20 @@ class RedundantBraces(implicit val ftoks: FormatTokens) RedundantParens.breaksBeforeOp(x) => false case _ => useDelim eq T.LeftBrace } - def replaceWithNextBrace(claimToo: List[Int] = Nil) = ftoks - .nextNonComment(lp) match { - case FT(lt, _: T.LeftBrace, m) => - val claim = m.idx :: claimToo - if (lt eq rt) removeToken(claim = claim) - else replaceWithBrace(owner = Some(m.rightOwner), claim = claim) - case _ => replaceWithBrace(owner = Some(arg), claim = claimToo) - } + def replaceWithNextBrace(claimToo: List[Int] = Nil) = + ftoks.nextNonComment(lp) match { + case FT(lt, _: T.LeftBrace, m) => + val claim = m.idx :: claimToo + if (lt eq rt) removeToken(claim = claim) + else replaceWithBrace(owner = Some(m.rightOwner), claim = claim) + case _ => replaceWithBrace(owner = Some(arg), claim = claimToo) + } def rewriteFunction(f: Term.FunctionTerm)(shouldMoveBrace: => Boolean) = - getBlockToReplaceAsFuncBodyInSingleArgApply(ta, f).fold { + getBlockToReplaceAsFuncBodyInSingleArgApply(ta, f).fold( if (!shouldMoveBrace) null else if (f eq arg) replaceWithBrace() - else replaceWithNextBrace() - } { case (xb, xlb) => + else replaceWithNextBrace(), + ) { case (xb, xlb) => val shouldMoveNextBrace = !canRewriteStatWithParens(xb) || !okLineSpan(xb) || (useDelim eq T.LeftBrace) if (!shouldMoveNextBrace) null @@ -255,17 +253,17 @@ class RedundantBraces(implicit val ftoks: FormatTokens) getRightBraceBeforeRightParen(shouldBeRemoved = false).map { rb => ft.meta.rightOwner match { case ac: Term.ArgClause => ftoks.matchingOptLeft(rb).map(ftoks.prev) - .foreach { lb => - session.rule[RemoveScala3OptionalBraces].foreach { r => + .foreach(lb => + session.rule[RemoveScala3OptionalBraces].foreach(r => session.getClaimed(lb.meta.idx).foreach { case (leftIdx, _) => val repl = r.onLeftForArgClause(ac)(lb, left.style) if (null ne repl) { implicit val ft: FT = ftoks.prev(rb) repl.onRightAndClaim(hasFormatOff, leftIdx) } - } - } - } + }, + ), + ) case _ => } (left, removeToken) @@ -276,9 +274,9 @@ class RedundantBraces(implicit val ftoks: FormatTokens) val pftOpt = getRightBraceBeforeRightParen(shouldBeRemoved = true) def replaceWithBrace(rb: T, rtype: ReplacementType, startOff: Int = 0) = { val rbo = Some(left.ft.rightOwner) - left -> replaceToken("}", owner = rbo, rtype = rtype) { - new T.RightBrace(rb.input, rb.dialect, rb.start + startOff) - } + left -> replaceToken("}", owner = rbo, rtype = rtype)( + new T.RightBrace(rb.input, rb.dialect, rb.start + startOff), + ) } def replaceIfAfterRightBrace = pftOpt.map { pft => val rb = pft.left @@ -292,14 +290,14 @@ class RedundantBraces(implicit val ftoks: FormatTokens) .flatMap { r => val repl = r.onLeftForArgClause(ac)(left.ft, left.style) if (repl eq null) None else repl.onRight(hasFormatOff) - }.orElse { + }.orElse( if (left.claim.nonEmpty) None - else Some(replaceWithBrace(ft.right, ReplacementType.Replace)) - } + else Some(replaceWithBrace(ft.right, ReplacementType.Replace)), + ) case _ => None - }).getOrElse { - replaceIfAfterRightBrace.orNull // don't know how to Replace - } + }).getOrElse( + replaceIfAfterRightBrace.orNull, // don't know how to Replace + ) case _ => null } @@ -371,9 +369,9 @@ class RedundantBraces(implicit val ftoks: FormatTokens) .exists(_.isRemove) || !useParens && !okLineSpan(t) if (keepBrace) null else removeToken } else // arg clause is this block - if (useParens) replaceTokenBy("(", Some(p)) { x => - new T.LeftParen(x.input, x.dialect, x.start) - } + if (useParens) replaceTokenBy("(", Some(p))(x => + new T.LeftParen(x.input, x.dialect, x.start), + ) else null case Some(f: Term.FunctionTerm) if getBlockToReplaceAsFuncBodyIfInSingleArgApply(f).exists { @@ -400,9 +398,9 @@ class RedundantBraces(implicit val ftoks: FormatTokens) if t.stats.isEmpty && isDefnBodiesEnabled(noParams = false) => val prevIsEquals = ftoks.prevNonComment(ft).left.is[T.Equals] if (prevIsEquals) removeToken - else replaceTokenBy("=", t.parent) { x => - new T.Equals(x.input, x.dialect, x.start) - } + else replaceTokenBy("=", t.parent)(x => + new T.Equals(x.input, x.dialect, x.start), + ) case _ => null } } @@ -445,9 +443,9 @@ class RedundantBraces(implicit val ftoks: FormatTokens) }) || okComment(ft) && !elseAfterRightBraceThenpOnLeft) => (left, removeToken) case ReplacementType.Replace if left.ft.right.is[T.LeftParen] => - left -> replaceTokenBy(")", t.parent) { x => - new T.RightParen(x.input, x.dialect, x.start) - } + left -> replaceTokenBy(")", t.parent)(x => + new T.RightParen(x.input, x.dialect, x.start), + ) case _ => null } case _ => (left, removeToken) @@ -482,11 +480,11 @@ class RedundantBraces(implicit val ftoks: FormatTokens) }) } - private def getOpeningParen(t: Term.ArgClause): Option[T.LeftParen] = ftoks - .getHead(t).left match { - case lp: T.LeftParen => Some(lp) - case _ => None - } + private def getOpeningParen(t: Term.ArgClause): Option[T.LeftParen] = + ftoks.getHead(t).left match { + case lp: T.LeftParen => Some(lp) + case _ => None + } // single-arg apply of a lambda // a(b => { c; d }) change to a { b => c; d } @@ -702,9 +700,9 @@ class RedundantBraces(implicit val ftoks: FormatTokens) !stat.tokens.headOption.exists { case x: T.LeftParen => matching(x) match { case Some(y) if y.left ne stat.tokens.last => - session.rule[RedundantParens].exists { - _.onToken(ftoks(x, -1), session, style).exists(_.isRemove) - } + session.rule[RedundantParens].exists( + _.onToken(ftoks(x, -1), session, style).exists(_.isRemove), + ) case Some(_) if !style.dialect.allowTryWithAnyExpr => !stat.isAny[Term.Tuple, Lit.Unit] case _ => true @@ -773,22 +771,22 @@ class RedundantBraces(implicit val ftoks: FormatTokens) ftoks: FormatTokens, session: Session, ): Boolean = ftoks.nextNonCommentAfter(ft).right.is[T.KwElse] && { - val pft = ftoks.findToken(ft, ftoks.prev) { xft => + val pft = ftoks.findToken(ft, ftoks.prev)(xft => xft.left match { case _: T.Comment => false case _: T.RightBrace => !session.isRemovedOnLeft(xft, ok = true) case _ => true - } - } + }, + ) val rbOwner = ft.rightOwner - findTreeWithParent(pft.leftOwner) { p => + findTreeWithParent(pft.leftOwner)(p => if (p eq rbOwner) Some(false) else p.parent match { case None => Some(false) case Some(pp: Term.If) if pp.thenp eq p => Some(true) case _ => None - } - }.isDefined + }, + ).isDefined } } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Rewrite.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Rewrite.scala index 078795b2d7..21d4fad63c 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Rewrite.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Rewrite.scala @@ -43,10 +43,10 @@ case class RewriteCtx(style: ScalafmtConfig, input: Input, tree: Tree) { .map(x => patchBuilder.get(lookupKey(x)).fold(x.text)(_.newTok)).mkString def addPatchSet(ps: TokenPatch*): Unit = - if (!ps.exists(p => tokenTraverser.isExcluded(p.tok))) ps.foreach { p => + if (!ps.exists(p => tokenTraverser.isExcluded(p.tok))) ps.foreach(p => patchBuilder - .updateWith(lookupKey(p.tok))(v => Some(v.fold(p)(TokenPatch.merge(_, p)))) - } + .updateWith(lookupKey(p.tok))(v => Some(v.fold(p)(TokenPatch.merge(_, p)))), + ) def onlyWhitespaceBefore(index: Int): Boolean = tokenTraverser .findAtOrBefore(index - 1) { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/SortModifiers.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/SortModifiers.scala index 2dca536c07..3969da4f7f 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/SortModifiers.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/SortModifiers.scala @@ -38,10 +38,10 @@ class SortModifiers(implicit ctx: RewriteCtx) extends RewriteSession { case s: Stat.WithMods => sortMods(s.mods) case p: Term.Param => val start = p.pos.start - sortMods(p.mods.filterNot { m => + sortMods(p.mods.filterNot(m => m.isAny[Mod.ValParam, Mod.VarParam, Mod.Using, Mod.Erased] || - TreeOps.noExplicitImplicit(start, orElse = false)(m) - }) + TreeOps.noExplicitImplicit(start, orElse = false)(m), + )) case _ => } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/MarkdownParser.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/MarkdownParser.scala index 49051db8d0..63613116c3 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/MarkdownParser.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/MarkdownParser.scala @@ -23,14 +23,12 @@ private[scalafmt] object MarkdownParser { case _ => } - Success { - if (hadFencedParts) { - val out = new StringBuilder() - parts.foreach(_.renderToString(out)) - if (out.last != '\n') out.append('\n') - out.toString() - } else code - } + Success(if (hadFencedParts) { + val out = new StringBuilder() + parts.foreach(_.renderToString(out)) + if (out.last != '\n') out.append('\n') + out.toString() + } else code) } } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/PolicyOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/PolicyOps.scala index 4856592214..028e1c8518 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/PolicyOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/PolicyOps.scala @@ -254,11 +254,11 @@ object PolicyOps { val triggeredIndent = Indent.before(unindent, trigger) val triggerUnindent = Policy .onlyFor(lt, prefix = "UNIND{")(_.map(_.withIndent(triggeredIndent))) - val cancelUnindent = delayedBreakPolicy(Policy.End <= lt) { - Policy.onlyFor(lt, rank = 1, prefix = "UNIND}") { // use rank to apply after policy above - _.map(_.switch(trigger, false)) - } - } + val cancelUnindent = delayedBreakPolicy(Policy.End <= lt)( + Policy.onlyFor(lt, rank = 1, prefix = "UNIND}")( // use rank to apply after policy above + _.map(_.switch(trigger, false)), + ), + ) policy ==> triggerUnindent & cancelUnindent } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/StyleMap.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/StyleMap.scala index eb2f11a03b..61ca6a643c 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/StyleMap.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/StyleMap.scala @@ -55,10 +55,10 @@ class StyleMap(tokens: FormatTokens, val init: ScalafmtConfig) { opensLiteralArgumentList(ft)(curr) => forcedBinPack += ft.meta.leftOwner changeStyle(setBinPack(curr, callSite = BinPack.Site.Always)) - .foreach { x => + .foreach(x => tokens.matchingOptLeft(ft) - .foreach(y => disableBinPack.update(y.idx, x.binPack.callSite)) - } + .foreach(y => disableBinPack.update(y.idx, x.binPack.callSite)), + ) case _: T.RightParen => disableBinPack.remove(ft.idx) .foreach(x => changeStyle(setBinPack(curr, callSite = x))) case _ => diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TreeOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TreeOps.scala index 40610ca1e1..ee48bbb364 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TreeOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TreeOps.scala @@ -97,7 +97,7 @@ object TreeOps { )(key: V => K)(f: V => T): Map[K, V] = { val ret = Map.newBuilder[K, V] var stack = List.empty[(T, V)] - coll.foreach { elem => + coll.foreach(elem => f(elem) match { case open @ (_: OpenDelim | _: Interpolation.Start | _: Xml.Start | _: Xml.SpliceStart) => stack = (open, elem) :: stack @@ -109,8 +109,8 @@ object TreeOps { ret += key(elem) -> openElem stack = stack.tail case _ => - } - } + }, + ) if (stack.nonEmpty) throw new IllegalArgumentException( stack.map { case (x, _) => s"[${x.end}]$x" } .mkString("Orphan parens (", ", ", ")"), @@ -144,13 +144,13 @@ object TreeOps { */ def findTreeOrParent( tree: Tree, - )(pred: Tree => Option[Boolean]): Option[Tree] = findTreeEx(tree) { t => + )(pred: Tree => Option[Boolean]): Option[Tree] = findTreeEx(tree)(t => pred(t) match { case None => t.parent case Some(true) => Some(null) case Some(false) => None - } - } + }, + ) /** Returns first tree which matches the given predicate. The predicate * returns None to indicate failure; or the tree to recurse to; if the tree @@ -175,13 +175,13 @@ object TreeOps { */ def findTreeWithParent(tree: Tree)( pred: Tree => Option[Boolean], - ): Option[Tree] = findTreeWithParentEx(tree) { t => + ): Option[Tree] = findTreeWithParentEx(tree)(t => pred(t) match { case None => Some(t) case Some(true) => Some(null) case Some(false) => None - } - } + }, + ) /** Returns first ancestor whose parent matches the given predicate. The * predicate returns None to indicate failure; or the tree to recurse to; if @@ -345,8 +345,9 @@ object TreeOps { if (children.isEmpty) 0 else 1 + maxTreeDepth(children) } - def maxTreeDepth(trees: Seq[Tree]): Int = trees - .foldLeft(0) { case (res, t) => math.max(res, treeDepth(t)) } + def maxTreeDepth(trees: Seq[Tree]): Int = trees.foldLeft(0) { case (res, t) => + math.max(res, treeDepth(t)) + } def getSingleArgOnLeftBraceOnLeft(ft: FT)(implicit ftoks: FormatTokens, diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/ValidationOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/ValidationOps.scala index 7845ce1e65..1f9c7425b6 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/ValidationOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/ValidationOps.scala @@ -6,32 +6,32 @@ object ValidationOps { def checkNonNeg( ns: sourcecode.Text[Int]*, - )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach { n => + )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach(n => if (n.value < 0) errors += - s"${n.source} must be non-negative, was ${n.value}" - } + s"${n.source} must be non-negative, was ${n.value}", + ) def checkPositive( ns: sourcecode.Text[Int]*, - )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach { n => - if (n.value <= 0) errors += s"${n.source} must be positive, was ${n.value}" - } + )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach(n => + if (n.value <= 0) errors += s"${n.source} must be positive, was ${n.value}", + ) def checkNonNegOpt( ns: sourcecode.Text[Option[Int]]*, - )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach { n => - n.value.foreach { nv => - if (nv < 0) errors += s"${n.source} must be non-negative, was $nv" - } - } + )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach(n => + n.value.foreach(nv => + if (nv < 0) errors += s"${n.source} must be non-negative, was $nv", + ), + ) def checkPositiveOpt( ns: sourcecode.Text[Option[Int]]*, - )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach { n => - n.value.foreach { nv => - if (nv <= 0) errors += s"${n.source} must be positive, was $nv" - } - } + )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach(n => + n.value.foreach(nv => + if (nv <= 0) errors += s"${n.source} must be positive, was $nv", + ), + ) def addIf(what: sourcecode.Text[Boolean])(implicit errors: mutable.Buffer[String], diff --git a/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala b/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala index 253ec3b143..fbc1d10e02 100644 --- a/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala +++ b/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala @@ -42,9 +42,9 @@ object CoursierDependencyDownloader extends DependencyDownloaderFactory { val repositories = properties.repositories.map { x => val host = new URI(x).getHost val repo = MavenRepository.of(x) - properties.repositoryCredentials.find(_.host == host).fold(repo) { cred => - repo.withCredentials(Credentials.of(cred.username, cred.password)) - } + properties.repositoryCredentials.find(_.host == host).fold(repo)(cred => + repo.withCredentials(Credentials.of(cred.username, cred.password)), + ) } new CoursierDependencyDownloader(writer, repositories) } diff --git a/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala b/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala index 7d41987de4..b7c7e720c3 100644 --- a/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala +++ b/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala @@ -22,11 +22,11 @@ class ScalafmtReflectConfig private[dynamic] (val fmtReflect: ScalafmtReflect)( private val projectField = target.invoke("project") private val projectMatcherField = projectField.invoke("matcher") - private lazy val indentField = Try { + private lazy val indentField = Try( if (getVersion < ScalafmtVersion(3, 0, 0)) target .invoke("continuationIndent") - else target.invoke("indent") - } + else target.invoke("indent"), + ) lazy val projectIsGit = Try(projectField.invokeAs[Boolean]("git")) .getOrElse(false) diff --git a/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala b/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala index 18b70ca5bf..31e5630a6b 100644 --- a/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala +++ b/scalafmt-dynamic/jvm/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala @@ -13,15 +13,15 @@ class ReentrantCache[K, V] { @tailrec final def getOrAddToCache(key: K, shouldEvict: V => Boolean = _ => false)( get: () => V, - ): V = synchronized { // try to exit quickly from synchronized block + ): V = synchronized( // try to exit quickly from synchronized block cache.get(key) match { case Some(fut) => Right(fut) case None => val p = Promise[V]() cache += key -> p.future Left(p) - } - } match { + }, + ) match { case Right(fut) => // we set the timeout to 10 minutes because // we can't expect everybody to have the same internet connection speed. diff --git a/scalafmt-dynamic/jvm/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala b/scalafmt-dynamic/jvm/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala index cdb3d897b0..b23f007a23 100644 --- a/scalafmt-dynamic/jvm/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala +++ b/scalafmt-dynamic/jvm/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala @@ -116,9 +116,9 @@ class DynamicSuite extends FunSuite { def assertMissingVersion()(implicit loc: Location): Unit = { out.reset() missingVersions.clear() - intercept[ScalafmtDynamicError.ConfigMissingVersion] { - dynamic.format(config, filename, "object A") - } + intercept[ScalafmtDynamicError.ConfigMissingVersion]( + dynamic.format(config, filename, "object A"), + ) assertEquals(out.toString(), "") assert(missingVersions.nonEmpty) } @@ -172,7 +172,7 @@ class DynamicSuite extends FunSuite { def checkExhaustive(name: String)( config: String => String, - )(fn: (Format, String) => Unit): Unit = testedVersions.foreach { version => + )(fn: (Format, String) => Unit): Unit = testedVersions.foreach(version => test(s"$name [v=$version]") { val format = new Format(name, identity) val dialect = if (version < "3.0.0") null else "scala213" @@ -180,8 +180,8 @@ class DynamicSuite extends FunSuite { format.setVersion(version, dialect, config(version)) fn(format, version) } finally format.dynamic.clear() - } - } + }, + ) def checkVersion(version: String, dialect: String): Unit = check(s"v$version") { f => @@ -419,9 +419,9 @@ class DynamicSuite extends FunSuite { } } - checkExhaustive("continuation-indent-callSite-and-defnSite") { _ => - "continuationIndent { callSite = 5, defnSite = 3 }" - } { (f, _) => + checkExhaustive("continuation-indent-callSite-and-defnSite")(_ => + "continuationIndent { callSite = 5, defnSite = 3 }", + ) { (f, _) => val original = """|class A { | function1( | argument1, @@ -449,9 +449,9 @@ class DynamicSuite extends FunSuite { f.assertFormat(original, expected) } - checkExhaustive("hasRewriteRules-and-withoutRewriteRules") { _ => - "rewrite.rules = [RedundantBraces]" - } { (f, version) => + checkExhaustive("hasRewriteRules-and-withoutRewriteRules")(_ => + "rewrite.rules = [RedundantBraces]", + ) { (f, version) => f.assertFormat() val cache = f.dynamic.configLoader match { case x: ScalafmtConfigLoader.CachedProxy => x.cache @@ -475,17 +475,17 @@ class DynamicSuite extends FunSuite { val loader = f.dynamic.moduleLoader val module = loader.load(f.config, version, f.dynamic.properties).right.get - val thrown1 = intercept[ScalafmtDynamicError.ConfigParseError] { - module.parseConfig(f.config).get - } + val thrown1 = intercept[ScalafmtDynamicError.ConfigParseError]( + module.parseConfig(f.config).get, + ) assertNoDiff( thrown1.getMessage.take(60), "Invalid config: Default dialect is deprecated; use explicit:", ) - val thrown2 = intercept[ScalafmtDynamicError.ConfigParseError] { - module.parseConfigFromString(config).get - } + val thrown2 = intercept[ScalafmtDynamicError.ConfigParseError]( + module.parseConfigFromString(config).get, + ) assertNoDiff( thrown2.getMessage.take(60), "Invalid config: Default dialect is deprecated; use explicit:", @@ -564,17 +564,17 @@ class DynamicSuite extends FunSuite { assertDynamicConfig(fmt)(f) } - checkExhaustive("check project.git=true")(_ => "project.git = true") { (f, _) => - assertDynamicConfig(f)(x => assertEquals(x.projectIsGit, true)) - } + checkExhaustive("check project.git=true")(_ => "project.git = true")((f, _) => + assertDynamicConfig(f)(x => assertEquals(x.projectIsGit, true)), + ) - checkExhaustive("check project.git=false")(_ => "project.git = false") { - (f, _) => assertDynamicConfig(f)(x => assertEquals(x.projectIsGit, false)) - } + checkExhaustive("check project.git=false")(_ => "project.git = false")( + (f, _) => assertDynamicConfig(f)(x => assertEquals(x.projectIsGit, false)), + ) - checkExhaustive("check project.git missing")(_ => "") { (f, _) => - assertDynamicConfig(f)(x => assertEquals(x.projectIsGit, false)) - } + checkExhaustive("check project.git missing")(_ => "")((f, _) => + assertDynamicConfig(f)(x => assertEquals(x.projectIsGit, false)), + ) checkDynamicConfig( s"check indent.main", @@ -616,15 +616,15 @@ private object DynamicSuite { def nightly = BuildInfo.nightly def latest = { val latest = BuildInfo.previousStable - ScalafmtVersion.parse(latest).flatMap { ver => + ScalafmtVersion.parse(latest).flatMap(ver => if (ver.rc <= 0 && ver.snapshot.isEmpty) None else if (ver.patch > 0) Some(ScalafmtVersion(ver.major, ver.minor, ver.patch - 1).toString) else if (ver.minor > 0) Some(ScalafmtVersion(ver.major, ver.minor - 1, 0).toString) else if (ver.major > 0) Some(ScalafmtVersion(ver.major - 1, 0, 0).toString) - else None - }.getOrElse(latest) + else None, + ).getOrElse(latest) } def getDialectError(version: String, dialect: String, sbt: Boolean = false) = diff --git a/scalafmt-dynamic/native/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala b/scalafmt-dynamic/native/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala index 68f9062d26..a9d057225a 100644 --- a/scalafmt-dynamic/native/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala +++ b/scalafmt-dynamic/native/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala @@ -6,10 +6,10 @@ import munit.FunSuite class DynamicSuite extends FunSuite { - test("Scalafmt interface") { - interceptMessage[ScalafmtException] { - "Can't use different version for native CLI" - }(Scalafmt.create(this.getClass.getClassLoader)) - } + test("Scalafmt interface")( + interceptMessage[ScalafmtException]( + "Can't use different version for native CLI", + )(Scalafmt.create(this.getClass.getClassLoader)), + ) } diff --git a/scalafmt-dynamic/shared/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala b/scalafmt-dynamic/shared/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala index 60af63df00..6f888fb154 100644 --- a/scalafmt-dynamic/shared/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala +++ b/scalafmt-dynamic/shared/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala @@ -34,15 +34,13 @@ object ScalafmtVersion { """(\d{1,2})\.(\d{1,2})\.(\d{1,2})(?:-RC(\d{1,2}))?([-+].+)?""".r def parse(version: String): Option[ScalafmtVersion] = version match { - case versionRegex(major, minor, patch, rc, snapshot) => Try { - ScalafmtVersion( - positiveInt(major), - positiveInt(minor), - positiveInt(patch), - if (rc == null) 0 else positiveInt(rc), - if (snapshot == null) "" else snapshot, - ) - }.toOption + case versionRegex(major, minor, patch, rc, snapshot) => Try(ScalafmtVersion( + positiveInt(major), + positiveInt(minor), + positiveInt(patch), + if (rc == null) 0 else positiveInt(rc), + if (snapshot == null) "" else snapshot, + )).toOption case _ => None } diff --git a/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/BatchPathFinder.scala b/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/BatchPathFinder.scala index 7019f5e0c0..b01e3ec80b 100644 --- a/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/BatchPathFinder.scala +++ b/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/BatchPathFinder.scala @@ -19,13 +19,13 @@ trait BatchPathFinder { else { val files = Seq.newBuilder[AbsoluteFile] val dirs = Seq.newBuilder[AbsoluteFile] - paths.foreach { x => + paths.foreach(x => if (!x.isRegularFile) dirs += x // DESNOTE(2017-05-19, pjrt): A plain, fully passed file will (try to) be // formatted regardless of what it is or where it is. // NB: Unless respectProjectFilters is also specified. - else if (!filterFilesToo || matches(x.path)) files += x - } + else if (!filterFilesToo || matches(x.path)) files += x, + ) files.result() ++ findFilesExplicit(dirs.result()) } } diff --git a/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/FileOps.scala b/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/FileOps.scala index de4e61e0cc..e956660e4b 100644 --- a/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/FileOps.scala +++ b/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/FileOps.scala @@ -145,9 +145,9 @@ object FileOps { def getFileMatcher(paths: Seq[Path]): Path => Boolean = { val dirBuilder = Seq.newBuilder[Path] val fileBuilder = Set.newBuilder[Path] - paths.foreach { path => - if (isRegularFile(path)) fileBuilder += path else dirBuilder += path - } + paths.foreach(path => + if (isRegularFile(path)) fileBuilder += path else dirBuilder += path, + ) val dirs = dirBuilder.result() val files = fileBuilder.result() x => diff --git a/scalafmt-tests-community/intellij/src/test/scala/org/scalafmt/community/intellij/CommunityIntellijScalaSuite.scala b/scalafmt-tests-community/intellij/src/test/scala/org/scalafmt/community/intellij/CommunityIntellijScalaSuite.scala index a7eb20fa40..00a382b305 100644 --- a/scalafmt-tests-community/intellij/src/test/scala/org/scalafmt/community/intellij/CommunityIntellijScalaSuite.scala +++ b/scalafmt-tests-community/intellij/src/test/scala/org/scalafmt/community/intellij/CommunityIntellijScalaSuite.scala @@ -15,37 +15,39 @@ class CommunityIntellijScala_2024_2_Suite override protected def totalStatesVisited: Option[Int] = Some(59396273) - override protected def builds = Seq(getBuild( - "2024.2.28", - dialects.Scala213, - 3469, - excluded = "glob:**/{testdata,testData,resources}/**" :: Nil, - fileOverride = """|{ - | "glob:**/sbt/sbt-impl/workspace-entities/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/structure-view/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/repl/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/tasty-reader/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/package-search-client/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/integration/textAnalysis/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/integration/features-trainer/**" { - | runner.dialect = scala33 - | } - |} - |""" - .stripMargin, - )) + override protected def builds = Seq { + getBuild( + "2024.2.28", + dialects.Scala213, + 3469, + excluded = "glob:**/{testdata,testData,resources}/**" :: Nil, + fileOverride = """|{ + | "glob:**/sbt/sbt-impl/workspace-entities/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/structure-view/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/repl/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/tasty-reader/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/package-search-client/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/integration/textAnalysis/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/integration/features-trainer/**" { + | runner.dialect = scala33 + | } + |} + |""" + .stripMargin, + ) + } } @@ -54,39 +56,41 @@ class CommunityIntellijScala_2024_3_Suite override protected def totalStatesVisited: Option[Int] = Some(59611023) - override protected def builds = Seq(getBuild( - "2024.3.4", - dialects.Scala213, - 3475, - excluded = "glob:**/{testdata,testData,resources}/**" :: Nil, - fileOverride = """|{ - | "glob:**/sbt/sbt-impl/workspace-entities/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/structure-view/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/repl/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/tasty-reader/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/package-search-client/**" { - | runner.dialect = scala33 - | } - | "glob:**/scalac-patches/scalac3-patches/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/integration/textAnalysis/**" { - | runner.dialect = scala33 - | } - | "glob:**/scala/integration/features-trainer/**" { - | runner.dialect = scala33 - | } - |} - |""" - .stripMargin, - )) + override protected def builds = Seq { + getBuild( + "2024.3.4", + dialects.Scala213, + 3475, + excluded = "glob:**/{testdata,testData,resources}/**" :: Nil, + fileOverride = """|{ + | "glob:**/sbt/sbt-impl/workspace-entities/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/structure-view/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/repl/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/tasty-reader/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/package-search-client/**" { + | runner.dialect = scala33 + | } + | "glob:**/scalac-patches/scalac3-patches/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/integration/textAnalysis/**" { + | runner.dialect = scala33 + | } + | "glob:**/scala/integration/features-trainer/**" { + | runner.dialect = scala33 + | } + |} + |""" + .stripMargin, + ) + } } diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/FidelityTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/FidelityTest.scala index 8397c50d6d..a2c392d4f3 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/FidelityTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/FidelityTest.scala @@ -36,7 +36,7 @@ class FidelityTest extends FunSuite with FormatAssertions { }.map(x => TestCase(x, FileOps.readFile(x))) } - examples.foreach { example => + examples.foreach(example => test(example.filename) { val formatted = Scalafmt.formatCode( example.code, @@ -47,6 +47,6 @@ class FidelityTest extends FunSuite with FormatAssertions { scala.meta.parsers.Parse.parseSource, Scala213, ) - } - } + }, + ) } diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala index 0f75854944..29042f0186 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala @@ -7,7 +7,7 @@ import scala.meta._ import munit.FunSuite class ScalafmtRunnerTest extends FunSuite { - test("sbt dialect supports trailing commas") { + test("sbt dialect supports trailing commas")( ScalafmtRunner.sbt.getDialect( """| |lazy @@ -18,6 +18,6 @@ class ScalafmtRunnerTest extends FunSuite { | b, |) | """.stripMargin, - ).parse[Source].get - } + ).parse[Source].get, + ) } diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/CliTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/CliTest.scala index f1797a6d22..a0149f8299 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/CliTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/CliTest.scala @@ -255,7 +255,7 @@ trait CliTestBehavior { } test(s"excludefilters are respected: $label") { - val input = string2dir( + val input = string2dir { s"""|/foo.sbt |lazy val x = project | @@ -270,8 +270,8 @@ trait CliTestBehavior { | |/target/nested3/DoNotFormatMe.scala |object CIgnoreME { } - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""|/foo.sbt |lazy val x = project @@ -308,12 +308,12 @@ trait CliTestBehavior { "--config-str", s"""{version="$version",style=IntelliJ}""", ) - if (PlatformCompat.isNativeOnWindows()) intercept[UncheckedIOException] { - Cli.exceptionThrowingMainWithOptions(args, baseCliOptions) - } - else intercept[IOException] { - Cli.exceptionThrowingMainWithOptions(args, baseCliOptions) - } + if (PlatformCompat.isNativeOnWindows()) intercept[UncheckedIOException]( + Cli.exceptionThrowingMainWithOptions(args, baseCliOptions), + ) + else intercept[IOException]( + Cli.exceptionThrowingMainWithOptions(args, baseCliOptions), + ) } check("notfound") check("target/notfound") @@ -346,7 +346,7 @@ trait CliTestBehavior { } test(s"scalafmt (no arg) read config from git repo: $label") { - val input = string2dir( + val input = string2dir { s"""|/foo.scala |object FormatMe { | val x = 1 @@ -358,8 +358,8 @@ trait CliTestBehavior { |version = "$version" |maxColumn = 2 |project.excludeFilters = [target] - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""|/.scalafmt.conf @@ -425,7 +425,7 @@ trait CliTestBehavior { } test(s"if project.includeFilters isn't modified (and files aren't passed manually), it should ONLY accept scala and sbt files: $label") { - val root = string2dir( + val root = string2dir { s"""| |/scalafmt.conf |style = default @@ -437,8 +437,8 @@ trait CliTestBehavior { |/sbt.sbt |$sbtOriginal |/sbt.sbtfile - |$sbtOriginal""".stripMargin, - ) + |$sbtOriginal""".stripMargin + } val config = root / "scalafmt.conf" runWith(root, s"--config $config") @@ -576,12 +576,11 @@ trait CliTestBehavior { } test(s"command line argument error: $label") { - val exit = Console.withErr(Output.NoopStream.printStream) { - Cli.mainWithOptions( + val exit = Console + .withErr(Output.NoopStream.printStream)(Cli.mainWithOptions( Array("--foobar"), getMockOptions(AbsoluteFile.userDir), - ) - } + )) assertEquals(exit, ExitCode.CommandLineArgumentError, exit) } @@ -865,12 +864,10 @@ class CliTest extends AbstractCliTest with CliTestBehavior { test("can't specify both --config and --config-str") { val errStream = new ByteArrayOutputStream() - val obtained = Console.withErr(errStream) { - Cli.getConfig( - Array("--config", "foo", "--config-str", "bar"), - CliTest.defaultOptions, - ) - } + val obtained = Console.withErr(errStream)(Cli.getConfig( + Array("--config", "foo", "--config-str", "bar"), + CliTest.defaultOptions, + )) assertEquals( errStream.toString.trim, "Error: may not specify both --config and --config-str", @@ -879,7 +876,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { } test(s"scalafmt use includePaths") { - val input = string2dir( + val input = string2dir { s"""|/bar.scala |object FormatMe { | val x = 1 @@ -892,8 +889,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 2 |project { includePaths = ["glob:**/bar.scala"] } - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""|/.scalafmt.conf @@ -914,7 +911,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { } test(s"scalafmt use excludePaths") { - val input = string2dir( + val input = string2dir { s"""|/foo.scala |object FormatMe { | val x = 1 @@ -927,8 +924,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 2 |project { excludePaths = ["glob:**target**"] } - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""|/.scalafmt.conf @@ -949,7 +946,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { } test(s"scalafmt: includeFilters overrides default includePaths") { - val input = string2dir( + val input = string2dir { s"""|/bar.scala |object FormatMe { | val x = 1 @@ -962,8 +959,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 2 |project { includeFilters = ["bar"] } - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""|/.scalafmt.conf @@ -986,7 +983,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { test(s"scalafmt: includeFilters with explicit includePaths") { val defaultIncludePathsJson = ProjectFiles.defaultIncludePaths .mkString("[\"", "\", \"", "\"]") - val input = string2dir( + val input = string2dir { s"""|/bar.scala |object FormatMe { | val x = 1 @@ -1002,8 +999,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { | includePaths = $defaultIncludePathsJson | includeFilters = ["bar"] |} - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""|/.scalafmt.conf @@ -1027,7 +1024,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { } test(s"handles .md files when present in includePaths") { - val input = string2dir( + val input = string2dir { s"""|/foobar.md |# Hello |Example usage 1 with long spaced line @@ -1042,8 +1039,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 8 |project.includePaths."+" = ["glob:**.md"] - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""| |/.scalafmt.conf @@ -1201,7 +1198,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { } test(s"handles .md fences with uneven backticks") { - val input = string2dir( + val input = string2dir { s"""|/foobar.md |# Hello |Example usage 1 with long spaced line @@ -1216,8 +1213,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 8 |project.includePaths."+" = ["glob:**.md"] - |""".stripMargin, - ) + |""".stripMargin + } val expected = s"""| |/.scalafmt.conf @@ -1249,20 +1246,18 @@ class CliTest extends AbstractCliTest with CliTestBehavior { | 1 |}""" .stripMargin - Console.withOut(out) { - Console.withErr(err) { - val options = getConfig(Array("--stdin", "--test")) - val options2 = options.copy( - configStr = Some(s"{version = $stableVersion}"), - common = options.common.copy( - in = new ByteArrayInputStream(codeNoEol.getBytes), - out = Console.out, - err = Console.err, - ), - ) - run(options2, ExitCode.TestError) - } - } + Console.withOut(out)(Console.withErr(err) { + val options = getConfig(Array("--stdin", "--test")) + val options2 = options.copy( + configStr = Some(s"{version = $stableVersion}"), + common = options.common.copy( + in = new ByteArrayInputStream(codeNoEol.getBytes), + out = Console.out, + err = Console.err, + ), + ) + run(options2, ExitCode.TestError) + }) assertEquals(CliTest.stripCR(out.toString), "error: --test failed\n") assertEquals( CliTest.stripCR(err.toString), diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/FileTestOps.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/FileTestOps.scala index 37c41649a5..76157b7951 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/FileTestOps.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/cli/FileTestOps.scala @@ -38,10 +38,10 @@ object FileTestOps { def dir2string(file: AbsoluteFile): String = { val rootPath = file.path val prefix = rootPath.toString - FileOps.listFiles(rootPath).sortBy(_.toString).map { path => + FileOps.listFiles(rootPath).sortBy(_.toString).map(path => s"""|${path.toString.stripPrefix(prefix)} - |${FileOps.readFile(path)}""".stripMargin - }.mkString("\n").replace(File.separator, "/") // ensure original separators + |${FileOps.readFile(path)}""".stripMargin, + ).mkString("\n").replace(File.separator, "/") // ensure original separators } def getMockOptions(baseDir: AbsoluteFile): CliOptions = diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ConfigDialectOverrideTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ConfigDialectOverrideTest.scala index 5cdfc0dda5..3cb0b9f797 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ConfigDialectOverrideTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ConfigDialectOverrideTest.scala @@ -10,25 +10,25 @@ class ConfigDialectOverrideTest extends FunSuite { // toplevelSeparator is never actually used, // but as the only non-boolean Dialect value it makes for a good test - test("dialect override - non boolean setting") { + test("dialect override - non boolean setting")( ScalafmtConfig.fromHoconString( """| |runner.dialectOverride.toplevelSeparator = ">" |runner.dialect = scala213 |""".stripMargin, - ).get - } + ).get, + ) - test("throws on an incorrect type of setting") { - intercept[java.util.NoSuchElementException] { + test("throws on an incorrect type of setting")( + intercept[java.util.NoSuchElementException]( ScalafmtConfig.fromHoconString( """| |runner.dialectOverride.toplevelSeparator = true |runner.dialect = scala213 |""".stripMargin, - ).get - } - } + ).get, + ), + ) def testBooleanFlag( methodName: String, @@ -42,7 +42,7 @@ class ConfigDialectOverrideTest extends FunSuite { |runner.dialect = scala213 |""".stripMargin, ).get - Seq(true, false).foreach { flag => + Seq(true, false).foreach(flag => test(s"boolean flag: $methodName($flag)") { if (testDirectly) assertEquals(getter(generatedMap(methodName)(Scala213, flag)), flag) @@ -54,8 +54,8 @@ class ConfigDialectOverrideTest extends FunSuite { getter(makeBooleanConfig(methodName, flag).runner.getDialect), flag, ) - } - } + }, + ) } testBooleanFlag("allowFewerBraces", _.allowFewerBraces, testDirectly = false) diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala index 88048af716..5f4d31e7b7 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala @@ -19,7 +19,7 @@ class ScalafmtConfigTest extends FunSuite { } test("file overrides") { - val config = ScalafmtConfig.fromHoconString( + val config = ScalafmtConfig.fromHoconString { """ |newlines.source = fold |newlines.topLevelBodyIfMinStatements = [before,after] @@ -29,8 +29,8 @@ class ScalafmtConfigTest extends FunSuite { | newlines.topLevelBodyIfMinStatements = [] | } |} - | """.stripMargin, - ).get + | """.stripMargin + }.get val nlCfg1 = config.getConfigFor("/x/src/main/scala/foo.scala").get.newlines val nlCfg2 = config.getConfigFor("/x/src/test/scala/bar.scala").get.newlines assertEquals(nlCfg1.source, Newlines.fold) diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/sysops/FileOpsTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/sysops/FileOpsTest.scala index e8cacf2817..08108c0a9d 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/sysops/FileOpsTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/sysops/FileOpsTest.scala @@ -14,8 +14,8 @@ class FileOpsTest extends munit.FunSuite { private var path: Path = _ - override def beforeEach(context: BeforeEach): Unit = path = Files - .createTempDirectory("FileOpsTestDir") + override def beforeEach(context: BeforeEach): Unit = + path = Files.createTempDirectory("FileOpsTestDir") override def afterEach(context: AfterEach): Unit = try deleteTree(path) diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/CanRunTests.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/CanRunTests.scala index 6016c6bbba..82b96fee40 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/CanRunTests.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/CanRunTests.scala @@ -15,13 +15,13 @@ trait CanRunTests extends FunSuite with HasTests { if (ignore(t)) { // Not even ignore(t), save console space. } else if (t.skip) test(paddedName.ignore) {} - else test(paddedName) { + else test(paddedName)( try run(t) catch { case Error.WithCode(e: ParseException, code) => fail("test does not parse\n" + parseException2Message(e, code), e) - } - } + }, + ) } def runTestsDefault(): Unit = testsToRun.foreach(runTest(defaultRun)) diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/ErrorTest.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/ErrorTest.scala index de2e05c34e..9249053f84 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/ErrorTest.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/ErrorTest.scala @@ -7,12 +7,12 @@ import munit.FunSuite class ErrorTest extends FunSuite { private val nonSourceFile = Seq("class A {", "val x + 1", "println 1") - nonSourceFile.foreach { original => - test(s"errors are caught: $original") { + nonSourceFile.foreach(original => + test(s"errors are caught: $original")( Scalafmt.format(original, HasTests.unitTest40) match { case _: Formatted.Success => fail("expected failure, got success") case _ => - } - } - } + }, + ), + ) } diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/HasTests.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/HasTests.scala index f7aca586e7..0bc548acb8 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/HasTests.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/HasTests.scala @@ -70,13 +70,13 @@ trait HasTests extends FormatAssertions { val moduleSkip = isSkip(head) def loadStyle(cfg: String, base: ScalafmtConfig, ln: Int): ScalafmtConfig = - ScalafmtConfig.fromHoconString(cfg, base).getOrRecover { c => + ScalafmtConfig.fromHoconString(cfg, base).getOrRecover(c => throw new IllegalArgumentException( s"""|Failed to parse line=$ln filename $filename: |$cfg |$c""".stripMargin, - ) - } + ), + ) val style: ScalafmtConfig = loadStyle( stripPrefixOpt(head, onlyPrefix).getOrElse(head), { val base = spec2style(spec) @@ -103,12 +103,12 @@ trait HasTests extends FormatAssertions { val name = matcher.group(1) val extraConfig = Option(matcher.group(2)) val original = matcher.group(3) - val extra = Option(matcher.group(4)).flatMap { x => + val extra = Option(matcher.group(4)).flatMap(x => ConfParsed.fromString(x).conf match { case Configured.Ok(v) => Some(v) case _ => Some(Conf.Str(x)) - } - } + }, + ) val expected = matcher.group(5) val testStyle = extraConfig.fold(style)(loadStyle(_, style, linenum)) diff --git a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/Report.scala b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/Report.scala index d49be3361c..0dfdbb0d55 100644 --- a/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/Report.scala +++ b/scalafmt-tests/shared/src/test/scala/org/scalafmt/util/Report.scala @@ -65,43 +65,45 @@ object Report { def reportBody(xs: Text.Modifier*) = html(body(background := "#f9f9f9", xs)) - def compare(before: TestStats, after: TestStats): String = reportBody(div( - h1( - id := "title", - s"Compare ${after.gitInfo.branch} and" + s" ${before.gitInfo.branch}" + - s" (${before.shortCommit}...${after.shortCommit})", - ), - explanation, - after.intersectResults(before).sortBy { case (aft, bef) => - -Math.abs(aft.visitedStates - bef.visitedStates) - }.map { case (aft, bef) => - div( - h2(aft.test.fullName), - table( - tr(th(""), th("Before"), th("After"), th("Diff")), - tr( - td("Time (ms)"), - td(bef.timeMs), - td(aft.timeMs), - td(bef.timeMs - aft.timeMs), + def compare(before: TestStats, after: TestStats): String = reportBody { + div( + h1( + id := "title", + s"Compare ${after.gitInfo.branch} and" + s" ${before.gitInfo.branch}" + + s" (${before.shortCommit}...${after.shortCommit})", + ), + explanation, + after.intersectResults(before).sortBy { case (aft, bef) => + -Math.abs(aft.visitedStates - bef.visitedStates) + }.map { case (aft, bef) => + div( + h2(aft.test.fullName), + table( + tr(th(""), th("Before"), th("After"), th("Diff")), + tr( + td("Time (ms)"), + td(bef.timeMs), + td(aft.timeMs), + td(bef.timeMs - aft.timeMs), + ), + tr( + td("States"), + td(bef.visitedStates), + td(aft.visitedStates), + td(aft.visitedStates - bef.visitedStates), + ), ), - tr( - td("States"), - td(bef.visitedStates), - td(aft.visitedStates), - td(aft.visitedStates - bef.visitedStates), + pre( + fontFamily := "monospace", + background := "#fff", + fontSize := "16px", + width := testWidth(aft), + code(heatmapBar(aft.test.style), raw(mkHtml(mergeResults(aft, bef)))), ), - ), - pre( - fontFamily := "monospace", - background := "#fff", - fontSize := "16px", - width := testWidth(aft), - code(heatmapBar(aft.test.style), raw(mkHtml(mergeResults(aft, bef)))), - ), - ) - }, - )).render + ) + }, + ) + }.render def mergeResults(after: Result, before: Result): Seq[FormatOutput] = after .tokens.zip(before.tokens).map { case (aft, bef) =>