From bd166f77ccae37fbb0c05608d61e236bc6ce0e52 Mon Sep 17 00:00:00 2001 From: Hanns Holger Rutz Date: Thu, 4 Jan 2018 03:55:45 +0100 Subject: [PATCH] code clean-up, latest dependencies - cleans up code style: no procedure syntax, return types in public methods, removed unused variables, various improvements such as `!isEmpty` to `nonEmpty`, `.size > 0` to `nonEmpty` etc. - bring Scala versions and ScalaTest dependency to latest versions - add migration-manager plugin to monitor version compatibility --- build.sbt | 15 +- cli/src/main/scala/scalariform/Utils.scala | 4 +- .../commandline/CommandLineOptionParser.scala | 37 +- .../scala/scalariform/commandline/Main.scala | 36 +- .../commandline/ScalaFileWalker.scala | 2 +- project/build.properties | 2 +- project/build.sbt | 2 +- project/plugins.sbt | 11 +- .../scala/scalariform/ScalaVersions.scala | 18 +- .../scalariform/astselect/AstSelector.scala | 8 +- .../scalariform/formatter/Alignment.scala | 8 +- .../formatter/AnnotationFormatter.scala | 2 +- .../formatter/CaseClauseFormatter.scala | 32 +- .../formatter/CommentFormatter.scala | 6 +- .../scalariform/formatter/ExprFormatter.scala | 105 +++--- .../scalariform/formatter/FormatResult.scala | 12 +- .../formatter/FormatterDirectiveParser.scala | 11 +- .../formatter/FormatterState.scala | 10 +- .../formatter/ScalaFormatter.scala | 112 +++--- .../formatter/SpecificFormatter.scala | 6 +- .../formatter/TemplateFormatter.scala | 17 +- .../scalariform/formatter/TypeFormatter.scala | 10 +- .../scalariform/formatter/XmlFormatter.scala | 6 +- .../preferences/IFormattingPreferences.scala | 12 +- .../preferences/PreferenceDescriptor.scala | 18 +- .../PreferencesImporterExporter.scala | 9 +- .../main/scala/scalariform/lexer/Chars.scala | 8 +- .../scala/scalariform/lexer/HiddenToken.scala | 6 +- .../scalariform/lexer/HiddenTokens.scala | 18 +- .../scala/scalariform/lexer/LexerMode.scala | 6 +- .../scala/scalariform/lexer/ModeStack.scala | 22 +- .../scalariform/lexer/NewlineInferencer.scala | 8 +- .../lexer/RedundantSemicolonDetector.scala | 5 +- .../scala/scalariform/lexer/ScalaLexer.scala | 26 +- .../scalariform/lexer/ScalaLexerReader.scala | 4 +- .../scalariform/lexer/ScalaOnlyLexer.scala | 50 +-- .../scala/scalariform/lexer/TagState.scala | 2 +- .../main/scala/scalariform/lexer/Token.scala | 8 +- .../scala/scalariform/lexer/TokenType.scala | 12 +- .../lexer/UnicodeEscapeReader.scala | 10 +- .../lexer/WhitespaceAndCommentsGrouper.scala | 10 +- .../scala/scalariform/lexer/XmlLexer.scala | 33 +- .../scala/scalariform/parser/AstNodes.scala | 184 +++++----- .../parser/InferredSemicolonScalaParser.scala | 320 +++++++++--------- .../scalariform/parser/ScalaParser.scala | 100 +++--- version.sbt | 2 +- 46 files changed, 659 insertions(+), 686 deletions(-) diff --git a/build.sbt b/build.sbt index 62858f00..47ed6850 100644 --- a/build.sbt +++ b/build.sbt @@ -11,8 +11,8 @@ lazy val commonSettings = inConfig(Test)(Defaults.testSettings) ++ scalaVersion := crossScalaVersions.value.head, crossScalaVersions := Seq( "2.12.4", - "2.11.11", - "2.10.6" + "2.11.12", + "2.10.7" ), scalacOptions ++= (CrossVersion.partialVersion(scalaVersion.value) match { case Some((2, 12)) => Seq( @@ -68,7 +68,7 @@ def getPublishToRepo = Def.setting { Some(Opts.resolver.sonatypeStaging) } -lazy val subprojectSettings = commonSettings :+ ( +def subprojectSettings(projectName: String) = commonSettings ++ Seq( ScalariformKeys.preferences := PreferencesImporterExporter.loadPreferences( (baseDirectory.value / ".." / "formatterPreferences.properties").getPath) ) @@ -85,11 +85,11 @@ def scala2_11Dependencies = Def.setting { lazy val scalariform = (project enablePlugins(BuildInfoPlugin) - settings(subprojectSettings) + settings(subprojectSettings("scalariform")) settings(publishSettings("scalariform")) settings( libraryDependencies ++= scala2_11Dependencies.value, - libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test", + libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.4" % "test", // sbt doesn't automatically load the content of the MANIFST.MF file, therefore // we have to do it here by ourselves. Furthermore, the version format in the // MANIFEST.MF is `version.qualifier`, which means that we have to replace @@ -118,13 +118,14 @@ lazy val scalariform = (project } Package.JarManifest(m) }, - testOptions in Test += Tests.Argument("-oI") + testOptions in Test += Tests.Argument("-oI"), + mimaPreviousArtifacts := Set(organization.value %% "scalariform" % "0.2.6") ) ) lazy val cli = (project enablePlugins(BuildInfoPlugin) - settings(subprojectSettings) + settings(subprojectSettings("cli")) settings(publishSettings("cli")) settings( libraryDependencies += "commons-io" % "commons-io" % "1.4", diff --git a/cli/src/main/scala/scalariform/Utils.scala b/cli/src/main/scala/scalariform/Utils.scala index 43aba717..ecf9296a 100644 --- a/cli/src/main/scala/scalariform/Utils.scala +++ b/cli/src/main/scala/scalariform/Utils.scala @@ -1,8 +1,8 @@ package scalariform object Utils { - def writeText(file: java.io.File, text: String, encodingOpt: Option[String] = None) { - import java.io.{OutputStreamWriter, FileOutputStream} + def writeText(file: java.io.File, text: String, encodingOpt: Option[String] = None): Unit = { + import java.io.{ OutputStreamWriter, FileOutputStream } val encoding = encodingOpt getOrElse (System getProperty "file.encoding") val writer = new OutputStreamWriter(new FileOutputStream(file), encoding) try diff --git a/cli/src/main/scala/scalariform/commandline/CommandLineOptionParser.scala b/cli/src/main/scala/scalariform/commandline/CommandLineOptionParser.scala index e2a2035a..1561289c 100644 --- a/cli/src/main/scala/scalariform/commandline/CommandLineOptionParser.scala +++ b/cli/src/main/scala/scalariform/commandline/CommandLineOptionParser.scala @@ -3,49 +3,50 @@ package scalariform.commandline import scala.util.parsing.combinator._ class CommandLineOptionParser extends RegexParsers { + type Arg = Parser[CommandLineArgument] - lazy val option: Parser[CommandLineArgument] = + lazy val option: Arg = phrase(help) | phrase(version) | phrase(scalaVersion) | phrase(stdin) | phrase(stdout) | phrase(recurse) | phrase(test) | phrase(forceOutput) | phrase(quiet) | phrase(fileList) | phrase(encoding) | phrase(toggle) | phrase(preferenceFile) | phrase(preferenceOption) | phrase(badOption) - lazy val test = ("--test" | "-t") ^^^ Test + lazy val test: Parser[Test.type] = ("--test" | "-t") ^^^ Test - lazy val forceOutput = ("--forceOutput" | "-f") ^^^ ForceOutput + lazy val forceOutput: Arg = ("--forceOutput" | "-f") ^^^ ForceOutput - lazy val stdout = "--stdout" ^^^ Stdout + lazy val stdout: Arg = "--stdout" ^^^ Stdout - lazy val stdin = "--stdin" ^^^ Stdin + lazy val stdin: Arg = "--stdin" ^^^ Stdin - lazy val quiet = ("--quiet" | "-q") ^^^ Quiet + lazy val quiet: Arg = ("--quiet" | "-q") ^^^ Quiet - lazy val recurse = ("--recurse" | "-r") ^^^ Recurse + lazy val recurse: Arg = ("--recurse" | "-r") ^^^ Recurse - lazy val help = ("--help" | "-help" | "-h") ^^^ Help + lazy val help: Arg = ("--help" | "-help" | "-h") ^^^ Help - lazy val version = ("--version" | "-version") ^^^ Version + lazy val version: Arg = ("--version" | "-version") ^^^ Version - lazy val scalaVersion = ("--scalaVersion=" | "-s=") ~> """(\d|\.)+""".r ^^ ScalaVersion + lazy val scalaVersion: Arg = ("--scalaVersion=" | "-s=") ~> """(\d|\.)+""".r ^^ ScalaVersion - lazy val fileList = ("--fileList=" | "-l=") ~> ".+".r ^^ FileList + lazy val fileList: Arg = ("--fileList=" | "-l=") ~> ".+".r ^^ FileList - lazy val encoding = "--encoding=" ~> ".+".r ^^ Encoding + lazy val encoding: Arg = "--encoding=" ~> ".+".r ^^ Encoding - lazy val toggle = plusOrMinus ~ preferenceKey ^^ { case onOrOff ~ key ⇒ PreferenceOption(key, onOrOff.toString) } + lazy val toggle: Arg = plusOrMinus ~ preferenceKey ^^ { case onOrOff ~ key ⇒ PreferenceOption(key, onOrOff.toString) } - lazy val plusOrMinus = "+" ^^^ true | "-" ^^^ false + lazy val plusOrMinus: Parser[Boolean] = "+" ^^^ true | "-" ^^^ false - lazy val preferenceFile = ("--preferenceFile=" | "-p=") ~> ".+".r ^^ PreferenceFile + lazy val preferenceFile: Arg = ("--preferenceFile=" | "-p=") ~> ".+".r ^^ PreferenceFile - lazy val preferenceOption = ("-" ~> preferenceKey <~ "=") ~ """(\w|\.)+""".r ^^ { + lazy val preferenceOption: Arg = ("-" ~> preferenceKey <~ "=") ~ """(\w|\.)+""".r ^^ { case (key ~ value) ⇒ PreferenceOption(key, value) } lazy val preferenceKey: Parser[String] = """[a-zA-Z.]+""".r - lazy val badOption = guard(plusOrMinus) ~> ".*".r ^^ BadOption + lazy val badOption: Arg = guard(plusOrMinus) ~> ".*".r ^^ BadOption - def getArgument(s: String) = parse(option, s) getOrElse FileName(s) + def getArgument(s: String): CommandLineArgument = parse(option, s) getOrElse FileName(s) } sealed trait CommandLineArgument diff --git a/cli/src/main/scala/scalariform/commandline/Main.scala b/cli/src/main/scala/scalariform/commandline/Main.scala index 9b903835..606fcc2c 100644 --- a/cli/src/main/scala/scalariform/commandline/Main.scala +++ b/cli/src/main/scala/scalariform/commandline/Main.scala @@ -12,7 +12,7 @@ import scalariform.Utils._ object Main { - def main(args: Array[String]) { + def main(args: Array[String]): Unit = { sys.exit(if (process(args)) 1 else 0) } @@ -39,16 +39,16 @@ object Main { showUsage = true } - val encoding: String = arguments.collect { - case Encoding(encoding) ⇒ encoding - }.headOption.getOrElse(System getProperty "file.encoding") + val encoding: String = arguments.collectFirst { + case Encoding(e) ⇒ e + }.getOrElse(System getProperty "file.encoding") try Charset.forName(encoding) catch { - case e: UnsupportedCharsetException ⇒ + case _: UnsupportedCharsetException ⇒ errors ::= "Unsupported encoding " + encoding - case e: IllegalCharsetNameException ⇒ + case _: IllegalCharsetNameException ⇒ errors ::= "Illegal encoding " + encoding } @@ -64,7 +64,7 @@ object Main { } } - val preferenceOptions = (for (p @ PreferenceOption(_, _) ← arguments) yield p) + val preferenceOptions = for (p @ PreferenceOption(_, _) ← arguments) yield p for (PreferenceOption(key, _) ← preferenceOptions if !(AllPreferences.preferencesByKey contains key)) { errors ::= "Unrecognised preference: " + key @@ -74,14 +74,14 @@ object Main { if (errors.isEmpty) { preferences = preferenceOptions.foldLeft(preferences) { - case (preferences, PreferenceOption(key, valueString)) ⇒ + case (p, PreferenceOption(key, valueString)) ⇒ val descriptor = AllPreferences.preferencesByKey(key) def processDescriptor[T](descriptor: PreferenceDescriptor[T]) = { descriptor.preferenceType.parseValue(valueString) match { - case Right(value) ⇒ preferences.setPreference(descriptor, value) + case Right(value) ⇒ p.setPreference(descriptor, value) case Left(error) ⇒ errors ::= "Could not parse value for preference " + key + ", " + error - preferences + p } } processDescriptor(descriptor) @@ -92,7 +92,7 @@ object Main { def getFiles(): List[File] = { var files: List[File] = Nil - def addFile(fileName: String) { + def addFile(fileName: String): Unit = { val file = new File(fileName) if (!file.exists) errors ::= "No such file " + file @@ -140,7 +140,7 @@ object Main { if (forceOutput && files.size > 1) errors ::= "Cannot use --forceOutput with multiple files" - if (!errors.isEmpty) { + if (errors.nonEmpty) { for (error ← errors.reverse) System.err.println("Error: " + error) if (showUsage) @@ -148,11 +148,11 @@ object Main { return true } - def log(s: String) = if (!quiet && !stdout && !stdin) println(s) + def log(s: String): Unit = if (!quiet && !stdout && !stdin) println(s) - val scalaVersion = arguments.collect { - case ScalaVersion(scalaVersion) ⇒ scalaVersion - }.headOption.getOrElse(ScalaVersions.DEFAULT_VERSION) + val scalaVersion = arguments.collectFirst { + case ScalaVersion(sv) ⇒ sv + }.getOrElse(ScalaVersions.DEFAULT_VERSION) log("Assuming source is Scala " + scalaVersion) @@ -166,7 +166,7 @@ object Main { try Some(ScalaFormatter.format(s, preferences, scalaVersion = scalaVersion)) catch { - case e: ScalaParserException ⇒ None + case _: ScalaParserException ⇒ None } if (test) @@ -293,7 +293,7 @@ object Main { private case object NotFormattedCorrectly extends FormatResult private case object DidNotParse extends FormatResult - private def printUsage() { + private def printUsage(): Unit = { println("Usage: scalariform [options] [files...]") println() println("Options:") diff --git a/cli/src/main/scala/scalariform/commandline/ScalaFileWalker.scala b/cli/src/main/scala/scalariform/commandline/ScalaFileWalker.scala index 9daa19ae..0b00446b 100644 --- a/cli/src/main/scala/scalariform/commandline/ScalaFileWalker.scala +++ b/cli/src/main/scala/scalariform/commandline/ScalaFileWalker.scala @@ -1,7 +1,7 @@ package scalariform.commandline import java.io.File -import java.util.{ArrayList, Collection} +import java.util.{ ArrayList, Collection } import scala.collection.JavaConverters._ import org.apache.commons.io._ diff --git a/project/build.properties b/project/build.properties index b7dd3cb2..a31be40f 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.0.2 +sbt.version=1.0.4 \ No newline at end of file diff --git a/project/build.sbt b/project/build.sbt index 7c0c97c4..5244bd27 100644 --- a/project/build.sbt +++ b/project/build.sbt @@ -1 +1 @@ -scalacOptions := Seq("-feature", "-deprecation", "-Xlint") +scalacOptions := Seq("-feature", "-deprecation", "-Xlint:-unused,_") diff --git a/project/plugins.sbt b/project/plugins.sbt index 913c2359..1d025a58 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,5 +1,6 @@ -addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.1") -addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.0") -addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.7.0") -addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.0") -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5") +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.2") +addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.0") +addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.7.0") +addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.0") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.6") +addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.1.18") diff --git a/scalariform/src/main/scala/scalariform/ScalaVersions.scala b/scalariform/src/main/scala/scalariform/ScalaVersions.scala index e34c2815..53499430 100644 --- a/scalariform/src/main/scala/scalariform/ScalaVersions.scala +++ b/scalariform/src/main/scala/scalariform/ScalaVersions.scala @@ -1,8 +1,8 @@ package scalariform +import scala.math.Ordering import scala.util.Properties import scalariform.utils.Utils._ -import scala.math.Ordering object ScalaVersion { @@ -27,21 +27,21 @@ case class ScalaVersion(major: Int, minor: Int, extra: String = "") extends Orde private def majorMinor = (major, minor) - def compare(that: ScalaVersion) = Ordering[(Int, Int)].compare(this.majorMinor, that.majorMinor) + def compare(that: ScalaVersion): Int = Ordering[(Int, Int)].compare(this.majorMinor, that.majorMinor) - override def toString = major + "." + minor + "." + extra + override def toString: String = major + "." + minor + "." + extra } object ScalaVersions { - val Scala_2_11 = ScalaVersion.parse("2.11.0").get - val Scala_2_10 = ScalaVersion.parse("2.10.0").get - val Scala_2_9 = ScalaVersion.parse("2.9.2").get - val Scala_2_8 = ScalaVersion.parse("2.8.1").get + val Scala_2_11: ScalaVersion = ScalaVersion.parse("2.11.0").get + val Scala_2_10: ScalaVersion = ScalaVersion.parse("2.10.0").get + val Scala_2_9: ScalaVersion = ScalaVersion.parse("2.9.2").get + val Scala_2_8: ScalaVersion = ScalaVersion.parse("2.8.1").get - lazy val DEFAULT_VERSION = Properties.scalaPropOrElse("version.number", "2.9.2") + lazy val DEFAULT_VERSION: String = Properties.scalaPropOrElse("version.number", "2.9.2") - lazy val DEFAULT = ScalaVersion.parse(DEFAULT_VERSION).get + lazy val DEFAULT: ScalaVersion = ScalaVersion.parse(DEFAULT_VERSION).get } diff --git a/scalariform/src/main/scala/scalariform/astselect/AstSelector.scala b/scalariform/src/main/scala/scalariform/astselect/AstSelector.scala index 7588b248..a2707057 100644 --- a/scalariform/src/main/scala/scalariform/astselect/AstSelector.scala +++ b/scalariform/src/main/scala/scalariform/astselect/AstSelector.scala @@ -1,10 +1,10 @@ package scalariform.astselect +import scala.util.control.Exception._ +import scalariform.ScalaVersions import scalariform.lexer._ import scalariform.parser._ import scalariform.utils.Range -import scala.util.control.Exception._ -import scalariform.ScalaVersions object AstSelector { @@ -58,7 +58,7 @@ class AstSelector(source: String, scalaVersion: String = ScalaVersions.DEFAULT_V private val compilationUnitOpt: Option[CompilationUnit] = { val parser = new ScalaParser(tokens.toArray) - parser.safeParse(parser.compilationUnitOrScript) + parser.safeParse(parser.compilationUnitOrScript()) } private val allTokens: List[Token] = tokens.flatMap { token ⇒ @@ -183,7 +183,7 @@ class AstSelector(source: String, scalaVersion: String = ScalaVersions.DEFAULT_V nodeStack match { case List(_: BlockExpr, _: MatchExpr, _*) ⇒ false case List(_: BlockExpr, _: ProcFunBody, _*) ⇒ false - case List(node, _*) ⇒ !(nonSelectableAstNodes contains node.getClass.asInstanceOf[Class[_ <: AstNode]]) + case List(node, _*) ⇒ !(nonSelectableAstNodes contains node.getClass) case Nil ⇒ false } diff --git a/scalariform/src/main/scala/scalariform/formatter/Alignment.scala b/scalariform/src/main/scala/scalariform/formatter/Alignment.scala index 6fbdedfa..83b6a9d6 100644 --- a/scalariform/src/main/scala/scalariform/formatter/Alignment.scala +++ b/scalariform/src/main/scala/scalariform/formatter/Alignment.scala @@ -1,7 +1,8 @@ package scalariform.formatter +import java.lang.Math._ + import scalariform.parser._ -import Math._ // For now, this is just a place to store alignment related functionality. // TOOD: refactor duplicate behavior in here @@ -30,9 +31,8 @@ object Alignment { largestIdLength: Int ) { - def prepend(equalsExpr: EqualsExpr, length: Int) = { + def prepend(equalsExpr: EqualsExpr, length: Int) = ConsecutiveSingleLineEqualsExprs(equalsExpr :: equalsExprs, max(length, largestIdLength)) - } } case class ConsecutiveSingleLineCaseClauses( @@ -43,7 +43,7 @@ object Alignment { def prepend(clause: CaseClause, length: Int) = ConsecutiveSingleLineCaseClauses(clause :: clauses, max(length, largestCasePatternLength), min(length, smallestCasePatternLength)) - def patternLengthRange = largestCasePatternLength - smallestCasePatternLength + def patternLengthRange: Int = largestCasePatternLength - smallestCasePatternLength } diff --git a/scalariform/src/main/scala/scalariform/formatter/AnnotationFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/AnnotationFormatter.scala index 192d61d0..585b8bdd 100644 --- a/scalariform/src/main/scala/scalariform/formatter/AnnotationFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/AnnotationFormatter.scala @@ -1,7 +1,7 @@ package scalariform.formatter -import scalariform.parser._ import scalariform.formatter.preferences._ +import scalariform.parser._ trait AnnotationFormatter { self: HasFormattingPreferences with TypeFormatter with ExprFormatter ⇒ diff --git a/scalariform/src/main/scala/scalariform/formatter/CaseClauseFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/CaseClauseFormatter.scala index 36cf1407..c16ef72e 100644 --- a/scalariform/src/main/scala/scalariform/formatter/CaseClauseFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/CaseClauseFormatter.scala @@ -1,11 +1,11 @@ package scalariform.formatter +import scala.PartialFunction._ +import scalariform.formatter.Alignment._ +import scalariform.formatter.preferences._ import scalariform.lexer.Token import scalariform.parser._ import scalariform.utils.Utils -import scalariform.formatter.preferences._ -import Alignment._ -import PartialFunction._ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter with HasHiddenTokenInfo with ScalaFormatter ⇒ @@ -22,7 +22,7 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi // We have to decide whether to indent the hidden tokens before the CASE token (or possibly a preceding // NEWLINE token from a prior case block). - def handleCaseIndent(caseClause: CaseClause) { + def handleCaseIndent(caseClause: CaseClause): Unit = if (!isFirstCaseClause) { previousCaseClauseTrailingNewlineOpt(caseClause, caseClausesAstNode) match { case Some(newline) ⇒ @@ -32,9 +32,8 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi formatResult = formatResult.before(caseClause.firstToken, formatterState.currentIndentLevelInstruction) } } - } - def formatSingleCaseClause(caseClause: CaseClause) { + def formatSingleCaseClause(caseClause: CaseClause): Unit = { handleCaseIndent(caseClause) formatResult ++= formatCaseClause(caseClause, None, hasSingleCaseClause) isFirstCaseClause = false @@ -42,9 +41,9 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi for (clauseGroup ← clauseGroups) clauseGroup match { - case Left(consecutiveClauses @ ConsecutiveSingleLineCaseClauses(caseClauses, largestCasePatternLength, smallestCasePatternLength)) ⇒ + case Left(consecutiveClauses @ ConsecutiveSingleLineCaseClauses(caseClauses, largestCasePatternLength, _)) ⇒ if (consecutiveClauses.patternLengthRange <= formattingPreferences(AlignSingleLineCaseStatements.MaxArrowIndent)) { - for (caseClause @ CaseClause(casePattern, statSeq) ← caseClauses) { + for (caseClause @ CaseClause(_, _) ← caseClauses) { handleCaseIndent(caseClause) val arrowInstruction = PlaceAtColumn(formatterState.indentLevel, largestCasePatternLength + 1) formatResult ++= formatCaseClause( @@ -108,7 +107,7 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi } private def formatCaseClause( - caseClause: CaseClause, + caseClause: CaseClause, arrowInstructionOpt: Option[PlaceAtColumn], hasSingleCaseClause: Boolean )(implicit formatterState: FormatterState): FormatResult = { @@ -117,9 +116,8 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi var formatResult: FormatResult = NoFormatResult formatResult ++= formatCasePattern(casePattern, arrowInstructionOpt) val hasNewline = caseClause.casePattern.caseToken.associatedWhitespaceAndComments.containsNewline - val singleCaseWithoutNewline = ( + val singleCaseWithoutNewline = hasSingleCaseClause && !hasNewline && !formattingPreferences(SingleCasePatternOnNewline) - ) val singleExpr = cond(statSeq.firstStatOpt) { case Some(Expr(_)) ⇒ true } && cond(statSeq.otherStats) { case Nil | List((_, None)) ⇒ true } @@ -128,15 +126,15 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi containsNewline(statSeq) && !singleExpr def unindent(x: Map[Token, IntertokenFormatInstruction]) = x.map { - case (k, v @ EnsureNewlineAndIndent(indentLevel, relativeTo)) => + case (k, EnsureNewlineAndIndent(indentLevel, relativeTo)) => k -> EnsureNewlineAndIndent(indentLevel - 1, relativeTo) - case x => x + case z => z } if (indentBlock) { val result = formatResult.before(statSeq.firstToken, formatterState.nextIndentLevelInstruction) formatResult = - if(!singleCaseWithoutNewline) result + if (!singleCaseWithoutNewline) result else result.copy( predecessorFormatting = @@ -149,7 +147,7 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi val stateForStatSeq = if (singleExpr && !indentBlock) formatterState else formatterState.indent formatResult ++= { val result = format(statSeq)(stateForStatSeq) - if(!singleCaseWithoutNewline) result + if (!singleCaseWithoutNewline) result else result.copy( // unindent body tokens predecessorFormatting = unindent(result.predecessorFormatting), @@ -188,9 +186,9 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi } private def previousCaseClauseTrailingNewlineOpt(caseClause: CaseClause, caseClauses: CaseClauses): Option[Token] = - Utils.pairWithPrevious(caseClauses.caseClauses).collect { + Utils.pairWithPrevious(caseClauses.caseClauses).collectFirst { case (Some(previousClause), `caseClause`) ⇒ previousClause - }.headOption.flatMap(getTrailingNewline) + }.flatMap(getTrailingNewline) private def previousCaseClauseEndsWithNewline(caseClause: CaseClause, caseClauses: CaseClauses): Boolean = previousCaseClauseTrailingNewlineOpt(caseClause, caseClauses).isDefined diff --git a/scalariform/src/main/scala/scalariform/formatter/CommentFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/CommentFormatter.scala index 85ea303a..e42bfed9 100644 --- a/scalariform/src/main/scala/scalariform/formatter/CommentFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/CommentFormatter.scala @@ -1,8 +1,8 @@ package scalariform.formatter -import scalariform.lexer._ -import scalariform.formatter.preferences._ import scala.annotation.tailrec +import scalariform.formatter.preferences._ +import scalariform.lexer._ trait CommentFormatter { self: HasFormattingPreferences with ScalaFormatter ⇒ @@ -12,7 +12,7 @@ trait CommentFormatter { self: HasFormattingPreferences with ScalaFormatter ⇒ val (contents, _) = rest.splitAt(rest.length - "*/".length) val firstLine :: otherLines = contents.split("""\r?\n([ \t]*(\*(?!/))?)?""", Integer.MAX_VALUE).toList val initialSpaces = firstLine takeWhile (_.isWhitespace) - val adjustedLines = dropInitialSpaces(firstLine, initialSpaces.size) :: (otherLines map { dropInitialSpaces(_, afterStarSpaces) }) + val adjustedLines = dropInitialSpaces(firstLine, initialSpaces.length) :: (otherLines map { dropInitialSpaces(_, afterStarSpaces) }) // val adjustedLines map { line ⇒ if (line startsWith "*/") "*" + line else line } (start, adjustedLines) } diff --git a/scalariform/src/main/scala/scalariform/formatter/ExprFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/ExprFormatter.scala index e25a0832..56447ac1 100755 --- a/scalariform/src/main/scala/scalariform/formatter/ExprFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/ExprFormatter.scala @@ -1,13 +1,12 @@ package scalariform.formatter +import scala.PartialFunction._ import scalariform.formatter.Alignment._ -import scalariform.lexer.Chars -import scalariform.lexer.Token +import scalariform.formatter.preferences._ +import scalariform.lexer.{ Chars, Token } import scalariform.lexer.Tokens._ import scalariform.parser._ import scalariform.utils.Utils -import scalariform.formatter.preferences._ -import scala.PartialFunction._ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter with HasHiddenTokenInfo with TypeFormatter with TemplateFormatter with ScalaFormatter with XmlFormatter with CaseClauseFormatter ⇒ @@ -54,7 +53,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult = formatResult.before(scala.firstToken, Compact) formatResult ++= format(scala)(formatterState) scala match { - case Expr(List(BlockExpr(lbrace, caseClausesOrStatSeq, rbrace))) if !containsNewline(scala) ⇒ + case Expr(List(BlockExpr(_, _, rbrace))) if !containsNewline(scala) ⇒ formatResult = formatResult.before(rbrace, Compact) // First token of caseClausesOrStatSeq (or rbrace): formatResult = formatResult.before(scala.tokens.drop(1).head, Compact) @@ -116,10 +115,10 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi case (_, _: ArgumentExprs) if formattingPreferences(PreserveSpaceBeforeArguments) ⇒ CompactPreservingGap // TODO: Probably not needed now with CallExpr case (_, elem) if element.firstTokenOption exists { firstToken ⇒ newlineBefore(firstToken) && !(Set(COMMA, COLON) contains firstToken.tokenType) } ⇒ val isNestedArgument = elem match { - case Argument(Expr(CallExpr(None, _, _, moreArgs, _) :: tail)) if moreArgs.isEmpty ⇒ false - case Argument(Expr(EqualsExpr(_, _, Expr(headExpr :: innerTail)) :: tail)) ⇒ headExpr match { - case CallExpr(children, _, _, moreArgs, _) ⇒ moreArgs.nonEmpty || headExpr.tokens.exists(tk => hiddenPredecessors(tk).containsNewline) - case _ ⇒ headExpr.tokens.exists(tk => hiddenPredecessors(tk).containsNewline) + case Argument(Expr(CallExpr(None, _, _, moreArgs, _) :: _)) if moreArgs.isEmpty ⇒ false + case Argument(Expr(EqualsExpr(_, _, Expr(headExpr :: _)) :: _)) ⇒ headExpr match { + case CallExpr(_, _, _, moreArgs, _) ⇒ moreArgs.nonEmpty || headExpr.tokens.exists(tk => hiddenPredecessors(tk).containsNewline) + case _ ⇒ headExpr.tokens.exists(tk => hiddenPredecessors(tk).containsNewline) } case _ ⇒ true } @@ -199,7 +198,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult ++= format(typeArgs)(currentFormatterState.clearExpressionBreakHappened) for ((newlineOpt, argumentExprs) ← newLineOptsAndArgumentExprss) { - if (newlineOpt == None && formattingPreferences(PreserveSpaceBeforeArguments)) + if (newlineOpt.isEmpty && formattingPreferences(PreserveSpaceBeforeArguments)) formatResult = formatResult.before(argumentExprs.firstToken, CompactPreservingGap) val expressionBreakHappened = currentFormatterState.expressionBreakHappened val (argResult, argUpdatedFormatterState) = format(argumentExprs)(currentFormatterState.clearExpressionBreakHappened) @@ -318,9 +317,9 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi val firstTwoArguments = contents.iterator.filter { x ⇒ cond(x) { - case Argument(_) ⇒ true - case callExpr: CallExpr ⇒ true - case equalsExpr: EqualsExpr ⇒ true + case Argument(_) ⇒ true + case _: CallExpr ⇒ true + case _: EqualsExpr ⇒ true } }.take(2).toList firstTwoArguments match { @@ -340,7 +339,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi var currentExprNewlineCount = 0 // TODO: refactor this as well as "def groupParams" to share logic - val eitherAlignableArguments = (contents.foldLeft(List[EitherAlignableEqualsExpr]()) { (existingExprs, exprElement) ⇒ + val eitherAlignableArguments = contents.foldLeft(List[EitherAlignableEqualsExpr]()) { (existingExprs, exprElement) ⇒ if (!alignArgsEnabled) { // If we're not aligning argument, place each alignable element in its own group. val nextExprsOption = condOpt(exprElement) { @@ -372,7 +371,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi case _ ⇒ existingExprs } } - }).reverse map { + }.reverse map { // Reverse the sub-expressions to be in source-order. case Left(ConsecutiveSingleLineEqualsExprs(exprs, length)) => Left(ConsecutiveSingleLineEqualsExprs(exprs.reverse, length)) @@ -592,7 +591,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult ++= format(body)(bodyFormatterState) // TODO: take into account pre-Else semi - for (ElseClause(elseSemiOpt, elseToken, elseBody) ← elseClauseOption) { + for (ElseClause(_, elseToken, elseBody) ← elseClauseOption) { if (formattingPreferences(CompactControlReadability) && bodyIsABlock && containsNewline(body)) formatResult = formatResult.before(elseToken, formatterState.currentIndentLevelInstruction) else if (bodyIsABlock && containsNewline(body)) @@ -625,7 +624,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi format(condition) } - private def isIfExpr(expr: Expr) = expr.contents.size == 1 && expr.contents(0).isInstanceOf[IfExpr] + private def isIfExpr(expr: Expr) = expr.contents.size == 1 && expr.contents.head.isInstanceOf[IfExpr] private def format(forExpr: ForExpr)(implicit formatterState: FormatterState): FormatResult = { val ForExpr(_, _, enumerators, rParenOrBrace, newlinesOpt, yieldOption, body) = forExpr @@ -763,7 +762,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult ++= format(body)(bodyFormatterState) formatResult = statSepOpt match { - case Some(semi) if isInferredNewline(semi) ⇒ { + case Some(semi) if isInferredNewline(semi) ⇒ val instruction = if (indentBody) formatterState.currentIndentLevelInstruction @@ -772,8 +771,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi else formatterState.currentIndentLevelInstruction formatResult.formatNewline(semi, instruction) - } - case _ ⇒ { + case _ ⇒ val instruction = if (indentBody) formatterState.currentIndentLevelInstruction @@ -784,7 +782,6 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi else CompactEnsuringGap formatResult.before(whileToken, instruction) - } } formatResult ++= format(condExpr) @@ -792,7 +789,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult } - private def isBlockExpr(expr: Expr) = expr.contents.size == 1 && expr.contents(0).isInstanceOf[BlockExpr] + private def isBlockExpr(expr: Expr) = expr.contents.size == 1 && expr.contents.head.isInstanceOf[BlockExpr] def format(blockExpr: BlockExpr, indent: Boolean)(implicit formatterState: FormatterState): FormatResult = { val BlockExpr(_, caseClausesOrStatSeq, rbrace) = blockExpr @@ -819,7 +816,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi else { if (statSeq.firstTokenOption.isDefined) { statSeq.firstStatOpt match { - case Some(Expr(List(anonFn @ AnonymousFunction(params, arrowToken, subStatSeq)))) ⇒ + case Some(Expr(List(AnonymousFunction(params, _, subStatSeq)))) ⇒ def hasNestedAnonymousFunction(subStatSeq: StatSeq): Boolean = (for { firstStat <- subStatSeq.firstStatOpt @@ -829,7 +826,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi val (instruction, subStatState) = if (hasNestedAnonymousFunction(subStatSeq)) (CompactEnsuringGap, indentedState.indent(-1)) - else if (hiddenPredecessors(params(0).firstToken).containsNewline) + else if (hiddenPredecessors(params.head.firstToken).containsNewline) (indentedInstruction, indentedState.indent) else (CompactEnsuringGap, indentedState) @@ -848,7 +845,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult ++= format(subStatSeq)(subStatState) case _ ⇒ val instruction = statSeq.selfReferenceOpt match { - case Some((selfReference, arrow)) if !hiddenPredecessors(selfReference.firstToken).containsNewline ⇒ + case Some((selfReference, _)) if !hiddenPredecessors(selfReference.firstToken).containsNewline ⇒ CompactEnsuringGap case _ ⇒ statFormatterState(statSeq.firstStatOpt)(indentedState).currentIndentLevelInstruction @@ -877,7 +874,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi val firstStatFormatterState = statFormatterState(firstStatOpt) - for ((selfReference, arrow) ← selfReferenceOpt) { + for ((selfReference, _) ← selfReferenceOpt) { formatResult ++= format(selfReference) for (stat ← firstStatOpt if hiddenPredecessors(stat.firstToken).containsNewline) formatResult = formatResult.before(stat.firstToken, firstStatFormatterState.currentIndentLevelInstruction) @@ -947,8 +944,8 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi } if (nextAnnotationOpt.isEmpty) { val firstPostAnnotationToken = modifiers match { - case Nil ⇒ defOrDcl.firstToken - case (modifier :: rest) ⇒ modifier.firstToken + case Nil ⇒ defOrDcl.firstToken + case (modifier :: _) ⇒ modifier.firstToken } val instruction = if (annotation.newlineOption.isDefined) formatterState.currentIndentLevelInstruction @@ -980,11 +977,11 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi var formatResult: FormatResult = NoFormatResult val PatDefOrDcl(_, pattern, otherPatterns, typedOpt, equalsClauseOption) = patDefOrDcl formatResult ++= format(pattern) - for ((comma, otherPattern) ← otherPatterns) + for ((_, otherPattern) ← otherPatterns) formatResult ++= format(otherPattern) - for ((colon, type_) ← typedOpt) + for ((_, type_) ← typedOpt) formatResult ++= format(type_) - for ((equals, body) ← equalsClauseOption) { + for ((_, body) ← equalsClauseOption) { // TODO: Copy and paste from format(FunDefOrDcl) val bodyToken = body.firstToken val (formatInstruction, exprFormatterState) = @@ -1008,11 +1005,11 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult ++= format(typeParamClause.contents) val doubleIndentParams = formattingPreferences(DoubleIndentMethodDeclaration) formatResult ++= formatParamClauses(paramClauses, doubleIndentParams) - for ((colon, type_) ← returnTypeOpt) + for ((_, type_) ← returnTypeOpt) formatResult ++= format(type_) for (funBody ← funBodyOpt) { funBody match { - case ExprFunBody(equals, macroOpt, body) ⇒ { + case ExprFunBody(_, _, body) ⇒ // TODO: see format(PatDefOrDcl) val bodyToken = body.firstToken val (formatInstruction, exprFormatterState) = @@ -1022,15 +1019,13 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi (CompactEnsuringGap, formatterState) formatResult = formatResult.before(bodyToken, formatInstruction) formatResult ++= format(body)(exprFormatterState) - } - case ProcFunBody(newlineOpt, bodyBlock) ⇒ { + case ProcFunBody(newlineOpt, bodyBlock) ⇒ for (newline ← newlineOpt) formatResult = formatResult.formatNewline(newline, CompactEnsuringGap) if (newlineOpt.isEmpty) formatResult = formatResult.before(bodyBlock.firstToken, CompactEnsuringGap) // TODO: else? formatResult ++= format(bodyBlock) - } } } formatResult @@ -1040,7 +1035,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi val ParamClauses(_, paramClausesAndNewlines) = paramClauses var formatResult: FormatResult = NoFormatResult val currentFormatterState = formatterState - for ((paramClause, newlineOption) ← paramClausesAndNewlines) { // TODO: Newlines. // maybe already done in some cases by format(tmplDef)? + for ((paramClause, _) ← paramClausesAndNewlines) { // TODO: Newlines. // maybe already done in some cases by format(tmplDef)? val (paramClauseFormatResult, _) = formatParamClause(paramClause, doubleIndentParams)(currentFormatterState) formatResult ++= paramClauseFormatResult } @@ -1071,7 +1066,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi // Account for whitespace between prefix token types. This assumes everything // will be placed on a single line with no newlines between prefixes. val numberOfPrefixTypes = Seq( - !annotations.isEmpty, + annotations.nonEmpty, valOrVarOpt.isDefined ).count(_ == true) + modifiers.length if (numberOfPrefixTypes > 0) @@ -1124,8 +1119,6 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi * Groups consecutive single line params in a [[scalariform.parser.ParamClause]] for alignment. * The head of the return value (and head of the params list in the returned ConsecutiveSingleLineParams is guaranteed * to be the very first parameter in the paramClause. The other parameters are not necessarily in the order they appear. - * @param paramClause - * @param formatterState * * @return List of grouped params. Left stores a group of parameters that can be aligned together, * Right stores an unalignable param. @@ -1133,7 +1126,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi private def groupParams(paramClause: ParamClause, alignParameters: Boolean)(implicit formatterState: FormatterState): List[EitherAlignableParam] = { val ParamClause(_, implicitOption, firstParamOption, otherParamsWithComma, _) = paramClause - val otherParams = otherParamsWithComma.map { case (comma, param) ⇒ param } + val otherParams = otherParamsWithComma.map { case (_, param) ⇒ param } // This is reversed because "appendParamToGroup" works on lists, and will // create the list in the reverse order of the list it is given. @@ -1148,9 +1141,9 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi // This unintuitive line is dependent on the ordering of groupedParams being passed // in. It's in reverse. - val isFirstParam = !nextParam.isDefined + val isFirstParam = nextParam.isEmpty - val firstParamAlignable = !implicitOption.isDefined || + val firstParamAlignable = implicitOption.isEmpty || (newlineBefore(implicitOption.get) && otherParams != Nil && newlineBefore(otherParams.head)) val paramIsAlignable = alignParameters && (!isFirstParam || firstParamAlignable) @@ -1159,7 +1152,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi calculateParamSectionLengths(paramToAppend, isFirstParam) match { case Some(sectionLengths) ⇒ groupedParams match { - case Right(param) :: tail ⇒ + case Right(_) :: _ ⇒ Left(ConsecutiveSingleLineParams(List(paramToAppend), sectionLengths, sectionLengths)) :: groupedParams case Left(existingParams) :: tail ⇒ if (previousParam.isDefined) { @@ -1281,7 +1274,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi } otherGroupedParams.foreach { - case Left(ConsecutiveSingleLineParams(params, maxSectionLengths, thisSectionLengths)) ⇒ + case Left(ConsecutiveSingleLineParams(params, maxSectionLengths, _)) ⇒ params.foreach { param ⇒ val firstToken = param.firstToken @@ -1301,7 +1294,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult ++= format(param)(paramFormatterState) } - def alignFirstParam(firstParam: Param) = { + def alignFirstParam(firstParam: Param): Unit = { // Place implicit on its own line. for (implicitToken ← implicitOption) { if (hiddenPredecessors(implicitToken).containsNewline || (containsNewline(firstParam) && alignParameters)) @@ -1324,15 +1317,15 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi } } - def alignOtherParams(firstToken: Token) = { + def alignOtherParams(firstToken: Token): Unit = { if (hiddenPredecessors(firstToken).containsNewline) { paramFormatterState = if (alignParameters) formatterState.alignWithToken(relativeToken) else formatterState.indent(paramIndent) formatResult = formatResult.before(firstToken, paramFormatterState.currentIndentLevelInstruction) } } - def indentType(param: Param, maxSectionLengths: ParamSectionLengths) = { - for ((colon, typeAst) ← param.paramTypeOpt) { + def indentType(param: Param, maxSectionLengths: ParamSectionLengths): Unit = { + for ((_, typeAst) ← param.paramTypeOpt) { val typeSpaces = maxSectionLengths.prefixAndIdLength + 1 formatResult = formatResult.before( typeAst.firstToken, @@ -1345,8 +1338,8 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi } } - def indentDefault(param: Param, maxSectionLengths: ParamSectionLengths) = { - for ((equal, default) ← param.defaultValueOpt) { + def indentDefault(param: Param, maxSectionLengths: ParamSectionLengths): Unit = { + for ((equal, _) ← param.defaultValueOpt) { val defaultSpaces = { maxSectionLengths.prefixAndIdLength + maxSectionLengths.typeLength + 2 @@ -1373,10 +1366,10 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi for (annotation ← annotations) { formatResult ++= format(annotation) } - for ((colon, paramType) ← paramTypeOpt) { + for ((_, paramType) ← paramTypeOpt) { formatResult ++= format(paramType) } - for ((equals, expr) ← defaultValueOpt) { + for ((_, expr) ← defaultValueOpt) { formatResult ++= format(expr) } formatResult @@ -1386,7 +1379,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi val ImportClause(_, importExpr, otherImportExprs) = import_ var formatResult: FormatResult = NoFormatResult formatResult ++= format(importExpr) - for ((comma, otherImportExpr) ← otherImportExprs) + for ((_, otherImportExpr) ← otherImportExprs) formatResult ++= format(otherImportExpr) formatResult } @@ -1416,7 +1409,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi formatResult = formatResult.before(firstImportSelector.firstToken, Compact) formatResult ++= format(firstImportSelector) - for ((comma, otherImportSelector) ← otherImportSelectors) + for ((_, otherImportSelector) ← otherImportSelectors) formatResult ++= format(otherImportSelector) if (!formattingPreferences(SpacesAroundMultiImports)) @@ -1424,7 +1417,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi } else { formatResult = formatResult.before(firstImportSelector.firstToken, formatterState.nextIndentLevelInstruction) formatResult ++= format(firstImportSelector) - for ((comma, otherImportSelector) ← otherImportSelectors) { + for ((_, otherImportSelector) ← otherImportSelectors) { formatResult = formatResult.before(otherImportSelector.firstToken, formatterState.nextIndentLevelInstruction) formatResult ++= format(otherImportSelector) } diff --git a/scalariform/src/main/scala/scalariform/formatter/FormatResult.scala b/scalariform/src/main/scala/scalariform/formatter/FormatResult.scala index 1a2ca282..57676844 100644 --- a/scalariform/src/main/scala/scalariform/formatter/FormatResult.scala +++ b/scalariform/src/main/scala/scalariform/formatter/FormatResult.scala @@ -14,28 +14,28 @@ case class FormatResult( xmlRewrites: Map[Token, String] ) { - def replaceXml(token: Token, replacement: String) = { + def replaceXml(token: Token, replacement: String): FormatResult = { require(token.tokenType.isXml) copy(xmlRewrites = xmlRewrites + (token -> replacement)) } - def before(token: Token, formatInstruction: IntertokenFormatInstruction) = { + def before(token: Token, formatInstruction: IntertokenFormatInstruction): FormatResult = { require(!token.isNewline, " cannot do 'before' formatting for NEWLINE* tokens: " + token + ", " + formatInstruction) copy(predecessorFormatting = predecessorFormatting + (token -> formatInstruction)) } - def formatNewline(token: Token, formatInstruction: IntertokenFormatInstruction) = { + def formatNewline(token: Token, formatInstruction: IntertokenFormatInstruction): FormatResult = { require(token.isNewline, " cannot do 'newline' formatting for non-NEWLINE tokens: " + token + ", " + formatInstruction) copy(inferredNewlineFormatting = inferredNewlineFormatting + (token -> formatInstruction)) } - def formatNewlineOrOrdinary(token: Token, formatInstruction: IntertokenFormatInstruction) = + def formatNewlineOrOrdinary(token: Token, formatInstruction: IntertokenFormatInstruction): FormatResult = if (token.isNewline) formatNewline(token, formatInstruction) else before(token, formatInstruction) def tokenWillHaveNewline(token: Token): Boolean = { val hasNewlineInstruction = predecessorFormatting.get(token) map { - PartialFunction.cond(_) { case newlineInstruction: EnsureNewlineAndIndent ⇒ true } + PartialFunction.cond(_) { case _: EnsureNewlineAndIndent ⇒ true } } hasNewlineInstruction.getOrElse(false) } @@ -47,7 +47,7 @@ case class FormatResult( this.xmlRewrites ++ other.xmlRewrites ) - def ++(other: FormatResult) = mergeWith(other) + def ++(other: FormatResult): FormatResult = mergeWith(other) } object NoFormatResult extends FormatResult(Map(), Map(), Map()) diff --git a/scalariform/src/main/scala/scalariform/formatter/FormatterDirectiveParser.scala b/scalariform/src/main/scala/scalariform/formatter/FormatterDirectiveParser.scala index 60c3e75f..e5763f7c 100644 --- a/scalariform/src/main/scala/scalariform/formatter/FormatterDirectiveParser.scala +++ b/scalariform/src/main/scala/scalariform/formatter/FormatterDirectiveParser.scala @@ -1,16 +1,17 @@ package scalariform.formatter + import scala.util.parsing.combinator._ class FormatterDirectiveParser extends JavaTokenParsers { - val directives: Parser[List[FormatterDirective]] = "format:" ~> - ("ON" ^^^ List(ToggleFormatting(true)) | "OFF" ^^^ List(ToggleFormatting(false)) | repsep(toggle, ",")) + val plusOrMinus: Parser[Boolean] = "+" ^^^ true | "-" ^^^ false - val plusOrMinus = "+" ^^^ true | "-" ^^^ false + val toggle: Parser[ToggleOption] = plusOrMinus ~ ident ^^ { case onOrOff ~ optionName ⇒ ToggleOption(onOrOff, optionName) } - val toggle = plusOrMinus ~ ident ^^ { case onOrOff ~ optionName ⇒ ToggleOption(onOrOff, optionName) } + val directives: Parser[List[FormatterDirective]] = "format:" ~> + ("ON" ^^^ List(ToggleFormatting(true)) | "OFF" ^^^ List(ToggleFormatting(false)) | repsep(toggle, ",")) - def getDirectives(s: String) = parse(directives, s) getOrElse Nil + def getDirectives(s: String): List[FormatterDirective] = parse(directives, s) getOrElse Nil } object FormatterDirectiveParser { diff --git a/scalariform/src/main/scala/scalariform/formatter/FormatterState.scala b/scalariform/src/main/scala/scalariform/formatter/FormatterState.scala index 21a6d824..f71e1958 100644 --- a/scalariform/src/main/scala/scalariform/formatter/FormatterState.scala +++ b/scalariform/src/main/scala/scalariform/formatter/FormatterState.scala @@ -5,8 +5,8 @@ import scalariform.lexer.Token case class FormatterState( indentLevel: Int = 0, indentRelativeToTokenOption: Option[Token] = None, - val inSingleLineBlock: Boolean = false, - val expressionBreakHappened: Boolean = false + inSingleLineBlock: Boolean = false, + expressionBreakHappened: Boolean = false ) { private val nextIndentLevel = indentLevel + 1 @@ -21,10 +21,10 @@ case class FormatterState( def currentIndentLevelInstruction = EnsureNewlineAndIndent(indentLevel, relativeTo = indentRelativeToTokenOption) - def indentForExpressionBreak = indent.copy(expressionBreakHappened = true) + def indentForExpressionBreak: FormatterState = indent.copy(expressionBreakHappened = true) - def indentForExpressionBreakIfNeeded = if (expressionBreakHappened) this else indent.copy(expressionBreakHappened = true) + def indentForExpressionBreakIfNeeded: FormatterState = if (expressionBreakHappened) this else indent.copy(expressionBreakHappened = true) - def clearExpressionBreakHappened = copy(expressionBreakHappened = false) + def clearExpressionBreakHappened: FormatterState = copy(expressionBreakHappened = false) } diff --git a/scalariform/src/main/scala/scalariform/formatter/ScalaFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/ScalaFormatter.scala index 7a52bb4d..859bdb41 100755 --- a/scalariform/src/main/scala/scalariform/formatter/ScalaFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/ScalaFormatter.scala @@ -1,12 +1,12 @@ package scalariform.formatter +import scala.PartialFunction._ +import scalariform.ScalaVersions +import scalariform.formatter.preferences._ import scalariform.lexer.Tokens._ import scalariform.lexer._ import scalariform.parser._ import scalariform.utils._ -import scalariform.formatter.preferences._ -import PartialFunction._ -import scalariform.ScalaVersions trait HasHiddenTokenInfo { @@ -157,7 +157,7 @@ abstract class ScalaFormatter tokenIndentMap: Map[Token, Int], positionHintOption: Option[Int] = None ): Option[TextEdit] = { - def writeIntertokenCompact() { + def writeIntertokenCompact(): Unit = { val comments = hiddenTokens.comments for ((previousCommentOption, comment, nextCommentOption) ← Utils.withPreviousAndNext(comments)) { val needGapBetweenThisAndPrevious = cond(previousCommentOption) { @@ -191,7 +191,7 @@ abstract class ScalaFormatter else writeIntertokenCompact() case CompactPreservingGap ⇒ - if (allWhitespace && !hiddenTokens.isEmpty) + if (allWhitespace && hiddenTokens.nonEmpty) builder.append(" ") else writeIntertokenCompact() @@ -231,7 +231,7 @@ abstract class ScalaFormatter case Some(SingleLineComment(_)) ⇒ math.min(1, newlineCount) case _ ⇒ math.min(2, newlineCount) } - for (i ← 1 to newlinesToWrite) + for (_ ← 1 to newlinesToWrite) builder.newline() } if (nextOpt.isEmpty) { @@ -273,10 +273,10 @@ abstract class ScalaFormatter class StringBuilderExtra(builder: StringBuilder) { - def indent(indentLevel: Int, baseIndentOption: Option[Int] = None) = { + def indent(indentLevel: Int, baseIndentOption: Option[Int] = None): StringBuilder = { for { baseIndent ← baseIndentOption - n ← 1 to baseIndent + _ ← 1 to baseIndent } builder.append(" ") val indentChars = formattingPreferences.indentStyle.indent(indentLevel) builder.append(indentChars) @@ -285,37 +285,37 @@ abstract class ScalaFormatter def write(token: Token, replacementOption: Option[String] = None): Option[TextEdit] = { val rewriteArrows = formattingPreferences(RewriteArrowSymbols) - val actualReplacementOption = replacementOption orElse (condOpt(token.tokenType) { + val actualReplacementOption = replacementOption orElse condOpt(token.tokenType) { case ARROW if rewriteArrows ⇒ "⇒" case LARROW if rewriteArrows ⇒ "←" case EOF ⇒ "" - }) + } builder.append(actualReplacementOption getOrElse token.rawText) actualReplacementOption map { replaceEdit(token, _) } } - def write(hiddenToken: HiddenToken) = { + def write(hiddenToken: HiddenToken): StringBuilder = { builder.append(hiddenToken.token.rawText) builder } - def newline() = { + def newline(): StringBuilder = { builder.append(newlineSequence) builder } - def atBeginningOfLine = builder.isEmpty || lastChar == '\n' + def atBeginningOfLine: Boolean = builder.isEmpty || lastChar == '\n' private def lastChar = builder(builder.length - 1) - def currentColumn = { + def currentColumn: Int = { var pos = builder.length - 1 while (pos >= 0 && builder(pos) != '\n') pos -= 1 builder.length - pos - 1 } - def currentIndent = { + def currentIndent: String = { val lineStart = builder.length - currentColumn var pos = lineStart while (pos < builder.length && builder(pos).isWhitespace) @@ -323,15 +323,15 @@ abstract class ScalaFormatter builder.substring(lineStart, pos) } - def lastCharacter = if (builder.length == 0) None else Some(lastChar) + def lastCharacter: Option[Char] = if (builder.isEmpty) None else Some(lastChar) - def ensureAtBeginningOfLine() = { + def ensureAtBeginningOfLine(): StringBuilder = { if (!atBeginningOfLine) newline() builder } - def atVisibleCharacter = builder.length > 0 && !Character.isWhitespace(lastChar) + def atVisibleCharacter: Boolean = builder.nonEmpty && !Character.isWhitespace(lastChar) } implicit def stringBuilder2stringBuilderExtra(builder: StringBuilder): StringBuilderExtra = new StringBuilderExtra(builder) @@ -341,18 +341,18 @@ abstract class ScalaFormatter private def handleNewlineFormatting( previousTokenOption: Option[Token], - token: Token, - nextTokenOption: Option[Token], - tokens: List[Token], - tokenIndentMap: Map[Token, Int], - maybeNewlineFormat: Option[IntertokenFormatInstruction] + token: Token, + nextTokenOption: Option[Token], + tokens: List[Token], + tokenIndentMap: Map[Token, Int], + maybeNewlineFormat: Option[IntertokenFormatInstruction] ): IntertokenFormatInstruction = { def defaultNewline() = defaultNewlineFormattingInstruction( previousTokenOption, token, nextTokenOption ) - if(!allowParamGroupsOnNewlines) maybeNewlineFormat.getOrElse(defaultNewline()) + if (!allowParamGroupsOnNewlines) maybeNewlineFormat.getOrElse(defaultNewline()) else { // add support for newline param groups: // @@ -361,48 +361,45 @@ abstract class ScalaFormatter // (role: R, user: U) // (implicit t: Timer) val maybeIndentLevel = nextTokenOption.map(_.tokenType) match { - case - Some(LPAREN) | Some(LBRACKET) if ( - token.tokenType == NEWLINE && maybeNewlineFormat.isEmpty && - !previousTokenOption.exists(_.tokenType == RBRACE) // exclude `}` followed by `(` - ) => + case Some(LPAREN) | Some(LBRACKET) if token.tokenType == NEWLINE && maybeNewlineFormat.isEmpty && + !previousTokenOption.exists(_.tokenType == RBRACE) // exclude `}` followed by `(` + => // backtrack through tokens to find first open brace/newline delimiter val tokenGroup = tokens.splitAt(tokens.indexOf(token))._1 - val delimiterToken = Utils.withPreviousAndNext(tokenGroup).reverse.find { case (prev, curr, next) => - val tt = curr.tokenType - tt == LBRACE || tt == NEWLINES || (tt == NEWLINE && - // keep backtracking if newline plus `[`, `(`, or `]` - !next.exists(n => Set(LBRACKET, LPAREN).exists(_ == n.tokenType)) && - !prev.exists(_.tokenType == RBRACKET) // e.g. private[this] - ) + val delimiterToken = Utils.withPreviousAndNext(tokenGroup).reverse.find { + case (prev, curr, next) => + val tt = curr.tokenType + tt == LBRACE || tt == NEWLINES || (tt == NEWLINE && + // keep backtracking if newline plus `[`, `(`, or `]` + !next.exists(n => Set(LBRACKET, LPAREN).contains(n.tokenType)) && + !prev.exists(_.tokenType == RBRACKET) // e.g. private[this] + ) }.map(_._2) // first token after delimiter has indent level of param group's parent - delimiterToken.flatMap{ x => + delimiterToken.flatMap { x => val indentToken = tokenGroup(tokenGroup.indexOf(x) + 1) tokenIndentMap.get(indentToken) }. - // top-level definition, use first token's indent level - orElse( - tokenGroup.headOption.flatMap(tokenIndentMap.get) - ) + // top-level definition, use first token's indent level + orElse( + tokenGroup.headOption.flatMap(tokenIndentMap.get) + ) case _ => None } - def calcIndent(i: Int) = ( - i / indentSpacesNum + 1 - ) + def calcIndent(i: Int) = i / indentSpacesNum + 1 maybeNewlineFormat match { case Some(t: EnsureNewlineAndIndent) => // apply new indent level - maybeIndentLevel.map( x => t.copy(indentLevel = calcIndent(x))).getOrElse(t) + maybeIndentLevel.map(x => t.copy(indentLevel = calcIndent(x))).getOrElse(t) case Some(t) => t case None => maybeIndentLevel.map { num => EnsureNewlineAndIndent(calcIndent(num)) }. - getOrElse(defaultNewline()) + getOrElse(defaultNewline()) } } } @@ -430,28 +427,29 @@ abstract class ScalaFormatter } private def printableFormattingInstruction( - previousTokenOption: Option[Token], - token: Token, - nextTokenOption: Option[Token], - predecessorFormatting: Map[Token, IntertokenFormatInstruction]): IntertokenFormatInstruction = { + previousTokenOption: Option[Token], + token: Token, + nextTokenOption: Option[Token], + predecessorFormatting: Map[Token, IntertokenFormatInstruction] + ): IntertokenFormatInstruction = { val maybePredecessorFormatting = predecessorFormatting.get(token) val isGaplessAssignment = maybePredecessorFormatting match { // `foreach(_.id= ..)` - case x @ Some(PlaceAtColumn(_, _, Some(Token(USCORE, _, _, _)))) => token.tokenType == EQUALS + case Some(PlaceAtColumn(_, _, Some(Token(USCORE, _, _, _)))) => token.tokenType == EQUALS // `foreach(foo= _)` case _ => token.tokenType == EQUALS && nextTokenOption.exists(_.tokenType == USCORE) } val maybeInstruction = - if(isGaplessAssignment) Some(CompactEnsuringGap) + if (isGaplessAssignment) Some(CompactEnsuringGap) else maybePredecessorFormatting.orElse( previousTokenOption.map(defaultFormattingInstruction(_, token)) ) maybeInstruction.getOrElse( - if (token.tokenType == EOF) EnsureNewlineAndIndent(0) /* <-- to allow formatting of files with just a scaladoc comment */ - else Compact - ) + if (token.tokenType == EOF) EnsureNewlineAndIndent(0) /* <-- to allow formatting of files with just a scaladoc comment */ + else Compact + ) } private def defaultFormattingInstruction(token1: Token, token2: Token): IntertokenFormatInstruction = { @@ -595,9 +593,9 @@ object ScalaFormatter { type Result = CompilationUnit - def parse(parser: ScalaParser) = parser.compilationUnitOrScript() + def parse(parser: ScalaParser): CompilationUnit = parser.compilationUnitOrScript() - def format(formatter: ScalaFormatter, result: Result) = formatter.format(result)(FormatterState(indentLevel = initialIndentLevel)) + def format(formatter: ScalaFormatter, result: Result): FormatResult = formatter.format(result)(FormatterState(indentLevel = initialIndentLevel)) } val (edits, _) = specificFormatter.fullFormat(source, scalaVersion = scalaVersion)(formattingPreferences) diff --git a/scalariform/src/main/scala/scalariform/formatter/SpecificFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/SpecificFormatter.scala index 1fd3e893..6aceefcb 100644 --- a/scalariform/src/main/scala/scalariform/formatter/SpecificFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/SpecificFormatter.scala @@ -1,11 +1,11 @@ package scalariform.formatter +import scalariform.ScalaVersions +import scalariform.formatter.preferences._ import scalariform.lexer.Tokens._ import scalariform.lexer._ import scalariform.parser._ import scalariform.utils._ -import scalariform.formatter.preferences._ -import scalariform.ScalaVersions trait SpecificFormatter { @@ -68,7 +68,7 @@ trait SpecificFormatter { val formattingPreferences: IFormattingPreferences = actualFormattingPreferences - val newlineSequence = newlineSequence_ + val newlineSequence: String = newlineSequence_ } diff --git a/scalariform/src/main/scala/scalariform/formatter/TemplateFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/TemplateFormatter.scala index 808e3a36..21dafdee 100644 --- a/scalariform/src/main/scala/scalariform/formatter/TemplateFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/TemplateFormatter.scala @@ -1,9 +1,8 @@ package scalariform.formatter +import scalariform.formatter.preferences._ import scalariform.lexer.Token - import scalariform.parser._ -import scalariform.formatter.preferences._ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatter with HasHiddenTokenInfo with TypeFormatter with ExprFormatter with ScalaFormatter ⇒ @@ -19,8 +18,8 @@ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatte } for { - accessModifier ← accessModifierOpt - astNode ← (paramClausesOpt orElse templateInheritanceSectionOpt orElse templateBodyOption) + _ ← accessModifierOpt + astNode ← paramClausesOpt orElse templateInheritanceSectionOpt orElse templateBodyOption firstToken ← astNode.firstTokenOption } formatResult = formatResult.formatNewlineOrOrdinary(firstToken, CompactEnsuringGap) @@ -28,7 +27,7 @@ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatte paramClauses ← paramClausesOpt firstToken ← paramClauses.firstTokenOption } { - if (annotations.size > 0) + if (annotations.nonEmpty) formatResult = formatResult.formatNewlineOrOrdinary(firstToken, CompactEnsuringGap) val doubleIndentParams = (formattingPreferences(DoubleIndentConstructorArguments) && !templateInheritanceSectionOpt.exists { section ⇒ @@ -47,7 +46,7 @@ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatte currentFormatterState = formatterState.indent(inheritanceIndent) formatResult = formatResult.before(extendsOrSubtype, currentFormatterState.currentIndentLevelInstruction) } - for (EarlyDefs(earlyBody: TemplateBody, withOpt) ← earlyDefsOpt) + for (EarlyDefs(earlyBody: TemplateBody, _) ← earlyDefsOpt) formatResult ++= format(earlyBody)(currentFormatterState) for (templateParents ← templateParentsOpt) { @@ -94,14 +93,14 @@ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatte val Template(earlyDefsOpt, templateParentsOpt, templateBodyOpt) = template var formatResult: FormatResult = NoFormatResult - for (EarlyDefs(earlyBody, withOpt) ← earlyDefsOpt) + for (EarlyDefs(earlyBody, _) ← earlyDefsOpt) formatResult ++= format(earlyBody) for (templateParents ← templateParentsOpt) formatResult ++= format(templateParents) // TODO: Copy and paste from above - for (templateBody @ TemplateBody(newlineOpt, lbrace, statSeq, rbrace) ← templateBodyOpt) { + for (TemplateBody(newlineOpt, lbrace, statSeq, rbrace) ← templateBodyOpt) { newlineOpt match { case Some(newline) ⇒ formatResult = formatResult.formatNewline(newline, CompactEnsuringGap) @@ -126,7 +125,7 @@ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatte // TODO: Unify with TmplDef code val currentFormatterState = formatterState - for ((withToken, type_, argumentExprss2) ← withTypes) { + for ((_, type_, argumentExprss2) ← withTypes) { formatResult ++= format(type_)(currentFormatterState) for (argumentExprs2 ← argumentExprss2) formatResult ++= format(argumentExprs2)(currentFormatterState)._1 diff --git a/scalariform/src/main/scala/scalariform/formatter/TypeFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/TypeFormatter.scala index 5351e294..cf234b87 100644 --- a/scalariform/src/main/scala/scalariform/formatter/TypeFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/TypeFormatter.scala @@ -1,10 +1,8 @@ package scalariform.formatter -import scalariform.lexer.Token -import scalariform.parser._ -import scalariform.lexer.Tokens import scalariform.formatter.preferences._ -import scalariform.lexer.Chars +import scalariform.lexer.{ Chars, Token, Tokens } +import scalariform.parser._ trait TypeFormatter { self: HasFormattingPreferences with AnnotationFormatter with ExprFormatter with ScalaFormatter ⇒ @@ -54,8 +52,8 @@ trait TypeFormatter { self: HasFormattingPreferences with AnnotationFormatter wi case annotation @ Annotation(_, _, _, _) ⇒ format(annotation) case TypeParamClause(contents) ⇒ format(contents) case TypeParam(contents) ⇒ format(contents) - case VarianceTypeElement(id) ⇒ NoFormatResult - case VarargsTypeElement(star) ⇒ NoFormatResult + case VarianceTypeElement(_) ⇒ NoFormatResult + case VarargsTypeElement(_) ⇒ NoFormatResult case _ ⇒ NoFormatResult } } diff --git a/scalariform/src/main/scala/scalariform/formatter/XmlFormatter.scala b/scalariform/src/main/scala/scalariform/formatter/XmlFormatter.scala index 19ae7c65..ebcb7dd2 100644 --- a/scalariform/src/main/scala/scalariform/formatter/XmlFormatter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/XmlFormatter.scala @@ -1,9 +1,9 @@ package scalariform.formatter +import scalariform.formatter.preferences._ +import scalariform.lexer._ import scalariform.parser._ import scalariform.utils._ -import scalariform.lexer._ -import scalariform.formatter.preferences._ trait XmlFormatter { self: HasFormattingPreferences with ExprFormatter with ScalaFormatter ⇒ @@ -110,7 +110,7 @@ trait XmlFormatter { self: HasFormattingPreferences with ExprFormatter with Scal var firstNonWhitespace = true for (previousAndThis ← Utils.pairWithPrevious(contents)) { previousAndThis match { - case (_, XmlPCDATA(token @ Token(_, Trimmed(prefix, infix, suffix), _, _))) ⇒ + case (_, XmlPCDATA(token @ Token(_, Trimmed(_, infix, _), _, _))) ⇒ if (infix == "") { if (multiline) formatResult = formatResult.replaceXml(token, "") diff --git a/scalariform/src/main/scala/scalariform/formatter/preferences/IFormattingPreferences.scala b/scalariform/src/main/scala/scalariform/formatter/preferences/IFormattingPreferences.scala index 18ab2c9f..c749ed36 100644 --- a/scalariform/src/main/scala/scalariform/formatter/preferences/IFormattingPreferences.scala +++ b/scalariform/src/main/scala/scalariform/formatter/preferences/IFormattingPreferences.scala @@ -14,18 +14,18 @@ trait IFormattingPreferences { abstract sealed class IndentStyle { def indent(n: Int): String - protected def repeat(s: String, n: Int) = 1 to n map { _ ⇒ s } mkString + protected def repeat(s: String, n: Int): String = 1 to n map { _ ⇒ s } mkString } case object Tabs extends IndentStyle { - def indent(indentLevel: Int) = repeat("\t", indentLevel) + def indent(indentLevel: Int): String = repeat("\t", indentLevel) } case class Spaces(n: Int) extends IndentStyle { - def indent(indentLevel: Int) = repeat(repeat(" ", n), indentLevel) + def indent(indentLevel: Int): String = repeat(repeat(" ", n), indentLevel) - def length(indentLevel: Int) = indent(indentLevel).length + def length(indentLevel: Int): Int = indent(indentLevel).length } @@ -35,9 +35,9 @@ class FormattingPreferences(val preferencesMap: Map[PreferenceDescriptor[_], Any def setPreference[T](preference: PreferenceDescriptor[T], value: T) = new FormattingPreferences(preferencesMap + (preference -> value)) - override def toString = getClass.getSimpleName + "(" + preferencesMap + ")" + override def toString: String = getClass.getSimpleName + "(" + preferencesMap + ")" - val indentStyle = if (this(IndentWithTabs)) Tabs else Spaces(this(IndentSpaces)) + val indentStyle: IndentStyle = if (this(IndentWithTabs)) Tabs else Spaces(this(IndentSpaces)) } case object FormattingPreferences extends FormattingPreferences(Map()) { diff --git a/scalariform/src/main/scala/scalariform/formatter/preferences/PreferenceDescriptor.scala b/scalariform/src/main/scala/scalariform/formatter/preferences/PreferenceDescriptor.scala index 271e4f18..d49e6b18 100755 --- a/scalariform/src/main/scala/scalariform/formatter/preferences/PreferenceDescriptor.scala +++ b/scalariform/src/main/scala/scalariform/formatter/preferences/PreferenceDescriptor.scala @@ -22,7 +22,7 @@ case object Prevent extends Intent case object IntentPreference extends PreferenceType[Intent] { - def parseValue(s: String) = + def parseValue(s: String): Either[String, Intent] = s.toLowerCase match { case "preserve" ⇒ Right(Preserve) case "force" ⇒ Right(Force) @@ -33,7 +33,7 @@ case object IntentPreference extends PreferenceType[Intent] { case object BooleanPreference extends PreferenceType[Boolean] { - def parseValue(s: String) = + def parseValue(s: String): Either[String, Boolean] = s.toLowerCase match { case "true" ⇒ Right(true) case "false" ⇒ Right(false) @@ -46,7 +46,7 @@ case class IntegerPreference(min: Int, max: Int) extends PreferenceType[Int] { require(min <= max) - def parseValue(s: String) = + def parseValue(s: String): Either[String, Int] = try { val n = Integer.parseInt(s) if (n < min) @@ -56,7 +56,7 @@ case class IntegerPreference(min: Int, max: Int) extends PreferenceType[Int] { else Right(n) } catch { - case e: NumberFormatException ⇒ Left("Could not parse as integer: " + s) + case _: NumberFormatException ⇒ Left("Could not parse as integer: " + s) } } @@ -74,13 +74,13 @@ trait PreferenceDescriptor[T] { trait IntentPreferenceDescriptor extends PreferenceDescriptor[Intent] { - val preferenceType = IntentPreference + val preferenceType: IntentPreference.type = IntentPreference } trait BooleanPreferenceDescriptor extends PreferenceDescriptor[Boolean] { - val preferenceType = BooleanPreference + val preferenceType: BooleanPreference.type = BooleanPreference } @@ -151,7 +151,7 @@ case object CompactStringConcatenation extends BooleanPreferenceDescriptor { case object DanglingCloseParenthesis extends IntentPreferenceDescriptor { val key = "danglingCloseParenthesis" val description = "Dangling closing ')' in an argument expression on a new line" - val defaultValue = Prevent + val defaultValue: Prevent.type = Prevent } case object DoubleIndentConstructorArguments extends BooleanPreferenceDescriptor { @@ -176,13 +176,13 @@ case object DoubleIndentMethodDeclaration extends BooleanPreferenceDescriptor { case object FirstArgumentOnNewline extends IntentPreferenceDescriptor { val key = "firstArgumentOnNewline" val description = "First argument to functions calls on a new line" - val defaultValue = Force + val defaultValue: Force.type = Force } case object FirstParameterOnNewline extends IntentPreferenceDescriptor { val key = "firstParameterOnNewline" val description = "First parameter in function or class definitions on a new line" - val defaultValue = Force + val defaultValue: Force.type = Force } case object FormatXml extends BooleanPreferenceDescriptor { diff --git a/scalariform/src/main/scala/scalariform/formatter/preferences/PreferencesImporterExporter.scala b/scalariform/src/main/scala/scalariform/formatter/preferences/PreferencesImporterExporter.scala index 3c036cd0..edeba166 100644 --- a/scalariform/src/main/scala/scalariform/formatter/preferences/PreferencesImporterExporter.scala +++ b/scalariform/src/main/scala/scalariform/formatter/preferences/PreferencesImporterExporter.scala @@ -1,9 +1,10 @@ package scalariform.formatter.preferences +import java.io.IOException import java.util.Properties + import scala.collection.JavaConverters._ import scalariform.utils.Utils._ -import java.io.IOException object PreferencesImporterExporter { @@ -15,9 +16,9 @@ object PreferencesImporterExporter { var preferences = FormattingPreferences() - def setPreference[T](preferenceDescriptor: PreferenceDescriptor[T], valueString: String) = + def setPreference[T](preferenceDescriptor: PreferenceDescriptor[T], valueString: String): Unit = preferenceDescriptor.preferenceType.parseValue(valueString) match { - case Left(error) ⇒ + case Left(_) ⇒ case Right(value) ⇒ preferences = preferences.setPreference(preferenceDescriptor, value) } @@ -47,7 +48,7 @@ object PreferencesImporterExporter { } @throws(classOf[IOException]) - def savePreferences(path: String, preferences: IFormattingPreferences) { + def savePreferences(path: String, preferences: IFormattingPreferences): Unit = { val properties = asProperties(preferences) withFileOutputStream(path) { stream ⇒ properties.store(stream, "Scalariform formatter preferences") diff --git a/scalariform/src/main/scala/scalariform/lexer/Chars.scala b/scalariform/src/main/scala/scalariform/lexer/Chars.scala index 1be129cc..3cfe98ae 100644 --- a/scalariform/src/main/scala/scalariform/lexer/Chars.scala +++ b/scalariform/src/main/scala/scalariform/lexer/Chars.scala @@ -13,13 +13,13 @@ object Chars { '^' | '*' | '+' | '-' | '<' | '>' | '?' | ':' | '=' | '&' | '|' | '/' | '\\' ⇒ true - case c ⇒ isSpecial(c) + case _ ⇒ isSpecial(c) } /** * @see scala.reflect.internal.Chars.isSpecial */ - def isSpecial(c: Char) = { + def isSpecial(c: Char): Boolean = { val chtp = Character.getType(c) chtp == Character.MATH_SYMBOL.toInt || chtp == Character.OTHER_SYMBOL.toInt } @@ -27,13 +27,13 @@ object Chars { /** * @see scala.reflect.internal.Chars.isIdentifierStart */ - def isIdentifierStart(c: Char) = + def isIdentifierStart(c: Char): Boolean = (c == '_') || (c == '$') || Character.isUnicodeIdentifierStart(c) /** * @see scala.reflect.internal.Chars.isIdentifierPart */ - def isIdentifierPart(c: Char) = + def isIdentifierPart(c: Char): Boolean = (c == '$') || Character.isUnicodeIdentifierPart(c) && c != CharConstants.SU } diff --git a/scalariform/src/main/scala/scalariform/lexer/HiddenToken.scala b/scalariform/src/main/scala/scalariform/lexer/HiddenToken.scala index 0fd76684..7a9f4c13 100644 --- a/scalariform/src/main/scala/scalariform/lexer/HiddenToken.scala +++ b/scalariform/src/main/scala/scalariform/lexer/HiddenToken.scala @@ -2,11 +2,11 @@ package scalariform.lexer abstract sealed class HiddenToken(val token: Token) { - lazy val newlineful = token.text contains '\n' + lazy val newlineful: Boolean = token.text contains '\n' - def text = token.text + def text: String = token.text - def rawText = token.rawText + def rawText: String = token.rawText } diff --git a/scalariform/src/main/scala/scalariform/lexer/HiddenTokens.scala b/scalariform/src/main/scala/scalariform/lexer/HiddenTokens.scala index 0769d7c2..0ece3a12 100644 --- a/scalariform/src/main/scala/scalariform/lexer/HiddenTokens.scala +++ b/scalariform/src/main/scala/scalariform/lexer/HiddenTokens.scala @@ -4,7 +4,7 @@ object NoHiddenTokens extends HiddenTokens(Nil) case class HiddenTokens(tokens: List[HiddenToken]) extends Iterable[HiddenToken] { - def removeInitialWhitespace = new HiddenTokens(tokens.dropWhile(_.isInstanceOf[Whitespace])) + def removeInitialWhitespace = HiddenTokens(tokens.dropWhile(_.isInstanceOf[Whitespace])) override def iterator: Iterator[HiddenToken] = tokens.iterator @@ -14,13 +14,13 @@ case class HiddenTokens(tokens: List[HiddenToken]) extends Iterable[HiddenToken] val whitespaces: List[Whitespace] = tokens collect { case whitespace @ Whitespace(_) ⇒ whitespace } - def firstTokenOption = tokens.headOption + def firstTokenOption: Option[HiddenToken] = tokens.headOption - def lastTokenOption = tokens.lastOption + def lastTokenOption: Option[HiddenToken] = tokens.lastOption - def containsNewline = text contains '\n' + def containsNewline: Boolean = text contains '\n' - def containsComment = comments.nonEmpty + def containsComment: Boolean = comments.nonEmpty def containsUnicodeEscape: Boolean = { for (token ← tokens if token.token.containsUnicodeEscape) @@ -33,12 +33,12 @@ case class HiddenTokens(tokens: List[HiddenToken]) extends Iterable[HiddenToken] for (token ← tokens) sb.append(token.text) sb.toString } - lazy val rawText = tokens.map(_.token.rawText).mkString + lazy val rawText: String = tokens.map(_.token.rawText).mkString - def rawTokens = tokens.map(_.token) + def rawTokens: List[Token] = tokens.map(_.token) - def offset = tokens.head.token.offset + def offset: Int = tokens.head.token.offset - def lastCharacterOffset = tokens.last.token.lastCharacterOffset + def lastCharacterOffset: Int = tokens.last.token.lastCharacterOffset } diff --git a/scalariform/src/main/scala/scalariform/lexer/LexerMode.scala b/scalariform/src/main/scala/scalariform/lexer/LexerMode.scala index 59340166..7b268220 100644 --- a/scalariform/src/main/scala/scalariform/lexer/LexerMode.scala +++ b/scalariform/src/main/scala/scalariform/lexer/LexerMode.scala @@ -6,7 +6,7 @@ class ScalaMode extends LexerMode { private var braceNestLevel: Int = 0 - def nestBrace() { braceNestLevel += 1 } + def nestBrace(): Unit = { braceNestLevel += 1 } def unnestBrace(): Int = { braceNestLevel -= 1 @@ -23,14 +23,14 @@ class XmlMode extends LexerMode { private var tagNestLevel: Int = 0 - def nestTag() { tagNestLevel += 1 } + def nestTag(): Unit = { tagNestLevel += 1 } def unnestTag(): Int = { tagNestLevel -= 1 tagNestLevel } - def nestingLevel = tagNestLevel + def nestingLevel: Int = tagNestLevel } diff --git a/scalariform/src/main/scala/scalariform/lexer/ModeStack.scala b/scalariform/src/main/scala/scalariform/lexer/ModeStack.scala index 02ee5576..cf151260 100644 --- a/scalariform/src/main/scala/scalariform/lexer/ModeStack.scala +++ b/scalariform/src/main/scala/scalariform/lexer/ModeStack.scala @@ -1,45 +1,45 @@ package scalariform.lexer -import scala.collection.mutable.Stack +import scala.collection.mutable /** * Keeping track of nesting level of XML within Scala. */ trait ModeStack { self: ScalaLexer ⇒ - private val modeStack = new Stack[LexerMode] + private val modeStack = new mutable.Stack[LexerMode] modeStack.push(new ScalaMode) - protected def popMode() { + protected def popMode(): Unit = { modeStack.pop() } - protected def isRootMode = modeStack.size == 1 + protected def isRootMode: Boolean = modeStack.size == 1 - protected def switchToScalaModeAndFetchToken() { + protected def switchToScalaModeAndFetchToken(): Unit = { switchToScalaMode() fetchScalaToken() } - protected def switchToXmlModeAndFetchToken() { + protected def switchToXmlModeAndFetchToken(): Unit = { modeStack.push(new XmlMode) fetchXmlToken() } - protected def switchToStringInterpolationMode(multiLine: Boolean) { + protected def switchToStringInterpolationMode(multiLine: Boolean): Unit = { modeStack.push(new StringInterpolationMode(multiLine)) } - protected def switchToScalaMode() { + protected def switchToScalaMode(): Unit = { modeStack.push(new ScalaMode) } - protected def isStringInterpolationMode = modeStack.head.isInstanceOf[StringInterpolationMode] + protected def isStringInterpolationMode: Boolean = modeStack.head.isInstanceOf[StringInterpolationMode] - protected def isXmlMode = modeStack.head.isInstanceOf[XmlMode] + protected def isXmlMode: Boolean = modeStack.head.isInstanceOf[XmlMode] - protected def isScalaMode = modeStack.head.isInstanceOf[ScalaMode] + protected def isScalaMode: Boolean = modeStack.head.isInstanceOf[ScalaMode] protected def xmlMode: XmlMode = modeStack.head.asInstanceOf[XmlMode] diff --git a/scalariform/src/main/scala/scalariform/lexer/NewlineInferencer.scala b/scalariform/src/main/scala/scalariform/lexer/NewlineInferencer.scala index 9dc76871..cd7449a0 100644 --- a/scalariform/src/main/scala/scalariform/lexer/NewlineInferencer.scala +++ b/scalariform/src/main/scala/scalariform/lexer/NewlineInferencer.scala @@ -28,7 +28,7 @@ class NewlineInferencer(delegate: WhitespaceAndCommentsGrouper) extends Iterator */ private var regionMarkerStack: List[TokenType] = Nil - def hasNext = nextToken != null || tokenToEmitNextTime != null + def hasNext: Boolean = nextToken != null || tokenToEmitNextTime != null def next(): Token = { val token = @@ -48,7 +48,7 @@ class NewlineInferencer(delegate: WhitespaceAndCommentsGrouper) extends Iterator * Multiple statements are allowed immediately inside "{..}" regions, but disallowed immediately inside "[..]", "(..)" * and "case ... =>" regions. */ - private def updateRegionStack(tokenType: TokenType, nextToken: Token) = + private def updateRegionStack(tokenType: TokenType, nextToken: Token): Unit = tokenType match { case LBRACE ⇒ regionMarkerStack ::= RBRACE @@ -61,7 +61,7 @@ class NewlineInferencer(delegate: WhitespaceAndCommentsGrouper) extends Iterator // "case class" and "case object" are excluded from the usual "case .. =>" region. if (followingTokenType != CLASS && followingTokenType != OBJECT) regionMarkerStack ::= ARROW - case tokenType if regionMarkerStack.headOption == Some(tokenType) ⇒ + case _ if regionMarkerStack.headOption == Some(tokenType) ⇒ regionMarkerStack = regionMarkerStack.tail case _ ⇒ } @@ -105,7 +105,7 @@ class NewlineInferencer(delegate: WhitespaceAndCommentsGrouper) extends Iterator else if (regionMarkerStack.nonEmpty && regionMarkerStack.head != RBRACE) false else - return previousToken != null && (TOKENS_WHICH_CAN_END_A_STATEMENT contains previousToken.tokenType) + previousToken != null && (TOKENS_WHICH_CAN_END_A_STATEMENT contains previousToken.tokenType) } private def containsBlankLine(s: String): Boolean = { diff --git a/scalariform/src/main/scala/scalariform/lexer/RedundantSemicolonDetector.scala b/scalariform/src/main/scala/scalariform/lexer/RedundantSemicolonDetector.scala index 2532d88c..ad1a3ecf 100644 --- a/scalariform/src/main/scala/scalariform/lexer/RedundantSemicolonDetector.scala +++ b/scalariform/src/main/scala/scalariform/lexer/RedundantSemicolonDetector.scala @@ -1,9 +1,8 @@ package scalariform.lexer -import scalariform.utils.Utils._ -import scalariform.utils.TextEdit -import scalariform.utils.TextEditProcessor import scalariform.ScalaVersions +import scalariform.utils.{ TextEdit, TextEditProcessor } +import scalariform.utils.Utils._ object RedundantSemicolonDetector { diff --git a/scalariform/src/main/scala/scalariform/lexer/ScalaLexer.scala b/scalariform/src/main/scala/scalariform/lexer/ScalaLexer.scala index 94388b6a..ddd232a0 100644 --- a/scalariform/src/main/scala/scalariform/lexer/ScalaLexer.scala +++ b/scalariform/src/main/scala/scalariform/lexer/ScalaLexer.scala @@ -1,9 +1,9 @@ package scalariform.lexer import scala.xml.parsing.TokenTests +import scalariform._ import scalariform.lexer.CharConstants.SU import scalariform.lexer.Tokens._ -import scalariform._ class ScalaLexer( protected val reader: IUnicodeEscapeReader, @@ -34,7 +34,7 @@ class ScalaLexer( /** * Is the current character the result of a unicode escape? */ - protected def isUnicodeEscape = unicodeEscapesBuffer(bufferStart).isDefined + protected def isUnicodeEscape: Boolean = unicodeEscapesBuffer(bufferStart).isDefined // ------------------------------------------------------------------------------------------------------------ @@ -71,7 +71,7 @@ class ScalaLexer( */ private var untilEof = if (reader.isEof) 0 else -1 - protected def eof = untilEof == 0 + protected def eof: Boolean = untilEof == 0 private var eofTokenEmitted = false @@ -87,13 +87,13 @@ class ScalaLexer( /** * Get the character at the given lookahead from the current position. */ - protected def ch(lookahead: Int) = { - for (n ← 1 to lookahead + 1 - charsInBuffer) + protected def ch(lookahead: Int): Char = { + for (_ ← 1 to lookahead + 1 - charsInBuffer) bufferOneCharacter() charBuffer((bufferStart + lookahead) & BUFFER_MASK) } - private def bufferOneCharacter() { + private def bufferOneCharacter(): Unit = { charBuffer(bufferEnd) = reader.read() unicodeEscapesBuffer(bufferEnd) = reader.unicodeEscapeOpt bufferEnd = (bufferEnd + 1) & BUFFER_MASK @@ -104,7 +104,7 @@ class ScalaLexer( /** * Accept the current character and advance to the next. */ - protected def nextChar() { + protected def nextChar(): Unit = { if (bufferEnd == bufferStart) bufferOneCharacter() lastCh = charBuffer(bufferStart) @@ -125,7 +125,7 @@ class ScalaLexer( /** * Mark the end of a token of the given type. */ - protected def token(tokenType: TokenType) { + protected def token(tokenType: TokenType): Unit = { // require(tokenType == EOF || tokenLength > 0) finaliseTokenData() builtToken = Token(tokenType, tokenText, tokenOffset, rawText) @@ -135,7 +135,7 @@ class ScalaLexer( resetTokenData() } - private def resetTokenData() { + private def resetTokenData(): Unit = { rawText = null tokenText = null tokenOffset = stopIndex + 1 @@ -143,7 +143,7 @@ class ScalaLexer( seenUnicodeEscape = false } - private def finaliseTokenData() { + private def finaliseTokenData(): Unit = { if (tokenText == null) { stopIndex = math.min(tokenOffset + tokenLength - 1, reader.text.length - 1) // min protects against overeager consumption past EOF rawText = reader.text.substring(tokenOffset, stopIndex + 1) @@ -165,7 +165,7 @@ class ScalaLexer( protected def lookaheadIs(s: String): Boolean = s.zipWithIndex forall { case (c, index) ⇒ ch(index) == c } - protected def munch(s: String) { + protected def munch(s: String): Unit = { // require(lookaheadIs(s)) for (_ ← 1 to s.length) nextChar() @@ -185,9 +185,9 @@ class ScalaLexer( builtToken } - override def hasNext = !eofTokenEmitted + override def hasNext: Boolean = !eofTokenEmitted - private def fetchStringInterpolationToken() { + private def fetchStringInterpolationToken(): Unit = { if (stringInterpolationMode.interpolationVariable) { stringInterpolationMode.interpolationVariable = false do { diff --git a/scalariform/src/main/scala/scalariform/lexer/ScalaLexerReader.scala b/scalariform/src/main/scala/scalariform/lexer/ScalaLexerReader.scala index 5c771b3d..af7f3c6b 100644 --- a/scalariform/src/main/scala/scalariform/lexer/ScalaLexerReader.scala +++ b/scalariform/src/main/scala/scalariform/lexer/ScalaLexerReader.scala @@ -1,7 +1,7 @@ package scalariform.lexer -import scalariform.lexer.Tokens._ import scala.util.parsing.input._ +import scalariform.lexer.Tokens._ class ScalaLexerReader(val tokens: List[Token]) extends Reader[Token] { @@ -21,7 +21,7 @@ class ScalaLexerReader(val tokens: List[Token]) extends Reader[Token] { protected def lineContents: String = token.rawText - override def longString = lineContents + override def longString: String = lineContents } diff --git a/scalariform/src/main/scala/scalariform/lexer/ScalaOnlyLexer.scala b/scalariform/src/main/scala/scalariform/lexer/ScalaOnlyLexer.scala index 0c3bd36d..dd4ee68b 100644 --- a/scalariform/src/main/scala/scalariform/lexer/ScalaOnlyLexer.scala +++ b/scalariform/src/main/scala/scalariform/lexer/ScalaOnlyLexer.scala @@ -1,11 +1,11 @@ package scalariform.lexer import scala.annotation._ +import scalariform._ import scalariform.lexer.CharConstants.SU import scalariform.lexer.Chars._ import scalariform.lexer.Tokens._ import scalariform.utils.Utils -import scalariform._ /** * Lexer implementation for non-XML Scala @@ -16,7 +16,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ private var possibleInterpolationId = false - protected def fetchScalaToken() { + protected def fetchScalaToken(): Unit = { (ch: @switch) match { case ' ' | '\t' | '\n' | '\r' /* TODO: | FF */ ⇒ nextChar() @@ -78,9 +78,9 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ case '\'' ⇒ nextChar() if (isIdentifierStart(ch)) - charLitOr(() => getIdentRest) + charLitOr(() => getIdentRest()) else if (isOperatorPart(ch) && (ch != '\\')) - charLitOr(() => getOperatorRest) + charLitOr(() => getOperatorRest()) else { getLitChar() if (ch == '\'' || forgiveErrors) { @@ -148,15 +148,15 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ token(WS) } - private def getStringLit() { + private def getStringLit(): Unit = { getStringLitOrBackquotedIdent(delimiter = '"', errorMsg = "unclosed string literal", tokenType = STRING_LITERAL) } - private def getBackquotedIdent() { + private def getBackquotedIdent(): Unit = { getStringLitOrBackquotedIdent(delimiter = '`', errorMsg = "unclosed quoted identifer", tokenType = VARID, errorMsgOnEmpty = Some("empty quoted identifier")) } - private def getStringLitOrBackquotedIdent(delimiter: Char, errorMsg: String, tokenType: TokenType, errorMsgOnEmpty: Option[String] = None) { + private def getStringLitOrBackquotedIdent(delimiter: Char, errorMsg: String, tokenType: TokenType, errorMsgOnEmpty: Option[String] = None): Unit = { // require(ch == delimiter) nextChar() @tailrec @@ -177,7 +177,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ scanForClosingQuotes(firstTime = true) } - private def getLitChar() { + private def getLitChar(): Unit = { if (ch == '\\') { nextChar() if ('0' <= ch && ch <= '7') { @@ -196,11 +196,11 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ nextChar() } - private def getMultiLineStringLit() { + private def getMultiLineStringLit(): Unit = { munch("\"\"\"") @tailrec - def scanForClosingTripleQuotes() { + def scanForClosingTripleQuotes(): Unit = { if (lookaheadIs("\"\"\"")) { munch("\"\"\"") while (ch == '\"') { nextChar() } @@ -216,7 +216,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ } @tailrec - final protected def getStringPart(multiLine: Boolean) { + final protected def getStringPart(multiLine: Boolean): Unit = { if (ch == '"') { if (multiLine) { nextChar() @@ -322,7 +322,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ if (isSpecial(ch)) { nextChar(); getOperatorRest() } else finishNamed() } - private def getIdentOrOperatorRest() { + private def getIdentOrOperatorRest(): Unit = { if (isIdentifierPart(ch)) getIdentRest() else ch match { @@ -339,7 +339,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ } } - private def finishNamed() { + private def finishNamed(): Unit = { val tokenType = if (processingSymbol) SYMBOL_LITERAL @@ -352,7 +352,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ token(tokenType) } - private def getSingleLineComment() { + private def getSingleLineComment(): Unit = { // require(ch == '/') nextChar() // require(ch == '/') @@ -376,20 +376,20 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ consumeUntilNewline() } - private def getMultilineComment() { + private def getMultilineComment(): Unit = { munch("/*") @tailrec - def consumeUntilSplatSlash(nesting: Int) { + def consumeUntilSplatSlash(nesting: Int): Unit = { if (nesting == 0) token(MULTILINE_COMMENT) else (ch: @switch) match { - case '*' if (ch(1) == '/') ⇒ + case '*' if ch(1) == '/' ⇒ nextChar() nextChar() consumeUntilSplatSlash(nesting - 1) - case '/' if (ch(1) == '*') ⇒ + case '/' if ch(1) == '*' ⇒ nextChar() nextChar() consumeUntilSplatSlash(nesting + 1) @@ -404,7 +404,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ consumeUntilSplatSlash(nesting = 1) } - private def getFraction() { + private def getFraction(): Unit = { while ('0' <= ch && ch <= '9') { nextChar() } if (ch == 'e' || ch == 'E') { nextChar() @@ -418,7 +418,7 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ token(FLOATING_POINT_LITERAL) } - private def getHexNumber() { + private def getHexNumber(): Unit = { // require(ch == '0') nextChar() // require(ch == 'x' || ch == 'X') @@ -435,15 +435,15 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ munchHexDigits() } - private def getNumber(base: Int) { - def isDigit(c: Char) = if (c == SU) false else (Character isDigit c) + private def getNumber(base: Int): Unit = { + def isDigit(c: Char) = if (c == SU) false else Character isDigit c val base1 = if (base < 10) 10 else base // read 8,9's even if format is octal, produce a malformed number error afterwards. while (Utils.digit2int(ch, base1) >= 0) nextChar() - def restOfUncertainToken() = { + def restOfUncertainToken(): Unit = { def isEfd = ch match { case 'e' | 'E' | 'f' | 'F' | 'd' | 'D' ⇒ true case _ ⇒ false @@ -506,12 +506,12 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒ } - private def checkNoLetter() { + private def checkNoLetter(): Unit = { if (isIdentifierPart(ch) && ch >= ' ' && !forgiveErrors) throw new ScalaLexerException("Invalid literal number: " + ch) } - private def charLitOr(op: () ⇒ Unit) { + private def charLitOr(op: () ⇒ Unit): Unit = { nextChar() if (ch == '\'') { nextChar() diff --git a/scalariform/src/main/scala/scalariform/lexer/TagState.scala b/scalariform/src/main/scala/scalariform/lexer/TagState.scala index 9d5dd2e2..5808746a 100644 --- a/scalariform/src/main/scala/scalariform/lexer/TagState.scala +++ b/scalariform/src/main/scala/scalariform/lexer/TagState.scala @@ -1,6 +1,6 @@ package scalariform.lexer -abstract sealed trait TagState +sealed trait TagState case object InStartTag extends TagState case object InEndTag extends TagState case object Normal extends TagState diff --git a/scalariform/src/main/scala/scalariform/lexer/Token.scala b/scalariform/src/main/scala/scalariform/lexer/Token.scala index 5e71a0cf..5e809ea0 100644 --- a/scalariform/src/main/scala/scalariform/lexer/Token.scala +++ b/scalariform/src/main/scala/scalariform/lexer/Token.scala @@ -17,13 +17,13 @@ case class Token(tokenType: TokenType, text: String, offset: Int, rawText: Strin def associatedWhitespaceAndComments: HiddenTokens = associatedWhitespaceAndComments_ - def length = rawText.length + def length: Int = rawText.length def range = Range(offset, length) - def lastCharacterOffset = offset + length - 1 + def lastCharacterOffset: Int = offset + length - 1 - def isScalaDocComment = tokenType == MULTILINE_COMMENT && text.startsWith("/**") && text != "/**/" + def isScalaDocComment: Boolean = tokenType == MULTILINE_COMMENT && text.startsWith("/**") && text != "/**/" - def isNewline = tokenType.isNewline + def isNewline: Boolean = tokenType.isNewline } diff --git a/scalariform/src/main/scala/scalariform/lexer/TokenType.scala b/scalariform/src/main/scala/scalariform/lexer/TokenType.scala index b7c66f7c..c047dc86 100644 --- a/scalariform/src/main/scala/scalariform/lexer/TokenType.scala +++ b/scalariform/src/main/scala/scalariform/lexer/TokenType.scala @@ -2,16 +2,16 @@ package scalariform.lexer case class TokenType(name: String, isXml: Boolean = false) { - def isNewline = this == Tokens.NEWLINE || this == Tokens.NEWLINES + def isNewline: Boolean = this == Tokens.NEWLINE || this == Tokens.NEWLINES - def isKeyword = Tokens.KEYWORDS contains this + def isKeyword: Boolean = Tokens.KEYWORDS contains this - def isComment = Tokens.COMMENTS contains this + def isComment: Boolean = Tokens.COMMENTS contains this - def isId = Tokens.IDS contains this + def isId: Boolean = Tokens.IDS contains this - def isLiteral = Tokens.LITERALS contains this + def isLiteral: Boolean = Tokens.LITERALS contains this - override lazy val toString = name + override lazy val toString: String = name } diff --git a/scalariform/src/main/scala/scalariform/lexer/UnicodeEscapeReader.scala b/scalariform/src/main/scala/scalariform/lexer/UnicodeEscapeReader.scala index be529112..1511a63d 100644 --- a/scalariform/src/main/scala/scalariform/lexer/UnicodeEscapeReader.scala +++ b/scalariform/src/main/scala/scalariform/lexer/UnicodeEscapeReader.scala @@ -35,9 +35,9 @@ trait IUnicodeEscapeReader extends Iterator[Char] { */ def unicodeEscapeOpt: Option[String] - def next() = read() + def next(): Char = read() - def hasNext = !isEof + def hasNext: Boolean = !isEof /** * Return a clone of this reader initialised to the current state @@ -65,7 +65,7 @@ class UnicodeEscapeReader(val text: String, forgiveErrors: Boolean = false) exte reader } - def isEof = pos >= text.length + def isEof: Boolean = pos >= text.length @throws(classOf[ScalaLexerException]) def read(): Char = { @@ -111,7 +111,7 @@ class UnicodeEscapeReader(val text: String, forgiveErrors: Boolean = false) exte do sb.append(consumeNextCharacter()) while (nextChar == 'u') - for (n ← 1 to 4) + for (_ ← 1 to 4) sb.append(consumeNextCharacter()) sb.toString @@ -149,7 +149,7 @@ class NoUnicodeEscapeReader(val text: String) extends IUnicodeEscapeReader { private var pos = 0 - def copy = { + def copy: NoUnicodeEscapeReader = { val reader = new NoUnicodeEscapeReader(text) reader.pos = pos reader diff --git a/scalariform/src/main/scala/scalariform/lexer/WhitespaceAndCommentsGrouper.scala b/scalariform/src/main/scala/scalariform/lexer/WhitespaceAndCommentsGrouper.scala index 19c3c83b..e8e067f3 100644 --- a/scalariform/src/main/scala/scalariform/lexer/WhitespaceAndCommentsGrouper.scala +++ b/scalariform/src/main/scala/scalariform/lexer/WhitespaceAndCommentsGrouper.scala @@ -1,7 +1,7 @@ package scalariform.lexer -import scalariform.lexer.Tokens._ import scala.collection.mutable.ListBuffer +import scalariform.lexer.Tokens._ class WhitespaceAndCommentsGrouper(lexer: ScalaLexer) extends Iterator[Token] { @@ -11,13 +11,13 @@ class WhitespaceAndCommentsGrouper(lexer: ScalaLexer) extends Iterator[Token] { private var hiddenTokens: HiddenTokens = _ - def getHiddenTokens = hiddenTokens + def getHiddenTokens: HiddenTokens = hiddenTokens - def hasNext = !ended + def hasNext: Boolean = !ended private[lexer] def text = lexer.text - def next() = { + def next(): Token = { require(hasNext) hiddenTokens = readHiddenTokens() val resultToken = nextToken @@ -34,7 +34,7 @@ class WhitespaceAndCommentsGrouper(lexer: ScalaLexer) extends Iterator[Token] { hiddenTokens += makeHiddenToken(nextToken) nextToken = lexer.next() } - new HiddenTokens(hiddenTokens.toList) + HiddenTokens(hiddenTokens.toList) } private def isCommentOrWhitespace(token: Token) = token.tokenType match { diff --git a/scalariform/src/main/scala/scalariform/lexer/XmlLexer.scala b/scalariform/src/main/scala/scalariform/lexer/XmlLexer.scala index 8a63447d..644df669 100644 --- a/scalariform/src/main/scala/scalariform/lexer/XmlLexer.scala +++ b/scalariform/src/main/scala/scalariform/lexer/XmlLexer.scala @@ -1,9 +1,9 @@ package scalariform.lexer +import scala.PartialFunction.cond import scala.annotation._ import scalariform.lexer.CharConstants.SU import scalariform.lexer.Tokens._ -import scala.PartialFunction.cond /** * Lexer implementation for XML literals and patterns @@ -22,9 +22,9 @@ trait XmlLexer { self: ScalaLexer ⇒ } } - protected def fetchXmlToken() { + protected def fetchXmlToken(): Unit = { (ch: @switch) match { - case '<' ⇒ { + case '<' ⇒ if (ch(1) == '/') { nextChar() nextChar() @@ -61,9 +61,8 @@ trait XmlLexer { self: ScalaLexer ⇒ xmlMode.isTagMode = true xmlMode.tagState = InStartTag } - // xmlMode.nestTag() - } - case '/' ⇒ { + // xmlMode.nestTag() + case '/' ⇒ if (tagMode) { if (ch(1) == '>') { nextChar() @@ -77,7 +76,6 @@ trait XmlLexer { self: ScalaLexer ⇒ getXmlCharData() } else getXmlCharData() - } case '>' ⇒ if (tagMode) { nextChar() @@ -85,11 +83,10 @@ trait XmlLexer { self: ScalaLexer ⇒ xmlMode.isTagMode = false xmlMode.tagState match { case InStartTag ⇒ xmlMode.nestTag() - case InEndTag ⇒ { + case InEndTag ⇒ val nestingLevel = xmlMode.unnestTag() if (nestingLevel == 0 && !moreXmlToCome) popMode() - } case Normal ⇒ throw new AssertionError("shouldn't reach here") } } else @@ -116,7 +113,7 @@ trait XmlLexer { self: ScalaLexer ⇒ } case '{' ⇒ if (ch(1) != '{') - switchToScalaModeAndFetchToken + switchToScalaModeAndFetchToken() else getXmlCharData() // TODO: tagMode? case SU ⇒ token(EOF) @@ -134,7 +131,7 @@ trait XmlLexer { self: ScalaLexer ⇒ } } - private def getXmlCDATA() { + private def getXmlCDATA(): Unit = { munch(" Flattenable): Flattenable = new Flattenable { val tokens: List[Token] = list flatMap { _.tokens } } + protected implicit def optionToFlattenable[T](option: Option[T])(implicit flat: T => Flattenable): Flattenable = new Flattenable { val tokens: List[Token] = option.toList flatMap { _.tokens } } + protected implicit def pairToFlattenable[T1, T2](pair: (T1, T2))(implicit flat1: T1 => Flattenable, flat2: T2 => Flattenable): Flattenable = new Flattenable { val tokens: List[Token] = pair._1.tokens ::: pair._2.tokens } + protected implicit def tripleToFlattenable[T1, T2, T3](triple: (T1, T2, T3))(implicit flat1: T1 => Flattenable, flat2: T2 => Flattenable, flat3: T3 => Flattenable): Flattenable = new Flattenable { val tokens: List[Token] = triple._1.tokens ++ triple._2.tokens ++ triple._3.tokens } + protected implicit def eitherToFlattenable[T1, T2](either: T1 Either T2)(implicit flat1: T1 => Flattenable, flat2: T2 => Flattenable): Flattenable = new Flattenable { + val tokens: List[Token] = either match { case Left(f) ⇒ f.tokens case Right(f) ⇒ f.tokens } @@ -40,9 +40,9 @@ sealed trait AstNode extends Product { private def immediateAstNodes(n: Any): List[AstNode] = n match { case a: AstNode ⇒ List(a) - case t: Token ⇒ Nil + case _: Token ⇒ Nil case Some(x) ⇒ immediateAstNodes(x) - case xs @ (_ :: _) ⇒ xs flatMap { immediateAstNodes(_) } + case xs @ (_ :: _) ⇒ xs flatMap { immediateAstNodes _ } case Left(x) ⇒ immediateAstNodes(x) case Right(x) ⇒ immediateAstNodes(x) case (l, r) ⇒ immediateAstNodes(l) ++ immediateAstNodes(r) @@ -64,69 +64,69 @@ sealed trait AstNode extends Product { } -case class GeneralTokens(val toks: List[Token]) extends AstNode with TypeElement with ExprElement { - lazy val tokens = flatten(toks) +case class GeneralTokens(toks: List[Token]) extends AstNode with TypeElement with ExprElement { + lazy val tokens: List[Token] = flatten(toks) } case class Refinement(lbrace: Token, refineStatSeq: StatSeq, rbrace: Token) extends AstNode with TypeElement { - lazy val tokens = flatten(lbrace, refineStatSeq, rbrace) + lazy val tokens: List[Token] = flatten(lbrace, refineStatSeq, rbrace) } case class TypeParam(contents: List[TypeElement]) extends AstNode with TypeElement { - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } case class TypeParamClause(contents: List[TypeElement]) extends AstNode with TypeElement { //require(!contents.isEmpty) - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } case class Annotation(at: Token, annotationType: Type, argumentExprss: List[ArgumentExprs], newlineOption: Option[Token]) extends TypeElement with ExprElement { - lazy val tokens = flatten(at, annotationType, argumentExprss, newlineOption) + lazy val tokens: List[Token] = flatten(at, annotationType, argumentExprss, newlineOption) } case class InfixTypeConstructor(id: Token) extends AstNode with TypeElement { - lazy val tokens = flatten(id) + lazy val tokens: List[Token] = flatten(id) } sealed trait TypeElement extends AstNode case class Type(contents: List[TypeElement]) extends AstNode with TypeElement { //require(!contents.isEmpty) - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } case class VarianceTypeElement(id: Token) extends AstNode with TypeElement { - lazy val tokens = flatten(id) + lazy val tokens: List[Token] = flatten(id) } case class VarargsTypeElement(star: Token) extends AstNode with TypeElement { - lazy val tokens = flatten(star) + lazy val tokens: List[Token] = flatten(star) } case class CallByNameTypeElement(arrow: Token) extends AstNode with TypeElement { - lazy val tokens = flatten(arrow) + lazy val tokens: List[Token] = flatten(arrow) } sealed trait ExprElement extends AstNode case class Expr(contents: List[ExprElement]) extends AstNode with ExprElement with Stat with Enumerator with XmlContents with ImportExpr { - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } case class ParenExpr(lparen: Token, contents: List[ExprElement], rparen: Token) extends ExprElement { - lazy val tokens = flatten(lparen, contents, rparen) + lazy val tokens: List[Token] = flatten(lparen, contents, rparen) } case class PrefixExprElement(id: Token) extends ExprElement { - lazy val tokens = flatten(id) + lazy val tokens: List[Token] = flatten(id) } case class PostfixExpr(first: List[ExprElement], postfixId: Token) extends ExprElement { - lazy val tokens = flatten(first, postfixId) + lazy val tokens: List[Token] = flatten(first, postfixId) } case class InfixExpr(left: List[ExprElement], infixId: Token, newlineOption: Option[Token], right: List[ExprElement]) extends ExprElement { - lazy val tokens = flatten(left, infixId, newlineOption, right) + lazy val tokens: List[Token] = flatten(left, infixId, newlineOption, right) } case class CallExpr( @@ -136,30 +136,30 @@ case class CallExpr( newLineOptsAndArgumentExprss: List[(Option[Token], ArgumentExprs)] = Nil, uscoreOpt: Option[Token] = None ) extends ExprElement { - lazy val tokens = flatten(exprDotOpt, id, typeArgsOpt, newLineOptsAndArgumentExprss, uscoreOpt) + lazy val tokens: List[Token] = flatten(exprDotOpt, id, typeArgsOpt, newLineOptsAndArgumentExprss, uscoreOpt) } case class TypeExprElement(contents: List[TypeElement]) extends AstNode with ExprElement { //require(!contents.isEmpty) - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } trait ArgumentExprs extends ExprElement case class BlockArgumentExprs(contents: List[ExprElement]) extends ArgumentExprs { - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } case class ParenArgumentExprs(lparen: Token, contents: List[ExprElement], rparen: Token) extends ArgumentExprs { - lazy val tokens = flatten(lparen, contents, rparen) + lazy val tokens: List[Token] = flatten(lparen, contents, rparen) } case class Argument(expr: Expr) extends AstNode with ExprElement { - lazy val tokens = flatten(expr) + lazy val tokens: List[Token] = flatten(expr) } case class New(newToken: Token, template: Template) extends ExprElement { - lazy val tokens = flatten(newToken, template) + lazy val tokens: List[Token] = flatten(newToken, template) } case class IfExpr( @@ -170,28 +170,28 @@ case class IfExpr( elseClause: Option[ElseClause] ) extends AstNode with ExprElement { - lazy val tokens = flatten(ifToken, condExpr, newlinesOpt, body, elseClause) + lazy val tokens: List[Token] = flatten(ifToken, condExpr, newlinesOpt, body, elseClause) } case class ElseClause(semiOpt: Option[Token], elseToken: Token, elseBody: Expr) extends AstNode { - lazy val tokens = flatten(semiOpt, elseToken, elseBody) + lazy val tokens: List[Token] = flatten(semiOpt, elseToken, elseBody) } case class BlockExpr(lbrace: Token, caseClausesOrStatSeq: Either[CaseClauses, StatSeq], rbrace: Token) extends AstNode with ExprElement { - lazy val tokens = flatten(lbrace, caseClausesOrStatSeq, rbrace) + lazy val tokens: List[Token] = flatten(lbrace, caseClausesOrStatSeq, rbrace) } case class CondExpr(lparen: Token, condition: Expr, rparen: Token) extends AstNode { - lazy val tokens = flatten(lparen, condition, rparen) + lazy val tokens: List[Token] = flatten(lparen, condition, rparen) } case class WhileExpr(whileToken: Token, condExpr: CondExpr, newlinesOpt: Option[Token], body: Expr) extends AstNode with ExprElement { - lazy val tokens = flatten(whileToken, condExpr, newlinesOpt, body) + lazy val tokens: List[Token] = flatten(whileToken, condExpr, newlinesOpt, body) } case class DoExpr(doToken: Token, body: Expr, statSepOpt: Option[Token], whileToken: Token, condExpr: CondExpr) extends AstNode with ExprElement { - lazy val tokens = flatten(doToken, body, statSepOpt, whileToken, condExpr) + lazy val tokens: List[Token] = flatten(doToken, body, statSepOpt, whileToken, condExpr) } case class ForExpr( @@ -204,14 +204,14 @@ case class ForExpr( body: Expr ) extends AstNode with ExprElement { - lazy val tokens = flatten(forToken, lParenOrBrace, enumerators, rParenOrBrace, newlinesOption, yieldOption, body) + lazy val tokens: List[Token] = flatten(forToken, lParenOrBrace, enumerators, rParenOrBrace, newlinesOption, yieldOption, body) } sealed trait Enumerator extends AstNode case class Enumerators(initialGenerator: Generator, rest: List[(Token, Enumerator)]) extends AstNode { - lazy val tokens = flatten(initialGenerator, rest) + lazy val tokens: List[Token] = flatten(initialGenerator, rest) } case class Generator( @@ -222,56 +222,56 @@ case class Generator( guards: List[Guard] ) extends AstNode with Enumerator { - lazy val tokens = flatten(valOption, pattern, equalsOrArrowToken, expr, guards) + lazy val tokens: List[Token] = flatten(valOption, pattern, equalsOrArrowToken, expr, guards) } case class Guard(ifToken: Token, expr: Expr) extends AstNode with Enumerator { - lazy val tokens = flatten(ifToken, expr) + lazy val tokens: List[Token] = flatten(ifToken, expr) } case class CatchClause(catchToken: Token, catchBlockOrExpr: Either[BlockExpr, Expr]) extends AstNode { - lazy val tokens = flatten(catchToken, catchBlockOrExpr) + lazy val tokens: List[Token] = flatten(catchToken, catchBlockOrExpr) } case class TryExpr(tryToken: Token, body: Expr, catchClauseOption: Option[CatchClause], finallyClauseOption: Option[(Token, Expr)]) extends AstNode with ExprElement { - lazy val tokens = flatten(tryToken, body, catchClauseOption, finallyClauseOption) + lazy val tokens: List[Token] = flatten(tryToken, body, catchClauseOption, finallyClauseOption) } case class FullDefOrDcl(annotations: List[Annotation], modifiers: List[Modifier], defOrDcl: DefOrDcl) extends Stat { - lazy val tokens = flatten(annotations, modifiers, defOrDcl) + lazy val tokens: List[Token] = flatten(annotations, modifiers, defOrDcl) } case class MatchExpr(left: List[ExprElement], matchToken: Token, block: BlockExpr) extends ExprElement { - lazy val tokens = flatten(left, matchToken, block) + lazy val tokens: List[Token] = flatten(left, matchToken, block) } case class AscriptionExpr(left: List[ExprElement], colon: Token, right: List[ExprElement]) extends ExprElement { - lazy val tokens = flatten(left, colon, right) + lazy val tokens: List[Token] = flatten(left, colon, right) } case class EqualsExpr(lhs: List[ExprElement], equals: Token, rhs: Expr) extends ExprElement { - lazy val tokens = flatten(lhs, equals, rhs) + lazy val tokens: List[Token] = flatten(lhs, equals, rhs) } case class CaseClause(casePattern: CasePattern, statSeq: StatSeq) extends AstNode { - lazy val tokens = flatten(casePattern, statSeq) + lazy val tokens: List[Token] = flatten(casePattern, statSeq) } case class CasePattern(caseToken: Token, pattern: Expr, guardOption: Option[Guard], arrow: Token) extends AstNode { - lazy val tokens = flatten(caseToken, pattern, guardOption, arrow) + lazy val tokens: List[Token] = flatten(caseToken, pattern, guardOption, arrow) } case class CaseClauses(caseClauses: List[CaseClause]) extends AstNode { //require(!caseClauses.isEmpty) - lazy val tokens = flatten(caseClauses) + lazy val tokens: List[Token] = flatten(caseClauses) } sealed trait DefOrDcl extends AstNode case class TypeDefOrDcl(contents: List[TypeElement]) extends DefOrDcl { //require(!contents.isEmpty) - lazy val tokens = flatten(contents) + lazy val tokens: List[Token] = flatten(contents) } case class PatDefOrDcl( @@ -282,30 +282,30 @@ case class PatDefOrDcl( equalsClauseOption: Option[(Token, Expr)] ) extends DefOrDcl { - lazy val tokens = flatten(valOrVarToken, pattern, otherPatterns, typedOpt, equalsClauseOption) + lazy val tokens: List[Token] = flatten(valOrVarToken, pattern, otherPatterns, typedOpt, equalsClauseOption) } sealed trait FunBody extends AstNode case class ProcFunBody(newlineOpt: Option[Token], bodyBlock: BlockExpr) extends FunBody { - lazy val tokens = flatten(newlineOpt, bodyBlock) + lazy val tokens: List[Token] = flatten(newlineOpt, bodyBlock) } case class ExprFunBody(equals: Token, macroOpt: Option[Token], body: Expr) extends FunBody { - lazy val tokens = flatten(equals, macroOpt, body) + lazy val tokens: List[Token] = flatten(equals, macroOpt, body) } case class ParamClauses(newlineOpt: Option[Token], paramClausesAndNewlines: List[(ParamClause, Option[Token])]) extends AstNode { - lazy val tokens = flatten(newlineOpt, paramClausesAndNewlines) + lazy val tokens: List[Token] = flatten(newlineOpt, paramClausesAndNewlines) } case class ParamClause(lparen: Token, implicitOption: Option[Token], firstParamOption: Option[Param], otherParams: List[(Token, Param)], rparen: Token) extends AstNode { - lazy val tokens = flatten(lparen, implicitOption, firstParamOption, otherParams, rparen) + lazy val tokens: List[Token] = flatten(lparen, implicitOption, firstParamOption, otherParams, rparen) } case class Param(annotations: List[Annotation], modifiers: List[Modifier], valOrVarOpt: Option[Token], id: Token, paramTypeOpt: Option[(Token, Type)], defaultValueOpt: Option[(Token, Expr)]) extends AstNode { - lazy val tokens = flatten(annotations, modifiers, valOrVarOpt, id, paramTypeOpt, defaultValueOpt) + lazy val tokens: List[Token] = flatten(annotations, modifiers, valOrVarOpt, id, paramTypeOpt, defaultValueOpt) } case class FunDefOrDcl( @@ -318,7 +318,7 @@ case class FunDefOrDcl( localDef: Boolean ) extends DefOrDcl { - lazy val tokens = flatten(defToken, nameToken, typeParamClauseOpt, paramClauses, returnTypeOpt, funBodyOpt) + lazy val tokens: List[Token] = flatten(defToken, nameToken, typeParamClauseOpt, paramClauses, returnTypeOpt, funBodyOpt) } @@ -333,7 +333,7 @@ case class TmplDef( templateBodyOption: Option[TemplateBody] ) extends DefOrDcl { //require(markerTokens.size <= 2) - lazy val tokens = flatten(markerTokens, name, typeParamClauseOpt, annotations, accessModifierOpt, paramClausesOpt, templateInheritanceSectionOpt, templateBodyOption) + lazy val tokens: List[Token] = flatten(markerTokens, name, typeParamClauseOpt, annotations, accessModifierOpt, paramClausesOpt, templateInheritanceSectionOpt, templateBodyOption) } @@ -343,20 +343,20 @@ case class TemplateInheritanceSection( templateParentsOpt: Option[TemplateParents] ) extends AstNode { - lazy val tokens = flatten(extendsOrSubtype, earlyDefsOpt, templateParentsOpt) + lazy val tokens: List[Token] = flatten(extendsOrSubtype, earlyDefsOpt, templateParentsOpt) } case class EarlyDefs(earlyBody: TemplateBody, withOpt: Option[Token]) extends AstNode { - lazy val tokens = flatten(earlyBody, withOpt) + lazy val tokens: List[Token] = flatten(earlyBody, withOpt) } case class Template(earlyDefsOpt: Option[EarlyDefs], templateParentsOpt: Option[TemplateParents], templateBodyOpt: Option[TemplateBody]) extends ExprElement { - lazy val tokens = flatten(earlyDefsOpt, templateParentsOpt, templateBodyOpt) + lazy val tokens: List[Token] = flatten(earlyDefsOpt, templateParentsOpt, templateBodyOpt) } case class TemplateBody(newlineOpt: Option[Token], lbrace: Token, statSeq: StatSeq, rbrace: Token) extends AstNode { - lazy val tokens = flatten(newlineOpt, lbrace, statSeq, rbrace) + lazy val tokens: List[Token] = flatten(newlineOpt, lbrace, statSeq, rbrace) } sealed trait Stat extends AstNode @@ -367,97 +367,97 @@ case class StatSeq( otherStats: List[(Token, Option[Stat])] ) extends AstNode with ExprElement { - lazy val tokens = flatten(selfReferenceOpt, firstStatOpt, otherStats) + lazy val tokens: List[Token] = flatten(selfReferenceOpt, firstStatOpt, otherStats) } case class TemplateParents(typeAndArgs: (Type, List[ArgumentExprs]), withTypesAndArgs: List[(Token, Type, List[ArgumentExprs])]) extends AstNode { - lazy val tokens = flatten(typeAndArgs, withTypesAndArgs) + lazy val tokens: List[Token] = flatten(typeAndArgs, withTypesAndArgs) } case class ImportClause(importToken: Token, importExpr: ImportExpr, otherImportExprs: List[(Token, ImportExpr)]) extends AstNode with Stat { - lazy val tokens = flatten(importToken, importExpr, otherImportExprs) + lazy val tokens: List[Token] = flatten(importToken, importExpr, otherImportExprs) } sealed trait ImportExpr extends AstNode case class BlockImportExpr(prefixExpr: Expr, importSelectors: ImportSelectors) extends ImportExpr { - lazy val tokens = flatten(prefixExpr, importSelectors) + lazy val tokens: List[Token] = flatten(prefixExpr, importSelectors) } case class ImportSelectors(lbrace: Token, firstImportSelector: Expr, otherImportSelectors: List[(Token, Expr)], rbrace: Token) extends AstNode { - lazy val tokens = flatten(lbrace, firstImportSelector, otherImportSelectors, rbrace) + lazy val tokens: List[Token] = flatten(lbrace, firstImportSelector, otherImportSelectors, rbrace) } case class PackageBlock(packageToken: Token, name: CallExpr, newlineOpt: Option[Token], lbrace: Token, topStats: StatSeq, rbrace: Token) extends Stat { - lazy val tokens = flatten(packageToken, name, newlineOpt, lbrace, topStats, rbrace) + lazy val tokens: List[Token] = flatten(packageToken, name, newlineOpt, lbrace, topStats, rbrace) } case class PackageStat(packageToken: Token, name: CallExpr) extends Stat { - lazy val tokens = flatten(packageToken, name) + lazy val tokens: List[Token] = flatten(packageToken, name) } sealed trait Modifier extends AstNode case class SimpleModifier(token: Token) extends Modifier { - lazy val tokens = flatten(token) + lazy val tokens: List[Token] = flatten(token) } case class AccessModifier(privateOrProtected: Token, accessQualifierOpt: Option[AccessQualifier]) extends Modifier { - lazy val tokens = flatten(privateOrProtected, accessQualifierOpt) + lazy val tokens: List[Token] = flatten(privateOrProtected, accessQualifierOpt) } case class AccessQualifier(lbracket: Token, thisOrId: Token, rbracket: Token) extends AstNode { - lazy val tokens = flatten(lbracket, thisOrId, rbracket) + lazy val tokens: List[Token] = flatten(lbracket, thisOrId, rbracket) } case class CompilationUnit(topStats: StatSeq, eofToken: Token) extends AstNode { - lazy val tokens = flatten(topStats, eofToken) + lazy val tokens: List[Token] = flatten(topStats, eofToken) } case class AnonymousFunctionStart(parameters: List[ExprElement], arrow: Token) extends ExprElement { - lazy val tokens = flatten(parameters, arrow) + lazy val tokens: List[Token] = flatten(parameters, arrow) } case class AnonymousFunction(parameters: List[ExprElement], arrow: Token, body: StatSeq) extends ExprElement { - lazy val tokens = flatten(parameters, arrow, body) + lazy val tokens: List[Token] = flatten(parameters, arrow, body) } case class StringInterpolation(interpolationId: Token, stringPartsAndScala: List[(Token, Expr)], terminalString: Token) extends ExprElement { - lazy val tokens = flatten(interpolationId, stringPartsAndScala, terminalString) + lazy val tokens: List[Token] = flatten(interpolationId, stringPartsAndScala, terminalString) } sealed trait XmlExprElement extends ExprElement case class XmlStartTag(startOpen: Token, name: Token, attributes: List[(Option[Token], XmlAttribute)], whitespaceOption: Option[Token], tagClose: Token) extends XmlExprElement { - lazy val tokens = flatten(startOpen, name, attributes, whitespaceOption, tagClose) + lazy val tokens: List[Token] = flatten(startOpen, name, attributes, whitespaceOption, tagClose) } case class XmlAttribute(name: Token, whitespaceOption: Option[Token], equals: Token, whitespaceOption2: Option[Token], valueOrEmbeddedScala: Either[Token, Expr]) extends XmlExprElement { - lazy val tokens = flatten(name, whitespaceOption, equals, whitespaceOption2, valueOrEmbeddedScala) + lazy val tokens: List[Token] = flatten(name, whitespaceOption, equals, whitespaceOption2, valueOrEmbeddedScala) } case class XmlEmptyElement(startOpen: Token, name: Token, attributes: List[(Option[Token], XmlAttribute)], whitespaceOption: Option[Token], emptyClose: Token) extends XmlElement { - lazy val tokens = flatten(startOpen, name, attributes, whitespaceOption, emptyClose) + lazy val tokens: List[Token] = flatten(startOpen, name, attributes, whitespaceOption, emptyClose) } case class XmlEndTag(endOpen: Token, name: Token, whitespaceOption: Option[Token], tagClose: Token) extends XmlExprElement { - lazy val tokens = flatten(endOpen, name, whitespaceOption, tagClose) + lazy val tokens: List[Token] = flatten(endOpen, name, whitespaceOption, tagClose) } sealed trait XmlElement extends XmlContents case class XmlNonEmptyElement(startTag: XmlStartTag, contents: List[XmlContents], endTag: XmlEndTag) extends XmlElement { - lazy val tokens = flatten(startTag, contents, endTag) + lazy val tokens: List[Token] = flatten(startTag, contents, endTag) } sealed trait XmlContents extends XmlExprElement -case class XmlPCDATA(token: Token) extends XmlContents { lazy val tokens = flatten(token) } -case class XmlCDATA(token: Token) extends XmlContents { lazy val tokens = flatten(token) } -case class XmlComment(token: Token) extends XmlContents { lazy val tokens = flatten(token) } -case class XmlUnparsed(token: Token) extends XmlContents { lazy val tokens = flatten(token) } -case class XmlProcessingInstruction(token: Token) extends XmlContents { lazy val tokens = flatten(token) } +case class XmlPCDATA(token: Token) extends XmlContents { lazy val tokens: List[Token] = flatten(token) } +case class XmlCDATA(token: Token) extends XmlContents { lazy val tokens: List[Token] = flatten(token) } +case class XmlComment(token: Token) extends XmlContents { lazy val tokens: List[Token] = flatten(token) } +case class XmlUnparsed(token: Token) extends XmlContents { lazy val tokens: List[Token] = flatten(token) } +case class XmlProcessingInstruction(token: Token) extends XmlContents { lazy val tokens: List[Token] = flatten(token) } case class XmlExpr(first: XmlContents, otherElements: List[XmlContents]) extends ExprElement { - lazy val tokens = flatten(first, otherElements) + lazy val tokens: List[Token] = flatten(first, otherElements) } diff --git a/scalariform/src/main/scala/scalariform/parser/InferredSemicolonScalaParser.scala b/scalariform/src/main/scala/scalariform/parser/InferredSemicolonScalaParser.scala index 6059f50b..f85f394e 100644 --- a/scalariform/src/main/scala/scalariform/parser/InferredSemicolonScalaParser.scala +++ b/scalariform/src/main/scala/scalariform/parser/InferredSemicolonScalaParser.scala @@ -1,14 +1,14 @@ package scalariform.parser +import scala.PartialFunction._ import scalariform.lexer.Tokens._ import scalariform.lexer._ -import PartialFunction._ object InferredSemicolonScalaParser { def findSemicolons(tokens: Array[Token]): Set[Token] = { val parser = new InferredSemicolonScalaParser(tokens) - parser.safeParse(parser.compilationUnitOrScript) + parser.safeParse(parser.compilationUnitOrScript()) parser.inferredSemicolons } @@ -21,9 +21,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { private val forgiving = true def safeParse[T](production: ⇒ T): Option[T] = - try Some(production) catch { case e: ScalaParserException ⇒ None } + try Some(production) catch { case _: ScalaParserException ⇒ None } - def compilationUnitOrScript() { + def compilationUnitOrScript(): Unit = { val originalPos = pos try { compilationUnit() @@ -33,19 +33,19 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { if (logging) println("Rewinding to try alternative: " + currentToken) try { scriptBody() - } catch { case e2: ScalaParserException ⇒ throw e } + } catch { case _: ScalaParserException ⇒ throw e } } } require(tokens.nonEmpty) // at least EOF - private def inParens[T](body: ⇒ T) { + private def inParens[T](body: ⇒ T): Unit = { accept(LPAREN) body accept(RPAREN) } - private def inBraces[T](body: ⇒ T) { + private def inBraces[T](body: ⇒ T): Unit = { accept(LBRACE) body accept(RBRACE) @@ -57,20 +57,20 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { else body - private def inBrackets[T](body: ⇒ T) { + private def inBrackets[T](body: ⇒ T): Unit = { accept(LBRACKET) body accept(RBRACKET) } - private def makeParens[T](body: ⇒ T) = inParens { if (RPAREN) None else Some(body) } + private def makeParens[T](body: ⇒ T): Unit = inParens { if (RPAREN) None else Some(body) } - private def scriptBody() { + private def scriptBody(): Unit = { templateStats() accept(EOF) } - private def templateStats() = { + private def templateStats(): Unit = { templateStatSeq() } @@ -90,7 +90,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { case _ ⇒ accept(SEMI) } - private def acceptStatSepOpt() = if (!isStatSeqEnd) acceptStatSep + private def acceptStatSepOpt() = if (!isStatSeqEnd) acceptStatSep() private def isModifier = currentTokenType match { case ABSTRACT | FINAL | SEALED | PRIVATE | @@ -166,7 +166,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { private def isStatSep: Boolean = isStatSep(currentTokenType) - private def tokenSeparated[T](separator: TokenType, sepFirst: Boolean, part: ⇒ T) { + private def tokenSeparated[T](separator: TokenType, sepFirst: Boolean, part: ⇒ T): Unit = { if (sepFirst) () else part while (separator) { nextToken() @@ -174,18 +174,18 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def commaSeparated[T](part: ⇒ T) = - tokenSeparated(COMMA, false, part) + private def commaSeparated[T](part: ⇒ T): Unit = + tokenSeparated(COMMA, sepFirst = false, part = part) - private def caseSeparated[T](part: ⇒ T) = tokenSeparated(CASE, true, part) - private def readAnnots[T](part: ⇒ T) = tokenSeparated(AT, true, part) + private def caseSeparated[T](part: ⇒ T): Unit = tokenSeparated(CASE, sepFirst = true, part = part) + private def readAnnots[T](part: ⇒ T): Unit = tokenSeparated(AT, sepFirst = true, part = part) trait PatternContextSensitive { - def argType() - def functionArgType() + def argType(): Unit + def functionArgType(): Unit - private def tupleInfixType() { + private def tupleInfixType(): Unit = { nextToken() if (RPAREN) { nextToken() @@ -206,9 +206,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def makeExistentialTypeTree() = refinement() + private def makeExistentialTypeTree(): Unit = refinement() - def typ() { + def typ(): Unit = { if (LPAREN) tupleInfixType() else infixType() @@ -223,16 +223,16 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def typeArgs() = { + def typeArgs(): Unit = { inBrackets(types()) } - def annotType() = { + def annotType(): Unit = { simpleType() annotTypeRest() } - def simpleType() = { + def simpleType(): Unit = { currentTokenType match { case LPAREN ⇒ inParens(types()) @@ -250,7 +250,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { ident() } - private def simpleTypeRest() { + private def simpleTypeRest(): Unit = currentTokenType match { case HASH ⇒ typeProjection() @@ -259,11 +259,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { typeArgs() simpleTypeRest() case _ ⇒ - Nil } - } - def compoundType() = { + def compoundType(): Option[Unit] = { if (LBRACE) None else Some(annotType()) compoundTypeRest() } @@ -277,7 +275,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { if (LBRACE) Some(refinement()) else None } - def infixTypeRest() { + def infixTypeRest(): Unit = if (isIdent && !STAR) { val identToken = currentToken InfixTypeConstructor(ident()) @@ -288,19 +286,17 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } else { infixType() } - } else - Nil - } + } - def infixType() = { + def infixType(): Unit = { compoundType() infixTypeRest() } - private def types() = + private def types(): Unit = commaSeparated(argType()) - private def functionTypes() = + private def functionTypes(): Unit = commaSeparated(functionArgType()) } @@ -313,7 +309,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { private def selector() = ident() - private def pathC(thisOK: Boolean, typeOK: Boolean) { + private def pathC(thisOK: Boolean, typeOK: Boolean): Unit = { if (THIS) { nextToken() if (!thisOK || DOT) { @@ -354,9 +350,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def path(thisOK: Boolean, typeOK: Boolean) = pathC(thisOK, typeOK) + private def path(thisOK: Boolean, typeOK: Boolean): Unit = pathC(thisOK, typeOK) - private def selectors(delme: String, typeOK: Boolean) { + private def selectors(delme: String, typeOK: Boolean): Unit = { if (typeOK && TYPE) nextToken() else { @@ -368,13 +364,13 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def mixinQualifierOpt() { - if (LBRACKET) inBrackets(ident) + private def mixinQualifierOpt(): Unit = { + if (LBRACKET) inBrackets(ident()) } - private def stableId() = path(thisOK = false, typeOK = false) + private def stableId(): Unit = path(thisOK = false, typeOK = false) - private def qualId() = { + private def qualId(): Unit = { ident() if (DOT) { nextToken() @@ -395,7 +391,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { else throw new ScalaParserException("illegal literal: " + currentToken) - private def interpolatedString(inPattern: Boolean) { + private def interpolatedString(inPattern: Boolean): Unit = { nextToken() while (STRING_PART) { nextToken() @@ -415,7 +411,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { nextToken() } - private def newLineOpt() { if (NEWLINE) nextToken() } + private def newLineOpt(): Unit = { if (NEWLINE) nextToken() } private def newLinesOpt() = if (NEWLINE || NEWLINES) nextToken() @@ -431,22 +427,22 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { else None - private def typedOpt() = + private def typedOpt(): Unit = if (COLON) { nextToken() typ() } - private def typeOrInfixType(location: Location) = + private def typeOrInfixType(location: Location): Unit = if (location == Local) typ() else startInfixType() - private def annotTypeRest() = + private def annotTypeRest(): Unit = annotations(skipNewLines = false) - private def wildcardType() = { + private def wildcardType(): Unit = { typeBounds() } @@ -461,15 +457,15 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def statement(location: Location) = expr(location) + private def statement(location: Location): Unit = expr(location) - def expr() { expr(Local) } + def expr(): Unit = { expr(Local) } - private def expr(location: Location) { + private def expr(location: Location): Unit = { expr0(location) } - private def expr0(location: Location) { + private def expr0(location: Location): Unit = { currentTokenType match { case IF ⇒ nextToken() @@ -488,7 +484,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { case LBRACE ⇒ inBraces(block()) case LPAREN ⇒ inParens(expr()) - case _ ⇒ expr + case _ ⇒ expr() } if (!CATCH) None @@ -581,7 +577,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def implicitClosure(location: Location) { + private def implicitClosure(location: Location): Unit = { ident() if (COLON) { nextToken() @@ -591,7 +587,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { if (location != InBlock) expr() else block() } - private def postfixExpr() { + private def postfixExpr(): Unit = { prefixExpr() while (isIdent) { ident() @@ -602,7 +598,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def prefixExpr() { + private def prefixExpr(): Unit = { if (isUnaryOp) { val isMinus = MINUS ident() @@ -615,7 +611,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { simpleExpr() } - private def simpleExpr() { + private def simpleExpr(): Unit = { var canApply = true if (isLiteral) literal() else currentTokenType match { @@ -626,7 +622,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { case USCORE ⇒ nextToken() case LPAREN ⇒ - makeParens(commaSeparated(expr)) + makeParens(commaSeparated(expr())) case LBRACE ⇒ canApply = false blockExpr() @@ -640,7 +636,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { simpleExprRest(canApply) } - private def simpleExprRest(canApply: Boolean) { + private def simpleExprRest(canApply: Boolean): Unit = { if (canApply) newLineOptWhenFollowedBy(LBRACE) currentTokenType match { @@ -663,9 +659,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def argumentExprs() { - def argument() = expr() - def args() = commaSeparated(argument()) + private def argumentExprs(): Unit = { + def argument(): Unit = expr() + def args(): Unit = commaSeparated(argument()) currentTokenType match { case LBRACE ⇒ blockExpr() case LPAREN ⇒ @@ -674,21 +670,22 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def multipleArgumentExprs() { - if (!LPAREN) Nil - else { argumentExprs(); multipleArgumentExprs() } - } + private def multipleArgumentExprs(): Unit = + if (LPAREN) { + argumentExprs() + multipleArgumentExprs() + } - private def blockExpr() { + private def blockExpr(): Unit = { inBraces { if (justCase) caseClauses() else block() } } - private def block() { blockStatSeq() } + private def block(): Unit = { blockStatSeq() } - private def caseClauses() { + private def caseClauses(): Unit = { caseSeparated { (pattern(), guard(), caseBlock()) } @@ -697,19 +694,19 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { // accept(CASE) } - private def caseBlock() { + private def caseBlock(): Unit = { accept(ARROW) block() } - private def guard() { + private def guard(): Unit = { if (IF) { nextToken() postfixExpr() } } - private def enumerators() { + private def enumerators(): Unit = { val newStyle = !VAL generator(eqOK = false) while (isStatSep) { @@ -724,7 +721,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def generator(eqOK: Boolean) { + private def generator(eqOK: Boolean): Unit = { if (VAL) nextToken() noSeq.pattern1() if (EQUALS && eqOK) nextToken() else accept(LARROW) @@ -738,9 +735,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { def isXML: Boolean = false - def functionArgType() = argType() + def functionArgType(): Unit = argType() - def argType() { + def argType(): Unit = { currentTokenType match { case USCORE ⇒ nextToken() @@ -752,11 +749,11 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def patterns() { + def patterns(): Unit = { commaSeparated(pattern()) } - def pattern() { // Scalac now uses a loop() method, but this is still OK: + def pattern(): Unit = { // Scalac now uses a loop() method, but this is still OK: pattern1() if (PIPE) while (PIPE) { @@ -765,7 +762,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def pattern1() { + def pattern1(): Unit = { pattern2() if (COLON) { nextToken() @@ -773,7 +770,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def pattern2() { + def pattern2(): Unit = { pattern3() if (AT) { // TODO: Compare Parsers.scala @@ -784,7 +781,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def pattern3() { + def pattern3(): Unit = { val firstToken = currentToken val secondToken = InferredSemicolonScalaParser.this(pos + 1) simplePattern() @@ -809,7 +806,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def simplePattern() { + def simplePattern(): Unit = { currentTokenType match { case VARID | OTHERID | PLUS | MINUS | STAR | PIPE | TILDE | EXCLAMATION | THIS ⇒ val nameIsMinus: Boolean = MINUS // TODO case Ident(name) if name == nme.MINUS => @@ -825,7 +822,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { case CHARACTER_LITERAL | INTEGER_LITERAL | FLOATING_POINT_LITERAL | STRING_LITERAL | SYMBOL_LITERAL | TRUE | FALSE | NULL ⇒ literal(inPattern = true) case LPAREN ⇒ - makeParens(noSeq.patterns) + makeParens(noSeq.patterns()) case XML_START_OPEN | XML_COMMENT | XML_CDATA | XML_UNPARSED | XML_PROCESSING_INSTRUCTION ⇒ xmlLiteralPattern() case _ ⇒ @@ -836,8 +833,8 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } object outPattern extends PatternContextSensitive { - def argType() = typ() - def functionArgType() = paramType() + def argType(): Unit = typ() + def functionArgType(): Unit = paramType() } object seqOK extends SeqContextSensitive { @@ -854,18 +851,18 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { override val isXML = true } - def typ() = outPattern.typ() - def startInfixType() = outPattern.infixType() - def startAnnotType() = outPattern.annotType() - def exprTypeArgs() = outPattern.typeArgs() - def exprSimpleType() = outPattern.simpleType() + def typ(): Unit = outPattern.typ() + def startInfixType(): Unit = outPattern.infixType() + def startAnnotType(): Unit = outPattern.annotType() + def exprTypeArgs(): Unit = outPattern.typeArgs() + def exprSimpleType(): Unit = outPattern.simpleType() - def pattern() = noSeq.pattern() - def patterns() = noSeq.patterns() - def seqPatterns() = seqOK.patterns() - def xmlSeqPatterns() = xmlSeqOK.patterns() + def pattern(): Unit = noSeq.pattern() + def patterns(): Unit = noSeq.patterns() + def seqPatterns(): Unit = seqOK.patterns() + def xmlSeqPatterns(): Unit = xmlSeqOK.patterns() - private def argumentPatterns() = { + private def argumentPatterns(): Unit = { inParens { if (RPAREN) Nil else seqPatterns() } } @@ -889,8 +886,8 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def modifiers() { - def loop() { + private def modifiers(): Unit = { + def loop(): Unit = { currentTokenType match { case PRIVATE | PROTECTED ⇒ nextToken() @@ -908,35 +905,34 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { loop() } - private def localModifiers() { + private def localModifiers(): Unit = if (isLocalModifier) { nextToken() localModifiers() - } else Nil - } + } - private def annotations(skipNewLines: Boolean) { + private def annotations(skipNewLines: Boolean): Unit = { readAnnots { annotationExpr() if (skipNewLines) newLineOpt() else None } } - private def constructorAnnotations() = + private def constructorAnnotations(): Unit = readAnnots { exprSimpleType() argumentExprs() } - private def annotationExpr() { + private def annotationExpr(): Unit = { exprSimpleType() if (LPAREN) multipleArgumentExprs() } - private def paramClauses() { + private def paramClauses(): Unit = { var implicitmod = false - def param() { + def param(): Unit = { annotations(skipNewLines = false) val ownerIsTypeName = true // TODO: if (owner.isTypeName) if (ownerIsTypeName) { @@ -957,7 +953,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } // Differs from nsc in that we've pulled in lparen/rparen - def paramClause() { + def paramClause(): Unit = { accept(LPAREN) if (RPAREN) { accept(RPAREN) @@ -991,8 +987,8 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def typeParamClauseOpt(allowVariance: Boolean) { - def typeParam() { + private def typeParamClauseOpt(allowVariance: Boolean): Unit = { + def typeParam(): Unit = { if (allowVariance && isIdent) { // TODO: condition if (PLUS) nextToken() @@ -1018,25 +1014,25 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def typeBounds() { + private def typeBounds(): Unit = { bound(SUPERTYPE) bound(SUBTYPE) } - private def bound(tokenType: TokenType) { + private def bound(tokenType: TokenType): Unit = { if (tokenType) { nextToken() typ() } } - private def importClause() { + private def importClause(): Unit = { accept(IMPORT) commaSeparated(importExpr()) } - private def importExpr() { - def thisDotted() { + private def importExpr(): Unit = { + def thisDotted(): Unit = { nextToken() accept(DOT) selector() @@ -1050,7 +1046,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { accept(DOT) if (THIS) thisDotted() } - def loop() { + def loop(): Unit = { currentTokenType match { case USCORE ⇒ nextToken() @@ -1067,7 +1063,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { loop() } - private def importSelectors() { + private def importSelectors(): Unit = { inBraces(commaSeparated(importSelector())) } @@ -1075,7 +1071,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { if (USCORE) nextToken() else ident() - private def importSelector() { + private def importSelector(): Unit = { wildcardOrIdent() currentTokenType match { case ARROW ⇒ @@ -1085,7 +1081,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def defOrDcl(localDef: Boolean = false) = currentTokenType match { + private def defOrDcl(localDef: Boolean = false): Unit = currentTokenType match { case VAL ⇒ patDefOrDcl() case VAR ⇒ patDefOrDcl() case DEF ⇒ funDefOrDcl(localDef) @@ -1093,13 +1089,13 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { case _ ⇒ tmplDef() } - def nonLocalDefOrDcl() { + def nonLocalDefOrDcl(): Unit = { annotations(skipNewLines = true) modifiers() defOrDcl() } - private def patDefOrDcl() { + private def patDefOrDcl(): Unit = { nextToken() commaSeparated(noSeq.pattern2()) typedOpt() @@ -1114,7 +1110,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def funDefOrDcl(localDef: Boolean) { + private def funDefOrDcl(localDef: Boolean): Unit = { accept(DEF) if (THIS) { nextToken() @@ -1133,7 +1129,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def funDefRest() { + private def funDefRest(): Unit = { typeParamClauseOpt(allowVariance = false) paramClauses() newLineOptWhenFollowedBy(LBRACE) @@ -1156,14 +1152,14 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def constrExpr() { + private def constrExpr(): Unit = { if (LBRACE) constrBlock() else selfInvocation() } - private def selfInvocation() { + private def selfInvocation(): Unit = { accept(THIS) newLineOptWhenFollowedBy(LBRACE) argumentExprs() @@ -1174,7 +1170,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def constrBlock() { + private def constrBlock(): Unit = { accept(LBRACE) selfInvocation() if (isStatSep) { @@ -1184,7 +1180,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { accept(RBRACE) } - private def typeDefOrDcl() { + private def typeDefOrDcl(): Unit = { accept(TYPE) newLinesOpt() ident() @@ -1200,13 +1196,13 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def topLevelTmplDef() { + private def topLevelTmplDef(): Unit = { annotations(skipNewLines = true) modifiers() tmplDef() } - private def tmplDef() { + private def tmplDef(): Unit = { currentTokenType match { case TRAIT ⇒ classDef() case CLASS ⇒ classDef() @@ -1217,7 +1213,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def classDef() { + private def classDef(): Unit = { if (CASE) nextToken() // We use two tokens whereas nsc uses CASEOBJECT val isTrait: Boolean = TRAIT @@ -1234,7 +1230,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { templateOpt(isTrait) } - private def objectDef() { + private def objectDef(): Unit = { if (CASE) nextToken() // We use two tokens whereas nsc uses CASEOBJECT accept(OBJECT) @@ -1242,8 +1238,8 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { templateOpt(isTrait = false) } - private def templateParents() { - def readAppliedParent() { + private def templateParents(): Unit = { + def readAppliedParent(): Unit = { startAnnotType() if (LPAREN) multipleArgumentExprs() @@ -1255,7 +1251,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def template() { + private def template(): Unit = { newLineOptWhenFollowedBy(LBRACE) if (LBRACE) { templateBody() @@ -1270,7 +1266,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def templateOpt(isTrait: Boolean) { + private def templateOpt(isTrait: Boolean): Unit = { if (EXTENDS || SUBTYPE && isTrait) { nextToken() template() @@ -1280,11 +1276,11 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def templateBody() { + private def templateBody(): Unit = { inBraces(templateStatSeq()) } - private def templateBodyOpt() { + private def templateBodyOpt(): Unit = { newLineOptWhenFollowedBy(LBRACE) if (LBRACE) templateBody() @@ -1294,16 +1290,16 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { None } - private def refinement() { + private def refinement(): Unit = { inBraces(refineStatSeq()) } - private def packaging() { + private def packaging(): Unit = { pkgQualId() inBraces(topStatSeq()) } - private def topStatSeq() { + private def topStatSeq(): Unit = { while (!isStatSeqEnd) { currentTokenType match { case PACKAGE ⇒ @@ -1327,7 +1323,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def templateStatSeq() { + private def templateStatSeq(): Unit = { if (isExprIntro) { expr(InTemplate) @@ -1354,7 +1350,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def refineStatSeq() { + private def refineStatSeq(): Unit = { while (!isStatSeqEnd) { if (isDclIntro) defOrDcl() @@ -1366,7 +1362,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def localDef() { + private def localDef(): Unit = { annotations(skipNewLines = true) localModifiers() // val modifierCondition = true // TODO: !!!! @@ -1374,7 +1370,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { or(defOrDcl(localDef = true), tmplDef()) } - private def blockStatSeq() { + private def blockStatSeq(): Unit = { while (!isStatSeqEnd && !justCase) { if (IMPORT) { importClause() @@ -1400,8 +1396,8 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - def compilationUnit() { - def topstats() { + def compilationUnit(): Unit = { + def topstats(): Unit = { while (SEMI) nextToken() @@ -1434,7 +1430,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { accept(EOF) } - private def xmlStartTag(isPattern: Boolean) { + private def xmlStartTag(isPattern: Boolean): Unit = { accept(XML_START_OPEN) accept(XML_NAME) while (!XML_TAG_CLOSE) { @@ -1451,7 +1447,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { accept(XML_TAG_CLOSE) } - private def xmlAttribute(isPattern: Boolean) { + private def xmlAttribute(isPattern: Boolean): Unit = { accept(XML_NAME) nextTokenIf(XML_WHITESPACE) accept(XML_ATTR_EQ) @@ -1466,7 +1462,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def xmlEmptyElement(isPattern: Boolean) { + private def xmlEmptyElement(isPattern: Boolean): Unit = { accept(XML_START_OPEN) accept(XML_NAME) while (!XML_EMPTY_CLOSE) { @@ -1483,7 +1479,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { accept(XML_EMPTY_CLOSE) } - private def xmlEmbeddedScala(isPattern: Boolean) { + private def xmlEmbeddedScala(isPattern: Boolean): Unit = { if (isPattern) { accept(LBRACE) xmlSeqPatterns() @@ -1492,14 +1488,14 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { blockExpr() } - private def xmlEndTag() { + private def xmlEndTag(): Unit = { accept(XML_END_OPEN) accept(XML_NAME) nextTokenIf(XML_WHITESPACE) accept(XML_TAG_CLOSE) } - private def xmlNonEmptyElement(isPattern: Boolean) { + private def xmlNonEmptyElement(isPattern: Boolean): Unit = { xmlStartTag(isPattern) while (!XML_END_OPEN) { currentTokenType match { @@ -1516,23 +1512,11 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { xmlEndTag() } - private def xmlElement(isPattern: Boolean) { + private def xmlElement(isPattern: Boolean): Unit = { or(xmlNonEmptyElement(isPattern), xmlEmptyElement(isPattern)) } - private def xml(isPattern: Boolean) { - def xmlContent() { - currentTokenType match { - case XML_START_OPEN ⇒ xmlElement(isPattern) - case XML_PCDATA ⇒ XmlPCDATA(nextToken()) - case XML_COMMENT ⇒ XmlComment(nextToken()) - case XML_CDATA ⇒ XmlCDATA(nextToken()) - case XML_UNPARSED ⇒ XmlUnparsed(nextToken()) - case XML_PROCESSING_INSTRUCTION ⇒ XmlProcessingInstruction(nextToken()) - case _ ⇒ throw new ScalaParserException("Expected XML: " + currentToken) - } - xmlContent() - } + private def xml(isPattern: Boolean): Unit = { while (XML_START_OPEN || XML_PCDATA) { if (XML_START_OPEN) xmlElement(isPattern) @@ -1541,9 +1525,9 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { } } - private def xmlLiteral() = xml(isPattern = false) + private def xmlLiteral(): Unit = xml(isPattern = false) - private def xmlLiteralPattern() = xml(isPattern = true) + private def xmlLiteralPattern(): Unit = xml(isPattern = true) private var pos = 0 @@ -1585,7 +1569,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { private def isVariableName(name: String): Boolean = { val first = name(0) - ((first.isLower && first.isLetter) || first == '_') + (first.isLower && first.isLetter) || first == '_' } private def optional[T](p: ⇒ T): Option[T] = @@ -1596,7 +1580,7 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) { try { p1 } catch { - case e: ScalaParserException ⇒ + case _: ScalaParserException ⇒ pos = originalPos if (logging) println("Rewinding to try alternative: " + currentToken) p2 diff --git a/scalariform/src/main/scala/scalariform/parser/ScalaParser.scala b/scalariform/src/main/scala/scalariform/parser/ScalaParser.scala index 50b37118..83c3ffe5 100644 --- a/scalariform/src/main/scala/scalariform/parser/ScalaParser.scala +++ b/scalariform/src/main/scala/scalariform/parser/ScalaParser.scala @@ -1,10 +1,10 @@ package scalariform.parser +import scala.PartialFunction._ +import scala.collection.mutable.ListBuffer +import scalariform.ScalaVersions import scalariform.lexer.Tokens._ import scalariform.lexer._ -import scalariform.ScalaVersions -import scala.collection.mutable.ListBuffer -import scala.PartialFunction._ class ScalaParser(tokens: Array[Token]) { @@ -15,7 +15,7 @@ class ScalaParser(tokens: Array[Token]) { import ScalaParser._ def safeParse[T](production: ⇒ T): Option[T] = - try Some(production) catch { case e: ScalaParserException ⇒ None } + try Some(production) catch { case _: ScalaParserException ⇒ None } def compilationUnitOrScript(): CompilationUnit = { val originalPos = pos @@ -27,7 +27,7 @@ class ScalaParser(tokens: Array[Token]) { if (logging) println("Rewinding to try alternative: " + currentToken) try { scriptBody() - } catch { case e2: ScalaParserException ⇒ throw e } + } catch { case _: ScalaParserException ⇒ throw e } } } @@ -80,7 +80,7 @@ class ScalaParser(tokens: Array[Token]) { throw new ScalaParserException("Expected token " + tokenType + " but got " + currentToken) private def acceptStatSep(): Token = currentTokenType match { - case NEWLINE | NEWLINES ⇒ nextToken + case NEWLINE | NEWLINES ⇒ nextToken() case _ ⇒ accept(SEMI) } @@ -172,10 +172,10 @@ class ScalaParser(tokens: Array[Token]) { } private def commaSeparated[T](part: ⇒ T) = - tokenSeparated(COMMA, false, part) match { case (firstOpt, rest) ⇒ (firstOpt.get, rest) } + tokenSeparated(COMMA, sepFirst = false, part = part) match { case (firstOpt, rest) ⇒ (firstOpt.get, rest) } - private def caseSeparated[T](part: ⇒ T) = tokenSeparated(CASE, true, part)._2 - private def readAnnots[T](part: ⇒ T) = tokenSeparated(AT, true, part)._2 + private def caseSeparated[T](part: ⇒ T) = tokenSeparated(CASE, sepFirst = true, part = part)._2 + private def readAnnots[T](part: ⇒ T) = tokenSeparated(AT, sepFirst = true, part = part)._2 trait PatternContextSensitive { @@ -402,7 +402,7 @@ class ScalaParser(tokens: Array[Token]) { } private def mixinQualifierOpt(): Option[TypeExprElement] = - if (LBRACKET) Some(TypeExprElement(typeElementFlatten3(inBrackets(ident)))) else None + if (LBRACKET) Some(TypeExprElement(typeElementFlatten3(inBrackets(ident())))) else None private def stableId(): List[Token] = path(thisOK = false, typeOK = false) @@ -536,7 +536,7 @@ class ScalaParser(tokens: Array[Token]) { val (lbrace, block_, rbrace) = inBraces(block()) makeExpr(BlockExpr(lbrace, Right(block_), rbrace)) case LPAREN ⇒ makeExpr(inParens(expr())) - case _ ⇒ expr + case _ ⇒ expr() } val catchClauseOption: Option[CatchClause] = if (!CATCH) @@ -702,9 +702,10 @@ class ScalaParser(tokens: Array[Token]) { private def isRightAssociative(token: Token) = token.text.endsWith(":") private object NestedInfixExpr { - def unapply(infixExpr: InfixExpr) = condOpt(infixExpr) { - case InfixExpr(List(InfixExpr(x, op1, newLineOpt1, y)), op2, newLineOpt2, z) ⇒ (x, op1, newLineOpt1, y, op2, newLineOpt2, z) - } + def unapply(infixExpr: InfixExpr): Option[(List[ExprElement], Token, Option[Token], List[ExprElement], Token, Option[Token], List[ExprElement])] = + condOpt(infixExpr) { + case InfixExpr(List(InfixExpr(x, op1, newLineOpt1, y)), op2, newLineOpt2, z) ⇒ (x, op1, newLineOpt1, y, op2, newLineOpt2, z) + } } private def performRotationsForPrecedence(infixExpr: InfixExpr): InfixExpr = infixExpr match { @@ -742,7 +743,7 @@ class ScalaParser(tokens: Array[Token]) { val unaryId = PrefixExprElement(ident()) if (isMinus && isNumericLit) { val literal_ = literal() - simpleExprRest(exprElementFlatten2((unaryId, literal_)), true) + simpleExprRest(exprElementFlatten2((unaryId, literal_)), canApply = true) } else List(Expr(exprElementFlatten2((unaryId, simpleExpr())))) } else @@ -762,7 +763,7 @@ class ScalaParser(tokens: Array[Token]) { case USCORE ⇒ exprElementFlatten2(nextToken()) case LPAREN ⇒ - val (lparen, parenBody, rparen) = makeParens(commaSeparated(expr)) + val (lparen, parenBody, rparen) = makeParens(commaSeparated(expr())) exprElementFlatten2(ParenExpr(lparen, exprElementFlatten2(parenBody), rparen)) case LBRACE ⇒ canApply = false @@ -913,7 +914,7 @@ class ScalaParser(tokens: Array[Token]) { def isXML: Boolean = false - def functionArgType() = argType() + def functionArgType(): List[TypeElement] = argType() def argType(): List[TypeElement] = currentTokenType match { case USCORE ⇒ @@ -1018,7 +1019,7 @@ class ScalaParser(tokens: Array[Token]) { SYMBOL_LITERAL | TRUE | FALSE | NULL ⇒ exprElementFlatten2(literal(inPattern = true)) case LPAREN ⇒ - val (lparen, patterns_, rparen) = makeParens(noSeq.patterns) + val (lparen, patterns_, rparen) = makeParens(noSeq.patterns()) exprElementFlatten2((lparen, patterns_, rparen)) case XML_START_OPEN | XML_COMMENT | XML_CDATA | XML_UNPARSED | XML_PROCESSING_INSTRUCTION ⇒ exprElementFlatten2(xmlLiteralPattern()) @@ -1048,16 +1049,16 @@ class ScalaParser(tokens: Array[Token]) { override val isXML = true } - def typ() = outPattern.typ() - def startInfixType() = outPattern.infixType() - def startAnnotType() = outPattern.annotType() - def exprTypeArgs() = outPattern.typeArgs() - def exprSimpleType() = outPattern.simpleType() + def typ(): Type = outPattern.typ() + def startInfixType(): List[TypeElement] = outPattern.infixType() + def startAnnotType(): List[TypeElement] = outPattern.annotType() + def exprTypeArgs(): List[TypeElement] = outPattern.typeArgs() + def exprSimpleType(): List[TypeElement] = outPattern.simpleType() - def pattern() = noSeq.pattern() - def patterns() = noSeq.patterns() - def seqPatterns() = seqOK.patterns() - def xmlSeqPatterns() = xmlSeqOK.patterns() + def pattern(): Expr = noSeq.pattern() + def patterns(): List[ExprElement] = noSeq.patterns() + def seqPatterns(): List[ExprElement] = seqOK.patterns() + def xmlSeqPatterns(): List[ExprElement] = xmlSeqOK.patterns() private def argumentPatterns(): List[ExprElement] = { val (lparen, patterns_, rparen) = inParens { if (RPAREN) Nil else seqPatterns() } @@ -1089,7 +1090,7 @@ class ScalaParser(tokens: Array[Token]) { private def modifiers(): List[Modifier] = { val modifiers = ListBuffer[Modifier]() - def loop() { + def loop(): Unit = { currentTokenType match { case PRIVATE | PROTECTED ⇒ val privateOrProtected = nextToken() @@ -1349,7 +1350,7 @@ class ScalaParser(tokens: Array[Token]) { Some((equalsToken, clause)) } else None - PatDefOrDcl(valOrVarToken, pattern_, otherPatterns.toList, typedOpt_, equalsClauseOption) + PatDefOrDcl(valOrVarToken, pattern_, otherPatterns, typedOpt_, equalsClauseOption) } private def funDefOrDcl(localDef: Boolean): FunDefOrDcl = { @@ -1769,7 +1770,8 @@ class ScalaParser(tokens: Array[Token]) { if (initialSemis.isEmpty) otherStatSeq else { - val otherStats = (initialSemis.init.toList.map((_, None)) :+ ((initialSemis.last, otherStatSeq.firstStatOpt))) ++ otherStatSeq.otherStats + val otherStats = (initialSemis.init.toList.map((_, Option.empty[Stat])) :+ + ((initialSemis.last, otherStatSeq.firstStatOpt))) ++ otherStatSeq.otherStats StatSeq(selfReferenceOpt = None, firstStatOpt = None, otherStats = otherStats) } } @@ -1946,7 +1948,7 @@ class ScalaParser(tokens: Array[Token]) { private def isVariableName(name: String): Boolean = { val first = name(0) - ((first.isLower && first.isLetter) || first == '_') + (first.isLower && first.isLetter) || first == '_' } private def optional[T](p: ⇒ T): Option[T] = @@ -1957,7 +1959,7 @@ class ScalaParser(tokens: Array[Token]) { try { p1 } catch { - case e: ScalaParserException ⇒ + case _: ScalaParserException ⇒ pos = originalPos if (logging) println("Rewinding to try alternative: " + currentToken) p2 @@ -1983,13 +1985,13 @@ object ScalaParser { */ def parse(text: String, scalaVersion: String = ScalaVersions.DEFAULT_VERSION): Option[AstNode] = { val parser = new ScalaParser(ScalaLexer.tokenise(text, scalaVersion = scalaVersion).toArray) - parser.safeParse(parser.compilationUnitOrScript) + parser.safeParse(parser.compilationUnitOrScript()) } trait ExprElementFlattenable { def elements: List[ExprElement] } case class ExprElements(elements: List[ExprElement]) extends ExprElementFlattenable - def exprElementFlatten[T <% ExprElementFlattenable]: (T ⇒ List[ExprElement]) = t ⇒ { exprElementFlatten2(t) } - def exprElementFlatten2[T <% ExprElementFlattenable](t: T): List[ExprElement] = groupGeneralTokens(t.elements) + def exprElementFlatten[T](implicit flat: T => ExprElementFlattenable): (T ⇒ List[ExprElement]) = t ⇒ { exprElementFlatten2(t) } + def exprElementFlatten2[T](t: T)(implicit flat: T => ExprElementFlattenable): List[ExprElement] = groupGeneralTokens(t.elements) def groupGeneralTokens(xs: List[ExprElement]): List[ExprElement] = { val eq = (x: ExprElement, y: ExprElement) ⇒ (x, y) match { case (GeneralTokens(_), GeneralTokens(_)) ⇒ true @@ -2015,39 +2017,39 @@ object ScalaParser { implicit def listOfTokenToExprFlattenable(tokens: List[Token]): ExprElementFlattenable = GeneralTokens(tokens) implicit def exprToExprFlattenable(expr: Expr): ExprElementFlattenable = expr.contents implicit def exprElementToExprFlattenable(exprElement: ExprElement): ExprElementFlattenable = ExprElements(List(exprElement)) - implicit def ordinaryPairToExprFlattenable[A <% ExprElementFlattenable, B <% ExprElementFlattenable](pair: (A, B)): ExprElementFlattenable = + implicit def ordinaryPairToExprFlattenable[A, B](pair: (A, B))(implicit flatA: A => ExprElementFlattenable, flatB: B => ExprElementFlattenable): ExprElementFlattenable = ExprElements(pair._1.elements ::: pair._2.elements) - implicit def tripleToExprFlattenable[A <% ExprElementFlattenable, B <% ExprElementFlattenable, C <% ExprElementFlattenable](triple: (A, B, C)): ExprElementFlattenable = + implicit def tripleToExprFlattenable[A, B, C](triple: (A, B, C))(implicit flatA: A => ExprElementFlattenable, flatB: B => ExprElementFlattenable, flatC: C => ExprElementFlattenable): ExprElementFlattenable = ExprElements(triple._1.elements ::: triple._2.elements ::: triple._3.elements) - implicit def eitherToExprFlattenable[A <% ExprElementFlattenable, B <% ExprElementFlattenable](either: Either[A, B]): ExprElementFlattenable = ExprElements(either match { + implicit def eitherToExprFlattenable[A, B](either: Either[A, B])(implicit flatA: A => ExprElementFlattenable, flatB: B => ExprElementFlattenable): ExprElementFlattenable = ExprElements(either match { case Left(x) ⇒ x.elements case Right(x) ⇒ x.elements }) - implicit def optionToExprFlattenable[T <% ExprElementFlattenable](option: Option[T]): ExprElementFlattenable = option.toList - implicit def listToExprFlattenable[T <% ExprElementFlattenable](list: List[T]): ExprElementFlattenable = ExprElements(list flatMap { _.elements }) - implicit def vectorToExprFlattenable[T <% ExprElementFlattenable](vector: Vector[T]): ExprElementFlattenable = ExprElements(vector.toList flatMap { _.elements }) + implicit def optionToExprFlattenable[T](option: Option[T])(implicit flat: T => ExprElementFlattenable): ExprElementFlattenable = option.toList + implicit def listToExprFlattenable[T](list: List[T])(implicit flat: T => ExprElementFlattenable): ExprElementFlattenable = ExprElements(list flatMap { _.elements }) + implicit def vectorToExprFlattenable[T](vector: Vector[T])(implicit flat: T => ExprElementFlattenable): ExprElementFlattenable = ExprElements(vector.toList flatMap { _.elements }) def makeExpr(flattenables: ExprElementFlattenable*): Expr = Expr(flattenables.toList flatMap { _.elements }) trait TypeElementFlattenable { def elements: List[TypeElement] } - case class TypeElements(val elements: List[TypeElement]) extends TypeElementFlattenable - def typeElementFlatten[T <% TypeElementFlattenable]: (T ⇒ List[TypeElement]) = _.elements - def typeElementFlatten2[T <% TypeElementFlattenable](t: T): List[TypeElement] = t.elements + case class TypeElements(elements: List[TypeElement]) extends TypeElementFlattenable + def typeElementFlatten[T](implicit flat: T => TypeElementFlattenable): (T ⇒ List[TypeElement]) = _.elements + def typeElementFlatten2[T](t: T)(implicit flat: T => TypeElementFlattenable): List[TypeElement] = t.elements def typeElementFlatten3(flattenables: TypeElementFlattenable*): List[TypeElement] = flattenables.toList flatMap { _.elements } implicit def tokenToTypeFlattenable(token: Token): TypeElementFlattenable = GeneralTokens(List(token)) implicit def listOfTokenToTypeFlattenable(tokens: List[Token]): TypeElementFlattenable = GeneralTokens(tokens) implicit def typeElementToTypeFlattenable(typeElement: TypeElement): TypeElementFlattenable = TypeElements(List(typeElement)) - implicit def eitherToTypeFlattenable[A <% TypeElementFlattenable, B <% TypeElementFlattenable](either: Either[A, B]): TypeElementFlattenable = TypeElements(either match { + implicit def eitherToTypeFlattenable[A, B](either: Either[A, B])(implicit flatA: A => TypeElementFlattenable, flatB: B => TypeElementFlattenable): TypeElementFlattenable = TypeElements(either match { case Left(x) ⇒ x.elements case Right(x) ⇒ x.elements }) - implicit def pairToTypeFlattenable[A <% TypeElementFlattenable, B <% TypeElementFlattenable](pair: (A, B)): TypeElementFlattenable = + implicit def pairToTypeFlattenable[A, B](pair: (A, B))(implicit flatA: A => TypeElementFlattenable, flatB: B => TypeElementFlattenable): TypeElementFlattenable = TypeElements(pair._1.elements ::: pair._2.elements) - implicit def tripleToTypeFlattenable[A <% TypeElementFlattenable, B <% TypeElementFlattenable, C <% TypeElementFlattenable](triple: (A, B, C)): TypeElementFlattenable = + implicit def tripleToTypeFlattenable[A, B, C](triple: (A, B, C))(implicit flatA: A => TypeElementFlattenable, flatB: B => TypeElementFlattenable, flatC: C => TypeElementFlattenable): TypeElementFlattenable = TypeElements(triple._1.elements ::: triple._2.elements ::: triple._3.elements) - implicit def optionToTypeFlattenable[T <% TypeElementFlattenable](option: Option[T]): TypeElementFlattenable = option.toList - implicit def listToTypeFlattenable[T <% TypeElementFlattenable](list: List[T]): TypeElementFlattenable = TypeElements(list flatMap { _.elements }) + implicit def optionToTypeFlattenable[T](option: Option[T])(implicit flat: T => TypeElementFlattenable): TypeElementFlattenable = option.toList + implicit def listToTypeFlattenable[T](list: List[T])(implicit flat: T => TypeElementFlattenable): TypeElementFlattenable = TypeElements(list flatMap { _.elements }) } diff --git a/version.sbt b/version.sbt index a9721bef..7965a5da 100644 --- a/version.sbt +++ b/version.sbt @@ -1 +1 @@ -version in ThisBuild := "0.2.6" +version in ThisBuild := "0.2.7-SNAPSHOT"