diff --git a/.scalafmt.conf b/.scalafmt.conf index 4cc94aed41..3ab712ac73 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -28,6 +28,7 @@ rewrite { stringInterpolation = true } sortModifiers.preset = styleGuide + trailingCommas.style = "always" } # Disabled in default since this operation is potentially # dangerous if you define your own stripMargin with different diff --git a/build.sbt b/build.sbt index b1ad336621..97872ce48c 100644 --- a/build.sbt +++ b/build.sbt @@ -24,7 +24,7 @@ inThisBuild(List( "olafurpg", "Ólafur Páll Geirsson", "olafurpg@gmail.com", - url("https://geirsson.com") + url("https://geirsson.com"), )), scalaVersion := scala213, crossScalaVersions := List(scala213, scala212), @@ -32,7 +32,7 @@ inThisBuild(List( resolvers ++= Resolver.sonatypeOssRepos("snapshots"), libraryDependencies ++= List(munit.value % Test, scalacheck % Test, scalametaTestkit % Test), - testFrameworks += new TestFramework("munit.Framework") + testFrameworks += new TestFramework("munit.Framework"), )) name := "scalafmtRoot" @@ -60,9 +60,9 @@ lazy val dynamic = project.in(file("scalafmt-dynamic")).settings( "io.get-coursier" % "interface" % "0.0.17", "com.typesafe" % "config" % "1.4.3", munit.value % Test, - scalametaTestkit % Test + scalametaTestkit % Test, ), - scalacOptions ++= scalacJvmOptions.value + scalacOptions ++= scalacJvmOptions.value, ).dependsOn(interfaces).dependsOn(core.jvm % "test") .enablePlugins(BuildInfoPlugin) @@ -79,7 +79,7 @@ lazy val interfaces = project.in(file("scalafmt-interfaces")).settings( props.put("version", version.value) IO.write(props, "scalafmt properties", out) List(out) - } + }, ) lazy val sysops = crossProject(JVMPlatform).withoutSuffixFor(JVMPlatform) @@ -95,7 +95,7 @@ lazy val sysops = crossProject(JVMPlatform).withoutSuffixFor(JVMPlatform) Seq("org.scala-lang.modules" %% "scala-parallel-collections" % "1.0.4") case _ => Seq() } - } + }, ) lazy val config = crossProject(JVMPlatform).withoutSuffixFor(JVMPlatform) @@ -103,7 +103,7 @@ lazy val config = crossProject(JVMPlatform).withoutSuffixFor(JVMPlatform) moduleName := "scalafmt-config", description := "Scalafmt config parsing", scalacOptions ++= scalacJvmOptions.value, - libraryDependencies ++= Seq(metaconfig.value) + libraryDependencies ++= Seq(metaconfig.value), ).jvmSettings(libraryDependencies ++= Seq(metaconfigTypesafe.value)) // .jsSettings( // libraryDependencies ++= Seq( @@ -120,16 +120,16 @@ lazy val core = crossProject(JVMPlatform).in(file("scalafmt-core")).settings( "org.scalameta" %% "mdoc-parser" % mdocV, // scala-reflect is an undeclared dependency of fansi, see #1252. // Scalafmt itself does not require scala-reflect. - "org.scala-lang" % "scala-reflect" % scalaVersion.value + "org.scala-lang" % "scala-reflect" % scalaVersion.value, ), libraryDependencies ++= { CrossVersion.partialVersion(scalaVersion.value) match { case Some((2, 13)) => Seq() case _ => Seq(compilerPlugin( - "org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full + "org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full, )) } - } + }, ) // .jsSettings( // libraryDependencies ++= List( @@ -171,7 +171,7 @@ lazy val cli = project.in(file("scalafmt-cli")).settings( libraryDependencies ++= Seq( "com.googlecode.java-diff-utils" % "diffutils" % "1.3.0", "com.martiansoftware" % "nailgun-server" % "0.9.1", - "com.github.scopt" %% "scopt" % "4.1.0" + "com.github.scopt" %% "scopt" % "4.1.0", ), scalacOptions ++= scalacJvmOptions.value, Compile / mainClass := Some("org.scalafmt.cli.Cli"), @@ -184,7 +184,7 @@ lazy val cli = project.in(file("scalafmt-cli")).settings( nativeImageOptions ++= { val isStatic = sys.env.get("NATIVE_IMAGE_STATIC").exists(_.toBoolean) if (isStatic) Seq("--static") else Nil - } + }, ).dependsOn(coreJVM, dynamic).enablePlugins(NativeImagePlugin) lazy val tests = project.in(file("scalafmt-tests")).settings( @@ -193,13 +193,13 @@ lazy val tests = project.in(file("scalafmt-tests")).settings( // Test dependencies "com.lihaoyi" %% "scalatags" % "0.12.0", scalametaTestkit, - munit.value + munit.value, ), scalacOptions ++= scalacJvmOptions.value, javaOptions += "-Dfile.encoding=UTF8", buildInfoPackage := "org.scalafmt.tests", buildInfoKeys := - Seq[BuildInfoKey]("resourceDirectory" -> (Test / resourceDirectory).value) + Seq[BuildInfoKey]("resourceDirectory" -> (Test / resourceDirectory).value), ).enablePlugins(BuildInfoPlugin).dependsOn(coreJVM, dynamic, cli) lazy val benchmarks = project.in(file("scalafmt-benchmarks")).settings( @@ -220,14 +220,14 @@ lazy val benchmarks = project.in(file("scalafmt-benchmarks")).settings( "-Xss8M", "-Xms512M", "-Xmx2G", - "-server" - ) + "-server", + ), ).dependsOn(coreJVM).enablePlugins(JmhPlugin) lazy val docs = project.in(file("scalafmt-docs")).settings( crossScalaVersions := List(scala212), publish / skip := true, - mdoc := (Compile / run).evaluated + mdoc := (Compile / run).evaluated, ).dependsOn(cli, dynamic).enablePlugins(DocusaurusPlugin) val V = "\\d+\\.\\d+\\.\\d+" @@ -252,8 +252,8 @@ lazy val buildInfoSettings: Seq[Def.Setting[_]] = Seq( "commit" -> sys.process.Process("git rev-parse HEAD").lineStream_!.head, "timestamp" -> System.currentTimeMillis().toString, scalaVersion, - sbtVersion + sbtVersion, ), buildInfoPackage := "org.scalafmt", - buildInfoObject := "Versions" + buildInfoObject := "Versions", ) diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 47921d0363..7a142271de 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -16,7 +16,7 @@ object Dependencies { val scalapb = Def.setting { ExclusionRule( organization = "com.thesamet.scalapb", - name = s"scalapb-runtime_${scalaBinaryVersion.value}" + name = s"scalapb-runtime_${scalaBinaryVersion.value}", ) } diff --git a/project/Mima.scala b/project/Mima.scala index d9f9403f77..86ccd7c2f4 100644 --- a/project/Mima.scala +++ b/project/Mima.scala @@ -10,6 +10,6 @@ object Mima { ProblemFilters.exclude[Problem]("org.scalafmt.config.*"), ProblemFilters.exclude[Problem]("org.scalafmt.internal.*"), ProblemFilters.exclude[Problem]("org.scalafmt.rewrite.*"), - ProblemFilters.exclude[Problem]("org.scalafmt.util.*") + ProblemFilters.exclude[Problem]("org.scalafmt.util.*"), ) } diff --git a/project/plugins.sbt b/project/plugins.sbt index 2a079b0d97..546ee52105 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,7 +1,7 @@ resolvers ++= Seq( Classpaths.sbtPluginReleases, Resolver.sonatypeRepo("releases"), - Resolver.bintrayIvyRepo("jetbrains", "sbt-plugins") + Resolver.bintrayIvyRepo("jetbrains", "sbt-plugins"), ) addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.5.2") diff --git a/readme/src/main/scala/org/scalafmt/readme/Adopters.scala b/readme/src/main/scala/org/scalafmt/readme/Adopters.scala index 09bd56f599..141badcacb 100644 --- a/readme/src/main/scala/org/scalafmt/readme/Adopters.scala +++ b/readme/src/main/scala/org/scalafmt/readme/Adopters.scala @@ -14,54 +14,54 @@ object Adopters { Adopter( "sbt", "https://github.com/sbt/sbt", - Some("The interactive build tool for Scala") + Some("The interactive build tool for Scala"), ), Adopter( "scala-native", "https://github.com/scala-native/scala-native", - Some("Your favourite language gets closer to bare metal.") + Some("Your favourite language gets closer to bare metal."), ), Adopter("HERE", "http://here.com", None), Adopter("Letgo", "http://letgo.com", None), Adopter( "Seventh Sense", "http://7thsense.io", - Some("Predictive analytics for sales and marketing") + Some("Predictive analytics for sales and marketing"), ), Adopter( "Teralytics", "http://teralytics.net", - Some("We transform raw, human activity data into valuable insights.") + Some("We transform raw, human activity data into valuable insights."), ), Adopter( "Venatus Media", "https://venatusmedia.com", - Some("We represent some of the largest entertainment publishers and monetize billions of ads.") + Some("We represent some of the largest entertainment publishers and monetize billions of ads."), ), Adopter( "http4s", "http://http4s.org", - Some("A minimal, idiomatic Scala interface for HTTP") + Some("A minimal, idiomatic Scala interface for HTTP"), ), Adopter( "Mendix", "https://mendix.com", - Some("The fastest and easiest platform to create and continuously improve mobile and web apps at scale.") + Some("The fastest and easiest platform to create and continuously improve mobile and web apps at scale."), ), Adopter( "Foursquare", "https://enterprise.foursquare.com", - Some("We use location intelligence to build meaningful consumer experiences and business solutions.") + Some("We use location intelligence to build meaningful consumer experiences and business solutions."), ), Adopter( "Codacy", "https://codacy.com", - Some("Codacy is an Automated Code Review Tool that monitors your technical debt, helps you improve your code quality, teaches best practices to your developers, and helps you save time in Code Reviews.") + Some("Codacy is an Automated Code Review Tool that monitors your technical debt, helps you improve your code quality, teaches best practices to your developers, and helps you save time in Code Reviews."), ), Adopter( "ZyseMe", "https://www.zyse.me/", - Some("We use ML to predict body measurements and automate pattern creation to integrate with production, allowing companies to produce and/or sell made-to-measure garments at scale.") - ) + Some("We use ML to predict body measurements and automate pattern creation to integrate with production, allowing companies to produce and/or sell made-to-measure garments at scale."), + ), ) } diff --git a/readme/src/main/scala/org/scalafmt/readme/Readme.scala b/readme/src/main/scala/org/scalafmt/readme/Readme.scala index 524a303545..ef356e4438 100644 --- a/readme/src/main/scala/org/scalafmt/readme/Readme.scala +++ b/readme/src/main/scala/org/scalafmt/readme/Readme.scala @@ -27,8 +27,8 @@ object Readme { src := "https://camo.githubusercontent.com/da2edb525cde1455a622c58c0effc3a90b9a181c/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667", alt := "Join the chat at https://gitter.im/scalameta/scalameta", - maxWidth := "100%;" - ) + maxWidth := "100%;", + ), ) val eval = new Eval() @@ -83,7 +83,7 @@ object Readme { def user(name: String) = a(href := s"$github/$name", s"@$name") def users(names: String*) = span( - names.dropRight(1).map(x => span(user(x), ", ")) :+ user(names.last): _* + names.dropRight(1).map(x => span(user(x), ", ")) :+ user(names.last): _*, ) def pr(id: Int) = a(href := repo + s"/pull/$id", s"#$id") @@ -108,7 +108,7 @@ object Readme { def changedConfig(style: ScalafmtConfig): String = { val diff = Conf.patch( ConfEncoder[ScalafmtConfig].write(ScalafmtConfig.default), - ConfEncoder[ScalafmtConfig].write(style) + ConfEncoder[ScalafmtConfig].write(style), ) Conf.printHocon(diff) } @@ -117,14 +117,14 @@ object Readme { def configurationBlock( style: ScalafmtConfig, - collapsed: Boolean = false + collapsed: Boolean = false, ): TypedTag[String] = div( span( "Show/hide configuration used for this example", - `class` := "scalafmt-configuration-toggle" + `class` := "scalafmt-configuration-toggle", ), pre(changedConfig(style)), - `class` := "scalafmt-configuration" + (if (collapsed) " collapsed" else "") + `class` := "scalafmt-configuration" + (if (collapsed) " collapsed" else ""), ) def fullWidthDemo(style: ScalafmtConfig)(code: String): TypedTag[String] = { @@ -132,9 +132,9 @@ object Readme { div( rows(List( div(hl.scala(code), `class` := "before"), - div(hl.scala(formatted), `class` := "after") + div(hl.scala(formatted), `class` := "after"), )), - configurationBlock(style) + configurationBlock(style), ) } @@ -151,8 +151,8 @@ object Readme { val formatted = Scalafmt.format( code, ScalafmtConfig.default40.copy(align = - ScalafmtConfig.default40.align.copy(tokens = AlignToken.default) - ) + ScalafmtConfig.default40.align.copy(tokens = AlignToken.default), + ), ).get hl.scala(formatted) } @@ -164,30 +164,30 @@ object Readme { .copy(rewrite = ScalafmtConfig.default.rewrite.copy(rules = Seq(AvoidInfix))) val rewriteImportSelectors = ScalafmtConfig.default.copy(rewrite = - ScalafmtConfig.default.rewrite.copy(rules = Seq(ExpandImportSelectors)) + ScalafmtConfig.default.rewrite.copy(rules = Seq(ExpandImportSelectors)), ) val rewriteBraces = ScalafmtConfig.default.copy(rewrite = ScalafmtConfig.default.rewrite.copy( redundantBraces = ScalafmtConfig.default.rewrite.redundantBraces .copy(stringInterpolation = true), - rules = Seq(RedundantBraces) - ) + rules = Seq(RedundantBraces), + ), ) val rewriteParens = ScalafmtConfig.default.copy(rewrite = - ScalafmtConfig.default.rewrite.copy(rules = Seq(RedundantParens)) + ScalafmtConfig.default.rewrite.copy(rules = Seq(RedundantParens)), ) val rewriteImports = ScalafmtConfig.default .copy(rewrite = ScalafmtConfig.default.rewrite.copy(rules = Seq(SortImports))) val rewriteAsciiImports = ScalafmtConfig.default.copy(rewrite = - ScalafmtConfig.default.rewrite.copy(rules = Seq(AsciiSortImports)) + ScalafmtConfig.default.rewrite.copy(rules = Seq(AsciiSortImports)), ) val rewriteSortModifiers = ScalafmtConfig.default120.copy(rewrite = - ScalafmtConfig.default.rewrite.copy(rules = Seq(SortModifiers)) + ScalafmtConfig.default.rewrite.copy(rules = Seq(SortModifiers)), ) /** This looks way too hacky. But can't seem to find a typeclass that ought to @@ -206,30 +206,30 @@ object Readme { .map(_.productPrefix).mkString("[\"", "\", \"", "\"]") val rewritePreferCurlyFors = ScalafmtConfig.default.copy(rewrite = - ScalafmtConfig.default.rewrite.copy(rules = Seq(PreferCurlyFors)) + ScalafmtConfig.default.rewrite.copy(rules = Seq(PreferCurlyFors)), ) val verticalAlign = ScalafmtConfig.default.copy( maxColumn = 60, - verticalMultiline = VerticalMultiline(atDefnSite = true) + verticalMultiline = VerticalMultiline(atDefnSite = true), ) val verticalMultilineDefaultConfigStr = Conf.printHocon(Conf.Obj( "verticalMultiline" -> ConfEncoder[VerticalMultiline] - .write(ScalafmtConfig.default.verticalMultiline) + .write(ScalafmtConfig.default.verticalMultiline), )) val verticalAlignImplicitBefore = ScalafmtConfig.default.copy( maxColumn = 60, verticalMultiline = - VerticalMultiline(atDefnSite = true, newlineBeforeImplicitKW = true) + VerticalMultiline(atDefnSite = true, newlineBeforeImplicitKW = true), ) val verticalAlignImplicitAfter = ScalafmtConfig.default.copy( maxColumn = 60, verticalMultiline = - VerticalMultiline(atDefnSite = true, newlineAfterImplicitKW = true) + VerticalMultiline(atDefnSite = true, newlineAfterImplicitKW = true), ) val multilineNewlineAfterParen = ScalafmtConfig.default.copy( @@ -237,8 +237,8 @@ object Readme { verticalMultiline = VerticalMultiline( atDefnSite = true, arityThreshold = 2, - newlineAfterOpenParen = true - ) + newlineAfterOpenParen = true, + ), ) val multilineDanglingParens = ScalafmtConfig.default.copy( @@ -246,17 +246,17 @@ object Readme { verticalMultiline = VerticalMultiline( atDefnSite = true, arityThreshold = 2, - excludeDanglingParens = Nil - ) + excludeDanglingParens = Nil, + ), ) val newlineAlwaysBeforeTopLevelStatements = ScalafmtConfig.default .copy(newlines = - ScalafmtConfig.default.newlines.copy(alwaysBeforeTopLevelStatements = true) + ScalafmtConfig.default.newlines.copy(alwaysBeforeTopLevelStatements = true), ) val arityThreshold = ScalafmtConfig.default.copy(verticalMultiline = - VerticalMultiline(atDefnSite = true, arityThreshold = 2) + VerticalMultiline(atDefnSite = true, arityThreshold = 2), ) def fmt(style: ScalafmtConfig)(code: String): TypedTag[String] = diff --git a/scalafmt-benchmarks/src/main/scala-2.12/benchmarks/MacroBenchmark.scala b/scalafmt-benchmarks/src/main/scala-2.12/benchmarks/MacroBenchmark.scala index e4597444ee..913cf96791 100644 --- a/scalafmt-benchmarks/src/main/scala-2.12/benchmarks/MacroBenchmark.scala +++ b/scalafmt-benchmarks/src/main/scala-2.12/benchmarks/MacroBenchmark.scala @@ -30,7 +30,7 @@ abstract class MacroBenchmark(parallel: Boolean, maxFiles: Int) def setup(): Unit = files = { val x = Corpus.files(Corpus.fastparse.copy( // TODO(olafur) remove once testkit 1.7 is out - url = Corpus.fastparse.url.replace("olafurpg", "scalameta") + url = Corpus.fastparse.url.replace("olafurpg", "scalameta"), )).filter(f => f.projectUrl.contains("scala-js")).take(maxFiles).map(_.read) .toBuffer if (parallel) x.par else x diff --git a/scalafmt-benchmarks/src/main/scala/org/scalafmt/benchmarks/FormatBenchmark.scala b/scalafmt-benchmarks/src/main/scala/org/scalafmt/benchmarks/FormatBenchmark.scala index 7cef69a66e..878a752c01 100644 --- a/scalafmt-benchmarks/src/main/scala/org/scalafmt/benchmarks/FormatBenchmark.scala +++ b/scalafmt-benchmarks/src/main/scala/org/scalafmt/benchmarks/FormatBenchmark.scala @@ -8,6 +8,6 @@ trait FormatBenchmark { def formatRewrite(code: String): String = Scalafmt.formatCode( code, baseStyle = ScalafmtConfig.default - .copy(rewrite = RewriteSettings(rules = Seq(SortImports, RedundantBraces))) + .copy(rewrite = RewriteSettings(rules = Seq(SortImports, RedundantBraces))), ).get } diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/Cli.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/Cli.scala index e595aa1b78..3590a6d274 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/Cli.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/Cli.scala @@ -13,11 +13,11 @@ import scala.util.control.NoStackTrace object Cli { def nailMain(nGContext: NGContext): Unit = { val workingDirectory = AbsoluteFile.fromPathIfAbsolute( - nGContext.getWorkingDirectory + nGContext.getWorkingDirectory, ).getOrElse { throw new IllegalStateException( s"Expected absolute path, " + - s"obtained nGContext.getWorkingDirectory = ${nGContext.getWorkingDirectory}" + s"obtained nGContext.getWorkingDirectory = ${nGContext.getWorkingDirectory}", ) } val exit = mainWithOptions( @@ -27,9 +27,9 @@ object Cli { cwd = Some(workingDirectory), out = nGContext.out, in = nGContext.in, - err = nGContext.err - ) - ) + err = nGContext.err, + ), + ), ) nGContext.exit(exit.code) } @@ -47,7 +47,7 @@ object Cli { def exceptionThrowingMainWithOptions( args: Array[String], - options: CliOptions + options: CliOptions, ): Unit = { val exit = mainWithOptions(args, options) throwIfError(exit) @@ -99,7 +99,7 @@ object Cli { |Consider creating '${options.getProposedConfigFile}' |with the following (other parameters may also be required): |${getProposedConfigVersion(options)} - |""".stripMargin + |""".stripMargin, ) } { // Run format using @@ -116,7 +116,7 @@ object Cli { s"""|error: missing Scalafmt version. |Consider adding the following to $where: |${getProposedConfigVersion(options)} - |""".stripMargin + |""".stripMargin, ) } { case Left(error) => Left(s"error: invalid configuration: $error") @@ -136,7 +136,7 @@ object Cli { | |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]") @@ -146,7 +146,7 @@ object Cli { private[cli] def runWithRunner( options: CliOptions, - runner: ScalafmtRunner + runner: ScalafmtRunner, ): ExitCode = { val termDisplayMessage = if (options.writeMode == WriteMode.Test) diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliArgParser.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliArgParser.scala index e9c039ca30..a196f296f2 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliArgParser.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliArgParser.scala @@ -33,7 +33,7 @@ object CliArgParser { override def showUsageOnError: Option[Boolean] = Some(false) private def printAndExit( - includeUsage: Boolean + includeUsage: Boolean, )(ignore: Unit, c: CliOptions): CliOptions = { if (includeUsage) displayToOut(usage) else displayToOut(header) sys.exit @@ -50,12 +50,12 @@ object CliArgParser { .text("print version ") arg[Path]("...").optional().unbounded().action((file, c) => - c.addFile(file) + c.addFile(file), ).text( """|file, or directory (in which all *.scala files are to be formatted); |if starts with '@', refers to path listing files to be formatted |(with "@-" referring to standard input as a special case)""" - .stripMargin + .stripMargin, ) opt[Seq[Path]]('f', "files").action((files, c) => c.withFiles(files)) @@ -76,7 +76,7 @@ object CliArgParser { .text("file or directory, when missing all *.scala files are formatted.") opt[Unit]("respect-project-filters") .action((_, c) => c.copy(respectProjectFilters = true)).text( - "use project filters even when specific files to format are provided" + "use project filters even when specific files to format are provided", ) opt[Path]('c', "config").action((file, c) => c.copy(config = Some(file))) .text("a file path to .scalafmt.conf.") @@ -92,26 +92,26 @@ object CliArgParser { opt[Unit]("reportError").action((_, c) => c.copy(error = true)) .text("exit with status 1 if any mis-formatted code found.") opt[Unit]("test").action((_, c) => - writeMode(c, WriteMode.Test).copy(error = true) + writeMode(c, WriteMode.Test).copy(error = true), ).text("test for mis-formatted code only, exits with status 1 on failure.") opt[Unit]("check").action((_, c) => - writeMode(c, WriteMode.Test).copy(error = true, check = true) + writeMode(c, WriteMode.Test).copy(error = true, check = true), ).text("test for mis-formatted code only, exits with status 1 on first failure.") opt[FileFetchMode]("mode").action((m, c) => c.copy(mode = Option(m))).text( s"""|Sets the files to be formatted fetching mode. |Options: |${FileFetchMode.help} - |""".stripMargin + |""".stripMargin, ) opt[Unit]("diff") .action((_, c) => c.copy(mode = Option(DiffFiles("master")))).text( s"""|Format files listed in `git diff` against master. - |Deprecated: use --mode diff instead""".stripMargin + |Deprecated: use --mode diff instead""".stripMargin, ) opt[String]("diff-branch") .action((branch, c) => c.copy(mode = Option(DiffFiles(branch)))).text( s"""|Format files listed in `git diff` against given git ref. - |Deprecated: use --mode diff-ref= instead""".stripMargin + |Deprecated: use --mode diff-ref= instead""".stripMargin, ) opt[Unit]("build-info").action { (_, _) => println(buildInfo); sys.exit } .text("prints build information") @@ -133,7 +133,7 @@ object CliArgParser { s"""|Examples: |$usageExamples |Please file bugs to https://github.com/scalameta/scalafmt/issues - |""".stripMargin + |""".stripMargin, ) checkConfig { c => diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliOptions.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliOptions.scala index 7fb932328f..65afed0c18 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliOptions.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/CliOptions.scala @@ -39,18 +39,18 @@ object CliOptions { out = guardPrintStream(parsed.quiet && !parsed.stdIn)(parsed.common.out), info = guardPrintStream( parsed.stdIn || parsed.writeMode == WriteMode.Stdout || - parsed.quiet || parsed.writeMode == WriteMode.List + parsed.quiet || parsed.writeMode == WriteMode.List, )(auxOut), debug = guardPrintStream(parsed.quiet)( - if (parsed.debug) auxOut else parsed.common.debug + if (parsed.debug) auxOut else parsed.common.debug, ), - err = guardPrintStream(parsed.quiet)(parsed.common.err) - ) + err = guardPrintStream(parsed.quiet)(parsed.common.err), + ), ) } private def guardPrintStream(p: => Boolean)( - candidate: PrintStream + candidate: PrintStream, ): PrintStream = if (p) NoopOutputStream.printStream else candidate } @@ -72,7 +72,7 @@ case class CommonOptions( in: InputStream = System.in, err: PrintStream = System.err, debug: PrintStream = NoopOutputStream.printStream, - info: PrintStream = NoopOutputStream.printStream + info: PrintStream = NoopOutputStream.printStream, ) { private[cli] lazy val workingDirectory: AbsoluteFile = cwd .getOrElse(AbsoluteFile.userDir) @@ -98,7 +98,7 @@ case class CliOptions( stdIn: Boolean = false, noStdErr: Boolean = false, error: Boolean = false, - check: Boolean = false + check: Boolean = false, ) { val writeMode: WriteMode = writeModeOpt.getOrElse(WriteMode.Override) @@ -148,7 +148,7 @@ case class CliOptions( private[cli] lazy val hoconOpt: Option[ConfParsed] = configStr .map(ConfParsed.fromString(_)).orElse { canonicalConfigFile.map( - _.fold(x => new ConfParsed(Configured.exception(x)), ConfParsed.fromPath(_)) + _.fold(x => new ConfParsed(Configured.exception(x)), ConfParsed.fromPath(_)), ) } @@ -176,7 +176,7 @@ case class CliOptions( } private def getHoconValueOpt[A]( - f: ConfParsed => Option[Either[String, A]] + f: ConfParsed => Option[Either[String, A]], ): Option[A] = hoconOpt.flatMap(f).map { case Right(x) => x case Left(x) => throw new ScalafmtConfigException(x) @@ -184,7 +184,7 @@ case class CliOptions( private def getHoconValue[A]( default: A, - f: ConfParsed => Option[Either[String, A]] + f: ConfParsed => Option[Either[String, A]], ): A = getHoconValueOpt[A](f).getOrElse(default) private[cli] def isGit: Boolean = diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/FileFetchMode.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/FileFetchMode.scala index 51a720da19..a07ff30901 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/FileFetchMode.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/FileFetchMode.scala @@ -15,7 +15,7 @@ object FileFetchMode { "diff" -> DiffFiles("master"), "changed" -> ChangedFiles, "any" -> RecursiveSearch, - "anygit" -> GitFiles + "anygit" -> GitFiles, ) private val availableModesMap: Map[String, FileFetchMode] = availableModes.toMap diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/InputMethod.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/InputMethod.scala index c16f0ee8dc..c987a5971b 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/InputMethod.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/InputMethod.scala @@ -19,7 +19,7 @@ sealed abstract class InputMethod { final def write( formatted: String, original: String, - options: CliOptions + options: CliOptions, ): ExitCode = { val codeChanged = formatted != original if (options.writeMode == WriteMode.Stdout) print(formatted, options) diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala index 9a912287c2..9e651c07ee 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtCoreRunner.scala @@ -15,7 +15,7 @@ import scala.meta.tokenizers.TokenizeException object ScalafmtCoreRunner extends ScalafmtRunner { override private[cli] def run( options: CliOptions, - termDisplayMessage: String + termDisplayMessage: String, ): ExitCode = options.scalafmtConfig.fold { e => options.common.err.println(s"${e.msg}") ExitCode.UnexpectedError @@ -49,7 +49,7 @@ object ScalafmtCoreRunner extends ScalafmtRunner { private[this] def handleFile( inputMethod: InputMethod, options: CliOptions, - config: ScalafmtConfig + config: ScalafmtConfig, ): ExitCode = try unsafeHandleFile(inputMethod, options, config) catch { @@ -61,7 +61,7 @@ object ScalafmtCoreRunner extends ScalafmtRunner { private[this] def unsafeHandleFile( inputMethod: InputMethod, options: CliOptions, - scalafmtConfig: ScalafmtConfig + scalafmtConfig: ScalafmtConfig, ): ExitCode = { val input = inputMethod.readInput(options) val filename = inputMethod.path.toString diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala index bd2560e52e..5c245f1334 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtDynamicRunner.scala @@ -15,7 +15,7 @@ import util.control.Breaks._ object ScalafmtDynamicRunner extends ScalafmtRunner { override private[cli] def run( options: CliOptions, - termDisplayMessage: String + termDisplayMessage: String, ): ExitCode = { val reporter = new ScalafmtCliReporter(options) val scalafmtInstance = Scalafmt.create(this.getClass.getClassLoader) @@ -63,7 +63,7 @@ object ScalafmtDynamicRunner extends ScalafmtRunner { private[this] def handleFile( inputMethod: InputMethod, session: ScalafmtSession, - options: CliOptions + options: CliOptions, ): ExitCode = { val input = inputMethod.readInput(options) diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtRunner.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtRunner.scala index efa74a8b74..96eb5beacd 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtRunner.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/ScalafmtRunner.scala @@ -10,17 +10,17 @@ import org.scalafmt.sysops.BatchPathFinder trait ScalafmtRunner { private[cli] def run( options: CliOptions, - termDisplayMessage: String + termDisplayMessage: String, ): ExitCode protected def newTermDisplay( options: CliOptions, inputMethods: Seq[InputMethod], - msg: String + msg: String, ): TermDisplay = { val termDisplay = new TermDisplay( new OutputStreamWriter(options.common.info), - fallbackMode = options.nonInteractive || TermDisplay.defaultFallbackMode + fallbackMode = options.nonInteractive || TermDisplay.defaultFallbackMode, ) if ( options.writeMode != WriteMode.Stdout && inputMethods.lengthCompare(5) > 0 @@ -34,7 +34,7 @@ trait ScalafmtRunner { protected def getInputMethods( options: CliOptions, - filter: Path => Boolean + filter: Path => Boolean, ): Seq[InputMethod] = if (options.stdIn) Seq(InputMethod.StdinCode(options.assumeFilename, options.common.in)) @@ -51,7 +51,7 @@ trait ScalafmtRunner { /** Returns file paths defined via options.{customFiles,customExclude} */ private[this] def getFilesFromCliOptions( options: CliOptions, - canFormat: Path => Boolean + canFormat: Path => Boolean, ): Seq[AbsoluteFile] = { val gitOps = options.gitOps val finder = options.fileFetchMode match { @@ -64,7 +64,7 @@ trait ScalafmtRunner { } val files = finder.findMatchingFiles( options.respectProjectFilters, - options.customFilesOpt.getOrElse(Seq.empty): _* + options.customFilesOpt.getOrElse(Seq.empty): _*, ) val excludeRegexp = options.excludeFilterRegexp.pattern files.filter(f => !excludeRegexp.matcher(f.toString()).find()) diff --git a/scalafmt-cli/src/main/scala/org/scalafmt/cli/TermDisplay.scala b/scalafmt-cli/src/main/scala/org/scalafmt/cli/TermDisplay.scala index 13491cb923..4c3da5e602 100644 --- a/scalafmt-cli/src/main/scala/org/scalafmt/cli/TermDisplay.scala +++ b/scalafmt-cli/src/main/scala/org/scalafmt/cli/TermDisplay.scala @@ -32,7 +32,7 @@ object Terminal { } Try( Process(Seq("bash", "-c", s"$pathedTput $s 2> /dev/tty")).!!(nullLog) - .trim.toInt + .trim.toInt, ).toOption } @@ -91,7 +91,7 @@ object TermDisplay { previouslyDownloaded: Long, length: Option[Long], startTime: Long, - updateCheck: Boolean + updateCheck: Boolean, ) extends Info { /** 0.0 to 1.0 */ @@ -115,7 +115,7 @@ object TermDisplay { private case class CheckUpdateInfo( currentTimeOpt: Option[Long], remoteTimeOpt: Option[Long], - isDone: Boolean + isDone: Boolean, ) extends Info { def fraction = None def display(): String = @@ -189,7 +189,7 @@ object TermDisplay { } def removeEntry(url: String, success: Boolean, fallbackMessage: => String)( - update0: Info => Info + update0: Info => Info, ): Unit = { downloads.synchronized { downloads -= url @@ -240,7 +240,7 @@ object TermDisplay { val url0 = if (total0 >= width) url.take( - ((width - baseExtraWidth - 1) max (url.length - overflow0)) - 1 + ((width - baseExtraWidth - 1) max (url.length - overflow0)) - 1, ) + "…" else url @@ -372,7 +372,7 @@ object Cache { class TermDisplay( out: Writer, - val fallbackMode: Boolean = TermDisplay.defaultFallbackMode + val fallbackMode: Boolean = TermDisplay.defaultFallbackMode, ) extends Cache.Logger { import TermDisplay._ @@ -387,20 +387,20 @@ class TermDisplay( override def startTask(msg: String, file: File): Unit = updateThread.newEntry( msg, DownloadInfo(0L, 0L, None, System.currentTimeMillis(), updateCheck = false), - s"$msg\n" + s"$msg\n", ) def taskLength( url: String, totalLength: Long, - alreadyDownloaded: Long + alreadyDownloaded: Long, ): Unit = { val info = updateThread.infos.get(url) assert(info != null) val newInfo = info match { case info0: DownloadInfo => info0.copy( length = Some(totalLength), - previouslyDownloaded = alreadyDownloaded + previouslyDownloaded = alreadyDownloaded, ) case _ => throw new Exception(s"Incoherent display state for $url") } @@ -427,11 +427,11 @@ class TermDisplay( override def checkingUpdates( url: String, - currentTimeOpt: Option[Long] + currentTimeOpt: Option[Long], ): Unit = updateThread.newEntry( url, CheckUpdateInfo(currentTimeOpt, None, isDone = false), - s"$url\n" + s"$url\n", ) } diff --git a/scalafmt-config/shared/src/main/scala/org/scalafmt/config/ConfParsed.scala b/scalafmt-config/shared/src/main/scala/org/scalafmt/config/ConfParsed.scala index 8fd8cebfb8..868a2f608b 100644 --- a/scalafmt-config/shared/src/main/scala/org/scalafmt/config/ConfParsed.scala +++ b/scalafmt-config/shared/src/main/scala/org/scalafmt/config/ConfParsed.scala @@ -11,11 +11,11 @@ import org.scalafmt.config.PlatformConfig._ class ConfParsed(val conf: Configured[Conf]) extends AnyVal { def getHoconValueOpt[A]( - path: String* + path: String*, )(implicit ev: ConfDecoderEx[A]): Option[Either[String, A]] = { val res = conf.andThen(_.getNestedConf(path: _*)).andThen(ev.read(None, _)) res.fold[Option[Either[String, A]]](x => - if (x.isMissingField) None else Some(Left(x.msg)) + if (x.isMissingField) None else Some(Left(x.msg)), )(x => Some(Right(x))) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/Error.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/Error.scala index 210b99e954..d749d9aca0 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/Error.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/Error.scala @@ -31,7 +31,7 @@ object Error { case class PreciseIncomplete(pos: Position, formattedCode: String) extends Error( pos - .formatMessage("error", "Unable to format file due to bug in scalafmt") + .formatMessage("error", "Unable to format file due to bug in scalafmt"), ) case class CantFindDefnToken(what: String, tree: Tree) extends Error(s"Expected keyword of type $what in tree $tree") @@ -48,7 +48,7 @@ object Error { |${output.linesIterator.toVector.take(10).mkString("\n")} |===================== |Formatter changed AST - |""".stripMargin + |""".stripMargin, ) case class FormatterOutputDoesNotParse(msg: String, line: Int) @@ -57,7 +57,7 @@ object Error { case class UnexpectedTree[Expected <: Tree: ClassTag](obtained: Tree) extends Error( s"""|Expected: ${classTag[Expected].runtimeClass.getName} - |Obtained: ${log(obtained)}""".stripMargin + |Obtained: ${log(obtained)}""".stripMargin, ) case class CantFormatFile(msg: String) @@ -78,7 +78,7 @@ object Error { case class SearchStateExploded( deepestState: State, partialOutput: String, - ft: FormatToken + ft: FormatToken, ) extends Error({ val tok = LoggerOps.log2(ft) val line = ft.left.pos.endLine @@ -94,7 +94,7 @@ object Error { case object NoMatchingFiles extends Error( "No files formatted/tested. " + - "Verify include/exclude filters and command line arguments." + "Verify include/exclude filters and command line arguments.", ) with NoStackTrace diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/Formatted.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/Formatted.scala index 536c58cd2b..6393a77538 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/Formatted.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/Formatted.scala @@ -21,7 +21,7 @@ object Formatted { private[scalafmt] case class Result( formatted: Formatted, - config: ScalafmtConfig + config: ScalafmtConfig, ) { def get: String = formatted.get } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/Scalafmt.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/Scalafmt.scala index b33b7f3c33..c7a282547e 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/Scalafmt.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/Scalafmt.scala @@ -54,14 +54,14 @@ object Scalafmt { code: String, style: ScalafmtConfig, range: Set[Range], - filename: String + filename: String, ): Formatted = formatCode(code, style, range, filename).formatted private[scalafmt] def formatCode( code: String, baseStyle: ScalafmtConfig = ScalafmtConfig.uncheckedDefault, range: Set[Range] = Set.empty, - filename: String = defaultFilename + filename: String = defaultFilename, ): Formatted.Result = { def getStyleByFile(style: ScalafmtConfig) = { val isSbt = FileOps.isSbt(filename) @@ -76,7 +76,7 @@ object Scalafmt { else baseStyle.getConfigFor(filename).map(getStyleByFile) styleTry.fold( x => Formatted.Result(Formatted.Failure(x), baseStyle), - formatCodeWithStyle(code, _, range, filename) + formatCodeWithStyle(code, _, range, filename), ) } @@ -97,11 +97,11 @@ object Scalafmt { code: String, style: ScalafmtConfig, range: Set[Range], - filename: String + filename: String, ): Formatted.Result = { val isWin = code.contains(WinLineEnding) val (prefix, unixCode) = splitCodePrefix( - if (isWin) code.replaceAll(WinLineEnding, UnixLineEnding) else code + if (isWin) code.replaceAll(WinLineEnding, UnixLineEnding) else code, ) doFormat(unixCode, style, filename, range) match { case Failure(e) => Formatted.Result(Formatted.Failure(e), style) @@ -118,7 +118,7 @@ object Scalafmt { code: String, style: ScalafmtConfig, file: String, - range: Set[Range] + range: Set[Range], ): Try[String] = if (FileOps.isMarkdown(file)) MarkdownParser .transformMdoc(code)(doFormatOne(_, style, file, range)) @@ -133,7 +133,7 @@ object Scalafmt { code: String, style: ScalafmtConfig, file: String, - range: Set[Range] + range: Set[Range], ): Try[String] = if (code.matches("\\s*")) Success("") else { @@ -160,7 +160,7 @@ object Scalafmt { Failure(PreciseIncomplete(pos, formattedString)) } } - } + }, ) } @@ -168,7 +168,7 @@ object Scalafmt { def format( code: String, style: ScalafmtConfig = ScalafmtConfig.default, - range: Set[Range] = Set.empty[Range] + range: Set[Range] = Set.empty[Range], ): Formatted = formatCode(code, style, range).formatted // used by ScalafmtReflect.parseConfig diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Align.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Align.scala index 7b498a2cb3..ecafa476ef 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Align.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Align.scala @@ -92,8 +92,8 @@ case class Align( "Defn.Trait" -> "class/object/trait/enum", "Defn.Enum" -> "class/object/trait/enum", "Enumerator.Generator" -> "for", - "Enumerator.Val" -> "for" - ) + "Enumerator.Val" -> "for", + ), ) { def getOpenParenTupleSite = openParenTupleSite.getOrElse(openParenCallSite) @@ -115,7 +115,7 @@ object Align { openParenDefnSite = false, tokens = Seq.empty, tokenCategory = Map.empty, - treeCategory = Map.empty + treeCategory = Map.empty, ) // stable set of alignment operators, the previous defaultWithAlign. val some = Align() @@ -132,7 +132,7 @@ object Align { allowOverflow = true, multiline = true, arrowEnumeratorGenerator = true, - tokenCategory = Map("Equals" -> "Assign", "LeftArrow" -> "Assign") + tokenCategory = Map("Equals" -> "Assign", "LeftArrow" -> "Assign"), ) val allValues = List(default, none, some, most) @@ -149,7 +149,7 @@ object Align { // this is really no longer necessary; metaconfig supports "+" key case (state, Conf.Obj(List(("add", c)))) => Console.err.println( - """'align.tokens.add' is deprecated; use align.tokens."+" instead.""" + """'align.tokens.add' is deprecated; use align.tokens."+" instead.""", ) base.read(None, c).map(x => state.fold(x)(_ ++ x)) case (state, c) => preset.lift(c) 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 9564940842..59f1f52e29 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 @@ -19,7 +19,7 @@ case class AlignToken( code: String, @DeprecatedName("owner", "use owners instead", "3.0.0") owner: String = null, - owners: Seq[AlignToken.Owner] = Seq.empty + owners: Seq[AlignToken.Owner] = Seq.empty, ) { def getMatcher: Seq[AlignToken.Matcher] = { val specs = @@ -43,7 +43,7 @@ object AlignToken { */ case class Owner( regex: Option[String] = None, - parents: Seq[String] = Seq.empty + parents: Seq[String] = Seq.empty, ) { def getMatcher: Matcher = new Matcher(regex.map(pattern), parents.map(pattern)) @@ -83,7 +83,7 @@ object AlignToken { AlignToken("->", applyInfix), AlignToken("→", applyInfix), AlignToken(":=", applyInfix), - AlignToken("=", "(Enumerator.Val|Defn.(Va(l|r)|GivenAlias|Def|Type))") + AlignToken("=", "(Enumerator.Val|Defn.(Va(l|r)|GivenAlias|Def|Type))"), ) class Matcher(val owner: Option[jurPattern], val parents: Seq[jurPattern]) { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AvoidInfixSettings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AvoidInfixSettings.scala index ac8948811b..c3c4104e90 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AvoidInfixSettings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/AvoidInfixSettings.scala @@ -11,7 +11,7 @@ case class AvoidInfixSettings( // strict match private[config] val excludeFilters: Seq[AvoidInfixSettings.Filter], private val excludeScalaTest: Option[Boolean] = None, - excludePlaceholderArg: Option[Boolean] = None + excludePlaceholderArg: Option[Boolean] = None, ) { // if the user completely redefined (rather than appended), we don't touch @inline @@ -30,9 +30,9 @@ case class AvoidInfixSettings( else None private def withTestExclude: AvoidInfixSettings = getExcludeWithExtra( - AvoidInfixSettings.testExclude + AvoidInfixSettings.testExclude, ).fold(copy(excludeScalaTest = Some(false)))(x => - copy(excludeFilters = x, excludeScalaTest = Some(false)) + copy(excludeFilters = x, excludeScalaTest = Some(false)), ) @inline @@ -40,7 +40,7 @@ case class AvoidInfixSettings( excludeFilters.eq(obj) || excludeFilters.startsWith(obj) private def getExcludeWithExtra( - obj: Seq[AvoidInfixSettings.Filter] + obj: Seq[AvoidInfixSettings.Filter], ): Option[Seq[AvoidInfixSettings.Filter]] = if (obj.isEmpty) None else { @@ -50,7 +50,7 @@ case class AvoidInfixSettings( } private[config] def withExtraExclude( - obj: Seq[AvoidInfixSettings.Filter] + obj: Seq[AvoidInfixSettings.Filter], ): Option[AvoidInfixSettings] = getExcludeWithExtra(obj) .map(x => copy(excludeFilters = x)) @@ -129,14 +129,14 @@ object AvoidInfixSettings { "atMostOneElementOf", "allElementsOf", "inOrderElementsOf", - "theSameElementsAs" + "theSameElementsAs", ).map(Filter.apply) private[config] val sbtExclude = Seq("cross").map(Filter.apply) private[config] val default = AvoidInfixSettings( includeFilters = mainInclude, - excludeFilters = mainExclude + excludeFilters = mainExclude, ) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/BinPack.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/BinPack.scala index 118ea4f884..a9e2e4c92b 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/BinPack.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/BinPack.scala @@ -42,7 +42,7 @@ case class BinPack( literalsSingleLine: Boolean = false, literalsMinArgCount: Int = 5, literalsInclude: Seq[String] = Seq(".*"), - literalsExclude: Seq[String] = Seq("String", "Term.Name") + literalsExclude: Seq[String] = Seq("String", "Term.Name"), ) { def literalsRegex: FilterMatcher = FilterMatcher(literalsInclude, literalsExclude) @@ -74,7 +74,7 @@ object BinPack { val enabled = BinPack( unsafeDefnSite = Unsafe.Always, unsafeCallSite = Unsafe.Always, - parentConstructors = ParentCtors.Always + parentConstructors = ParentCtors.Always, ) implicit val decoder: ConfDecoderEx[BinPack] = Presets @@ -99,7 +99,7 @@ object BinPack { Always, Never, Oneline, - OnelineIfPrimaryOneline + OnelineIfPrimaryOneline, ) { case Conf.Bool(true) => Configured.ok(Always) case Conf.Bool(false) => Configured.ok(Never) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Comments.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Comments.scala index c7d0670245..943e6ca52d 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Comments.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Comments.scala @@ -17,7 +17,7 @@ import metaconfig._ case class Comments( wrap: Comments.Wrap = Comments.Wrap.no, wrapSingleLineMlcAsSlc: Boolean = false, - wrapStandaloneSlcAsSlc: Boolean = false + wrapStandaloneSlcAsSlc: Boolean = false, ) { @inline def willWrap: Boolean = wrap ne Comments.Wrap.no diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/DanglingParentheses.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/DanglingParentheses.scala index e409bdf05f..0c2210c885 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/DanglingParentheses.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/DanglingParentheses.scala @@ -7,14 +7,14 @@ case class DanglingParentheses( defnSite: Boolean, ctrlSite: Boolean = true, private[config] val tupleSite: Option[Boolean] = None, - private val exclude: Option[List[DanglingParentheses.Exclude]] = None + private val exclude: Option[List[DanglingParentheses.Exclude]] = None, ) { @inline def tupleOrCallSite(isTuple: Boolean) = if (isTuple) tupleSite.getOrElse(callSite) else callSite def getExclude( - isVerticalMultiline: Boolean + isVerticalMultiline: Boolean, ): Seq[DanglingParentheses.Exclude] = exclude.getOrElse { if (!isVerticalMultiline) Nil else DanglingParentheses.Exclude.defaultVerticalMultiline diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Docstrings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Docstrings.scala index 0982fbdc3e..372d72c387 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Docstrings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Docstrings.scala @@ -27,7 +27,7 @@ case class Docstrings( private[config] val wrapMaxColumn: Option[Int] = None, forceBlankLineBefore: Option[Boolean] = None, blankFirstLine: Docstrings.BlankFirstLine = Docstrings.BlankFirstLine.no, - style: Docstrings.Style = Docstrings.SpaceAsterisk + style: Docstrings.Style = Docstrings.SpaceAsterisk, ) { import Docstrings._ @@ -44,7 +44,7 @@ case class Docstrings( import ValidationOps._ addIf( blankFirstLine.eq(BlankFirstLine.keep) && style.eq(Docstrings.Asterisk), - s"docstrings" + s"docstrings", ) } @@ -62,7 +62,7 @@ object Docstrings { } case object Preserve extends Style { override def skipFirstLine: Boolean = throw new NotImplementedError( - "skipFirstLine called for docstrings.style=preserve, it's a bug in scalafmt" + "skipFirstLine called for docstrings.style=preserve, it's a bug in scalafmt", ) } case object Asterisk extends Style { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/FormatEvent.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/FormatEvent.scala index c96874c589..59565cab69 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/FormatEvent.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/FormatEvent.scala @@ -18,7 +18,7 @@ object FormatEvent { case class CompleteFormat( totalExplored: Int, finalState: State, - visits: IndexedSeq[Int] + visits: IndexedSeq[Int], ) extends FormatEvent case class Written(formatLocations: FormatWriter#FormatLocations) extends FormatEvent diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/IndentOperator.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/IndentOperator.scala index 7776ff0e49..887066759c 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/IndentOperator.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/IndentOperator.scala @@ -52,13 +52,13 @@ case class IndentOperator( @annotation.DeprecatedName( "topLevelOnly", "Use indentOperator.exemptScope instead (true->topLevelOnly, false->all)", - "3.4.0" + "3.4.0", ) private val topLevelOnly: Boolean = true, @annotation.ExtraName("include") includeRegex: String = ".*", @annotation.ExtraName("exclude") - excludeRegex: String = "^(&&|\\|\\|)$" + excludeRegex: String = "^(&&|\\|\\|)$", ) { private val includeRegexp = includeRegex.r.pattern private val excludeRegexp = excludeRegex.r.pattern @@ -68,7 +68,7 @@ case class IndentOperator( lazy val getExemptScope: IndentOperator.Exempt = exemptScope.getOrElse( if (topLevelOnly) IndentOperator.Exempt.oldTopLevel - else IndentOperator.Exempt.all + else IndentOperator.Exempt.all, ) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Indents.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Indents.scala index ebc567f25a..b8161aebb4 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Indents.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Indents.scala @@ -37,7 +37,7 @@ case class Indents( @annotation.ExtraName("deriveSite") extendSite: Int = 4, withSiteRelativeToExtends: Int = 0, - commaSiteRelativeToExtends: Int = 2 + commaSiteRelativeToExtends: Int = 2, ) { lazy val getSignificant = significant.getOrElse(main) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Literals.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Literals.scala index 24bbaf1b66..051519a845 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Literals.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Literals.scala @@ -8,7 +8,7 @@ case class Literals( double: Case = Case.Lower, hexDigits: Case = Case.Lower, hexPrefix: Case = Case.Lower, - scientific: Case = Case.Lower + scientific: Case = Case.Lower, ) object Literals { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/NamedDialect.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/NamedDialect.scala index c13cab1f60..bb96fed827 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/NamedDialect.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/NamedDialect.scala @@ -27,7 +27,7 @@ object NamedDialect { Sbt0137, Sbt1, Scala3Future, - scala3 + scala3, ).map(apply).sortBy(_.name) private[config] val defaultName = "default" 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 bb15669438..1cc840678d 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 @@ -158,13 +158,13 @@ case class Newlines( @annotation.DeprecatedName( "topLevelStatementsMinBreaks", "Use newlines.topLevelStatementBlankLines instead", - "3.0.0" + "3.0.0", ) private val topLevelStatementsMinBreaks: Int = 1, @annotation.DeprecatedName( "topLevelStatements", "Use newlines.topLevelStatementBlankLines instead", - "3.0.0" + "3.0.0", ) private val topLevelStatements: Seq[BeforeAfter] = Seq.empty, beforeTemplateBodyIfBreakInParentCtors: Boolean = false, @@ -185,14 +185,14 @@ case class Newlines( @annotation.DeprecatedName( "alwaysBeforeMultilineDef", "Use newlines.forceBeforeMultilineAssign instead", - "3.0.0" + "3.0.0", ) private val alwaysBeforeMultilineDef: Boolean = false, private[config] val beforeMultiline: Option[SourceHints] = None, @annotation.DeprecatedName( "beforeMultilineDef", "Use newlines.beforeMultiline, newlines.forceBeforeMultilineAssign instead", - "3.0.0" + "3.0.0", ) beforeMultilineDef: Option[SourceHints] = None, private[config] val selectChains: Option[SourceHints] = None, @@ -203,14 +203,14 @@ case class Newlines( avoidForSimpleOverflow: Seq[AvoidForSimpleOverflow] = Seq.empty, inInterpolation: InInterpolation = InInterpolation.allow, ignoreInSyntax: Boolean = true, - avoidAfterYield: Boolean = true + avoidAfterYield: Boolean = true, ) { if ( implicitParamListModifierForce.nonEmpty && implicitParamListModifierPrefer.nonEmpty ) throw new ScalafmtConfigException( "can't specify both " + - "implicitParamListModifierForce and implicitParamListModifierPrefer" + "implicitParamListModifierForce and implicitParamListModifierPrefer", ) @inline @@ -278,7 +278,7 @@ case class Newlines( if (topLevelStatementBlankLines.isEmpty) { val nb = NumBlanks( if (topLevelStatements.contains(before)) 1 else 0, - if (topLevelStatements.contains(after)) 1 else 0 + if (topLevelStatements.contains(after)) 1 else 0, ) if (nb.isEmpty) Seq.empty else { @@ -299,7 +299,7 @@ case class Newlines( def getTopStatBlankLines( tree: Tree, numBreaks: Int, - nest: Int + nest: Int, ): Option[NumBlanks] = topStatBlankLinesSorted.iterator .takeWhile(_.minBreaks <= numBreaks).find { x => x.minNest <= nest && x.maxNest >= nest && @@ -405,7 +405,7 @@ object Newlines { never, always, multiline, - multilineWithCaseOnly + multilineWithCaseOnly, ) { case Conf.Bool(true) => Configured.Ok(always) case Conf.Bool(false) => Configured.Ok(never) @@ -460,7 +460,7 @@ object Newlines { after: Int = 0, beforeAll: Option[Int] = None, afterAll: Option[Int] = None, - beforeEndMarker: Int = 0 + beforeEndMarker: Int = 0, ) { def isEmpty: Boolean = before == 0 && after == 0 } @@ -494,7 +494,7 @@ object Newlines { minBreaks: Int = 1, blanks: Option[NumBlanks] = None, minNest: Int = 0, - maxNest: Int = Int.MaxValue + maxNest: Int = Int.MaxValue, ) { lazy val pattern = regex.map(_.r.pattern) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/OptIn.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/OptIn.scala index f0df93616d..69f9cf558c 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/OptIn.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/OptIn.scala @@ -109,9 +109,9 @@ case class OptIn( @annotation.DeprecatedName( "forceBlankLineBeforeDocstring", "Use docstrings.forceBlankLineBefore instead", - "3.4.0" + "3.4.0", ) - forceBlankLineBeforeDocstring: Boolean = true + forceBlankLineBeforeDocstring: Boolean = true, ) object OptIn { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Presets.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Presets.scala index 2312a1505a..dd7e239533 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Presets.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Presets.scala @@ -8,7 +8,7 @@ object Presets { def mapDecoder[A <: Product]( baseDecoder: ConfDecoderEx[A], - sectionName: String = null + sectionName: String = null, )(implicit presets: PartialFunction[Conf, A]): ConfDecoderEx[A] = (state, conf) => decodePresets(conf, sectionName, presets) match { @@ -21,7 +21,7 @@ object Presets { private def decodePresets[A]( conf: Conf, sectionName: String, - presets: PartialFunction[Conf, A] + presets: PartialFunction[Conf, A], ): Option[Configured[(A, Conf)]] = { def me = getClass.getSimpleName object presetsMatch { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ProjectFiles.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ProjectFiles.scala index 29db6c1ae1..43af6c63b6 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ProjectFiles.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ProjectFiles.scala @@ -20,15 +20,15 @@ case class ProjectFiles( @DeprecatedName( "includeFilters", "use `includePaths` with `regex:` prefix", - "v3.0.0" + "v3.0.0", ) includeFilters: Seq[String] = Nil, @DeprecatedName( "excludeFilters", "use `excludePaths` with `regex:` prefix", - "v3.0.0" + "v3.0.0", ) - excludeFilters: Seq[String] = Nil + excludeFilters: Seq[String] = Nil, ) { // required for ScalafmtDynamic (ScalafmtReflectConfig.isIncludedInProject) lazy val matcher: ProjectFiles.FileMatcher = ProjectFiles.FileMatcher(this) @@ -51,7 +51,7 @@ object ProjectFiles { object FileMatcher { def apply( pf: ProjectFiles, - regexExclude: Seq[String] = Nil + regexExclude: Seq[String] = Nil, ): FileMatcher = { // check if includePaths were specified explicitly val useIncludePaths = pf.includePaths.ne(defaultIncludePaths) || @@ -59,7 +59,7 @@ object ProjectFiles { val includePaths = if (useIncludePaths) pf.includePaths else Seq.empty new FileMatcher( nio(includePaths) ++ regex(pf.includeFilters), - nio(pf.excludePaths) ++ regex(pf.excludeFilters ++ regexExclude) + nio(pf.excludePaths) ++ regex(pf.excludeFilters ++ regexExclude), ) } @@ -73,7 +73,7 @@ object ProjectFiles { try fs.getPathMatcher(pattern) catch { case _: IllegalArgumentException => throw new ScalafmtConfigException( - s"Illegal pattern in configuration: $pattern" + s"Illegal pattern in configuration: $pattern", ) } def matches(path: file.Path): Boolean = matcher.matches(path) @@ -85,7 +85,7 @@ object ProjectFiles { case e: java.util.regex.PatternSyntaxException => throw new ScalafmtConfigException( s"""|Illegal regex in configuration: $regex - |reason: ${e.getMessage()}""".stripMargin + |reason: ${e.getMessage()}""".stripMargin, ) } @@ -106,7 +106,7 @@ object ProjectFiles { sealed abstract class Layout { def getInfo(path: AbsoluteFile): Option[FileInfo] protected[config] def getDialectByLang(lang: String)(implicit - dialect: Dialect + dialect: Dialect, ): Option[NamedDialect] final def getLang(path: AbsoluteFile): Option[String] = getInfo(path) .map(_.lang) @@ -163,7 +163,7 @@ object ProjectFiles { private[config] val s3 = nd(NamedDialect.scala3) override protected[config] def getDialectByLang( - lang: String + lang: String, )(implicit dialect: Dialect): Option[NamedDialect] = lang match { case "scala-2.10" if is211 => s210 case "scala-2.11" if is212 || !is211 => s211 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 40d117f276..446cc3e674 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 @@ -14,7 +14,7 @@ object ReaderUtil { oneOfCustomEx(options: _*)(PartialFunction.empty) def oneOfCustom[T: ClassTag]( - options: sourcecode.Text[T]* + options: sourcecode.Text[T]*, )(f: PartialFunction[Conf, Configured[T]]): ConfCodecEx[T] = { object extract { def unapply(conf: Conf): Option[Configured[T]] = f.lift(conf) @@ -23,7 +23,7 @@ object ReaderUtil { } def oneOfCustomEx[T: ClassTag]( - options: sourcecode.Text[T]* + options: sourcecode.Text[T]*, )(f: PartialFunction[(Option[T], Conf), Configured[T]]): ConfCodecEx[T] = { val m = options.map(x => lowerCaseNoBackticks(x.source) -> x.value).toMap val decoder = ConfDecoderEx.fromPartial[T]("String")(f.orElse { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantBracesSettings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantBracesSettings.scala index d7ff16908c..623d9cbaa4 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantBracesSettings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantBracesSettings.scala @@ -13,7 +13,7 @@ case class RedundantBracesSettings( stringInterpolation: Boolean = false, parensForOneLineApply: Boolean = true, generalExpressions: Boolean = true, - ifElseExpressions: Boolean = false + ifElseExpressions: Boolean = false, ) object RedundantBracesSettings { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantParensSettings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantParensSettings.scala index 2aae04ebb0..53a733ea8f 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantParensSettings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RedundantParensSettings.scala @@ -3,7 +3,7 @@ package org.scalafmt.config import metaconfig._ case class RedundantParensSettings( - infixSide: Option[RedundantParensSettings.InfixSide] = None + infixSide: Option[RedundantParensSettings.InfixSide] = None, ) object RedundantParensSettings { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReflectOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReflectOps.scala index 99acf3cfe3..a4b7b4fee3 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReflectOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ReflectOps.scala @@ -30,7 +30,7 @@ private[config] object ReflectOps { def invokeStaticOn( target: AnyRef, methodName: String, - args: (Class[_], AnyRef)* + args: (Class[_], AnyRef)*, ): AnyRef = { val method = clazz.getMethod(methodName, args.map(_._1): _*) method.invoke(target, args.map(_._2): _*) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteScala3Settings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteScala3Settings.scala index 1e36747315..90c74448be 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteScala3Settings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteScala3Settings.scala @@ -11,7 +11,7 @@ case class RewriteScala3Settings( countEndMarkerLines: RewriteScala3Settings.EndMarkerLines = RewriteScala3Settings.EndMarkerLines.all, removeEndMarkerMaxLines: Int = 0, - insertEndMarkerMinLines: Int = 0 + insertEndMarkerMinLines: Int = 0, ) object RewriteScala3Settings { @@ -26,7 +26,7 @@ object RewriteScala3Settings { .mapDecoder(generic.deriveDecoderEx(default).noTypos, "rewrite.scala3") { case Conf.Bool(true) => new RewriteScala3Settings( convertToNewSyntax = true, - removeOptionalBraces = RemoveOptionalBraces.yes + removeOptionalBraces = RemoveOptionalBraces.yes, ) case Conf.Bool(false) => default } @@ -35,7 +35,7 @@ object RewriteScala3Settings { enabled: Boolean = true, fewerBracesMinSpan: Int = 2, fewerBracesMaxSpan: Int = 0, - oldSyntaxToo: Boolean = false + oldSyntaxToo: Boolean = false, ) object RemoveOptionalBraces { @@ -80,7 +80,7 @@ object RewriteScala3Settings { // https://dotty.epfl.ch/docs/reference/changed-features/vararg-splices.html // https://dotty.epfl.ch/docs/reference/changed-features/imports.html // https://dotty.epfl.ch/docs/reference/changed-features/wildcards.html - deprecated: Boolean = true + deprecated: Boolean = true, ) private object ConvertToNewSyntax { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteSettings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteSettings.scala index d00cda1ef2..ce5c9e4cb7 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteSettings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/RewriteSettings.scala @@ -16,11 +16,11 @@ case class RewriteSettings( @annotation.DeprecatedName( "allowInfixPlaceholderArg", "Use `avoidInfix.excludePlaceholderArg` instead", - "3.8.0" + "3.8.0", ) private val allowInfixPlaceholderArg: Boolean = true, @annotation.ExtraName("neverInfix") - avoidInfix: AvoidInfixSettings = AvoidInfixSettings.default + avoidInfix: AvoidInfixSettings = AvoidInfixSettings.default, ) { def isAllowInfixPlaceholderArg: Boolean = avoidInfix.excludePlaceholderArg .getOrElse(allowInfixPlaceholderArg) 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 ea407e13a8..9b6d17864c 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 @@ -134,13 +134,13 @@ case class ScalafmtConfig( @annotation.DeprecatedName( "poorMansTrailingCommasInConfigStyle", "Scala supports trailing commas after 2.12.2. Use trailingCommas instead", - "2.5.0" + "2.5.0", ) poorMansTrailingCommasInConfigStyle: Boolean = false, @annotation.DeprecatedName( "trailingCommas", "use rewrite.trailingCommas.style instead", - "3.0.5" + "3.0.5", ) private val trailingCommas: Option[TrailingCommas.Style] = None, verticalMultiline: VerticalMultiline = VerticalMultiline(), @@ -149,7 +149,7 @@ case class ScalafmtConfig( encoding: Codec = "UTF-8", project: ProjectFiles = ProjectFiles(), fileOverride: Conf.Obj = Conf.Obj.empty, - xmlLiterals: XmlLiterals = XmlLiterals() + xmlLiterals: XmlLiterals = XmlLiterals(), ) { import ScalafmtConfig._ @@ -162,7 +162,7 @@ case class ScalafmtConfig( copy(runner = runner.withDialect(dialect)) private[scalafmt] def withDialect( - dialect: Option[NamedDialect] + dialect: Option[NamedDialect], ): ScalafmtConfig = dialect.fold(this)(withDialect) def withDialect(dialect: Dialect, name: String): ScalafmtConfig = @@ -170,7 +170,7 @@ case class ScalafmtConfig( def withDialect(dialect: Dialect): ScalafmtConfig = withDialect( dialect, - NamedDialect.getName(dialect).getOrElse("unknown dialect") + NamedDialect.getName(dialect).getOrElse("unknown dialect"), ) private lazy val forMain: ScalafmtConfig = @@ -211,7 +211,7 @@ case class ScalafmtConfig( } private def getConfigViaLayoutInfoFor(absfile: AbsoluteFile)( - f: (ProjectFiles.Layout, String) => ScalafmtConfig + f: (ProjectFiles.Layout, String) => ScalafmtConfig, ): Option[ScalafmtConfig] = project.layout.flatMap { layout => layout.getInfo(absfile).map { info => val style = f(layout, info.lang) @@ -256,7 +256,7 @@ case class ScalafmtConfig( def withoutRewrites: ScalafmtConfig = copy( trailingCommas = None, docstrings = docstrings.withoutRewrites, - rewrite = rewrite.withoutRewrites + rewrite = rewrite.withoutRewrites, ) lazy val forceNewlineBeforeDocstring: Boolean = docstrings @@ -293,7 +293,7 @@ object ScalafmtConfig { indent = Indents(callSite = 2, defnSite = 2), align = default.align.copy(openParenCallSite = false), optIn = default.optIn.copy(configStyleArguments = false), - danglingParentheses = DanglingParentheses.shortcutTrue + danglingParentheses = DanglingParentheses.shortcutTrue, ) def addAlign(style: ScalafmtConfig): ScalafmtConfig = style @@ -307,7 +307,7 @@ object ScalafmtConfig { binPack = BinPack( unsafeDefnSite = BinPack.Unsafe.Always, unsafeCallSite = BinPack.Unsafe.Always, - parentConstructors = BinPack.ParentCtors.Always + parentConstructors = BinPack.ParentCtors.Always, ), danglingParentheses = DanglingParentheses(false, false), indent = Indents(callSite = 4, defnSite = 4), @@ -315,7 +315,7 @@ object ScalafmtConfig { newlines = default.newlines.copy( avoidInResultType = true, neverBeforeJsNative = true, - sometimesBeforeColonInMethodReturnType = false + sometimesBeforeColonInMethodReturnType = false, ), // For some reason, the bin packing does not play nicely with forced // config style. It's fixable, but I don't want to spend time on it @@ -325,8 +325,8 @@ object ScalafmtConfig { align = default.align.copy( arrowEnumeratorGenerator = false, tokens = Seq(AlignToken.caseArrow), - openParenCtrlSite = false - ) + openParenCtrlSite = false, + ), ) /** Ready styles provided by scalafmt. @@ -344,8 +344,8 @@ object ScalafmtConfig { default.runner.optimizer.copy( // The tests were not written in this style forceConfigStyleMinSpan = 500, - forceConfigStyleMinArgCount = 5 - ) + forceConfigStyleMinArgCount = 5, + ), ) private def readActiveStylePresets(conf: Conf): Configured[ScalafmtConfig] = @@ -402,7 +402,7 @@ object ScalafmtConfig { if (!dialect.allowSignificantIndentation) addIf(newlines.beforeOpenParenCallSite.nonEmpty, errDialect) addIfDirect( // can't use addIf on multiline conditions !(binPack.unsafeCallSite.isNever && binPack.unsafeDefnSite.isNever) && { newlines.implicitParamListModifierForce.nonEmpty || newlines.implicitParamListModifierPrefer.nonEmpty }, - "binPack.unsafeXXXSite && newlines.implicitParamListModifierXXX (not implemented)" + "binPack.unsafeXXXSite && newlines.implicitParamListModifierXXX (not implemented)", ) checkPositive(indent.main, indent.callSite, indent.defnSite, indent.commaSiteRelativeToExtends) checkNonNeg(indent.caseSite, indent.extendSite, indent.withSiteRelativeToExtends) @@ -448,7 +448,7 @@ object ScalafmtConfig { x.copy( version = state.version, runner = x.runner.withParser(state.runner.parser) - .withDialect(dialect) + .withDialect(dialect), ) } baseDecoder.read(Some(preset), restConf) @@ -466,7 +466,7 @@ object ScalafmtConfig { def fromHoconString( string: String, default: ScalafmtConfig = ScalafmtConfig.default, - path: Option[String] = None + path: Option[String] = None, ): Configured[ScalafmtConfig] = fromConf(ConfParsed.fromString(string, path), default = default) @@ -474,13 +474,13 @@ object ScalafmtConfig { def fromHoconFile( file: Path, default: ScalafmtConfig = ScalafmtConfig.default, - path: Option[String] = None + path: Option[String] = None, ): Configured[ScalafmtConfig] = fromConf(ConfParsed.fromPath(file, path), default = default) def fromConf( parsed: ConfParsed, - default: ScalafmtConfig + default: ScalafmtConfig, ): Configured[ScalafmtConfig] = ScalafmtConfig.decoder.read(Option(default), parsed.conf) match { case Configured.Ok(x) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtOptimizer.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtOptimizer.scala index 9d778a04f5..426bd7bb43 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtOptimizer.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtOptimizer.scala @@ -66,7 +66,7 @@ case class ScalafmtOptimizer( recurseOnBlocks: Boolean = true, @annotation.ExtraName("forceConfigStyleOnOffset") forceConfigStyleMinSpan: Int = 150, - forceConfigStyleMinArgCount: Int = 2 + forceConfigStyleMinArgCount: Int = 2, ) object ScalafmtOptimizer { @@ -83,6 +83,6 @@ object ScalafmtOptimizer { acceptOptimalAtHints = false, disableOptimizationsInsideSensitiveAreas = false, pruneSlowStates = false, - recurseOnBlocks = false + recurseOnBlocks = false, ) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtRunner.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtRunner.scala index 9049a3bbc5..e226205afb 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtRunner.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/ScalafmtRunner.scala @@ -25,7 +25,7 @@ case class ScalafmtRunner( private[config] val dialect: NamedDialect = NamedDialect.default, private val dialectOverride: Conf.Obj = Conf.Obj.empty, ignoreWarnings: Boolean = false, - fatalWarnings: Boolean = false + fatalWarnings: Boolean = false, ) { @inline private[scalafmt] def getDialect = dialect.dialect @@ -80,7 +80,7 @@ object ScalafmtRunner { debug = false, parser = ScalafmtParser.Source, optimizer = ScalafmtOptimizer.default, - maxStateVisits = 1000000 + maxStateVisits = 1000000, ) val sbt = default.withDialect(meta.dialects.Sbt) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/SortSettings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/SortSettings.scala index 14869c64bd..e97d5f4fe3 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/SortSettings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/SortSettings.scala @@ -13,7 +13,7 @@ object SortSettings { object ModKey { def apply[A](name: String)(implicit - classifier: Classifier[Mod, A] + classifier: Classifier[Mod, A], ): ModKey = ModKey(name, _.is[A]) } @@ -51,7 +51,7 @@ object SortSettings { modTransparent, modInline, modInfix, - modOpaque + modOpaque, ) // https://docs.scala-lang.org/style/declarations.html#modifiers @@ -74,7 +74,7 @@ object SortSettings { modTransparent, modInline, modInfix, - modOpaque + modOpaque, ) implicit val sortSettingsModKeyCodec: ConfCodecEx[ModKey] = ReaderUtil diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Spaces.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Spaces.scala index 23a7167b5a..7e57532a90 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Spaces.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/Spaces.scala @@ -59,7 +59,7 @@ case class Spaces( neverAroundInfixTypes: Seq[String] = Nil, afterKeywordBeforeParen: Boolean = true, inByNameTypes: Boolean = true, - afterSymbolicDefs: Boolean = false + afterSymbolicDefs: Boolean = false, ) { def isSpaceAfterKeyword(tokenAfter: Token): Boolean = afterKeywordBeforeParen || !tokenAfter.is[Token.LeftParen] diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/TrailingCommas.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/TrailingCommas.scala index 2c6c9120b9..676abbcf5a 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/TrailingCommas.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/TrailingCommas.scala @@ -4,7 +4,7 @@ import metaconfig._ case class TrailingCommas( allowFolding: Boolean = true, - style: TrailingCommas.Style = TrailingCommas.never + style: TrailingCommas.Style = TrailingCommas.never, ) { def withoutRewrites: TrailingCommas = copy(style = TrailingCommas.keep) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/VerticalMultiline.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/VerticalMultiline.scala index 3ab67d4ddd..fdb9a81371 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/config/VerticalMultiline.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/config/VerticalMultiline.scala @@ -7,7 +7,7 @@ import metaconfig._ case class VerticalMultiline( atDefnSite: Boolean = false, arityThreshold: Int = 100, - newlineAfterOpenParen: Boolean = false + newlineAfterOpenParen: Boolean = false, ) object VerticalMultiline { 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 f7a984052b..60fd6e39c6 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 @@ -18,7 +18,7 @@ import org.scalafmt.util.TreeOps */ private class BestFirstSearch private ( range: Set[Range], - formatWriter: FormatWriter + formatWriter: FormatWriter, )(implicit val formatOps: FormatOps) { import LoggerOps._ import TokenOps._ @@ -57,7 +57,7 @@ private class BestFirstSearch private ( !best.get(curr.depth).exists(_.alwaysBetter(curr)) def shouldRecurseOnBlock(ft: FormatToken, stop: Token)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Token] = if (!recurseOnBlocks || !isInsideNoOptZone(ft)) None else { @@ -66,7 +66,7 @@ private class BestFirstSearch private ( closeOpt.filter(close => // Block must span at least 3 lines to be worth recursing. close != stop && distance(left.left, close) > style.maxColumn * 3 && - extractStatementsIfAny(left.meta.leftOwner).nonEmpty + extractStatementsIfAny(left.meta.leftOwner).nonEmpty, ) } @@ -79,7 +79,7 @@ private class BestFirstSearch private ( start: State, stop: Token, depth: Int, - maxCost: Int + maxCost: Int, ): Option[State] = { val key = (start.depth, stateColumnKey(start)) val cachedState = memo.get(key) @@ -101,7 +101,7 @@ private class BestFirstSearch private ( start: State, stop: Token, depth: Int = 0, - maxCost: Int = Integer.MAX_VALUE + maxCost: Int = Integer.MAX_VALUE, ): State = { def newGeneration = new mutable.PriorityQueue[State]() var Q = newGeneration @@ -130,7 +130,7 @@ private class BestFirstSearch private ( if (explored > runner.maxStateVisits) throw SearchStateExploded( deepestYet, formatWriter.mkString(deepestYet), - tokens(deepestYet.depth) + tokens(deepestYet.depth), ) implicit val style = styleMap.at(splitToken) @@ -159,7 +159,7 @@ private class BestFirstSearch private ( throw SearchStateExploded( deepestYet, formatWriter.mkString(deepestYet), - splitToken + splitToken, ) } else { val actualSplit = getActiveSplits(curr, maxCost) @@ -295,7 +295,7 @@ private class BestFirstSearch private ( |splitsAfterPolicy=$splitsAfterPolicy""".stripMargin if (runner.debug) logger.debug( s"""|Failed to format - |$msg""".stripMargin + |$msg""".stripMargin, ) complete(deepestYet) SearchResult(deepestYet, reachedEOF = false) @@ -310,7 +310,7 @@ object BestFirstSearch { def apply( formatOps: FormatOps, range: Set[Range], - formatWriter: FormatWriter + formatWriter: FormatWriter, ): SearchResult = new BestFirstSearch(range, formatWriter)(formatOps).getBestPath 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 278ddec839..053fe7ea30 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 @@ -8,7 +8,7 @@ import org.scalafmt.config.{ Newlines, ScalafmtConfig, ScalafmtRunner, - TrailingCommas + TrailingCommas, } import org.scalafmt.internal.Length.Num import org.scalafmt.internal.Policy.NoPolicy @@ -28,7 +28,7 @@ import scala.meta.tokens.{Token => T} class FormatOps( val topSourceTree: Tree, baseStyle: ScalafmtConfig, - val filename: String = "" + val filename: String = "", ) { import FormatOps._ import PolicyOps._ @@ -55,7 +55,7 @@ class FormatOps( prevNonComment, prevNonCommentBefore, nextNonComment, - nextNonCommentSameLine + nextNonCommentSameLine, } private val usedTokens = tokens.head.left +: tokens.map(_.right) @@ -121,12 +121,12 @@ class FormatOps( @inline final def findFirst(start: FormatToken, end: T)( - f: FormatToken => Boolean + f: FormatToken => Boolean, ): Option[FormatToken] = findFirst(start, end.end)(f) @tailrec final def findFirst(start: FormatToken, end: Int)( - f: FormatToken => Boolean + f: FormatToken => Boolean, ): Option[FormatToken] = if (start.left.end >= end) None else if (f(start)) Some(start) @@ -136,7 +136,7 @@ class FormatOps( } def findFirstOnRight[A](start: FormatToken, end: T)(implicit - classifier: Classifier[T, A] + classifier: Classifier[T, A], ): Option[T] = findFirst(start, end.start)(x => classifier(x.right)) .map(_.right) @@ -161,7 +161,7 @@ class FormatOps( @tailrec final def endOfSingleLineBlock( - start: FormatToken + start: FormatToken, )(implicit style: ScalafmtConfig): T = { lazy val isInfix = isInfixRhs(start) val endFound = start.right match { @@ -225,23 +225,23 @@ class FormatOps( .fold(TokenRanges.empty)(other => TokenRanges(TokenRange(token, other))) def insideBlock[A](start: FormatToken, end: T)(implicit - classifier: Classifier[T, A] + classifier: Classifier[T, A], ): TokenRanges = insideBlock(start, end, x => classifier(x.left)) def insideBlock( start: FormatToken, end: T, - matches: FormatToken => Boolean + matches: FormatToken => Boolean, ): TokenRanges = insideBlock { x => if (matches(x)) matchingOpt(x.left) else None }(start, end) def insideBracesBlock(start: FormatToken, end: T, parensToo: Boolean = false)( - implicit style: ScalafmtConfig + implicit style: ScalafmtConfig, ): TokenRanges = insideBlock(x => getEndOfBlock(x, parensToo))(start, end) def insideBlock( - matches: FormatToken => Option[T] + matches: FormatToken => Option[T], )(start: FormatToken, end: T): TokenRanges = { var result = TokenRanges.empty @@ -292,7 +292,7 @@ class FormatOps( @inline def splitOneArgOneLine(close: T, owner: Tree)(implicit fileLine: FileLine, - style: ScalafmtConfig + style: ScalafmtConfig, ): Policy = { val pf = if (style.poorMansTrailingCommasInConfigStyle) @@ -339,7 +339,7 @@ class FormatOps( else Decision.onlyNewlineSplits(s) def penalizeNewlineByNesting(from: T, to: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = { val policy = Policy.before(to) { case Decision(FormatToken(l, _, m), s) => val nonBoolPenalty = if (isBoolOperator(l)) 0 else 5 @@ -354,14 +354,14 @@ class FormatOps( ft.meta.leftOwner match { case lo: Stat.WithTemplate => Some(lo.templ) case _ => None - } + }, ) val TemplateOnRight = new ExtractFromMeta(ft => ft.meta.rightOwner match { case ro: Template => Some(ro) case _ => None - } + }, ) def templateCurlyFt(template: Template): Option[FormatToken] = @@ -374,20 +374,20 @@ class FormatOps( templateCurly(template).getOrElse(getLastNonTrivialToken(template)) def templateDerivesOrCurlyOrLastNonTrivial(template: Template)(implicit - ft: FormatToken + ft: FormatToken, ): T = findTemplateGroupOnRight(_.getExpireToken)(template) .getOrElse(templateCurlyOrLastNonTrivial(template)) private def findTreeInGroup[A]( trees: Seq[Tree], - func: TemplateSupertypeGroup => A + func: TemplateSupertypeGroup => A, )(expireFunc: Seq[Tree] => T)(implicit ft: FormatToken): Option[A] = trees .find(_.pos.end >= ft.right.end).map { x => func(TemplateSupertypeGroup(x, trees, expireFunc)) } def findTemplateGroupOnRight[A]( - func: TemplateSupertypeGroup => A + func: TemplateSupertypeGroup => A, )(template: Template)(implicit ft: FormatToken): Option[A] = { @tailrec def iter(groups: Seq[Seq[Tree]]): Option[A] = @@ -441,7 +441,7 @@ class FormatOps( if (tokens.isAttachedCommentThenBreak(ft)) ft.right else ft.left def insideInfixSplit(app: Member.Infix, ft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = app match { case t: Type.ApplyInfix if style.spaces.neverAroundInfixTypes.contains(t.op.value) => @@ -486,7 +486,7 @@ class FormatOps( lhsApp: Member.Infix, ft: FormatToken, afterInfix: Newlines.AfterInfix, - newStmtMod: Option[Modification] = None + newStmtMod: Option[Modification] = None, )(implicit style: ScalafmtConfig): Seq[Split] = { val fullInfixTreeOpt = findTreeWithParentSimple(lhsApp, false)(isInfixApp) val fullInfix = fullInfixTreeOpt.flatMap(asInfixApp).getOrElse(lhsApp) @@ -497,7 +497,7 @@ class FormatOps( final def maybeGetInfixSplitsBeforeLhs( ft: FormatToken, - mod: => Option[Modification] = None + mod: => Option[Modification] = None, )(nonInfixSplits: => Seq[Split])(implicit style: ScalafmtConfig): Seq[Split] = { val tree = ft.meta.rightOwner val ai = style.breakAfterInfix(tree) @@ -508,11 +508,11 @@ class FormatOps( private[internal] object InfixSplits { def apply(app: Member.Infix, ft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): InfixSplits = apply(app, ft, findEnclosingInfix(app)) def apply(app: Member.Infix, ft: FormatToken, fullInfix: Member.Infix)( - implicit style: ScalafmtConfig + implicit style: ScalafmtConfig, ): InfixSplits = { val leftInfix = findLeftInfix(fullInfix) new InfixSplits(app, ft, fullInfix, leftInfix) @@ -526,7 +526,7 @@ class FormatOps( @tailrec private def findEnclosingInfix( child: Member.Infix, - childTree: Tree + childTree: Tree, ): Member.Infix = if (isEnclosedInParens(childTree)) child else childTree.parent match { @@ -539,7 +539,7 @@ class FormatOps( findEnclosingInfix(app, app) def withNLIndent(split: Split)(app: Member.Infix, ft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Split = { val noNL = !split.isNL && { val nextFt = nextNonCommentSameLine(ft) @@ -554,7 +554,7 @@ class FormatOps( app: Member.Infix, ft: FormatToken, fullInfix: Member.Infix, - leftInfix: Member.Infix + leftInfix: Member.Infix, )(implicit style: ScalafmtConfig) { private val beforeLhs = ft.left.start < app.pos.start private val fullExpire = getLastEnclosedToken(fullInfix) @@ -675,7 +675,7 @@ class FormatOps( def getBeforeLhsOrRhs( afterInfix: Newlines.AfterInfix, newStmtMod: Option[Modification] = None, - spaceMod: Modification = Space + spaceMod: Modification = Space, ): Seq[Split] = { val beforeLhs = ft.meta.leftOwner ne app.op val maxPrecedence = @@ -745,7 +745,7 @@ class FormatOps( val singleLineSplits = Seq( spaceSingleLine.onlyFor(SplitTag.InfixChainNoNL), spaceSingleLine.onlyIf(singleLinePolicy.isDefined), - nlSinglelineSplit + nlSinglelineSplit, ) val otherSplits = closeOpt.fold { @@ -810,7 +810,7 @@ class FormatOps( private def findNextInfixes( fullTree: Tree, tree: Tree, - res: mutable.Buffer[Member.Infix] + res: mutable.Buffer[Member.Infix], ): Unit = if (tree ne fullTree) tree.parent match { case Some(ia: Member.Infix) => if (ia.lhs eq tree) { @@ -827,7 +827,7 @@ class FormatOps( private def findNestedInfixes( tree: Tree, - res: mutable.Buffer[Member.Infix] + res: mutable.Buffer[Member.Infix], ): Unit = tree match { case Member.ArgClause(arg :: Nil) if !isEnclosedInParens(tree) => findNestedInfixes(arg, res) @@ -894,7 +894,7 @@ class FormatOps( def mustUseConfigStyle( ft: FormatToken, beforeCloseFt: => FormatToken, - allowForce: => Boolean = true + allowForce: => Boolean = true, )(implicit style: ScalafmtConfig): Boolean = style.optIn.configStyleArguments && couldUseConfigStyle(ft, beforeCloseFt, allowForce) @@ -902,7 +902,7 @@ class FormatOps( def couldUseConfigStyle( ft: FormatToken, beforeCloseFt: => FormatToken, - allowForce: => Boolean = true + allowForce: => Boolean = true, )(implicit style: ScalafmtConfig): Boolean = { def opensImplicit = (next(ft).hasBreak || @@ -915,7 +915,7 @@ class FormatOps( /** Works for `using` as well */ def opensConfigStyleImplicitParamList(formatToken: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = soft.ImplicitOrUsing.unapply(formatToken.right) && style.newlines.notBeforeImplicitParamListModifier && hasImplicitParamList(formatToken.meta.rightOwner) @@ -941,7 +941,7 @@ class FormatOps( def typeTemplateSplits(template: Template, indentIfSecond: Int)(implicit fileLine: FileLine, ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = { def getPolicy(expire: T) = expire match { case lb: T.LeftBrace if template.self.tokens.isEmpty => @@ -973,9 +973,9 @@ class FormatOps( Split(Space, 0).withIndent(indent).withSingleLine( slbEnd, exclude = insideBlock[T.LeftParen](ft, slbEnd), - noSyntaxNL = true + noSyntaxNL = true, ), - nlSplit(1) + nlSplit(1), ) } }(template).getOrElse { @@ -984,7 +984,7 @@ class FormatOps( } def ctorWithChain(ownerSet: Set[Tree], lastToken: T)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Policy = if (style.binPack.parentConstructors eq BinPack.ParentCtors.Always) NoPolicy else if (ownerSet.isEmpty) NoPolicy @@ -1003,11 +1003,11 @@ class FormatOps( rhs: => Option[Tree], lastToken: T, indentLen: Int, - extendsThenWith: => Boolean = false + extendsThenWith: => Boolean = false, )(implicit fileLine: FileLine, ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = { val nlMod = NewlineT(alt = Some(Space)) val indent = @@ -1021,9 +1021,9 @@ class FormatOps( Split(Space, 0).withIndent(indent).withSingleLine( slbEnd, exclude = insideBracesBlock(ft, slbEnd, true), - noSyntaxNL = extendsThenWith + noSyntaxNL = extendsThenWith, ), - Split(nlMod, 1).withIndent(indent) + Split(nlMod, 1).withIndent(indent), ) } else if (isFirstCtor) { @@ -1052,7 +1052,7 @@ class FormatOps( .preActivateFor(nlOnelineTag.left.toOption) .withSingleLine(lastToken, noSyntaxNL = noSyntaxNL) .withIndent(indent), - Split(nlMod, 1).withPolicy(nlPolicy & pnlPolicy).withIndent(indent) + Split(nlMod, 1).withPolicy(nlPolicy & pnlPolicy).withIndent(indent), ) } else Seq(Split(Space, 0), Split(Newline, 1)) } @@ -1092,7 +1092,7 @@ class FormatOps( /** Implementation for `verticalMultiline` */ def verticalMultiline( - ft: FormatToken + ft: FormatToken, )(implicit style: ScalafmtConfig): Seq[Split] = { val lpOwner = ft.meta.leftOwner val lpParent = lpOwner.parent @@ -1234,10 +1234,10 @@ class FormatOps( slbSplit.notIf(noSlb), Split(space, 0, policy = policy).onlyIf(spaceImplicit).andPolicy( decideNewlinesOnlyAfterClose(r), - tokens.isRightCommentThenBreak(next(ft)) + tokens.isRightCommentThenBreak(next(ft)), ).withIndent(firstIndent), // Otherwise split vertically - Split(nlMod, 1, policy = policy).withIndent(firstIndent) + Split(nlMod, 1, policy = policy).withIndent(firstIndent), ) } @@ -1271,7 +1271,7 @@ class FormatOps( } def getSpaceAndNewlineAfterCurlyLambda(newlines: Int)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): (Boolean, NewlineT) = style.newlines.afterCurlyLambdaParams match { case Newlines.AfterCurlyLambdaParams.squash => (true, Newline) case Newlines.AfterCurlyLambdaParams.never => @@ -1293,7 +1293,7 @@ class FormatOps( } def getNoSplit(ft: FormatToken, spaceOk: Boolean)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Modification = ft.right match { case _: T.Comment => val isDetachedSlc = ft.hasBreak && tokens.isBreakAfterRight(ft) @@ -1337,7 +1337,7 @@ class FormatOps( |Tree: ${log(t)} |Parent: ${log(t.parent)} |GrandParent: ${log(t.parent.flatMap(_.parent))} - |""".stripMargin + |""".stripMargin, ) throw UnexpectedTree[Member.SyntaxValuesClause](t) } @@ -1346,7 +1346,7 @@ class FormatOps( final def findPrevSelectAndApply( tree: Tree, enclosed: Boolean, - applyTree: Option[Member.Apply] = None + applyTree: Option[Member.Apply] = None, ): (Option[SelectLike], Option[Member.Apply]) = { @inline def isEnclosed: Boolean = enclosed && isEnclosedInParens(tree) @@ -1362,13 +1362,13 @@ class FormatOps( def findPrevSelect( tree: SelectLike, - enclosed: Boolean = true + enclosed: Boolean = true, ): Option[SelectLike] = findPrevSelectAndApply(tree.qual, enclosed)._1 @tailrec private def findLastApplyAndNextSelectEnclosed( tree: Tree, - select: Option[SelectLike] = None + select: Option[SelectLike] = None, ): (Tree, Option[SelectLike]) = if (isEnclosedInParens(tree)) (tree, select) else tree.parent match { @@ -1383,7 +1383,7 @@ class FormatOps( private def findLastApplyAndNextSelectPastEnclosed( tree: Tree, select: Option[SelectLike] = None, - prevEnclosed: Option[Tree] = None + prevEnclosed: Option[Tree] = None, ): (Tree, Option[SelectLike]) = tree.parent match { case Some(GetSelectLike(p)) => findLastApplyAndNextSelectPastEnclosed(p.tree, select.orElse(Some(p))) @@ -1401,7 +1401,7 @@ class FormatOps( final def findLastApplyAndNextSelect( tree: Tree, - enclosed: Boolean + enclosed: Boolean, ): (Tree, Option[SelectLike]) = if (enclosed) findLastApplyAndNextSelectEnclosed(tree) else findLastApplyAndNextSelectPastEnclosed(tree) @@ -1409,7 +1409,7 @@ class FormatOps( def canStartSelectChain( thisSelectLike: SelectLike, nextSelect: Option[Term], - lastApply: Tree + lastApply: Tree, )(implicit style: ScalafmtConfig): Boolean = { val thisTree = thisSelectLike.tree val ok = thisTree.ne(lastApply) && @@ -1438,7 +1438,7 @@ class FormatOps( final def inSelectChain( prevSelect: Option[SelectLike], thisSelect: SelectLike, - lastApply: Tree + lastApply: Tree, )(implicit style: ScalafmtConfig): Boolean = prevSelect match { case None => false case Some(p) if canStartSelectChain(p, Some(thisSelect.tree), lastApply) => @@ -1460,7 +1460,7 @@ class FormatOps( } def withIndentOnXmlStart(tok: T.Xml.Start, splits: Seq[Split])(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = if (style.xmlLiterals.assumeFormatted) { val end = matching(tok) @@ -1469,7 +1469,7 @@ class FormatOps( } else splits def withIndentOnXmlSpliceStart(ft: FormatToken, splits: Seq[Split])(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = ft.left match { case t: T.Xml.SpliceStart if style.xmlLiterals.assumeFormatted => val end = matching(t) @@ -1489,7 +1489,7 @@ class FormatOps( @tailrec private def getNestedOpens( tree: Member.ArgClause, - res: List[FormatToken] + res: List[FormatToken], ): List[FormatToken] = { val args = tree.values if (args.isEmpty) res @@ -1504,7 +1504,7 @@ class FormatOps( private def getNestedOpensPolicy( opens: List[FormatToken], - policy: Policy + policy: Policy, ): Policy = opens.foldLeft(policy) { case (res, x) => val onOpen = Policy(tokens.nextNonComment(x).right match { case t: T.LeftBrace => Policy.End.After(t) @@ -1517,7 +1517,7 @@ class FormatOps( @tailrec def getFoldedPolicy( body: Tree, - policy: Policy = Policy.NoPolicy + policy: Policy = Policy.NoPolicy, ): Policy = body match { case t: Member.Apply if t.fun ne body => val opens = getNestedOpens(t.argClause, Nil) @@ -1537,7 +1537,7 @@ class FormatOps( body: Tree, nlSplitFunc: Int => Split, isKeep: Boolean, - spaceIndents: Seq[Indent] = Seq.empty + spaceIndents: Seq[Indent] = Seq.empty, )(implicit style: ScalafmtConfig): Seq[Split] = { def bheadFT = tokens.getHead(body) val blastFT = tokens.getLastNonTrivial(body) @@ -1550,32 +1550,32 @@ class FormatOps( nlSplitFunc(1).andPolicy(penalize(penalty)).forThisLine(nextLine) def getSplits(spaceSplit: Split) = ( spaceSplit.withIndents(spaceIndents), - getNlSplit(1)(nextLine(spaceSplit.fileLine)) + getNlSplit(1)(nextLine(spaceSplit.fileLine)), ) def getSlb(end: T, excl: TokenRanges)(implicit fileLine: FileLine) = SingleLineBlock(end, exclude = excl, noSyntaxNL = true) def getSlbSplit( end: T, exclude: TokenRanges = TokenRanges.empty, - policy: Policy = Policy.NoPolicy + policy: Policy = Policy.NoPolicy, )(implicit fileLine: FileLine) = Split(Space, 0) .withPolicy(policy | getSlb(end, exclude)) .withOptimalToken(end, ignore = blast.start > end.start) def getSpaceSplit(penalty: Int, policy: Policy = Policy.NoPolicy)(implicit - fileLine: FileLine + fileLine: FileLine, ) = { val spacePolicy = policy | penalize(penalty) Split(Space, 0).withPolicy(spacePolicy).withOptimalToken(blast) } def getPolicySplits(penalty: Int, policy: Policy)(implicit - fileLine: FileLine + fileLine: FileLine, ) = getSplits(getSpaceSplit(penalty, policy)) def getSlbSplits( exclude: TokenRanges = TokenRanges.empty, - policy: Policy = Policy.NoPolicy + policy: Policy = Policy.NoPolicy, )(implicit fileLine: FileLine) = ( getSlbSplit(expire, exclude, policy), - getNlSplit(if (policy.isEmpty) 0 else 1) + getNlSplit(if (policy.isEmpty) 0 else 1), ) def hasStateColumn = spaceIndents.exists(_.hasStateColumn) @tailrec @@ -1627,13 +1627,13 @@ class FormatOps( body: Tree, nlSplitFunc: Int => Split, isKeep: Boolean, - spaceIndents: Seq[Indent] + spaceIndents: Seq[Indent], )(implicit style: ScalafmtConfig): Seq[Split] = if (body.tokens.isEmpty) Seq(Split(Space, 0)) else foldedNonEmptyNonComment(body, nlSplitFunc, isKeep, spaceIndents) private def unfoldedSpaceNonEmptyNonComment(body: Tree, slbOnly: Boolean)( - implicit style: ScalafmtConfig + implicit style: ScalafmtConfig, ): Split = { val expire = nextNonCommentSameLine(tokens.getLastNonTrivial(body)).left def slbSplit(end: T)(implicit fileLine: FileLine) = Split(Space, 0) @@ -1654,7 +1654,7 @@ class FormatOps( body: Tree, nlSplitFunc: Int => Split, spaceIndents: Seq[Indent], - slbOnly: Boolean + slbOnly: Boolean, )(implicit style: ScalafmtConfig): Seq[Split] = if (body.tokens.isEmpty) Seq(Split(Space, 0).withIndents(spaceIndents)) else { @@ -1663,7 +1663,7 @@ class FormatOps( } def checkComment(ft: FormatToken, nlSplitFunc: Int => Split)( - splitsFunc: FormatToken => Seq[Split] + splitsFunc: FormatToken => Seq[Split], ): Seq[Split] = if (!ft.right.is[T.Comment]) splitsFunc(ft) else if (ft.hasBreak) Seq(nlSplitFunc(0).forThisLine) @@ -1685,7 +1685,7 @@ class FormatOps( ft: FormatToken, body: Tree, isKeep: Boolean, - spaceIndents: Seq[Indent] = Seq.empty + spaceIndents: Seq[Indent] = Seq.empty, )(nlSplitFunc: Int => Split)(implicit style: ScalafmtConfig): Seq[Split] = checkComment(ft, nlSplitFunc) { _ => foldedNonComment(body, nlSplitFunc, isKeep, spaceIndents) @@ -1694,14 +1694,14 @@ class FormatOps( def slbOnly( ft: FormatToken, body: Tree, - spaceIndents: Seq[Indent] = Seq.empty + spaceIndents: Seq[Indent] = Seq.empty, )(nlSplitFunc: Int => Split)(implicit style: ScalafmtConfig): Seq[Split] = checkComment(ft, nlSplitFunc) { _ => unfoldedNonComment(body, nlSplitFunc, spaceIndents, true) } def get(ft: FormatToken, body: Tree, spaceIndents: Seq[Indent] = Seq.empty)( - classicNoBreakFunc: => Split + classicNoBreakFunc: => Split, )(nlSplitFunc: Int => Split)(implicit style: ScalafmtConfig): Seq[Split] = checkComment(ft, nlSplitFunc) { x => style.newlines.getBeforeMultiline match { @@ -1725,15 +1725,15 @@ class FormatOps( def getWithIndent( ft: FormatToken, body: Tree, - spaceIndents: Seq[Indent] = Seq.empty + spaceIndents: Seq[Indent] = Seq.empty, )(classicNoBreakFunc: => Split)(nlSplitFunc: Int => Split)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = get(ft, body, spaceIndents)(classicNoBreakFunc)(x => - withIndent(nlSplitFunc(x), ft, body) + withIndent(nlSplitFunc(x), ft, body), ) def withIndent(nlSplit: Split, ft: FormatToken, body: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Split = asInfixApp(body).fold { val lastFt = tokens.getLast(body) val right = nextNonComment(ft).right @@ -1749,7 +1749,7 @@ class FormatOps( // Redundant () delims around case statements def isCaseBodyEnclosedAsBlock(ft: FormatToken, caseStat: CaseTree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = { val body = caseStat.body (ft.noBreak || style.newlines.getBeforeMultiline.ignoreSourceSplit) && @@ -1785,7 +1785,7 @@ class FormatOps( ft: FormatToken, noNLMod: => Modification, tparam: Type.Param, - bounds: Type.Param => Seq[Type] + bounds: Type.Param => Seq[Type], )(implicit style: ScalafmtConfig): Seq[Split] = { val boundOpt = bounds(tparam).find(_.pos.start > ft.right.end) val expireOpt = boundOpt.map(getLastNonTrivialToken) @@ -1796,7 +1796,7 @@ class FormatOps( ft: FormatToken, noNLMod: => Modification, typeOwner: Tree, - boundEndOpt: Option[T] + boundEndOpt: Option[T], )(implicit style: ScalafmtConfig): Seq[Split] = { val typeEnd = getLastNonTrivialToken(typeOwner) val boundEnd = boundEndOpt.getOrElse(typeEnd) @@ -1812,13 +1812,13 @@ class FormatOps( case Newlines.classic => Seq(Split(noNLMod, 0)) case Newlines.unfold => Seq( Split(noNLMod, 0).withSingleLine(typeEnd), - Split(Newline, 1).withIndent(indent).withPolicy(unfoldPolicy) + Split(Newline, 1).withIndent(indent).withPolicy(unfoldPolicy), ) case Newlines.keep if ft.hasBreak => Seq(Split(Newline, 1).withIndent(indent)) case _ => Seq( Split(noNLMod, 0).withSingleLine(boundEnd), - Split(Newline, 1).withIndent(indent) + Split(Newline, 1).withIndent(indent), ) } } @@ -1827,7 +1827,7 @@ class FormatOps( private trait Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] } @@ -1836,11 +1836,11 @@ class FormatOps( // ) = => ?=> <- catch do else finally for // if match return then throw try while yield def unapply(ftMeta: FormatToken.Meta)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Seq[Split]] = get(tokens(ftMeta.idx)).flatMap(_.splits) def get( - ft: FormatToken + ft: FormatToken, )(implicit style: ScalafmtConfig): Option[OptionalBracesRegion] = if (!style.dialect.allowSignificantIndentation) None else Option(ft.left match { @@ -1873,7 +1873,7 @@ class FormatOps( tree: Tree, forceNL: Boolean, danglingKeyword: Boolean = true, - indentOpt: Option[Int] = None + indentOpt: Option[Int] = None, )(implicit fileLine: FileLine, style: ScalafmtConfig): Seq[Split] = { val treeTokens = tree.tokens val end = tokens.getLast(treeTokens, tree) @@ -1899,7 +1899,7 @@ class FormatOps( Seq(Split(Newline, 0).withIndent(indent).withPolicy(nlPolicy)) else Seq( Split(Space, 0).withSingleLine(slbExpire), - Split(Newline, 1)(nextLine).withIndent(indent).withPolicy(nlPolicy) + Split(Newline, 1)(nextLine).withIndent(indent).withPolicy(nlPolicy), ) } @@ -1907,7 +1907,7 @@ class FormatOps( // TODO: amend for additional cases when the parser supports them private object ColonEolImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t: Template if templateCurlyFt(t).contains(ft) => Some(new OptionalBracesRegion { @@ -1944,7 +1944,7 @@ class FormatOps( private def onArgClause( ft: FormatToken, ac: Term.ArgClause, - args: List[Tree] + args: List[Tree], )(implicit style: ScalafmtConfig): Option[OptionalBracesRegion] = { def funcSplit(arg: Term.FunctionTerm)(implicit fl: FileLine) = { val end = tokens.getLast(arg) @@ -1995,7 +1995,7 @@ class FormatOps( private object BlockImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = { val leftOwner = ft.meta.leftOwner findTreeWithParentSimple(nft.meta.rightOwner)(_ eq leftOwner) match { @@ -2013,7 +2013,7 @@ class FormatOps( private object RightParenImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case ParamClauseParent(t: Defn.ExtensionGroup) if isBlockStart(t.body, nft) => @@ -2053,7 +2053,7 @@ class FormatOps( private object RightArrowImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t: Case => // unsupported except for right brace Some(new OptionalBracesRegion { @@ -2067,7 +2067,7 @@ class FormatOps( private object ForImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t @ Term.For(enums, _) if isSeqMulti(enums) => Some(new OptionalBracesRegion { @@ -2087,7 +2087,7 @@ class FormatOps( private object WhileImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t @ Term.While(b: Term.Block, _) if !matchingOpt(nft.right).exists(_.end >= b.pos.end) => @@ -2106,7 +2106,7 @@ class FormatOps( private object DoImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t @ Term.While(_, body) => Some(new OptionalBracesRegion { def owner = Some(t) @@ -2124,7 +2124,7 @@ class FormatOps( private object EqualsImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t: Ctor.Secondary => Some(new OptionalBracesRegion { def owner = Some(t) @@ -2138,7 +2138,7 @@ class FormatOps( def owner = Some(t) def splits = getSplitsForStats(ft, nft, x.cases, nlOnly = true) def rightBrace = treeLast(x) - } + }, ) case _ => BlockImpl.create(ft, nft) } @@ -2146,7 +2146,7 @@ class FormatOps( private object TryImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = { def trySplits(expr: Term, finallyp: Option[Term], usesOB: => Boolean) = if (!isTreeSingleExpr(expr)) Some(getSplits(ft, expr, true)) @@ -2160,14 +2160,14 @@ class FormatOps( def splits = trySplits(expr, finallyp, isCatchUsingOptionalBraces(t)) def rightBrace = blockLast(expr) - } + }, ) case t @ Term.TryWithHandler(expr, _, finallyp) => Some( new OptionalBracesRegion { def owner = Some(t) def splits = trySplits(expr, finallyp, false) def rightBrace = blockLast(expr) - } + }, ) case _ => None } @@ -2179,7 +2179,7 @@ class FormatOps( private object CatchImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t @ Term.Try(_, catchp, _) => Some(new OptionalBracesRegion { def owner = Some(t) @@ -2192,7 +2192,7 @@ class FormatOps( private object FinallyImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = { val lo = ft.meta.leftOwner def createImpl(usingOB: => Boolean)(finallyExpr: Tree) = { @@ -2219,7 +2219,7 @@ class FormatOps( private object MatchImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = { def result(tree: Tree, cases: Seq[Tree]): Option[Seq[Split]] = if (tokens.tokenJustBeforeOpt(cases).contains(nft)) @@ -2243,7 +2243,7 @@ class FormatOps( private object ThenImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t: Term.If => Some(new OptionalBracesRegion { def owner = Some(t) @@ -2256,7 +2256,7 @@ class FormatOps( private object IfImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t: Term.If => val nr = nft.right @@ -2282,7 +2282,7 @@ class FormatOps( private object ElseImpl extends Factory { def create(ft: FormatToken, nft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[OptionalBracesRegion] = ft.meta.leftOwner match { case t: Term.If => (t.elsep match { case _: Term.If => None @@ -2310,7 +2310,7 @@ class FormatOps( ft: FormatToken, nft: FormatToken, tree: Tree, - danglingKeyword: Boolean = true + danglingKeyword: Boolean = true, )(implicit fileLine: FileLine, style: ScalafmtConfig): Seq[Split] = { val forceNL = !hasSingleTermStatIfBlock(tree) || shouldBreakInOptionalBraces(nft) @@ -2322,7 +2322,7 @@ class FormatOps( nft: FormatToken, head: => Tree, tail: Seq[Tree], - nlOnly: Boolean = false + nlOnly: Boolean = false, )(implicit fileLine: FileLine, style: ScalafmtConfig): Option[Seq[Split]] = if (tokens.tokenJustBeforeOpt(head).contains(nft)) Some { val forceNL = nlOnly || shouldBreakInOptionalBraces(ft) @@ -2334,7 +2334,7 @@ class FormatOps( ft: FormatToken, nft: FormatToken, trees: Seq[Tree], - nlOnly: Boolean = false + nlOnly: Boolean = false, )(implicit fileLine: FileLine, style: ScalafmtConfig): Option[Seq[Split]] = trees.headOption.flatMap { head => getSplitsForStatsImpl(ft, nft, head, trees.tail, nlOnly) @@ -2343,7 +2343,7 @@ class FormatOps( private def getSplitsForIf( ft: FormatToken, nft: FormatToken, - t: Term.If + t: Term.If, )(implicit fileLine: FileLine, style: ScalafmtConfig): Seq[Split] = { def nestedIf(x: Term.If) = { val forceNL = shouldBreakInOptionalBraces(nft) || @@ -2383,7 +2383,7 @@ class FormatOps( } private def shouldBreakInOptionalBraces( - ft: FormatToken + ft: FormatToken, )(implicit style: ScalafmtConfig): Boolean = style.newlines.source match { case Newlines.unfold => true case Newlines.keep => ft.hasBreak @@ -2416,7 +2416,7 @@ class FormatOps( def indentAndBreakBeforeCtrl[A](tree: Tree, split: Split)(implicit style: ScalafmtConfig, - classifier: Classifier[T, A] + classifier: Classifier[T, A], ): Option[Split] = if ( !style.dialect.allowSignificantIndentation || @@ -2625,7 +2625,7 @@ class FormatOps( .getLastNonTrivialOpt(tree).map(_.left) def getEndOfBlock(ft: FormatToken, parensToo: Boolean)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[T] = ft.left match { case x: T.LeftBrace => matchingOpt(x) case x: T.LeftParen => if (parensToo) matchingOpt(x) else None @@ -2644,7 +2644,7 @@ class FormatOps( } def rightIsCloseDelimToAddTrailingComma(left: T, ft: => FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = style.getTrailingCommas match { case TrailingCommas.keep => left.is[T.Comma] && TreeOps.rightIsCloseDelimForTrailingComma(left, ft) @@ -2658,7 +2658,7 @@ class FormatOps( } def getMustDangleForTrailingCommas(getCloseFt: => FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = !style.rewrite.trailingCommas.allowFolding && { val closeFt = getCloseFt val beforeClose = @@ -2685,7 +2685,7 @@ object FormatOps { case class TemplateSupertypeGroup( superType: Tree, superTypeGroup: Seq[Tree], - expireTokenFunc: Seq[Tree] => T + expireTokenFunc: Seq[Tree] => T, ) { def getExpireToken = expireTokenFunc(superTypeGroup) def isSecond = superTypeGroup.drop(1).headOption.contains(superType) @@ -2703,12 +2703,12 @@ object FormatOps { } def getOpenParenAlignIndents( - end: T + end: T, )(implicit style: ScalafmtConfig): Seq[Indent] = if (style.align.closeParenSite) Seq( Indent(Length.StateColumn, end, ExpiresOn.After), Indent(Length.Num(1), end, ExpiresOn.Before), - Indent(Length.Num(-1), end, ExpiresOn.After) + Indent(Length.Num(-1), end, ExpiresOn.After), ) else Seq(Indent(Length.StateColumn, end, ExpiresOn.Before)) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatToken.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatToken.scala index af85983c65..49d9998f1f 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatToken.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatToken.scala @@ -87,7 +87,7 @@ object FormatToken { idx: Int, formatOff: Boolean, left: TokenMeta, - right: TokenMeta + right: TokenMeta, ) { @inline def leftOwner: Tree = left.owner 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 e61a7cd881..775cb99cb4 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 @@ -32,8 +32,8 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken] val idx = leftTok2tok.getOrElse( FormatTokens.thash(tok), throw new NoSuchElementException( - s"Missing token index [${tok.start}:${tok.end}]: `$tok`" - ) + s"Missing token index [${tok.start}:${tok.end}]: `$tok`", + ), ) if (idx >= arr.length) arr.last else { @@ -80,8 +80,8 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken] def matching(token: Token): Token = matchingParentheses.getOrElse( FormatTokens.thash(token), throw new NoSuchElementException( - s"Missing matching token index [${token.start}:${token.end}]: `$token`" - ) + s"Missing matching token index [${token.start}:${token.end}]: `$token`", + ), ) @inline def matchingOpt(token: Token): Option[Token] = matchingParentheses @@ -97,7 +97,7 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken] def getDelimsIfEnclosed( tokens: Tokens, - tree: Tree + tree: Tree, ): Option[(FormatToken, FormatToken)] = getHeadOpt(tokens, tree) .flatMap { head => matchingOpt(head.left).flatMap { other => @@ -131,7 +131,7 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken] .isDefined def getClosingIfInParens( - last: FormatToken + last: FormatToken, )(head: FormatToken): Option[FormatToken] = if (areMatchingParens(last.left)(head.left)) Some(prev(last)) else { @@ -154,7 +154,7 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken] @tailrec final def findTokenWith[A](ft: FormatToken, iter: FormatToken => FormatToken)( - f: FormatToken => Option[A] + f: FormatToken => Option[A], ): Either[FormatToken, A] = f(ft) match { case Some(a) => Right(a) case _ => @@ -163,7 +163,7 @@ class FormatTokens(leftTok2tok: Map[TokenHash, Int])(val arr: Array[FormatToken] } final def findToken(ft: FormatToken, iter: FormatToken => FormatToken)( - f: FormatToken => Boolean + f: FormatToken => Boolean, ): FormatToken = findTokenWith(ft, iter)(Some(_).filter(f)).merge final def nextNonCommentSameLine(curr: FormatToken): FormatToken = @@ -309,7 +309,7 @@ object FormatTokens { * possible. */ def apply(tokens: Tokens, owner: Token => Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): (FormatTokens, StyleMap) = { var left: Token = null var lmeta: FormatToken.TokenMeta = null 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 f1689c2f49..18723e9d25 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 @@ -192,7 +192,7 @@ class FormatWriter(formatOps: FormatOps) { loc.copy( replace = "(", shift = loc.shift - 1, - state = state.copy(prev = prevBegState, split = split) + state = state.copy(prev = prevBegState, split = split), ) } @@ -213,7 +213,7 @@ class FormatWriter(formatOps: FormatOps) { val endLoc = locations(end) locations(end) = endLoc.copy( replace = ")", - state = endLoc.state.copy(prev = newPrevEndState) + state = endLoc.state.copy(prev = newPrevEndState), ) case _ => } @@ -225,7 +225,7 @@ class FormatWriter(formatOps: FormatOps) { private def getOptionalBracesOwner( floc: FormatLocation, - minBlockStats: Int + minBlockStats: Int, ): Option[Tree] = { val ob = formatOps.OptionalBraces.get(floc.formatToken)(floc.style) ob.flatMap(_.owner).filter { @@ -401,7 +401,7 @@ class FormatWriter(formatOps: FormatOps) { locations(end) = eLoc.copy( missingBracesOpenOrTuck = !addLine && (eLoc.missingBracesIndent.isEmpty || eLoc.missingBracesOpenOrTuck), - missingBracesIndent = eLoc.missingBracesIndent + begIndent + missingBracesIndent = eLoc.missingBracesIndent + begIndent, ) } } @@ -431,7 +431,7 @@ class FormatWriter(formatOps: FormatOps) { def prevState = curr.state.prev private def appendWhitespace(alignOffset: Int, delayedAlign: Int)(implicit - sb: StringBuilder + sb: StringBuilder, ): Int = { val mod = state.split.modExt.mod def currentAlign = tokenAligns.get(i).fold(0)(_ + alignOffset) @@ -469,7 +469,7 @@ class FormatWriter(formatOps: FormatOps) { @tailrec def iter( floc: FormatLocation, - hadNL: Boolean + hadNL: Boolean, ): Option[FormatToken] = { val isNL = floc.hasBreakAfter if (isNL && !whenNL) None @@ -569,7 +569,7 @@ class FormatWriter(formatOps: FormatOps) { } private def formatOnelineDocstring( - text: String + text: String, )(implicit sb: StringBuilder): Boolean = curr.isStandalone && { val matcher = onelineDocstring.matcher(text) matcher.matches() && @@ -591,7 +591,7 @@ class FormatWriter(formatOps: FormatOps) { } private def formatDocstring( - text: String + text: String, )(implicit sb: StringBuilder): Unit = if (style.docstrings.style eq Docstrings.Preserve) sb.append(text) else if (!formatOnelineDocstring(text)) new FormatMlDoc(text).format() @@ -599,7 +599,7 @@ class FormatWriter(formatOps: FormatOps) { private abstract class FormatCommentBase( protected val maxColumn: Int, protected val extraIndent: Int = 1, - protected val leadingMargin: Int = 0 + protected val leadingMargin: Int = 0, )(implicit sb: StringBuilder) { protected final val breakBefore = curr.hasBreakBefore protected final val indent = prevState.indentation @@ -622,19 +622,19 @@ class FormatWriter(formatOps: FormatOps) { protected class WordFormatter( appendLineBreak: () => Unit, extraMargin: String = " ", - prefixFirstWord: String => String = _ => "" + prefixFirstWord: String => String = _ => "", ) { final def apply( iter: WordIter, lineLength: Int, atLineBeg: Boolean, - needSpaceIfAtLineBeg: Boolean = true + needSpaceIfAtLineBeg: Boolean = true, ): Int = iterate( iter, sb.length - lineLength, 0, atLineBeg, - needSpaceIfAtLineBeg + needSpaceIfAtLineBeg, ) @tailrec @@ -643,7 +643,7 @@ class FormatWriter(formatOps: FormatOps) { lineBeg: Int, linesSoFar: Int, atLineBeg: Boolean = false, - needSpaceIfAtLineBeg: Boolean = false + needSpaceIfAtLineBeg: Boolean = false, ): Int = if (iter.hasNext) { val word = iter.next() @@ -781,7 +781,7 @@ class FormatWriter(formatOps: FormatOps) { private def iterParagraphs( iter: ParaIter, firstLineLen: Int, - atLineBeg: Boolean + atLineBeg: Boolean, ): Int = { var lines = wf(iter.next(), firstLineLen, atLineBeg) while (iter.hasNext) { @@ -805,14 +805,14 @@ class FormatWriter(formatOps: FormatOps) { } private class FormatMlDoc(isWrap: Boolean)(text: String)(implicit - sb: StringBuilder + sb: StringBuilder, ) extends FormatCommentBase( if (isWrap) style.docstringsWrapMaxColumn else style.maxColumn, if (style.docstrings.style eq Docstrings.SpaceAsterisk) 2 else 1, - if (style.docstrings.style eq Docstrings.AsteriskSpace) 1 else 0 + if (style.docstrings.style eq Docstrings.AsteriskSpace) 1 else 0, ) { def this(text: String)(implicit sb: StringBuilder) = this( - (style.docstrings.wrap eq Docstrings.Wrap.yes) && curr.isStandalone + (style.docstrings.wrap eq Docstrings.Wrap.yes) && curr.isStandalone, )(text) private val spaces: String = getIndentation(indent + extraIndent) @@ -848,7 +848,7 @@ class FormatWriter(formatOps: FormatOps) { private def formatTerm( term: Scaladoc.Term, termIndent: String, - sbNonEmpty: Boolean + sbNonEmpty: Boolean, ): Unit = { def forceFirstLine(): Unit = { // don't output on top line @@ -908,7 +908,7 @@ class FormatWriter(formatOps: FormatOps) { private def formatTextAfterMargin( text: Scaladoc.Text, - termIndent: String + termIndent: String, ): Unit = { def prefixFirstWord(word: String): String = { def likeNonText = word.startsWith("```") || @@ -931,7 +931,7 @@ class FormatWriter(formatOps: FormatOps) { nested: Boolean, code: Seq[String], termIndent: String, - isRelative: Boolean + isRelative: Boolean, ): Unit = { val ok = nested && formatScalaCodeBlock(code, termIndent) if (!ok) formatCodeBlock(code, termIndent, isRelative) @@ -940,7 +940,7 @@ class FormatWriter(formatOps: FormatOps) { private def formatCodeBlock( code: Seq[String], termIndent: String, - isRelative: Boolean + isRelative: Boolean, ): Unit = { val offsetOpt = if (isRelative) None @@ -975,13 +975,13 @@ class FormatWriter(formatOps: FormatOps) { private def formatScalaCodeBlock( code: Seq[String], - termIndent: String + termIndent: String, ): Boolean = { val codeStyle = style.copy( runner = style.runner.forCodeBlock, // let's not wrap docstrings, to avoid recursion docstrings = style.docstrings.withoutRewrites, - maxColumn = style.maxColumn - spaces.length - termIndent.length - 1 + maxColumn = style.maxColumn - spaces.length - termIndent.length - 1, ) Scalafmt.format(code.mkString("\n"), codeStyle) match { case Formatted.Success(res) => @@ -993,7 +993,7 @@ class FormatWriter(formatOps: FormatOps) { } private def formatListBlock( - listIndent: String + listIndent: String, )(block: Scaladoc.ListBlock): Unit = { val prefix = block.prefix val itemIndent = getIndentation(listIndent.length + prefix.length + 1) @@ -1004,7 +1004,7 @@ class FormatWriter(formatOps: FormatOps) { } private def formatListTerm( - itemIndent: String + itemIndent: String, )(item: Scaladoc.ListItem): Unit = { formatTextAfterMargin(item.text, itemIndent) item.terms.foreach(formatTerm(_, itemIndent, sbNonEmpty = true)) @@ -1137,7 +1137,7 @@ class FormatWriter(formatOps: FormatOps) { def appendCandidate() = columnCandidates += new AlignStop( getAlignColumn(floc) + columnShift, floc, - getAlignHashKey(floc) + getAlignHashKey(floc), ) if (alignContainer eq null) alignContainer = container else if (alignContainer ne container) { @@ -1177,7 +1177,7 @@ class FormatWriter(formatOps: FormatOps) { wasSameContainer(alignContainer), block.refStops, candidates, - location.formatToken + location.formatToken, ) if (matches > 0) appendToBlock(matches) if (isBlankLine || matches == 0 && shouldFlush(alignContainer)) { @@ -1191,7 +1191,7 @@ class FormatWriter(formatOps: FormatOps) { } if (isBlankLine || alignContainer.eq(null)) getBlockToFlush( getAlignContainer(location.formatToken.meta.rightOwner), - isBlankLine + isBlankLine, ).foreach(flushAlignBlock) } blocks.valuesIterator.foreach(flushAlignBlock) @@ -1235,7 +1235,7 @@ class FormatWriter(formatOps: FormatOps) { @tailrec private def getAlignContainerParent( child: Tree, - maybeParent: Option[Tree] = None + maybeParent: Option[Tree] = None, )(implicit fl: FormatLocation): Tree = maybeParent.orElse(child.parent) match { case Some(AlignContainer(p)) => p @@ -1307,14 +1307,14 @@ class FormatWriter(formatOps: FormatOps) { } private def flushAlignBlock( - block: AlignBlock + block: AlignBlock, )(implicit builder: mutable.Builder[(Int, Int), Map[Int, Int]]): Unit = { if (block.hasMultiple) flushMultiEntryAlignBlock(block) block.clear() } private def flushMultiEntryAlignBlock( - block: AlignBlock + block: AlignBlock, )(implicit builder: mutable.Builder[(Int, Int), Map[Int, Int]]): Unit = { val endIndex = locations.length - 1 block.foreach { x => @@ -1378,7 +1378,7 @@ class FormatWriter(formatOps: FormatOps) { def setStat( stat: Tree, idx: Int, - isLast: Boolean + isLast: Boolean, ): Option[(Int, Newlines.NumBlanks)] = setStats(idx, stat, stat, isLast) def blanks(cnt: => Int, edge: Boolean, edgeCnt: => Option[Int]): Int = if (edge) edgeCnt.getOrElse(math.min(cnt, 1)) else cnt @@ -1392,7 +1392,7 @@ class FormatWriter(formatOps: FormatOps) { idx: Int, stat: Tree, statLast: Tree, - isLast: Boolean + isLast: Boolean, ): Option[(Int, Newlines.NumBlanks)] = getBlanks(stat, statLast, nest) .map { case (x, head, last) => val beforeCnt = blanksBefore(x, notUnindentedPkg && idx == 0) @@ -1408,7 +1408,7 @@ class FormatWriter(formatOps: FormatOps) { stat: Term.EndMarker, prevIdx: Int, prevBlanks: Newlines.NumBlanks, - isLast: Boolean + isLast: Boolean, ): Unit = { val last = tokens.getLast(stat) if (prevBlanks.beforeEndMarker <= 0) extraBlankMap.remove(prevIdx) @@ -1422,7 +1422,7 @@ class FormatWriter(formatOps: FormatOps) { rest: Seq[Stat], idx: Int, previous: Option[(Int, Newlines.NumBlanks)], - imports: Option[(Int, ImportExportStat, ImportExportStat)] + imports: Option[(Int, ImportExportStat, ImportExportStat)], ): Unit = { val stat = rest.head val newRest = rest.tail @@ -1546,7 +1546,7 @@ class FormatWriter(formatOps: FormatOps) { def getBlanks( statHead: Tree, statLast: Tree, - nest: Int + nest: Int, ): Option[(Newlines.NumBlanks, FormatToken, FormatToken)] = { val head = tokens.tokenJustBefore(statHead) val last = tokens.getLast(statLast) @@ -1586,7 +1586,7 @@ class FormatWriter(formatOps: FormatOps) { sameOwner: Boolean, a: Seq[AlignStop], b: Seq[AlignStop], - eol: FormatToken + eol: FormatToken, ): Int = { val endOfLineOwner = eol.meta.rightOwner @tailrec @@ -1630,7 +1630,7 @@ object FormatWriter { // if indent is empty, indicates open; otherwise, whether to tuck missingBracesOpenOrTuck: Boolean = false, missingBracesIndent: Set[Int] = Set.empty, - replace: String = null + replace: String = null, ) { def hasBreakAfter: Boolean = state.split.isNL def hasBreakBefore: Boolean = @@ -1651,7 +1651,7 @@ object FormatWriter { buffer: mutable.ArrayBuffer[AlignLine] = new mutable.ArrayBuffer[AlignLine], var refStops: Seq[AlignStop] = Seq.empty, - var stopColumns: IndexedSeq[Int] = IndexedSeq.empty + var stopColumns: IndexedSeq[Int] = IndexedSeq.empty, ) { def appendToEmptyBlock(line: AlignLine): Unit = { val stops = line.stops @@ -1882,7 +1882,7 @@ object FormatWriter { private def getLineDiff( toks: Array[FormatLocation], beg: FormatToken, - end: FormatToken + end: FormatToken, ): Int = getLineDiff(toks(beg.meta.idx), toks(end.meta.idx)) def isEmptyDocstring(text: String): Boolean = emptyDocstring.matcher(text) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Indent.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Indent.scala index 46da7bfc7d..45b49b4566 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Indent.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Indent.scala @@ -52,7 +52,7 @@ case class ActualIndent( length: Int, expireEnd: Int, expiresAt: ExpiresOn, - reset: Boolean + reset: Boolean, ) { @inline def notExpiredBy(ft: FormatToken): Boolean = expiresAt @@ -90,8 +90,8 @@ private class IndentImpl(length: Length, expire: Token, expiresAt: ExpiresOn) length.withStateOffset(offset), expire.end, expiresAt, - length.reset - ) + length.reset, + ), ) override def toString: String = { val when = if (expiresAt == ExpiresOn.Before) '<' else '>' diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/ModExt.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/ModExt.scala index 363a431f31..6ff2fbcffd 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/ModExt.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/ModExt.scala @@ -23,7 +23,7 @@ case class ModExt(mod: Modification, indents: Seq[Indent] = Seq.empty) { def withIndentOpt( length: => Length, expire: Option[Token], - when: ExpiresOn + when: ExpiresOn, ): ModExt = expire.fold(this)(withIndent(length, _, when)) def withIndent(indent: => Indent): ModExt = indent match { diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Modification.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Modification.scala index 5f46b5cca2..c5953bdac9 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Modification.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Modification.scala @@ -34,7 +34,7 @@ case object NoSplit extends Modification { case class NewlineT( isDouble: Boolean = false, noIndent: Boolean = false, - alt: Option[ModExt] = None + alt: Option[ModExt] = None, ) extends Modification { override def toString = { val double = if (isDouble) "Double" else "" 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 0244a27dd4..10b6d572d3 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 @@ -60,28 +60,28 @@ object Policy { } def apply(endPolicy: End.WithPos, noDequeue: Boolean = false, rank: Int = 0)( - f: Pf + f: Pf, )(implicit fileLine: FileLine): Policy = new ClauseImpl(f, endPolicy, noDequeue, rank) def after(token: Token, noDequeue: Boolean = false, rank: Int = 0)(f: Pf)( - implicit fileLine: FileLine + implicit fileLine: FileLine, ): Policy = apply(End.After(token), noDequeue, rank)(f) def before(token: Token, noDequeue: Boolean = false, rank: Int = 0)(f: Pf)( - implicit fileLine: FileLine + implicit fileLine: FileLine, ): Policy = apply(End.Before(token), noDequeue, rank)(f) def after(trigger: Token, policy: Policy)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = new Switch(NoPolicy, trigger, policy) def before(policy: Policy, trigger: Token)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = new Switch(policy, trigger, NoPolicy) def on(token: Token, noDequeue: Boolean = false)(f: Pf)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = apply(End.On(token), noDequeue)(f) abstract class Clause(implicit val fileLine: FileLine) extends Policy { @@ -105,7 +105,7 @@ object Policy { val f: Policy.Pf, val endPolicy: End.WithPos, val noDequeue: Boolean, - val rank: Int = 0 + val rank: Int = 0, )(implicit fileLine: FileLine) extends Clause @@ -132,7 +132,7 @@ object Policy { override lazy val f: Pf = { case x => p2.f.applyOrElse( p1.f.andThen(x.withSplits _).applyOrElse(x, identity[Decision]), - (y: Decision) => y.splits + (y: Decision) => y.splits, ) } @@ -153,7 +153,7 @@ object Policy { } class Delay(policy: Policy, begPolicy: End.WithPos)(implicit - fileLine: FileLine + fileLine: FileLine, ) extends Policy { override def f: Pf = PartialFunction.empty override def rank: Int = 0 @@ -170,7 +170,7 @@ object Policy { object Delay { def apply(policy: Policy, begPolicy: End.WithPos)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = if (policy.isEmpty) policy else new Delay(policy, begPolicy) } @@ -195,7 +195,7 @@ object Policy { object Relay { def apply(before: Policy, after: Policy)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = if (before.isEmpty) after else if (after.isEmpty) before @@ -203,7 +203,7 @@ object Policy { } class Switch(before: Policy, trigger: Token, after: Policy)(implicit - fileLine: FileLine + fileLine: FileLine, ) extends Policy { override def f: Pf = before.f override def rank: Int = before.rank @@ -224,7 +224,7 @@ object Policy { object Proxy { def apply(policy: Policy, end: End.WithPos)( - factory: Policy => Pf + factory: Policy => Pf, )(implicit fileLine: FileLine): Policy = if (policy.isEmpty) NoPolicy else new Proxy(policy, factory, end) } @@ -232,7 +232,7 @@ object Policy { private class Proxy( policy: Policy, factory: Policy => Policy.Pf, - override val endPolicy: End.WithPos + override val endPolicy: End.WithPos, )(implicit fileLine: FileLine) extends Policy.Clause { override val f: Pf = factory(policy) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/PolicySummary.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/PolicySummary.scala index a78ef100ea..71197f6ef6 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/PolicySummary.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/PolicySummary.scala @@ -13,7 +13,7 @@ class PolicySummary(val policies: Seq[Policy]) extends AnyVal { def combine(other: Policy, ft: FormatToken): PolicySummary = if (ft.right.is[Token.EOF]) PolicySummary.empty else new PolicySummary( - (other +: policies).flatMap(_.unexpiredOpt(ft)).sortBy(_.rank) + (other +: policies).flatMap(_.unexpiredOpt(ft)).sortBy(_.rank), ) def execute(decision: Decision, debug: Boolean = false): Decision = policies 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 ba954f9666..10162ccc54 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 @@ -56,7 +56,7 @@ class Router(formatOps: FormatOps) { nextAfterNonComment, nextNonCommentAfter, prevNonCommentSameLine, - nextNonCommentSameLine + nextNonCommentSameLine, } private def getSplitsImpl(implicit formatToken: FormatToken): Seq[Split] = { @@ -72,7 +72,7 @@ class Router(formatOps: FormatOps) { Seq(Split(NoSplit.orNL(next(ft).right.is[T.EOF]), 0)) case FormatToken(_: T.BOF, _, _) => Seq(Split(NoSplit, 0)) case FormatToken(_, _: T.EOF, _) => Seq( - Split(Newline, 0) // End files with trailing newline + Split(Newline, 0), // End files with trailing newline ) case FormatToken(start: T.Interpolation.Start, _, m) => val end = matching(start) @@ -91,7 +91,7 @@ class Router(formatOps: FormatOps) { Seq( Indent(StateColumn, end, After), // -1 because of margin characters | - Indent(if (startsWithPipe) -1 else -2, end, After) + Indent(if (startsWithPipe) -1 else -2, end, After), ) } } @@ -104,13 +104,13 @@ class Router(formatOps: FormatOps) { _: T.Interpolation.Id | _: T.Interpolation.Part | _: T.Interpolation.Start | _: T.Interpolation.SpliceStart, _, - _ + _, ) => Seq(Split(NoSplit, 0)) case FormatToken( _, T.Interpolation.Part(_) | T.Interpolation.End() | T.Interpolation .SpliceEnd(), - _ + _, ) => Seq(Split(NoSplit, 0)) case FormatToken(T.LeftBrace(), T.RightBrace(), _) => Seq(Split(NoSplit, 0)) @@ -125,7 +125,7 @@ class Router(formatOps: FormatOps) { val beforeClose = tokens.justBefore(close) val policy = SingleLineBlock( close, - okSLC = style.importSelectors eq ImportSelectors.singleLine + okSLC = style.importSelectors eq ImportSelectors.singleLine, ) val newlineBeforeClosingCurly = decideNewlinesOnlyBeforeClose(close) @@ -147,7 +147,7 @@ class Router(formatOps: FormatOps) { .notIf(mustUseNL || mustDangleForTrailingCommas).withPolicy(policy), Split(Newline, 1).onlyIf(newlinePolicy ne NoPolicy) .withPolicy(newlinePolicy) - .withIndent(style.indent.main, close, Before) + .withIndent(style.indent.main, close, Before), ) case FormatToken(_, _: T.RightBrace, _) if existsParentOfType[ImportExportStat](rightOwner) => @@ -162,7 +162,7 @@ class Router(formatOps: FormatOps) { Seq( Indent(Length.StateColumn, close, ExpiresOn.After), Indent(Length.Num(style.indent.main), close, ExpiresOn.Before), - Indent(Length.Num(-1), close, ExpiresOn.After) + Indent(Length.Num(-1), close, ExpiresOn.After), ) } else None @@ -212,7 +212,7 @@ class Router(formatOps: FormatOps) { _: T.KwThrow | _: T.KwTry | _: T.KwCatch | _: T.KwFinally | _: T.KwFor | _: T.KwDo | _: T.KwWhile | _: T.KwYield | _: T.KwIf, _, - OptionalBraces(splits) + OptionalBraces(splits), ) if dialect.allowSignificantIndentation => splits // { ... } Blocks @@ -234,7 +234,7 @@ class Router(formatOps: FormatOps) { else { val double = tok.hasBlankLine || !isSelfAnnotationNL && rightIsComment && blankLineBeforeDocstring( - tok + tok, ) NewlineT(double) } @@ -377,7 +377,7 @@ class Router(formatOps: FormatOps) { .onlyIf(lambdaNLOnly.contains(false) && lambdaPolicy != null) .notIf(style.newlines.keepBreak(newlines)) .withOptimalTokenOpt(lambdaArrow) - .withIndent(lambdaIndent, close, Before).withPolicy(lambdaPolicy) + .withIndent(lambdaIndent, close, Before).withPolicy(lambdaPolicy), ) right match { case t: T.Xml.Start => withIndentOnXmlStart(t, splits) @@ -387,7 +387,7 @@ class Router(formatOps: FormatOps) { case FormatToken( T.RightArrow() | T.ContextArrow(), _, - StartsStatementRight(stmt) + StartsStatementRight(stmt), ) if leftOwner.isInstanceOf[Term.FunctionTerm] => val leftFunc = leftOwner.asInstanceOf[Term.FunctionTerm] val (afterCurlySpace, afterCurlyNewlines) = @@ -399,14 +399,14 @@ class Router(formatOps: FormatOps) { (!rightOwner.is[Defn] || style.newlines.source.eq(Newlines.fold)) ) Split(Space, 0).withSingleLineNoOptimal( getOptimalTokenFor(getLastNonTrivial(leftFunc.body).left), - noSyntaxNL = true + noSyntaxNL = true, ) else Split.ignored val (endIndent, expiresOn) = functionExpire(leftFunc) Seq( spaceSplit, Split(afterCurlyNewlines, 1) - .withIndent(style.indent.main, endIndent, expiresOn) + .withIndent(style.indent.main, endIndent, expiresOn), ) case FormatToken(_: T.RightArrow | _: T.ContextArrow, right, _) @@ -478,7 +478,7 @@ class Router(formatOps: FormatOps) { Split(Space, 0) .withIndent(spaceIndent, endOfFunction, expiresOn) .withOptimalToken(getOptimalTokenFor(next(nonComment))), - newlineSplit + newlineSplit, ) } } @@ -500,7 +500,7 @@ class Router(formatOps: FormatOps) { CtrlBodySplits.checkComment(tok, nlSplit(tok)) { ft => def withSlbSplit(implicit l: FileLine) = Seq( baseSplit.withSingleLine(getLastNonTrivialToken(body)), - nlSplit(ft)(1)(nextLine) + nlSplit(ft)(1)(nextLine), ) val beforeMultiline = style.newlines.getBeforeMultiline if (isCaseBodyABlock(ft, owner)) Seq(baseSplit) @@ -533,13 +533,13 @@ class Router(formatOps: FormatOps) { Seq( spaceSplit, // For some reason, this newline cannot cost 1. - Split(NewlineT(isDouble = tok.hasBlankLine), 0) + Split(NewlineT(isDouble = tok.hasBlankLine), 0), ) case FormatToken( _: T.RightParen, _, - ParamClauseParentLeft(extGroup: Defn.ExtensionGroup) + ParamClauseParentLeft(extGroup: Defn.ExtensionGroup), ) if !LeftParenOrBrace.unapply(nextNonComment(formatToken).right) => val expireToken = getLastToken(extGroup) def nlSplit(cost: Int = 0)(implicit fileLine: FileLine) = @@ -570,8 +570,8 @@ class Router(formatOps: FormatOps) { formatToken, Some( if (left.is[T.Comment] && tok.noBreak) Space - else NewlineT(isDouble = tok.hasBlankLine) - ) + else NewlineT(isDouble = tok.hasBlankLine), + ), ) { val spaceCouldBeOk = annoLeft && (style.newlines.source match { @@ -587,13 +587,13 @@ class Router(formatOps: FormatOps) { // This split needs to have an optimalAt field. Split(Space, 0).onlyIf(spaceCouldBeOk).withSingleLine(expire), // For some reason, this newline cannot cost 1. - Split(NewlineT(isDouble = tok.hasBlankLine), 0) + Split(NewlineT(isDouble = tok.hasBlankLine), 0), ) } case FormatToken(_, T.RightBrace(), _) => Seq( Split(xmlSpace(rightOwner), 0), - Split(NewlineT(isDouble = formatToken.hasBlankLine), 0) + Split(NewlineT(isDouble = formatToken.hasBlankLine), 0), ) case FormatToken(_: T.KwPackage, _, _) if leftOwner.is[Pkg] => Seq(Split(Space, 0)) @@ -640,7 +640,7 @@ class Router(formatOps: FormatOps) { def getSplitsBeforeOpenParen( src: Newlines.SourceHints, indentLen: Int, - shouldAlignBefore: Align => Boolean + shouldAlignBefore: Align => Boolean, )(lastSyntaxClause: => Option[Member.SyntaxValuesClause]) = { val close = matching(open) val indent = Indent(indentLen, close, ExpiresOn.After) @@ -672,8 +672,8 @@ class Router(formatOps: FormatOps) { baseNoSplit.withSingleLine(slbEnd), Split(Newline, 1).withIndent(indent).withPolicy( penalizeNewlineByNesting(open, close), - multipleArgs - ).andPolicy(nlPolicy) + multipleArgs, + ).andPolicy(nlPolicy), ) case Newlines.keep => if (newlines != 0) Seq(Split(Newline, 0).withIndent(indent)) @@ -690,14 +690,14 @@ class Router(formatOps: FormatOps) { } Seq( noSplitSplit, - Split(Newline, 1).withIndent(indent).withPolicyOpt(nlColonPolicy) + Split(Newline, 1).withIndent(indent).withPolicyOpt(nlColonPolicy), ) } val argsOpt = if (isAlignFirstParen) lastSyntaxClause else None argsOpt.flatMap(getLastTokenOpt).fold(splits) { x => val noSplitIndents = Seq( Indent(StateColumn, x, ExpiresOn.Before), - Indent(-indentLen, x, ExpiresOn.Before) + Indent(-indentLen, x, ExpiresOn.Before), ) splits.map(s => if (s.isNL) s else s.withIndents(noSplitIndents)) } @@ -749,7 +749,7 @@ class Router(formatOps: FormatOps) { case FormatToken( _: T.KwObject | _: T.KwClass | _: T.KwTrait | _: T.KwEnum, _, - WithTemplateOnLeft(template) + WithTemplateOnLeft(template), ) => def expire = getTemplateGroups(template) .flatMap(_.last.headOption.flatMap(_.tokens.headOption)) @@ -815,7 +815,7 @@ class Router(formatOps: FormatOps) { if (noSplitMod == null) Seq( Split(Newline, 0).withPolicyOpt(newlinePolicy) - .withIndent(style.indent.callSite, close, Before) + .withIndent(style.indent.callSite, close, Before), ) else { val newlinePenalty = 3 + nestedApplies(leftOwner) @@ -825,7 +825,7 @@ class Router(formatOps: FormatOps) { Split(noSplitMod, 0).withSingleLine(close), if (noMultiline) Split.ignored else multilineSpaceSplit, Split(Newline, newlinePenalty).withPolicyOpt(newlinePolicy) - .withIndent(style.indent.callSite, close, Before) + .withIndent(style.indent.callSite, close, Before), ) } @@ -956,7 +956,7 @@ class Router(formatOps: FormatOps) { Split(Newline, nestedPenalty + Constants.ExceedColumnPenalty) .withPolicy(newlinePolicy).withIndent(indent, close, Before), Split(NoSplit, nestedPenalty).withSingleLine(breakToken) - .andPolicy(newlinePolicy & newlineAfterAssignDecision) + .andPolicy(newlinePolicy & newlineAfterAssignDecision), ) } @@ -1004,8 +1004,8 @@ class Router(formatOps: FormatOps) { _, penalty = penalty, penalizeLambdas = multipleArgs, - noSyntaxNL = multipleArgs - ) + noSyntaxNL = multipleArgs, + ), ) } @@ -1031,7 +1031,7 @@ class Router(formatOps: FormatOps) { Split(noSplitMod, 0).withPolicy(oneArgOneLine & implicitPolicy) .withOptimalToken(right, killOnFail = true) .withIndent(extraOneArgPerLineIndent) - .withIndent(indent, close, Before) + .withIndent(indent, close, Before), ) else { val noSplitPolicy = @@ -1040,7 +1040,7 @@ class Router(formatOps: FormatOps) { SingleLineBlock( close, exclude = excludeBlocks, - noSyntaxNL = multipleArgs + noSyntaxNL = multipleArgs, ) else if (splitsForAssign.isDefined) singleLine(3) else singleLine(10) @@ -1053,11 +1053,11 @@ class Router(formatOps: FormatOps) { .withPolicy(oneArgOneLine & implicitPolicy).onlyIf( (notTooManyArgs && align) || (handleImplicit && - style.newlines.notBeforeImplicitParamListModifier) + style.newlines.notBeforeImplicitParamListModifier), ).withIndents( if (align) getOpenParenAlignIndents(close) - else Seq(Indent(indent, close, ExpiresOn.Before)) - ) + else Seq(Indent(indent, close, ExpiresOn.Before)), + ), ) } @@ -1081,7 +1081,7 @@ class Router(formatOps: FormatOps) { Split(NoSplit.orNL(noSplit), cost, policy = newlinePolicy) .andPolicy(singleLine(4), !noConfigStyle).andPolicyOpt( asInfixApp(args.head).map(InfixSplits(_, tok).nlPolicy), - !singleArgument + !singleArgument, ) } Seq(split.withIndent(indent, close, Before)) @@ -1161,7 +1161,7 @@ class Router(formatOps: FormatOps) { .withPolicy(noSplitPolicy).withIndents(noSplitIndents), Split(nlMod, if (mustUseNL || slbOnly) 0 else nlCost) .withPolicy(nlDanglePolicy & nlOnelinePolicy & penalizeBrackets) - .withIndent(indent) + .withIndent(indent), ) } @@ -1239,7 +1239,7 @@ class Router(formatOps: FormatOps) { val penalizeNewlinesPolicy = policyWithExclude(exclude, Policy.End.Before, Policy.End.On)( Policy.End.On(close), - new PenalizeAllNewlines(_, 3 + indentLen * bracketPenalty) + new PenalizeAllNewlines(_, 3 + indentLen * bracketPenalty), ) val noSplit = @@ -1307,7 +1307,7 @@ class Router(formatOps: FormatOps) { .withSingleLineOpt(if (singleLineOnly) Some(close) else None) .andPolicy(nlPolicy) .andPolicy(penalizeNewlinesPolicy, singleLineOnly) - .andPolicyOpt(singleArgAsInfix.map(InfixSplits(_, ft).nlPolicy)) + .andPolicyOpt(singleArgAsInfix.map(InfixSplits(_, ft).nlPolicy)), ) // Closing def site ): ReturnType @@ -1327,7 +1327,7 @@ class Router(formatOps: FormatOps) { Seq( Split(sameLineSplit, 0).onlyIf(newlines == 0 || x.ne(Newlines.keep)) .withSingleLine(expire), - Split(Newline, 1).withIndent(indent, expire, After) + Split(Newline, 1).withIndent(indent, expire, After), ) } bopSplits.getOrElse { @@ -1339,7 +1339,7 @@ class Router(formatOps: FormatOps) { // Spark style guide allows this: // https://github.com/databricks/scala-style-guide#indent Split(Newline, Constants.SparkColonNewline) - .withIndent(indent, expire, After).withPolicy(penalizeNewlines) + .withIndent(indent, expire, After).withPolicy(penalizeNewlines), ) } case FormatToken(_: T.Colon, _, DefDefReturnTypeLeft(returnType)) @@ -1376,7 +1376,7 @@ class Router(formatOps: FormatOps) { decideNewlinesOnlyAfterToken(breakAfter) Seq( Split(Newline, 0).withSingleLine(close, killOnFail = true), - Split(Space, 1, policy = multiLine) + Split(Space, 1, policy = multiLine), ) } val oneArgPerLineSplits = @@ -1388,7 +1388,7 @@ class Router(formatOps: FormatOps) { case FormatToken( _: T.MacroSplice | _: T.MacroQuote, _: T.LeftBrace | _: T.LeftBracket, - _ + _, ) => Seq(Split(NoSplit, 0)) case FormatToken(_: T.KwMatch, _, _) => val indentLen = style.indent.matchSite.fold(0)(_ - style.indent.main) @@ -1478,7 +1478,7 @@ class Router(formatOps: FormatOps) { Seq( Split(noSpace, 0)(Space) .withSingleLine(endOfSingleLineBlock(optFT), noSyntaxNL = true), - Split(Newline, 1).withPolicy(nlPolicy & indentOncePolicy) + Split(Newline, 1).withPolicy(nlPolicy & indentOncePolicy), ) } } @@ -1492,7 +1492,7 @@ class Router(formatOps: FormatOps) { val indent = style.indent.getDefnSite(leftOwner) Seq( Split(Space, 0), - Split(Newline, 1).withIndent(indent, right, After) + Split(Newline, 1).withIndent(indent, right, After), ) case _: Defn.RepeatedEnumCase if { if (!style.newlines.sourceIgnored) newlines != 0 @@ -1688,7 +1688,7 @@ class Router(formatOps: FormatOps) { Split(ignoreNoSplit, 0)(NoSplit) .withPolicy(slbPolicy, prevChain).andPolicy(penalizeBreaks), Split(if (ignoreNoSplit) Newline else nlMod, nlCost) - .withPolicy(newlinePolicy) + .withPolicy(newlinePolicy), ) } else { val isComment = left.is[T.Comment] @@ -1700,7 +1700,7 @@ class Router(formatOps: FormatOps) { else getNlMod }.withPolicy(breakOnNextDot) .onlyFor(SplitTag.SelectChainSecondNL), - Split(if (doBreak) Newline else Space(isComment), 0) + Split(if (doBreak) Newline else Space(isComment), 0), ) } @@ -1716,7 +1716,7 @@ class Router(formatOps: FormatOps) { Split(nlOnly, 0)(NoSplit) .withSingleLine(expire, noSyntaxNL = true), Split(NewlineT(alt = Some(NoSplit)), nlCost) - .withPolicyOpt(forcedBreakOnNextDotPolicy) + .withPolicyOpt(forcedBreakOnNextDotPolicy), ) case Newlines.fold => @@ -1737,7 +1737,7 @@ class Router(formatOps: FormatOps) { val policy = forcedBreakOnNextDotPolicy Seq( noSplitBase.withPolicyOpt(policy), - nlSplitBase.withPolicyOpt(policy) + nlSplitBase.withPolicyOpt(policy), ) } } @@ -1809,7 +1809,7 @@ class Router(formatOps: FormatOps) { enumCase.inits.headOption, getLastToken(rightOwner), style.indent.extendSite, - enumCase.inits.lengthCompare(1) > 0 + enumCase.inits.lengthCompare(1) > 0, ) // Template @@ -1823,7 +1823,7 @@ class Router(formatOps: FormatOps) { lastToken, style.indent.extendSite, if (template.early.nonEmpty) template.inits.nonEmpty - else template.inits.lengthCompare(1) > 0 + else template.inits.lengthCompare(1) > 0, ) // trait A extends B, C, D, E @@ -1842,7 +1842,7 @@ class Router(formatOps: FormatOps) { findTemplateGroupOnRight(_.superType)(template), templateCurlyOrLastNonTrivial(template), style.indent.main, - template.inits.lengthCompare(1) > 0 + template.inits.lengthCompare(1) > 0, ) // trait A extends B with C with D with E case template: Template => @@ -1852,14 +1852,14 @@ class Router(formatOps: FormatOps) { withChain(top).toSet, Some(t.rhs), top.tokens.last, - style.indent.main + style.indent.main, ) case enumCase: Defn.EnumCase => val indent = style.indent.withSiteRelativeToExtends val expire = getLastToken(enumCase) Seq( Split(Space, 0).withIndent(indent, expire, ExpiresOn.After), - Split(Newline, 1).withIndent(indent, expire, ExpiresOn.After) + Split(Newline, 1).withIndent(indent, expire, ExpiresOn.After), ) case _ => Seq(Split(Space, 0)) } @@ -1886,10 +1886,10 @@ class Router(formatOps: FormatOps) { noSplit, Split(Newline, 1).withIndent(indentLen, close, Before) .withPolicy(penalizeNewlines) - .andPolicy(decideNewlinesOnlyBeforeClose(close)) + .andPolicy(decideNewlinesOnlyBeforeClose(close)), ) } else Seq( - Split(NoSplit, 0).withIndents(indents).withPolicy(penalizeNewlines) + Split(NoSplit, 0).withIndents(indents).withPolicy(penalizeNewlines), ) case FormatToken(_: T.KwIf, right, _) if leftOwner.is[Term.If] => val owner = leftOwner.asInstanceOf[Term.If] @@ -1950,7 +1950,7 @@ class Router(formatOps: FormatOps) { Split(Space, 0).withSingleLineNoOptimal( expire, insideBracesBlock(formatToken, expire), - noSyntaxNL = leftOwner.is[Term.ForYield] && right.is[T.KwYield] + noSyntaxNL = leftOwner.is[Term.ForYield] && right.is[T.KwYield], ) }(nlSplitFunc) case FormatToken(T.RightBrace(), T.KwElse(), _) => @@ -1967,13 +1967,13 @@ class Router(formatOps: FormatOps) { Seq( Split(Space, 0).notIf(noSpace) .withSingleLineNoOptimal(expire, exclude, noSyntaxNL = noSyntaxNL), - Split(Newline, 1) + Split(Newline, 1), ) case ft @ FormatToken(_, _: T.KwThen | _: T.KwDo, _) => if (style.newlines.sourceIgnored || newlines == 0) Seq( Split(Space, 0) .withOptimalToken(nextNonCommentSameLine(next(ft)).left), - Split(Newline, 1) + Split(Newline, 1), ) else Seq(Split(Newline, 0)) // Last else branch @@ -2041,7 +2041,7 @@ class Router(formatOps: FormatOps) { def spaceSplit(implicit fileLine: FileLine) = spaceSplitWithoutPolicy .withPolicy(PenalizeAllNewlines(close, 1)) def newlineSplit(cost: Int, forceDangle: Boolean)(implicit - fileLine: FileLine + fileLine: FileLine, ) = { val shouldDangle = forceDangle || style.danglingParentheses.callSite Split(Newline, cost) @@ -2071,7 +2071,7 @@ class Router(formatOps: FormatOps) { spaceSplitWithoutPolicy.withSingleLine(close) .andPolicyOpt(singleLineInfixPolicy) }, - newlineSplit(10, true) + newlineSplit(10, true), ) } @@ -2113,7 +2113,7 @@ class Router(formatOps: FormatOps) { val indent = style.indent.main val lindents = Seq( Indent(indent, rparen, Before), - Indent(-indent, expire, After) + Indent(-indent, expire, After), ) val lmod = NewlineT(noIndent = rhsIsCommentedOut(postParenFt)) val lsplit = Seq(Split(lmod, 0).withIndents(lindents)) @@ -2135,12 +2135,12 @@ class Router(formatOps: FormatOps) { val arrowIndent = style.indent.caseSite - bodyIndent val indents = Seq( Indent(bodyIndent, expire, After), - Indent(arrowIndent, arrow, After) + Indent(arrowIndent, arrow, After), ) val mod = ModExt(Space, indents) Seq( Split(mod, 0).withSingleLine(expire, killOnFail = true), - Split(mod, 0, policy = policy) + Split(mod, 0, policy = policy), ) case tok @ FormatToken(_, cond @ T.KwIf(), _) if rightOwner.is[Case] => @@ -2158,7 +2158,7 @@ class Router(formatOps: FormatOps) { } Seq( noSplit, - Split(Newline, 1).withPolicy(penalizeNewlineByNesting(cond, arrow)) + Split(Newline, 1).withPolicy(penalizeNewlineByNesting(cond, arrow)), ) } @@ -2179,7 +2179,7 @@ class Router(formatOps: FormatOps) { case FormatToken( kw @ (_: T.KwTry | _: T.KwCatch | _: T.KwFinally), _, - _ + _, ) => val body = leftOwner match { case t: Term.Try => kw match { @@ -2213,7 +2213,7 @@ class Router(formatOps: FormatOps) { } else Seq( // Either everything fits in one line or break on => Split(Space, 0).withSingleLineNoOptimal(lastToken), - Split(Newline, 1).withIndent(indent) + Split(Newline, 1).withIndent(indent), ) // Term.For @@ -2249,7 +2249,7 @@ class Router(formatOps: FormatOps) { val spaceSplit = Split(Space, 0) .notIf(style.newlines.forceAfterImplicitParamListModifier).withPolicy( SingleLineBlock(params.tokens.last), - style.newlines.notPreferAfterImplicitParamListModifier + style.newlines.notPreferAfterImplicitParamListModifier, ) Seq(spaceSplit, Split(Newline, if (spaceSplit.isActive) 1 else 0)) @@ -2293,7 +2293,7 @@ class Router(formatOps: FormatOps) { case FormatToken( T.Ident(_) | T.Literal() | T.Interpolation.End() | T.Xml.End(), T.Ident(_) | T.Literal() | T.Xml.Start(), - _ + _, ) => Seq(Split(Space, 0)) // Case @@ -2319,7 +2319,7 @@ class Router(formatOps: FormatOps) { val exclude = insideBracesBlock(formatToken, endOfGuard, true) Seq( Split(Space, 0).withSingleLine(endOfGuard, exclude = exclude), - Split(Newline, 1) + Split(Newline, 1), ) case Newlines.unfold => Seq(Split(Newline, 0)) case _ => Seq(Split(Space, 0).onlyIf(newlines == 0), Split(Newline, 1)) @@ -2434,7 +2434,7 @@ class Router(formatOps: FormatOps) { private def getSplitsDefValEquals( ft: FormatToken, body: Tree, - spaceIndents: Seq[Indent] = Seq.empty + spaceIndents: Seq[Indent] = Seq.empty, )(splits: => Seq[Split])(implicit style: ScalafmtConfig): Seq[Split] = { def expire = getLastToken(body) if (ft.right.is[T.LeftBrace]) // The block will take care of indenting by 2 @@ -2454,7 +2454,7 @@ class Router(formatOps: FormatOps) { } private def getSplitsDefEquals(ft: FormatToken, body: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = { val expire = getLastToken(body) def baseSplit = Split(Space, 0) @@ -2479,13 +2479,13 @@ class Router(formatOps: FormatOps) { } private def getSplitsValEquals(ft: FormatToken, body: Tree)( - classicSplits: => Seq[Split] + classicSplits: => Seq[Split], )(implicit style: ScalafmtConfig): Seq[Split] = if (style.newlines.getBeforeMultiline eq Newlines.classic) classicSplits else CtrlBodySplits.getWithIndent(ft, body)(null)(Split(Newline, _)) private def getSplitsValEqualsClassic(ft: FormatToken, body: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = { def wouldDangle = ft.meta.leftOwner.parent.exists { case p: Member.ParamClause => !shouldNotDangleAtDefnSite(p.parent, false) @@ -2529,7 +2529,7 @@ class Router(formatOps: FormatOps) { val exclude = insideBracesBlock(ft, expire) policyWithExclude(exclude, Policy.End.On, Policy.End.After)( Policy.End.Before(expire), - new PenalizeAllNewlines(_, Constants.ShouldBeSingleLine) + new PenalizeAllNewlines(_, Constants.ShouldBeSingleLine), ) } val spaceSplit = body match { @@ -2544,12 +2544,12 @@ class Router(formatOps: FormatOps) { } Seq( spaceSplit, - CtrlBodySplits.withIndent(Split(Newline, 1 + penalty), ft, body) + CtrlBodySplits.withIndent(Split(Newline, 1 + penalty), ft, body), ) } private def getSplitsEnumerator(ft: FormatToken, body: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Seq[Split] = maybeGetInfixSplitsBeforeLhs(ft) { val expire = getLastNonTrivialToken(body) val spaceIndents = diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Split.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Split.scala index 20fb93e371..60c6b2039f 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Split.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/Split.scala @@ -45,7 +45,7 @@ case class Split( neededTags: Set[SplitTag] = Set.empty, activeTags: Set[SplitTag] = Set.empty, policy: Policy = NoPolicy, - optimalAt: Option[OptimalToken] = None + optimalAt: Option[OptimalToken] = None, )(implicit val fileLine: FileLine) { import PolicyOps._ @@ -97,7 +97,7 @@ case class Split( if (isIgnored) this else copy( activeTags = activeTags + splitTag, - neededTags = neededTags + splitTag + neededTags = neededTags + splitTag, ) def preActivateFor(splitTag: Option[SplitTag]): Split = @@ -111,13 +111,13 @@ case class Split( def withOptimalTokenOpt( token: => Option[Token], - killOnFail: Boolean = false + killOnFail: Boolean = false, ): Split = withOptimalAt(token.map(OptimalToken(_, killOnFail))) def withOptimalToken( token: => Token, killOnFail: Boolean = false, - ignore: Boolean = false + ignore: Boolean = false, ): Split = if (ignore) this else withOptimalAt(Some(OptimalToken(token, killOnFail))) @@ -139,7 +139,7 @@ case class Split( exclude: => TokenRanges = TokenRanges.empty, noSyntaxNL: Boolean = false, killOnFail: Boolean = false, - rank: Int = 0 + rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig): Split = withSingleLineAndOptimal( expire, @@ -147,7 +147,7 @@ case class Split( exclude, noSyntaxNL, killOnFail, - rank + rank, ) def withSingleLineOpt( @@ -155,7 +155,7 @@ case class Split( exclude: => TokenRanges = TokenRanges.empty, noSyntaxNL: Boolean = false, killOnFail: Boolean = false, - rank: Int = 0 + rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig): Split = expire .fold(this)(withSingleLine(_, exclude, noSyntaxNL, killOnFail, rank)) @@ -165,7 +165,7 @@ case class Split( exclude: => TokenRanges = TokenRanges.empty, noSyntaxNL: Boolean = false, killOnFail: Boolean = false, - rank: Int = 0 + rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig): Split = withOptimalToken(optimal, killOnFail) .withSingleLineNoOptimal(expire, exclude, noSyntaxNL, rank) @@ -174,9 +174,9 @@ case class Split( expire: Token, exclude: => TokenRanges = TokenRanges.empty, noSyntaxNL: Boolean = false, - rank: Int = 0 + rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig): Split = withPolicy( - SingleLineBlock(expire, exclude, noSyntaxNL = noSyntaxNL, rank = rank) + SingleLineBlock(expire, exclude, noSyntaxNL = noSyntaxNL, rank = rank), ) def withPolicyOpt(newPolicy: => Option[Policy]): Split = @@ -215,7 +215,7 @@ case class Split( def withIndentOpt( length: => Length, expire: Option[Token], - when: ExpiresOn + when: ExpiresOn, ): Split = withMod(modExt.withIndentOpt(length, expire, when)) def withIndent(indent: => Indent, ignore: Boolean = false): Split = @@ -269,7 +269,7 @@ object Split { def ignored(implicit fileLine: FileLine) = Split(ModExt(NoSplit), 0).ignored def apply(ignore: Boolean, cost: Int)(modExt: ModExt)(implicit - fileLine: FileLine + fileLine: FileLine, ): Split = if (ignore) ignored else Split(modExt, cost) } 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 9c26de06a0..63a93f5787 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 @@ -22,7 +22,7 @@ final case class State( column: Int, allAltAreNL: Boolean, appliedPenalty: Int, // penalty applied from overflow - delayedPenalty: Int // apply if positive, ignore otherwise + delayedPenalty: Int, // apply if positive, ignore otherwise ) { override def toString = s"State($cost, $depth)" @@ -34,7 +34,7 @@ final case class State( */ def next(initialNextSplit: Split, nextAllAltAreNL: Boolean)(implicit style: ScalafmtConfig, - tokens: FormatTokens + tokens: FormatTokens, ): State = { val tok = tokens(depth) val right = tok.right @@ -119,7 +119,7 @@ final case class State( nextStateColumn, nextAllAltAreNL, appliedPenalty + penalty, - nextDelayedPenalty + nextDelayedPenalty, ) } @@ -133,7 +133,7 @@ final case class State( @tailrec private def getOverflowPenalty( nextSplit: Split, - defaultOverflowPenalty: Int + defaultOverflowPenalty: Int, )(implicit style: ScalafmtConfig, tokens: FormatTokens): (Int, Int) = { val prevActive = delayedPenalty > 0 val fullPenalty = defaultOverflowPenalty + @@ -205,7 +205,7 @@ final case class State( @tailrec private def getLineStartOwner(isComment: Boolean)(implicit style: ScalafmtConfig, - tokens: FormatTokens + tokens: FormatTokens, ): Option[(FormatToken, Tree)] = { val ft = tokens(depth) if (ft.meta.left.hasNL) None @@ -235,7 +235,7 @@ final case class State( */ private def lineStartsStatement(isComment: Boolean)(implicit style: ScalafmtConfig, - tokens: FormatTokens + tokens: FormatTokens, ): Option[FormatToken] = getLineStartOwner(isComment) .flatMap { case (lineFt, lineOwner) => val ft = tokens(depth) @@ -252,7 +252,7 @@ final case class State( } private def getRelativeToLhsLastLineEnd( - isNL: Boolean + isNL: Boolean, )(implicit style: ScalafmtConfig, tokens: FormatTokens): Option[Int] = { val allowed = style.indent.relativeToLhsLastLine @@ -356,7 +356,7 @@ object State { private val slcLine = Pattern.compile("^/\\/\\/*+\\h*+(.*?)\\h*+$") def getColumns(ft: FormatToken, indent: Int, column: Int)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): (Int, Int) = { val syntax = ft.meta.right.text val firstNL = ft.meta.right.firstNL @@ -401,7 +401,7 @@ object State { private def getColumnsFromMultiline( syntax: String, firstNL: Int, - firstLength: Int + firstLength: Int, ): (Int, Int) = { @tailrec def iter(prevMaxLength: Int, lineBeg: Int): (Int, Int) = { @@ -418,9 +418,9 @@ object State { syntax: String, firstNL: Int, adjustMargin: Int => Int, - firstLength: Int + firstLength: Int, ): (Int, Int) = pipeOpt.fold( - getColumnsFromMultiline(syntax, firstNL, firstLength) + getColumnsFromMultiline(syntax, firstNL, firstLength), )(getColumnsWithStripMargin(_, syntax, firstNL, adjustMargin, firstLength)) private def getColumnsWithStripMargin( @@ -428,7 +428,7 @@ object State { syntax: String, firstNL: Int, adjustMargin: Int => Int, - firstLength: Int + firstLength: Int, ): (Int, Int) = { val matcher = getStripMarginPattern(pipe).matcher(syntax) matcher.region(firstNL, syntax.length) @@ -456,7 +456,7 @@ object State { private def allowSplitForLineStart( split: Split, ft: FormatToken, - isComment: Boolean + isComment: Boolean, ): Boolean = { split.length == 0 || isComment || isInterpolation(ft.meta.rightOwner) || ft.meta.leftOwner.is[meta.Term.Assign] diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroup.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroup.scala index eb032fa454..4f08cb3b32 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroup.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroup.scala @@ -101,7 +101,7 @@ object SyntacticGroup { } require( Literal.precedence == Term.SimpleExpr1.precedence && - Literal.precedence == Pat.SimplePattern.precedence + Literal.precedence == Pat.SimplePattern.precedence, ) case object Path extends Type with Term with Pat { override def categories = List("Type", "Term", "Pat") @@ -110,6 +110,6 @@ object SyntacticGroup { require( Path.precedence == Type.SimpleTyp.precedence && Path.precedence == Term.SimpleExpr1.precedence && - Path.precedence == Pat.SimplePattern.precedence + Path.precedence == Pat.SimplePattern.precedence, ) } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroupOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroupOps.scala index 8ee420e6c0..341bc4f5b4 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroupOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/SyntacticGroupOps.scala @@ -15,7 +15,7 @@ object SyntacticGroupOps { customAssociativity: Boolean, customPrecedence: Boolean, side: Side, - forceRight: Boolean = false + forceRight: Boolean = false, ): Boolean = { def isLeftAssociative(name: String): Boolean = !customAssociativity || @@ -53,7 +53,7 @@ object SyntacticGroupOps { def groupNeedsParenthesis( outerGroup: SyntacticGroup, innerGroup: SyntacticGroup, - side: Side + side: Side, ): Boolean = (outerGroup, innerGroup) match { case (g.Term.InfixExpr(outerOperator), g.Term.InfixExpr(innerOperator)) => operatorNeedsParenthesis( @@ -62,7 +62,7 @@ object SyntacticGroupOps { customAssociativity = true, customPrecedence = true, side, - forceRight = true + forceRight = true, ) case (g.Type.InfixTyp(outerOperator), g.Type.InfixTyp(innerOperator)) => operatorNeedsParenthesis( @@ -70,7 +70,7 @@ object SyntacticGroupOps { innerOperator, customAssociativity = true, customPrecedence = false, - side + side, ) case (g.Pat.Pattern3(outerOperator), g.Pat.Pattern3(innerOperator)) => operatorNeedsParenthesis( @@ -78,7 +78,7 @@ object SyntacticGroupOps { innerOperator, customAssociativity = true, customPrecedence = true, - side + side, ) case (_: g.Term.PrefixExpr, g.Term.PrefixArg(_, _: g.Term.PrefixExpr)) => diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/ConvertToNewScala3Syntax.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/ConvertToNewScala3Syntax.scala index 5df92439bf..08406b8488 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/ConvertToNewScala3Syntax.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/ConvertToNewScala3Syntax.scala @@ -31,7 +31,7 @@ private class ConvertToNewScala3Syntax(implicit val ftoks: FormatTokens) override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = Option { val flag = style.rewrite.scala3.newSyntax def left = ftoks.prevNonComment(ft).left @@ -91,7 +91,7 @@ private class ConvertToNewScala3Syntax(implicit val ftoks: FormatTokens) case _: Type.AnonymousParam if dialect.allowUnderscoreAsTypePlaceholder => replaceTokenBy("_")(t => - new Token.Underscore(t.input, t.dialect, t.start) + new Token.Underscore(t.input, t.dialect, t.start), ) case _ => null } @@ -103,7 +103,7 @@ private class ConvertToNewScala3Syntax(implicit val ftoks: FormatTokens) override def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = Option { def nextRight = ftoks.nextNonComment(ftoks.next(ft)).right ft.right match { 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 2ec403c33d..92d68291c7 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 @@ -16,7 +16,7 @@ import org.scalafmt.util.TokenOps class FormatTokensRewrite( ftoks: FormatTokens, styleMap: StyleMap, - rules: Seq[FormatTokensRewrite.Rule] + rules: Seq[FormatTokensRewrite.Rule], ) { import FormatTokensRewrite._ @@ -195,14 +195,14 @@ class FormatTokensRewrite( private def applyRules(implicit ft: FormatToken, - session: Session + session: Session, ): Option[Int] = { implicit val style = styleMap.at(ft.right) session.applyRules(rules) } private def applyRule( - rule: Rule + rule: Rule, )(implicit ft: FormatToken, session: Session): Option[Int] = { implicit val style = styleMap.at(ft.right) session.applyRule(rule) @@ -216,7 +216,7 @@ object FormatTokensRewrite { RemoveScala3OptionalBraces, ConvertToNewScala3Syntax, RemoveEmptyDocstrings, - RewriteTrailingCommas + RewriteTrailingCommas, ) private[rewrite] trait Rule { @@ -225,22 +225,22 @@ object FormatTokensRewrite { def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] // act on or modify only ft.right; process close (right) delim def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] protected final def removeToken(implicit ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = removeToken(Nil) protected final def removeToken( - claim: Iterable[Int] = Nil + claim: Iterable[Int] = Nil, )(implicit ft: FormatToken, style: ScalafmtConfig): Replacement = Replacement(this, ft, ReplacementType.Remove, style, claim) @@ -248,7 +248,7 @@ object FormatTokensRewrite { text: String, owner: Option[Tree] = None, claim: Iterable[Int] = Nil, - rtype: ReplacementType = ReplacementType.Replace + rtype: ReplacementType = ReplacementType.Replace, )(tok: T)(implicit ft: FormatToken, style: ScalafmtConfig): Replacement = { val mOld = ft.meta.right val mNew = mOld.copy(text = text, owner = owner.getOrElse(mOld.owner)) @@ -260,15 +260,15 @@ object FormatTokensRewrite { text: String, owner: Option[Tree] = None, claim: Iterable[Int] = Nil, - rtype: ReplacementType = ReplacementType.Replace + rtype: ReplacementType = ReplacementType.Replace, )(f: T => T)(implicit ft: FormatToken, style: ScalafmtConfig): Replacement = replaceToken(text, owner, claim, rtype)(f(ft.right)) protected final def replaceTokenIdent(text: String, t: T)(implicit ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = replaceToken(text)( - new T.Ident(t.input, t.dialect, t.start, t.start + text.length, text) + new T.Ident(t.input, t.dialect, t.start, t.start + text.length, text), ) } @@ -337,7 +337,7 @@ object FormatTokensRewrite { @inline private[rewrite] def claim(repl: Replacement)(implicit - ft: FormatToken + ft: FormatToken, ): Int = claim(ft.meta.idx, repl) private def justClaim(ftIdx: Int)(repl: Replacement): Int = { @@ -362,7 +362,7 @@ object FormatTokensRewrite { } private[FormatTokensRewrite] def applyRule( - attemptedRule: Rule + attemptedRule: Rule, )(implicit ft: FormatToken, style: ScalafmtConfig): Option[Int] = if (attemptedRule.enabled) attemptedRule.onToken.map { repl => val idx = claim(repl) @@ -372,7 +372,7 @@ object FormatTokensRewrite { else None private[FormatTokensRewrite] def applyRules( - rules: Seq[Rule] + rules: Seq[Rule], )(implicit ft: FormatToken, style: ScalafmtConfig): Option[Int] = { @tailrec def iter(remainingRules: Seq[Rule]): Option[Int] = remainingRules match { @@ -387,7 +387,7 @@ object FormatTokensRewrite { private[rewrite] def rule[A <: Rule](implicit tag: ClassTag[A], - sc: ScalafmtConfig + sc: ScalafmtConfig, ): Option[A] = { val ruleOpt = rules.find(tag.runtimeClass.isInstance) ruleOpt.map(_.asInstanceOf[A]).filter(_.enabled) @@ -409,7 +409,7 @@ object FormatTokensRewrite { how: ReplacementType, style: ScalafmtConfig, // list of FormatToken indices, with the claimed token on the **right** - claim: Iterable[Int] = Nil + claim: Iterable[Int] = Nil, ) { @inline def isRemove: Boolean = how eq ReplacementType.Remove @@ -419,14 +419,14 @@ object FormatTokensRewrite { def onRight(hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = if (rule.enabled) rule.onRight(this, hasFormatOff) else None def onRightAndClaim(hasFormatOff: Boolean, leftIdx: Int)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Unit = { val (ltRepl, rtRepl) = onRight(hasFormatOff).getOrElse((null, null)) session.claim(rtRepl) @@ -443,7 +443,7 @@ object FormatTokensRewrite { private def mergeWhitespaceLeftToRight( lt: FormatToken.Meta, - rt: FormatToken.Meta + rt: FormatToken.Meta, ): Option[Array[T]] = { import FormatToken.isNL val rtBW = rt.between 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 b83a84d5ae..d7fb5a6fe6 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 @@ -22,7 +22,7 @@ object Imports extends RewriteFactory { sort: Sort = Sort.none, expand: Boolean = false, contiguousGroups: ContiguousGroups = ContiguousGroups.only, - private val groups: Seq[Seq[String]] = Nil + private val groups: Seq[Seq[String]] = Nil, ) { private lazy val regex = groups.zipWithIndex .flatMap { case (patterns, index) => patterns.map((_, index)) } @@ -87,7 +87,7 @@ object Imports extends RewriteFactory { else obj.imports.sort val validated = obj.copy( rules = Imports +: nonImportRules, - imports = obj.imports.copy(expand = expand, sort = sort) + imports = obj.imports.copy(expand = expand, sort = sort), ) Configured.Ok(validated) } @@ -99,18 +99,18 @@ object Imports extends RewriteFactory { raw: String, cnt: Int, commentsBefore: Seq[Token] = Seq.empty, - commentAfter: Option[Token] = None + commentAfter: Option[Token] = None, ) private class Grouping( buffer: ListBuffer[GroupingEntry] = new ListBuffer[GroupingEntry], - stats: HashSet[String] = new HashSet[String] + stats: HashSet[String] = new HashSet[String], ) { def add( kw: String, ref: String, selectors: Selectors, - owner: Importer + owner: Importer, ): Unit = { val stat = s"$kw $ref${selectors.pretty}" if (stats.add(stat)) buffer += GroupingEntry(stat, ref, selectors, owner) @@ -127,7 +127,7 @@ object Imports extends RewriteFactory { stat: String, ref: String, selectors: Selectors, - owner: Importer + owner: Importer, ) { lazy val labels = ref.split('.') :+ selectors.raw } @@ -295,7 +295,7 @@ object Imports extends RewriteFactory { protected final def getSelector( selector: Importee, - needRaw: Boolean + needRaw: Boolean, ): Selectors = { val selectorString = selector.toString() val (commentsBefore, commentAfter) = getCommentsAround(selector) @@ -314,20 +314,20 @@ object Imports extends RewriteFactory { Selectors( pretty, if (needRaw && hadComments) s"{$selector}" else pretty, - 1 + 1, ) } else Selectors( selectorString, selectorString, 1, commentsBefore, - commentAfter + commentAfter, ) } protected final def getSelectors( selectors: Seq[Importee], - needRaw: Boolean + needRaw: Boolean, ): Selectors = { val selectorCount = selectors.length if (selectorCount == 1) getSelector(selectors.head, needRaw) @@ -357,7 +357,7 @@ object Imports extends RewriteFactory { pretty, if (hadComments && needRaw) tuples.map(_._2).mkString("{", ",", "}") else pretty, - selectorCount + selectorCount, ) } } @@ -373,7 +373,7 @@ object Imports extends RewriteFactory { } protected final def getCommentsAround( - tree: Tree + tree: Tree, ): (Seq[Token], Option[Token]) = { val tokens = tree.tokens val beg = getCommentsBefore(tokens.head) @@ -409,7 +409,7 @@ object Imports extends RewriteFactory { group: Grouping, kw: String, ref: String, - importer: Importer + importer: Importer, ): Unit protected val groups = Array.fill(settings.numGroups + 1)(new Grouping) @@ -419,7 +419,7 @@ object Imports extends RewriteFactory { kw: String, ref: String, selector: Importee, - importer: Importer + importer: Importer, ): Unit = group.add(kw, ref, getSelector(selector, true), importer) protected final def addToGroup( @@ -427,7 +427,7 @@ object Imports extends RewriteFactory { kw: String, ref: String, selectors: Seq[Importee], - importer: Importer + importer: Importer, ): Unit = if (selectors.nonEmpty) group .add(kw, ref, getSelectors(selectors, true), importer) @@ -503,7 +503,7 @@ object Imports extends RewriteFactory { } override protected def processImports( - stats: Seq[Seq[ImportExportStat]] + stats: Seq[Seq[ImportExportStat]], ): Unit = if (settings.noGroups) processEachLine(stats) else if (settings.contiguousGroups eq ContiguousGroups.only) @@ -515,7 +515,7 @@ object Imports extends RewriteFactory { val lastTok = x.last.tokens.last ( getCommentsBefore(headTok).headOption.getOrElse(headTok), - getCommentAfter(lastTok).getOrElse(lastTok) + getCommentAfter(lastTok).getOrElse(lastTok), ) } @@ -541,7 +541,7 @@ object Imports extends RewriteFactory { private def processTokenRanges( importString: String, - tokenRanges: (Token, Token)* + tokenRanges: (Token, Token)*, ): Unit = { implicit val patchBuilder = Seq.newBuilder[TokenPatch] @@ -580,7 +580,7 @@ object Imports extends RewriteFactory { group: Grouping, kw: String, ref: String, - importer: Importer + importer: Importer, ): Unit = { // if there's a wildcard, unimports and renames must come with it, cannot be expanded val importees = importer.importees @@ -612,7 +612,7 @@ object Imports extends RewriteFactory { group: Grouping, kw: String, ref: String, - importer: Importer + importer: Importer, ): Unit = addToGroup(group, kw, ref, importer.importees, importer) } @@ -627,7 +627,7 @@ object Imports extends RewriteFactory { */ private class ExpandNone(implicit ctx: RewriteCtx) extends Base { override protected def processImports( - stats: Seq[Seq[ImportExportStat]] + stats: Seq[Seq[ImportExportStat]], ): Unit = stats.flatten.foreach { t => val patchBuilder = Seq.newBuilder[TokenPatch] t.importers.foreach { importer => diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Patch.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Patch.scala index a5e21f8612..9caa8ede20 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Patch.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/Patch.scala @@ -15,7 +15,7 @@ object TokenPatch { def AddRight( tok: Token, toAdd: String, - keepTok: Boolean = false + keepTok: Boolean = false, ): TokenPatch = Add(tok, "", toAdd, keepTok) def AddLeft(tok: Token, toAdd: String, keepTok: Boolean = false): TokenPatch = Add(tok, toAdd, "", keepTok) @@ -23,7 +23,7 @@ object TokenPatch { override val tok: Token, addLeft: String, addRight: String, - keepTok: Boolean + keepTok: Boolean, ) extends TokenPatch(tok, s"""$addLeft${if (keepTok) tok else ""}$addRight""") } @@ -34,7 +34,7 @@ object Patch { add1.tok, add1.addLeft + add2.addLeft, add1.addRight + add2.addRight, - add1.keepTok && add2.keepTok + add1.keepTok && add2.keepTok, ) case (_: Remove, add: Add) => add.copy(keepTok = false) case (add: Add, _: Remove) => add.copy(keepTok = false) @@ -42,7 +42,7 @@ object Patch { case _ => sys.error( s"""|Can't merge token patches: |1. $a - |2. $b""".stripMargin + |2. $b""".stripMargin, ) } 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 35a85b215d..39c4608459 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 @@ -59,7 +59,7 @@ private class PreferCurlyFors(implicit val ftoks: FormatTokens) override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = Option { ft.right match { case x: Token.LeftParen @@ -90,7 +90,7 @@ private class PreferCurlyFors(implicit val ftoks: FormatTokens) override def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = ft.right match { case x: Token.RightParen if left.how == ReplacementType.Replace && 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 98a3d52c87..7d1cba9675 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 @@ -27,7 +27,7 @@ object RedundantBraces extends Rewrite with FormatTokensRewrite.RuleFactory { } def canRewriteBlockWithParens(b: Term.Block)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Boolean = getBlockSingleStat(b).exists(canRewriteStatWithParens) def canRewriteStatWithParens(t: Stat)(implicit ftoks: FormatTokens): Boolean = @@ -46,7 +46,7 @@ object RedundantBraces extends Rewrite with FormatTokensRewrite.RuleFactory { @tailrec def canRewriteFuncWithParens( f: Term.FunctionTerm, - nested: Boolean = false + nested: Boolean = false, ): Boolean = !needParensAroundParams(f) && (getTreeSingleStat(f.body) match { case Some(t: Term.FunctionTerm) => canRewriteFuncWithParens(t, true) @@ -70,7 +70,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = Option { ft.right match { case _: Token.LeftBrace => onLeftBrace @@ -82,7 +82,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) override def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = Option { ft.right match { case _: Token.RightBrace => onRightBrace(left) @@ -93,14 +93,14 @@ class RedundantBraces(implicit val ftoks: FormatTokens) private def replaceWithEquals(implicit ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = replaceTokenBy("=") { x => new Token.Equals(x.input, x.dialect, x.start) } private def onLeftParen(implicit ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = { val rt = ft.right val rtOwner = ft.meta.rightOwner @@ -139,7 +139,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) private def onRightParen(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): (Replacement, Replacement) = left.how match { case ReplacementType.Remove => val resOpt = getRightBraceBeforeRightParen(false).map { rb => @@ -193,7 +193,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) private def getRightBraceBeforeRightParen(shouldBeRemoved: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[FormatToken] = { val pft = ftoks.prevNonComment(ft) val ok = pft.left match { @@ -216,13 +216,13 @@ class RedundantBraces(implicit val ftoks: FormatTokens) private def onLeftBrace(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = onLeftBrace(ft.meta.rightOwner) private def onLeftBrace(owner: Tree)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = { def handleInterpolation = if ( @@ -260,11 +260,11 @@ class RedundantBraces(implicit val ftoks: FormatTokens) private def onRightBrace(left: Replacement)(implicit ft: FormatToken, - style: ScalafmtConfig + style: ScalafmtConfig, ): (Replacement, Replacement) = (left, removeToken) private def settings(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): RedundantBracesSettings = style.rewrite.redundantBraces private def processInterpolation(implicit ft: FormatToken): Boolean = { @@ -298,7 +298,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) } private def okToReplaceFunctionInSingleArgApply(f: Term.FunctionTerm)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = f.parent.flatMap(okToReplaceFunctionInSingleArgApply) .exists(_._2 eq f) @@ -311,7 +311,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) // single-arg apply of a lambda // a(b => { c; d }) change to a { b => c; d } private def okToReplaceFunctionInSingleArgApply(tree: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Token.LeftParen, Term.FunctionTerm)] = tree match { case ta @ Term.ArgClause((func: Term.FunctionTerm) :: Nil, _) if { val body = func.body @@ -326,7 +326,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) // a single-stat lambda with braces can be converted to one without braces, // but the reverse conversion isn't always possible private def okToRemoveFunctionInApplyOrInit( - t: Term.FunctionTerm + t: Term.FunctionTerm, )(implicit style: ScalafmtConfig): Boolean = t.parent match { case Some(p: Term.ArgClause) => p.parent match { case Some(_: Init) => okToRemoveAroundFunctionBody(t.body, false) @@ -340,7 +340,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) private def processBlock(b: Term.Block)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = (b.tokens.headOption.contains(ft.right) && b.tokens.last.is[Token.RightBrace] && okToRemoveBlock(b)) && @@ -351,7 +351,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) }) private def checkValidInfixParent( - p: Tree + p: Tree, )(implicit ft: FormatToken, style: ScalafmtConfig): Boolean = p match { case _: Member.Infix => /* for infix, we will preserve the block unless the closing brace @@ -373,7 +373,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) } private def okToRemoveBlock( - b: Term.Block + b: Term.Block, )(implicit style: ScalafmtConfig, session: Session): Boolean = b.parent .exists { @@ -420,12 +420,12 @@ class RedundantBraces(implicit val ftoks: FormatTokens) } private def checkBlockAsBody(b: Term.Block, rhs: Tree, noParams: => Boolean)( - implicit style: ScalafmtConfig + implicit style: ScalafmtConfig, ): Boolean = rhs.eq(b) && getSingleStatIfLineSpanOk(b).exists(innerOk(b)) && isDefnBodiesEnabled(noParams) private def isDefnBodiesEnabled( - noParams: => Boolean + noParams: => Boolean, )(implicit style: ScalafmtConfig): Boolean = settings.defnBodies match { case RedundantBracesSettings.DefnBodies.all => true case RedundantBracesSettings.DefnBodies.none => false @@ -449,7 +449,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) } private def okToRemoveBlockWithinApply(b: Term.Block)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = getSingleStatIfLineSpanOk(b).exists { case f: Term.FunctionTerm => !needParensAroundParams(f) && { val fb = f.body @@ -466,7 +466,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) /** Some blocks look redundant but aren't */ private def shouldRemoveSingleStatBlock(b: Term.Block)(implicit style: ScalafmtConfig, - session: Session + session: Session, ): Boolean = getSingleStatIfLineSpanOk(b).exists { stat => @tailrec def checkParent(tree: Tree): Boolean = tree match { @@ -514,7 +514,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) SyntacticGroupOps.groupNeedsParenthesis( TreeSyntacticGroup(p), TreeSyntacticGroup(t), - if (useRight) Side.Right else Side.Left + if (useRight) Side.Right else Side.Left, ) case _ => true // don't allow other non-infix } @@ -525,7 +525,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) case parent => SyntacticGroupOps.groupNeedsParenthesis( TreeSyntacticGroup(parent), TreeSyntacticGroup(stat), - Side.Left + Side.Left, ) } @@ -534,14 +534,14 @@ class RedundantBraces(implicit val ftoks: FormatTokens) @inline private def okToRemoveAroundFunctionBody(b: Term, s: Seq[Tree])(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = okToRemoveAroundFunctionBody(b, isSeqSingle(s)) private def okToRemoveAroundFunctionBody( b: Term, - okIfMultipleStats: => Boolean + okIfMultipleStats: => Boolean, )(implicit style: ScalafmtConfig): Boolean = isDefnBodiesEnabled(noParams = - false + false, ) && (getTreeSingleStat(b) match { case Some(_: Term.PartialFunction) => false @@ -551,7 +551,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) }) private def getBlockNestedPartialFunction( - tree: Tree + tree: Tree, ): Option[Term.PartialFunction] = tree match { case x: Term.PartialFunction => Some(x) case x: Term.Block => getBlockNestedPartialFunction(x) @@ -560,7 +560,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) @tailrec private def getBlockNestedPartialFunction( - tree: Term.Block + tree: Term.Block, ): Option[Term.PartialFunction] = getBlockSingleStat(tree) match { case Some(x: Term.PartialFunction) => Some(x) case Some(x: Term.Block) => getBlockNestedPartialFunction(x) @@ -568,7 +568,7 @@ class RedundantBraces(implicit val ftoks: FormatTokens) } private def getSingleStatIfLineSpanOk(b: Term.Block)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Stat] = getBlockSingleStat(b).filter(okLineSpan(_)) private def okLineSpan(tree: Tree)(implicit style: ScalafmtConfig): Boolean = diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantParens.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantParens.scala index 53b5f239e5..6671d6d94a 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantParens.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RedundantParens.scala @@ -72,7 +72,7 @@ class RedundantParens(implicit val ftoks: FormatTokens) override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = ft.right match { case _: Token.LeftParen => findEnclosed.flatMap { case (cnt, tree) => if (okToReplaceWithCount(cnt, tree)) Some(removeToken) else None @@ -83,14 +83,14 @@ class RedundantParens(implicit val ftoks: FormatTokens) override def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = if (left.isRemove && RewriteTrailingCommas.checkIfPrevious) Some((left, removeToken)) else None private def okToReplaceWithCount(numParens: Int, tree: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = tree match { case _: Lit.Unit | _: Member.Tuple => numParens >= 3 case _ if numParens >= 2 => true @@ -135,7 +135,7 @@ class RedundantParens(implicit val ftoks: FormatTokens) } private def okToReplaceOther( - t: Tree + t: Tree, )(implicit style: ScalafmtConfig): Boolean = t match { case _: Lit | _: Name | _: Term.Interpolate => true case _: Term.PartialFunction | _: Member.Apply => true @@ -148,7 +148,7 @@ class RedundantParens(implicit val ftoks: FormatTokens) } private def okToReplaceArgClause( - t: Member.ArgClause + t: Member.ArgClause, )(implicit style: ScalafmtConfig): Boolean = t.values match { case arg :: Nil => arg match { case _: Term.Block | _: Term.PartialFunction => t.parent @@ -165,7 +165,7 @@ class RedundantParens(implicit val ftoks: FormatTokens) } private def okToReplaceInfix(pia: Member.Infix, tia: Member.Infix)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = !breaksBeforeOp(tia) && style.rewrite.redundantParens.infixSide.exists { case RedundantParensSettings.InfixSide.many @@ -181,7 +181,7 @@ class RedundantParens(implicit val ftoks: FormatTokens) } private def okToReplaceInfix(pia: Member.Infix, t: Tree)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = t match { case tia: Member.Infix => okToReplaceInfix(pia, tia) case _: Lit | _: Name | _: Term.Interpolate => true @@ -212,7 +212,7 @@ class RedundantParens(implicit val ftoks: FormatTokens) (ftoks.prevNonComment(lt), ftoks.nextNonComment(rt)) match { case ( prev @ FormatToken(_: Token.LeftParen, _, _), - next @ FormatToken(_, _: Token.RightParen, _) + next @ FormatToken(_, _: Token.RightParen, _), ) => iter(ftoks.prev(prev), ftoks.next(next), cnt + 1) case _ => TreeOps .findEnclosedBetweenParens(lt.right, rt.left, ft.meta.rightOwner) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveEmptyDocstrings.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveEmptyDocstrings.scala index ec981f0385..31d0c55b71 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveEmptyDocstrings.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveEmptyDocstrings.scala @@ -22,7 +22,7 @@ object RemoveEmptyDocstrings override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = { val skip = ft.right.is[Token.Comment] && FormatWriter.isEmptyDocstring(ft.meta.right.text) @@ -32,7 +32,7 @@ object RemoveEmptyDocstrings override def onRight(lt: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = None } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveScala3OptionalBraces.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveScala3OptionalBraces.scala index f3e4b2cd16..70b1a92b1d 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveScala3OptionalBraces.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RemoveScala3OptionalBraces.scala @@ -38,7 +38,7 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = Option { ft.right match { case x: Token.LeftBrace // skip empty brace pairs @@ -77,7 +77,7 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) override def onRight(left: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = { val nextFt = ftoks.nextNonComment(ftoks.next(ft)) val notOkToRewrite = hasFormatOff || // can't force significant indentation @@ -113,7 +113,7 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) private def onLeftForBlock(tree: Term.Block)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Replacement = tree.parent.fold(null: Replacement) { case t: Term.If => val ok = ftoks.prevNonComment(ft).left match { @@ -161,7 +161,7 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) } private def shouldRewriteArgClauseWithLeftParen[A <: Rule]( - lp: Token + lp: Token, )(implicit ft: FormatToken, session: Session, tag: ClassTag[A]) = { val prevFt = ftoks.prevNonComment(ft) prevFt.left.eq(lp) && session.claimedRule(prevFt.meta.idx - 1) @@ -169,7 +169,7 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) } private[rewrite] def onLeftForArgClause( - tree: Term.ArgClause + tree: Term.ArgClause, )(implicit ft: FormatToken, style: ScalafmtConfig): Replacement = { val ok = style.dialect.allowFewerBraces && style.rewrite.scala3.removeOptionalBraces.fewerBracesMaxSpan > 0 && @@ -190,7 +190,7 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) private def shouldRewriteColonOnRight(left: Replacement)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = { val lft = left.ft lft.meta.rightOwner match { @@ -206,11 +206,11 @@ private class RemoveScala3OptionalBraces(implicit val ftoks: FormatTokens) private def shouldRewriteArgClauseColonOnRight( ac: Term.ArgClause, - lft: FormatToken + lft: FormatToken, )(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = ac.values match { case arg :: Nil => val begIdx = math.max(ftoks.getHead(arg).meta.idx - 1, lft.meta.idx + 1) 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 bdfd5cf204..32f6291040 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 @@ -57,7 +57,7 @@ case class RewriteCtx(style: ScalafmtConfig, input: Input, tree: Tree) { }.isDefined def findNonWhitespaceWith( - f: (Token => Option[Boolean]) => Option[Token] + f: (Token => Option[Boolean]) => Option[Token], ): Option[(Token, Option[T.LF])] = { var lf: Option[T.LF] = None val nonWs = f { @@ -70,7 +70,7 @@ case class RewriteCtx(style: ScalafmtConfig, input: Input, tree: Tree) { // end is inclusive def removeLFToAvoidEmptyLine(beg: Int, end: Int)(implicit - builder: Rewrite.PatchBuilder + builder: Rewrite.PatchBuilder, ): Unit = if (onlyWhitespaceBefore(beg)) tokenTraverser.findAtOrAfter(end + 1) { case _: T.LF => Some(true) case _: T.Whitespace => None @@ -121,7 +121,7 @@ object Rewrite { PreferCurlyFors, ExpandImportSelectors, AvoidInfix, - SortModifiers + SortModifiers, ) implicit val reader: ConfCodecEx[Rewrite] = ReaderUtil.oneOf(rewrites: _*) @@ -136,7 +136,7 @@ object Rewrite { def apply( input: Input, style: ScalafmtConfig, - toInput: String => Input + toInput: String => Input, ): Input = { val rewrites = style.rewrite.rewriteFactoryRules if (rewrites.isEmpty) input @@ -162,7 +162,7 @@ object RewriteCtx { // https://www.scala-lang.org/files/archive/spec/2.13/06-expressions.html#prefix-infix-and-postfix-operations def isSimpleExprOr( - expr: Tree + expr: Tree, )(orElse: PartialFunction[Tree, Boolean]): Boolean = expr match { case _: Lit | _: Name | _: Term.Interpolate => true case _: Term.New | _: Term.NewAnonymous => true diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RewriteTrailingCommas.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RewriteTrailingCommas.scala index 85420ccf4c..043355fd04 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RewriteTrailingCommas.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/rewrite/RewriteTrailingCommas.scala @@ -22,7 +22,7 @@ object RewriteTrailingCommas extends FormatTokensRewrite.RuleFactory { private[rewrite] def checkIfPrevious(implicit ft: FormatToken, session: Session, - ftoks: FormatTokens + ftoks: FormatTokens, ): Boolean = ft.right match { case _: Token.RightParen => val maybeCommaFt = ftoks.prevNonComment(ft) @@ -49,11 +49,11 @@ private class RewriteTrailingCommas(implicit val ftoks: FormatTokens) override def onToken(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[Replacement] = if (shouldRemove(ft)) Some(removeToken) else None private[rewrite] def shouldRemove( - ft: FormatToken + ft: FormatToken, )(implicit session: Session): Boolean = ft.right.is[Token.Comma] && { val rightOwner = ft.meta.rightOwner val nft = ftoks.nextNonCommentAfter(ft) @@ -79,7 +79,7 @@ private class RewriteTrailingCommas(implicit val ftoks: FormatTokens) override def onRight(lt: Replacement, hasFormatOff: Boolean)(implicit ft: FormatToken, session: Session, - style: ScalafmtConfig + style: ScalafmtConfig, ): Option[(Replacement, Replacement)] = None } diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/LiteralOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/LiteralOps.scala index 18ae4ee3bd..c58e25a3f6 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/LiteralOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/LiteralOps.scala @@ -45,7 +45,7 @@ object LiteralOps { str: String, suffixUpper: Char, suffixLower: Char, - suffixCase: Case + suffixCase: Case, )(implicit style: ScalafmtConfig): String = if (str.last == suffixUpper || str.last == suffixLower) style.literals .scientific.process(str.dropRight(1)) + @@ -53,7 +53,7 @@ object LiteralOps { else style.literals.scientific.process(str) private def prettyPrintHex( - str: String + str: String, )(implicit style: ScalafmtConfig): String = if (str.startsWith("0x") || str.startsWith("0X")) style.literals.hexPrefix .process(str.take(2)) + style.literals.hexDigits.process(str.drop(2)) 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 c946bdf6e1..0ad636ba8b 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 @@ -16,7 +16,7 @@ object PolicyOps { penalty: Int, penalizeLambdas: Boolean = true, noSyntaxNL: Boolean = false, - val rank: Int = 0 + val rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig) extends Policy.Clause { override val noDequeue: Boolean = false @@ -34,13 +34,13 @@ object PolicyOps { expire: T, penalty: Int, penalizeLambdas: Boolean = true, - noSyntaxNL: Boolean = false + noSyntaxNL: Boolean = false, )(implicit fileLine: FileLine, style: ScalafmtConfig): Policy = new PenalizeAllNewlines( Policy.End.Before(expire), penalty, penalizeLambdas, - noSyntaxNL + noSyntaxNL, ) } @@ -54,7 +54,7 @@ object PolicyOps { val endPolicy: Policy.End.WithPos, okSLC: Boolean = false, noSyntaxNL: Boolean = false, - val rank: Int = 0 + val rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig) extends Policy.Clause { import TokenOps.isLeftCommentThenBreak @@ -75,7 +75,7 @@ object PolicyOps { exclude: TokenRanges = TokenRanges.empty, okSLC: Boolean = false, noSyntaxNL: Boolean = false, - rank: Int = 0 + rank: Int = 0, )(implicit fileLine: FileLine, style: ScalafmtConfig): Policy = policyWithExclude(exclude, Policy.End.On, Policy.End.After)( Policy.End.On(expire), @@ -83,15 +83,15 @@ object PolicyOps { _, okSLC = okSLC, noSyntaxNL = noSyntaxNL, - rank = rank - ) + rank = rank, + ), ) } final class DecideNewlinesOnlyBeforeToken( val token: T, split: Option[Split], - val rank: Int = 0 + val rank: Int = 0, )(implicit fileLine: FileLine) extends Policy.Clause { override val endPolicy: Policy.End.WithPos = Policy.End.On(token) @@ -111,7 +111,7 @@ object PolicyOps { final class DecideNewlinesOnlyAfterToken( val token: T, split: Option[Split], - val rank: Int = 0 + val rank: Int = 0, )(implicit fileLine: FileLine) extends Policy.Clause { override val endPolicy: Policy.End.WithPos = Policy.End.After(token) @@ -131,15 +131,15 @@ object PolicyOps { def policyWithExclude( exclude: TokenRanges, endLt: T => Policy.End.WithPos, - endRt: T => Policy.End.WithPos + endRt: T => Policy.End.WithPos, )(expire: Policy.End.WithPos, policyFunc: Policy.End.WithPos => Policy)( - implicit fileLine: FileLine + implicit fileLine: FileLine, ): Policy = { val lastPolicy = policyFunc(expire) exclude.ranges.foldLeft(lastPolicy) { case (policy, range) => new Policy.Relay( policyFunc(endLt(range.lt)), - new Policy.Delay(policy, endRt(range.rt)) + new Policy.Delay(policy, endRt(range.rt)), ) } } @@ -162,39 +162,39 @@ object PolicyOps { } def delayedBreakPolicy(end: Policy.End.WithPos)(onBreakPolicy: Policy)( - implicit fileLine: FileLine + implicit fileLine: FileLine, ): Policy = Policy.Proxy(onBreakPolicy, end)(delayedBreakPolicyFactory) def delayedBreakPolicyBefore(token: T)(onBreakPolicy: Policy)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = delayedBreakPolicy(Policy.End.Before(token))(onBreakPolicy) def delayedBreakPolicyFor(token: T)(f: T => Policy)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = delayedBreakPolicyBefore(token)(f(token)) def decideNewlinesOnlyBeforeClose(close: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = decideNewlinesOnlyBeforeClose(Split(Newline, 0))(close) def decideNewlinesOnlyBeforeCloseOnBreak(close: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = delayedBreakPolicyFor(close)(decideNewlinesOnlyBeforeClose) def decideNewlinesOnlyBeforeClose(split: Split)(close: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = new DecideNewlinesOnlyBeforeToken(close, Option(split)) def decideNewlinesOnlyAfterClose(close: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = decideNewlinesOnlyAfterClose(Split(Newline, 0))(close) def decideNewlinesOnlyAfterClose(split: Split)(close: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = new DecideNewlinesOnlyAfterToken(close, Option(split)) def decideNewlinesOnlyAfterToken(token: T)(implicit - fileLine: FileLine + fileLine: FileLine, ): Policy = new DecideNewlinesOnlyAfterToken(token, None) def unindentAtExclude(exclude: TokenRanges, indent: Length): Policy = exclude 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 bc655f80be..4fc35466c1 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 @@ -73,7 +73,7 @@ class StyleMap(tokens: FormatTokens, val init: ScalafmtConfig) { @tailrec private def isBasicLiteral( - tree: Tree + tree: Tree, )(implicit style: ScalafmtConfig): Boolean = tree match { case lit: Lit => val strName = tree match { @@ -121,7 +121,7 @@ class StyleMap(tokens: FormatTokens, val init: ScalafmtConfig) { }) def opensLiteralArgumentList( - ft: FormatToken + ft: FormatToken, )(implicit style: ScalafmtConfig): Boolean = (ft.meta.leftOwner match { case Member.Tuple(v) => Some(v) case Member.SyntaxValuesClause(v) => Some(v) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenOps.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenOps.scala index 000cf654c0..8bdcb6f133 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenOps.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenOps.scala @@ -45,7 +45,7 @@ object TokenOps { text.startsWith("/**") // excludes /**/ def blankLineBeforeDocstring(ft: FormatToken)(implicit - style: ScalafmtConfig + style: ScalafmtConfig, ): Boolean = style.forceNewlineBeforeDocstring && isDocstring(ft.meta.right.text) && TreeOps.findTreeOrParent(ft.meta.leftOwner) { @@ -101,12 +101,12 @@ object TokenOps { val formatOnCode = Set( "@formatter:on", // IntelliJ - "format: on" // scalariform + "format: on", // scalariform ) val formatOffCode = Set( "@formatter:off", // IntelliJ - "format: off" // scalariform + "format: off", // scalariform ) @inline diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenTraverser.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenTraverser.scala index d9eabfbf5c..33343806f9 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenTraverser.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/util/TokenTraverser.scala @@ -63,7 +63,7 @@ class TokenTraverser(tokens: Tokens, input: Input) { * Some(token) if the predicate returned Some(true), else None. */ def findAfter( - token: Token + token: Token, )(predicate: Token => Option[Boolean]): Option[Token] = tok2idx.get(token) .flatMap(x => findAtOrAfter(x + 1)(predicate)) @@ -73,13 +73,13 @@ class TokenTraverser(tokens: Tokens, input: Input) { * Some(token) if the predicate returned Some(true), else None. */ def findBefore( - token: Token + token: Token, )(predicate: Token => Option[Boolean]): Option[Token] = tok2idx.get(token) .flatMap(x => findAtOrBefore(x - 1)(predicate)) @tailrec final def findAtOrAfter( - off: Int + off: Int, )(pred: Token => Option[Boolean]): Option[Token] = if (off >= tokens.length) None else { @@ -93,7 +93,7 @@ class TokenTraverser(tokens: Tokens, input: Input) { @tailrec final def findAtOrBefore( - off: Int + off: Int, )(pred: Token => Option[Boolean]): Option[Token] = if (off < 0) None else { @@ -106,7 +106,7 @@ class TokenTraverser(tokens: Tokens, input: Input) { } final def filter(start: Token, end: Token)( - predicate: Token => Boolean + predicate: Token => Boolean, ): Seq[Token] = if (start == end || nextToken(start) == start) Nil else { 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 1167df517c..b341feec5e 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 @@ -48,13 +48,13 @@ object TreeOps { object SingleArgInBraces { def unapply(tree: Tree)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Option[(FormatToken, Term, FormatToken)] = tree match { case t: Term.ArgClause => unapply(t) case _ => None } def unapply(tree: Term.ArgClause)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Option[(FormatToken, Term, FormatToken)] = tree.values match { case arg :: Nil => getBraces(tree).map { case (b, e) => (b, arg, e) } case _ => None @@ -64,12 +64,12 @@ object TreeOps { getBraces(tree).isDefined @inline def getBraces(tree: Tree)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Option[(FormatToken, FormatToken)] = ftoks.getDelimsIfEnclosed(tree) .filter(_._1.left.is[LeftBrace]) def orBlock(tree: Tree)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Option[(FormatToken, Stat, FormatToken)] = tree match { case t: Term.ArgClause => unapply(t) case Term.Block(arg :: Nil) => getBraces(tree).map { case (b, e) => @@ -80,14 +80,14 @@ object TreeOps { object OrBlock { def unapply(tree: Tree)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Option[(FormatToken, Stat, FormatToken)] = orBlock(tree) } } @tailrec def isBlockFunction( - fun: Term.FunctionTerm + fun: Term.FunctionTerm, )(implicit ftoks: FormatTokens): Boolean = fun.parent match { case Some(p: Term.FunctionTerm) => isBlockFunction(p) case Some(p) => isExprWithParentInBraces(fun)(p) @@ -95,15 +95,15 @@ object TreeOps { } def isFunctionWithBraces(fun: Term.FunctionTerm)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Boolean = fun.parent.exists(isExprWithParentInBraces(fun)) def isExprWithParentInBraces(expr: Tree)(parent: Tree)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Boolean = SingleArgInBraces.orBlock(parent).exists(_._2 eq expr) def extractStatementsIfAny( - tree: Tree + tree: Tree, )(implicit ftoks: FormatTokens): Seq[Tree] = tree match { case b: Term.Block => b.stats case SingleArgInBraces(_, fun: Term.FunctionTerm, _) => fun :: Nil @@ -124,7 +124,7 @@ object TreeOps { } def getStatementStarts(tree: Tree, soft: SoftKeywordClasses)(implicit - ftoks: FormatTokens + ftoks: FormatTokens, ): Map[TokenHash, Tree] = { val ret = Map.newBuilder[TokenHash, Tree] ret.sizeHint(tree.tokens.length) @@ -139,7 +139,7 @@ object TreeOps { mods: Seq[Mod], tree: Tree, what: String, - isMatch: Token => Boolean + isMatch: Token => Boolean, ): Unit = { // Each @annotation gets a separate line val annotations = mods.filter(_.is[Mod.Annot]) @@ -156,14 +156,14 @@ object TreeOps { } } def addDefn[T](mods: Seq[Mod], tree: Tree)(implicit - tag: ClassTag[T] + tag: ClassTag[T], ): Unit = { val runtimeClass = tag.runtimeClass addDefnTokens( mods, tree, runtimeClass.getSimpleName, - runtimeClass.isInstance + runtimeClass.isInstance, ) } @@ -243,7 +243,7 @@ object TreeOps { case _ => } if (stack.nonEmpty) throw new IllegalArgumentException( - stack.map(x => s"[${x.end}]$x").mkString("Orphan parens (", ", ", ")") + stack.map(x => s"[${x.end}]$x").mkString("Orphan parens (", ", ", ")"), ) val result = ret.result() result @@ -273,7 +273,7 @@ object TreeOps { /** Returns first ancestor which matches the given predicate. */ def findTreeOrParent( - tree: Tree + tree: Tree, )(pred: Tree => Option[Boolean]): Option[Tree] = findTreeEx(tree) { t => pred(t) match { case None => t.parent @@ -295,7 +295,7 @@ object TreeOps { } def findTreeOrParentSimple(tree: Tree, flag: Boolean = true)( - pred: Tree => Boolean + pred: Tree => Boolean, ): Option[Tree] = findTreeOrParent(tree)(x => if (pred(x) == flag) Some(true) else None) @@ -304,7 +304,7 @@ object TreeOps { * flag, which terminates the search. */ def findTreeWithParent(tree: Tree)( - pred: Tree => Option[Boolean] + pred: Tree => Option[Boolean], ): Option[Tree] = findTreeWithParentEx(tree) { t => pred(t) match { case None => Some(t) @@ -319,7 +319,7 @@ object TreeOps { */ @tailrec def findTreeWithParentEx( - tree: Tree + tree: Tree, )(pred: Tree => Option[Tree]): Option[Tree] = tree.parent match { case None => None case Some(p) => pred(p) match { @@ -330,21 +330,21 @@ object TreeOps { } def findTreeWithParentSimple(tree: Tree, flag: Boolean = true)( - pred: Tree => Boolean + pred: Tree => Boolean, ): Option[Tree] = findTreeWithParent(tree)(x => if (pred(x) == flag) Some(true) else None) /** Returns first ancestor with a parent of a given type. */ def findTreeWithParentOfType[A <: Tree](tree: Tree)(implicit - classifier: Classifier[Tree, A] + classifier: Classifier[Tree, A], ): Option[Tree] = findTreeWithParentSimple(tree)(classifier.apply) /** Returns true if a matching ancestor of a given type exists. */ @inline def existsParentOfType[A <: Tree](tree: Tree)(implicit - classifier: Classifier[Tree, A] + classifier: Classifier[Tree, A], ): Boolean = findTreeWithParentOfType[A](tree).isDefined @tailrec @@ -661,7 +661,7 @@ object TreeOps { getImplicitParamList(kwOwner).isDefined def shouldNotDangleAtDefnSite(tree: Option[Tree], isVerticalMultiline: Boolean)( - implicit style: ScalafmtConfig + implicit style: ScalafmtConfig, ): Boolean = !style.danglingParentheses.defnSite || { val excludes = style.danglingParentheses.getExclude(isVerticalMultiline) excludes.nonEmpty && tree.flatMap { @@ -803,7 +803,7 @@ object TreeOps { @tailrec final def followedBySelectOrApply( - tree: Tree + tree: Tree, )(implicit ftoks: FormatTokens): Boolean = tree.parent match { case Some(p: Term.New) => followedBySelectOrApply(p) case Some(_: Term.Select) => true @@ -828,7 +828,7 @@ object TreeOps { def rightIsCloseDelimForTrailingComma( left: Token, ft: FormatToken, - whenNL: Boolean = true + whenNL: Boolean = true, )(implicit style: ScalafmtConfig): Boolean = { def owner = ft.meta.rightOwner def isArgOrParamClauseSite(tree: Tree) = !whenNL || isArgClauseSite(tree) || @@ -847,7 +847,7 @@ object TreeOps { def findEnclosedBetweenParens( lt: Token, rt: Token, - tree: Tree + tree: Tree, ): Option[Tree] = { val beforeParens = lt.start val afterParens = rt.end @@ -871,7 +871,7 @@ object TreeOps { def getStyleAndOwners( topSourceTree: Tree, - baseStyle: ScalafmtConfig + baseStyle: ScalafmtConfig, ): (ScalafmtConfig, collection.Map[TokenHash, Tree]) = { var infixCount = 0 // Creates lookup table from token offset to its closest scala.meta tree @@ -1004,14 +1004,14 @@ object TreeOps { }) def isFewerBraces( - tree: Term.Apply + tree: Term.Apply, )(implicit dialect: Dialect, ftoks: FormatTokens): Boolean = dialect.allowFewerBraces && ftoks.getHead(tree.argClause).left.is[Colon] @tailrec def isFewerBracesLhs(tree: Tree)(implicit dialect: Dialect, - ftoks: FormatTokens + ftoks: FormatTokens, ): Boolean = !ftoks.isEnclosedInMatching(tree) && (tree match { case t: Term.Apply => isFewerBraces(t) @@ -1023,7 +1023,7 @@ object TreeOps { @tailrec def isFewerBracesRhs(tree: Tree)(implicit dialect: Dialect, - ftoks: FormatTokens + ftoks: FormatTokens, ): Boolean = !ftoks.isEnclosedInMatching(tree) && (tree match { case t: Term.Apply => isFewerBraces(t) 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 1686a99795..7845ce1e65 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 @@ -5,20 +5,20 @@ import scala.collection.mutable object ValidationOps { def checkNonNeg( - ns: sourcecode.Text[Int]* + ns: sourcecode.Text[Int]*, )(implicit errors: mutable.Buffer[String]): Unit = ns.foreach { n => if (n.value < 0) errors += s"${n.source} must be non-negative, was ${n.value}" } def checkPositive( - ns: sourcecode.Text[Int]* + 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}" } def checkNonNegOpt( - ns: sourcecode.Text[Option[Int]]* + 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" @@ -26,7 +26,7 @@ object ValidationOps { } def checkPositiveOpt( - ns: sourcecode.Text[Option[Int]]* + 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" @@ -34,15 +34,15 @@ object ValidationOps { } def addIf(what: sourcecode.Text[Boolean])(implicit - errors: mutable.Buffer[String] + errors: mutable.Buffer[String], ): Unit = addIfDirect(what.value, what.source) def addIf(what: sourcecode.Text[Boolean], why: => String)(implicit - errors: mutable.Buffer[String] + errors: mutable.Buffer[String], ): Unit = addIfDirect(what.value, s"$why: ${what.source}") def addIfDirect(what: Boolean, why: => String)(implicit - errors: mutable.Buffer[String] + errors: mutable.Buffer[String], ): Unit = if (what) errors += why } diff --git a/scalafmt-docs/src/main/scala/docs/FileModifier.scala b/scalafmt-docs/src/main/scala/docs/FileModifier.scala index 253a9c18ea..2304c096ab 100644 --- a/scalafmt-docs/src/main/scala/docs/FileModifier.scala +++ b/scalafmt-docs/src/main/scala/docs/FileModifier.scala @@ -15,7 +15,7 @@ class FileModifier extends StringModifier { override def process( info: String, code: Input, - reporter: Reporter + reporter: Reporter, ): String = { val file = AbsolutePath(info) if (file.isFile) { diff --git a/scalafmt-docs/src/main/scala/docs/Main.scala b/scalafmt-docs/src/main/scala/docs/Main.scala index 151d4afad4..6ecfaf9157 100644 --- a/scalafmt-docs/src/main/scala/docs/Main.scala +++ b/scalafmt-docs/src/main/scala/docs/Main.scala @@ -11,11 +11,11 @@ object Main { .withOut(Paths.get("website", "target", "docs")).withSiteVariables(Map( "VERSION" -> Versions.version, "STABLE_VERSION" -> Versions.stable, - "SCALAMETA_VERSION" -> Versions.scalameta + "SCALAMETA_VERSION" -> Versions.scalameta, )).withStringModifiers(List( new FileModifier, new ScalafmtModifier, - new DefaultsModifier + new DefaultsModifier, )).withArgs(args.toList) val exit = mdoc.Main.process(settings) diff --git a/scalafmt-docs/src/main/scala/docs/ScalafmtModifier.scala b/scalafmt-docs/src/main/scala/docs/ScalafmtModifier.scala index 72a5a61ef4..56351343e2 100644 --- a/scalafmt-docs/src/main/scala/docs/ScalafmtModifier.scala +++ b/scalafmt-docs/src/main/scala/docs/ScalafmtModifier.scala @@ -19,7 +19,7 @@ class ScalafmtModifier extends StringModifier { override def process( info: String, code: Input, - reporter: Reporter + reporter: Reporter, ): String = { val base = if (code.text.contains("package")) defaultConfig else defaultSbtConfig diff --git a/scalafmt-docs/src/main/scala/website/package.scala b/scalafmt-docs/src/main/scala/website/package.scala index 2da0201555..3dec9f19cc 100644 --- a/scalafmt-docs/src/main/scala/website/package.scala +++ b/scalafmt-docs/src/main/scala/website/package.scala @@ -42,7 +42,7 @@ package object website { val out = Files.newOutputStream( Paths.get("target", "website.log"), StandardOpenOption.CREATE, - StandardOpenOption.APPEND + StandardOpenOption.APPEND, ) new PrintStream(out) } @@ -118,7 +118,7 @@ ${scalaCode(formatted)} $configString -""" +""", ) } diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala index 31b86f4d62..b6d8a55030 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/CoursierDependencyDownloader.scala @@ -10,7 +10,7 @@ import coursierapi.{Dependency => CoursierDependency, _} private class CoursierDependencyDownloader( downloadProgressWriter: OutputStreamWriter, - customRepositories: Seq[Repository] + customRepositories: Seq[Repository], ) extends DependencyDownloader { override def download(dependencies: Seq[Dependency]): Try[Seq[URL]] = Try { @@ -29,7 +29,7 @@ private class CoursierDependencyDownloader( // Default repositories are ivy2local, central and also anything in COURSIER_REPOSITORIES overrides customRepositories ++ Repository.defaults().asScala ++ Seq( "https://oss.sonatype.org/content/repositories/snapshots", - "https://oss.sonatype.org/content/repositories/public" + "https://oss.sonatype.org/content/repositories/public", ).map(MavenRepository.of) } diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/Dependency.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/Dependency.scala index 30b0b3f4d6..d7030de598 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/Dependency.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/Dependency.scala @@ -10,7 +10,7 @@ object Dependency { val core = "scalafmt-core_" + scalaBinaryVersion Seq( Dependency(organization(version), core, version.toString), - Dependency("org.scala-lang", "scala-reflect", scalaVersion) + Dependency("org.scala-lang", "scala-reflect", scalaVersion), ) } diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtConfigLoader.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtConfigLoader.scala index 169ef056ea..391726be9e 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtConfigLoader.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtConfigLoader.scala @@ -16,7 +16,7 @@ trait ScalafmtConfigLoader { def load( configPath: Path, properties: ScalafmtProperties, - moduleLoader: ScalafmtModuleLoader + moduleLoader: ScalafmtModuleLoader, ): FormatEval[ScalafmtReflectConfig] } @@ -26,7 +26,7 @@ object ScalafmtConfigLoader extends ScalafmtConfigLoader { override def load( configPath: Path, properties: ScalafmtProperties, - moduleLoader: ScalafmtModuleLoader + moduleLoader: ScalafmtModuleLoader, ): FormatEval[ScalafmtReflectConfig] = for { version <- readVersion(configPath) // can't use current build directly, -dynamic doesn't include -core @@ -61,7 +61,7 @@ object ScalafmtConfigLoader extends ScalafmtConfigLoader { override def load( configPath: Path, properties: ScalafmtProperties, - moduleLoader: ScalafmtModuleLoader + moduleLoader: ScalafmtModuleLoader, ): FormatEval[ScalafmtReflectConfig] = Try(Files.getLastModifiedTime(configPath)).fold( _ => Left(new ConfigDoesNotExist(configPath)), @@ -71,7 +71,7 @@ object ScalafmtConfigLoader extends ScalafmtConfigLoader { def load() = loader.load(configPath, properties, moduleLoader) .map((_, currentTimestamp)) cache.getOrAddToCache(configPath, evict)(load).map(_._1) - } + }, ) } diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamic.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamic.scala index 603b6a0774..97fa1a3baf 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamic.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamic.scala @@ -8,7 +8,7 @@ import org.scalafmt.interfaces._ final case class ScalafmtDynamic( properties: ScalafmtProperties, moduleLoader: ScalafmtModuleLoader, - configLoader: ScalafmtConfigLoader + configLoader: ScalafmtConfigLoader, ) extends Scalafmt with RepositoryCredential.ScalafmtExtension with ScalafmtSessionFactory { @@ -16,11 +16,11 @@ final case class ScalafmtDynamic( def this() = this( ScalafmtProperties(), new ScalafmtModuleLoader.CachedProxy( - ScalafmtDynamic.defaultUncachedModuleLoader + ScalafmtDynamic.defaultUncachedModuleLoader, ), new ScalafmtConfigLoader.CachedProxy( - ScalafmtDynamic.defaultUncachedConfigLoader - ) + ScalafmtDynamic.defaultUncachedConfigLoader, + ), ) override def clear(): Unit = moduleLoader.close() @@ -42,7 +42,7 @@ final case class ScalafmtDynamic( copy(properties = properties.withMavenRepositories(value)) override def withRepositoryCredentials( - value: RepositoryCredential* + value: RepositoryCredential*, ): Scalafmt = copy(properties = properties.withRepositoryCredentials(value)) override def format(config: Path, file: Path, code: String): String = @@ -51,7 +51,7 @@ final case class ScalafmtDynamic( override def createSession(config: Path): ScalafmtSession = resolveConfig(config).fold( error => { properties.reportError(config, error); throw error }, - new ScalafmtDynamicSession(properties, _) + new ScalafmtDynamicSession(properties, _), ) def resolveConfig(configPath: Path): FormatEval[ScalafmtReflectConfig] = diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicError.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicError.scala index 76ec19ffae..a17d329605 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicError.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicError.scala @@ -12,7 +12,7 @@ object ScalafmtDynamicError { sealed abstract class ConfigError( val configPath: Path, msg: String, - cause: Throwable = null + cause: Throwable = null, ) extends ScalafmtDynamicError(msg, cause) class ConfigDoesNotExist(configPath: Path) @@ -27,14 +27,14 @@ object ScalafmtDynamicError { class CannotDownload( configPath: Path, version: ScalafmtVersion, - cause: Throwable = null + cause: Throwable = null, ) extends ConfigError(configPath, s"[v$version] failed to download", cause) class CorruptedClassPath( configPath: Path, version: ScalafmtVersion, urls: Seq[URL], - cause: Throwable + cause: Throwable, ) extends ConfigError(configPath, getCorruptedClassPath(version, urls), cause) def getCorruptedClassPath(version: ScalafmtVersion, urls: Seq[URL]): String = diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala index 70fc9e2d38..79d8369f99 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala @@ -9,7 +9,7 @@ import org.scalafmt.interfaces._ final case class ScalafmtDynamicSession( properties: ScalafmtProperties, - cfg: ScalafmtReflectConfig + cfg: ScalafmtReflectConfig, ) extends ScalafmtSession { import ScalafmtDynamicSession._ diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtModuleLoader.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtModuleLoader.scala index bbb0b9ed9f..c2bc0efc87 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtModuleLoader.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtModuleLoader.scala @@ -15,7 +15,7 @@ trait ScalafmtModuleLoader extends Closeable { def load( configPath: Path, version: ScalafmtVersion, - properties: ScalafmtProperties + properties: ScalafmtProperties, ): FormatEval[ScalafmtReflect] } @@ -27,13 +27,13 @@ object ScalafmtModuleLoader { override def load( configPath: Path, version: ScalafmtVersion, - properties: ScalafmtProperties + properties: ScalafmtProperties, ): FormatEval[ScalafmtReflect] = { val dependencies = Dependency.dependencies(version) val urls = downloader.create(properties).download(dependencies) urls.fold( x => Left(new CannotDownload(configPath, version, x)), - loadClassPath(configPath, version) + loadClassPath(configPath, version), ) } @@ -49,7 +49,7 @@ object ScalafmtModuleLoader { override def load( configPath: Path, version: ScalafmtVersion, - properties: ScalafmtProperties + properties: ScalafmtProperties, ): FormatEval[ScalafmtReflect] = { def load() = loader.load(configPath, version, properties) cache.getOrAddToCache(version)(load) @@ -64,7 +64,7 @@ object ScalafmtModuleLoader { } private def loadClassPath(configPath: Path, version: ScalafmtVersion)( - urls: Seq[URL] + urls: Seq[URL], ): FormatEval[ScalafmtReflect] = Try { val classloader = new URLClassLoader(urls.toArray, null) ScalafmtReflect(classloader, version) diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtProperties.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtProperties.scala index c9f2c9a0e9..a1c51baf32 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtProperties.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtProperties.scala @@ -9,7 +9,7 @@ final case class ScalafmtProperties( reporter: ScalafmtReporter = ConsoleScalafmtReporter, repositories: Seq[String] = Nil, repositoryCredentials: Seq[RepositoryCredential] = Nil, - respectExcludeFilters: Boolean = true + respectExcludeFilters: Boolean = true, ) { def withReporter(value: ScalafmtReporter): ScalafmtProperties = @@ -22,7 +22,7 @@ final case class ScalafmtProperties( copy(repositories = value) def withRepositoryCredentials( - value: Seq[RepositoryCredential] + value: Seq[RepositoryCredential], ): ScalafmtProperties = copy(repositoryCredentials = value) def reportError(file: Path, error: ScalafmtDynamicError): Unit = error match { diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflect.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflect.scala index e01ac9dd47..033b65713e 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflect.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflect.scala @@ -32,14 +32,14 @@ case class ScalafmtReflect(classLoader: ClassLoader, version: ScalafmtVersion) "format", classOf[String], defaultScalaFmtConfig.getClass, - scalaSetCls + scalaSetCls, ) private val formatMethodWithFilename = Try(scalafmtCls.getMethod( "format", classOf[String], defaultScalaFmtConfig.getClass, scalaSetCls, - classOf[String] + classOf[String], )).toOption lazy val intellijScalaFmtConfig: Option[ScalafmtReflectConfig] = @@ -52,7 +52,7 @@ case class ScalafmtReflect(classLoader: ClassLoader, version: ScalafmtVersion) private def parseConfigWith( f: => Try[Object], - path: Path = null + path: Path = null, ): Try[ScalafmtReflectConfig] = { import ScalafmtDynamicError.ConfigParseError @inline @@ -100,7 +100,7 @@ case class ScalafmtReflect(classLoader: ClassLoader, version: ScalafmtVersion) def tryFormat( code: String, config: ScalafmtReflectConfig, - fileOpt: Option[Path] = None + fileOpt: Option[Path] = None, ): Try[String] = { require(this eq config.fmtReflect) @@ -128,7 +128,7 @@ case class ScalafmtReflect(classLoader: ClassLoader, version: ScalafmtVersion) shortMessage, e.getMessage, range, - e + e, ) Failure(exception) } @@ -141,7 +141,7 @@ case class ScalafmtReflect(classLoader: ClassLoader, version: ScalafmtVersion) pos.invokeAs[Int]("startColumn"), pos.invokeAs[Int]("end"), pos.invokeAs[Int]("endLine"), - pos.invokeAs[Int]("endColumn") + pos.invokeAs[Int]("endColumn"), ) catch { case _: ReflectiveOperationException | _: ClassCastException => @@ -153,7 +153,7 @@ case class ScalafmtReflect(classLoader: ClassLoader, version: ScalafmtVersion) start.invokeAs[Int]("column"), end.invokeAs[Int]("offset"), end.invokeAs[Int]("line"), - end.invokeAs[Int]("column") + end.invokeAs[Int]("column"), ) } diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala index 563780b765..3a2028ad14 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtReflectConfig.scala @@ -10,7 +10,7 @@ import scala.util.Try //noinspection TypeAnnotation class ScalafmtReflectConfig private[dynamic] (val fmtReflect: ScalafmtReflect)( - private[dynamic] val target: Object + private[dynamic] val target: Object, ) { import ScalafmtReflectConfig._ import fmtReflect.classLoader @@ -49,7 +49,7 @@ class ScalafmtReflectConfig private[dynamic] (val fmtReflect: ScalafmtReflect)( } lazy val withSbtDialect: Try[ScalafmtReflectConfig] = Try( - target.invoke("forSbt") + target.invoke("forSbt"), ).recover { case ReflectionException(_: NoSuchMethodException) => target.invoke("withDialect", (dialectCls, sbtDialect)) }.map(new ScalafmtReflectConfig(fmtReflect)(_)) @@ -71,11 +71,11 @@ class ScalafmtReflectConfig private[dynamic] (val fmtReflect: ScalafmtReflect)( target.invoke( if (i == rewriteParamIdx) "apply$default$" + (rewriteParamIdx + 1) else if (publicParams.contains(p)) p - else p + "$access$" + i + else p + "$access$" + i, ) } new ScalafmtReflectConfig(fmtReflect)( - ctor.newInstance(fieldValues: _*).asInstanceOf[Object] + ctor.newInstance(fieldValues: _*).asInstanceOf[Object], ) } diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala index cb27931748..559d3cd4a4 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtVersion.scala @@ -7,7 +7,7 @@ case class ScalafmtVersion( minor: Int, patch: Int, rc: Int = 0, - snapshot: String = "" + snapshot: String = "", ) extends Comparable[ScalafmtVersion] { private val integerRepr: Int = { val max = 100 @@ -40,7 +40,7 @@ object ScalafmtVersion { positiveInt(minor), positiveInt(patch), if (rc == null) 0 else positiveInt(rc), - if (snapshot == null) "" else snapshot + if (snapshot == null) "" else snapshot, ) }.toOption case _ => None diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/PositionExceptionImpl.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/PositionExceptionImpl.scala index ff4a31c59b..390dd6b560 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/PositionExceptionImpl.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/PositionExceptionImpl.scala @@ -9,7 +9,7 @@ case class PositionExceptionImpl( shortMessage: String, longMessage: String, pos: RangePosition, - cause: Throwable + cause: Throwable, ) extends PositionException(longMessage, cause) { def start: Int = pos.start def end: Int = pos.end diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/RangePosition.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/RangePosition.scala index ad5af2966b..c9b7749b43 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/RangePosition.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/RangePosition.scala @@ -6,5 +6,5 @@ case class RangePosition( startCharacter: Int, end: Int, endLine: Int, - endCharacter: Int + endCharacter: Int, ) diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/VersionMismatch.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/VersionMismatch.scala index 26a90b4b8d..21aabc03f3 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/VersionMismatch.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/exceptions/VersionMismatch.scala @@ -2,5 +2,5 @@ package org.scalafmt.dynamic.exceptions case class VersionMismatch(obtainedVersion: String, expectedVersion: String) extends Exception( - s"Scalafmt version mismatch. Version in .scalafmt.conf is '$obtainedVersion' and running version is '$expectedVersion'." + s"Scalafmt version mismatch. Version in .scalafmt.conf is '$obtainedVersion' and running version is '$expectedVersion'.", ) diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala index 50a7d2dd0b..18b70ca5bf 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReentrantCache.scala @@ -12,7 +12,7 @@ class ReentrantCache[K, V] { @tailrec final def getOrAddToCache(key: K, shouldEvict: V => Boolean = _ => false)( - get: () => V + get: () => V, ): V = synchronized { // try to exit quickly from synchronized block cache.get(key) match { case Some(fut) => Right(fut) diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReflectUtils.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReflectUtils.scala index 1bae64e2de..b39d34c986 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReflectUtils.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/utils/ReflectUtils.scala @@ -30,7 +30,7 @@ object ReflectUtils { def invokeStaticOn( target: AnyRef, methodName: String, - args: (Class[_], AnyRef)* + args: (Class[_], AnyRef)*, ): AnyRef = { val method = clazz.getMethod(methodName, args.map(_._1): _*) method.invoke(target, args.map(_._2): _*) diff --git a/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala b/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala index 18c0137a7c..27daee1992 100644 --- a/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala +++ b/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/DynamicSuite.scala @@ -38,7 +38,7 @@ class DynamicSuite extends FunSuite { p.startLine, p.startCharacter, p.endLine, - p.endCharacter + p.endCharacter, ) val formattedMessage = pos.formatMessage("error", p.shortMessage) out.write(formattedMessage.getBytes(StandardCharsets.UTF_8)) @@ -46,14 +46,14 @@ class DynamicSuite extends FunSuite { } override def missingVersion( config: Path, - defaultVersion: String + defaultVersion: String, ): Unit = missingVersions += defaultVersion override def parsedConfig(config: Path, scalafmtVersion: String): Unit = { val n = parsed.getOrElse(scalafmtVersion, 0) parsed(scalafmtVersion) = n + 1 } override def trimStacktrace(e: Throwable): Unit = e.setStackTrace( - e.getStackTrace.takeWhile(!_.getClassName.contains("DynamicSuite")) + e.getStackTrace.takeWhile(!_.getClassName.contains("DynamicSuite")), ) } val dynamic: ScalafmtDynamic = cfgFunc { @@ -61,7 +61,7 @@ class DynamicSuite extends FunSuite { new ScalafmtDynamic( properties = ScalafmtProperties(reporter = reporter), moduleLoader = new ScalafmtModuleLoader.CachedProxy(getModuleLoader), - configLoader = new ScalafmtConfigLoader.CachedProxy(configLoader) + configLoader = new ScalafmtConfigLoader.CachedProxy(configLoader), ) } val config = Files.createTempFile("scalafmt", ".scalafmt.conf") @@ -79,7 +79,7 @@ class DynamicSuite extends FunSuite { |version="$newVersion" |$dialectLine |${rest.mkString("\n")} - |""".stripMargin + |""".stripMargin, ) } def relevant: String = out.toString @@ -100,7 +100,7 @@ class DynamicSuite extends FunSuite { def assertFormat()(implicit loc: Location): Unit = assertFormat("object A { }", "object A {}\n") def assertFormat(original: String, expected: String, file: Path = filename)( - implicit loc: Location + implicit loc: Location, ): Unit = { out.reset() val obtained = dynamic.format(config, file, original) @@ -118,7 +118,7 @@ class DynamicSuite extends FunSuite { assert(missingVersions.nonEmpty) } def assertThrows[A <: Throwable: ClassTag]( - code: String = "object A { }" + code: String = "object A { }", )(implicit loc: Location): A = { out.reset() intercept[A](dynamic.format(config, filename, code)) @@ -126,7 +126,7 @@ class DynamicSuite extends FunSuite { def assertError(expected: String)(implicit loc: Location): Unit = assertError("object A { }", expected) def assertError(code: String, expected: String, path: Path = filename)( - implicit loc: Location + implicit loc: Location, ): Unit = { out.reset() val obtained = dynamic.format(config, path, code) @@ -134,13 +134,13 @@ class DynamicSuite extends FunSuite { assertNotEquals( obtained.replaceAll("\\s*", " "), expected.replaceAll("\\s*", " "), - s"Formatter shouldn't have produced plausible format ($path)" + s"Formatter shouldn't have produced plausible format ($path)", ) } } def check(name: String, cfgFunc: ScalafmtDynamic => ScalafmtDynamic = identity)( - fn: Format => Unit + fn: Format => Unit, ): Unit = test(name) { val format = new Format(name, cfgFunc) try fn(format) @@ -162,11 +162,11 @@ class DynamicSuite extends FunSuite { "1.2.0", "1.1.0", "1.0.0-RC4", - "1.0.0" + "1.0.0", ) def checkExhaustive(name: String)( - config: String => String + config: String => String, )(fn: (Format, String) => Unit): Unit = testedVersions.foreach { version => test(s"$name [v=$version]") { val format = new Format(name, identity) @@ -201,7 +201,7 @@ class DynamicSuite extends FunSuite { code, s"""|$name.scala:1:8: error:$dialectError ${bq}identifier$bq expected but ${bq}object$bq found |$code - | ^^^^^^""".stripMargin + | ^^^^^^""".stripMargin, ) } } @@ -256,7 +256,7 @@ class DynamicSuite extends FunSuite { | Did you mean 'maxColumn'? |max = 70 |^ - |""".stripMargin + |""".stripMargin, ) } @@ -267,7 +267,7 @@ class DynamicSuite extends FunSuite { |project.excludeFilters = [ | ".*foo(" |] - |""".stripMargin + |""".stripMargin, ) val err = f.assertThrows[ScalafmtDynamicError.ConfigParseError]().getMessage assertNoDiff( @@ -275,7 +275,7 @@ class DynamicSuite extends FunSuite { """|Invalid config: Illegal regex in configuration: .*foo( |reason: Unclosed group near index 6 |.*foo( - |""".stripMargin + |""".stripMargin, ) } @@ -286,12 +286,12 @@ class DynamicSuite extends FunSuite { |project.excludePaths = [ | "foo.scala" |] - |""".stripMargin + |""".stripMargin, ) val err = f.assertThrows[ScalafmtDynamicError.ConfigParseError]().getMessage assertNoDiff( err.takeRight(120), - "Invalid config: Illegal pattern in configuration: foo.scala" + "Invalid config: Illegal pattern in configuration: foo.scala", ) } @@ -305,7 +305,7 @@ class DynamicSuite extends FunSuite { val parseError = f.assertThrows[ScalafmtDynamicError.ConfigParseError]() assert( parseError.getMessage - .contains("Key 'invalid' may not be followed by token: end of file") + .contains("Key 'invalid' may not be followed by token: end of file"), ) f.setConfig("maxColumn = 40") @@ -346,7 +346,7 @@ class DynamicSuite extends FunSuite { f.assertFormat( s"""lazy val x = "$version"""", s"""lazy val x = "$version"\n""", - path + path, ) // test scala doesn't allow top-level terms (not passing path here) if (version >= "3.0.0" || scalaVersion >= "213") f @@ -355,7 +355,7 @@ class DynamicSuite extends FunSuite { "lazy val x = project", s"""|$name.scala:1:1: error:$dialectError classes cannot be lazy |lazy val x = project - |^^^^""".stripMargin + |^^^^""".stripMargin, ) // check wrapped literals, supported in sbt using scala 2.13+ val wrappedLiteral = "object a { val x: Option[0] = Some(0) }" @@ -366,14 +366,14 @@ class DynamicSuite extends FunSuite { s"""$filename:1:28: error:$dialectError ${bq}identifier$bq expected but ${bq}integer constant$bq found |$wrappedLiteral | ^""".stripMargin, - path + path, ) } def assertIsWrappedLiteralSuccess(): Unit = f.assertFormat( wrappedLiteral, wrappedLiteral.replaceAll(" +", " ").trim + "\n", - path + path, ) if (!isSbt && scalaVersion >= "213" && version > "2.0") assertIsWrappedLiteralSuccess() @@ -468,7 +468,7 @@ class DynamicSuite extends FunSuite { } assertNoDiff( thrown1.getMessage.take(60), - "Invalid config: Default dialect is deprecated; use explicit:" + "Invalid config: Default dialect is deprecated; use explicit:", ) val thrown2 = intercept[ScalafmtDynamicError.ConfigParseError] { @@ -476,7 +476,7 @@ class DynamicSuite extends FunSuite { } assertNoDiff( thrown2.getMessage.take(60), - "Invalid config: Default dialect is deprecated; use explicit:" + "Invalid config: Default dialect is deprecated; use explicit:", ) } @@ -484,7 +484,7 @@ class DynamicSuite extends FunSuite { f.setConfig( s"""|version=3.0.0-RC6 |align=does-not-exist - |""".stripMargin + |""".stripMargin, ) val thrown = f.assertThrows[ScalafmtDynamicError.ConfigParseError]() assertNoDiff( @@ -494,7 +494,7 @@ class DynamicSuite extends FunSuite { | expected : Object | "align" : "does-not-exist", |^ - |""".stripMargin + |""".stripMargin, ) } @@ -502,7 +502,7 @@ class DynamicSuite extends FunSuite { f.setConfig( s"""|version=2.7.5 |align=does-not-exist - |""".stripMargin + |""".stripMargin, ) val thrown = f.assertThrows[ScalafmtDynamicError.ConfigParseError]() assertNoDiff( @@ -510,14 +510,14 @@ class DynamicSuite extends FunSuite { """|Invalid config: Type mismatch; | found : String (value: "does-not-exist") | expected : Object - |""".stripMargin + |""".stripMargin, ) } check("invalid version - current") { f => f.setConfig( s"""|version=current - |""".stripMargin + |""".stripMargin, ) val error = f.assertThrows[ScalafmtDynamicError.ConfigInvalidVersion]() .getMessage @@ -527,7 +527,7 @@ class DynamicSuite extends FunSuite { check("invalid version - missing") { f => f.setConfig( s"""|maxColumn = 40 - |""".stripMargin + |""".stripMargin, ) val error = f.assertThrows[ScalafmtDynamicError.ConfigMissingVersion]() .getMessage @@ -535,7 +535,7 @@ class DynamicSuite extends FunSuite { } private def assertDynamicConfig(fmt: Format)( - f: ScalafmtReflectConfig => Unit + f: ScalafmtReflectConfig => Unit, ): Unit = fmt.dynamic.resolveConfig(fmt.config) match { case Left(e) => fail("failed to load config", e) case Right(cfg) => f(cfg) @@ -545,7 +545,7 @@ class DynamicSuite extends FunSuite { name: String, version: String, dialect: String, - rest: String* + rest: String*, )(f: ScalafmtReflectConfig => Unit): Unit = check(s"$name [v=$version d=$dialect]") { fmt => fmt.setVersion(version, dialect, rest: _*) @@ -568,7 +568,7 @@ class DynamicSuite extends FunSuite { s"check indent.main", "3.0.0", "scala211", - s"indent.main = 3" + s"indent.main = 3", ) { cfg => assertEquals(cfg.indentMain, Some(3)) assertEquals(cfg.indentCallSite, Some(2)) @@ -581,7 +581,7 @@ class DynamicSuite extends FunSuite { version, "scala211", s"$section.callSite = 3", - s"$section.defnSite = 5" + s"$section.defnSite = 5", ) { cfg => assertEquals(cfg.indentMain, Some(2)) assertEquals(cfg.indentCallSite, Some(3)) @@ -606,7 +606,7 @@ private object DynamicSuite { override def load( cfg: Path, ver: ScalafmtVersion, - props: ScalafmtProperties + props: ScalafmtProperties, ): FormatEval[ScalafmtReflect] = if (ver.toString == nightly) Right(ScalafmtReflect(clsLoader, ver)) else downloader.load(cfg, ver, props) diff --git a/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/PositionSyntax.scala b/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/PositionSyntax.scala index 96721a5d4e..3add35cc2a 100644 --- a/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/PositionSyntax.scala +++ b/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/PositionSyntax.scala @@ -12,7 +12,7 @@ object PositionSyntax { if (message.isEmpty) "" else if (severity.isEmpty) " " else if (message.startsWith("\n")) ":" - else ": " + else ": ", ).append(message).append(pos.rangeText).toString } @@ -48,7 +48,7 @@ object PositionSyntax { val startColumn = if (i == pos.startLine) pos.startColumn else 0 val endColumn = if (i == pos.endLine) pos.endColumn else Int.MaxValue sb.append("\n> ").append( - lineContent(i, startColumn = startColumn, endColumn = endColumn).text + lineContent(i, startColumn = startColumn, endColumn = endColumn).text, ) i += 1 } @@ -66,13 +66,13 @@ object PositionSyntax { private def lineContent( line: Int, startColumn: Int = 0, - endColumn: Int = Int.MaxValue + endColumn: Int = Int.MaxValue, ): Position = Position.Range( pos.input, startLine = line, startColumn = startColumn, endLine = line, - endColumn = endColumn + endColumn = endColumn, ) private def lineContent: String = pos match { diff --git a/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/ScalafmtVersionSuite.scala b/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/ScalafmtVersionSuite.scala index 1d233bdada..e6e1e205d0 100644 --- a/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/ScalafmtVersionSuite.scala +++ b/scalafmt-dynamic/src/test/scala/org/scalafmt/dynamic/ScalafmtVersionSuite.scala @@ -8,32 +8,32 @@ class ScalafmtVersionSuite extends FunSuite { assertEquals(ScalafmtVersion.parse("0.1.3"), Some(ScalafmtVersion(0, 1, 3))) assertEquals( ScalafmtVersion.parse("2.0.0-RC4"), - Some(ScalafmtVersion(2, 0, 0, 4)) + Some(ScalafmtVersion(2, 0, 0, 4)), ) assertEquals(ScalafmtVersion.parse("2.1.1"), Some(ScalafmtVersion(2, 1, 1))) assertEquals( ScalafmtVersion.parse("2.2.3-SNAPSHOT"), - Some(ScalafmtVersion(2, 2, 3, 0, "-SNAPSHOT")) + Some(ScalafmtVersion(2, 2, 3, 0, "-SNAPSHOT")), ) assertEquals( ScalafmtVersion.parse("2.0.0-RC1-SNAPSHOT"), - Some(ScalafmtVersion(2, 0, 0, 1, "-SNAPSHOT")) + Some(ScalafmtVersion(2, 0, 0, 1, "-SNAPSHOT")), ) assertEquals( ScalafmtVersion.parse("2.2.2-SNAPSHOT"), - Some(ScalafmtVersion(2, 2, 2, 0, "-SNAPSHOT")) + Some(ScalafmtVersion(2, 2, 2, 0, "-SNAPSHOT")), ) assertEquals( ScalafmtVersion.parse("99.99.99-RC99-SNAPSHOT"), - Some(ScalafmtVersion(99, 99, 99, 99, "-SNAPSHOT")) + Some(ScalafmtVersion(99, 99, 99, 99, "-SNAPSHOT")), ) assertEquals( ScalafmtVersion.parse("99.99.99-RC99+foobar"), - Some(ScalafmtVersion(99, 99, 99, 99, "+foobar")) + Some(ScalafmtVersion(99, 99, 99, 99, "+foobar")), ) assertEquals( ScalafmtVersion.parse("99.99.99+foobar"), - Some(ScalafmtVersion(99, 99, 99, 0, "+foobar")) + Some(ScalafmtVersion(99, 99, 99, 0, "+foobar")), ) } @@ -42,11 +42,11 @@ class ScalafmtVersionSuite extends FunSuite { assertEquals(ScalafmtVersion.parse("2.2.2").get.toString, "2.2.2") assertEquals( ScalafmtVersion.parse("2.2.2-SNAPSHOT").get.toString, - "2.2.2-SNAPSHOT" + "2.2.2-SNAPSHOT", ) assertEquals( ScalafmtVersion.parse("2.2.2-RC2-SNAPSHOT").get.toString, - "2.2.2-RC2-SNAPSHOT" + "2.2.2-RC2-SNAPSHOT", ) } 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 46f8d96129..7019f5e0c0 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 @@ -13,7 +13,7 @@ trait BatchPathFinder { final def findMatchingFiles( filterFilesToo: Boolean, - paths: AbsoluteFile* + paths: AbsoluteFile*, ): Seq[AbsoluteFile] = if (paths.isEmpty) findFiles() else { @@ -49,7 +49,7 @@ object BatchPathFinder { } final class GitBranchFiles(git: GitOps, branch: String)( - val matches: Path => Boolean + val matches: Path => Boolean, ) extends BatchPathFinder { override def findFiles(dir: AbsoluteFile*): Seq[AbsoluteFile] = git .diff(branch, dir: _*).filter(x => matches(x.path)) 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 57b8cd59a1..44acb1f517 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 @@ -49,7 +49,7 @@ object FileOps { .readAttributes( file, classOf[BasicFileAttributes], - LinkOption.NOFOLLOW_LINKS + LinkOption.NOFOLLOW_LINKS, ) def listFiles(path: String): Seq[Path] = listFiles(getFile(path)) @@ -59,7 +59,7 @@ object FileOps { def listFiles( file: Path, - matches: (Path, BasicFileAttributes) => Boolean + matches: (Path, BasicFileAttributes) => Boolean, ): Seq[Path] = { val iter = Files.find(file, Integer.MAX_VALUE, (p, a) => matches(p, a)) try iter.iterator().asScala.toList @@ -106,7 +106,7 @@ object FileOps { } def writeFile(filename: String, content: String)(implicit - codec: Codec + codec: Codec, ): Unit = writeFile(getFile(filename), content) @inline @@ -120,7 +120,7 @@ object FileOps { def getCanonicalConfigFile( workingDirectory: AbsoluteFile, - config: Option[Path] = None + config: Option[Path] = None, ): Option[Try[Path]] = config.fold(tryGetConfigInDir(workingDirectory)) { x => val file = workingDirectory.join(x) tryCheckConfigFile(file) diff --git a/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/GitOps.scala b/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/GitOps.scala index c1591567a4..bba45fcca8 100644 --- a/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/GitOps.scala +++ b/scalafmt-sysops/shared/src/main/scala/org/scalafmt/sysops/GitOps.scala @@ -19,7 +19,7 @@ object GitOps { def getCanonicalConfigFile( cwd: AbsoluteFile, - config: Option[Path] = None + config: Option[Path] = None, ): Option[Try[Path]] = FileOps.getCanonicalConfigFile(cwd, config) .orElse(getRootConfigFile) @@ -28,7 +28,7 @@ object GitOps { def getProposedConfigFile( cwd: AbsoluteFile, - config: Option[Path] = None + config: Option[Path] = None, ): AbsoluteFile = config.fold { obj.rootDir.getOrElse(cwd) / FileOps.defaultConfigFileName }(cwd / _) diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/CommentTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/CommentTest.scala index 1a6a543fee..b109a90f96 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/CommentTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/CommentTest.scala @@ -8,7 +8,7 @@ class CommentTest extends FunSuite { private val javadocStyle: ScalafmtConfig = ScalafmtConfig.default .copy(docstrings = ScalafmtConfig.default.docstrings - .copy(style = Docstrings.Asterisk, wrap = Docstrings.Wrap.no) + .copy(style = Docstrings.Asterisk, wrap = Docstrings.Wrap.no), ) test("remove trailing space in comments") { diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/CustomStructureTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/CustomStructureTest.scala index b152153e4d..5d85a34792 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/CustomStructureTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/CustomStructureTest.scala @@ -8,7 +8,7 @@ import scala.meta.internal.parsers.ScalametaParser class CustomStructureTest extends FunSuite { private def check(original: String, expected: Tree, dialect: Dialect)(implicit - loc: munit.Location + loc: munit.Location, ): Unit = { val parser = new ScalametaParser(Input.String(original))(dialect) assertNoDiff(parser.parseStat().structure, expected.structure) @@ -30,17 +30,17 @@ class CustomStructureTest extends FunSuite { Term.Name("a"), Some(Type.Apply( Type.Name("Foo"), - Type.ArgClause(List(Type.Wildcard(Type.Bounds(None, None)))) + Type.ArgClause(List(Type.Wildcard(Type.Bounds(None, None)))), )), - None + None, )), - None - )) + None, + )), )), Some(Type.Name("Unit")), - Term.Name("???") + Term.Name("???"), ), - dialects.Scala3 + dialects.Scala3, ) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/Debug.scala b/scalafmt-tests/src/test/scala/org/scalafmt/Debug.scala index 9968df57ca..1f6e8fe54e 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/Debug.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/Debug.scala @@ -70,7 +70,7 @@ class Debug(val verbose: Boolean) { val clean = "%-15s".format(LoggerOps.cleanup(tok).slice(0, 15)) stack.prepend( s"${posWidth.format(tok.end)}: $clean" + - s" ${state.split} ${prev.indentation} ${prev.column} [${state.cost}]" + s" ${state.split} ${prev.indentation} ${prev.column} [${state.cost}]", ) iter(prev) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/FidelityTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/FidelityTest.scala index dc6fc4bef6..2da22df429 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/FidelityTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/FidelityTest.scala @@ -1,6 +1,6 @@ package org.scalafmt -import scala.meta.dialects.Scala211 +import scala.meta.dialects.Scala213 import java.io.File import java.nio.file.Path @@ -27,7 +27,7 @@ class FidelityTest extends FunSuite with FormatAssertions { "GitCommit.scala", "/target/", "/resources/", - "/gh-pages/" + "/gh-pages/", ).map(_.replace("/", File.separator)) FileOps.listFiles(".").filter { x => val filename = x.toString @@ -40,11 +40,11 @@ class FidelityTest extends FunSuite with FormatAssertions { val formatted = Scalafmt.formatCode( example.code, ScalafmtConfig.default, - filename = example.filename + filename = example.filename, ) assertFormatPreservesAst(example.filename, example.code, formatted.get)( scala.meta.parsers.Parse.parseSource, - Scala211 + Scala213, ) } } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/FormatTests.scala b/scalafmt-tests/src/test/scala/org/scalafmt/FormatTests.scala index 52ea4329d5..0fa99ab38c 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/FormatTests.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/FormatTests.scala @@ -40,7 +40,7 @@ class FormatTests extends FunSuite with CanRunTests with FormatAssertions { val result = Scalafmt.formatCode( t.original, t.style.copy(runner = scalafmtRunner(runner, debug)), - filename = t.filename + filename = t.filename, ) debug.printTest() val resultEither = result.formatted.toEither @@ -63,7 +63,7 @@ class FormatTests extends FunSuite with CanRunTests with FormatAssertions { val result2 = Scalafmt.formatCode( obtained, t.style.copy(runner = scalafmtRunner(runner, debug2)), - filename = t.filename + filename = t.filename, ) debug2.printTest() val result2Either = result2.formatted.toEither @@ -71,7 +71,7 @@ class FormatTests extends FunSuite with CanRunTests with FormatAssertions { case Left(e: ParseException) if !onlyManual => assertEquals( "test does not parse: " + parseException2Message(e, obtained), - t.expected + t.expected, ) case Left(e) => throw FormatException(e, obtained) case Right(code) => @@ -99,7 +99,7 @@ class FormatTests extends FunSuite with CanRunTests with FormatAssertions { t.filename, t.original, obtained, - result.config.runner + result.config.runner, ) } @@ -113,7 +113,7 @@ class FormatTests extends FunSuite with CanRunTests with FormatAssertions { val k = for { _ <- Future(FileOps.writeFile( s"target${File.separator}index.html", - Report.heatmap(results) + Report.heatmap(results), )) } yield () // Travis exits right after running tests. diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/ManualTests.scala b/scalafmt-tests/src/test/scala/org/scalafmt/ManualTests.scala index 8f904c4d12..5a3b5db7b5 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/ManualTests.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/ManualTests.scala @@ -28,7 +28,7 @@ object ManualTests extends HasTests { original, isSkip(name), isOnly(name), - style + style, ) } } yield test @@ -44,7 +44,7 @@ object ManualTests extends HasTests { content, false, false, - style + style, ) } manualFiles ++ scalaFiles diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtProps.scala b/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtProps.scala index c60f107f70..1be29b1714 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtProps.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtProps.scala @@ -16,12 +16,12 @@ class ScalafmtProps extends FunSuite with FormatAssertions { import ScalafmtProps._ def getBugs( config: ScalafmtConfig = ScalafmtConfig.default, - count: Int = Int.MaxValue + count: Int = Int.MaxValue, ): mutable.Seq[(CorpusFile, Observation[Bug])] = { val corpus = Corpus.files( // TODO(olafur) remove once testkit 1.7 is out Corpus.fastparse - .copy(Corpus.fastparse.url.replace("olafurpg", "scalameta")) + .copy(Corpus.fastparse.url.replace("olafurpg", "scalameta")), ).take(count).toBuffer.par SyntaxAnalysis.run[Observation[Bug]](corpus) { file => val code = file.read @@ -35,7 +35,7 @@ class ScalafmtProps extends FunSuite with FormatAssertions { "Idempotence", formatted, formattedSecondTime, - diff.getMessage + diff.getMessage, ) } Nil @@ -52,7 +52,7 @@ class ScalafmtProps extends FunSuite with FormatAssertions { case e: Error.FormatterOutputDoesNotParse => List(Observation( e.getMessage.linesIterator.slice(1, 2).mkString(""), e.line, - FormattedOutputDoesNotParse + FormattedOutputDoesNotParse, )) case e: Error => List(Observation(e.getMessage, -1, Unknown(e))) case e: DiffFailure => @@ -61,7 +61,7 @@ class ScalafmtProps extends FunSuite with FormatAssertions { List(Observation( e.diff.linesIterator.take(3).mkString("\n"), line, - NonIdempotent + NonIdempotent, )) } } @@ -93,7 +93,7 @@ object ScalafmtProps { title: String, expected: String, obtained: String, - diff: String + diff: String, ) extends Exception def main(args: Array[String]): Unit = { diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala index 2efc7c24d2..c953428ad9 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtRunnerTest.scala @@ -15,7 +15,7 @@ class ScalafmtRunnerTest extends FunSuite { | | b, |) - | """.stripMargin + | """.stripMargin, ).parse[Source].get } } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtTest.scala index 0f9ade902a..bed3693136 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/ScalafmtTest.scala @@ -8,7 +8,7 @@ class ScalafmtTest extends FunSuite { def check( original: String, expected: String, - config: ScalafmtConfig = ScalafmtConfig.default + config: ScalafmtConfig = ScalafmtConfig.default, )(implicit loc: munit.Location): Unit = test(logger.revealWhitespace(original).take(30)) { val obtained = Scalafmt.formatCode(original, config).get @@ -25,7 +25,7 @@ class ScalafmtTest extends FunSuite { """|object A { println("HELLO!") } | |// comment - |""".stripMargin + |""".stripMargin, ) check( """|object A { @@ -38,7 +38,7 @@ class ScalafmtTest extends FunSuite { | val xx = 3 |} |""".stripMargin, - config.ScalafmtConfig.defaultWithAlign + config.ScalafmtConfig.defaultWithAlign, ) check( """|object A { function(aaaaaaaa, bbbbbbbbbb, ddddd(eeeeeeeeee, fffffff, gggggggg)) } @@ -51,7 +51,7 @@ class ScalafmtTest extends FunSuite { | ) |} |""".stripMargin, - config.ScalafmtConfig.default.copy(maxColumn = 40) + config.ScalafmtConfig.default.copy(maxColumn = 40), ) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/UnitTests.scala b/scalafmt-tests/src/test/scala/org/scalafmt/UnitTests.scala index 69cc65cafc..689cfaf8d9 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/UnitTests.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/UnitTests.scala @@ -24,7 +24,7 @@ object UnitTests extends HasTests { if (sys.env.contains("CI") && test.only) sys.error( s"""|Please remove ONLY from test '${test.name}' in file '$filename'. |Tests with ONLY will not be merged, this feature is only meant to be used for local development. - | """.stripMargin + | """.stripMargin, ) test } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliOptionsTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliOptionsTest.scala index 3a2ce3d222..0ea6bd5023 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliOptionsTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliOptionsTest.scala @@ -16,29 +16,29 @@ class CliOptionsTest extends FunSuite { ScalafmtConfig.fromHoconString("preset = foobar"), Configured.error( "Unknown style \"foobar\". Expected one of: " + - "Scala.js, IntelliJ, default, defaultWithAlign" - ) + "Scala.js, IntelliJ, default, defaultWithAlign", + ), ) assertEquals( ScalafmtConfig.fromHoconString( """|preset = defaultWithAlign |maxColumn = 100 - |""".stripMargin + |""".stripMargin, ), - Configured.ok(ScalafmtConfig.defaultWithAlign.copy(maxColumn = 100)) + Configured.ok(ScalafmtConfig.defaultWithAlign.copy(maxColumn = 100)), ) assertEquals( ScalafmtConfig.fromHoconString("preset = intellij"), - Configured.ok(ScalafmtConfig.intellij) + Configured.ok(ScalafmtConfig.intellij), ) assertEquals( ScalafmtConfig.fromHoconString("preset = Scala.js"), - Configured.ok(ScalafmtConfig.scalaJs) + Configured.ok(ScalafmtConfig.scalaJs), ) assertEquals( ScalafmtConfig.fromHoconString("preset = defaultWithAlign"), - Configured.ok(ScalafmtConfig.defaultWithAlign) + Configured.ok(ScalafmtConfig.defaultWithAlign), ) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliTest.scala index f997d945df..25431852aa 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/cli/CliTest.scala @@ -4,7 +4,7 @@ import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, IOException, - PrintStream + PrintStream, } import java.nio.charset.StandardCharsets import java.nio.file.{Files, Path} @@ -27,7 +27,7 @@ abstract class AbstractCliTest extends FunSuite { def runArgs( args: Array[String], init: CliOptions = baseCliOptions, - exitCode: ExitCode = ExitCode.Ok + exitCode: ExitCode = ExitCode.Ok, ): Unit = run(Cli.getConfig(args, init).get, exitCode) def run(options: CliOptions, exitCode: ExitCode = ExitCode.Ok) = @@ -38,7 +38,7 @@ abstract class AbstractCliTest extends FunSuite { def assertContains(out: String, expected: String) = assert( CliTest.stripCR(out).contains(CliTest.stripCR(expected)), - out + "\n should have contained \n" + expected + out + "\n should have contained \n" + expected, ) val unformatted = """| @@ -80,7 +80,7 @@ abstract class AbstractCliTest extends FunSuite { cmds: Seq[Array[String]], exitCode: ExitCode = ExitCode.Ok, assertOut: String => Unit = { _ => }, - testExitCode: Option[ExitCode] = None + testExitCode: Option[ExitCode] = None, ): Unit = cmds.foreach { args => val out = new ByteArrayOutputStream() val init: CliOptions = getMockOptions(input, input, new PrintStream(out)) @@ -117,7 +117,7 @@ trait CliTestBehavior { "--config", scalafmtConfig.toFile.getPath, originalTmpFile.toFile.getPath, - originalTmpFile2.toFile.getPath + originalTmpFile2.toFile.getPath, ) runArgs(args) val obtained = FileOps.readFile(originalTmpFile.toString) @@ -133,7 +133,7 @@ trait CliTestBehavior { "--stdout", "--config-str", s"""{version="$version",style=IntelliJ}""", - originalTmpFile.toFile.getPath + originalTmpFile.toFile.getPath, ) val baos = new ByteArrayOutputStream() val ps = new PrintStream(baos) @@ -159,7 +159,7 @@ trait CliTestBehavior { "--assume-filename", "build.sbt", "--config", - scalafmtConfig.toFile.getPath + scalafmtConfig.toFile.getPath, ) val printToStdout = getConfig(args) val bais = new ByteArrayInputStream(sbtOriginal.getBytes) @@ -179,7 +179,7 @@ trait CliTestBehavior { tmpFile.toFile.getPath, "--test", "--config-str", - s"""{version="$version",style=IntelliJ}""" + s"""{version="$version",style=IntelliJ}""", ) runArgs(args, exitCode = ExitCode.TestError) val str = FileOps.readFile(tmpFile.toString) @@ -192,7 +192,7 @@ trait CliTestBehavior { tmpFile.toFile.getPath, "--test", "--config-str", - s"""{version="$version",style=IntelliJ, docstring = Asterisk}""" + s"""{version="$version",style=IntelliJ, docstring = Asterisk}""", ) runArgs(args, exitCode = ExitCode.UnexpectedError) } @@ -203,7 +203,7 @@ trait CliTestBehavior { val args = Array( "--config-str", s"""{version="$version",style=IntelliJ}""", - tmpFile.toFile.getAbsolutePath + tmpFile.toFile.getAbsolutePath, ) Cli.exceptionThrowingMainWithOptions(args, baseCliOptions) val obtained = FileOps.readFile(tmpFile.toString) @@ -219,7 +219,7 @@ trait CliTestBehavior { |lazy val x = project |/foo.sc |lazy val x = project - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/foo.sbt |lazy val x = project @@ -233,7 +233,7 @@ trait CliTestBehavior { runArgs(Array( input.toString(), "--config-str", - s"""{version="$version",style=IntelliJ}""" + s"""{version="$version",style=IntelliJ}""", )) val obtained = dir2string(input) assertNoDiff(obtained, expected) @@ -255,7 +255,7 @@ trait CliTestBehavior { | |/target/nested3/DoNotFormatMe.scala |object CIgnoreME { } - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/foo.sbt |lazy val x = project @@ -277,7 +277,7 @@ trait CliTestBehavior { s"""{version="$version",style=IntelliJ}""", input.toString(), "--exclude", - "target/nested".asFilename + "target/nested".asFilename, )) val obtained = dir2string(input) @@ -290,7 +290,7 @@ trait CliTestBehavior { val args = Array( s"$filename.scala".asFilename, "--config-str", - s"""{version="$version",style=IntelliJ}""" + s"""{version="$version",style=IntelliJ}""", ) intercept[IOException] { Cli.exceptionThrowingMainWithOptions(args, baseCliOptions) @@ -315,12 +315,12 @@ trait CliTestBehavior { "--mode", "diff", "--config-str", - s"""{version="$version",style=IntelliJ}""" + s"""{version="$version",style=IntelliJ}""", )) val stdin = getConfig(Array( "--stdin", "--config-str", - s"""{version="$version",style=IntelliJ}""" + s"""{version="$version",style=IntelliJ}""", )).copy(common = CommonOptions(in = new ByteArrayInputStream("".getBytes))) run(stdin) } @@ -338,7 +338,7 @@ trait CliTestBehavior { |version = "$version" |maxColumn = 2 |project.excludeFilters = [target] - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/.scalafmt.conf @@ -365,7 +365,7 @@ trait CliTestBehavior { |object FormatMe |/foo.sc |object FormatMe - |""".stripMargin + |""".stripMargin, ), """|/foo.sc |object FormatMe @@ -373,7 +373,7 @@ trait CliTestBehavior { |/foo.scala |object FormatMe |""".stripMargin, - Seq(Array("--config-str", s"""{version="$version"}""")) + Seq(Array("--config-str", s"""{version="$version"}""")), ) } @@ -390,7 +390,7 @@ trait CliTestBehavior { |/.scalafmt.conf |version="$version" |maxColumn = 2 - |""".stripMargin + |""".stripMargin, ) val workingDir = input / "nested" val options: CliOptions = { @@ -415,7 +415,7 @@ trait CliTestBehavior { |/sbt.sbt |$sbtOriginal |/sbt.sbtfile - |$sbtOriginal""".stripMargin + |$sbtOriginal""".stripMargin, ) val config = root / "scalafmt.conf" @@ -441,7 +441,7 @@ trait CliTestBehavior { |/inner3/file1.scala |$unformatted |/inner3/file2.scalahala - |$unformatted""".stripMargin + |$unformatted""".stripMargin, ) val inner1 = root / "inner1" val inner2 = root / "inner2" @@ -469,7 +469,7 @@ trait CliTestBehavior { |/inner3/file1.scala |$unformatted |/inner3/file2.scalahala - |$unformatted""".stripMargin + |$unformatted""".stripMargin, ) val inner1 = root / "inner1" val inner2 = root / "inner2" @@ -479,7 +479,7 @@ trait CliTestBehavior { val opts = Seq( "--respect-project-filters", - s"""--config-str {version="$version"}""" + s"""--config-str {version="$version"}""", ) ++ Seq(inner1, inner2, full1, full2) runWith(root, opts.mkString(" ")) @@ -496,7 +496,7 @@ trait CliTestBehavior { |style = intellij |/foo.scala |object A - | """.stripMargin + | """.stripMargin, ) val config = (root / "scalafmt.conf").toString() val toFormat = (root / "foo.scala").toString() @@ -520,7 +520,7 @@ trait CliTestBehavior { s"""{version="$version",style=IntelliJ}""", "-i", "-f", - fileStr(file1, file2, file3) + fileStr(file1, file2, file3), ) runArgs(args) val obtained = FileOps.readFile(file1.toString) @@ -545,9 +545,9 @@ trait CliTestBehavior { out, s"""foo.scala:1: error:$dialectError illegal start of simple expression |object A { foo( } - | ^""".stripMargin + | ^""".stripMargin, ), - Some(ExitCode.Ok) + Some(ExitCode.Ok), ) } @@ -555,7 +555,7 @@ trait CliTestBehavior { val exit = Console.withErr(NoopOutputStream.printStream) { Cli.mainWithOptions( Array("--foobar"), - getMockOptions(AbsoluteFile.userDir) + getMockOptions(AbsoluteFile.userDir), ) } assertEquals(exit, ExitCode.CommandLineArgumentError, exit) @@ -585,8 +585,8 @@ trait CliTestBehavior { |-object A { } |+object A {} |error: --test failed - |To fix this ...""".stripMargin - ) + |To fix this ...""".stripMargin, + ), ) } @@ -602,8 +602,8 @@ trait CliTestBehavior { assert( out.contains(s"foo.scala:2: error:$dialectError") && out.contains("end of file") && out.contains("error: ParseError=2"), - out - ) + out, + ), ) } @@ -623,8 +623,8 @@ trait CliTestBehavior { assert( out.contains(s"foo.scala:2: error:$dialectError") && out.contains(s"end of file") && out.contains("error: ParseError=2"), - out - ) + out, + ), ) } @@ -644,8 +644,8 @@ trait CliTestBehavior { assert( out.contains("Invalid field: blah") || out.contains("found option 'blah' which wasn't expected"), - s"assertion failed [$out]" - ) + s"assertion failed [$out]", + ), ) } @@ -675,11 +675,11 @@ trait CliTestBehavior { Seq(Array( "--config-str", s"""{version="$version",onTestFailure="$expected"}""", - "--test" + "--test", )), ExitCode.TestError, assertOut = - out => assert(out.contains(expected) && !out.contains(unexpected)) + out => assert(out.contains(expected) && !out.contains(unexpected)), ) } @@ -705,8 +705,8 @@ trait CliTestBehavior { assertOut = out => assert( out.contains("bar.scala") && !out.contains("baz.scala") && - out.contains("dir/foo.scala") - ) + out.contains("dir/foo.scala"), + ), ) } } @@ -735,9 +735,9 @@ class CliTest extends AbstractCliTest with CliTestBehavior { assertOut = out => assertContains( out, - s"""Illegal pattern in configuration: foo.scala""".stripMargin + s"""Illegal pattern in configuration: foo.scala""".stripMargin, ), - Some(ExitCode.UnexpectedError) + Some(ExitCode.UnexpectedError), ) } @@ -763,9 +763,9 @@ class CliTest extends AbstractCliTest with CliTestBehavior { """|Illegal regex in configuration: .*foo( |reason: Unclosed group near index 6 |.*foo( - |""".stripMargin + |""".stripMargin, ), - Some(ExitCode.UnexpectedError) + Some(ExitCode.UnexpectedError), ) } @@ -778,7 +778,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { string2dir(input), input, Seq( - Array("--debug") // debug options is needed to output running scalafmt version + Array("--debug"), // debug options is needed to output running scalafmt version ), ExitCode.UnsupportedVersion, assertOut = out => { @@ -787,7 +787,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { assertEquals(out1, out2) // two invocations val msg = s"error: missing Scalafmt configuration file." assertEquals(out1.substring(0, msg.length), msg) - } + }, ) } @@ -802,7 +802,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { string2dir(input), input, Seq( - Array("--debug") // debug options is needed to output running scalafmt version + Array("--debug"), // debug options is needed to output running scalafmt version ), ExitCode.UnsupportedVersion, assertOut = out => { @@ -811,7 +811,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { assertEquals(out1, out2) // two invocations val msg = s"error: missing Scalafmt version." assertEquals(out1.substring(0, msg.length), msg) - } + }, ) } @@ -833,12 +833,12 @@ class CliTest extends AbstractCliTest with CliTestBehavior { val obtained = Console.withErr(errStream) { Cli.getConfig( Array("--config", "foo", "--config-str", "bar"), - CliTest.defaultOptions + CliTest.defaultOptions, ) } assertEquals( errStream.toString.trim, - "Error: may not specify both --config and --config-str" + "Error: may not specify both --config and --config-str", ) assertEquals(None: Option[CliOptions], obtained) } @@ -857,7 +857,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 2 |project { includePaths = ["glob:**/bar.scala"] } - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/.scalafmt.conf @@ -891,7 +891,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 2 |project { excludePaths = ["glob:**target**"] } - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/.scalafmt.conf @@ -925,7 +925,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 2 |project { includeFilters = ["bar"] } - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/.scalafmt.conf @@ -964,7 +964,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { | includePaths = $defaultIncludePathsJson | includeFilters = ["bar"] |} - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/.scalafmt.conf @@ -1003,7 +1003,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 8 |project.includePaths."+" = ["glob:**.md"] - |""".stripMargin + |""".stripMargin, ) val expected = s"""| |/.scalafmt.conf @@ -1037,7 +1037,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |``` |/.scalafmt.conf |version = $stableVersion - |""".stripMargin + |""".stripMargin, ) val expected = s"""| |/.scalafmt.conf @@ -1070,7 +1070,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { | */ | } |``` - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/foobar.md | Intro @@ -1087,7 +1087,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { runArgs(Array( input.toString(), "--config-str", - s"""{version = "$stableVersion", project.includePaths."+" = ["glob:**.md"]}""" + s"""{version = "$stableVersion", project.includePaths."+" = ["glob:**.md"]}""", )) val obtained = dir2string(input) assertNoDiff(obtained, expected) @@ -1101,7 +1101,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { | ```scala mdoc | object A { } | ``` - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/foobar2.md | Intro text: @@ -1112,7 +1112,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { runArgs(Array( input.toString(), "--config-str", - s"""{version = "$stableVersion", project.includePaths."+" = ["glob:**.md"]}""" + s"""{version = "$stableVersion", project.includePaths."+" = ["glob:**.md"]}""", )) val obtained = dir2string(input) assertNoDiff(obtained, expected) @@ -1131,7 +1131,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { | */ | } |``` - |""".stripMargin + |""".stripMargin, ) val expected = s"""|/foobar.md |```scala mdoc @@ -1148,9 +1148,9 @@ class CliTest extends AbstractCliTest with CliTestBehavior { Array( input.toString(), "--config-str", - s"""{version = "$stableVersion", project.includePaths."+" = ["glob:**.md"]}""" + s"""{version = "$stableVersion", project.includePaths."+" = ["glob:**.md"]}""", ), - exitCode = ExitCode.ParseError + exitCode = ExitCode.ParseError, ) val obtained = dir2string(input) assertNoDiff(obtained, expected) @@ -1172,7 +1172,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |version = $stableVersion |maxColumn = 8 |project.includePaths."+" = ["glob:**.md"] - |""".stripMargin + |""".stripMargin, ) val expected = s"""| |/.scalafmt.conf @@ -1211,8 +1211,8 @@ class CliTest extends AbstractCliTest with CliTestBehavior { common = options.common.copy( in = new ByteArrayInputStream(codeNoEol.getBytes), out = Console.out, - err = Console.err - ) + err = Console.err, + ), ) run(options2, ExitCode.TestError) } @@ -1225,7 +1225,7 @@ class CliTest extends AbstractCliTest with CliTestBehavior { |@@ -4,1 +4,2 @@ | } |+ - |""".stripMargin + |""".stripMargin, ) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/cli/FileTestOps.scala b/scalafmt-tests/src/test/scala/org/scalafmt/cli/FileTestOps.scala index 2d224164c1..ad15b3cbae 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/cli/FileTestOps.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/cli/FileTestOps.scala @@ -47,12 +47,12 @@ object FileTestOps { def getMockOptions( baseDir: AbsoluteFile, workingDir: AbsoluteFile, - out: PrintStream = NoopOutputStream.printStream + out: PrintStream = NoopOutputStream.printStream, ): CliOptions = CliOptions.default.copy( baseConfig = ScalafmtConfig.default, gitOpsConstructor = _ => new FakeGitOps(baseDir), common = CliOptions.default.common - .copy(cwd = Some(workingDir), out = out, err = out) + .copy(cwd = Some(workingDir), out = out, err = out), ) val baseCliOptions: CliOptions = diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala index 38a5be8c87..88048af716 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/config/ScalafmtConfigTest.scala @@ -12,7 +12,7 @@ class ScalafmtConfigTest extends FunSuite { | "/sbt-test/" | "bin/issue" |] - | """.stripMargin + | """.stripMargin, ).get assert(config.project.matcher.matches("qux/Kazbar.scala")) assert(!config.project.matcher.matches("foo/sbt-test/src/main")) @@ -29,7 +29,7 @@ class ScalafmtConfigTest extends FunSuite { | newlines.topLevelBodyIfMinStatements = [] | } |} - | """.stripMargin + | """.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 @@ -37,7 +37,7 @@ class ScalafmtConfigTest extends FunSuite { assertEquals(nlCfg2.source, Newlines.unfold) assertEquals( nlCfg1.topLevelBodyIfMinStatements, - Seq(Newlines.before, Newlines.after) + Seq(Newlines.before, Newlines.after), ) assertEquals(nlCfg2.topLevelBodyIfMinStatements, Seq.empty) } @@ -47,7 +47,7 @@ class ScalafmtConfigTest extends FunSuite { """| |align = none |align.stripMargin = true - | """.stripMargin + | """.stripMargin, ).get // none was ignored assertEquals(config.align, Align(stripMargin = true)) @@ -58,7 +58,7 @@ class ScalafmtConfigTest extends FunSuite { """ |align.preset = none |align.stripMargin = true - """.stripMargin + """.stripMargin, ).get assertEquals(config.align, Align.none.copy(stripMargin = true)) } @@ -67,14 +67,14 @@ class ScalafmtConfigTest extends FunSuite { val config1 = ScalafmtConfig.fromHoconString( """| |runner.dialect = scala213 - |""".stripMargin + |""".stripMargin, ).get assert(!config1.runner.getDialect.allowToplevelTerms) val config2 = ScalafmtConfig.fromHoconString( """| |runner.dialectOverride.allowToplevelTerms = true |runner.dialect = scala213 - |""".stripMargin + |""".stripMargin, ).get assert(config2.runner.getDialect.allowToplevelTerms) } @@ -84,7 +84,7 @@ class ScalafmtConfigTest extends FunSuite { """| |runner.dialect = scala213 |rewrite.trailingCommas = never - |""".stripMargin + |""".stripMargin, ).get assert(config1.hasRewrites) val config2 = config1.withoutRewrites @@ -97,7 +97,7 @@ class ScalafmtConfigTest extends FunSuite { |runner.dialect = scala213 |rewrite.trailingCommas = keep |docstrings.removeEmpty = true - |""".stripMargin + |""".stripMargin, ).get assert(config1.hasRewrites) val config2 = config1.withoutRewrites diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/config/StandardProjectLayoutTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/config/StandardProjectLayoutTest.scala index fefd59c86b..2b033677c6 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/config/StandardProjectLayoutTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/config/StandardProjectLayoutTest.scala @@ -36,7 +36,7 @@ class StandardProjectLayoutTest extends munit.FunSuite { "/prj/src/main/scalaX/src/src/x/src/src/src" -> "scalaX", "/prj/src/main/scalaX/src/src/src/x/src/src" -> "scalaX", "/prj/src/main/scalaX/src/src/src/src/x/src" -> "scalaX", - "/prj/src/main/scalaX/src/src/src/src/src/x" -> "scalaX" + "/prj/src/main/scalaX/src/src/src/src/src/x" -> "scalaX", ).foreach { case (path, expectedLang) => test(s"StandardConvention.getLang($path) == $expectedLang") { val actualLang = getLang(AbsoluteFile(path)) @@ -58,7 +58,7 @@ class StandardProjectLayoutTest extends munit.FunSuite { "/prj/src/main/scalaX/src/test/scalaY/foo" -> Some(true), "/prj/src/test/scalaX/src/main/scalaY/foo" -> Some(false), "/prj/src/none/scalaX/src/main/scalaY/foo" -> Some(false), - "/prj/src/none/scalaX/src/test/scalaY/foo" -> Some(true) + "/prj/src/none/scalaX/src/test/scalaY/foo" -> Some(true), ).foreach { case (path, expectedTest) => test(s"StandardConvention.isTest($path) == $expectedTest") { val actualTest = getInfo(AbsoluteFile(path)).map(_.isTest) @@ -83,7 +83,7 @@ class StandardProjectLayoutTest extends munit.FunSuite { (s3, "scala-2", s213), (s213, "scala-3", s3), (s3, "scala-3", None), - (nd(dialects.Scala3Future), "scala-3", None) + (nd(dialects.Scala3Future), "scala-3", None), ).foreach { case (curDialectOpt, lang, expDialectOpt) => val curName = curDialectOpt.map(_.name).orNull val expName = expDialectOpt.map(_.name).orNull diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/stats/JavaInfo.scala b/scalafmt-tests/src/test/scala/org/scalafmt/stats/JavaInfo.scala index 1d6a0a1fb1..1eda26a6c4 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/stats/JavaInfo.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/stats/JavaInfo.scala @@ -7,6 +7,6 @@ object JavaInfo { def apply(): JavaInfo = JavaInfo( sys.props("java.vm.name"), sys.props("java.vm.vendor"), - sys.props("java.vm.version") + sys.props("java.vm.version"), ) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/stats/MachineStats.scala b/scalafmt-tests/src/test/scala/org/scalafmt/stats/MachineStats.scala index 35af0188bf..168c4a5e09 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/stats/MachineStats.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/stats/MachineStats.scala @@ -4,7 +4,7 @@ case class MachineStats( javaInfo: JavaInfo, osInfo: OsInfo, runtimeInfo: RuntimeInfo, - gitInfo: GitInfo + gitInfo: GitInfo, ) object MachineStats { diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/stats/RuntimeInfo.scala b/scalafmt-tests/src/test/scala/org/scalafmt/stats/RuntimeInfo.scala index fa5bd965e0..97caedff51 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/stats/RuntimeInfo.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/stats/RuntimeInfo.scala @@ -3,7 +3,7 @@ package org.scalafmt.stats case class RuntimeInfo( availableProcessor: Int, maxMemory: Long, - totalMemory: Long + totalMemory: Long, ) object RuntimeInfo { @@ -13,7 +13,7 @@ object RuntimeInfo { RuntimeInfo( runtime.availableProcessors(), runtime.maxMemory(), - runtime.totalMemory() + runtime.totalMemory(), ) } } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/stats/TestStats.scala b/scalafmt-tests/src/test/scala/org/scalafmt/stats/TestStats.scala index 086724d323..2cc9bed572 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/stats/TestStats.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/stats/TestStats.scala @@ -10,7 +10,7 @@ case class TestStats( javaInfo: JavaInfo, osInfo: OsInfo, runtimeInfo: RuntimeInfo, - gitInfo: GitInfo + gitInfo: GitInfo, ) { def shortInfo: String = s"TestStats(created=${new Date(createdAt)}," + @@ -35,6 +35,6 @@ object TestStats { JavaInfo(), OsInfo(), RuntimeInfo(), - GitInfo() + GitInfo(), ) } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/sysops/GitOpsTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/sysops/GitOpsTest.scala index dc69dcce9d..67ed0d1f22 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/sysops/GitOpsTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/sysops/GitOpsTest.scala @@ -44,7 +44,7 @@ class GitOpsTest extends FunSuite { private def touch( name: String = Random.alphanumeric.take(10).mkString, - dir: Option[AbsoluteFile] = None + dir: Option[AbsoluteFile] = None, ): AbsoluteFile = { val d = dir.orElse(ops.rootDir).get.jfile val f = File.createTempFile(name, ".ext", d) @@ -55,7 +55,7 @@ class GitOpsTest extends FunSuite { def symbolicLinkTo( file: AbsoluteFile, name: String = Random.alphanumeric.take(10).mkString, - dir: Option[AbsoluteFile] = None + dir: Option[AbsoluteFile] = None, ): AbsoluteFile = { val linkFile = File .createTempFile(name, ".ext", dir.orElse(ops.rootDir).get.jfile) @@ -85,7 +85,7 @@ class GitOpsTest extends FunSuite { ops.lsTree(ops.workingDirectory).filterNot(_ == initFile) def mkDir( - dirName: String = Random.alphanumeric.take(10).mkString + dirName: String = Random.alphanumeric.take(10).mkString, ): AbsoluteFile = { val file = ops.rootDir.getOrElse(ops.workingDirectory) / dirName file.mkdir() @@ -149,7 +149,7 @@ class GitOpsTest extends FunSuite { } def diff(br: String, cwd: AbsoluteFile*)(implicit - ops: GitOpsImpl + ops: GitOpsImpl, ): Seq[AbsoluteFile] = ops.diff(br, cwd: _*) def diff(cwd: AbsoluteFile*)(implicit ops: GitOpsImpl): Seq[AbsoluteFile] = @@ -332,7 +332,7 @@ private object GitOpsTest { // Git commands def git(cmd: String, args: String*)(implicit ops: GitOpsImpl, - loc: Location + loc: Location, ): Seq[String] = Try(ops.exec("git" +: cmd +: args)) match { case Failure(f) => Assertions.fail(s"Failed git command. Got: $f") case Success(s) => s diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/DeleteTree.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/DeleteTree.scala index 40025ae0eb..8c5db3d578 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/DeleteTree.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/DeleteTree.scala @@ -14,12 +14,12 @@ object DeleteTree { class DeleteTree extends FileVisitor[Path] { override def preVisitDirectory( dir: Path, - attrs: BasicFileAttributes + attrs: BasicFileAttributes, ): FileVisitResult = FileVisitResult.CONTINUE override def visitFile( file: Path, - attrs: BasicFileAttributes + attrs: BasicFileAttributes, ): FileVisitResult = { Files.delete(file) FileVisitResult.CONTINUE @@ -30,7 +30,7 @@ class DeleteTree extends FileVisitor[Path] { override def postVisitDirectory( dir: Path, - exc: IOException + exc: IOException, ): FileVisitResult = { Files.delete(dir) FileVisitResult.CONTINUE diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/DiffTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/DiffTest.scala index 5cec5817cc..59e5080976 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/DiffTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/DiffTest.scala @@ -14,7 +14,7 @@ case class DiffTest( expected: String, skip: Boolean, only: Boolean, - style: ScalafmtConfig + style: ScalafmtConfig, ) { val file = DiffTest.testDir.relativize(Paths.get(loc.path)).toString val fullName = s"$file:${loc.line}: $name" diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/FormatAssertions.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/FormatAssertions.scala index 3e6b27cd2a..cc64a492a6 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/FormatAssertions.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/FormatAssertions.scala @@ -19,16 +19,16 @@ trait FormatAssertions { filename: String, original: String, obtained: String, - runner: ScalafmtRunner + runner: ScalafmtRunner, ): Unit = assertFormatPreservesAst(filename, original, obtained)( runner.getParser, - runner.getDialectForParser + runner.getDialectForParser, ) def assertFormatPreservesAst[T <: Tree]( filename: String, original: String, - obtained: String + obtained: String, )(implicit ev: Parse[T], dialect: Dialect): Unit = { import scala.meta._ def toInput(code: String) = Scalafmt @@ -49,7 +49,7 @@ trait FormatAssertions { case Parsed.Error(pos, _, details: ParseException) => throw FormatterOutputDoesNotParse( parseException2Message(details, obtained), - pos.startLine + pos.startLine, ) case _ => } @@ -62,7 +62,7 @@ trait FormatAssertions { val input = new ByteArrayInputStream(ast.getBytes("UTF-8")) val command = List( "clang-format", - "-style={ContinuationIndentWidth: 2, ColumnLimit: 120}" + "-style={ContinuationIndentWidth: 2, ColumnLimit: 120}", ) (command #< input).!!.trim } @@ -87,7 +87,7 @@ trait FormatAssertions { (" " * e.pos.startColumn) + "^", // arrow linesAfterCaret.mkString("\n"), "====== full result: ======", - obtained.stripTrailing() + obtained.stripTrailing(), ).filter(_.nonEmpty).mkString("", "\n", "\n") } } diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/HasTests.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/HasTests.scala index 35cbedb91d..9529fc1604 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/HasTests.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/HasTests.scala @@ -14,7 +14,7 @@ import org.scalafmt.config.{ NamedDialect, ScalafmtConfig, ScalafmtParser, - ScalafmtRunner + ScalafmtRunner, } import org.scalafmt.sysops.FileOps import org.scalafmt.tests.BuildInfo @@ -37,7 +37,7 @@ trait HasTests extends FormatAssertions { case evt: CompleteFormat => dg.completed(evt) case x: Written => dg.locations = x.formatLocations case _ => - } + }, ) lazy val debugResults = mutable.ArrayBuilder.make[Result] @@ -87,7 +87,7 @@ trait HasTests extends FormatAssertions { throw new IllegalArgumentException( s"""|Failed to parse filename $filename: |$cfg - |$c""".stripMargin + |$c""".stripMargin, ) } val style: ScalafmtConfig = loadStyle( @@ -96,7 +96,7 @@ trait HasTests extends FormatAssertions { filename2parse(filename).fold(base) { x => base.copy(runner = base.runner.withParser(x)) } - } + }, ) @tailrec @@ -107,7 +107,7 @@ trait HasTests extends FormatAssertions { var linenum = numLines(head, 2) val inputOutputRegex = Pattern.compile( s"(.+?)$sep(?:(.+)$sep===$sep)?(.+)$sep>>>(?: +(.+?))?$sep(.*)", - Pattern.DOTALL + Pattern.DOTALL, ) tail.map { t => val matcher = inputOutputRegex.matcher(t) @@ -128,7 +128,7 @@ trait HasTests extends FormatAssertions { trimmed(expected), moduleSkip || isSkip(name), moduleOnly || isOnly(name), - testStyle + testStyle, ) linenum += numLines(t) test @@ -155,7 +155,7 @@ trait HasTests extends FormatAssertions { output, Option(debug.formatTokenExplored).fold(0)(_.max), debug.explored, - debug.elapsedNs + debug.elapsedNs, ) } @@ -167,14 +167,14 @@ trait HasTests extends FormatAssertions { val result = Scalafmt.formatCode( t.original, t.style.copy(runner = runner), - filename = t.filename + filename = t.filename, ) val obtained = result.formatted.get if (t.style.rewrite.rules.isEmpty) assertFormatPreservesAst( t.filename, t.original, obtained, - result.config.runner + result.config.runner, ) assertNoDiff(obtained, t.expected) } @@ -188,7 +188,7 @@ trait HasTests extends FormatAssertions { entry.formatWhitespace(0) builder += FormatOutput( sb.result(), - Option(debug.formatTokenExplored).fold(-1)(_(token.meta.idx)) + Option(debug.formatTokenExplored).fold(-1)(_(token.meta.idx)), ) }) builder.result() @@ -209,7 +209,7 @@ object HasTests { align = ScalafmtConfig.default.align.copy( tokens = Seq.empty, openParenCallSite = true, - openParenDefnSite = true + openParenDefnSite = true, ), optIn = ScalafmtConfig.default.optIn .copy(breakChainOnFirstMethodDot = false), @@ -217,7 +217,7 @@ object HasTests { // looks nice, but updating the unit tests would take too much time. // I can imagine that I will throw away most of the tests and replace them // with autogenerated tests from scala-repos. - runner = ScalafmtConfig.conservativeRunner.withDialect(defaultDialect) + runner = ScalafmtConfig.conservativeRunner.withDialect(defaultDialect), ) val unitTest80 = testing.copy(indent = Indents(callSite = 4, defnSite = 4)) diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/Report.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/Report.scala index 8a647d4fb7..e2ee9526cd 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/Report.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/Report.scala @@ -25,10 +25,10 @@ object Report { code( heatmapBar(result.test.style), raw(result.obtainedHtml), - span("\n" + ("‾" * result.test.style.maxColumn)) - ) - ) - ) + span("\n" + ("‾" * result.test.style.maxColumn)), + ), + ), + ), )).render def heatmapBar(scalaStyle: ScalafmtConfig): Seq[Text.Modifier] = @@ -53,12 +53,12 @@ object Report { |The formatter uses Dijkstra's shortest path to determine the |formatting with the "cheapest" cost. The red regions are |tokens the formatter visits often. - | """.stripMargin + | """.stripMargin, ), ul( li("Declaration arguments: bin packed"), - li("Callsite arguments: one arg per line if overflowing") - ) + li("Callsite arguments: one arg per line if overflowing"), + ), ) def testWidth(result: Result) = result.test.style.maxColumn.toDouble * 9.625 @@ -69,7 +69,7 @@ object Report { h1( id := "title", s"Compare ${after.gitInfo.branch} and" + s" ${before.gitInfo.branch}" + - s" (${before.shortCommit}...${after.shortCommit})" + s" (${before.shortCommit}...${after.shortCommit})", ), explanation, after.intersectResults(before).sortBy { case (aft, bef) => @@ -83,24 +83,24 @@ object Report { td("Time (ms)"), td(bef.timeMs), td(aft.timeMs), - td(bef.timeMs - aft.timeMs) + td(bef.timeMs - aft.timeMs), ), tr( td("States"), td(bef.visitedStates), td(aft.visitedStates), - td(aft.visitedStates - bef.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)))) - ) + code(heatmapBar(aft.test.style), raw(mkHtml(mergeResults(aft, bef)))), + ), ) - } + }, )).render def mergeResults(after: Result, before: Result): Seq[FormatOutput] = after diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/Result.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/Result.scala index 601ea01be5..aec9d89e2d 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/Result.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/Result.scala @@ -9,7 +9,7 @@ case class Result( tokens: Seq[FormatOutput], maxVisitsOnSingleToken: Int, visitedStates: Int, - timeNs: Long + timeNs: Long, ) { def title = f"${test.name} (${timeMs}ms, $visitedStates states)" diff --git a/scalafmt-tests/src/test/scala/org/scalafmt/util/StyleMapTest.scala b/scalafmt-tests/src/test/scala/org/scalafmt/util/StyleMapTest.scala index 005acfa482..c3ad764b2a 100644 --- a/scalafmt-tests/src/test/scala/org/scalafmt/util/StyleMapTest.scala +++ b/scalafmt-tests/src/test/scala/org/scalafmt/util/StyleMapTest.scala @@ -19,11 +19,11 @@ class StyleMapTest extends FunSuite { val m = new FormatOps(code, ScalafmtConfig.default) assertEquals( m.styleMap.at(m.tokens.head).maxColumn, - ScalafmtConfig.default.maxColumn + ScalafmtConfig.default.maxColumn, ) assertEquals( m.styleMap.at(m.tokens.find(_.left.syntax == "println").get).maxColumn, - 100 + 100, ) assertEquals(m.styleMap.at(m.tokens.last).maxColumn, 110) } @@ -49,21 +49,21 @@ class StyleMapTest extends FunSuite { val newHeadConfig = newFormatOps.styleMap.at(headToken) assertEquals( headConfig.alignMap("=").last.owner.get.pattern(), - defaultEquals + defaultEquals, ) assertEquals( newHeadConfig.alignMap("=").last.owner.get.pattern(), - overrideEquals + overrideEquals, ) val newPrintlnConfig = newFormatOps.styleMap.at(printlnToken) assertEquals( printlnConfig.alignMap("=").last.owner.get.pattern(), - overrideEquals + overrideEquals, ) assertEquals( newPrintlnConfig.alignMap("=").last.owner.get.pattern(), - overrideEquals + overrideEquals, ) } @@ -77,8 +77,8 @@ class StyleMapTest extends FunSuite { val formatOps = new FormatOps( code, ScalafmtConfig(newlines = - Newlines(implicitParamListModifierForce = List(Newlines.before)) - ) + Newlines(implicitParamListModifierForce = List(Newlines.before)), + ), ) val token1 = formatOps.tokens.head val token2 = formatOps.tokens.find(_.left.syntax == "println").get @@ -94,14 +94,14 @@ class StyleMapTest extends FunSuite { assertEquals(style1.newlines.implicitParamListModifierForce, defaultValue) assertEquals( newStyle1.newlines.implicitParamListModifierForce, - overrideValue + overrideValue, ) val newStyle2 = formatOps2.styleMap.at(token2) assertEquals(style2.newlines.implicitParamListModifierForce, overrideValue) assertEquals( newStyle2.newlines.implicitParamListModifierForce, - overrideValue + overrideValue, ) }