diff options
Diffstat (limited to 'src')
779 files changed, 4276 insertions, 3108 deletions
diff --git a/src/asm/scala/tools/asm/tree/InsnList.java b/src/asm/scala/tools/asm/tree/InsnList.java index 55d83c2e8b..b1e2d97c6f 100644 --- a/src/asm/scala/tools/asm/tree/InsnList.java +++ b/src/asm/scala/tools/asm/tree/InsnList.java @@ -244,6 +244,14 @@ public class InsnList { * {@link InsnList}</i>. */ public void add(final AbstractInsnNode insn) { + if(insn.prev != null || insn.next != null) { + // Adding an instruction that still refers to others (in the same or another InsnList) leads to hard to debug bugs. + // Initially everything may look ok (e.g. iteration follows `next` thus a stale `prev` isn't noticed). + // However, a stale link brings the doubly-linked into disarray e.g. upon removing an element, + // which results in the `next` of a stale `prev` being updated, among other failure scenarios. + // Better fail early. + throw new RuntimeException("Instruction " + insn + " already belongs to some InsnList."); + } ++size; if (last == null) { first = insn; diff --git a/src/build/maven/maven-deploy.xml b/src/build/maven/maven-deploy.xml index bd946bf0f3..e70173319e 100644 --- a/src/build/maven/maven-deploy.xml +++ b/src/build/maven/maven-deploy.xml @@ -164,11 +164,7 @@ <attribute name="repository" /> <attribute name="version" /> <sequential> - <deploy-remote name="scala-library" version="@{version}" repository="@{repository}"> - <extra-attachments> - <artifact:attach type="jar" file="scala-library/scala-library-docs.jar" classifier="javadoc" /> - </extra-attachments> - </deploy-remote> + <deploy-remote name="scala-library" version="@{version}" repository="@{repository}"/> <deploy-remote name="jline" version="@{version}" repository="@{repository}"/> <deploy-remote name="scala-reflect" version="@{version}" repository="@{repository}"/> <deploy-remote name="scala-compiler" version="@{version}" repository="@{repository}" /> diff --git a/src/build/pack.xml b/src/build/pack.xml index 381d3f1931..20c4034107 100644 --- a/src/build/pack.xml +++ b/src/build/pack.xml @@ -112,8 +112,10 @@ MAIN DISTRIBUTION PACKAGING </target> <target name="pack-archives.latest.unix" depends="pack-archives.src" unless="os.win"> + <!-- be sure to use a relative symlink to make the distribution portable, + `resource` is relative to directory of `link` --> <symlink link="${dists.dir}/archives/scala-latest-sources.tgz" - resource="${dists.dir}/archives/scala-${version.number}-sources.tgz" + resource="scala-${version.number}-sources.tgz" overwrite="yes"/> </target> diff --git a/src/compiler/scala/reflect/macros/runtime/Typers.scala b/src/compiler/scala/reflect/macros/runtime/Typers.scala index 070b288c3a..398770ab35 100644 --- a/src/compiler/scala/reflect/macros/runtime/Typers.scala +++ b/src/compiler/scala/reflect/macros/runtime/Typers.scala @@ -54,8 +54,10 @@ trait Typers { wrapper(universe.analyzer.inferImplicit(tree, pt, reportAmbiguous = true, isView = isView, context = context, saveAmbiguousDivergent = !silent, pos = pos)) match { case failure if failure.tree.isEmpty => macroLogVerbose("implicit search has failed. to find out the reason, turn on -Xlog-implicits") - if (context.hasErrors) throw new TypecheckException(context.errBuffer.head.errPos, context.errBuffer.head.errMsg) - universe.EmptyTree + context.firstError match { + case Some(err) => throw new TypecheckException(err.errPos, err.errMsg) + case None => universe.EmptyTree + } case success => success.tree } diff --git a/src/compiler/scala/reflect/reify/package.scala b/src/compiler/scala/reflect/reify/package.scala index 78f85c2634..ae0288186b 100644 --- a/src/compiler/scala/reflect/reify/package.scala +++ b/src/compiler/scala/reflect/reify/package.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect import scala.reflect.macros.ReificationException import scala.tools.nsc.Global diff --git a/src/compiler/scala/reflect/reify/utils/Extractors.scala b/src/compiler/scala/reflect/reify/utils/Extractors.scala index 7338df1f72..d5f27dc119 100644 --- a/src/compiler/scala/reflect/reify/utils/Extractors.scala +++ b/src/compiler/scala/reflect/reify/utils/Extractors.scala @@ -11,7 +11,7 @@ trait Extractors { // Example of a reified tree for `reify(List(1, 2))`: // (also contains an example of a reified type as a third argument to the constructor of Expr) // { - // val $u: reflect.runtime.universe.type = scala.reflect.runtime.`package`.universe; + // val $u: scala.reflect.runtime.universe.type = scala.reflect.runtime.`package`.universe; // val $m: $u.Mirror = $u.runtimeMirror(Test.this.getClass().getClassLoader()); // $u.Expr[List[Int]]($m, { // final class $treecreator1 extends scala.reflect.api.TreeCreator { diff --git a/src/compiler/scala/tools/ant/Same.scala b/src/compiler/scala/tools/ant/Same.scala index 6362d28580..6036b238b6 100644 --- a/src/compiler/scala/tools/ant/Same.scala +++ b/src/compiler/scala/tools/ant/Same.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.tools.ant +package scala +package tools.ant import java.io.{File, FileInputStream} diff --git a/src/compiler/scala/tools/ant/sabbus/Break.scala b/src/compiler/scala/tools/ant/sabbus/Break.scala index 0b6701b6e9..b170ceaed8 100644 --- a/src/compiler/scala/tools/ant/sabbus/Break.scala +++ b/src/compiler/scala/tools/ant/sabbus/Break.scala @@ -7,7 +7,8 @@ \* */ -package scala.tools.ant.sabbus +package scala +package tools.ant.sabbus import org.apache.tools.ant.Task diff --git a/src/compiler/scala/tools/ant/sabbus/Make.scala b/src/compiler/scala/tools/ant/sabbus/Make.scala index 5274594f3d..027a828f03 100644 --- a/src/compiler/scala/tools/ant/sabbus/Make.scala +++ b/src/compiler/scala/tools/ant/sabbus/Make.scala @@ -7,7 +7,8 @@ \* */ -package scala.tools.ant.sabbus +package scala +package tools.ant.sabbus import java.io.File import org.apache.tools.ant.Task diff --git a/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala b/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala index 363c31f6c4..595b45ae51 100644 --- a/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala +++ b/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.tools.ant +package scala +package tools.ant package sabbus import java.io.{ File, FileWriter } diff --git a/src/compiler/scala/tools/ant/sabbus/Use.scala b/src/compiler/scala/tools/ant/sabbus/Use.scala index 5f50bb7908..a8736f228b 100644 --- a/src/compiler/scala/tools/ant/sabbus/Use.scala +++ b/src/compiler/scala/tools/ant/sabbus/Use.scala @@ -7,7 +7,8 @@ \* */ -package scala.tools.ant +package scala +package tools.ant package sabbus import java.io.File diff --git a/src/compiler/scala/tools/ant/templates/tool-windows.tmpl b/src/compiler/scala/tools/ant/templates/tool-windows.tmpl index 411a27b9c7..bd6cf561b9 100644 --- a/src/compiler/scala/tools/ant/templates/tool-windows.tmpl +++ b/src/compiler/scala/tools/ant/templates/tool-windows.tmpl @@ -14,8 +14,9 @@ set _LINE_TOOLCP= :another_param -if "%1%"=="-toolcp" ( - set _LINE_TOOLCP=%2% +rem Use "%~1" to handle spaces in paths. See http://ss64.com/nt/syntax-args.html +if "%~1"=="-toolcp" ( + set _LINE_TOOLCP=%~2 shift shift goto another_param diff --git a/src/compiler/scala/tools/cmd/Demo.scala b/src/compiler/scala/tools/cmd/Demo.scala index af818845bb..fc90140f8f 100644 --- a/src/compiler/scala/tools/cmd/Demo.scala +++ b/src/compiler/scala/tools/cmd/Demo.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.tools +package scala +package tools package cmd /** A sample command specification for illustrative purposes. diff --git a/src/compiler/scala/tools/cmd/Interpolation.scala b/src/compiler/scala/tools/cmd/Interpolation.scala index abffd6bb2e..d1c798b621 100644 --- a/src/compiler/scala/tools/cmd/Interpolation.scala +++ b/src/compiler/scala/tools/cmd/Interpolation.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.tools +package scala +package tools package cmd /** Interpolation logic for generated files. The idea is to be diff --git a/src/compiler/scala/tools/cmd/gen/AnyVals.scala b/src/compiler/scala/tools/cmd/gen/AnyVals.scala index 35d4eaf1b6..7e01afac2b 100644 --- a/src/compiler/scala/tools/cmd/gen/AnyVals.scala +++ b/src/compiler/scala/tools/cmd/gen/AnyVals.scala @@ -22,8 +22,8 @@ trait AnyValReps { } def coercionCommentExtra = "" def coercionComment = """ - /** Language mandated coercions from @name@ to "wider" types.%s - */""".format(coercionCommentExtra) +/** Language mandated coercions from @name@ to "wider" types.%s + */""".format(coercionCommentExtra) def implicitCoercions: List[String] = { val coercions = this match { @@ -35,7 +35,7 @@ trait AnyValReps { case _ => Nil } if (coercions.isEmpty) Nil - else coercionComment :: coercions + else coercionComment.lines.toList ++ coercions } def isCardinal: Boolean = isIntegerType(this) @@ -183,7 +183,7 @@ trait AnyValReps { } def objectLines = { val comp = if (isCardinal) cardinalCompanion else floatingCompanion - (comp + allCompanions + "\n" + nonUnitCompanions).trim.lines.toList ++ implicitCoercions map interpolate + interpolate(comp + allCompanions + "\n" + nonUnitCompanions).trim.lines.toList ++ (implicitCoercions map interpolate) } /** Makes a set of binary operations based on the given set of ops, args, and resultFn. @@ -209,11 +209,14 @@ trait AnyValReps { ) def lcname = name.toLowerCase + def boxedSimpleName = this match { + case C => "Character" + case I => "Integer" + case _ => name + } def boxedName = this match { case U => "scala.runtime.BoxedUnit" - case C => "java.lang.Character" - case I => "java.lang.Integer" - case _ => "java.lang." + name + case _ => "java.lang." + boxedSimpleName } def zeroRep = this match { case L => "0L" @@ -228,7 +231,13 @@ trait AnyValReps { def indentN(s: String) = s.lines map indent mkString "\n" def boxUnboxImpls = Map( + "@boxRunTimeDoc@" -> """ + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxTo%s`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + *""".format(boxedSimpleName), "@boxImpl@" -> "%s.valueOf(x)".format(boxedName), + "@unboxRunTimeDoc@" -> """ + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxTo%s`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + *""".format(name), "@unboxImpl@" -> "x.asInstanceOf[%s].%sValue()".format(boxedName, lcname), "@unboxDoc@" -> "the %s resulting from calling %sValue() on `x`".format(name, lcname) ) @@ -299,7 +308,7 @@ import scala.language.implicitConversions def allCompanions = """ /** Transform a value type into a boxed reference type. - * + *@boxRunTimeDoc@ * @param x the @name@ to be boxed * @return a @boxed@ offering `x` as its underlying value. */ @@ -308,7 +317,7 @@ def box(x: @name@): @boxed@ = @boxImpl@ /** Transform a boxed type into a value type. Note that this * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a @boxed@. - * + *@unboxRunTimeDoc@ * @param x the @boxed@ to be unboxed. * @throws ClassCastException if the argument is not a @boxed@ * @return @unboxDoc@ @@ -471,7 +480,9 @@ override def getClass(): Class[Boolean] = null def objectLines = interpolate(allCompanions).lines.toList override def boxUnboxImpls = Map( + "@boxRunTimeDoc@" -> "", "@boxImpl@" -> "scala.runtime.BoxedUnit.UNIT", + "@unboxRunTimeDoc@" -> "", "@unboxImpl@" -> "()", "@unboxDoc@" -> "the Unit value ()" ) diff --git a/src/compiler/scala/tools/cmd/package.scala b/src/compiler/scala/tools/cmd/package.scala index d605ecae8f..c62a977950 100644 --- a/src/compiler/scala/tools/cmd/package.scala +++ b/src/compiler/scala/tools/cmd/package.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.tools +package scala +package tools package object cmd { def returning[T](x: T)(f: T => Unit): T = { f(x) ; x } diff --git a/src/compiler/scala/tools/nsc/CompileClient.scala b/src/compiler/scala/tools/nsc/CompileClient.scala index 64f6758e73..3017d8c9cc 100644 --- a/src/compiler/scala/tools/nsc/CompileClient.scala +++ b/src/compiler/scala/tools/nsc/CompileClient.scala @@ -3,11 +3,12 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc import settings.FscSettings import scala.tools.util.CompileOutputCommon -import sys.SystemProperties.preferIPv4Stack +import scala.sys.SystemProperties.preferIPv4Stack /** The client part of the fsc offline compiler. Instead of compiling * things itself, it send requests to a CompileServer. diff --git a/src/compiler/scala/tools/nsc/Driver.scala b/src/compiler/scala/tools/nsc/Driver.scala index fbfed6110f..3ac27a42e8 100644 --- a/src/compiler/scala/tools/nsc/Driver.scala +++ b/src/compiler/scala/tools/nsc/Driver.scala @@ -1,4 +1,5 @@ -package scala.tools.nsc +package scala +package tools.nsc import scala.tools.nsc.reporters.ConsoleReporter import Properties.{ versionString, copyrightString, residentPromptString } diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index d0b59b53cc..f1fccd6069 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -3,7 +3,9 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools +package nsc import java.io.{ File, FileOutputStream, PrintWriter, IOException, FileNotFoundException } import java.nio.charset.{ Charset, CharsetDecoder, IllegalCharsetNameException, UnsupportedCharsetException } @@ -218,7 +220,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) // not deprecated yet, but a method called "error" imported into // nearly every trait really must go. For now using globalError. def error(msg: String) = globalError(msg) - def inform(msg: String) = reporter.echo(msg) + override def inform(msg: String) = reporter.echo(msg) override def globalError(msg: String) = reporter.error(NoPosition, msg) override def warning(msg: String) = if (settings.fatalWarnings) globalError(msg) diff --git a/src/compiler/scala/tools/nsc/Main.scala b/src/compiler/scala/tools/nsc/Main.scala index 9f6f483ad8..a66ee572a9 100644 --- a/src/compiler/scala/tools/nsc/Main.scala +++ b/src/compiler/scala/tools/nsc/Main.scala @@ -5,6 +5,8 @@ package scala.tools package nsc +import scala.language.postfixOps + /** The main class for NSC, a compiler for the programming * language Scala. */ diff --git a/src/compiler/scala/tools/nsc/MainTokenMetric.scala b/src/compiler/scala/tools/nsc/MainTokenMetric.scala index e2893204e0..84eb688b63 100644 --- a/src/compiler/scala/tools/nsc/MainTokenMetric.scala +++ b/src/compiler/scala/tools/nsc/MainTokenMetric.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc import scala.tools.nsc.reporters.ConsoleReporter diff --git a/src/compiler/scala/tools/nsc/ScriptRunner.scala b/src/compiler/scala/tools/nsc/ScriptRunner.scala index 5f8bc71449..d553d71bf5 100644 --- a/src/compiler/scala/tools/nsc/ScriptRunner.scala +++ b/src/compiler/scala/tools/nsc/ScriptRunner.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc import io.{ Directory, File, Path } import java.io.IOException diff --git a/src/compiler/scala/tools/nsc/ast/Printers.scala b/src/compiler/scala/tools/nsc/ast/Printers.scala index 72538bac08..89652c5a20 100644 --- a/src/compiler/scala/tools/nsc/ast/Printers.scala +++ b/src/compiler/scala/tools/nsc/ast/Printers.scala @@ -42,7 +42,7 @@ trait Printers extends scala.reflect.internal.Printers { this: Global => } } - // overflow cases missing from TreePrinter in reflect.api + // overflow cases missing from TreePrinter in scala.reflect.api override def xprintTree(treePrinter: super.TreePrinter, tree: Tree) = tree match { case DocDef(comment, definition) => treePrinter.print(comment.raw) diff --git a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala index 0077ed0c84..1e70b7091b 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package ast import java.awt.{List => awtList, _} diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index a3abf633db..1dfb2f3bab 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -30,6 +30,9 @@ trait ParsersCommon extends ScannersCommon { val global : Global import global._ + def newLiteral(const: Any) = Literal(Constant(const)) + def literalUnit = newLiteral(()) + /** This is now an abstract class, only to work around the optimizer: * methods in traits are never inlined. */ @@ -57,7 +60,7 @@ trait ParsersCommon extends ScannersCommon { if (in.token == LPAREN) inParens(body) else { accept(LPAREN) ; alt } - @inline final def inParensOrUnit[T](body: => Tree): Tree = inParensOrError(body, Literal(Constant(()))) + @inline final def inParensOrUnit[T](body: => Tree): Tree = inParensOrError(body, literalUnit) @inline final def inParensOrNil[T](body: => List[T]): List[T] = inParensOrError(body, Nil) @inline final def inBraces[T](body: => T): T = { @@ -71,7 +74,7 @@ trait ParsersCommon extends ScannersCommon { else { accept(LBRACE) ; alt } @inline final def inBracesOrNil[T](body: => List[T]): List[T] = inBracesOrError(body, Nil) - @inline final def inBracesOrUnit[T](body: => Tree): Tree = inBracesOrError(body, Literal(Constant(()))) + @inline final def inBracesOrUnit[T](body: => Tree): Tree = inBracesOrError(body, literalUnit) @inline final def dropAnyBraces[T](body: => T): T = if (in.token == LBRACE) inBraces(body) else body @@ -355,7 +358,7 @@ self => /* If we see anything but the above, fail. */ return None } - Some(makePackaging(0, emptyPkg, newStmts)) + Some(makeEmptyPackage(0, newStmts)) } if (mainModuleName == newTermName(ScriptRunner.defaultScriptMain)) @@ -376,15 +379,13 @@ self => * } * }}} */ - - def emptyPkg = atPos(0, 0, 0) { Ident(nme.EMPTY_PACKAGE_NAME) } def emptyInit = DefDef( NoMods, nme.CONSTRUCTOR, Nil, ListOfNil, TypeTree(), - Block(List(Apply(gen.mkSuperInitCall, Nil)), Literal(Constant(()))) + Block(List(Apply(gen.mkSuperInitCall, Nil)), literalUnit) ) // def main @@ -395,11 +396,11 @@ self => // object Main def moduleName = newTermName(ScriptRunner scriptMain settings) - def moduleBody = Template(List(atPos(o2p(in.offset))(scalaAnyRefConstr)), emptyValDef, List(emptyInit, mainDef)) + def moduleBody = Template(atInPos(scalaAnyRefConstr) :: Nil, emptyValDef, List(emptyInit, mainDef)) def moduleDef = ModuleDef(NoMods, moduleName, moduleBody) // package <empty> { ... } - makePackaging(0, emptyPkg, List(moduleDef)) + makeEmptyPackage(0, moduleDef :: Nil) } /* --------------- PLACEHOLDERS ------------------------------------------- */ @@ -529,6 +530,10 @@ self => else syntaxError(in.offset, msg, skipIt) } + def syntaxErrorOrIncompleteAnd[T](msg: String, skipIt: Boolean)(and: T): T = { + syntaxErrorOrIncomplete(msg, skipIt) + and + } def expectedMsg(token: Int): String = token2string(token) + " expected but " +token2string(in.token) + " found." @@ -563,9 +568,9 @@ self => if (!isStatSeqEnd) acceptStatSep() - def errorTypeTree = TypeTree() setType ErrorType setPos o2p(in.offset) - def errorTermTree = Literal(Constant(null)) setPos o2p(in.offset) - def errorPatternTree = Ident(nme.WILDCARD) setPos o2p(in.offset) + def errorTypeTree = setInPos(TypeTree() setType ErrorType) + def errorTermTree = setInPos(newLiteral(null)) + def errorPatternTree = setInPos(Ident(nme.WILDCARD)) /** Check that type parameter is not by name or repeated. */ def checkNotByNameOrVarargs(tpt: Tree) = { @@ -607,6 +612,10 @@ self => } def isDefIntro = isTemplateIntro || isDclIntro + def isTopLevelIntro = in.token match { + case PACKAGE | IMPORT | AT => true + case _ => isTemplateIntro || isModifier + } def isNumericLit: Boolean = in.token match { case INTLIT | LONGLIT | FLOATLIT | DOUBLELIT => true @@ -666,6 +675,9 @@ self => def atPos[T <: Tree](pos: Position)(t: T): T = global.atPos(pos)(t) + def atInPos[T <: Tree](t: T): T = atPos(o2p(in.offset))(t) + def setInPos[T <: Tree](t: T): T = t setPos o2p(in.offset) + /** Convert tree to formal parameter list. */ def convertToParams(tree: Tree): List[ValDef] = tree match { case Parens(ts) => ts map convertToParam @@ -886,7 +898,7 @@ self => * }}} */ def compoundType(): Tree = compoundTypeRest( - if (in.token == LBRACE) atPos(o2p(in.offset))(scalaAnyRefConstr) + if (in.token == LBRACE) atInPos(scalaAnyRefConstr) else annotType() ) @@ -947,12 +959,11 @@ self => } /** Assumed (provisionally) to be TermNames. */ - def ident(skipIt: Boolean): Name = + def ident(skipIt: Boolean): Name = ( if (isIdent) rawIdent().encode - else { - syntaxErrorOrIncomplete(expectedMsg(IDENTIFIER), skipIt) - nme.ERROR - } + else syntaxErrorOrIncompleteAnd(expectedMsg(IDENTIFIER), skipIt)(nme.ERROR) + ) + def ident(): Name = ident(skipIt = true) def rawIdent(): Name = try in.name finally in.nextToken() @@ -1078,28 +1089,22 @@ self => * @note The returned tree does not yet have a position */ def literal(isNegated: Boolean = false, inPattern: Boolean = false): Tree = { - def finish(value: Any): Tree = { - val t = Literal(Constant(value)) - in.nextToken() - t - } + def finish(value: Any): Tree = try newLiteral(value) finally in.nextToken() if (in.token == SYMBOLLIT) Apply(scalaDot(nme.Symbol), List(finish(in.strVal))) else if (in.token == INTERPOLATIONID) interpolatedString(inPattern = inPattern) else finish(in.token match { - case CHARLIT => in.charVal - case INTLIT => in.intVal(isNegated).toInt - case LONGLIT => in.intVal(isNegated) - case FLOATLIT => in.floatVal(isNegated).toFloat - case DOUBLELIT => in.floatVal(isNegated) + case CHARLIT => in.charVal + case INTLIT => in.intVal(isNegated).toInt + case LONGLIT => in.intVal(isNegated) + case FLOATLIT => in.floatVal(isNegated).toFloat + case DOUBLELIT => in.floatVal(isNegated) case STRINGLIT | STRINGPART => in.strVal.intern() - case TRUE => true - case FALSE => false - case NULL => null - case _ => - syntaxErrorOrIncomplete("illegal literal", skipIt = true) - null + case TRUE => true + case FALSE => false + case NULL => null + case _ => syntaxErrorOrIncompleteAnd("illegal literal", skipIt = true)(null) }) } @@ -1112,18 +1117,15 @@ self => in.nextToken() while (in.token == STRINGPART) { partsBuf += literal() - exprBuf += { + exprBuf += ( if (inPattern) dropAnyBraces(pattern()) - else { - if (in.token == IDENTIFIER) atPos(in.offset)(Ident(ident())) - else if(in.token == LBRACE) expr() - else if(in.token == THIS) { in.nextToken(); atPos(in.offset)(This(tpnme.EMPTY)) } - else { - syntaxErrorOrIncomplete("error in interpolated string: identifier or block expected", skipIt = true) - EmptyTree - } + else in.token match { + case IDENTIFIER => atPos(in.offset)(Ident(ident())) + case LBRACE => expr() + case THIS => in.nextToken(); atPos(in.offset)(This(tpnme.EMPTY)) + case _ => syntaxErrorOrIncompleteAnd("error in interpolated string: identifier or block expected", skipIt = true)(EmptyTree) } - } + ) } if (in.token == STRINGLIT) partsBuf += literal() @@ -1195,7 +1197,7 @@ self => r } else { accept(LPAREN) - Literal(Constant(true)) + newLiteral(true) } } @@ -1249,7 +1251,7 @@ self => newLinesOpt() val thenp = expr() val elsep = if (in.token == ELSE) { in.nextToken(); expr() } - else Literal(Constant(())) + else literalUnit If(cond, thenp, elsep) } parseIf @@ -1323,7 +1325,7 @@ self => case RETURN => def parseReturn = atPos(in.skipToken()) { - Return(if (isExprIntro) expr() else Literal(Constant(()))) + Return(if (isExprIntro) expr() else literalUnit) } parseReturn case THROW => @@ -1511,8 +1513,7 @@ self => val cpos = r2p(tstart, tstart, in.lastOffset max tstart) makeNew(parents, self, stats, npos, cpos) case _ => - syntaxErrorOrIncomplete("illegal start of simple expression", skipIt = true) - errorTermTree + syntaxErrorOrIncompleteAnd("illegal start of simple expression", skipIt = true)(errorTermTree) } simpleExprRest(t, canApply = canApply) } @@ -1832,8 +1833,7 @@ self => } else { badStart } - syntaxErrorOrIncomplete(msg, skip) - errorPatternTree + syntaxErrorOrIncompleteAnd(msg, skip)(errorPatternTree) } /** {{{ @@ -1849,14 +1849,10 @@ self => * * XXX: Hook for IDE */ - def simplePattern(): Tree = { + def simplePattern(): Tree = ( // simple diagnostics for this entry point - def badStart(): Tree = { - syntaxErrorOrIncomplete("illegal start of simple pattern", skipIt = true) - errorPatternTree - } - simplePattern(badStart) - } + simplePattern(() => syntaxErrorOrIncompleteAnd("illegal start of simple pattern", skipIt = true)(errorPatternTree)) + ) def simplePattern(onError: () => Tree): Tree = { val start = in.offset in.token match { @@ -2222,16 +2218,18 @@ self => * }}} */ def typeBounds(): TypeBoundsTree = { - val t = TypeBoundsTree( - bound(SUPERTYPE, tpnme.Nothing), - bound(SUBTYPE, tpnme.Any) - ) - t setPos wrappingPos(List(t.hi, t.lo)) + val lo = bound(SUPERTYPE) + val hi = bound(SUBTYPE) + val t = TypeBoundsTree(lo, hi) + val defined = List(t.hi, t.lo) filter (_.pos.isDefined) + + if (defined.nonEmpty) + t setPos wrappingPos(defined) + else + t setPos o2p(in.offset) } - def bound(tok: Int, default: TypeName): Tree = - if (in.token == tok) { in.nextToken(); typ() } - else atPos(o2p(in.lastOffset)) { rootScalaDot(default) } + def bound(tok: Int): Tree = if (in.token == tok) { in.nextToken(); typ() } else EmptyTree /* -------- DEFS ------------------------------------------- */ @@ -2524,7 +2522,7 @@ self => */ def constrExpr(vparamss: List[List[ValDef]]): Tree = if (in.token == LBRACE) constrBlock(vparamss) - else Block(List(selfInvocation(vparamss)), Literal(Constant(()))) + else Block(selfInvocation(vparamss) :: Nil, literalUnit) /** {{{ * SelfInvocation ::= this ArgumentExprs {ArgumentExprs} @@ -2554,7 +2552,7 @@ self => else Nil } accept(RBRACE) - Block(stats, Literal(Constant(()))) + Block(stats, literalUnit) } /** {{{ @@ -2577,8 +2575,7 @@ self => case SUPERTYPE | SUBTYPE | SEMI | NEWLINE | NEWLINES | COMMA | RBRACE => TypeDef(mods | Flags.DEFERRED, name, tparams, typeBounds()) case _ => - syntaxErrorOrIncomplete("`=', `>:', or `<:' expected", skipIt = true) - EmptyTree + syntaxErrorOrIncompleteAnd("`=', `>:', or `<:' expected", skipIt = true)(EmptyTree) } } } @@ -2611,8 +2608,7 @@ self => case CASEOBJECT => objectDef(pos, (mods | Flags.CASE) withPosition (Flags.CASE, tokenRange(in.prev /*scanner skips on 'case' to 'object', thus take prev*/))) case _ => - syntaxErrorOrIncomplete("expected start of definition", skipIt = true) - EmptyTree + syntaxErrorOrIncompleteAnd("expected start of definition", skipIt = true)(EmptyTree) } } @@ -2674,6 +2670,40 @@ self => } } + /** Create a tree representing a package object, converting + * {{{ + * package object foo { ... } + * }}} + * to + * {{{ + * package foo { + * object `package` { ... } + * } + * }}} + */ + def packageObjectDef(start: Offset): PackageDef = { + val defn = objectDef(in.offset, NoMods) + val module = copyModuleDef(defn)(name = nme.PACKAGEkw) + val pid = atPos(o2p(defn.pos.startOrPoint))(Ident(defn.name)) + + makePackaging(start, pid, module :: Nil) + } + def packageOrPackageObject(start: Offset): Tree = ( + if (in.token == OBJECT) + joinComment(packageObjectDef(start) :: Nil).head + else { + in.flushDoc + makePackaging(start, pkgQualId(), inBracesOrNil(topStatSeq())) + } + ) + // TODO - eliminate this and use "def packageObjectDef" (see call site of this + // method for small elaboration.) + def makePackageObject(start: Int, objDef: ModuleDef): PackageDef = objDef match { + case ModuleDef(mods, name, impl) => + makePackaging( + start, atPos(o2p(objDef.pos.startOrPoint)){ Ident(name) }, List(ModuleDef(mods, nme.PACKAGEkw, impl))) + } + /** {{{ * ClassParents ::= AnnotType {`(' [Exprs] `)'} {with AnnotType} * TraitParents ::= AnnotType {with AnnotType} @@ -2753,14 +2783,14 @@ self => def anyrefParents() = { val caseParents = if (mods.isCase) List(productConstr, serializableConstr) else Nil parents0 ::: caseParents match { - case Nil => List(atPos(o2p(in.offset))(scalaAnyRefConstr)) + case Nil => atInPos(scalaAnyRefConstr) :: Nil case ps => ps } } def anyvalConstructor() = ( // Not a well-formed constructor, has to be finished later - see note // regarding AnyVal constructor in AddInterfaces. - DefDef(NoMods, nme.CONSTRUCTOR, Nil, ListOfNil, TypeTree(), Block(Nil, Literal(Constant(())))) + DefDef(NoMods, nme.CONSTRUCTOR, Nil, ListOfNil, TypeTree(), Block(Nil, literalUnit)) ) val tstart0 = if (body.isEmpty && in.lastOffset < tstart) in.lastOffset else tstart @@ -2809,42 +2839,10 @@ self => def makePackaging(start: Int, pkg: Tree, stats: List[Tree]): PackageDef = pkg match { case x: RefTree => atPos(start, pkg.pos.point)(PackageDef(x, stats)) } -/* - pkg match { - case id @ Ident(_) => - PackageDef(id, stats) - case Select(qual, name) => // drop this to flatten packages - makePackaging(start, qual, List(PackageDef(Ident(name), stats))) - } - } -*/ - - /** Create a tree representing a package object, converting - * {{{ - * package object foo { ... } - * }}} - * to - * {{{ - * package foo { - * object `package` { ... } - * } - * }}} - */ - def makePackageObject(start: Int, objDef: ModuleDef): PackageDef = objDef match { - case ModuleDef(mods, name, impl) => - makePackaging( - start, atPos(o2p(objDef.pos.startOrPoint)){ Ident(name) }, List(ModuleDef(mods, nme.PACKAGEkw, impl))) - } - /** {{{ - * Packaging ::= package QualId [nl] `{' TopStatSeq `}' - * }}} - */ - def packaging(start: Int): Tree = { - val pkg = pkgQualId() - val stats = inBracesOrNil(topStatSeq()) - makePackaging(start, pkg, stats) - } + def makeEmptyPackage(start: Int, stats: List[Tree]): PackageDef = ( + makePackaging(start, atPos(start, start, start)(Ident(nme.EMPTY_PACKAGE_NAME)), stats) + ) /** {{{ * TopStatSeq ::= TopStat {semi TopStat} @@ -2860,22 +2858,15 @@ self => while (!isStatSeqEnd) { stats ++= (in.token match { case PACKAGE => - val start = in.skipToken() - if (in.token == OBJECT) - joinComment(List(makePackageObject(start, objectDef(in.offset, NoMods)))) - else { - in.flushDoc - List(packaging(start)) - } + packageOrPackageObject(in.skipToken()) :: Nil case IMPORT => in.flushDoc importClause() case x if x == AT || isTemplateIntro || isModifier => - joinComment(List(topLevelTmplDef)) + joinComment(topLevelTmplDef :: Nil) case _ => - if (!isStatSep) - syntaxErrorOrIncomplete("expected class or object definition", skipIt = true) - Nil + if (isStatSep) Nil + else syntaxErrorOrIncompleteAnd("expected class or object definition", skipIt = true)(Nil) }) acceptStatSepOpt() } @@ -2986,7 +2977,7 @@ self => else List(tmplDef(pos, mods)) in.token match { - case RBRACE | CASE => defs :+ (Literal(Constant(())) setPos o2p(in.offset)) + case RBRACE | CASE => defs :+ setInPos(literalUnit) case _ => defs } } @@ -3036,7 +3027,7 @@ self => * CompilationUnit ::= {package QualId semi} TopStatSeq * }}} */ - def compilationUnit(): Tree = checkNoEscapingPlaceholders { + def compilationUnit(): PackageDef = checkNoEscapingPlaceholders { def topstats(): List[Tree] = { val ts = new ListBuffer[Tree] while (in.token == SEMI) in.nextToken() @@ -3044,6 +3035,9 @@ self => if (in.token == PACKAGE) { in.nextToken() if (in.token == OBJECT) { + // TODO - this next line is supposed to be + // ts += packageObjectDef(start) + // but this broke a scaladoc test (run/diagrams-filtering.scala) somehow. ts ++= joinComment(List(makePackageObject(start, objectDef(in.offset, NoMods)))) if (in.token != EOF) { acceptStatSep() @@ -3072,8 +3066,8 @@ self => resetPackage() topstats() match { - case List(stat @ PackageDef(_, _)) => stat - case stats => + case (stat @ PackageDef(_, _)) :: Nil => stat + case stats => val start = if (stats forall (_ == EmptyTree)) 0 else { @@ -3082,7 +3076,7 @@ self => else 0 } - makePackaging(start, atPos(start, start, start) { Ident(nme.EMPTY_PACKAGE_NAME) }, stats) + makeEmptyPackage(start, stats) } } } diff --git a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala index eb31f7a66e..c1a8b96cdf 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala @@ -13,6 +13,7 @@ import scala.annotation.{ switch, tailrec } import scala.collection.{ mutable, immutable } import mutable.{ ListBuffer, ArrayBuffer } import scala.xml.Utility.{ isNameStart } +import scala.language.postfixOps /** See Parsers.scala / ParsersCommon for some explanation of ScannersCommon. */ @@ -695,7 +696,7 @@ trait Scanners extends ScannersCommon { } } - @annotation.tailrec private def getStringPart(multiLine: Boolean): Unit = { + @scala.annotation.tailrec private def getStringPart(multiLine: Boolean): Unit = { def finishStringPart() = { setStrVal() token = STRINGPART diff --git a/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala b/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala index 80d70e6428..3a695c6f59 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala @@ -11,30 +11,98 @@ import javac._ /** An nsc sub-component. */ abstract class SyntaxAnalyzer extends SubComponent with Parsers with MarkupParsers with Scanners with JavaParsers with JavaScanners { + import global._ val phaseName = "parser" - def newPhase(prev: Phase): StdPhase = new ParserPhase(prev) - class ParserPhase(prev: scala.tools.nsc.Phase) extends StdPhase(prev) { + abstract class MemberDefTraverser extends Traverser { + def onMember(defn: MemberDef): Unit + + private var depth: Int = 0 + private def lower[T](body: => T): T = { + depth += 1 + try body finally depth -= 1 + } + def currentDepth = depth + + /** Prune this tree and all trees beneath it. Can be overridden. */ + def prune(md: MemberDef): Boolean = ( + md.mods.isSynthetic + || md.mods.isParamAccessor + || nme.isConstructorName(md.name) + || (md.name containsName nme.ANON_CLASS_NAME) + ) + + override def traverse(t: Tree): Unit = t match { + case md: MemberDef if prune(md) => + case md @ PackageDef(_, stats) => traverseTrees(stats) + case md: ImplDef => onMember(md) ; lower(traverseTrees(md.impl.body)) + case md: ValOrDefDef => onMember(md) ; lower(traverse(md.rhs)) + case _ => super.traverse(t) + } + } + + class MemberPosReporter(unit: CompilationUnit) extends MemberDefTraverser { + private var outputFn: MemberDef => String = outputForScreen + val path = unit.source.file.path + + // If a single line, outputs the line; if it spans multiple lines + // outputs NN,NN with start and end lines, e.g. 15,25. + def outputPos(md: MemberDef): String = { + val pos = md.pos + val start = pos.focusStart.line + val end = pos.focusEnd.line + + if (start == end) "" + start else s"$start,$end" + } + def outputForSed(md: MemberDef): String = { + val pos_s = "%-12s" format outputPos(md) + "p" + s"$pos_s $path # ${md.keyword} ${md.name}" + } + def outputForScreen(md: MemberDef): String = { + val pos_s = "%-20s" format " " * currentDepth + outputPos(md) + s"$pos_s ${md.keyword} ${md.name}" + } + + def onMember(md: MemberDef) = println(outputFn(md)) + // It recognizes "sed" and "anything else". + def show(style: String) { + if (style == "sed") { + outputFn = outputForSed + traverse(unit.body) + } + else { + outputFn = outputForScreen + println(path) + traverse(unit.body) + } + println("") + } + } + + private def initialUnitBody(unit: CompilationUnit): Tree = { + if (unit.isJava) new JavaUnitParser(unit).parse() + else if (global.reporter.incompleteHandled) newUnitParser(unit).parse() + else newUnitParser(unit).smartParse() + } + + class ParserPhase(prev: Phase) extends StdPhase(prev) { override val checkable = false override val keepsTypeParams = false - def apply(unit: global.CompilationUnit) { - import global._ + def apply(unit: CompilationUnit) { informProgress("parsing " + unit) - // if the body is already filled in, do nothing + // if the body is already filled in, don't overwrite it // otherwise compileLate is going to overwrite bodies of synthetic source files - if (unit.body == EmptyTree) { - unit.body = - if (unit.isJava) new JavaUnitParser(unit).parse() - else if (reporter.incompleteHandled) newUnitParser(unit).parse() - else newUnitParser(unit).smartParse() - } + if (unit.body == EmptyTree) + unit.body = initialUnitBody(unit) if (settings.Yrangepos && !reporter.hasErrors) validatePositions(unit.body) + + if (settings.Ymemberpos.isSetByUser) + new MemberPosReporter(unit) show (style = settings.Ymemberpos.value) } } } - diff --git a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala index 1f9862596c..2007d799df 100644 --- a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala +++ b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package backend import scala.collection.{ mutable, immutable } diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala index 94fbba8066..16ee40280c 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala @@ -38,7 +38,7 @@ trait BasicBlocks { import BBFlags._ - def code = method.code + def code = if (method eq null) NoCode else method.code private final class SuccessorList() { private var successors: List[BasicBlock] = Nil diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala index 31028e64d3..9c9c001f02 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala @@ -4,7 +4,8 @@ */ -package scala.tools.nsc +package scala +package tools.nsc package backend package icode diff --git a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala index c5fe3228a3..54be9d18f1 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala @@ -4,7 +4,8 @@ */ -package scala.tools.nsc +package scala +package tools.nsc package backend package icode diff --git a/src/compiler/scala/tools/nsc/backend/icode/Members.scala b/src/compiler/scala/tools/nsc/backend/icode/Members.scala index c1cda2c863..4389afb2b7 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Members.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Members.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package backend package icode @@ -73,7 +74,7 @@ trait Members { ) startBlock = b.successors.head } - + blocks -= b assert(!blocks.contains(b)) method.exh filter (_ covers b) foreach (_.covered -= b) diff --git a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala index ff118be3c4..925775adb9 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package backend package icode @@ -394,14 +395,14 @@ trait Opcodes { self: ICodes => override def category = mthdsCat } - + /** * A place holder entry that allows us to parse class files with invoke dynamic * instructions. Because the compiler doesn't yet really understand the * behavior of invokeDynamic, this op acts as a poison pill. Any attempt to analyze * this instruction will cause a failure. The only optimization that * should ever look at non-Scala generated icode is the inliner, and it - * has been modified to not examine any method with invokeDynamic + * has been modified to not examine any method with invokeDynamic * instructions. So if this poison pill ever causes problems then * there's been a serious misunderstanding */ diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala index 338a07c872..192890a509 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package backend.icode.analysis import scala.collection.{ mutable, immutable } @@ -541,7 +542,8 @@ abstract class CopyPropagation { m.isGetter // abstract getters are still pure, as we 'know' final override def toString() = ( - method.blocks map { b => + if (method eq null) List("<null>") + else method.blocks map { b => "\nIN(%s):\t Bindings: %s".format(b.label, in(b).bindings) + "\nIN(%s):\t Stack: %s".format(b.label, in(b).stack) } diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala index ebc2d33a62..a378998f8f 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala @@ -4,7 +4,8 @@ */ -package scala.tools.nsc +package scala +package tools.nsc package backend.icode.analysis import scala.collection.{ mutable, immutable } diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala index 26b7bc50d8..fecd48ed27 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala @@ -240,7 +240,8 @@ abstract class ReachingDefinitions { findDefs(bb, idx, m, 0) override def toString: String = { - method.code.blocks map { b => + if (method eq null) "<null>" + else method.code.blocks map { b => " entry(%s) = %s\n".format(b, in(b)) + " exit(%s) = %s\n".format(b, out(b)) } mkString ("ReachingDefinitions {\n", "\n", "\n}") diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala index 57380db7e7..7a53293384 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package backend.icode.analysis import scala.collection.{mutable, immutable} diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala b/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala index 66aed14d1c..0df828393d 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala @@ -8,7 +8,6 @@ package backend.jvm import java.io.{ DataOutputStream, FileOutputStream, IOException, OutputStream, File => JFile } import scala.tools.nsc.io._ -import scala.tools.nsc.util.ScalaClassLoader import java.util.jar.Attributes.Name import scala.language.postfixOps @@ -38,11 +37,22 @@ trait BytecodeWriters { for (part <- pathParts.init) dir = ensureDirectory(dir) subdirectoryNamed part ensureDirectory(dir) fileNamed pathParts.last + suffix } - private def getFile(sym: Symbol, clsName: String, suffix: String): AbstractFile = + def getFile(sym: Symbol, clsName: String, suffix: String): AbstractFile = getFile(outputDirectory(sym), clsName, suffix) + def factoryNonJarBytecodeWriter(): BytecodeWriter = { + val emitAsmp = settings.Ygenasmp.isSetByUser + val doDump = settings.Ydumpclasses.isSetByUser + (emitAsmp, doDump) match { + case (false, false) => new ClassBytecodeWriter { } + case (false, true ) => new ClassBytecodeWriter with DumpBytecodeWriter { } + case (true, false) => new ClassBytecodeWriter with AsmpBytecodeWriter + case (true, true ) => new ClassBytecodeWriter with AsmpBytecodeWriter with DumpBytecodeWriter { } + } + } + trait BytecodeWriter { - def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], sym: Symbol): Unit + def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], outfile: AbstractFile): Unit def close(): Unit = () } @@ -53,7 +63,9 @@ trait BytecodeWriters { ) val writer = new Jar(jfile).jarWriter(jarMainAttrs: _*) - def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], sym: Symbol) { + def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], outfile: AbstractFile) { + assert(outfile == null, + "The outfile formal param is there just because ClassBytecodeWriter overrides this method and uses it.") val path = jclassName + ".class" val out = writer.newOutputStream(path) @@ -65,9 +77,47 @@ trait BytecodeWriters { override def close() = writer.close() } + /* + * The ASM textual representation for bytecode overcomes disadvantages of javap ouput in three areas: + * (a) pickle dingbats undecipherable to the naked eye; + * (b) two constant pools, while having identical contents, are displayed differently due to physical layout. + * (c) stack maps (classfile version 50 and up) are displayed in encoded form by javap, + * their expansion by ASM is more readable. + * + * */ + trait AsmpBytecodeWriter extends BytecodeWriter { + import scala.tools.asm + + private val baseDir = Directory(settings.Ygenasmp.value).createDirectory() + + private def emitAsmp(jclassBytes: Array[Byte], asmpFile: io.File) { + val pw = asmpFile.printWriter() + try { + val cnode = new asm.tree.ClassNode() + val cr = new asm.ClassReader(jclassBytes) + cr.accept(cnode, 0) + val trace = new scala.tools.asm.util.TraceClassVisitor(new java.io.PrintWriter(new java.io.StringWriter())) + cnode.accept(trace) + trace.p.print(pw) + } + finally pw.close() + } + + abstract override def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], outfile: AbstractFile) { + super.writeClass(label, jclassName, jclassBytes, outfile) + + val segments = jclassName.split("[./]") + val asmpFile = segments.foldLeft(baseDir: Path)(_ / _) changeExtension "asmp" toFile; + + asmpFile.parent.createDirectory() + emitAsmp(jclassBytes, asmpFile) + } + } + trait ClassBytecodeWriter extends BytecodeWriter { - def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], sym: Symbol) { - val outfile = getFile(sym, jclassName, ".class") + def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], outfile: AbstractFile) { + assert(outfile != null, + "Precisely this override requires its invoker to hand out a non-null AbstractFile.") val outstream = new DataOutputStream(outfile.bufferedOutput) try outstream.write(jclassBytes, 0, jclassBytes.length) @@ -79,8 +129,8 @@ trait BytecodeWriters { trait DumpBytecodeWriter extends BytecodeWriter { val baseDir = Directory(settings.Ydumpclasses.value).createDirectory() - abstract override def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], sym: Symbol) { - super.writeClass(label, jclassName, jclassBytes, sym) + abstract override def writeClass(label: String, jclassName: String, jclassBytes: Array[Byte], outfile: AbstractFile) { + super.writeClass(label, jclassName, jclassBytes, outfile) val pathName = jclassName val dumpFile = pathName.split("[./]").foldLeft(baseDir: Path) (_ / _) changeExtension "class" toFile; diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala index 1b183ddd3f..e50b73dcc3 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package backend.jvm import scala.collection.{ mutable, immutable } @@ -51,6 +52,22 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { override def erasedTypes = true def apply(cls: IClass) = sys.error("no implementation") + // An AsmPhase starts and ends within a Run, thus the caches in question will get populated and cleared within a Run, too), SI-7422 + javaNameCache.clear() + javaNameCache ++= List( + NothingClass -> binarynme.RuntimeNothing, + RuntimeNothingClass -> binarynme.RuntimeNothing, + NullClass -> binarynme.RuntimeNull, + RuntimeNullClass -> binarynme.RuntimeNull + ) + + // unlike javaNameCache, reverseJavaName contains entries only for class symbols and their internal names. + reverseJavaName.clear() + reverseJavaName ++= List( + binarynme.RuntimeNothing.toString() -> RuntimeNothingClass, // RuntimeNothingClass is the bytecode-level return type of Scala methods with Nothing return-type. + binarynme.RuntimeNull.toString() -> RuntimeNullClass + ) + // Lazy val; can't have eager vals in Phase constructors which may // cause cycles before Global has finished initialization. lazy val BeanInfoAttr = rootMirror.getRequiredClass("scala.beans.BeanInfo") @@ -75,16 +92,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { new DirectToJarfileWriter(f.file) - case _ => - if (settings.Ydumpclasses.isDefault) - new ClassBytecodeWriter { } - else - new ClassBytecodeWriter with DumpBytecodeWriter { } - // TODO A ScalapBytecodeWriter could take asm.util.Textifier as starting point. - // Three areas where javap ouput is less than ideal (e.g. when comparing versions of the same classfile) are: - // (a) unreadable pickle; - // (b) two constant pools, while having identical contents, are displayed differently due to physical layout. - // (c) stack maps (classfile version 50 and up) are displayed in encoded form by javap, their expansion makes more sense instead. + case _ => factoryNonJarBytecodeWriter() } } @@ -111,9 +119,10 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { debuglog(s"Created new bytecode generator for ${classes.size} classes.") val bytecodeWriter = initBytecodeWriter(sortedClasses filter isJavaEntryPoint) - val plainCodeGen = new JPlainBuilder(bytecodeWriter) - val mirrorCodeGen = new JMirrorBuilder(bytecodeWriter) - val beanInfoCodeGen = new JBeanInfoBuilder(bytecodeWriter) + val needsOutfile = bytecodeWriter.isInstanceOf[ClassBytecodeWriter] + val plainCodeGen = new JPlainBuilder( bytecodeWriter, needsOutfile) + val mirrorCodeGen = new JMirrorBuilder( bytecodeWriter, needsOutfile) + val beanInfoCodeGen = new JBeanInfoBuilder(bytecodeWriter, needsOutfile) def emitFor(c: IClass) { if (isStaticModule(c.symbol) && isTopLevelModule(c.symbol)) { @@ -138,8 +147,6 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { } bytecodeWriter.close() - classes.clear() - reverseJavaName.clear() /* don't javaNameCache.clear() because that causes the following tests to fail: * test/files/run/macro-repl-dontexpand.scala @@ -163,19 +170,10 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { var pickledBytes = 0 // statistics - // Don't put this in per run caches. Contains entries for classes as well as members. - val javaNameCache = new mutable.WeakHashMap[Symbol, Name]() ++= List( - NothingClass -> binarynme.RuntimeNothing, - RuntimeNothingClass -> binarynme.RuntimeNothing, - NullClass -> binarynme.RuntimeNull, - RuntimeNullClass -> binarynme.RuntimeNull - ) + val javaNameCache = perRunCaches.newMap[Symbol, Name]() // unlike javaNameCache, reverseJavaName contains entries only for class symbols and their internal names. - val reverseJavaName = mutable.Map.empty[String, Symbol] ++= List( - binarynme.RuntimeNothing.toString() -> RuntimeNothingClass, // RuntimeNothingClass is the bytecode-level return type of Scala methods with Nothing return-type. - binarynme.RuntimeNull.toString() -> RuntimeNullClass - ) + val reverseJavaName = perRunCaches.newMap[String, Symbol]() private def mkFlags(args: Int*) = args.foldLeft(0)(_ | _) private def hasPublicBitSet(flags: Int) = (flags & asm.Opcodes.ACC_PUBLIC) != 0 @@ -379,7 +377,6 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { private val classfileVersion: Int = settings.target.value match { case "jvm-1.5" => asm.Opcodes.V1_5 - case "jvm-1.5-asm" => asm.Opcodes.V1_5 case "jvm-1.6" => asm.Opcodes.V1_6 case "jvm-1.7" => asm.Opcodes.V1_7 } @@ -407,7 +404,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { } /** basic functionality for class file building */ - abstract class JBuilder(bytecodeWriter: BytecodeWriter) { + abstract class JBuilder(bytecodeWriter: BytecodeWriter, needsOutfile: Boolean) { val EMPTY_STRING_ARRAY = Array.empty[String] @@ -465,7 +462,10 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { def writeIfNotTooBig(label: String, jclassName: String, jclass: asm.ClassWriter, sym: Symbol) { try { val arr = jclass.toByteArray() - bytecodeWriter.writeClass(label, jclassName, arr, sym) + val outF: scala.tools.nsc.io.AbstractFile = { + if(needsOutfile) getFile(sym, jclassName, ".class") else null + } + bytecodeWriter.writeClass(label, jclassName, arr, outF) } catch { case e: java.lang.RuntimeException if(e.getMessage() == "Class file too large!") => // TODO check where ASM throws the equivalent of CodeSizeTooBigException @@ -540,7 +540,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { collectInnerClass(sym) - val hasInternalName = (sym.isClass || (sym.isModule && !sym.isMethod)) + val hasInternalName = sym.isClass || sym.isModuleNotMethod val cachedJN = javaNameCache.getOrElseUpdate(sym, { if (hasInternalName) { sym.javaBinaryName } else { sym.javaSimpleName } @@ -696,7 +696,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { /** functionality for building plain and mirror classes */ - abstract class JCommonBuilder(bytecodeWriter: BytecodeWriter) extends JBuilder(bytecodeWriter) { + abstract class JCommonBuilder(bytecodeWriter: BytecodeWriter, needsOutfile: Boolean) extends JBuilder(bytecodeWriter, needsOutfile) { def debugLevel = settings.debuginfo.indexOfChoice @@ -1246,8 +1246,8 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { case class BlockInteval(start: BasicBlock, end: BasicBlock) /** builder of plain classes */ - class JPlainBuilder(bytecodeWriter: BytecodeWriter) - extends JCommonBuilder(bytecodeWriter) + class JPlainBuilder(bytecodeWriter: BytecodeWriter, needsOutfile: Boolean) + extends JCommonBuilder(bytecodeWriter, needsOutfile) with JAndroidBuilder { val MIN_SWITCH_DENSITY = 0.7 @@ -1625,6 +1625,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { jmethod = clinitMethod jMethodName = CLASS_CONSTRUCTOR_NAME jmethod.visitCode() + computeLocalVarsIndex(m) genCode(m, emitVars = false, isStatic = true) jmethod.visitMaxs(0, 0) // just to follow protocol, dummy arguments jmethod.visitEnd() @@ -2245,13 +2246,6 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { case x :: y :: ys => nextBlock = y; genBlock(x); genBlocks(y :: ys) } - def isAccessibleFrom(target: Symbol, site: Symbol): Boolean = { - target.isPublic || target.isProtected && { - (site.enclClass isSubClass target.enclClass) || - (site.enclosingPackage == target.privateWithin) - } - } // end of genCode()'s isAccessibleFrom() - def genCallMethod(call: CALL_METHOD) { val CALL_METHOD(method, style) = call val siteSymbol = clasz.symbol @@ -2887,7 +2881,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { /** builder of mirror classes */ - class JMirrorBuilder(bytecodeWriter: BytecodeWriter) extends JCommonBuilder(bytecodeWriter) { + class JMirrorBuilder(bytecodeWriter: BytecodeWriter, needsOutfile: Boolean) extends JCommonBuilder(bytecodeWriter, needsOutfile) { private var cunit: CompilationUnit = _ def getCurrentCUnit(): CompilationUnit = cunit @@ -2939,7 +2933,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { /** builder of bean info classes */ - class JBeanInfoBuilder(bytecodeWriter: BytecodeWriter) extends JBuilder(bytecodeWriter) { + class JBeanInfoBuilder(bytecodeWriter: BytecodeWriter, needsOutfile: Boolean) extends JBuilder(bytecodeWriter, needsOutfile) { /** * Generate a bean info class that describes the given class. diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala index 59df8e56c1..2c3bf26958 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala @@ -5,7 +5,6 @@ package scala.tools.nsc package backend.jvm -import scala.tools.nsc.io.AbstractFile import scala.tools.nsc.symtab._ /** Code shared between the erstwhile legacy backend (aka GenJVM) @@ -19,20 +18,6 @@ trait GenJVMASM { import icodes._ import definitions._ - protected def outputDirectory(sym: Symbol): AbstractFile = - settings.outputDirs outputDirFor enteringFlatten(sym.sourceFile) - - protected def getFile(base: AbstractFile, clsName: String, suffix: String): AbstractFile = { - var dir = base - val pathParts = clsName.split("[./]").toList - for (part <- pathParts.init) { - dir = dir.subdirectoryNamed(part) - } - dir.fileNamed(pathParts.last + suffix) - } - protected def getFile(sym: Symbol, clsName: String, suffix: String): AbstractFile = - getFile(outputDirectory(sym), clsName, suffix) - protected val ExcludedForwarderFlags = { import Flags._ // Should include DEFERRED but this breaks findMember. diff --git a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala index aaf2c55dcd..bde17b28fc 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala @@ -71,8 +71,10 @@ abstract class ClosureElimination extends SubComponent { def name = phaseName val closser = new ClosureElim - override def apply(c: IClass): Unit = - closser analyzeClass c + override def apply(c: IClass): Unit = { + if (closser ne null) + closser analyzeClass c + } } /** diff --git a/src/compiler/scala/tools/nsc/backend/opt/ConstantOptimization.scala b/src/compiler/scala/tools/nsc/backend/opt/ConstantOptimization.scala index ff93206ffd..43c8527f41 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/ConstantOptimization.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/ConstantOptimization.scala @@ -3,7 +3,8 @@ * @author James Iry */ -package scala.tools.nsc +package scala +package tools.nsc package backend.opt import scala.tools.nsc.backend.icode.analysis.LubException @@ -17,7 +18,7 @@ import scala.annotation.tailrec * null checks. * * With some more work it could be extended to - * - cache stable values (final fields, modules) in locals + * - cache stable values (final fields, modules) in locals * - replace the copy propagation in ClosureElilmination * - fold constants * - eliminate unnecessary stores and loads @@ -118,18 +119,18 @@ abstract class ConstantOptimization extends SubComponent { * * // left must be 1 or 2, right must be 2 or 3 then we must have a 1, 2 or 3 * Possible(xs) merge Possible(ys) => Possible(xs union ys) - * + * * // Left says can't be 2 or 3, right says can't be 3 or 4 * // then it's not 3 (it could be 2 from the right or 4 from the left) * Impossible(xs) merge Impossible(ys) => Impossible(xs intersect ys) - * + * * // Left says it can't be 2 or 3, right says it must be 3 or 4, then * // it can't be 2 (left rules out 4 and right says 3 is possible) * Impossible(xs) merge Possible(ys) => Impossible(xs -- ys) - * + * * Intuitively, Possible(empty) says that a location can't hold anything, * it's uninitialized. However, Possible(empty) never appears in the code. - * + * * Conversely, Impossible(empty) says nothing is impossible, it could be * anything. Impossible(empty) is given a synonym UNKNOWN and is used * for, e.g., the result of an arbitrary method call. @@ -155,7 +156,7 @@ abstract class ConstantOptimization extends SubComponent { def mightNotEqual(other: Contents): Boolean } private def SingleImpossible(x: Datum) = new Impossible(Set(x)) - + /** * The location is known to have one of a set of values. */ @@ -299,32 +300,32 @@ abstract class ConstantOptimization extends SubComponent { private def interpretInst(in: State, inst: Instruction): State = { // pop the consumed number of values off the `in` state's stack, producing a new state def dropConsumed: State = in drop inst.consumed - + inst match { case THIS(_) => in load THIS_LOCAL - + case CONSTANT(k) => // treat NaN as UNKNOWN because NaN must never equal NaN val const = if (k.isNaN) UNKNOWN else SinglePossible(Const(k)) in push const - + case LOAD_ARRAY_ITEM(_) | LOAD_FIELD(_, _) | CALL_PRIMITIVE(_) => dropConsumed push UNKNOWN case LOAD_LOCAL(local) => // TODO if a local is known to hold a constant then we can replace this instruction with a push of that constant in load local - + case STORE_LOCAL(local) => in store local - + case STORE_THIS(_) => // if a local is already known to have a constant and we're replacing with the same constant then we can // replace this with a drop in store THIS_LOCAL - + case CALL_METHOD(_, _) => // TODO we could special case implementations of equals that are known, e.g. String#equals // We could turn Possible(string constants).equals(Possible(string constants) into an eq check @@ -332,7 +333,7 @@ abstract class ConstantOptimization extends SubComponent { // and eliminate the null check that likely precedes this call val initial = dropConsumed (0 until inst.produced).foldLeft(initial) { case (know, _) => know push UNKNOWN } - + case BOX(_) => val value = in peek 0 // we simulate boxing by, um, boxing the possible/impossible contents @@ -345,7 +346,7 @@ abstract class ConstantOptimization extends SubComponent { case Impossible(values) => Impossible(values map Boxed) } dropConsumed push newValue - + case UNBOX(_) => val value = in peek 0 val newValue = value match { @@ -373,42 +374,42 @@ abstract class ConstantOptimization extends SubComponent { } } dropConsumed push newValue - + case LOAD_MODULE(_) | NEW(_) | LOAD_EXCEPTION(_) => in push NOT_NULL case CREATE_ARRAY(_, _) => dropConsumed push NOT_NULL - + case IS_INSTANCE(_) => // TODO IS_INSTANCE is going to be followed by a C(Z)JUMP // and if IS_INSTANCE/C(Z)JUMP the branch for "true" can // know that whatever was checked was not a null // see the TODO on CJUMP for more information about propagating null // information - // TODO if the top of stack is guaranteed null then we can eliminate this IS_INSTANCE check and + // TODO if the top of stack is guaranteed null then we can eliminate this IS_INSTANCE check and // replace with a constant false, but how often is a knowable null checked for instanceof? // TODO we could track type information and statically know to eliminate IS_INSTANCE // which might be a nice win under specialization dropConsumed push UNKNOWN // it's actually a Possible(true, false) but since the following instruction // will be a conditional jump comparing to true or false there // nothing to be gained by being more precise - + case CHECK_CAST(_) => // TODO we could track type information and statically know to eliminate CHECK_CAST // but that's probably not a huge win in - + case DUP(_) => val value = in peek 0 in push value - + case DROP(_) | MONITOR_ENTER() | MONITOR_EXIT() | STORE_ARRAY_ITEM(_) | STORE_FIELD(_, _) => dropConsumed case SCOPE_ENTER(_) | SCOPE_EXIT(_) => in - + case JUMP(_) | CJUMP(_, _, _, _) | CZJUMP(_, _, _, _) | RETURN(_) | THROW(_) | SWITCH(_, _) => dumpClassesAndAbort("Unexpected block ending instruction: " + inst) } @@ -468,7 +469,7 @@ abstract class ConstantOptimization extends SubComponent { val replacements = if (result.size == 1) List.fill(inst.consumed)(DROP(kind)) :+ JUMP(result.keySet.head) else inst :: Nil - + (result, replacements) } @@ -488,8 +489,7 @@ abstract class ConstantOptimization extends SubComponent { case SWITCH(tags, labels) => val in1 = in peek 0 - val newStuff = tags zip labels filter { case (tagSet, _) => canSwitch(in1, tagSet) } - val (reachableTags, reachableNormalLabels) = (tags zip labels filter { case (tagSet, _) => canSwitch(in1, tagSet) }).unzip + val reachableNormalLabels = tags zip labels collect { case (tagSet, label) if canSwitch(in1, tagSet) => label } val reachableLabels = if (labels.lengthCompare(tags.length) > 0) { // if we've got an extra label then it's the default val defaultLabel = labels.last @@ -533,7 +533,7 @@ abstract class ConstantOptimization extends SubComponent { // number of instructions excluding the last one val normalCount = block.size - 1 - var exceptionState = in.cleanStack + val exceptionState = in.cleanStack var normalExitState = in var idx = 0 while (idx < normalCount) { @@ -569,7 +569,7 @@ abstract class ConstantOptimization extends SubComponent { // worklist of basic blocks to process, initially the start block val worklist = MSet(m.startBlock) - // worklist of exception basic blocks. They're kept in a separate set so they can be + // worklist of exception basic blocks. They're kept in a separate set so they can be // processed after normal flow basic blocks. That's because exception basic blocks // are more likely to have multiple predecessors and queueing them for later // increases the chances that they'll only need to be interpreted once diff --git a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala index 1026e95fac..483bff6467 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala @@ -33,7 +33,7 @@ abstract class DeadCodeElimination extends SubComponent { val dce = new DeadCode() override def apply(c: IClass) { - if (settings.Xdce) + if (settings.Xdce && (dce ne null)) dce.analyzeClass(c) } } diff --git a/src/compiler/scala/tools/nsc/io/Jar.scala b/src/compiler/scala/tools/nsc/io/Jar.scala index ee3e2b04d1..2967f67e9c 100644 --- a/src/compiler/scala/tools/nsc/io/Jar.scala +++ b/src/compiler/scala/tools/nsc/io/Jar.scala @@ -10,7 +10,7 @@ import java.io.{ InputStream, OutputStream, IOException, FileNotFoundException, import java.util.jar._ import scala.collection.JavaConverters._ import Attributes.Name -import scala.language.implicitConversions +import scala.language.{ implicitConversions, postfixOps } // Attributes.Name instances: // diff --git a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala index f1b1d1a9a7..786754ce4c 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala @@ -293,15 +293,8 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { if (in.token == QMARK) { val pos = in.currentPos in.nextToken() - var lo: Tree = TypeTree(NothingClass.tpe) - var hi: Tree = TypeTree(AnyClass.tpe) - if (in.token == EXTENDS) { - in.nextToken() - hi = typ() - } else if (in.token == SUPER) { - in.nextToken() - lo = typ() - } + val hi = if (in.token == EXTENDS) { in.nextToken() ; typ() } else EmptyTree + val lo = if (in.token == SUPER) { in.nextToken() ; typ() } else EmptyTree val tdef = atPos(pos) { TypeDef( Modifiers(Flags.JAVA | Flags.DEFERRED), @@ -408,15 +401,8 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { def typeParam(): TypeDef = atPos(in.currentPos) { val name = identForType() - val hi = - if (in.token == EXTENDS) { - in.nextToken() - bound() - } else { - scalaDot(tpnme.Any) - } - TypeDef(Modifiers(Flags.JAVA | Flags.DEFERRED | Flags.PARAM), name, List(), - TypeBoundsTree(scalaDot(tpnme.Nothing), hi)) + val hi = if (in.token == EXTENDS) { in.nextToken() ; bound() } else EmptyTree + TypeDef(Modifiers(Flags.JAVA | Flags.DEFERRED | Flags.PARAM), name, Nil, TypeBoundsTree(EmptyTree, hi)) } def bound(): Tree = diff --git a/src/compiler/scala/tools/nsc/plugins/Plugins.scala b/src/compiler/scala/tools/nsc/plugins/Plugins.scala index a591482392..8f7794fa90 100644 --- a/src/compiler/scala/tools/nsc/plugins/Plugins.scala +++ b/src/compiler/scala/tools/nsc/plugins/Plugins.scala @@ -30,9 +30,8 @@ trait Plugins { val dirs = (settings.pluginsDir.value split File.pathSeparator).toList map injectDefault map Path.apply val maybes = Plugin.loadAllFrom(jars, dirs, settings.disable.value) val (goods, errors) = maybes partition (_.isSuccess) - errors foreach (_ recover { - case e: Exception => inform(e.getMessage) - }) + // Explicit parameterization of recover to suppress -Xlint warning about inferred Any + errors foreach (_.recover[Any] { case e: Exception => inform(e.getMessage) }) val classes = goods map (_.get) // flatten // Each plugin must only be instantiated once. A common pattern diff --git a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala index bda195f9d3..fdb5c72c3d 100644 --- a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala +++ b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package reporters import java.io.{ BufferedReader, IOException, PrintWriter } diff --git a/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala index 783e249931..c9718f711a 100644 --- a/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.tools.nsc +package scala +package tools.nsc package settings trait AbsScalaSettings { diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index ee9a3aed2a..788aa215be 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala @@ -4,7 +4,8 @@ */ // $Id$ -package scala.tools +package scala +package tools package nsc package settings @@ -156,6 +157,7 @@ trait ScalaSettings extends AbsScalaSettings val Yshowsymkinds = BooleanSetting ("-Yshow-symkinds", "Print abbreviated symbol kinds next to symbol names.") val skip = PhasesSetting ("-Yskip", "Skip") val Ygenjavap = StringSetting ("-Ygen-javap", "dir", "Generate a parallel output directory of .javap files.", "") + val Ygenasmp = StringSetting ("-Ygen-asmp", "dir", "Generate a parallel output directory of .asmp files (ie ASM Textifier output).", "") val Ydumpclasses = StringSetting ("-Ydump-classes", "dir", "Dump the generated bytecode to .class files (useful for reflective compilation that utilizes in-memory classloaders).", "") val Ynosqueeze = BooleanSetting ("-Yno-squeeze", "Disable creation of compact code in matching.") val Ystatistics = BooleanSetting ("-Ystatistics", "Print compiler statistics.") andThen (scala.reflect.internal.util.Statistics.enabled = _) @@ -164,6 +166,7 @@ trait ScalaSettings extends AbsScalaSettings val refinementMethodDispatch = ChoiceSetting ("-Ystruct-dispatch", "policy", "structural method dispatch policy", List("no-cache", "mono-cache", "poly-cache", "invoke-dynamic"), "poly-cache") val Yrangepos = BooleanSetting ("-Yrangepos", "Use range positions for syntax trees.") + val Ymemberpos = StringSetting ("-Yshow-member-pos", "output style", "Show start and end positions of members", "") withPostSetHook (_ => Yrangepos.value = true) val Yreifycopypaste = BooleanSetting ("-Yreify-copypaste", "Dump the reified trees in copypasteable representation.") val Yreplsync = BooleanSetting ("-Yrepl-sync", "Do not use asynchronous code for repl startup") val Yreploutdir = StringSetting ("-Yrepl-outdir", "path", "Write repl-generated classfiles to given output directory (use \"\" to generate a temporary dir)" , "") diff --git a/src/compiler/scala/tools/nsc/settings/ScalaVersion.scala b/src/compiler/scala/tools/nsc/settings/ScalaVersion.scala index d6a0149411..da1cc0c4cf 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaVersion.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaVersion.scala @@ -4,7 +4,8 @@ */ // $Id$ -package scala.tools.nsc.settings +package scala +package tools.nsc.settings /** * Represents a single Scala version in a manner that @@ -19,7 +20,7 @@ abstract class ScalaVersion extends Ordered[ScalaVersion] { */ case object NoScalaVersion extends ScalaVersion { def unparse = "none" - + def compare(that: ScalaVersion): Int = that match { case NoScalaVersion => 0 case _ => 1 @@ -33,7 +34,7 @@ case object NoScalaVersion extends ScalaVersion { * to segregate builds */ case class SpecificScalaVersion(major: Int, minor: Int, rev: Int, build: ScalaBuild) extends ScalaVersion { - def unparse = s"${major}.${minor}.${rev}.${build.unparse}" + def unparse = s"${major}.${minor}.${rev}.${build.unparse}" def compare(that: ScalaVersion): Int = that match { case SpecificScalaVersion(thatMajor, thatMinor, thatRev, thatBuild) => @@ -48,7 +49,7 @@ case class SpecificScalaVersion(major: Int, minor: Int, rev: Int, build: ScalaBu else build compare thatBuild case AnyScalaVersion => 1 case NoScalaVersion => -1 - } + } } /** @@ -56,7 +57,7 @@ case class SpecificScalaVersion(major: Int, minor: Int, rev: Int, build: ScalaBu */ case object AnyScalaVersion extends ScalaVersion { def unparse = "any" - + def compare(that: ScalaVersion): Int = that match { case AnyScalaVersion => 0 case _ => -1 @@ -70,7 +71,7 @@ object ScalaVersion { private val dot = "\\." private val dash = "\\-" private def not(s:String) = s"[^${s}]" - private val R = s"((${not(dot)}*)(${dot}(${not(dot)}*)(${dot}(${not(dash)}*)(${dash}(.*))?)?)?)".r + private val R = s"((${not(dot)}*)(${dot}(${not(dot)}*)(${dot}(${not(dash)}*)(${dash}(.*))?)?)?)".r def apply(versionString : String, errorHandler: String => Unit): ScalaVersion = { def errorAndValue() = { @@ -82,41 +83,41 @@ object ScalaVersion { ) AnyScalaVersion } - + def toInt(s: String) = s match { case null | "" => 0 case _ => s.toInt } - + def isInt(s: String) = util.Try(toInt(s)).isSuccess - + def toBuild(s: String) = s match { case null | "FINAL" => Final case s if (s.toUpperCase.startsWith("RC") && isInt(s.substring(2))) => RC(toInt(s.substring(2))) case s if (s.toUpperCase.startsWith("M") && isInt(s.substring(1))) => Milestone(toInt(s.substring(1))) case _ => Development(s) } - + try versionString match { case "none" => NoScalaVersion case "any" => AnyScalaVersion - case R(_, majorS, _, minorS, _, revS, _, buildS) => + case R(_, majorS, _, minorS, _, revS, _, buildS) => SpecificScalaVersion(toInt(majorS), toInt(minorS), toInt(revS), toBuild(buildS)) - case _ => + case _ => errorAndValue() } catch { case e: NumberFormatException => errorAndValue() } } - - def apply(versionString: String): ScalaVersion = + + def apply(versionString: String): ScalaVersion = apply(versionString, msg => throw new NumberFormatException(msg)) - + /** * The version of the compiler running now */ val current = apply(util.Properties.versionNumberString) - + /** * The 2.8.0 version. */ @@ -126,7 +127,7 @@ object ScalaVersion { /** * Represents the data after the dash in major.minor.rev-build */ -abstract class ScalaBuild extends Ordered[ScalaBuild] { +abstract class ScalaBuild extends Ordered[ScalaBuild] { /** * Return a version of this build information that can be parsed back into the * same ScalaBuild @@ -138,7 +139,7 @@ abstract class ScalaBuild extends Ordered[ScalaBuild] { */ case class Development(id: String) extends ScalaBuild { def unparse = s"-${id}" - + def compare(that: ScalaBuild) = that match { // sorting two development builds based on id is reasonably valid for two versions created with the same schema // otherwise it's not correct, but since it's impossible to put a total ordering on development build versions @@ -154,7 +155,7 @@ case class Development(id: String) extends ScalaBuild { */ case object Final extends ScalaBuild { def unparse = "" - + def compare(that: ScalaBuild) = that match { case Final => 0 // a final is newer than anything other than a development build or another final @@ -168,14 +169,14 @@ case object Final extends ScalaBuild { */ case class RC(n: Int) extends ScalaBuild { def unparse = s"-RC${n}" - + def compare(that: ScalaBuild) = that match { // compare two rcs based on their RC numbers case RC(thatN) => n - thatN // an rc is older than anything other than a milestone or another rc case Milestone(_) => 1 - case _ => -1 - } + case _ => -1 + } } /** @@ -183,12 +184,12 @@ case class RC(n: Int) extends ScalaBuild { */ case class Milestone(n: Int) extends ScalaBuild { def unparse = s"-M${n}" - + def compare(that: ScalaBuild) = that match { // compare two milestones based on their milestone numbers case Milestone(thatN) => n - thatN // a milestone is older than anything other than another milestone case _ => -1 - - } + + } } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index 7cec57968c..42bf0f6b41 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package symtab package classfile @@ -289,9 +290,9 @@ abstract class ClassfileParser { */ private def getNameAndType(index: Int, ownerTpe: Type): (Name, Type) = { if (index <= 0 || len <= index) errorBadIndex(index) - (values(index): @unchecked) match { - case p: ((Name, Type)) => p - case _ => + values(index) match { + case p: ((Name @unchecked, Type @unchecked)) => p + case _ => val start = firstExpecting(index, CONSTANT_NAMEANDTYPE) val name = getName(in.getChar(start).toInt) // create a dummy symbol for method types diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala index 7aaeb56deb..52ebb3b0a2 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala @@ -3,7 +3,8 @@ * @author Iulian Dragos */ -package scala.tools.nsc +package scala +package tools.nsc package symtab package classfile diff --git a/src/compiler/scala/tools/nsc/transform/CleanUp.scala b/src/compiler/scala/tools/nsc/transform/CleanUp.scala index 2ece06c801..d498949b03 100644 --- a/src/compiler/scala/tools/nsc/transform/CleanUp.scala +++ b/src/compiler/scala/tools/nsc/transform/CleanUp.scala @@ -32,19 +32,6 @@ abstract class CleanUp extends Transform with ast.TreeDSL { newStaticInits.clear() symbolsStoredAsStatic.clear() } - private def savingStatics[T](body: => T): T = { - val savedNewStaticMembers : mutable.Buffer[Tree] = newStaticMembers.clone() - val savedNewStaticInits : mutable.Buffer[Tree] = newStaticInits.clone() - val savedSymbolsStoredAsStatic : mutable.Map[String, Symbol] = symbolsStoredAsStatic.clone() - val result = body - - clearStatics() - newStaticMembers ++= savedNewStaticMembers - newStaticInits ++= savedNewStaticInits - symbolsStoredAsStatic ++= savedSymbolsStoredAsStatic - - result - } private def transformTemplate(tree: Tree) = { val Template(_, _, body) = tree clearStatics() diff --git a/src/compiler/scala/tools/nsc/transform/Constructors.scala b/src/compiler/scala/tools/nsc/transform/Constructors.scala index 06367009b6..5079108c27 100644 --- a/src/compiler/scala/tools/nsc/transform/Constructors.scala +++ b/src/compiler/scala/tools/nsc/transform/Constructors.scala @@ -81,7 +81,7 @@ abstract class Constructors extends Transform with ast.TreeDSL { val constrInfo: ConstrInfo = { stats find (_.symbol.isPrimaryConstructor) match { case Some(ddef @ DefDef(_, _, _, List(vparams), _, rhs @ Block(_, _))) => - ConstrInfo(ddef, vparams map (_.symbol), rhs) + ConstrInfo(ddef, vparams map (_.symbol), rhs) case x => // AnyVal constructor is OK assert(clazz eq AnyValClass, "no constructor in template: impl = " + impl) @@ -164,7 +164,8 @@ abstract class Constructors extends Transform with ast.TreeDSL { if (from.name != nme.OUTER || from.tpe.typeSymbol.isPrimitiveValueClass) result else localTyper.typedPos(to.pos) { - IF (from OBJ_EQ NULL) THEN Throw(NewFromConstructor(NPEConstructor)) ELSE result + // `throw null` has the same effect as `throw new NullPointerException`, see JVM spec on instruction `athrow` + IF (from OBJ_EQ NULL) THEN Throw(gen.mkZero(ThrowableClass.tpe)) ELSE result } } @@ -235,7 +236,7 @@ abstract class Constructors extends Transform with ast.TreeDSL { constrStatBuf += intoConstructor(impl.symbol, stat) } - // ----------- avoid making fields for symbols that are not accessed -------------- + // ----------- avoid making parameter-accessor fields for symbols accessed only within the primary constructor -------------- // A sorted set of symbols that are known to be accessed outside the primary constructor. val accessedSyms = new TreeSet[Symbol]((x, y) => x isLess y) @@ -243,6 +244,8 @@ abstract class Constructors extends Transform with ast.TreeDSL { // a list of outer accessor symbols and their bodies var outerAccessors: List[(Symbol, Tree)] = List() + val isDelayedInitSubclass = (clazz isSubClass DelayedInitClass) + // Could symbol's definition be omitted, provided it is not accessed? // This is the case if the symbol is defined in the current class, and // ( the symbol is an object private parameter accessor field, or @@ -250,12 +253,12 @@ abstract class Constructors extends Transform with ast.TreeDSL { def maybeOmittable(sym: Symbol) = sym.owner == clazz && ( sym.isParamAccessor && sym.isPrivateLocal || sym.isOuterAccessor && sym.owner.isEffectivelyFinal && !sym.isOverridingSymbol && - !(clazz isSubClass DelayedInitClass) + !isDelayedInitSubclass ) // Is symbol known to be accessed outside of the primary constructor, // or is it a symbol whose definition cannot be omitted anyway? - def mustbeKept(sym: Symbol) = !maybeOmittable(sym) || (accessedSyms contains sym) + def mustbeKept(sym: Symbol) = isDelayedInitSubclass || !maybeOmittable(sym) || (accessedSyms contains sym) // A traverser to set accessedSyms and outerAccessors val accessTraverser = new Traverser { @@ -379,12 +382,12 @@ abstract class Constructors extends Transform with ast.TreeDSL { * 'specInstance$' is added in phase specialize. */ def guardSpecializedInitializer(stats: List[Tree]): List[Tree] = if (settings.nospecialization.value) stats else { - // split the statements in presuper and postsuper - // var (prefix, postfix) = stats0.span(tree => !((tree.symbol ne null) && tree.symbol.isConstructor)) - // if (postfix.nonEmpty) { - // prefix = prefix :+ postfix.head - //postfix = postfix.tail - //} + // // split the statements in presuper and postsuper + // var (prefix, postfix) = stats0.span(tree => !((tree.symbol ne null) && tree.symbol.isConstructor)) + // if (postfix.nonEmpty) { + // prefix = prefix :+ postfix.head + // postfix = postfix.tail + // } if (usesSpecializedField && shouldGuard && stats.nonEmpty) { // save them for duplication in the specialized subclass @@ -414,76 +417,82 @@ abstract class Constructors extends Transform with ast.TreeDSL { } } else stats } -/* - def isInitDef(stat: Tree) = stat match { - case dd: DefDef => dd.symbol == delayedInitMethod - case _ => false - } -*/ - - /* Create a getter or a setter and enter into `clazz` scope */ - def addAccessor(sym: Symbol, name: TermName, flags: Long) = { - val m = clazz.newMethod(name, sym.pos, flags & ~(LOCAL | PRIVATE)) setPrivateWithin clazz - clazz.info.decls enter m - } - def addGetter(sym: Symbol): Symbol = { - val getr = addAccessor(sym, sym.getterName, getterFlags(sym.flags)) - getr setInfo MethodType(List(), sym.tpe) - defBuf += localTyper.typedPos(sym.pos)(DefDef(getr, Select(This(clazz), sym))) - getr - } - - def addSetter(sym: Symbol): Symbol = { - sym setFlag MUTABLE - val setr = addAccessor(sym, sym.setterName, setterFlags(sym.flags)) - setr setInfo MethodType(setr.newSyntheticValueParams(List(sym.tpe)), UnitClass.tpe) - defBuf += localTyper.typed { - //util.trace("adding setter def for "+setr) { - atPos(sym.pos) { - DefDef(setr, paramss => - Assign(Select(This(clazz), sym), Ident(paramss.head.head))) - }//} - } - setr - } + /* + * Translation scheme for DelayedInit + * ---------------------------------- + * + * Before returning, transformClassTemplate() rewrites DelayedInit subclasses. + * The list of statements that will end up in the primary constructor can be split into: + * + * (a) up to and including the super-constructor call. + * These statements can occur only in the (bytecode-level) primary constructor. + * + * (b) remaining statements + * + * The purpose of DelayedInit is leaving (b) out of the primary constructor and have their execution "delayed". + * + * The rewriting to achieve "delayed initialization" involves: + * (c) an additional, synthetic, public method encapsulating (b) + * (d) an additional, synthetic closure whose argless apply() just invokes (c) + * (e) after executing the statements in (a), + * the primary constructor instantiates (d) and passes it as argument + * to a `delayedInit()` invocation on the current instance. + * In turn, `delayedInit()` is a method defined as abstract in the `DelayedInit` trait + * so that it can be overridden (for an example see `scala.App`) + * + * The following helper methods prepare Trees as part of this rewriting: + * + * (f) `delayedEndpointDef()` prepares (c). + * A transformer, `constrStatTransformer`, is used to re-locate statements (b) from template-level + * to become statements in method (c). The main task here is re-formulating accesses to params + * of the primary constructors (to recap, (c) has zero-params) in terms of param-accessor fields. + * In a Delayed-Init subclass, each class-constructor gets a param-accessor field because `mustbeKept()` forces it. + * + * (g) `delayedInitClosure()` prepares (d) + * + * (h) `delayedInitCall()` prepares the `delayedInit()` invocation referred to in (e) + * + * Both (c) and (d) are added to the Template returned by `transformClassTemplate()` + * + * A note of historic interest: Previously the rewriting for DelayedInit would include in the closure body + * all of the delayed initialization sequence, which in turn required: + * - reformulating "accesses-on-this" into "accesses-on-outer", and + * - adding public getters and setters. + * + * @param stats the statements in (b) above + * + * @return the DefDef for (c) above + * + * */ + def delayedEndpointDef(stats: List[Tree]): DefDef = { - def ensureAccessor(sym: Symbol)(acc: => Symbol) = - if (sym.owner == clazz && !sym.isMethod && sym.isPrivate) { // there's an access to a naked field of the enclosing class - val getr = acc - getr makeNotPrivate clazz - getr - } else { - if (sym.owner == clazz) sym makeNotPrivate clazz - NoSymbol - } + val methodName = currentUnit.freshTermName("delayedEndpoint$" + clazz.fullNameAsName('$').toString + "$") + val methodSym = clazz.newMethod(methodName, impl.pos, SYNTHETIC | FINAL) + methodSym setInfoAndEnter MethodType(Nil, UnitClass.tpe) - def ensureGetter(sym: Symbol): Symbol = ensureAccessor(sym) { - val getr = sym.getter(clazz) - if (getr != NoSymbol) getr else addGetter(sym) - } + // changeOwner needed because the `stats` contained in the DefDef were owned by the template, not long ago. + val blk = Block(stats, gen.mkZero(UnitClass.tpe)).changeOwner(impl.symbol -> methodSym) + val delayedDD = localTyper typed { DefDef(methodSym, Nil, blk) } - def ensureSetter(sym: Symbol): Symbol = ensureAccessor(sym) { - var setr = sym.setter(clazz, hasExpandedName = false) - if (setr == NoSymbol) setr = sym.setter(clazz, hasExpandedName = true) - if (setr == NoSymbol) setr = addSetter(sym) - setr + delayedDD.asInstanceOf[DefDef] } - def delayedInitClosure(stats: List[Tree]) = - localTyper.typed { + /* @see overview at `delayedEndpointDef()` of the translation scheme for DelayedInit */ + def delayedInitClosure(delayedEndPointSym: MethodSymbol): ClassDef = { + val satelliteClass = localTyper.typed { atPos(impl.pos) { val closureClass = clazz.newClass(nme.delayedInitArg.toTypeName, impl.pos, SYNTHETIC | FINAL) val closureParents = List(AbstractFunctionClass(0).tpe) closureClass setInfoAndEnter new ClassInfoType(closureParents, newScope, closureClass) - val outerField = ( + val outerField: TermSymbol = ( closureClass newValue(nme.OUTER, impl.pos, PrivateLocal | PARAMACCESSOR) setInfoAndEnter clazz.tpe ) - val applyMethod = ( + val applyMethod: MethodSymbol = ( closureClass newMethod(nme.apply, impl.pos, FINAL) setInfoAndEnter MethodType(Nil, ObjectClass.tpe) @@ -492,58 +501,32 @@ abstract class Constructors extends Transform with ast.TreeDSL { val closureClassTyper = localTyper.atOwner(closureClass) val applyMethodTyper = closureClassTyper.atOwner(applyMethod) - val constrStatTransformer = new Transformer { - override def transform(tree: Tree): Tree = tree match { - case This(_) if tree.symbol == clazz => - applyMethodTyper.typed { - atPos(tree.pos) { - Select(This(closureClass), outerField) - } - } - case _ => - super.transform { - tree match { - case Select(qual, _) => - val getter = ensureGetter(tree.symbol) - if (getter != NoSymbol) - applyMethodTyper.typed { - atPos(tree.pos) { - Apply(Select(qual, getter), List()) - } - } - else tree - case Assign(lhs @ Select(qual, _), rhs) => - val setter = ensureSetter(lhs.symbol) - if (setter != NoSymbol) - applyMethodTyper.typed { - atPos(tree.pos) { - Apply(Select(qual, setter), List(rhs)) - } - } - else tree - case _ => - tree.changeOwner(impl.symbol -> applyMethod) - } - } + def applyMethodStat = + applyMethodTyper.typed { + atPos(impl.pos) { + val receiver = Select(This(closureClass), outerField) + Apply(Select(receiver, delayedEndPointSym), Nil) + } } - } - - def applyMethodStats = constrStatTransformer.transformTrees(stats) val applyMethodDef = DefDef( sym = applyMethod, vparamss = ListOfNil, - rhs = Block(applyMethodStats, gen.mkAttributedRef(BoxedUnit_UNIT))) + rhs = Block(applyMethodStat, gen.mkAttributedRef(BoxedUnit_UNIT))) ClassDef( sym = closureClass, constrMods = Modifiers(0), vparamss = List(List(outerFieldDef)), - body = List(applyMethodDef), + body = applyMethodDef :: Nil, superPos = impl.pos) } } + satelliteClass.asInstanceOf[ClassDef] + } + + /* @see overview at `delayedEndpointDef()` of the translation scheme for DelayedInit */ def delayedInitCall(closure: Tree) = localTyper.typedPos(impl.pos) { gen.mkMethodCall(This(clazz), delayedInitMethod, Nil, List(New(closure.symbol.tpe, This(clazz)))) } @@ -566,13 +549,18 @@ abstract class Constructors extends Transform with ast.TreeDSL { * See test case files/run/bug4680.scala, the output of which is wrong in many * particulars. */ - val needsDelayedInit = - (clazz isSubClass DelayedInitClass) /*&& !(defBuf exists isInitDef)*/ && remainingConstrStats.nonEmpty + val needsDelayedInit = (isDelayedInitSubclass && remainingConstrStats.nonEmpty) if (needsDelayedInit) { - val dicl = new ConstructorTransformer(unit) transform delayedInitClosure(remainingConstrStats) - defBuf += dicl - remainingConstrStats = List(delayedInitCall(dicl)) + val delayedHook: DefDef = delayedEndpointDef(remainingConstrStats) + defBuf += delayedHook + val hookCallerClass = { + // transform to make the closure-class' default constructor assign the the outer instance to its param-accessor field. + val drillDown = new ConstructorTransformer(unit) + drillDown transform delayedInitClosure(delayedHook.symbol.asInstanceOf[MethodSymbol]) + } + defBuf += hookCallerClass + remainingConstrStats = delayedInitCall(hookCallerClass) :: Nil } // Assemble final constructor @@ -594,12 +582,14 @@ abstract class Constructors extends Transform with ast.TreeDSL { deriveTemplate(impl)(_ => defBuf.toList filter (stat => mustbeKept(stat.symbol))) } // transformClassTemplate - override def transform(tree: Tree): Tree = + override def transform(tree: Tree): Tree = { tree match { case ClassDef(_,_,_,_) if !tree.symbol.isInterface && !isPrimitiveValueClass(tree.symbol) => deriveClassDef(tree)(transformClassTemplate) case _ => super.transform(tree) } + } + } // ConstructorTransformer } diff --git a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala index 1aa5f10738..48263a496e 100644 --- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala +++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package transform import symtab._ @@ -83,7 +84,7 @@ abstract class ExplicitOuter extends InfoTransform else findOrElse(clazz.info.decls)(_.outerSource == clazz)(NoSymbol) } def newOuterAccessor(clazz: Symbol) = { - val accFlags = SYNTHETIC | ARTIFACT | METHOD | STABLE | ( if (clazz.isTrait) DEFERRED else 0 ) + val accFlags = SYNTHETIC | ARTIFACT | STABLE | ( if (clazz.isTrait) DEFERRED else 0 ) val sym = clazz.newMethod(nme.OUTER, clazz.pos, accFlags) val restpe = if (clazz.isTrait) clazz.outerClass.tpe_* else clazz.outerClass.thisType diff --git a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala index 6ff8792a45..868bbb1e42 100644 --- a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala +++ b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala @@ -32,6 +32,21 @@ abstract class LambdaLift extends InfoTransform { } } + /** scala.runtime.*Ref classes */ + private lazy val allRefClasses: Set[Symbol] = { + refClass.values.toSet ++ volatileRefClass.values.toSet ++ Set(VolatileObjectRefClass, ObjectRefClass) + } + + /** Each scala.runtime.*Ref class has a static method `create(value)` that simply instantiates the Ref to carry that value. */ + private lazy val refCreateMethod: Map[Symbol, Symbol] = { + mapFrom(allRefClasses.toList)(x => getMemberMethod(x.companionModule, nme.create)) + } + + /** Quite frequently a *Ref is initialized with its zero (e.g., null, 0.toByte, etc.) Method `zero()` of *Ref class encapsulates that pattern. */ + private lazy val refZeroMethod: Map[Symbol, Symbol] = { + mapFrom(allRefClasses.toList)(x => getMemberMethod(x.companionModule, nme.zero)) + } + def transformInfo(sym: Symbol, tp: Type): Type = if (sym.isCapturedVariable) capturedVariableType(sym, tpe = lifted(tp), erasedTypes = true) else lifted(tp) @@ -444,56 +459,21 @@ abstract class LambdaLift extends InfoTransform { case ValDef(mods, name, tpt, rhs) => if (sym.isCapturedVariable) { val tpt1 = TypeTree(sym.tpe) setPos tpt.pos - /* Creating a constructor argument if one isn't present. */ - val constructorArg = rhs match { - case EmptyTree => - sym.tpe.typeSymbol.primaryConstructor.info.paramTypes match { - case List(tp) => gen.mkZero(tp) - case _ => - debugwarn("Couldn't determine how to properly construct " + sym) - rhs - } - case arg => arg + + val refTypeSym = sym.tpe.typeSymbol + + val factoryCall = typer.typedPos(rhs.pos) { + rhs match { + case EmptyTree => + val zeroMSym = refZeroMethod(refTypeSym) + gen.mkMethodCall(zeroMSym, Nil) + case arg => + val createMSym = refCreateMethod(refTypeSym) + gen.mkMethodCall(createMSym, arg :: Nil) + } } - /* Wrap expr argument in new *Ref(..) constructor. But try/catch - * is a problem because a throw will clear the stack and post catch - * we would expect the partially-constructed object to be on the stack - * for the call to init. So we recursively - * search for "leaf" result expressions where we know its safe - * to put the new *Ref(..) constructor or, if all else fails, transform - * an expr to { val temp=expr; new *Ref(temp) }. - * The reason we narrowly look for try/catch in captured var definitions - * is because other try/catch expression have already been lifted - * see SI-6863 - */ - def refConstr(expr: Tree): Tree = typer.typedPos(expr.pos)(expr match { - // very simple expressions can be wrapped in a new *Ref(expr) because they can't have - // a try/catch in final expression position. - case Ident(_) | Apply(_, _) | Literal(_) | New(_) | Select(_, _) | Throw(_) | Assign(_, _) | ValDef(_, _, _, _) | Return(_) | EmptyTree => - New(sym.tpe, expr) - case Try(block, catches, finalizer) => - Try(refConstr(block), catches map refConstrCase, finalizer) - case Block(stats, expr) => - Block(stats, refConstr(expr)) - case If(cond, trueBranch, falseBranch) => - If(cond, refConstr(trueBranch), refConstr(falseBranch)) - case Match(selector, cases) => - Match(selector, cases map refConstrCase) - // if we can't figure out what else to do, turn expr into {val temp1 = expr; new *Ref(temp1)} to avoid - // any possibility of try/catch in the *Ref constructor. This should be a safe tranformation as a default - // though it potentially wastes a variable slot. In particular this case handles LabelDefs. - case _ => - debuglog("assigning expr to temp: " + (expr.pos)) - val tempSym = currentOwner.newValue(unit.freshTermName("temp"), expr.pos) setInfo expr.tpe - val tempDef = ValDef(tempSym, expr) setPos expr.pos - val tempRef = Ident(tempSym) setPos expr.pos - Block(tempDef, New(sym.tpe, tempRef)) - }) - def refConstrCase(cdef: CaseDef): CaseDef = - CaseDef(cdef.pat, cdef.guard, refConstr(cdef.body)) - - treeCopy.ValDef(tree, mods, name, tpt1, refConstr(constructorArg)) + treeCopy.ValDef(tree, mods, name, tpt1, factoryCall) } else tree case Return(Block(stats, value)) => Block(stats, treeCopy.Return(tree, value)) setType tree.tpe setPos tree.pos diff --git a/src/compiler/scala/tools/nsc/transform/Mixin.scala b/src/compiler/scala/tools/nsc/transform/Mixin.scala index 8774390c8c..7fe7947239 100644 --- a/src/compiler/scala/tools/nsc/transform/Mixin.scala +++ b/src/compiler/scala/tools/nsc/transform/Mixin.scala @@ -34,7 +34,7 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { /** A member of a trait is implemented statically if its implementation after the * mixin transform is in the static implementation module. To be statically * implemented, a member must be a method that belonged to the trait's implementation class - * before (e.g. it is not abstract). Not statically implemented are + * before (i.e. it is not abstract). Not statically implemented are * - non-private modules: these are implemented directly in the mixin composition class * (private modules, on the other hand, are implemented statically, but their * module variable is not. all such private modules are lifted, because @@ -1037,7 +1037,7 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { else if (!clazz.isTrait) { // This needs to be a def to avoid sharing trees def accessedRef = accessedReference(sym) - if (sym.hasAccessorFlag && (!sym.isDeferred || sym.hasFlag(lateDEFERRED))) { + if (isConcreteAccessor(sym)) { // add accessor definitions addDefDef(sym, { if (sym.isSetter) { diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala index 4b00c0efe9..90ca157090 100644 --- a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala +++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala @@ -3,7 +3,8 @@ * @author Iulian Dragos */ -package scala.tools.nsc +package scala +package tools.nsc package transform import scala.tools.nsc.symtab.Flags diff --git a/src/compiler/scala/tools/nsc/transform/TailCalls.scala b/src/compiler/scala/tools/nsc/transform/TailCalls.scala index 313f968e93..6f422fcc90 100644 --- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala +++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala @@ -3,7 +3,8 @@ * @author Iulian Dragos */ -package scala.tools.nsc +package scala +package tools.nsc package transform import symtab.Flags @@ -87,98 +88,112 @@ abstract class TailCalls extends Transform { * </p> */ class TailCallElimination(unit: CompilationUnit) extends Transformer { - private val defaultReason = "it contains a recursive call not in tail position" + private def defaultReason = "it contains a recursive call not in tail position" + private val failPositions = perRunCaches.newMap[TailContext, Position]() withDefault (_.methodPos) + private val failReasons = perRunCaches.newMap[TailContext, String]() withDefaultValue defaultReason + private def tailrecFailure(ctx: TailContext) { + val method = ctx.method + val failReason = failReasons(ctx) + val failPos = failPositions(ctx) + + unit.error(failPos, s"could not optimize @tailrec annotated $method: $failReason") + } /** Has the label been accessed? Then its symbol is in this set. */ - private val accessed = new scala.collection.mutable.HashSet[Symbol]() + private val accessed = perRunCaches.newSet[Symbol]() // `accessed` was stored as boolean in the current context -- this is no longer tenable // with jumps to labels in tailpositions now considered in tailposition, // a downstream context may access the label, and the upstream one will be none the wiser // this is necessary because tail-calls may occur in places where syntactically they seem impossible // (since we now consider jumps to labels that are in tailposition, such as matchEnd(x) {x}) + sealed trait TailContext { + def method: Symbol // current method + def tparams: List[Symbol] // type parameters + def methodPos: Position // default position for failure reporting + def tailPos: Boolean // context is in tail position + def label: Symbol // new label, tail call target + def tailLabels: Set[Symbol] + + def enclosingType = method.enclClass.typeOfThis + def isEligible = method.isEffectivelyFinal + def isMandatory = method.hasAnnotation(TailrecClass) + def isTransformed = isEligible && accessed(label) + + def newThis(pos: Position) = { + def msg = "Creating new `this` during tailcalls\n method: %s\n current class: %s".format( + method.ownerChain.mkString(" -> "), + currentClass.ownerChain.mkString(" -> ") + ) + logResult(msg)(method.newValue(nme.THIS, pos, SYNTHETIC) setInfo currentClass.typeOfThis) + } + override def toString = s"${method.name} tparams=$tparams tailPos=$tailPos label=$label label info=${label.info}" + } - class Context() { - /** The current method */ - var method: Symbol = NoSymbol - - // symbols of label defs in this method that are in tail position - var tailLabels: Set[Symbol] = Set() - - /** The current tail-call label */ - var label: Symbol = NoSymbol - - /** The expected type arguments of self-recursive calls */ - var tparams: List[Symbol] = Nil - - /** Tells whether we are in a (possible) tail position */ - var tailPos = false - - /** The reason this method could not be optimized. */ - var failReason = defaultReason - var failPos = method.pos + object EmptyTailContext extends TailContext { + def method = NoSymbol + def tparams = Nil + def methodPos = NoPosition + def tailPos = false + def label = NoSymbol + def tailLabels = Set.empty[Symbol] + } - def this(that: Context) = { - this() - this.method = that.method - this.tparams = that.tparams - this.tailPos = that.tailPos - this.failPos = that.failPos - this.label = that.label - this.tailLabels = that.tailLabels + class DefDefTailContext(dd: DefDef) extends TailContext { + def method = dd.symbol + def tparams = dd.tparams map (_.symbol) + def methodPos = dd.pos + def tailPos = true + + lazy val label = mkLabel() + lazy val tailLabels = { + // labels are local to a method, so only traverse the rhs of a defdef + val collector = new TailPosLabelsTraverser + collector traverse dd.rhs + collector.tailLabels.toSet } - def this(dd: DefDef) { - this() - this.method = dd.symbol - this.tparams = dd.tparams map (_.symbol) - this.tailPos = true - this.failPos = dd.pos - - /* Create a new method symbol for the current method and store it in - * the label field. - */ - this.label = { - val label = method.newLabel(newTermName("_" + method.name), method.pos) - val thisParam = method.newSyntheticValueParam(currentClass.typeOfThis) - label setInfo MethodType(thisParam :: method.tpe.params, method.tpe.finalResultType) - } + + private def mkLabel() = { + val label = method.newLabel(newTermName("_" + method.name), method.pos) + val thisParam = method.newSyntheticValueParam(currentClass.typeOfThis) + label setInfo MethodType(thisParam :: method.tpe.params, method.tpe.finalResultType) if (isEligible) label substInfo (method.tpe.typeParams, tparams) - } - - def enclosingType = method.enclClass.typeOfThis - def isEligible = method.isEffectivelyFinal - // @tailrec annotation indicates mandatory transformation - def isMandatory = method.hasAnnotation(TailrecClass) - def isTransformed = isEligible && accessed(label) - def tailrecFailure() = unit.error(failPos, "could not optimize @tailrec annotated " + method + ": " + failReason) - def newThis(pos: Position) = logResult("Creating new `this` during tailcalls\n method: %s\n current class: %s".format( - method.ownerChain.mkString(" -> "), currentClass.ownerChain.mkString(" -> "))) { - method.newValue(nme.THIS, pos, SYNTHETIC) setInfo currentClass.typeOfThis + label } - - override def toString(): String = ( - "" + method.name + " tparams: " + tparams + " tailPos: " + tailPos + - " Label: " + label + " Label type: " + label.info - ) + private def isRecursiveCall(t: Tree) = { + val receiver = t.symbol + + ( (receiver != null) + && receiver.isMethod + && (method.name == receiver.name) + && (method.enclClass isSubClass receiver.enclClass) + ) + } + def containsRecursiveCall(t: Tree) = t exists isRecursiveCall } - - private var ctx: Context = new Context() - private def noTailContext() = { - val t = new Context(ctx) - t.tailPos = false - t + class ClonedTailContext(that: TailContext, override val tailPos: Boolean) extends TailContext { + def method = that.method + def tparams = that.tparams + def methodPos = that.methodPos + def tailLabels = that.tailLabels + def label = that.label } + private var ctx: TailContext = EmptyTailContext + private def noTailContext() = new ClonedTailContext(ctx, tailPos = false) + private def yesTailContext() = new ClonedTailContext(ctx, tailPos = true) + /** Rewrite this tree to contain no tail recursive calls */ - def transform(tree: Tree, nctx: Context): Tree = { + def transform(tree: Tree, nctx: TailContext): Tree = { val saved = ctx ctx = nctx try transform(tree) finally this.ctx = saved } + def yesTailTransform(tree: Tree): Tree = transform(tree, yesTailContext()) def noTailTransform(tree: Tree): Tree = transform(tree, noTailContext()) def noTailTransforms(trees: List[Tree]) = { val nctx = noTailContext() @@ -192,7 +207,6 @@ abstract class TailCalls extends Transform { case Select(qual, _) => qual case _ => EmptyTree } - def receiverIsSame = ctx.enclosingType.widen =:= receiver.tpe.widen def receiverIsSuper = ctx.enclosingType.widen <:< receiver.tpe.widen def isRecursiveCall = (ctx.method eq fun.symbol) && ctx.tailPos @@ -204,18 +218,16 @@ abstract class TailCalls extends Transform { */ def fail(reason: String) = { debuglog("Cannot rewrite recursive call at: " + fun.pos + " because: " + reason) - - ctx.failReason = reason + failReasons(ctx) = reason treeCopy.Apply(tree, noTailTransform(target), transformArgs) } /* Position of failure is that of the tree being considered. */ def failHere(reason: String) = { - ctx.failPos = fun.pos + failPositions(ctx) = fun.pos fail(reason) } def rewriteTailCall(recv: Tree): Tree = { debuglog("Rewriting tail recursive call: " + fun.pos.lineContent.trim) - accessed += ctx.label typedPos(fun.pos) { val args = mapWithIndex(transformArgs)((arg, i) => mkAttributedCastHack(arg, ctx.label.info.params(i + 1).tpe)) @@ -225,7 +237,7 @@ abstract class TailCalls extends Transform { if (!ctx.isEligible) fail("it is neither private nor final so can be overridden") else if (!isRecursiveCall) { - if (receiverIsSuper) failHere("it contains a recursive call targeting supertype " + receiver.tpe) + if (receiverIsSuper) failHere("it contains a recursive call targeting a supertype") else failHere(defaultReason) } else if (!matchesTypeArgs) failHere("it is called recursively with different type arguments") @@ -241,37 +253,23 @@ abstract class TailCalls extends Transform { super.transform(tree) - case dd @ DefDef(_, _, _, vparamss0, _, rhs0) if !dd.symbol.hasAccessorFlag => - val newCtx = new Context(dd) - def isRecursiveCall(t: Tree) = { - val sym = t.symbol - (sym != null) && { - sym.isMethod && (dd.symbol.name == sym.name) && (dd.symbol.enclClass isSubClass sym.enclClass) - } - } - if (newCtx.isMandatory) { - if (!rhs0.exists(isRecursiveCall)) { - unit.error(tree.pos, "@tailrec annotated method contains no recursive calls") - } - } - - // labels are local to a method, so only traverse the rhs of a defdef - val collectTailPosLabels = new TailPosLabelsTraverser - collectTailPosLabels traverse rhs0 - newCtx.tailLabels = collectTailPosLabels.tailLabels.toSet + case dd @ DefDef(_, name, _, vparamss0, _, rhs0) if !dd.symbol.hasAccessorFlag => + val newCtx = new DefDefTailContext(dd) + if (newCtx.isMandatory && !(newCtx containsRecursiveCall rhs0)) + unit.error(tree.pos, "@tailrec annotated method contains no recursive calls") - debuglog("Considering " + dd.name + " for tailcalls, with labels in tailpos: "+ newCtx.tailLabels) + debuglog(s"Considering $name for tailcalls, with labels in tailpos: ${newCtx.tailLabels}") val newRHS = transform(rhs0, newCtx) - deriveDefDef(tree){rhs => + deriveDefDef(tree) { rhs => if (newCtx.isTransformed) { /* We have rewritten the tree, but there may be nested recursive calls remaining. * If @tailrec is given we need to fail those now. */ if (newCtx.isMandatory) { for (t @ Apply(fn, _) <- newRHS ; if fn.symbol == newCtx.method) { - newCtx.failPos = t.pos - newCtx.tailrecFailure() + failPositions(newCtx) = t.pos + tailrecFailure(newCtx) } } val newThis = newCtx.newThis(tree.pos) @@ -283,8 +281,8 @@ abstract class TailCalls extends Transform { )) } else { - if (newCtx.isMandatory && newRHS.exists(isRecursiveCall)) - newCtx.tailrecFailure() + if (newCtx.isMandatory && (newCtx containsRecursiveCall newRHS)) + tailrecFailure(newCtx) newRHS } @@ -345,27 +343,25 @@ abstract class TailCalls extends Transform { case Apply(tapply @ TypeApply(fun, targs), vargs) => rewriteApply(tapply, fun, targs, vargs) - case Apply(fun, args) => - if (fun.symbol == Boolean_or || fun.symbol == Boolean_and) - treeCopy.Apply(tree, fun, transformTrees(args)) - else if (fun.symbol.isLabel && args.nonEmpty && args.tail.isEmpty && ctx.tailLabels(fun.symbol)) { - // this is to detect tailcalls in translated matches - // it's a one-argument call to a label that is in a tailposition and that looks like label(x) {x} - // thus, the argument to the call is in tailposition - val saved = ctx.tailPos - ctx.tailPos = true - debuglog("in tailpos label: "+ args.head) - val res = transform(args.head) - ctx.tailPos = saved - if (res ne args.head) { - // we tail-called -- TODO: shield from false-positives where we rewrite but don't tail-call - // must leave the jump to the original tailpos-label (fun)! - // there might be *a* tailcall *in* res, but it doesn't mean res *always* tailcalls - treeCopy.Apply(tree, fun, List(res)) - } - else rewriteApply(fun, fun, Nil, args) - } else rewriteApply(fun, fun, Nil, args) + case Apply(fun, args) if fun.symbol == Boolean_or || fun.symbol == Boolean_and => + treeCopy.Apply(tree, fun, transformTrees(args)) + + // this is to detect tailcalls in translated matches + // it's a one-argument call to a label that is in a tailposition and that looks like label(x) {x} + // thus, the argument to the call is in tailposition + case Apply(fun, args @ (arg :: Nil)) if fun.symbol.isLabel && ctx.tailLabels(fun.symbol) => + debuglog(s"in tailpos label: $arg") + val res = yesTailTransform(arg) + // we tail-called -- TODO: shield from false-positives where we rewrite but don't tail-call + // must leave the jump to the original tailpos-label (fun)! + // there might be *a* tailcall *in* res, but it doesn't mean res *always* tailcalls + if (res ne arg) + treeCopy.Apply(tree, fun, res :: Nil) + else + rewriteApply(fun, fun, Nil, args) + case Apply(fun, args) => + rewriteApply(fun, fun, Nil, args) case Alternative(_) | Star(_) | Bind(_, _) => sys.error("We should've never gotten inside a pattern") case Select(qual, name) => diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 2f5cb23abb..d7be0ed180 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -3,7 +3,8 @@ * @author */ -package scala.tools.nsc +package scala +package tools.nsc package transform import symtab.Flags._ @@ -470,7 +471,7 @@ abstract class UnCurry extends InfoTransform val fn1 = withInPattern(value = false)(transform(fn)) val args1 = transformTrees(fn.symbol.name match { case nme.unapply => args - case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeList(fn.pos, fn.symbol, fn.tpe, args.length)) + case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeList(fn.pos, fn.symbol, fn.tpe, args)) case _ => sys.error("internal error: UnApply node has wrong symbol") }) treeCopy.UnApply(tree, fn1, args1) diff --git a/src/compiler/scala/tools/nsc/transform/patmat/Logic.scala b/src/compiler/scala/tools/nsc/transform/patmat/Logic.scala index 92b7700c04..069484ff65 100644 --- a/src/compiler/scala/tools/nsc/transform/patmat/Logic.scala +++ b/src/compiler/scala/tools/nsc/transform/patmat/Logic.scala @@ -4,7 +4,8 @@ * @author Adriaan Moors */ -package scala.tools.nsc.transform.patmat +package scala +package tools.nsc.transform.patmat import scala.language.postfixOps import scala.collection.mutable @@ -384,18 +385,35 @@ trait ScalaLogic extends Interface with Logic with TreeAndTypeAnalysis { // else debug.patmat("NOT implies: "+(lower, upper)) - /* does V = C preclude V having value `other`? - (1) V = null is an exclusive assignment, - (2) V = A and V = B, for A and B value constants, are mutually exclusive unless A == B - we err on the safe side, for example: - - assume `val X = 1; val Y = 1`, then - (2: Int) match { case X => case Y => <falsely considered reachable> } - - V = 1 does not preclude V = Int, or V = Any, it could be said to preclude V = String, but we don't model that - - (3) for types we could try to do something fancy, but be conservative and just say no + /** Does V=A preclude V=B? + * + * (0) A or B must be in the domain to draw any conclusions. + * + * For example, knowing the the scrutinee is *not* true does not + * statically exclude it from being `X`, because that is an opaque + * Boolean. + * + * val X = true + * (true: Boolean) match { case true => case X <reachable> } + * + * (1) V = null excludes assignment to any other constant (modulo point #0). This includes + * both values and type tests (which are both modelled here as `Const`) + * (2) V = A and V = B, for A and B domain constants, are mutually exclusive unless A == B + * + * (3) We only reason about test tests as being excluded by null assignments, otherwise we + * only consider value assignments. + * TODO: refine this, a == 0 excludes a: String, or `a: Int` excludes `a: String` + * (since no value can be of both types. See also SI-7211) + * + * NOTE: V = 1 does not preclude V = Int, or V = Any, it could be said to preclude + * V = String, but we don't model that. */ - def excludes(a: Const, b: Const): Boolean = - a != b && ((a == NullConst || b == NullConst) || (a.isValue && b.isValue)) + def excludes(a: Const, b: Const): Boolean = { + val bothInDomain = domain exists (d => d(a) && d(b)) + val eitherIsNull = a == NullConst || b == NullConst + val bothAreValues = a.isValue && b.isValue + bothInDomain && (eitherIsNull || bothAreValues) && (a != b) + } // if(r) debug.patmat("excludes : "+(a, a.tp, b, b.tp)) // else debug.patmat("NOT excludes: "+(a, b)) diff --git a/src/compiler/scala/tools/nsc/transform/patmat/Solving.scala b/src/compiler/scala/tools/nsc/transform/patmat/Solving.scala index a0fb6e82fc..3c7dc79636 100644 --- a/src/compiler/scala/tools/nsc/transform/patmat/Solving.scala +++ b/src/compiler/scala/tools/nsc/transform/patmat/Solving.scala @@ -8,6 +8,7 @@ package scala.tools.nsc.transform.patmat import scala.collection.mutable import scala.reflect.internal.util.Statistics +import scala.language.postfixOps // naive CNF translation and simple DPLL solver trait Solving extends Logic { diff --git a/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala b/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala index 65bfd8e34e..56ed0ee16c 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package typechecker import java.lang.ArithmeticException diff --git a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala index 89fc55bc2c..61cdb63ac9 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala @@ -21,47 +21,65 @@ trait ContextErrors { import global._ import definitions._ - object ErrorKinds extends Enumeration { - type ErrorKind = Value - val Normal, Access, Ambiguous, Divergent = Value - } - - import ErrorKinds.ErrorKind - - trait AbsTypeError extends Throwable { + abstract class AbsTypeError extends Throwable { def errPos: Position def errMsg: String - def kind: ErrorKind + override def toString() = "[Type error at:" + errPos + "] " + errMsg } - case class NormalTypeError(underlyingTree: Tree, errMsg: String, kind: ErrorKind = ErrorKinds.Normal) - extends AbsTypeError { - - def errPos:Position = underlyingTree.pos - override def toString() = "[Type error at:" + underlyingTree.pos + "] " + errMsg + abstract class TreeTypeError extends AbsTypeError { + def underlyingTree: Tree + def errPos = underlyingTree.pos } - case class SymbolTypeError(underlyingSym: Symbol, errMsg: String, kind: ErrorKind = ErrorKinds.Normal) + case class NormalTypeError(underlyingTree: Tree, errMsg: String) + extends TreeTypeError + + case class AccessTypeError(underlyingTree: Tree, errMsg: String) + extends TreeTypeError + + case class AmbiguousTypeError(errPos: Position, errMsg: String) + extends AbsTypeError + + case class SymbolTypeError(underlyingSym: Symbol, errMsg: String) extends AbsTypeError { def errPos = underlyingSym.pos } - case class TypeErrorWrapper(ex: TypeError, kind: ErrorKind = ErrorKinds.Normal) + case class TypeErrorWrapper(ex: TypeError) extends AbsTypeError { def errMsg = ex.msg def errPos = ex.pos } - case class TypeErrorWithUnderlyingTree(tree: Tree, ex: TypeError, kind: ErrorKind = ErrorKinds.Normal) + case class TypeErrorWithUnderlyingTree(tree: Tree, ex: TypeError) extends AbsTypeError { def errMsg = ex.msg def errPos = tree.pos } - case class AmbiguousTypeError(underlyingTree: Tree, errPos: Position, errMsg: String, kind: ErrorKind = ErrorKinds.Ambiguous) extends AbsTypeError + // Unlike other type errors diverging implicit expansion + // will be re-issued explicitly on failed implicit argument search. + // This is because we want to: + // 1) provide better error message than just "implicit not found" + // 2) provide the type of the implicit parameter for which we got diverging expansion + // (pt at the point of divergence gives less information to the user) + // Note: it is safe to delay error message generation in this case + // becasue we don't modify implicits' infos. + case class DivergentImplicitTypeError(underlyingTree: Tree, pt0: Type, sym: Symbol) + extends TreeTypeError { + def errMsg: String = errMsgForPt(pt0) + def withPt(pt: Type): AbsTypeError = this.copy(pt0 = pt) + private def errMsgForPt(pt: Type) = + s"diverging implicit expansion for type ${pt}\nstarting with ${sym.fullLocationString}" + } - case class PosAndMsgTypeError(errPos: Position, errMsg: String, kind: ErrorKind = ErrorKinds.Normal) extends AbsTypeError + case class AmbiguousImplicitTypeError(underlyingTree: Tree, errMsg: String) + extends TreeTypeError + + case class PosAndMsgTypeError(errPos: Position, errMsg: String) + extends AbsTypeError object ErrorUtils { def issueNormalTypeError(tree: Tree, msg: String)(implicit context: Context) { @@ -72,10 +90,6 @@ trait ContextErrors { issueTypeError(SymbolTypeError(sym, msg)) } - def issueDivergentImplicitsError(tree: Tree, msg: String)(implicit context: Context) { - issueTypeError(NormalTypeError(tree, msg, ErrorKinds.Divergent)) - } - def issueAmbiguousTypeError(pre: Type, sym1: Symbol, sym2: Symbol, err: AmbiguousTypeError)(implicit context: Context) { context.issueAmbiguousError(pre, sym1, sym2, err) } @@ -592,6 +606,10 @@ trait ContextErrors { setError(tree) } + // typedPattern + def PatternMustBeValue(pat: Tree, pt: Type) = + issueNormalTypeError(pat, s"pattern must be a value: $pat"+ typePatternAdvice(pat.tpe.typeSymbol, pt.typeSymbol)) + // SelectFromTypeTree def TypeSelectionFromVolatileTypeError(tree: Tree, qual: Tree) = { val hiBound = qual.tpe.bounds.hi @@ -830,7 +848,7 @@ trait ContextErrors { underlyingSymbol(sym).fullLocationString + " cannot be accessed in " + location + explanation } - NormalTypeError(tree, errMsg, ErrorKinds.Access) + AccessTypeError(tree, errMsg) } def NoMethodInstanceError(fn: Tree, args: List[Tree], msg: String) = @@ -875,7 +893,7 @@ trait ContextErrors { "argument types " + argtpes.mkString("(", ",", ")") + (if (pt == WildcardType) "" else " and expected result type " + pt) val (pos, msg) = ambiguousErrorMsgPos(tree.pos, pre, best, firstCompeting, msg0) - issueAmbiguousTypeError(pre, best, firstCompeting, AmbiguousTypeError(tree, pos, msg)) + issueAmbiguousTypeError(pre, best, firstCompeting, AmbiguousTypeError(pos, msg)) setErrorOnLastTry(lastTry, tree) } else setError(tree) // do not even try further attempts because they should all fail // even if this is not the last attempt (because of the SO's possibility on the horizon) @@ -889,7 +907,7 @@ trait ContextErrors { def AmbiguousExprAlternativeError(tree: Tree, pre: Type, best: Symbol, firstCompeting: Symbol, pt: Type, lastTry: Boolean) = { val (pos, msg) = ambiguousErrorMsgPos(tree.pos, pre, best, firstCompeting, "expected type " + pt) - issueAmbiguousTypeError(pre, best, firstCompeting, AmbiguousTypeError(tree, pos, msg)) + issueAmbiguousTypeError(pre, best, firstCompeting, AmbiguousTypeError(pos, msg)) setErrorOnLastTry(lastTry, tree) } @@ -937,33 +955,10 @@ trait ContextErrors { def IncompatibleScrutineeTypeError(tree: Tree, pattp: Type, pt: Type) = issueNormalTypeError(tree, "scrutinee is incompatible with pattern type" + foundReqMsg(pattp, pt)) - def PatternTypeIncompatibleWithPtError2(pat: Tree, pt1: Type, pt: Type) = { - def errMsg = { - val sym = pat.tpe.typeSymbol - val clazz = sym.companionClass - val addendum = ( - if (sym.isModuleClass && clazz.isCaseClass && (clazz isSubClass pt1.typeSymbol)) { - // TODO: move these somewhere reusable. - val typeString = clazz.typeParams match { - case Nil => "" + clazz.name - case xs => xs map (_ => "_") mkString (clazz.name + "[", ",", "]") - } - val caseString = ( - clazz.caseFieldAccessors - map (_ => "_") // could use the actual param names here - mkString (clazz.name + "(", ",", ")") - ) - ( - "\nNote: if you intended to match against the class, try `case _: " + - typeString + "` or `case " + caseString + "`" - ) - } - else "" - ) - "pattern type is incompatible with expected type"+foundReqMsg(pat.tpe, pt) + addendum - } - issueNormalTypeError(pat, errMsg) - } + def PatternTypeIncompatibleWithPtError2(pat: Tree, pt1: Type, pt: Type) = + issueNormalTypeError(pat, + "pattern type is incompatible with expected type"+ foundReqMsg(pat.tpe, pt) + + typePatternAdvice(pat.tpe.typeSymbol, pt1.typeSymbol)) def PolyAlternativeError(tree: Tree, argtypes: List[Type], sym: Symbol, err: PolyAlternativeErrorKind.ErrorType) = { import PolyAlternativeErrorKind._ @@ -1174,7 +1169,7 @@ trait ContextErrors { if (explanation == "") "" else "\n" + explanation ) } - context.issueAmbiguousError(AmbiguousTypeError(tree, tree.pos, + context.issueAmbiguousError(AmbiguousImplicitTypeError(tree, if (isView) viewMsg else s"ambiguous implicit values:\n${coreMsg}match expected type $pt") ) @@ -1182,9 +1177,7 @@ trait ContextErrors { } def DivergingImplicitExpansionError(tree: Tree, pt: Type, sym: Symbol)(implicit context0: Context) = - issueDivergentImplicitsError(tree, - "diverging implicit expansion for type "+pt+"\nstarting with "+ - sym.fullLocationString) + issueTypeError(DivergentImplicitTypeError(tree, pt, sym)) } object NamesDefaultsErrorsGen { diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala index 949cd13520..e3bb595bd7 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package typechecker -import scala.collection.mutable +import scala.collection.{ immutable, mutable } import scala.annotation.tailrec import scala.reflect.internal.util.shortClassOfInstance @@ -17,15 +17,20 @@ import scala.reflect.internal.util.shortClassOfInstance trait Contexts { self: Analyzer => import global._ import definitions.{ JavaLangPackage, ScalaPackage, PredefModule } + import ContextMode._ - object NoContext extends Context { - outer = this + object NoContext + extends Context(EmptyTree, NoSymbol, EmptyScope, NoCompilationUnit, + null) { // We can't pass the uninitialized `this`. Instead, we treat null specially in `Context#outer` enclClass = this enclMethod = this + override val depth = 0 override def nextEnclosing(p: Context => Boolean): Context = this override def enclosingContextChain: List[Context] = Nil override def implicitss: List[List[ImplicitInfo]] = Nil + override def imports: List[ImportInfo] = Nil + override def firstImport: Option[ImportInfo] = None override def toString = "NoContext" } private object RootImports { @@ -88,280 +93,351 @@ trait Contexts { self: Analyzer => else RootImports.completeList } - def rootContext(unit: CompilationUnit): Context = rootContext(unit, EmptyTree, erasedTypes = false) - def rootContext(unit: CompilationUnit, tree: Tree): Context = rootContext(unit, tree, erasedTypes = false) - def rootContext(unit: CompilationUnit, tree: Tree, erasedTypes: Boolean): Context = { - var sc = startContext - for (sym <- rootImports(unit)) { - sc = sc.makeNewImport(sym) - sc.depth += 1 - } - val c = sc.make(unit, tree, sc.owner, sc.scope, sc.imports) + def rootContext(unit: CompilationUnit, tree: Tree = EmptyTree, erasedTypes: Boolean = false): Context = { + val rootImportsContext = (startContext /: rootImports(unit))((c, sym) => c.make(gen.mkWildcardImport(sym))) + val c = rootImportsContext.make(tree, unit = unit) if (erasedTypes) c.setThrowErrors() else c.setReportErrors() - c.implicitsEnabled = !erasedTypes - c.enrichmentEnabled = c.implicitsEnabled + c(EnrichmentEnabled | ImplicitsEnabled) = !erasedTypes c } def resetContexts() { - var sc = startContext - while (sc != NoContext) { - sc.tree match { + startContext.enclosingContextChain foreach { context => + context.tree match { case Import(qual, _) => qual setType singleType(qual.symbol.owner.thisType, qual.symbol) case _ => } - sc.flushAndReturnBuffer() - sc.flushAndReturnWarningsBuffer() - sc = sc.outer + context.reportBuffer.clearAll() } } - private object Errors { - final val ReportErrors = 1 << 0 - final val BufferErrors = 1 << 1 - final val AmbiguousErrors = 1 << 2 - final val notThrowMask = ReportErrors | BufferErrors - final val AllMask = ReportErrors | BufferErrors | AmbiguousErrors - } + /** + * A motley collection of the state and loosely associated behaviour of the type checker. + * Each `Typer` has an associated context, and as it descends into the tree new `(Typer, Context)` + * pairs are spawned. + * + * Meet the crew; first the state: + * + * - A tree, symbol, and scope representing the focus of the typechecker + * - An enclosing context, `outer`. + * - The current compilation unit. + * - A variety of bits that track the current error reporting policy (more on this later); + * whether or not implicits/macros are enabled, whether we are in a self or super call or + * in a constructor suffix. These are represented as bits in the mask `contextMode`. + * - Some odds and ends: undetermined type pararameters of the current line of type inference; + * contextual augmentation for error messages, tracking of the nesting depth. + * + * And behaviour: + * + * - The central point for issuing errors and warnings from the typechecker, with a means + * to buffer these for use in 'silent' type checking, when some recovery might be possible. + * - `Context` is something of a Zipper for the tree were are typechecking: it `enclosingContextChain` + * is the path back to the root. This is exactly what we need to resolve names (`lookupSymbol`) + * and to collect in-scope implicit defintions (`implicitss`) + * Supporting these are `imports`, which represents all `Import` trees in in the enclosing context chain. + * - In a similar vein, we can assess accessiblity (`isAccessible`.) + * + * More on error buffering: + * When are type errors recoverable? In quite a few places, it turns out. Some examples: + * trying to type an application with/without the expected type, or with/without implicit views + * enabled. This is usually mediated by `Typer.silent`, `Inferencer#tryTwice`. + * + * Intially, starting from the `typer` phase, the contexts either buffer or report errors; + * afterwards errors are thrown. This is configured in `rootContext`. Additionally, more + * fine grained control is needed based on the kind of error; ambiguity errors are often + * suppressed during exploraratory typing, such as determining whether `a == b` in an argument + * position is an assignment or a named argument, when `Infererencer#isApplicableSafe` type checks + * applications with and without an expected type, or whtn `Typer#tryTypedApply` tries to fit arguments to + * a function type with/without implicit views. + * + * When the error policies entails error/warning buffering, the mutable [[ReportBuffer]] records + * everything that is issued. It is important to note, that child Contexts created with `make` + * "inherit" the very same `ReportBuffer` instance, whereas children spawned through `makeSilent` + * receive an separate, fresh buffer. + * + * @param tree Tree associated with this context + * @param owner The current owner + * @param scope The current scope + * @param _outer The next outer context. + */ + class Context private[typechecker](val tree: Tree, val owner: Symbol, val scope: Scope, + val unit: CompilationUnit, _outer: Context) { + private def outerIsNoContext = _outer eq null + final def outer: Context = if (outerIsNoContext) NoContext else _outer + + /** The next outer context whose tree is a template or package definition */ + var enclClass: Context = _ - class Context private[typechecker] { - import Errors._ - - var unit: CompilationUnit = NoCompilationUnit - var tree: Tree = _ // Tree associated with this context - var owner: Symbol = NoSymbol // The current owner - var scope: Scope = _ // The current scope - var outer: Context = _ // The next outer context - var enclClass: Context = _ // The next outer context whose tree is a - // template or package definition - @inline final def savingEnclClass[A](c: Context)(a: => A): A = { + @inline private def savingEnclClass[A](c: Context)(a: => A): A = { val saved = enclClass enclClass = c try a finally enclClass = saved } - var enclMethod: Context = _ // The next outer context whose tree is a method - var variance: Variance = Variance.Invariant // Variance relative to enclosing class - private var _undetparams: List[Symbol] = List() // Undetermined type parameters, - // not inherited to child contexts - var depth: Int = 0 - var imports: List[ImportInfo] = List() // currently visible imports - var openImplicits: List[(Type,Tree)] = List() // types for which implicit arguments - // are currently searched - // for a named application block (Tree) the corresponding NamedApplyInfo + /** A bitmask containing all the boolean flags in a context, e.g. are implicit views enabled */ + var contextMode: ContextMode = ContextMode.DefaultMode + + /** Update all modes in `mask` to `value` */ + def update(mask: ContextMode, value: Boolean) { + contextMode = contextMode.set(value, mask) + } + + /** Set all modes in the mask `enable` to true, and all in `disable` to false. */ + def set(enable: ContextMode = NOmode, disable: ContextMode = NOmode): this.type = { + contextMode = contextMode.set(true, enable).set(false, disable) + this + } + + /** Is this context in all modes in the given `mask`? */ + def apply(mask: ContextMode): Boolean = contextMode.inAll(mask) + + /** The next outer context whose tree is a method */ + var enclMethod: Context = _ + + /** Variance relative to enclosing class */ + var variance: Variance = Variance.Invariant + + private var _undetparams: List[Symbol] = List() + + protected def outerDepth = if (outerIsNoContext) 0 else outer.depth + + val depth: Int = { + val increasesDepth = isRootImport || outerIsNoContext || (outer.scope != scope) + ( if (increasesDepth) 1 else 0 ) + outerDepth + } + + /** The currently visible imports */ + def imports: List[ImportInfo] = outer.imports + /** Equivalent to `imports.headOption`, but more efficient */ + def firstImport: Option[ImportInfo] = outer.firstImport + def isRootImport: Boolean = false + + /** Types for which implicit arguments are currently searched */ + var openImplicits: List[(Type,Tree)] = List() + + /* For a named application block (`Tree`) the corresponding `NamedApplyInfo`. */ var namedApplyBlockInfo: Option[(Tree, NamedApplyInfo)] = None var prefix: Type = NoPrefix - var inConstructorSuffix = false // are we in a secondary constructor - // after the this constructor call? - var returnsSeen = false // for method context: were returns encountered? - var inSelfSuperCall = false // is this context (enclosed in) a constructor call? - // (the call to the super or self constructor in the first line of a constructor) - // in this context the object's fields should not be in scope - - var diagnostic: List[String] = Nil // these messages are printed when issuing an error - var implicitsEnabled = false - var macrosEnabled = true - var enrichmentEnabled = false // to selectively allow enrichment in patterns, where other kinds of implicit conversions are not allowed - var checking = false - var retyping = false - - var savedTypeBounds: List[(Symbol, Type)] = List() // saved type bounds - // for type parameters which are narrowed in a GADT + def inConstructorSuffix_=(value: Boolean) = this(ConstructorSuffix) = value + def inConstructorSuffix = this(ConstructorSuffix) + def returnsSeen_=(value: Boolean) = this(ReturnsSeen) = value + def returnsSeen = this(ReturnsSeen) + def inSelfSuperCall_=(value: Boolean) = this(SelfSuperCall) = value + def inSelfSuperCall = this(SelfSuperCall) + def implicitsEnabled_=(value: Boolean) = this(ImplicitsEnabled) = value + def implicitsEnabled = this(ImplicitsEnabled) + def macrosEnabled_=(value: Boolean) = this(MacrosEnabled) = value + def macrosEnabled = this(MacrosEnabled) + def enrichmentEnabled_=(value: Boolean) = this(EnrichmentEnabled) = value + def enrichmentEnabled = this(EnrichmentEnabled) + def checking_=(value: Boolean) = this(Checking) = value + def checking = this(Checking) + def retyping_=(value: Boolean) = this(ReTyping) = value + def retyping = this(ReTyping) + + /** These messages are printed when issuing an error */ + var diagnostic: List[String] = Nil + + /** Saved type bounds for type parameters which are narrowed in a GADT. */ + var savedTypeBounds: List[(Symbol, Type)] = List() + + /** Indentation level, in columns, for output under -Ytyper-debug */ var typingIndentLevel: Int = 0 def typingIndent = " " * typingIndentLevel - var buffer: mutable.Set[AbsTypeError] = _ - var warningsBuffer: mutable.Set[(Position, String)] = _ - + /** The next enclosing context (potentially `this`) that is owned by a class or method */ def enclClassOrMethod: Context = if ((owner eq NoSymbol) || (owner.isClass) || (owner.isMethod)) this else outer.enclClassOrMethod + /** The next enclosing context (potentially `this`) that has a `CaseDef` as a tree */ def enclosingCaseDef = nextEnclosing(_.tree.isInstanceOf[CaseDef]) + + /** ...or an Apply. */ + def enclosingApply = nextEnclosing(_.tree.isInstanceOf[Apply]) + + // + // Tracking undetermined type parameters for type argument inference. + // def undetparamsString = if (undetparams.isEmpty) "" else undetparams.mkString("undetparams=", ", ", "") - def undetparams = _undetparams + /** Undetermined type parameters. See `Infer#{inferExprInstance, adjustTypeArgs}`. Not inherited to child contexts */ + def undetparams: List[Symbol] = _undetparams def undetparams_=(ps: List[Symbol]) = { _undetparams = ps } - def extractUndetparams() = { + /** Return and clear the undetermined type parameters */ + def extractUndetparams(): List[Symbol] = { val tparams = undetparams undetparams = List() tparams } - private[this] var mode = 0 - - def errBuffer = buffer - def hasErrors = buffer.nonEmpty - def hasWarnings = warningsBuffer.nonEmpty - - def state: Int = mode - def restoreState(state0: Int) = mode = state0 - - def reportErrors = (state & ReportErrors) != 0 - def bufferErrors = (state & BufferErrors) != 0 - def ambiguousErrors = (state & AmbiguousErrors) != 0 - def throwErrors = (state & notThrowMask) == 0 - - def setReportErrors() = mode = (ReportErrors | AmbiguousErrors) - def setBufferErrors() = { - //assert(bufferErrors || !hasErrors, "When entering the buffer state, context has to be clean. Current buffer: " + buffer) - mode = BufferErrors + /** Run `body` with this context with no undetermined type parameters, restore the original + * the original list afterwards. + * @param reportAmbiguous Should ambiguous errors be reported during evaluation of `body`? + */ + def savingUndeterminedTypeParams[A](reportAmbiguous: Boolean = ambiguousErrors)(body: => A): A = { + withMode() { + this(AmbiguousErrors) = reportAmbiguous + val saved = extractUndetparams() + try body + finally undetparams = saved + } } - def setThrowErrors() = mode &= (~AllMask) - def setAmbiguousErrors(report: Boolean) = if (report) mode |= AmbiguousErrors else mode &= notThrowMask - def updateBuffer(errors: mutable.Set[AbsTypeError]) = buffer ++= errors - def condBufferFlush(removeP: AbsTypeError => Boolean) { - val elems = buffer.filter(removeP) - buffer --= elems - } - def flushBuffer() { buffer.clear() } - def flushAndReturnBuffer(): mutable.Set[AbsTypeError] = { - val current = buffer.clone() - buffer.clear() + // + // Error reporting policies and buffer. + // + + private var _reportBuffer: ReportBuffer = new ReportBuffer + /** A buffer for errors and warnings, used with `this.bufferErrors == true` */ + def reportBuffer = _reportBuffer + /** Discard the current report buffer, and replace with an empty one */ + def useFreshReportBuffer() = _reportBuffer = new ReportBuffer + /** Discard the current report buffer, and replace with `other` */ + def restoreReportBuffer(other: ReportBuffer) = _reportBuffer = other + + /** The first error, if any, in the report buffer */ + def firstError: Option[AbsTypeError] = reportBuffer.firstError + /** Does the report buffer contain any errors? */ + def hasErrors = reportBuffer.hasErrors + + def reportErrors = this(ReportErrors) + def bufferErrors = this(BufferErrors) + def ambiguousErrors = this(AmbiguousErrors) + def throwErrors = contextMode.inNone(ReportErrors | BufferErrors) + + def setReportErrors(): Unit = set(enable = ReportErrors | AmbiguousErrors, disable = BufferErrors) + def setBufferErrors(): Unit = set(enable = BufferErrors, disable = ReportErrors | AmbiguousErrors) + def setThrowErrors(): Unit = this(ReportErrors | AmbiguousErrors | BufferErrors) = false + def setAmbiguousErrors(report: Boolean): Unit = this(AmbiguousErrors) = report + + /** Append the given errors to the report buffer */ + def updateBuffer(errors: Traversable[AbsTypeError]) = reportBuffer ++= errors + /** Clear all errors from the report buffer */ + def flushBuffer() { reportBuffer.clearAllErrors() } + /** Return and clear all errors from the report buffer */ + def flushAndReturnBuffer(): immutable.Seq[AbsTypeError] = { + val current = reportBuffer.errors + reportBuffer.clearAllErrors() current } - def flushAndReturnWarningsBuffer(): mutable.Set[(Position, String)] = { - val current = warningsBuffer.clone() - warningsBuffer.clear() - current - } - - def withImplicitsEnabled[T](op: => T): T = { - val saved = implicitsEnabled - implicitsEnabled = true - try op - finally implicitsEnabled = saved - } - def withImplicitsDisabled[T](op: => T): T = { - val saved = implicitsEnabled - implicitsEnabled = false - val savedP = enrichmentEnabled - enrichmentEnabled = false - try op - finally { - implicitsEnabled = saved - enrichmentEnabled = savedP + /** Issue and clear all warnings from the report buffer */ + def flushAndIssueWarnings() { + reportBuffer.warnings foreach { + case (pos, msg) => unit.warning(pos, msg) } + reportBuffer.clearAllWarnings() } - def withImplicitsDisabledAllowEnrichment[T](op: => T): T = { - val saved = implicitsEnabled - implicitsEnabled = false - val savedP = enrichmentEnabled - enrichmentEnabled = true - try op - finally { - implicitsEnabled = saved - enrichmentEnabled = savedP - } - } + // + // Temporary mode adjustment + // - def withMacrosEnabled[T](op: => T): T = { - val saved = macrosEnabled - macrosEnabled = true + @inline def withMode[T](enabled: ContextMode = NOmode, disabled: ContextMode = NOmode)(op: => T): T = { + val saved = contextMode + set(enabled, disabled) try op - finally macrosEnabled = saved + finally contextMode = saved } - def withMacrosDisabled[T](op: => T): T = { - val saved = macrosEnabled - macrosEnabled = false - try op - finally macrosEnabled = saved + def withImplicitsEnabled[T](op: => T): T = withMode(enabled = ImplicitsEnabled)(op) + def withImplicitsDisabled[T](op: => T): T = withMode(disabled = ImplicitsEnabled | EnrichmentEnabled)(op) + def withImplicitsDisabledAllowEnrichment[T](op: => T): T = withMode(enabled = EnrichmentEnabled, disabled = ImplicitsEnabled)(op) + def withMacrosEnabled[T](op: => T): T = withMode(enabled = MacrosEnabled)(op) + def withMacrosDisabled[T](op: => T): T = withMode(disabled = MacrosEnabled)(op) + + /** @return true if the `expr` evaluates to true within a silent Context that incurs no errors */ + @inline final def inSilentMode(expr: => Boolean): Boolean = { + withMode() { // withMode with no arguments to restore the mode mutated by `setBufferErrors`. + setBufferErrors() + try expr && !hasErrors + finally reportBuffer.clearAll() + } } - def make(unit: CompilationUnit, tree: Tree, owner: Symbol, - scope: Scope, imports: List[ImportInfo]): Context = { - val c = new Context - c.unit = unit - c.tree = tree - c.owner = owner - c.scope = scope - c.outer = this - - tree match { - case Template(_, _, _) | PackageDef(_, _) => - c.enclClass = c - c.prefix = c.owner.thisType - c.inConstructorSuffix = false - case _ => - c.enclClass = this.enclClass - c.prefix = - if (c.owner != this.owner && c.owner.isTerm) NoPrefix - else this.prefix - c.inConstructorSuffix = this.inConstructorSuffix + // + // Child Context Creation + // + + /** + * Construct a child context. The parent and child will share the report buffer. + * Compare with `makeSilent`, in which the child has a fresh report buffer. + * + * If `tree` is an `Import`, that import will be avaiable at the head of + * `Context#imports`. + */ + def make(tree: Tree = tree, owner: Symbol = owner, + scope: Scope = scope, unit: CompilationUnit = unit): Context = { + val isTemplateOrPackage = tree match { + case _: Template | _: PackageDef => true + case _ => false } - tree match { - case DefDef(_, _, _, _, _, _) => - c.enclMethod = c - case _ => - c.enclMethod = this.enclMethod + val isDefDef = tree match { + case _: DefDef => true + case _ => false } - c.variance = this.variance - c.depth = if (scope == this.scope) this.depth else this.depth + 1 - c.imports = imports - c.inSelfSuperCall = inSelfSuperCall - c.restoreState(this.state) - c.diagnostic = this.diagnostic - c.typingIndentLevel = typingIndentLevel - c.implicitsEnabled = this.implicitsEnabled - c.macrosEnabled = this.macrosEnabled - c.enrichmentEnabled = this.enrichmentEnabled - c.checking = this.checking - c.retyping = this.retyping - c.openImplicits = this.openImplicits - c.buffer = if (this.buffer == null) mutable.LinkedHashSet[AbsTypeError]() else this.buffer // need to initialize - c.warningsBuffer = if (this.warningsBuffer == null) mutable.LinkedHashSet[(Position, String)]() else this.warningsBuffer + val isImport = tree match { + case _: Import => true + case _ => false + } + val sameOwner = owner == this.owner + val prefixInChild = + if (isTemplateOrPackage) owner.thisType + else if (!sameOwner && owner.isTerm) NoPrefix + else prefix + + // The blank canvas + val c = if (isImport) + new Context(tree, owner, scope, unit, this) with ImportContext + else + new Context(tree, owner, scope, unit, this) + + // Fields that are directly propagated + c.variance = variance + c.diagnostic = diagnostic + c.typingIndentLevel = typingIndentLevel + c.openImplicits = openImplicits + c.contextMode = contextMode // note: ConstructorSuffix, a bit within `mode`, is conditionally overwritten below. + c._reportBuffer = reportBuffer + + // Fields that may take on a different value in the child + c.prefix = prefixInChild + c.enclClass = if (isTemplateOrPackage) c else enclClass + c(ConstructorSuffix) = !isTemplateOrPackage && c(ConstructorSuffix) + c.enclMethod = if (isDefDef) c else enclMethod + registerContext(c.asInstanceOf[analyzer.Context]) debuglog("[context] ++ " + c.unit + " / " + tree.summaryString) c } - def makeNewImport(sym: Symbol): Context = - makeNewImport(gen.mkWildcardImport(sym)) - - def makeNewImport(imp: Import): Context = { - val impInfo = new ImportInfo(imp, depth) - if (settings.lint && imp.pos.isDefined) // pos.isDefined excludes java.lang/scala/Predef imports - allImportInfos(unit) ::= impInfo - - make(unit, imp, owner, scope, impInfo :: imports) - } - def make(tree: Tree, owner: Symbol, scope: Scope): Context = + // TODO SI-7345 Moving this optimization into the main overload of `make` causes all tests to fail. + // even if it is extened to check that `unit == this.unit`. Why is this? if (tree == this.tree && owner == this.owner && scope == this.scope) this - else make0(tree, owner, scope) - - private def make0(tree: Tree, owner: Symbol, scope: Scope): Context = - make(unit, tree, owner, scope, imports) + else make(tree, owner, scope, unit) + /** Make a child context that represents a new nested scope */ def makeNewScope(tree: Tree, owner: Symbol): Context = make(tree, owner, newNestedScope(scope)) - // IDE stuff: distinguish between scopes created for typing and scopes created for naming. - - def make(tree: Tree, owner: Symbol): Context = - make0(tree, owner, scope) - - def make(tree: Tree): Context = - make(tree, owner) - def makeSilent(reportAmbiguousErrors: Boolean, newtree: Tree = tree): Context = { + /** Make a child context that buffers errors and warnings into a fresh report buffer. */ + def makeSilent(reportAmbiguousErrors: Boolean = ambiguousErrors, newtree: Tree = tree): Context = { val c = make(newtree) c.setBufferErrors() c.setAmbiguousErrors(reportAmbiguousErrors) - c.buffer = mutable.LinkedHashSet[AbsTypeError]() + c._reportBuffer = new ReportBuffer // A fresh buffer so as not to leak errors/warnings into `this`. c } + /** Make a silent child context does not allow implicits. Used to prevent chaining of implicit views. */ def makeImplicit(reportAmbiguousErrors: Boolean) = { val c = makeSilent(reportAmbiguousErrors) - c.implicitsEnabled = false - c.enrichmentEnabled = false + c(ImplicitsEnabled | EnrichmentEnabled) = false c } @@ -376,12 +452,10 @@ trait Contexts { self: Analyzer => * accessible. */ def makeConstructorContext = { - var baseContext = enclClass.outer - while (baseContext.tree.isInstanceOf[Template]) - baseContext = baseContext.outer + val baseContext = enclClass.outer.nextEnclosing(!_.tree.isInstanceOf[Template]) val argContext = baseContext.makeNewScope(tree, owner) + argContext.contextMode = contextMode argContext.inSelfSuperCall = true - argContext.restoreState(this.state) def enterElems(c: Context) { def enterLocalElems(e: ScopeEntry) { if (e != null && e.owner == c.scope) { @@ -389,7 +463,7 @@ trait Contexts { self: Analyzer => argContext.scope enter e.sym } } - if (c.owner.isTerm && !c.owner.isLocalDummy) { + if (c.isLocal && !c.owner.isLocalDummy) { enterElems(c.outer) enterLocalElems(c.scope.elems) } @@ -400,6 +474,10 @@ trait Contexts { self: Analyzer => argContext } + // + // Error and warning issuance + // + private def addDiagString(msg: String) = { val ds = if (diagnostic.isEmpty) "" @@ -416,16 +494,18 @@ trait Contexts { self: Analyzer => (new Exception).printStackTrace() } if (pf isDefinedAt err) pf(err) - else if (bufferErrors) { buffer += err } + else if (bufferErrors) { reportBuffer += err } else throw new TypeError(err.errPos, err.errMsg) } + /** Issue/buffer/throw the given type error according to the current mode for error reporting. */ def issue(err: AbsTypeError) { issueCommon(err) { case _ if reportErrors => unitError(err.errPos, addDiagString(err.errMsg)) } } + /** Issue/buffer/throw the given implicit ambiguity error according to the current mode for error reporting. */ def issueAmbiguousError(pre: Type, sym1: Symbol, sym2: Symbol, err: AbsTypeError) { issueCommon(err) { case _ if ambiguousErrors => if (!pre.isErroneous && !sym1.isErroneous && !sym2.isErroneous) @@ -433,35 +513,31 @@ trait Contexts { self: Analyzer => } } + /** Issue/buffer/throw the given implicit ambiguity error according to the current mode for error reporting. */ def issueAmbiguousError(err: AbsTypeError) { issueCommon(err) { case _ if ambiguousErrors => unitError(err.errPos, addDiagString(err.errMsg)) } } - // TODO remove + /** Issue/throw the given `err` according to the current mode for error reporting. */ def error(pos: Position, err: Throwable) = if (reportErrors) unitError(pos, addDiagString(err.getMessage())) else throw err + /** Issue/throw the given error message according to the current mode for error reporting. */ def error(pos: Position, msg: String) = { val msg1 = addDiagString(msg) if (reportErrors) unitError(pos, msg1) else throw new TypeError(pos, msg1) } - def warning(pos: Position, msg: String): Unit = warning(pos, msg, force = false) - def warning(pos: Position, msg: String, force: Boolean) { + /** Issue/throw the given error message according to the current mode for error reporting. */ + def warning(pos: Position, msg: String, force: Boolean = false) { if (reportErrors || force) unit.warning(pos, msg) - else if (bufferErrors) warningsBuffer += ((pos, msg)) - } - - def isLocal(): Boolean = tree match { - case Block(_,_) => true - case PackageDef(_, _) => false - case EmptyTree => false - case _ => outer.isLocal() + else if (bufferErrors) reportBuffer += (pos -> msg) } - def isNameInScope(name: Name) = lookupSymbol(name, _ => true).isSuccess + /** Is the owning symbol of this context a term? */ + final def isLocal: Boolean = owner.isTerm // nextOuter determines which context is searched next for implicits // (after `this`, which contributes `newImplicits` below.) In @@ -487,14 +563,34 @@ trait Contexts { self: Analyzer => def enclosingContextChain: List[Context] = this :: outer.enclosingContextChain - override def toString = "Context(%s@%s unit=%s scope=%s errors=%b, reportErrors=%b, throwErrors=%b)".format( - owner.fullName, tree.shortClass, unit, scope.##, hasErrors, reportErrors, throwErrors - ) - /** Is `sub` a subclass of `base` or a companion object of such a subclass? - */ - def isSubClassOrCompanion(sub: Symbol, base: Symbol) = + private def treeTruncated = tree.toString.replaceAll("\\s+", " ").lines.mkString("\\n").take(70) + private def treeIdString = if (settings.uniqid.value) "#" + System.identityHashCode(tree).toString.takeRight(3) else "" + private def treeString = tree match { + case x: Import => "" + x + case Template(parents, `emptyValDef`, body) => + val pstr = if ((parents eq null) || parents.isEmpty) "Nil" else parents mkString " " + val bstr = if (body eq null) "" else body.length + " stats" + s"""Template($pstr, _, $bstr)""" + case x => s"${tree.shortClass}${treeIdString}:${treeTruncated}" + } + + override def toString = + sm"""|Context($unit) { + | owner = $owner + | tree = $treeString + | scope = ${scope.size} decls + | contextMode = $contextMode + | outer.owner = ${outer.owner} + |}""" + + // + // Accessibility checking + // + + /** Is `sub` a subclass of `base` or a companion object of such a subclass? */ + private def isSubClassOrCompanion(sub: Symbol, base: Symbol) = sub.isNonBottomSubClass(base) || - sub.isModuleClass && sub.linkedClassOfClass.isNonBottomSubClass(base) + sub.isModuleClass && sub.linkedClassOfClass.isNonBottomSubClass(base) /** Return the closest enclosing context that defines a subclass of `clazz` * or a companion object thereof, or `NoContext` if no such context exists. @@ -506,8 +602,7 @@ trait Contexts { self: Analyzer => c } - /** Is `sym` accessible as a member of `pre` in current context? - */ + /** Is `sym` accessible as a member of `pre` in current context? */ def isAccessible(sym: Symbol, pre: Type, superAccess: Boolean = false): Boolean = { lastAccessCheckDetails = "" // Console.println("isAccessible(%s, %s, %s)".format(sym, pre, superAccess)) @@ -587,6 +682,10 @@ trait Contexts { self: Analyzer => } } + // + // Type bound management + // + def pushTypeBounds(sym: Symbol) { sym.info match { case tb: TypeBounds => if (!tb.isEmptyBounds) log(s"Saving $sym info=$tb") @@ -623,6 +722,10 @@ trait Contexts { self: Analyzer => } } + // + // Implicit collection + // + private var implicitsCache: List[List[ImplicitInfo]] = null private var implicitsRunId = NoRunId @@ -682,6 +785,8 @@ trait Contexts { self: Analyzer => * filtered out later by `eligibleInfos` (SI-4270 / 9129cfe9), as they don't type-check. */ def implicitss: List[List[ImplicitInfo]] = { + val imports = this.imports + val nextOuter = this.nextOuter if (implicitsRunId != currentRunId) { implicitsRunId = currentRunId implicitsCache = List() @@ -698,8 +803,8 @@ trait Contexts { self: Analyzer => } else if (scope != nextOuter.scope && !owner.isPackageClass) { debuglog("collect local implicits " + scope.toList)//DEBUG collectImplicits(scope, NoPrefix) - } else if (imports != nextOuter.imports) { - assert(imports.tail == nextOuter.imports, (imports, nextOuter.imports)) + } else if (firstImport != nextOuter.firstImport) { + assert(imports.tail.headOption == nextOuter.firstImport, (imports, nextOuter.imports)) collectImplicitImports(imports.head) } else if (owner.isPackageClass) { // the corresponding package object may contain implicit members. @@ -711,6 +816,10 @@ trait Contexts { self: Analyzer => implicitsCache } + // + // Imports and symbol lookup + // + /** It's possible that seemingly conflicting identifiers are * identifiably the same after type normalization. In such cases, * allow compilation to proceed. A typical example is: @@ -820,6 +929,8 @@ trait Contexts { self: Analyzer => ) } + def isNameInScope(name: Name) = lookupSymbol(name, _ => true).isSuccess + /** Find the symbol of a simple name starting from this context. * All names are filtered through the "qualifies" predicate, * the search continuing as long as no qualifying name is found. @@ -1026,6 +1137,75 @@ trait Contexts { self: Analyzer => } } //class Context + /** A `Context` focussed on an `Import` tree */ + trait ImportContext extends Context { + private val impInfo: ImportInfo = { + val info = new ImportInfo(tree.asInstanceOf[Import], outerDepth) + if (settings.lint && !isRootImport) // excludes java.lang/scala/Predef imports + allImportInfos(unit) ::= info + info + } + override final def imports = impInfo :: super.imports + override final def firstImport = Some(impInfo) + override final def isRootImport = !tree.pos.isDefined + override final def toString = s"ImportContext { $impInfo; outer.owner = ${outer.owner} }" + } + + /** A buffer for warnings and errors that are accumulated during speculative type checking. */ + final class ReportBuffer { + type Error = AbsTypeError + type Warning = (Position, String) + + private def newBuffer[A] = mutable.LinkedHashSet.empty[A] // Important to use LinkedHS for stable results. + + // [JZ] Contexts, pre- the SI-7345 refactor, avoided allocating the buffers until needed. This + // is replicated here out of conservatism. + private var _errorBuffer: mutable.LinkedHashSet[Error] = _ + private def errorBuffer = {if (_errorBuffer == null) _errorBuffer = newBuffer; _errorBuffer} + def errors: immutable.Seq[Error] = errorBuffer.toVector + + private var _warningBuffer: mutable.LinkedHashSet[Warning] = _ + private def warningBuffer = {if (_warningBuffer == null) _warningBuffer = newBuffer; _warningBuffer} + def warnings: immutable.Seq[Warning] = warningBuffer.toVector + + def +=(error: AbsTypeError): this.type = { + errorBuffer += error + this + } + def ++=(errors: Traversable[AbsTypeError]): this.type = { + errorBuffer ++= errors + this + } + def +=(warning: Warning): this.type = { + warningBuffer += warning + this + } + + def clearAll(): this.type = { + clearAllErrors(); clearAllWarnings(); + } + + def clearAllErrors(): this.type = { + errorBuffer.clear() + this + } + def clearErrors(removeF: PartialFunction[AbsTypeError, Boolean]): this.type = { + errorBuffer.retain(!PartialFunction.cond(_)(removeF)) + this + } + def retainErrors(leaveF: PartialFunction[AbsTypeError, Boolean]): this.type = { + errorBuffer.retain(PartialFunction.cond(_)(leaveF)) + this + } + def clearAllWarnings(): this.type = { + warningBuffer.clear() + this + } + + def hasErrors = errorBuffer.nonEmpty + def firstError = errorBuffer.headOption + } + class ImportInfo(val tree: Import, val depth: Int) { def pos = tree.pos def posOf(sel: ImportSelector) = tree.pos withPoint sel.namePos @@ -1112,3 +1292,75 @@ trait Contexts { self: Analyzer => override def safeToString = "ImportType("+expr+")" } } + +object ContextMode { + private implicit def liftIntBitsToContextState(bits: Int): ContextMode = apply(bits) + def apply(bits: Int): ContextMode = new ContextMode(bits) + final val NOmode: ContextMode = 0 + + final val ReportErrors: ContextMode = 1 << 0 + final val BufferErrors: ContextMode = 1 << 1 + final val AmbiguousErrors: ContextMode = 1 << 2 + + /** Are we in a secondary constructor after the this constructor call? */ + final val ConstructorSuffix: ContextMode = 1 << 3 + + /** For method context: were returns encountered? */ + final val ReturnsSeen: ContextMode = 1 << 4 + + /** Is this context (enclosed in) a constructor call? + * (the call to the super or self constructor in the first line of a constructor.) + * In such a context, the object's fields should not be in scope + */ + final val SelfSuperCall: ContextMode = 1 << 5 + + // TODO harvest documentation for this + final val ImplicitsEnabled: ContextMode = 1 << 6 + + final val MacrosEnabled: ContextMode = 1 << 7 + + /** To selectively allow enrichment in patterns, where other kinds of implicit conversions are not allowed */ + final val EnrichmentEnabled: ContextMode = 1 << 8 + + /** Are we in a run of [[scala.tools.nsc.typechecker.TreeCheckers]]? */ + final val Checking: ContextMode = 1 << 9 + + /** Are we retypechecking arguments independently from the function applied to them? See `Typer.tryTypedApply` */ + // TODO This seems to directly overlap with Mode.SNDTRYmode + final val ReTyping: ContextMode = 1 << 10 + + final val DefaultMode: ContextMode = MacrosEnabled + + private val contextModeNameMap = Map( + ReportErrors -> "ReportErrors", + BufferErrors -> "BufferErrors", + AmbiguousErrors -> "AmbiguousErrors", + ConstructorSuffix -> "ConstructorSuffix", + SelfSuperCall -> "SelfSuperCall", + ImplicitsEnabled -> "ImplicitsEnabled", + MacrosEnabled -> "MacrosEnabled", + Checking -> "Checking", + ReTyping -> "ReTyping" + ) +} + +/** + * A value class to carry the boolean flags of a context, such as whether errors should + * be buffered or reported. + */ +final class ContextMode private (val bits: Int) extends AnyVal { + import ContextMode._ + + def &(other: ContextMode): ContextMode = new ContextMode(bits & other.bits) + def |(other: ContextMode): ContextMode = new ContextMode(bits | other.bits) + def &~(other: ContextMode): ContextMode = new ContextMode(bits & ~(other.bits)) + def set(value: Boolean, mask: ContextMode) = if (value) |(mask) else &~(mask) + + def inAll(required: ContextMode) = (this & required) == required + def inAny(required: ContextMode) = (this & required) != NOmode + def inNone(prohibited: ContextMode) = (this & prohibited) == NOmode + + override def toString = + if (bits == 0) "NOmode" + else (contextModeNameMap filterKeys inAll).values.toList.sorted mkString " " +} diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index 85e31347be..f27c15180e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -8,7 +8,8 @@ //todo: disallow C#D in superclass //todo: treat :::= correctly -package scala.tools.nsc +package scala +package tools.nsc package typechecker import scala.annotation.tailrec @@ -80,9 +81,12 @@ trait Implicits { printTyping("typing implicit: %s %s".format(tree, context.undetparamsString)) val implicitSearchContext = context.makeImplicit(reportAmbiguous) val result = new ImplicitSearch(tree, pt, isView, implicitSearchContext, pos).bestImplicit - if (saveAmbiguousDivergent && implicitSearchContext.hasErrors) { - context.updateBuffer(implicitSearchContext.errBuffer.filter(err => err.kind == ErrorKinds.Ambiguous || err.kind == ErrorKinds.Divergent)) - debuglog("update buffer: " + implicitSearchContext.errBuffer) + if (result.isFailure && saveAmbiguousDivergent && implicitSearchContext.hasErrors) { + context.updateBuffer(implicitSearchContext.reportBuffer.errors.collect { + case dte: DivergentImplicitTypeError => dte + case ate: AmbiguousImplicitTypeError => ate + }) + debuglog("update buffer: " + implicitSearchContext.reportBuffer.errors) } printInference("[infer implicit] inferred " + result) context.undetparams = context.undetparams filterNot result.subst.from.contains @@ -152,6 +156,7 @@ trait Implicits { def isFailure = false def isAmbiguousFailure = false + def isDivergent = false final def isSuccess = !isFailure } @@ -159,6 +164,11 @@ trait Implicits { override def isFailure = true } + lazy val DivergentSearchFailure = new SearchResult(EmptyTree, EmptyTreeTypeSubstituter) { + override def isFailure = true + override def isDivergent = true + } + lazy val AmbiguousSearchFailure = new SearchResult(EmptyTree, EmptyTreeTypeSubstituter) { override def isFailure = true override def isAmbiguousFailure = true @@ -208,7 +218,10 @@ trait Implicits { case _ => false } override def hashCode = name.## + pre.## + sym.## - override def toString = name + ": " + tpe + override def toString = ( + if (tpeCache eq null) name + ": ?" + else name + ": " + tpe + ) } /** A sentinel indicating no implicit was found */ @@ -397,22 +410,18 @@ trait Implicits { (context.openImplicits find { case (tp, tree1) => tree1.symbol == tree.symbol && dominates(pt, tp)}) match { case Some(pending) => //println("Pending implicit "+pending+" dominates "+pt+"/"+undetParams) //@MDEBUG - throw DivergentImplicit + DivergentSearchFailure case None => try { context.openImplicits = (pt, tree) :: context.openImplicits // println(" "*context.openImplicits.length+"typed implicit "+info+" for "+pt) //@MDEBUG - typedImplicit0(info, ptChecked, isLocal) - } catch { - case ex: DivergentImplicit => + val result = typedImplicit0(info, ptChecked, isLocal) + if (result.isDivergent) { //println("DivergentImplicit for pt:"+ pt +", open implicits:"+context.openImplicits) //@MDEBUG - if (context.openImplicits.tail.isEmpty) { - if (!(pt.isErroneous)) - DivergingImplicitExpansionError(tree, pt, info.sym)(context) - SearchFailure - } else { - throw DivergentImplicit - } + if (context.openImplicits.tail.isEmpty && !pt.isErroneous) + DivergingImplicitExpansionError(tree, pt, info.sym)(context) + } + result } finally { context.openImplicits = context.openImplicits.tail } @@ -584,9 +593,11 @@ trait Implicits { ) case _ => fallback } - if (context.hasErrors) { - log("implicit adapt failed: " + context.errBuffer.head.errMsg) - return fail(context.errBuffer.head.errMsg) + context.firstError match { // using match rather than foreach to avoid non local return. + case Some(err) => + log("implicit adapt failed: " + err.errMsg) + return fail(err.errMsg) + case None => } if (Statistics.canEnable) Statistics.incCounter(typedImplicits) @@ -609,7 +620,7 @@ trait Implicits { } if (context.hasErrors) - fail("hasMatchingSymbol reported error: " + context.errBuffer.head.errMsg) + fail("hasMatchingSymbol reported error: " + context.firstError.get.errMsg) else if (isLocal && !hasMatchingSymbol(itree1)) fail("candidate implicit %s is shadowed by %s".format( info.sym.fullLocationString, itree1.symbol.fullLocationString)) @@ -632,8 +643,11 @@ trait Implicits { // #2421: check that we correctly instantiated type parameters outside of the implicit tree: checkBounds(itree2, NoPrefix, NoSymbol, undetParams, targs, "inferred ") - if (context.hasErrors) - return fail("type parameters weren't correctly instantiated outside of the implicit tree: " + context.errBuffer.head.errMsg) + context.firstError match { + case Some(err) => + return fail("type parameters weren't correctly instantiated outside of the implicit tree: " + err.errMsg) + case None => + } // filter out failures from type inference, don't want to remove them from undetParams! // we must be conservative in leaving type params in undetparams @@ -668,13 +682,14 @@ trait Implicits { case t => t } - if (context.hasErrors) - fail("typing TypeApply reported errors for the implicit tree: " + context.errBuffer.head.errMsg) - else { - val result = new SearchResult(itree2, subst) - if (Statistics.canEnable) Statistics.incCounter(foundImplicits) - printInference("[success] found %s for pt %s".format(result, ptInstantiated)) - result + context.firstError match { + case Some(err) => + fail("typing TypeApply reported errors for the implicit tree: " + err.errMsg) + case None => + val result = new SearchResult(itree2, subst) + if (Statistics.canEnable) Statistics.incCounter(foundImplicits) + printInference("[success] found %s for pt %s".format(result, ptInstantiated)) + result } } else fail("incompatible: %s does not match expected type %s".format(itree2.tpe, ptInstantiated)) @@ -783,15 +798,20 @@ trait Implicits { /** Preventing a divergent implicit from terminating implicit search, * so that if there is a best candidate it can still be selected. */ - private var divergence = false - private val divergenceHandler: PartialFunction[Throwable, SearchResult] = { - var remaining = 1; - { case x: DivergentImplicit if remaining > 0 => - remaining -= 1 - divergence = true - log("discarding divergent implicit during implicit search") + object DivergentImplicitRecovery { + // symbol of the implicit that caused the divergence. + // Initially null, will be saved on first diverging expansion. + private var implicitSym: Symbol = _ + private var countdown: Int = 1 + + def sym: Symbol = implicitSym + def apply(search: SearchResult, i: ImplicitInfo): SearchResult = + if (search.isDivergent && countdown > 0) { + countdown -= 1 + implicitSym = i.sym + log("discarding divergent implicit ${implicitSym} during implicit search") SearchFailure - } + } else search } /** Sorted list of eligible implicits. @@ -820,15 +840,15 @@ trait Implicits { @tailrec private def rankImplicits(pending: Infos, acc: Infos): Infos = pending match { case Nil => acc case i :: is => - def tryImplicitInfo(i: ImplicitInfo) = - try typedImplicit(i, ptChecked = true, isLocal) - catch divergenceHandler - - tryImplicitInfo(i) match { + DivergentImplicitRecovery(typedImplicit(i, ptChecked = true, isLocal), i) match { + case sr if sr.isDivergent => + Nil case sr if sr.isFailure => // We don't want errors that occur during checking implicit info // to influence the check of further infos. - context.condBufferFlush(_.kind != ErrorKinds.Divergent) + context.reportBuffer.retainErrors { + case err: DivergentImplicitTypeError => true + } rankImplicits(is, acc) case newBest => best = newBest @@ -876,10 +896,9 @@ trait Implicits { /* If there is no winner, and we witnessed and caught divergence, * now we can throw it for the error message. */ - if (divergence) - throw DivergentImplicit - - if (invalidImplicits.nonEmpty) + if (DivergentImplicitRecovery.sym != null) { + DivergingImplicitExpansionError(tree, pt, DivergentImplicitRecovery.sym)(context) + } else if (invalidImplicits.nonEmpty) setAddendum(pos, () => "\n Note: implicit "+invalidImplicits.head+" is not applicable here"+ " because it comes after the application point and it lacks an explicit result type") @@ -1085,8 +1104,10 @@ trait Implicits { try { val tree1 = typedPos(pos.focus)(arg) - if (context.hasErrors) processMacroExpansionError(context.errBuffer.head.errPos, context.errBuffer.head.errMsg) - else new SearchResult(tree1, EmptyTreeTypeSubstituter) + context.firstError match { + case Some(err) => processMacroExpansionError(err.errPos, err.errMsg) + case None => new SearchResult(tree1, EmptyTreeTypeSubstituter) + } } catch { case ex: TypeError => processMacroExpansionError(ex.pos, ex.msg) @@ -1430,6 +1451,3 @@ object ImplicitsStats { val implicitCacheAccs = Statistics.newCounter ("implicit cache accesses", "typer") val implicitCacheHits = Statistics.newSubCounter("implicit cache hits", implicitCacheAccs) } - -class DivergentImplicit extends Exception -object DivergentImplicit extends DivergentImplicit diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala index 4913034d3f..aaa6c66630 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -38,10 +38,7 @@ trait Infer extends Checkable { * @param removeRepeated allows keeping repeated parameter (if there's one argument). Used in NamesDefaults. */ def formalTypes(formals: List[Type], nargs: Int, removeByName: Boolean = true, removeRepeated: Boolean = true): List[Type] = { - val formals1 = if (removeByName) formals mapConserve { - case TypeRef(_, ByNameParamClass, List(arg)) => arg - case formal => formal - } else formals + val formals1 = if (removeByName) formals mapConserve dropByName else formals if (isVarArgTypes(formals1) && (removeRepeated || formals.length != nargs)) { val ft = formals1.last.dealiasWiden.typeArgs.head formals1.init ::: (for (i <- List.range(formals1.length - 1, nargs)) yield ft) @@ -72,6 +69,10 @@ trait Infer extends Checkable { * * `formals` are the formal types before expanding a potential repeated parameter (must come last in `formals`, if at all) * + * @param nbSubPats The number of arguments to the extractor pattern + * @param effectiveNbSubPats `nbSubPats`, unless there is one sub-pattern which, after unwrapping + * bind patterns, is a Tuple pattern, in which case it is the number of + * elements. Used to issue warnings about binding a `TupleN` to a single value. * @throws TypeError when the unapply[Seq] definition is ill-typed * @returns (null, null) when the expected number of sub-patterns cannot be satisfied by the given extractor * @@ -101,7 +102,8 @@ trait Infer extends Checkable { * `T_1, ..., T_m, U, ..., U`. Here, `U` is repeated `n-m` times. * */ - def extractorFormalTypes(pos: Position, resTp: Type, nbSubPats: Int, unappSym: Symbol): (List[Type], List[Type]) = { + def extractorFormalTypes(pos: Position, resTp: Type, nbSubPats: Int, + unappSym: Symbol, effectiveNbSubPats: Int): (List[Type], List[Type]) = { val isUnapplySeq = unappSym.name == nme.unapplySeq val booleanExtractor = resTp.typeSymbolDirect == BooleanClass @@ -131,8 +133,9 @@ trait Infer extends Checkable { else if (optionArgs.nonEmpty) if (nbSubPats == 1) { val productArity = productArgs.size - if (productArity > 1 && settings.lint) - global.currentUnit.warning(pos, s"extractor pattern binds a single value to a Product${productArity} of type ${optionArgs.head}") + if (productArity > 1 && productArity != effectiveNbSubPats && settings.lint) + global.currentUnit.warning(pos, + s"extractor pattern binds a single value to a Product${productArity} of type ${optionArgs.head}") optionArgs } // TODO: update spec to reflect we allow any ProductN, not just TupleN @@ -412,10 +415,9 @@ trait Infer extends Checkable { * since that induces a tie between m(=>A) and m(=>A,B*) [SI-3761] */ private def isCompatible(tp: Type, pt: Type): Boolean = { - def isCompatibleByName(tp: Type, pt: Type): Boolean = pt match { - case TypeRef(_, ByNameParamClass, List(res)) if !isByNameParamType(tp) => isCompatible(tp, res) - case _ => false - } + def isCompatibleByName(tp: Type, pt: Type): Boolean = ( + isByNameParamType(pt) && !isByNameParamType(tp) && isCompatible(tp, dropByName(pt)) + ) val tp1 = normalize(tp) (tp1 weak_<:< pt) || isCoercible(tp1, pt) || isCompatibleByName(tp, pt) } @@ -474,6 +476,7 @@ trait Infer extends Checkable { } existentialAbstraction(tparams.toList, tp1) } + def ensureFullyDefined(tp: Type): Type = if (isFullyDefined(tp)) tp else makeFullyDefined(tp) /** Return inferred type arguments of polymorphic expression, given * its type parameters and result type and a prototype `pt`. @@ -914,19 +917,28 @@ trait Infer extends Checkable { } /** - * Todo: Try to make isApplicable always safe (i.e. not cause TypeErrors). - * The chance of TypeErrors should be reduced through context errors + * Are arguments of the given types applicable to `ftpe`? Type argument inference + * is tried twice: firstly with the given expected type, and secondly with `WildcardType`. */ + // Todo: Try to make isApplicable always safe (i.e. not cause TypeErrors). + // The chance of TypeErrors should be reduced through context errors private[typechecker] def isApplicableSafe(undetparams: List[Symbol], ftpe: Type, argtpes0: List[Type], pt: Type): Boolean = { - val silentContext = context.makeSilent(reportAmbiguousErrors = false) - val typer0 = newTyper(silentContext) - val res1 = typer0.infer.isApplicable(undetparams, ftpe, argtpes0, pt) - if (pt != WildcardType && silentContext.hasErrors) { - silentContext.flushBuffer() - val res2 = typer0.infer.isApplicable(undetparams, ftpe, argtpes0, WildcardType) - if (silentContext.hasErrors) false else res2 - } else res1 + final case class Result(error: Boolean, applicable: Boolean) + def isApplicableWithExpectedType(pt0: Type): Result = { + val silentContext = context.makeSilent(reportAmbiguousErrors = false) + val applicable = newTyper(silentContext).infer.isApplicable(undetparams, ftpe, argtpes0, pt0) + Result(silentContext.hasErrors, applicable) + } + val canSecondTry = pt != WildcardType + val firstTry = isApplicableWithExpectedType(pt) + if (!firstTry.error || !canSecondTry) + firstTry.applicable + else { + val secondTry = isApplicableWithExpectedType(WildcardType) + // TODO `!secondTry.error &&` was faithfully replicated as part of the refactoring, but mayberedundant. + !secondTry.error && secondTry.applicable + } } /** Is type `ftpe1` strictly more specific than type `ftpe2` @@ -1535,16 +1547,6 @@ trait Infer extends Checkable { } } - @inline private def inSilentMode(context: Context)(expr: => Boolean): Boolean = { - val oldState = context.state - context.setBufferErrors() - val res = expr - val contextWithErrors = context.hasErrors - context.flushBuffer() - context.restoreState(oldState) - res && !contextWithErrors - } - // Checks against the name of the parameter and also any @deprecatedName. private def paramMatchesName(param: Symbol, name: Name) = param.name == name || param.deprecatedParamName.exists(_ == name) @@ -1613,7 +1615,7 @@ trait Infer extends Checkable { } def followType(sym: Symbol) = followApply(pre memberType sym) def bestForExpectedType(pt: Type, isLastTry: Boolean): Unit = { - val applicable0 = alts filter (alt => inSilentMode(context)(isApplicable(undetparams, followType(alt), argtpes, pt))) + val applicable0 = alts filter (alt => context inSilentMode (isApplicable(undetparams, followType(alt), argtpes, pt))) val applicable = overloadsToConsiderBySpecificity(applicable0, argtpes, varargsStar) val ranked = bestAlternatives(applicable)((sym1, sym2) => isStrictlyMoreSpecific(followType(sym1), followType(sym2), sym1, sym2) @@ -1623,8 +1625,8 @@ trait Infer extends Checkable { case best :: Nil => tree setSymbol best setType (pre memberType best) // success case Nil if pt eq WildcardType => NoBestMethodAlternativeError(tree, argtpes, pt, isLastTry) // failed case Nil => bestForExpectedType(WildcardType, isLastTry) // failed, but retry with WildcardType - } - } + } + } // This potentially makes up to four attempts: tryTwice may execute // with and without views enabled, and bestForExpectedType will try again // with pt = WildcardType if it fails with pt != WildcardType. @@ -1640,7 +1642,7 @@ trait Infer extends Checkable { */ def tryTwice(infer: Boolean => Unit): Unit = { if (context.implicitsEnabled) { - val saved = context.state + val savedContextMode = context.contextMode var fallback = false context.setBufferErrors() // We cache the current buffer because it is impossible to @@ -1654,17 +1656,17 @@ trait Infer extends Checkable { context.withImplicitsDisabled(infer(false)) if (context.hasErrors) { fallback = true - context.restoreState(saved) + context.contextMode = savedContextMode context.flushBuffer() infer(true) } } catch { case ex: CyclicReference => throw ex case ex: TypeError => // recoverable cyclic references - context.restoreState(saved) + context.contextMode = savedContextMode if (!fallback) infer(true) else () } finally { - context.restoreState(saved) + context.contextMode = savedContextMode context.updateBuffer(errorsToRestore) } } diff --git a/src/compiler/scala/tools/nsc/typechecker/Macros.scala b/src/compiler/scala/tools/nsc/typechecker/Macros.scala index 2dbfa1d0d3..d07297bb35 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Macros.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Macros.scala @@ -769,12 +769,12 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { if (macroDebugVerbose) println(s"typecheck #1 (against expectedTpe = $expectedTpe): $expanded") val expanded1 = typer.context.withImplicitsEnabled(typer.typed(expanded, mode, expectedTpe)) if (expanded1.isErrorTyped) { - if (macroDebugVerbose) println(s"typecheck #1 has failed: ${typer.context.errBuffer}") + if (macroDebugVerbose) println(s"typecheck #1 has failed: ${typer.context.reportBuffer.errors}") expanded1 } else { if (macroDebugVerbose) println(s"typecheck #2 (against pt = $pt): $expanded1") val expanded2 = typer.context.withImplicitsEnabled(super.onSuccess(expanded1)) - if (macroDebugVerbose && expanded2.isErrorTyped) println(s"typecheck #2 has failed: ${typer.context.errBuffer}") + if (macroDebugVerbose && expanded2.isErrorTyped) println(s"typecheck #2 has failed: ${typer.context.reportBuffer.errors}") expanded2 } } diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index de3010c371..541d60c16d 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -9,6 +9,7 @@ package typechecker import scala.collection.mutable import scala.annotation.tailrec import symtab.Flags._ +import scala.language.postfixOps /** This trait declares methods to create symbols and to enter them into scopes. * @@ -47,7 +48,6 @@ trait Namers extends MethodSynthesis { private class NormalNamer(context: Context) extends Namer(context) def newNamer(context: Context): Namer = new NormalNamer(context) - def newNamerFor(context: Context, tree: Tree): Namer = newNamer(context.makeNewScope(tree, tree.symbol)) abstract class Namer(val context: Context) extends MethodSynth with NamerContextErrors { thisNamer => // overridden by the presentation compiler @@ -254,7 +254,7 @@ trait Namers extends MethodSynthesis { case DocDef(_, defn) => enterSym(defn) case tree @ Import(_, _) => assignSymbol(tree) - returnContext = context.makeNewImport(tree) + returnContext = context.make(tree) case _ => } returnContext @@ -1629,7 +1629,7 @@ trait Namers extends MethodSynthesis { // @M an abstract type's type parameters are entered. // TODO: change to isTypeMember ? if (defnSym.isAbstractType) - newNamerFor(ctx, tree) enterSyms tparams //@M + newNamer(ctx.makeNewScope(tree, tree.symbol)) enterSyms tparams //@M restp complete sym } } diff --git a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala index 6921f8ce27..c08aa7e39f 100644 --- a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala +++ b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala @@ -19,6 +19,7 @@ trait NamesDefaults { self: Analyzer => import global._ import definitions._ import NamesDefaultsErrorsGen._ + import treeInfo.WildcardStarArg // Default getters of constructors are added to the companion object in the // typeCompleter of the constructor (methodSig). To compute the signature, @@ -278,8 +279,8 @@ trait NamesDefaults { self: Analyzer => val repeated = isScalaRepeatedParamType(paramTpe) val argTpe = ( if (repeated) arg match { - case Typed(expr, Ident(tpnme.WILDCARD_STAR)) => expr.tpe - case _ => seqType(arg.tpe) + case WildcardStarArg(expr) => expr.tpe + case _ => seqType(arg.tpe) } else // Note stabilizing can lead to a non-conformant argument when existentials are involved, e.g. neg/t3507-old.scala, hence the filter. @@ -302,11 +303,8 @@ trait NamesDefaults { self: Analyzer => } else { new ChangeOwnerTraverser(context.owner, sym) traverse arg // fixes #4502 if (repeated) arg match { - case Typed(expr, Ident(tpnme.WILDCARD_STAR)) => - expr - case _ => - val factory = Select(gen.mkAttributedRef(SeqModule), nme.apply) - blockTyper.typed(Apply(factory, List(resetLocalAttrs(arg)))) + case WildcardStarArg(expr) => expr + case _ => blockTyper typed gen.mkSeqApply(resetLocalAttrs(arg)) } else arg } Some(atPos(body.pos)(ValDef(sym, body).setType(NoType))) @@ -451,20 +449,6 @@ trait NamesDefaults { self: Analyzer => } else NoSymbol } - private def savingUndeterminedTParams[T](context: Context)(fn: List[Symbol] => T): T = { - val savedParams = context.extractUndetparams() - val savedReporting = context.ambiguousErrors - - context.setAmbiguousErrors(false) - try fn(savedParams) - finally { - context.setAmbiguousErrors(savedReporting) - //@M note that we don't get here when an ambiguity was detected (during the computation of res), - // as errorTree throws an exception - context.undetparams = savedParams - } - } - /** A full type check is very expensive; let's make sure there's a name * somewhere which could potentially be ambiguous before we go that route. */ @@ -479,12 +463,10 @@ trait NamesDefaults { self: Analyzer => // def f[T](x: T) = x // var x = 0 // f(x = 1) << "x = 1" typechecks with expected type WildcardType - savingUndeterminedTParams(context) { udp => + val udp = context.undetparams + context.savingUndeterminedTypeParams(reportAmbiguous = false) { val subst = new SubstTypeMap(udp, udp map (_ => WildcardType)) { - override def apply(tp: Type): Type = super.apply(tp match { - case TypeRef(_, ByNameParamClass, x :: Nil) => x - case _ => tp - }) + override def apply(tp: Type): Type = super.apply(dropByName(tp)) } // This throws an exception which is caught in `tryTypedApply` (as it // uses `silent`) - unfortunately, tryTypedApply recovers from the diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala index efd4fd804f..290ad76a1d 100644 --- a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala +++ b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala @@ -59,7 +59,22 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans override def changesBaseClasses = false override def transformInfo(sym: Symbol, tp: Type): Type = { - if (sym.isModule && !sym.isStatic) sym setFlag (lateMETHOD | STABLE) + // !!! This is a sketchy way to do things. + // It would be better to replace the module symbol with a method symbol + // rather than creating this module/method hybrid which must be special + // cased all over the place. Look for the call sites which use(d) some + // variation of "isMethod && !isModule", which to an observer looks like + // a nonsensical condition. (It is now "isModuleNotMethod".) + if (sym.isModule && !sym.isStatic) { + sym setFlag lateMETHOD | STABLE + // Note that this as far as we can see it works equally well + // to set the METHOD flag here and dump lateMETHOD, but it does + // mean that under separate compilation the typer will see + // modules as methods (albeit stable ones with singleton types.) + // So for now lateMETHOD lives while we try to convince ourselves + // we can live without it or deliver that info some other way. + log(s"Stabilizing module method for ${sym.fullLocationString}") + } super.transformInfo(sym, tp) } @@ -144,7 +159,8 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans // This has become noisy with implicit classes. if (settings.lint && settings.developer) { clazz.info.decls filter (x => x.isImplicit && x.typeParams.nonEmpty) foreach { sym => - val alts = clazz.info.decl(sym.name).alternatives + // implicit classes leave both a module symbol and a method symbol as residue + val alts = clazz.info.decl(sym.name).alternatives filterNot (_.isModule) if (alts.size > 1) alts foreach (x => unit.warning(x.pos, "parameterized overloaded implicit methods are not visible as view bounds")) } @@ -965,12 +981,15 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans val s = fn.symbol (s == Object_==) || (s == Object_!=) || (s == Any_==) || (s == Any_!=) } + def haveSubclassRelationship = (actual isSubClass receiver) || (receiver isSubClass actual) + // Whether the operands+operator represent a warnable combo (assuming anyrefs) // Looking for comparisons performed with ==/!= in combination with either an // equals method inherited from Object or a case class synthetic equals (for // which we know the logic.) def isWarnable = isReferenceOp || (isUsingDefaultScalaOp && isUsingWarnableEquals) def isEitherNullable = (NullClass.tpe <:< receiver.info) || (NullClass.tpe <:< actual.info) + def isEitherValueClass = actual.isDerivedValueClass || receiver.isDerivedValueClass def isBoolean(s: Symbol) = unboxedValueClass(s) == BooleanClass def isUnit(s: Symbol) = unboxedValueClass(s) == UnitClass def isNumeric(s: Symbol) = isNumericValueClass(unboxedValueClass(s)) || isAnyNumber(s) @@ -982,6 +1001,12 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans // used to short-circuit unrelatedTypes check if both sides are special def isSpecial(s: Symbol) = isMaybeAnyValue(s) || isAnyNumber(s) val nullCount = onSyms(_ filter (_ == NullClass) size) + def isNonsenseValueClassCompare = ( + !haveSubclassRelationship + && isUsingDefaultScalaOp + && isEitherValueClass + && !isCaseEquals + ) def nonSensibleWarning(what: String, alwaysEqual: Boolean) = { val msg = alwaysEqual == (name == nme.EQ || name == nme.eq) @@ -993,10 +1018,13 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans def nonSensiblyNeq() = nonSensible("", false) def nonSensiblyNew() = nonSensibleWarning("a fresh object", false) + def unrelatedMsg = name match { + case nme.EQ | nme.eq => "never compare equal" + case _ => "always compare unequal" + } def unrelatedTypes() = { - val msg = if (name == nme.EQ || name == nme.eq) - "never compare equal" else "always compare unequal" - unit.warning(pos, typesString + " are unrelated: they will most likely " + msg) + val weaselWord = if (isEitherValueClass) "" else " most likely" + unit.warning(pos, s"$typesString are unrelated: they will$weaselWord $unrelatedMsg") } if (nullCount == 2) // null == null @@ -1035,15 +1063,19 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans } } + // warn if one but not the other is a derived value class + // this is especially important to enable transitioning from + // regular to value classes without silent failures. + if (isNonsenseValueClassCompare) + unrelatedTypes() // possibleNumericCount is insufficient or this will warn on e.g. Boolean == j.l.Boolean - if (isWarnable && nullCount == 0 && !(isSpecial(receiver) && isSpecial(actual))) { + else if (isWarnable && nullCount == 0 && !(isSpecial(receiver) && isSpecial(actual))) { // better to have lubbed and lost def warnIfLubless(): Unit = { val common = global.lub(List(actual.tpe, receiver.tpe)) if (ObjectClass.tpe <:< common) unrelatedTypes() } - def eitherSubclasses = (actual isSubClass receiver) || (receiver isSubClass actual) // warn if actual has a case parent that is not same as receiver's; // if actual is not a case, then warn if no common supertype, as below if (isCaseEquals) { @@ -1056,14 +1088,12 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans //else // if a class, it must be super to thisCase (and receiver) since not <: thisCase if (!actual.isTrait && !(receiver isSubClass actual)) nonSensiblyNeq() - else if (!eitherSubclasses) warnIfLubless() + else if (!haveSubclassRelationship) warnIfLubless() case _ => } } - else if (actual isSubClass receiver) () - else if (receiver isSubClass actual) () // warn only if they have no common supertype below Object - else { + else if (!haveSubclassRelationship) { warnIfLubless() } } @@ -1261,6 +1291,16 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans } } + private def checkDelayedInitSelect(qual: Tree, sym: Symbol, pos: Position) = { + def isLikelyUninitialized = ( + (sym.owner isSubClass DelayedInitClass) + && !qual.tpe.isInstanceOf[ThisType] + && sym.accessedOrSelf.isVal + ) + if (settings.lint.value && isLikelyUninitialized) + unit.warning(pos, s"Selecting ${sym} from ${sym.owner}, which extends scala.DelayedInit, is likely to yield an uninitialized value") + } + private def lessAccessible(otherSym: Symbol, memberSym: Symbol): Boolean = ( (otherSym != NoSymbol) && !otherSym.isProtected @@ -1464,6 +1504,7 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans if(settings.Xmigration.value != NoScalaVersion) checkMigration(sym, tree.pos) checkCompileTimeOnly(sym, tree.pos) + checkDelayedInitSelect(qual, sym, tree.pos) if (sym eq NoSymbol) devWarning("Select node has NoSymbol! " + tree + " / " + tree.tpe) @@ -1511,10 +1552,10 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans // Verify classes extending AnyVal meet the requirements private def checkAnyValSubclass(clazz: Symbol) = { - if ((clazz isSubClass AnyValClass) && !isPrimitiveValueClass(clazz)) { + if (clazz.isDerivedValueClass) { if (clazz.isTrait) unit.error(clazz.pos, "Only classes (not traits) are allowed to extend AnyVal") - else if ((clazz != AnyValClass) && clazz.hasFlag(ABSTRACT)) + else if (clazz.hasAbstractFlag) unit.error(clazz.pos, "`abstract' modifier cannot be used with value classes") } } @@ -1591,7 +1632,7 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans enterReference(tree.pos, tpt.tpe.typeSymbol) tree - case Typed(_, Ident(tpnme.WILDCARD_STAR)) if !isRepeatedParamArg(tree) => + case treeInfo.WildcardStarArg(_) if !isRepeatedParamArg(tree) => unit.error(tree.pos, "no `: _*' annotation allowed here\n"+ "(such annotations are only allowed in arguments to *-parameters)") tree diff --git a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala index e22dc73b53..3f7e6d7665 100644 --- a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala @@ -4,7 +4,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package typechecker import scala.collection.{ mutable, immutable } @@ -64,8 +65,8 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT debuglog(s"add super acc ${sym.fullLocationString} to $clazz") val acc = clazz.newMethod(supername, sel.pos, SUPERACCESSOR | PRIVATE | ARTIFACT) setAlias sym val tpe = clazz.thisType memberType sym match { - case t if sym.isModule && !sym.isMethod => NullaryMethodType(t) - case t => t + case t if sym.isModuleNotMethod => NullaryMethodType(t) + case t => t } acc setInfoAndEnter (tpe cloneInfo acc) // Diagnostic for SI-7091 diff --git a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala index c531caa2e8..406bc445c9 100644 --- a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala +++ b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala @@ -9,6 +9,7 @@ package typechecker import scala.collection.{ mutable, immutable } import symtab.Flags._ import scala.collection.mutable.ListBuffer +import scala.language.postfixOps /** Synthetic method implementations for case classes and case objects. * @@ -94,7 +95,7 @@ trait SyntheticMethods extends ast.TreeDSL { // which they shouldn't. val accessorLub = ( if (settings.Xexperimental) { - global.weakLub(accessors map (_.tpe.finalResultType))._1 match { + global.weakLub(accessors map (_.tpe.finalResultType)) match { case RefinedType(parents, decls) if !decls.isEmpty => intersectionType(parents) case tp => tp } @@ -336,11 +337,13 @@ trait SyntheticMethods extends ast.TreeDSL { def shouldGenerate(m: Symbol) = { !hasOverridingImplementation(m) || { clazz.isDerivedValueClass && (m == Any_hashCode || m == Any_equals) && { - if (settings.lint) { - (clazz.info nonPrivateMember m.name) filter (m => (m.owner != AnyClass) && (m.owner != clazz) && !m.isDeferred) andAlso { m => - currentUnit.warning(clazz.pos, s"Implementation of ${m.name} inherited from ${m.owner} overridden in $clazz to enforce value class semantics") - } - } + // Without a means to suppress this warning, I've thought better of it. + // + // if (settings.lint) { + // (clazz.info nonPrivateMember m.name) filter (m => (m.owner != AnyClass) && (m.owner != clazz) && !m.isDeferred) andAlso { m => + // currentUnit.warning(clazz.pos, s"Implementation of ${m.name} inherited from ${m.owner} overridden in $clazz to enforce value class semantics") + // } + // } true } } diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala index 5f45fead91..5146cf6fa7 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala @@ -271,6 +271,24 @@ trait TypeDiagnostics { ) } + def typePatternAdvice(sym: Symbol, ptSym: Symbol) = { + val clazz = if (sym.isModuleClass) sym.companionClass else sym + val caseString = + if (clazz.isCaseClass && (clazz isSubClass ptSym)) + ( clazz.caseFieldAccessors + map (_ => "_") // could use the actual param names here + mkString (s"`case ${clazz.name}(", ",", ")`") + ) + else + "`case _: " + (clazz.typeParams match { + case Nil => "" + clazz.name + case xs => xs map (_ => "_") mkString (clazz.name + "[", ",", "]") + })+ "`" + + "\nNote: if you intended to match against the class, try "+ caseString + + } + case class TypeDiag(tp: Type, sym: Symbol) extends Ordered[TypeDiag] { // save the name because it will be mutated until it has been // distinguished from the other types in the same error message diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeStrings.scala b/src/compiler/scala/tools/nsc/typechecker/TypeStrings.scala index eb05486dca..afe6875218 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeStrings.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeStrings.scala @@ -153,7 +153,7 @@ trait TypeStrings { private type JClass = java.lang.Class[_] private val ObjectClass = classOf[java.lang.Object] private val primitives = Set[String]("byte", "char", "short", "int", "long", "float", "double", "boolean", "void") - private val primitiveMap = primitives.toList map { x => + private val primitiveMap = (primitives.toList map { x => val key = x match { case "int" => "Integer" case "char" => "Character" @@ -165,7 +165,7 @@ trait TypeStrings { } ("java.lang." + key) -> ("scala." + value) - } toMap + }).toMap def isAnonClass(cl: Class[_]) = { val xs = cl.getName.reverse takeWhile (_ != '$') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 9536df888e..001808e6bc 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -9,7 +9,8 @@ // Added: Thu Apr 12 18:23:58 2007 //todo: disallow C#D in superclass //todo: treat :::= correctly -package scala.tools.nsc +package scala +package tools.nsc package typechecker import scala.collection.mutable @@ -150,15 +151,19 @@ trait Typers extends Adaptations with Tags { } else { mkArg = gen.mkNamedArg // don't pass the default argument (if any) here, but start emitting named arguments for the following args if (!param.hasDefault && !paramFailed) { - context.errBuffer.find(_.kind == ErrorKinds.Divergent) match { - case Some(divergentImplicit) => + context.reportBuffer.errors.collectFirst { + case dte: DivergentImplicitTypeError => dte + } match { + case Some(divergent) => // DivergentImplicit error has higher priority than "no implicit found" // no need to issue the problem again if we are still in silent mode if (context.reportErrors) { - context.issue(divergentImplicit) - context.condBufferFlush(_.kind == ErrorKinds.Divergent) + context.issue(divergent.withPt(paramTp)) + context.reportBuffer.clearErrors { + case dte: DivergentImplicitTypeError => true + } } - case None => + case _ => NoImplicitFoundError(fun, param) } paramFailed = true @@ -599,7 +604,7 @@ trait Typers extends Adaptations with Tags { if (sym.isValue) { val tree1 = checkStable(tree) // A module reference in a pattern has type Foo.type, not "object Foo" - if (sym.isModule && !sym.isMethod) tree1 setType singleType(pre, sym) + if (sym.isModuleNotMethod) tree1 setType singleType(pre, sym) else tree1 } else fail() @@ -607,7 +612,7 @@ trait Typers extends Adaptations with Tags { fail() } else { if (sym.isStable && pre.isStable && !isByNameParamType(tree.tpe) && - (isStableContext(tree, mode, pt) || sym.isModule && !sym.isMethod)) + (isStableContext(tree, mode, pt) || sym.isModuleNotMethod)) tree.setType(singleType(pre, sym)) // To fully benefit from special casing the return type of // getClass, we have to catch it immediately so expressions @@ -679,17 +684,14 @@ trait Typers extends Adaptations with Tags { context.undetparams = context1.undetparams context.savedTypeBounds = context1.savedTypeBounds context.namedApplyBlockInfo = context1.namedApplyBlockInfo - if (context1.hasErrors) { - stopStats() - SilentTypeError(context1.errBuffer.head) - } else { - // If we have a successful result, emit any warnings it created. - if (context1.hasWarnings) { - context1.flushAndReturnWarningsBuffer() foreach { - case (pos, msg) => unit.warning(pos, msg) - } - } - SilentResultValue(result) + context1.firstError match { + case Some(err) => + stopStats() + SilentTypeError(err) + case None => + // If we have a successful result, emit any warnings it created. + context1.flushAndIssueWarnings() + SilentResultValue(result) } } else { assert(context.bufferErrors || isPastTyper, "silent mode is not available past typer") @@ -1169,7 +1171,10 @@ trait Typers extends Adaptations with Tags { val silentContext = context.makeImplicit(context.ambiguousErrors) val res = newTyper(silentContext).typed( new ApplyImplicitView(coercion, List(tree)) setPos tree.pos, mode, pt) - if (silentContext.hasErrors) context.issue(silentContext.errBuffer.head) else return res + silentContext.firstError match { + case Some(err) => context.issue(err) + case None => return res + } } } } @@ -1512,7 +1517,7 @@ trait Typers extends Adaptations with Tags { */ private def typedParentType(encodedtpt: Tree, templ: Template, inMixinPosition: Boolean): Tree = { val app = treeInfo.dissectApplied(encodedtpt) - val (treeInfo.Applied(core, targs, argss), decodedtpt) = ((app, app.callee)) + val (treeInfo.Applied(core, _, argss), decodedtpt) = ((app, app.callee)) val argssAreTrivial = argss == Nil || argss == ListOfNil // we cannot avoid cyclic references with `initialize` here, because when type macros arrive, @@ -1627,22 +1632,27 @@ trait Typers extends Adaptations with Tags { /** Makes sure that the first type tree in the list of parent types is always a class. * If the first parent is a trait, prepend its supertype to the list until it's a class. -*/ - private def normalizeFirstParent(parents: List[Tree]): List[Tree] = parents match { - case first :: rest if treeInfo.isTraitRef(first) => - def explode(supertpt: Tree, acc: List[Tree]): List[Tree] = { - if (treeInfo.isTraitRef(supertpt)) { - val supertpt1 = typedType(supertpt) - if (!supertpt1.isErrorTyped) { - val supersupertpt = TypeTree(supertpt1.tpe.firstParent) setPos supertpt.pos.focus - return explode(supersupertpt, supertpt1 :: acc) - } - } - if (supertpt.tpe.typeSymbol == AnyClass) supertpt setType AnyRefClass.tpe - supertpt :: acc - } - explode(first, Nil) ++ rest - case _ => parents + */ + private def normalizeFirstParent(parents: List[Tree]): List[Tree] = { + @annotation.tailrec + def explode0(parents: List[Tree]): List[Tree] = { + val supertpt :: rest = parents // parents is always non-empty here - it only grows + if (supertpt.tpe.typeSymbol == AnyClass) { + supertpt setType AnyRefTpe + parents + } else if (treeInfo isTraitRef supertpt) { + val supertpt1 = typedType(supertpt) + def supersuper = TypeTree(supertpt1.tpe.firstParent) setPos supertpt.pos.focus + if (supertpt1.isErrorTyped) rest + else explode0(supersuper :: supertpt1 :: rest) + } else parents + } + + def explode(parents: List[Tree]) = + if (treeInfo isTraitRef parents.head) explode0(parents) + else parents + + if (parents.isEmpty) Nil else explode(parents) } /** Certain parents are added in the parser before it is known whether @@ -2480,8 +2490,7 @@ trait Typers extends Adaptations with Tags { def adaptCase(cdef: CaseDef, mode: Mode, tpe: Type): CaseDef = deriveCaseDef(cdef)(adapt(_, mode, tpe)) - def ptOrLub(tps: List[Type], pt: Type ) = if (isFullyDefined(pt)) (pt, false) else weakLub(tps map (_.deconst)) - def ptOrLubPacked(trees: List[Tree], pt: Type) = if (isFullyDefined(pt)) (pt, false) else weakLub(trees map (c => packedType(c, context.owner).deconst)) + def packedTypes(trees: List[Tree]): List[Type] = trees map (c => packedType(c, context.owner).deconst) // takes untyped sub-trees of a match and type checks them def typedMatch(selector: Tree, cases: List[CaseDef], mode: Mode, pt: Type, tree: Tree = EmptyTree): Match = { @@ -2489,11 +2498,17 @@ trait Typers extends Adaptations with Tags { val selectorTp = packCaptured(selector1.tpe.widen).skolemizeExistential(context.owner, selector) val casesTyped = typedCases(cases, selectorTp, pt) - val (resTp, needAdapt) = ptOrLubPacked(casesTyped, pt) + def finish(cases: List[CaseDef], matchType: Type) = + treeCopy.Match(tree, selector1, cases) setType matchType - val casesAdapted = if (!needAdapt) casesTyped else casesTyped map (adaptCase(_, mode, resTp)) - - treeCopy.Match(tree, selector1, casesAdapted) setType resTp + if (isFullyDefined(pt)) + finish(casesTyped, pt) + else packedTypes(casesTyped) match { + case packed if sameWeakLubAsLub(packed) => finish(casesTyped, lub(packed)) + case packed => + val lub = weakLub(packed) + finish(casesTyped map (adaptCase(_, mode, lub)), lub) + } } // match has been typed -- virtualize it during type checking so the full context is available @@ -2846,7 +2861,7 @@ trait Typers extends Adaptations with Tags { case imp @ Import(_, _) => imp.symbol.initialize if (!imp.symbol.isError) { - context = context.makeNewImport(imp) + context = context.make(imp) typedImport(imp) } else EmptyTree case _ => @@ -3099,30 +3114,29 @@ trait Typers extends Adaptations with Tags { fun.tpe match { case OverloadedType(pre, alts) => def handleOverloaded = { - val undetparams = context.extractUndetparams() - val argtpes = new ListBuffer[Type] - val amode = forArgMode(fun, mode) - val args1 = args map { - case arg @ AssignOrNamedArg(Ident(name), rhs) => - // named args: only type the righthand sides ("unknown identifier" errors otherwise) - val rhs1 = typedArg(rhs, amode, BYVALmode, WildcardType) - argtpes += NamedType(name, rhs1.tpe.deconst) - // the assign is untyped; that's ok because we call doTypedApply - treeCopy.AssignOrNamedArg(arg, arg.lhs, rhs1) - case arg @ Typed(repeated, Ident(tpnme.WILDCARD_STAR)) => - val arg1 = typedArg(arg, amode, BYVALmode, WildcardType) - argtpes += RepeatedType(arg1.tpe.deconst) - arg1 - case arg => - val arg1 = typedArg(arg, amode, BYVALmode, WildcardType) - argtpes += arg1.tpe.deconst - arg1 + val undetparams = context.undetparams + val (args1, argTpes) = context.savingUndeterminedTypeParams() { + val amode = forArgMode(fun, mode) + def typedArg0(tree: Tree) = typedArg(tree, amode, BYVALmode, WildcardType) + args.map { + case arg @ AssignOrNamedArg(Ident(name), rhs) => + // named args: only type the righthand sides ("unknown identifier" errors otherwise) + val rhs1 = typedArg0(rhs) + // the assign is untyped; that's ok because we call doTypedApply + val arg1 = treeCopy.AssignOrNamedArg(arg, arg.lhs, rhs1) + (arg1, NamedType(name, rhs1.tpe.deconst)) + case arg @ treeInfo.WildcardStarArg(repeated) => + val arg1 = typedArg0(arg) + (arg1, RepeatedType(arg1.tpe.deconst)) + case arg => + val arg1 = typedArg0(arg) + (arg1, arg1.tpe.deconst) + }.unzip } - context.undetparams = undetparams if (context.hasErrors) setError(tree) else { - inferMethodAlternative(fun, undetparams, argtpes.toList, pt) + inferMethodAlternative(fun, undetparams, argTpes, pt) doTypedApply(tree, adapt(fun, mode.forFunMode, WildcardType), args1, mode, pt) } } @@ -3398,13 +3412,12 @@ trait Typers extends Adaptations with Tags { else { val resTp = fun1.tpe.finalResultType.dealiasWiden val nbSubPats = args.length - - val (formals, formalsExpanded) = extractorFormalTypes(fun0.pos, resTp, nbSubPats, fun1.symbol) + val (formals, formalsExpanded) = + extractorFormalTypes(fun0.pos, resTp, nbSubPats, fun1.symbol, treeInfo.effectivePatternArity(args)) if (formals == null) duplErrorTree(WrongNumberOfArgsError(tree, fun)) else { val args1 = typedArgs(args, mode, formals, formalsExpanded) - val pt1 = if (isFullyDefined(pt)) pt else makeFullyDefined(pt) // SI-1048 - + val pt1 = ensureFullyDefined(pt) // SI-1048 val itype = glb(List(pt1, arg.tpe)) arg setType pt1 // restore type (arg is a dummy tree, just needs to pass typechecking) val unapply = UnApply(fun1, args1) setPos tree.pos setType itype @@ -3963,7 +3976,7 @@ trait Typers extends Adaptations with Tags { case Apply(fn, args) if matches(fn) => Some((applyOp(args), fn)) case Assign(lhs, _) if matches(lhs) => Some((nme.updateDynamic, lhs)) case _ if matches(t) => Some((nme.selectDynamic, t)) - case _ => t.children flatMap findSelection headOption + case _ => (t.children flatMap findSelection).headOption } findSelection(cxTree) match { case Some((opName, treeInfo.Applied(_, targs, _))) => @@ -3991,7 +4004,7 @@ trait Typers extends Adaptations with Tags { } def typed1(tree: Tree, mode: Mode, pt: Type): Tree = { - def isPatternMode = mode.inPatternMode + def isPatternMode = mode.inPatternMode def inPatternConstructor = mode.inAll(PATTERNmode | FUNmode) def isQualifierMode = mode.inAll(QUALmode) @@ -4183,36 +4196,39 @@ trait Typers extends Adaptations with Tags { else fail() } - def typedIf(tree: If) = { + def typedIf(tree: If): If = { val cond1 = checkDead(typed(tree.cond, EXPRmode | BYVALmode, BooleanClass.tpe)) - val thenp = tree.thenp - val elsep = tree.elsep - if (elsep.isEmpty) { // in the future, should be unnecessary - val thenp1 = typed(thenp, UnitClass.tpe) - treeCopy.If(tree, cond1, thenp1, elsep) setType thenp1.tpe - } else { - var thenp1 = typed(thenp, pt) - var elsep1 = typed(elsep, pt) - def thenTp = packedType(thenp1, context.owner) - def elseTp = packedType(elsep1, context.owner) - - // println("typedIf: "+(thenp1.tpe, elsep1.tpe, ptOrLub(List(thenp1.tpe, elsep1.tpe)),"\n", thenTp, elseTp, thenTp =:= elseTp)) - val (owntype, needAdapt) = - // in principle we should pack the types of each branch before lubbing, but lub doesn't really work for existentials anyway - // in the special (though common) case where the types are equal, it pays to pack before comparing - // especially virtpatmat needs more aggressive unification of skolemized types - // this breaks src/library/scala/collection/immutable/TrieIterator.scala - if (!isPastTyper && thenp1.tpe.annotations.isEmpty && elsep1.tpe.annotations.isEmpty // annotated types need to be lubbed regardless (at least, continations break if you by pass them like this) - && thenTp =:= elseTp - ) (thenp1.tpe.deconst, false) // use unpacked type. Important to deconst, as is done in ptOrLub, otherwise `if (???) 0 else 0` evaluates to 0 (SI-6331) - // TODO: skolemize (lub of packed types) when that no longer crashes on files/pos/t4070b.scala - else ptOrLub(thenp1.tpe :: elsep1.tpe :: Nil, pt) - - if (needAdapt) { //isNumericValueType(owntype)) { - thenp1 = adapt(thenp1, mode, owntype) - elsep1 = adapt(elsep1, mode, owntype) - } - treeCopy.If(tree, cond1, thenp1, elsep1) setType owntype + // One-legged ifs don't need a lot of analysis + if (tree.elsep.isEmpty) + return treeCopy.If(tree, cond1, typed(tree.thenp, UnitClass.tpe), tree.elsep) setType UnitClass.tpe + + val thenp1 = typed(tree.thenp, pt) + val elsep1 = typed(tree.elsep, pt) + + // in principle we should pack the types of each branch before lubbing, but lub doesn't really work for existentials anyway + // in the special (though common) case where the types are equal, it pays to pack before comparing + // especially virtpatmat needs more aggressive unification of skolemized types + // this breaks src/library/scala/collection/immutable/TrieIterator.scala + // annotated types need to be lubbed regardless (at least, continations break if you by pass them like this) + def samePackedTypes = ( + !isPastTyper + && thenp1.tpe.annotations.isEmpty + && elsep1.tpe.annotations.isEmpty + && packedType(thenp1, context.owner) =:= packedType(elsep1, context.owner) + ) + def finish(ownType: Type) = treeCopy.If(tree, cond1, thenp1, elsep1) setType ownType + // TODO: skolemize (lub of packed types) when that no longer crashes on files/pos/t4070b.scala + // @PP: This was doing the samePackedTypes check BEFORE the isFullyDefined check, + // which based on everything I see everywhere else was a bug. I reordered it. + if (isFullyDefined(pt)) + finish(pt) + // Important to deconst, otherwise `if (???) 0 else 0` evaluates to 0 (SI-6331) + else thenp1.tpe.deconst :: elsep1.tpe.deconst :: Nil match { + case tp :: _ if samePackedTypes => finish(tp) + case tpes if sameWeakLubAsLub(tpes) => finish(lub(tpes)) + case tpes => + val lub = weakLub(tpes) + treeCopy.If(tree, cond1, adapt(thenp1, mode, lub), adapt(elsep1, mode, lub)) setType lub } } @@ -4359,11 +4375,9 @@ trait Typers extends Adaptations with Tags { case ex: CyclicReference => throw ex case te: TypeError => - // @H some of typer erros can still leak, + // @H some of typer errors can still leak, // for instance in continuations None - } finally { - c.flushBuffer() } } @@ -4679,12 +4693,11 @@ trait Typers extends Adaptations with Tags { case SelectFromTypeTree(_, _) => treeCopy.SelectFromTypeTree(tree, qual, name) } val (result, accessibleError) = silent(_.makeAccessible(tree1, sym, qual.tpe, qual)) match { + case SilentTypeError(err: AccessTypeError) => + (tree1, Some(err)) case SilentTypeError(err) => - if (err.kind != ErrorKinds.Access) { - context issue err - return setError(tree) - } - else (tree1, Some(err)) + context issue err + return setError(tree) case SilentResultValue(treeAndPre) => (stabilize(treeAndPre._1, treeAndPre._2, mode, pt), None) } @@ -4940,42 +4953,54 @@ trait Typers extends Adaptations with Tags { def typedUnApply(tree: UnApply) = { val fun1 = typed(tree.fun) - val tpes = formalTypes(unapplyTypeList(tree.fun.pos, tree.fun.symbol, fun1.tpe, tree.args.length), tree.args.length) + val tpes = formalTypes(unapplyTypeList(tree.fun.pos, tree.fun.symbol, fun1.tpe, tree.args), tree.args.length) val args1 = map2(tree.args, tpes)(typedPattern) treeCopy.UnApply(tree, fun1, args1) setType pt } - def typedTry(tree: Try) = { - tree match { - case Try(_, Nil, EmptyTree) => - if (!isPastTyper) context.warning(tree.pos, - "A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled.") - case _ => - } - - var block1 = typed(tree.block, pt) - var catches1 = typedCases(tree.catches, ThrowableClass.tpe, pt) - - for (cdef <- catches1 if !isPastTyper && cdef.guard.isEmpty) { - def warn(name: Name) = context.warning(cdef.pat.pos, s"This catches all Throwables. If this is really intended, use `case ${name.decoded} : Throwable` to clear this warning.") + def issueTryWarnings(tree: Try): Try = { + def checkForCatchAll(cdef: CaseDef) { def unbound(t: Tree) = t.symbol == null || t.symbol == NoSymbol - cdef.pat match { + def warn(name: Name) = { + val msg = s"This catches all Throwables. If this is really intended, use `case ${name.decoded} : Throwable` to clear this warning." + context.warning(cdef.pat.pos, msg) + } + if (cdef.guard.isEmpty) cdef.pat match { case Bind(name, i @ Ident(_)) if unbound(i) => warn(name) - case i @ Ident(name) if unbound(i) => warn(name) - case _ => + case i @ Ident(name) if unbound(i) => warn(name) + case _ => } } - - val finalizer1 = - if (tree.finalizer.isEmpty) tree.finalizer - else typed(tree.finalizer, UnitClass.tpe) - val (owntype, needAdapt) = ptOrLub(block1.tpe :: (catches1 map (_.tpe)), pt) - if (needAdapt) { - block1 = adapt(block1, mode, owntype) - catches1 = catches1 map (adaptCase(_, mode, owntype)) + if (!isPastTyper) tree match { + case Try(_, Nil, fin) => + if (fin eq EmptyTree) + context.warning(tree.pos, "A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled.") + case Try(_, catches, _) => + catches foreach checkForCatchAll } + tree + } - treeCopy.Try(tree, block1, catches1, finalizer1) setType owntype + def typedTry(tree: Try) = { + val Try(block, catches, fin) = tree + val block1 = typed(block, pt) + val catches1 = typedCases(catches, ThrowableClass.tpe, pt) + val fin1 = if (fin.isEmpty) fin else typed(fin, UnitClass.tpe) + + def finish(ownType: Type) = treeCopy.Try(tree, block1, catches1, fin1) setType ownType + + issueTryWarnings( + if (isFullyDefined(pt)) + finish(pt) + else block1 :: catches1 map (_.tpe.deconst) match { + case tpes if sameWeakLubAsLub(tpes) => finish(lub(tpes)) + case tpes => + val lub = weakLub(tpes) + val block2 = adapt(block1, mode, lub) + val catches2 = catches1 map (adaptCase(_, mode, lub)) + treeCopy.Try(tree, block2, catches2, fin1) setType lub + } + ) } def typedThrow(tree: Throw) = { @@ -5001,7 +5026,7 @@ trait Typers extends Adaptations with Tags { typedEta(checkDead(exprTyped)) } - case Ident(tpnme.WILDCARD_STAR) => + case t if treeInfo isWildcardStarType t => val exprTyped = typed(expr, mode.onlySticky, WildcardType) def subArrayType(pt: Type) = if (isPrimitiveValueClass(pt.typeSymbol) || !isFullyDefined(pt)) arrayType(pt) @@ -5028,9 +5053,8 @@ trait Typers extends Adaptations with Tags { if (isPatternMode) { val uncheckedTypeExtractor = extractorForUncheckedType(tpt.pos, tptTyped.tpe) - // make fully defined to avoid bounded wildcard types that may be in pt from calling dropExistential (SI-2038) - val ptDefined = if (isFullyDefined(pt)) pt else makeFullyDefined(pt) + val ptDefined = ensureFullyDefined(pt) val ownType = inferTypedPattern(tptTyped, tptTyped.tpe, ptDefined, canRemedy = uncheckedTypeExtractor.nonEmpty) treeTyped setType ownType @@ -5100,24 +5124,38 @@ trait Typers extends Adaptations with Tags { treeCopy.ReferenceToBoxed(tree, id1) setType tpe } - def typedLiteral(tree: Literal) = { - val value = tree.value - // Warn about likely interpolated strings which are missing their interpolators - if (settings.lint) value match { + // Warn about likely interpolated strings which are missing their interpolators + def warnMissingInterpolator(tree: Literal) { + // Unfortunately implicit not found strings looks for all the world like + // missing interpolators. + def isArgToImplicitNotFound = context.enclosingApply.tree match { + case Apply(fn, _) => fn.symbol.enclClass == ImplicitNotFoundClass + case _ => false + } + tree.value match { case Constant(s: String) => def names = InterpolatorIdentRegex findAllIn s map (n => newTermName(n stripPrefix "$")) - val shouldWarn = ( + def suspicious = ( (InterpolatorCodeRegex findFirstIn s).nonEmpty || (names exists (n => context.lookupSymbol(n, _ => true).symbol.exists)) ) - if (shouldWarn) + val noWarn = ( + isArgToImplicitNotFound + || !(s contains ' ') // another heuristic - e.g. a string with only "$asInstanceOf" + ) + if (!noWarn && suspicious) unit.warning(tree.pos, "looks like an interpolated String; did you forget the interpolator?") case _ => } + } + + def typedLiteral(tree: Literal) = { + if (settings.lint) + warnMissingInterpolator(tree) tree setType ( - if (value.tag == UnitTag) UnitClass.tpe - else ConstantType(value)) + if (tree.value.tag == UnitTag) UnitClass.tpe + else ConstantType(tree.value)) } def typedSingletonTypeTree(tree: SingletonTypeTree) = { @@ -5136,8 +5174,8 @@ trait Typers extends Adaptations with Tags { } def typedTypeBoundsTree(tree: TypeBoundsTree) = { - val lo1 = typedType(tree.lo, mode) - val hi1 = typedType(tree.hi, mode) + val lo1 = if (tree.lo.isEmpty) TypeTree(NothingTpe) else typedType(tree.lo, mode) + val hi1 = if (tree.hi.isEmpty) TypeTree(AnyTpe) else typedType(tree.hi, mode) treeCopy.TypeBoundsTree(tree, lo1, hi1) setType TypeBounds(lo1.tpe, hi1.tpe) } @@ -5298,7 +5336,7 @@ trait Typers extends Adaptations with Tags { } def atOwner(owner: Symbol): Typer = - newTyper(context.make(context.tree, owner)) + newTyper(context.make(owner = owner)) def atOwner(tree: Tree, owner: Symbol): Typer = newTyper(context.make(tree, owner)) @@ -5359,7 +5397,10 @@ trait Typers extends Adaptations with Tags { // as a compromise, context.enrichmentEnabled tells adaptToMember to go ahead and enrich, // but arbitrary conversions (in adapt) are disabled // TODO: can we achieve the pattern matching bit of the string interpolation SIP without this? - typingInPattern(context.withImplicitsDisabledAllowEnrichment(typed(tree, PATTERNmode, pt))) + typingInPattern(context.withImplicitsDisabledAllowEnrichment(typed(tree, PATTERNmode, pt))) match { + case tpt if tpt.isType => PatternMustBeValue(tpt, pt); tpt + case pat => pat + } } /** Types a (fully parameterized) type tree */ diff --git a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala index d55dce70c7..af3f772f79 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala @@ -33,12 +33,13 @@ trait Unapplies extends ast.TreeDSL /** returns type list for return type of the extraction * @see extractorFormalTypes */ - def unapplyTypeList(pos: Position, ufn: Symbol, ufntpe: Type, nbSubPats: Int) = { + def unapplyTypeList(pos: Position, ufn: Symbol, ufntpe: Type, args: List[Tree]) = { assert(ufn.isMethod, ufn) + val nbSubPats = args.length //Console.println("utl "+ufntpe+" "+ufntpe.typeSymbol) ufn.name match { case nme.unapply | nme.unapplySeq => - val (formals, _) = extractorFormalTypes(pos, unapplyUnwrap(ufntpe), nbSubPats, ufn) + val (formals, _) = extractorFormalTypes(pos, unapplyUnwrap(ufntpe), nbSubPats, ufn, treeInfo.effectivePatternArity(args)) if (formals == null) throw new TypeError(s"$ufn of type $ufntpe cannot extract $nbSubPats sub-patterns") else formals case _ => throw new TypeError(ufn+" is not an unapply or unapplySeq") diff --git a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala index 26d19906c2..58a5442465 100644 --- a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala +++ b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package util import scala.reflect.internal.Chars._ diff --git a/src/compiler/scala/tools/nsc/util/ShowPickled.scala b/src/compiler/scala/tools/nsc/util/ShowPickled.scala index 76b1394b85..f9d706ae55 100644 --- a/src/compiler/scala/tools/nsc/util/ShowPickled.scala +++ b/src/compiler/scala/tools/nsc/util/ShowPickled.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools +package scala +package tools package nsc package util diff --git a/src/compiler/scala/tools/nsc/util/package.scala b/src/compiler/scala/tools/nsc/util/package.scala index 039fec8605..5faa2f7513 100644 --- a/src/compiler/scala/tools/nsc/util/package.scala +++ b/src/compiler/scala/tools/nsc/util/package.scala @@ -3,7 +3,9 @@ * @author Paul Phillips */ -package scala.tools.nsc +package scala +package tools +package nsc import java.io.{ OutputStream, PrintStream, ByteArrayOutputStream, PrintWriter, StringWriter } diff --git a/src/compiler/scala/tools/reflect/FastTrack.scala b/src/compiler/scala/tools/reflect/FastTrack.scala index aa4ddc8ba8..3cf19396ee 100644 --- a/src/compiler/scala/tools/reflect/FastTrack.scala +++ b/src/compiler/scala/tools/reflect/FastTrack.scala @@ -26,7 +26,7 @@ trait FastTrack { final class FastTrackEntry(pf: PartialFunction[Applied, MacroContext => Tree]) extends (MacroArgs => Any) { def validate(tree: Tree) = pf isDefinedAt Applied(tree) - def apply(margs: MacroArgs) = { + def apply(margs: MacroArgs): margs.c.Expr[Nothing] = { val MacroArgs(c, _) = margs // Macros validated that the pf is defined here - and there's not much we could do if it weren't. c.Expr[Nothing](pf(Applied(c.expandee))(c))(c.WeakTypeTag.Nothing) diff --git a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala index f6ed5f8f1c..7f7bcd70d2 100644 --- a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala +++ b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala @@ -1,4 +1,5 @@ -package scala.tools +package scala +package tools package reflect import scala.tools.nsc.EXPRmode @@ -181,14 +182,15 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => (currentTyper, tree) => { trace("inferring implicit %s (macros = %s): ".format(if (isView) "view" else "value", !withMacrosDisabled))(showAttributed(pt, true, true, settings.Yshowsymkinds.value)) val context = currentTyper.context - analyzer.inferImplicit(tree, pt, reportAmbiguous = true, isView = isView, context = context, saveAmbiguousDivergent = !silent, pos = pos) match { - case failure if failure.tree.isEmpty => - trace("implicit search has failed. to find out the reason, turn on -Xlog-implicits: ")(failure.tree) - if (context.hasErrors) throw ToolBoxError("reflective implicit search has failed: %s".format(context.errBuffer.head.errMsg)) - EmptyTree - case success => - success.tree + val result = analyzer.inferImplicit(tree, pt, reportAmbiguous = true, isView = isView, context = context, saveAmbiguousDivergent = !silent, pos = pos) + if (result.isFailure) { + // @H: what's the point of tracing an empty tree? + trace("implicit search has failed. to find out the reason, turn on -Xlog-implicits: ")(result.tree) + context.firstError foreach { err => + throw ToolBoxError("reflective implicit search has failed: %s".format(err.errMsg)) + } } + result.tree }) def compile(expr0: Tree): () => Any = { diff --git a/src/compiler/scala/tools/util/PathResolver.scala b/src/compiler/scala/tools/util/PathResolver.scala index 8d65c40a01..863cbc5c1a 100644 --- a/src/compiler/scala/tools/util/PathResolver.scala +++ b/src/compiler/scala/tools/util/PathResolver.scala @@ -3,13 +3,14 @@ * @author Paul Phillips */ -package scala.tools +package scala +package tools package util import scala.tools.reflect.WrappedProperties.AccessControl -import nsc.{ Settings, GenericRunnerSettings } -import nsc.util.{ ClassPath, JavaClassPath, ScalaClassLoader } -import nsc.io.{ File, Directory, Path, AbstractFile } +import scala.tools.nsc.{ Settings, GenericRunnerSettings } +import scala.tools.nsc.util.{ ClassPath, JavaClassPath, ScalaClassLoader } +import scala.tools.nsc.io.{ File, Directory, Path, AbstractFile } import ClassPath.{ JavaContext, DefaultJavaContext, join, split } import PartialFunction.condOpt import scala.language.postfixOps diff --git a/src/compiler/scala/tools/util/SocketServer.scala b/src/compiler/scala/tools/util/SocketServer.scala index 7da9479dab..1d39a59cf4 100644 --- a/src/compiler/scala/tools/util/SocketServer.scala +++ b/src/compiler/scala/tools/util/SocketServer.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.tools.util +package scala +package tools.util import java.net.{ ServerSocket, SocketException, SocketTimeoutException } import java.io.{ PrintWriter, BufferedReader } diff --git a/src/compiler/scala/tools/util/VerifyClass.scala b/src/compiler/scala/tools/util/VerifyClass.scala index d208a9f9c2..3c203e1cf2 100644 --- a/src/compiler/scala/tools/util/VerifyClass.scala +++ b/src/compiler/scala/tools/util/VerifyClass.scala @@ -3,7 +3,7 @@ package scala.tools.util import scala.tools.nsc.io._ import java.net.URLClassLoader import scala.collection.JavaConverters._ - +import scala.language.postfixOps object VerifyClass { diff --git a/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala b/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala index c5136c752b..c38c7c8257 100644 --- a/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala +++ b/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala @@ -43,8 +43,6 @@ import scala.tools.nsc.util.InterruptReq */ trait CompilerControl { self: Global => - import syntaxAnalyzer.UnitParser - type Response[T] = scala.tools.nsc.interactive.Response[T] /** The scheduler by which client and compiler communicate @@ -297,6 +295,9 @@ trait CompilerControl { self: Global => val tpe: Type val accessible: Boolean def implicitlyAdded = false + + private def accessible_s = if (accessible) "" else "[inaccessible] " + def infoString = s"$accessible_s${sym.defStringSeenAs(tpe)}" } case class TypeMember( diff --git a/src/interactive/scala/tools/nsc/interactive/Global.scala b/src/interactive/scala/tools/nsc/interactive/Global.scala index dbdb2d02b6..c9b4603d74 100644 --- a/src/interactive/scala/tools/nsc/interactive/Global.scala +++ b/src/interactive/scala/tools/nsc/interactive/Global.scala @@ -15,14 +15,13 @@ import scala.reflect.internal.util.{ SourceFile, BatchSourceFile, Position, NoPo import scala.tools.nsc.reporters._ import scala.tools.nsc.symtab._ import scala.tools.nsc.doc.ScaladocAnalyzer -import scala.tools.nsc.typechecker.{ Analyzer, DivergentImplicit } +import scala.tools.nsc.typechecker.Analyzer import symtab.Flags.{ACCESSOR, PARAMACCESSOR} import scala.annotation.{ elidable, tailrec } import scala.language.implicitConversions trait InteractiveScaladocAnalyzer extends InteractiveAnalyzer with ScaladocAnalyzer { val global : Global - import global._ override def newTyper(context: Context) = new Typer(context) with InteractiveTyper with ScaladocTyper { override def canAdaptConstantTypeToLiteral = false } @@ -906,9 +905,9 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") /** Implements CompilerControl.askDocComment */ private[interactive] def getDocComment(sym: Symbol, source: SourceFile, site: Symbol, fragments: List[(Symbol,SourceFile)], response: Response[(String, String, Position)]) { - informIDE(s"getDocComment $sym at $source site $site") + informIDE(s"getDocComment $sym at $source, site $site") respond(response) { - withTempUnits(fragments.toList.unzip._2){ units => + withTempUnits(fragments.unzip._2){ units => for((sym, src) <- fragments) { val mirror = findMirrorSymbol(sym, units(src)) if (mirror ne NoSymbol) forceDocComment(mirror, units(src)) @@ -921,6 +920,8 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") } } } + // New typer run to remove temp units and drop per-run caches that might refer to symbols entered from temp units. + newTyperRun() } def stabilizedType(tree: Tree): Type = tree match { @@ -1034,23 +1035,21 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") } private def typeMembers(pos: Position): Stream[List[TypeMember]] = { - var tree = typedTreeAt(pos) - - // if tree consists of just x. or x.fo where fo is not yet a full member name - // ignore the selection and look in just x. - tree match { - case Select(qual, name) if tree.tpe == ErrorType => tree = qual - case _ => + // Choosing which tree will tell us the type members at the given position: + // If pos leads to an Import, type the expr + // If pos leads to a Select, type the qualifier as long as it is not erroneous + // (this implies discarding the possibly incomplete name in the Select node) + // Otherwise, type the tree found at 'pos' directly. + val tree0 = typedTreeAt(pos) match { + case sel @ Select(qual, _) if sel.tpe == ErrorType => qual + case Import(expr, _) => expr + case t => t } - val context = doLocateContext(pos) - - if (tree.tpe == null) - // TODO: guard with try/catch to deal with ill-typed qualifiers. - tree = analyzer.newTyper(context).typedQualifier(tree) + // TODO: guard with try/catch to deal with ill-typed qualifiers. + val tree = if (tree0.tpe eq null) analyzer newTyper context typedQualifier tree0 else tree0 debugLog("typeMembers at "+tree+" "+tree.tpe) - val superAccess = tree.isInstanceOf[Super] val members = new Members[TypeMember] @@ -1211,9 +1210,6 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") case ex: TypeError => debugLog("type error caught: "+ex) alt - case ex: DivergentImplicit => - debugLog("divergent implicit caught: "+ex) - alt } } diff --git a/src/interactive/scala/tools/nsc/interactive/REPL.scala b/src/interactive/scala/tools/nsc/interactive/REPL.scala index 432400ecd2..daa1c21c4a 100644 --- a/src/interactive/scala/tools/nsc/interactive/REPL.scala +++ b/src/interactive/scala/tools/nsc/interactive/REPL.scala @@ -2,7 +2,8 @@ * Copyright 2009-2013 Typesafe/Scala Solutions and LAMP/EPFL * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package interactive import scala.reflect.internal.util._ diff --git a/src/interactive/scala/tools/nsc/interactive/RangePositions.scala b/src/interactive/scala/tools/nsc/interactive/RangePositions.scala index a24be50b33..410f919daa 100644 --- a/src/interactive/scala/tools/nsc/interactive/RangePositions.scala +++ b/src/interactive/scala/tools/nsc/interactive/RangePositions.scala @@ -7,9 +7,8 @@ package scala.tools.nsc package interactive @deprecated("Use scala.reflect.internal.Positions", "2.11.0") -trait RangePositions extends { - override val useOffsetPositions = false -} with scala.reflect.internal.Positions with ast.Trees with ast.Positions { +trait RangePositions extends scala.reflect.internal.Positions with ast.Trees with ast.Positions { self: scala.tools.nsc.Global => + override val useOffsetPositions = false } diff --git a/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala b/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala index 7af9174704..ae70a74b60 100644 --- a/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala +++ b/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala @@ -1,4 +1,5 @@ -package scala.tools.nsc +package scala +package tools.nsc package interactive import scala.reflect.internal.util.{SourceFile, BatchSourceFile, RangePosition} diff --git a/src/interactive/scala/tools/nsc/interactive/tests/Tester.scala b/src/interactive/scala/tools/nsc/interactive/tests/Tester.scala index 8a47c1df37..a678c41718 100644 --- a/src/interactive/scala/tools/nsc/interactive/tests/Tester.scala +++ b/src/interactive/scala/tools/nsc/interactive/tests/Tester.scala @@ -2,7 +2,8 @@ * Copyright 2009-2013 Typesafe/Scala Solutions and LAMP/EPFL * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package interactive package tests diff --git a/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala b/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala index c0ad245091..08d84af8f5 100644 --- a/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala +++ b/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala @@ -16,21 +16,18 @@ private[tests] trait CoreTestDefs extends PresentationCompilerTestDef with AskCompletionAt { - def memberPrinter(member: compiler.Member): String = - "[accessible: %5s] ".format(member.accessible) + "`" + (member.sym.toString.trim + member.tpe.toString()).trim + "`" - override def runTest() { askAllSources(CompletionMarker) { pos => askCompletionAt(pos) } { (pos, members) => withResponseDelimiter { - reporter.println("[response] aksTypeCompletion at " + format(pos)) + reporter.println("[response] askCompletionAt " + format(pos)) // we skip getClass because it changed signature between 1.5 and 1.6, so there is no // universal check file that we can provide for this to work reporter.println("retrieved %d members".format(members.size)) compiler ask { () => val filtered = members.filterNot(member => (member.sym.name string_== "getClass") || member.sym.isConstructor) - reporter.println(filtered.map(memberPrinter).sortBy(_.toString()).mkString("\n")) + reporter println (filtered.map(_.infoString).sorted mkString "\n") } } } @@ -48,7 +45,7 @@ private[tests] trait CoreTestDefs askTypeAt(pos) } { (pos, tree) => withResponseDelimiter { - reporter.println("[response] askTypeAt at " + format(pos)) + reporter.println("[response] askTypeAt " + format(pos)) compiler.ask(() => reporter.println(tree)) } } diff --git a/src/jline/build.sbt b/src/jline/build.sbt index 4fc3bab28a..873f7574f1 100644 --- a/src/jline/build.sbt +++ b/src/jline/build.sbt @@ -4,9 +4,9 @@ name := "jline" organization := "org.scala-lang" -version := "2.10.0-SNAPSHOT" +version := "2.11.0-SNAPSHOT" -scalaVersion := "2.9.0-1" +scalaVersion := "2.10.1" // Only need these because of weird testing jline issues. retrieveManaged := true @@ -14,11 +14,11 @@ retrieveManaged := true parallelExecution in Test := false libraryDependencies ++= Seq( - "org.fusesource.jansi" % "jansi" % "1.4", - "com.novocode" % "junit-interface" % "0.7" % "test->default" + "org.fusesource.jansi" % "jansi" % "1.10", + "com.novocode" % "junit-interface" % "0.9" % "test->default" ) -javacOptions ++= Seq("-target", "1.5") +javacOptions ++= Seq("-source", "1.5", "-target", "1.5") proguardOptions ++= Seq( "-dontshrink", diff --git a/src/jline/manual-test.sh b/src/jline/manual-test.sh index aa5131c903..744e1756e8 100755 --- a/src/jline/manual-test.sh +++ b/src/jline/manual-test.sh @@ -3,6 +3,7 @@ # Apparently the jline bundled with sbt interferes with testing some # changes: for instance after changing the keybindings I kept seeing # failures until I realized what was happening and bypassed sbt, like this. +CP=lib_managed/jars/com.novocode/junit-interface/junit-interface-0.9.jar:lib_managed/jars/junit/junit-dep/junit-dep-4.8.2.jar:lib_managed/jars/org.fusesource.jansi/jansi/jansi-1.10.jar:lib_managed/jars/org.hamcrest/hamcrest-core/hamcrest-core-1.1.jar:lib_managed/jars/org.scala-tools.testing/test-interface/test-interface-0.5.jar:target/scala-2.10/test-classes:target/scala-2.10/jline_2.10-2.11.0-SNAPSHOT.min.jar -java -cp lib_managed/jar/com.novocode/junit-interface/junit-interface-0.5.jar:lib_managed/jar/junit/junit/junit-4.8.1.jar:lib_managed/jar/org.fusesource.jansi/jansi/jansi-1.4.jar:lib_managed/jar/org.scala-tools.testing/test-interface/test-interface-0.5.jar:target/scala-2.9.0.1/test-classes:target/scala-2.9.0.1/jline_2.9.0-1-2.10.0-SNAPSHOT.jar \ -org.junit.runner.JUnitCore scala.tools.jline.console.EditLineTest +sbt proguard +java -cp $CP org.junit.runner.JUnitCore scala.tools.jline.console.EditLineTest diff --git a/src/jline/project/build.properties b/src/jline/project/build.properties new file mode 100644 index 0000000000..9b860e23c5 --- /dev/null +++ b/src/jline/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.12.3 diff --git a/src/jline/project/plugins.sbt b/src/jline/project/plugins.sbt new file mode 100644 index 0000000000..9c13de92d8 --- /dev/null +++ b/src/jline/project/plugins.sbt @@ -0,0 +1,3 @@ +resolvers += Resolver.url("sbt-plugin-releases-scalasbt", url("http://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/"))(Resolver.ivyStylePatterns) + +addSbtPlugin("org.scala-sbt" % "xsbt-proguard-plugin" % "0.1.3") diff --git a/src/jline/project/plugins/build.sbt b/src/jline/project/plugins/build.sbt deleted file mode 100644 index 0e0f27b1eb..0000000000 --- a/src/jline/project/plugins/build.sbt +++ /dev/null @@ -1,5 +0,0 @@ -resolvers += "Proguard plugin repo" at "http://siasia.github.com/maven2" - -libraryDependencies <<= (libraryDependencies, appConfiguration) { (deps, app) => - deps :+ "com.github.siasia" %% "xsbt-proguard-plugin" % app.provider.id.version -} diff --git a/src/library/scala/Boolean.scala b/src/library/scala/Boolean.scala index e43b7d0a82..ddd11257c6 100644 --- a/src/library/scala/Boolean.scala +++ b/src/library/scala/Boolean.scala @@ -10,6 +10,8 @@ package scala +import scala.language.implicitConversions + /** `Boolean` (equivalent to Java's `boolean` primitive type) is a * subtype of [[scala.AnyVal]]. Instances of `Boolean` are not * represented by an object in the underlying runtime system. @@ -114,6 +116,8 @@ object Boolean extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToBoolean`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Boolean to be boxed * @return a java.lang.Boolean offering `x` as its underlying value. */ @@ -123,6 +127,8 @@ object Boolean extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Boolean. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToBoolean`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Boolean to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Boolean * @return the Boolean resulting from calling booleanValue() on `x` diff --git a/src/library/scala/Byte.scala b/src/library/scala/Byte.scala index d1979236d3..2510e859c0 100644 --- a/src/library/scala/Byte.scala +++ b/src/library/scala/Byte.scala @@ -606,6 +606,8 @@ object Byte extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToByte`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Byte to be boxed * @return a java.lang.Byte offering `x` as its underlying value. */ @@ -615,6 +617,8 @@ object Byte extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Byte. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToByte`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Byte to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Byte * @return the Byte resulting from calling byteValue() on `x` diff --git a/src/library/scala/Char.scala b/src/library/scala/Char.scala index 00ddff5b3b..1c9a2ba44f 100644 --- a/src/library/scala/Char.scala +++ b/src/library/scala/Char.scala @@ -606,6 +606,8 @@ object Char extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToCharacter`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Char to be boxed * @return a java.lang.Character offering `x` as its underlying value. */ @@ -615,6 +617,8 @@ object Char extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Character. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToChar`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Character to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Character * @return the Char resulting from calling charValue() on `x` diff --git a/src/library/scala/Double.scala b/src/library/scala/Double.scala index 85bf9fe5c5..ce081bbec1 100644 --- a/src/library/scala/Double.scala +++ b/src/library/scala/Double.scala @@ -10,6 +10,8 @@ package scala +import scala.language.implicitConversions + /** `Double`, a 64-bit IEEE-754 floating point number (equivalent to Java's `double` primitive type) is a * subtype of [[scala.AnyVal]]. Instances of `Double` are not * represented by an object in the underlying runtime system. @@ -380,6 +382,8 @@ object Double extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToDouble`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Double to be boxed * @return a java.lang.Double offering `x` as its underlying value. */ @@ -389,6 +393,8 @@ object Double extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Double. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToDouble`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Double to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Double * @return the Double resulting from calling doubleValue() on `x` diff --git a/src/library/scala/Float.scala b/src/library/scala/Float.scala index f67f45897f..4ff2d509b8 100644 --- a/src/library/scala/Float.scala +++ b/src/library/scala/Float.scala @@ -382,6 +382,8 @@ object Float extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToFloat`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Float to be boxed * @return a java.lang.Float offering `x` as its underlying value. */ @@ -391,6 +393,8 @@ object Float extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Float. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToFloat`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Float to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Float * @return the Float resulting from calling floatValue() on `x` diff --git a/src/library/scala/Int.scala b/src/library/scala/Int.scala index 1bacdbcee9..6a27195b10 100644 --- a/src/library/scala/Int.scala +++ b/src/library/scala/Int.scala @@ -606,6 +606,8 @@ object Int extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToInteger`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Int to be boxed * @return a java.lang.Integer offering `x` as its underlying value. */ @@ -615,6 +617,8 @@ object Int extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Integer. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToInt`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Integer to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Integer * @return the Int resulting from calling intValue() on `x` diff --git a/src/library/scala/Long.scala b/src/library/scala/Long.scala index 83adcda819..4d369ae010 100644 --- a/src/library/scala/Long.scala +++ b/src/library/scala/Long.scala @@ -606,6 +606,8 @@ object Long extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToLong`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Long to be boxed * @return a java.lang.Long offering `x` as its underlying value. */ @@ -615,6 +617,8 @@ object Long extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Long. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToLong`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Long to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Long * @return the Long resulting from calling longValue() on `x` diff --git a/src/library/scala/Short.scala b/src/library/scala/Short.scala index cdd298e542..4f91c51550 100644 --- a/src/library/scala/Short.scala +++ b/src/library/scala/Short.scala @@ -606,6 +606,8 @@ object Short extends AnyValCompanion { /** Transform a value type into a boxed reference type. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToShort`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the Short to be boxed * @return a java.lang.Short offering `x` as its underlying value. */ @@ -615,6 +617,8 @@ object Short extends AnyValCompanion { * method is not typesafe: it accepts any Object, but will throw * an exception if the argument is not a java.lang.Short. * + * Runtime implementation determined by `scala.runtime.BoxesRunTime.unboxToShort`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. + * * @param x the java.lang.Short to be unboxed. * @throws ClassCastException if the argument is not a java.lang.Short * @return the Short resulting from calling shortValue() on `x` diff --git a/src/library/scala/Unit.scala b/src/library/scala/Unit.scala index 01e592ec3c..0e59a184d1 100644 --- a/src/library/scala/Unit.scala +++ b/src/library/scala/Unit.scala @@ -10,6 +10,9 @@ package scala +import scala.language.implicitConversions + + /** `Unit` is a subtype of [[scala.AnyVal]]. There is only one value of type * `Unit`, `()`, and it is not represented by any object in the underlying * runtime system. A method with return type `Unit` is analogous to a Java diff --git a/src/library/scala/collection/BitSet.scala b/src/library/scala/collection/BitSet.scala index 6985563da2..e255e96140 100644 --- a/src/library/scala/collection/BitSet.scala +++ b/src/library/scala/collection/BitSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/BitSetLike.scala b/src/library/scala/collection/BitSetLike.scala index 9c4e710558..f11f3757a6 100644 --- a/src/library/scala/collection/BitSetLike.scala +++ b/src/library/scala/collection/BitSetLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import BitSetLike._ import mutable.StringBuilder diff --git a/src/library/scala/collection/BufferedIterator.scala b/src/library/scala/collection/BufferedIterator.scala index 741bca4e46..e6e97d584c 100644 --- a/src/library/scala/collection/BufferedIterator.scala +++ b/src/library/scala/collection/BufferedIterator.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection /** Buffered iterators are iterators which provide a method `head` * that inspects the next element without discarding it. diff --git a/src/library/scala/collection/CustomParallelizable.scala b/src/library/scala/collection/CustomParallelizable.scala index 53fe32b89f..cbeb28d643 100644 --- a/src/library/scala/collection/CustomParallelizable.scala +++ b/src/library/scala/collection/CustomParallelizable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import parallel.Combiner diff --git a/src/library/scala/collection/DefaultMap.scala b/src/library/scala/collection/DefaultMap.scala index bbd6b2c2fc..8afda7cfcf 100644 --- a/src/library/scala/collection/DefaultMap.scala +++ b/src/library/scala/collection/DefaultMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** A default map which implements the `+` and `-` methods of maps. * diff --git a/src/library/scala/collection/GenIterable.scala b/src/library/scala/collection/GenIterable.scala index b4e7a14ade..6fd4158726 100644 --- a/src/library/scala/collection/GenIterable.scala +++ b/src/library/scala/collection/GenIterable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenIterableLike.scala b/src/library/scala/collection/GenIterableLike.scala index ceb97707e1..1dbb54ddc7 100644 --- a/src/library/scala/collection/GenIterableLike.scala +++ b/src/library/scala/collection/GenIterableLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic.{ CanBuildFrom => CBF } diff --git a/src/library/scala/collection/GenIterableView.scala b/src/library/scala/collection/GenIterableView.scala index 5ab48efdf3..cd052ddf79 100644 --- a/src/library/scala/collection/GenIterableView.scala +++ b/src/library/scala/collection/GenIterableView.scala @@ -6,6 +6,7 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection trait GenIterableView[+A, +Coll] extends GenIterableViewLike[A, Coll, GenIterableView[A, Coll]] { } diff --git a/src/library/scala/collection/GenIterableViewLike.scala b/src/library/scala/collection/GenIterableViewLike.scala index e8d264cdd4..b519e99ae5 100644 --- a/src/library/scala/collection/GenIterableViewLike.scala +++ b/src/library/scala/collection/GenIterableViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection trait GenIterableViewLike[+A, +Coll, diff --git a/src/library/scala/collection/GenMap.scala b/src/library/scala/collection/GenMap.scala index f7b2ae4d70..3d7427981d 100644 --- a/src/library/scala/collection/GenMap.scala +++ b/src/library/scala/collection/GenMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenMapLike.scala b/src/library/scala/collection/GenMapLike.scala index 367377a59c..4e7d359251 100644 --- a/src/library/scala/collection/GenMapLike.scala +++ b/src/library/scala/collection/GenMapLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** A trait for all maps upon which operations may be * implemented in parallel. diff --git a/src/library/scala/collection/GenSeq.scala b/src/library/scala/collection/GenSeq.scala index 4c5488d7e2..480562cab5 100644 --- a/src/library/scala/collection/GenSeq.scala +++ b/src/library/scala/collection/GenSeq.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenSeqLike.scala b/src/library/scala/collection/GenSeqLike.scala index 78d63348c0..27b75c0491 100644 --- a/src/library/scala/collection/GenSeqLike.scala +++ b/src/library/scala/collection/GenSeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenSeqView.scala b/src/library/scala/collection/GenSeqView.scala index 423f8e305e..0a214832ad 100644 --- a/src/library/scala/collection/GenSeqView.scala +++ b/src/library/scala/collection/GenSeqView.scala @@ -6,6 +6,7 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection trait GenSeqView[+A, +Coll] extends GenSeqViewLike[A, Coll, GenSeqView[A, Coll]] { } diff --git a/src/library/scala/collection/GenSeqViewLike.scala b/src/library/scala/collection/GenSeqViewLike.scala index 51600218ad..d3af953f72 100644 --- a/src/library/scala/collection/GenSeqViewLike.scala +++ b/src/library/scala/collection/GenSeqViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection diff --git a/src/library/scala/collection/GenSet.scala b/src/library/scala/collection/GenSet.scala index 832177b128..2467860095 100644 --- a/src/library/scala/collection/GenSet.scala +++ b/src/library/scala/collection/GenSet.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenSetLike.scala b/src/library/scala/collection/GenSetLike.scala index f22a7c8f09..c5355e58ec 100644 --- a/src/library/scala/collection/GenSetLike.scala +++ b/src/library/scala/collection/GenSetLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** A template trait for sets which may possibly diff --git a/src/library/scala/collection/GenTraversable.scala b/src/library/scala/collection/GenTraversable.scala index 3db2dd77a9..b700f49cf6 100644 --- a/src/library/scala/collection/GenTraversable.scala +++ b/src/library/scala/collection/GenTraversable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenTraversableLike.scala b/src/library/scala/collection/GenTraversableLike.scala index 1080c54325..f4aa063d8a 100644 --- a/src/library/scala/collection/GenTraversableLike.scala +++ b/src/library/scala/collection/GenTraversableLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/GenTraversableOnce.scala b/src/library/scala/collection/GenTraversableOnce.scala index a05ee0fb54..d966c7324b 100644 --- a/src/library/scala/collection/GenTraversableOnce.scala +++ b/src/library/scala/collection/GenTraversableOnce.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import scala.reflect.ClassTag import scala.collection.generic.CanBuildFrom diff --git a/src/library/scala/collection/GenTraversableView.scala b/src/library/scala/collection/GenTraversableView.scala index 1d98eff8c1..7d9a6e9777 100644 --- a/src/library/scala/collection/GenTraversableView.scala +++ b/src/library/scala/collection/GenTraversableView.scala @@ -6,6 +6,7 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection trait GenTraversableView[+A, +Coll] extends GenTraversableViewLike[A, Coll, GenTraversableView[A, Coll]] { } diff --git a/src/library/scala/collection/GenTraversableViewLike.scala b/src/library/scala/collection/GenTraversableViewLike.scala index 8c9607663b..dde18a7a32 100644 --- a/src/library/scala/collection/GenTraversableViewLike.scala +++ b/src/library/scala/collection/GenTraversableViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/IndexedSeq.scala b/src/library/scala/collection/IndexedSeq.scala index 0b6e640537..1a33026101 100644 --- a/src/library/scala/collection/IndexedSeq.scala +++ b/src/library/scala/collection/IndexedSeq.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/IndexedSeqLike.scala b/src/library/scala/collection/IndexedSeqLike.scala index 473202a8eb..18c9175ee1 100644 --- a/src/library/scala/collection/IndexedSeqLike.scala +++ b/src/library/scala/collection/IndexedSeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import mutable.ArrayBuffer import scala.annotation.tailrec diff --git a/src/library/scala/collection/Iterable.scala b/src/library/scala/collection/Iterable.scala index 09c9ce122c..973efc447e 100644 --- a/src/library/scala/collection/Iterable.scala +++ b/src/library/scala/collection/Iterable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/IterableProxy.scala b/src/library/scala/collection/IterableProxy.scala index ddb2502965..3a0e2ab115 100644 --- a/src/library/scala/collection/IterableProxy.scala +++ b/src/library/scala/collection/IterableProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** This trait implements a proxy for iterable objects. It forwards all calls * to a different iterable object. diff --git a/src/library/scala/collection/IterableProxyLike.scala b/src/library/scala/collection/IterableProxyLike.scala index 6968a54399..9b8f6f3742 100644 --- a/src/library/scala/collection/IterableProxyLike.scala +++ b/src/library/scala/collection/IterableProxyLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ import mutable.Buffer diff --git a/src/library/scala/collection/IterableView.scala b/src/library/scala/collection/IterableView.scala index 985556e0d4..1d631739aa 100644 --- a/src/library/scala/collection/IterableView.scala +++ b/src/library/scala/collection/IterableView.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ import TraversableView.NoBuilder diff --git a/src/library/scala/collection/IterableViewLike.scala b/src/library/scala/collection/IterableViewLike.scala index b195ae4bc7..236bfd154c 100644 --- a/src/library/scala/collection/IterableViewLike.scala +++ b/src/library/scala/collection/IterableViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import immutable.Stream diff --git a/src/library/scala/collection/JavaConversions.scala b/src/library/scala/collection/JavaConversions.scala index 3cb7edacd6..b527b34f10 100644 --- a/src/library/scala/collection/JavaConversions.scala +++ b/src/library/scala/collection/JavaConversions.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import convert._ diff --git a/src/library/scala/collection/JavaConverters.scala b/src/library/scala/collection/JavaConverters.scala index 7700d90560..80dbf4b19d 100755 --- a/src/library/scala/collection/JavaConverters.scala +++ b/src/library/scala/collection/JavaConverters.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import convert._ diff --git a/src/library/scala/collection/LinearSeq.scala b/src/library/scala/collection/LinearSeq.scala index e52a1936fe..1e4975a0a7 100644 --- a/src/library/scala/collection/LinearSeq.scala +++ b/src/library/scala/collection/LinearSeq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/LinearSeqLike.scala b/src/library/scala/collection/LinearSeqLike.scala index a4bb194f8a..ff7985bf0d 100644 --- a/src/library/scala/collection/LinearSeqLike.scala +++ b/src/library/scala/collection/LinearSeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import immutable.List import scala.annotation.tailrec diff --git a/src/library/scala/collection/LinearSeqOptimized.scala b/src/library/scala/collection/LinearSeqOptimized.scala index 9cf37981f4..21bfedf5de 100755 --- a/src/library/scala/collection/LinearSeqOptimized.scala +++ b/src/library/scala/collection/LinearSeqOptimized.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import mutable.ListBuffer import immutable.List diff --git a/src/library/scala/collection/Map.scala b/src/library/scala/collection/Map.scala index 18ad20a855..f37c0993d4 100644 --- a/src/library/scala/collection/Map.scala +++ b/src/library/scala/collection/Map.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/MapLike.scala b/src/library/scala/collection/MapLike.scala index cc0129202f..5ec7d5c615 100644 --- a/src/library/scala/collection/MapLike.scala +++ b/src/library/scala/collection/MapLike.scala @@ -6,8 +6,8 @@ ** |/ ** \* */ - -package scala.collection +package scala +package collection import generic._ import mutable.{ Builder, MapBuilder } diff --git a/src/library/scala/collection/MapProxy.scala b/src/library/scala/collection/MapProxy.scala index e85d306e6f..941c1f5a4a 100644 --- a/src/library/scala/collection/MapProxy.scala +++ b/src/library/scala/collection/MapProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** This is a simple wrapper class for [[scala.collection.Map]]. * It is most useful for assembling customized map abstractions diff --git a/src/library/scala/collection/MapProxyLike.scala b/src/library/scala/collection/MapProxyLike.scala index ad09f7b970..44481131aa 100644 --- a/src/library/scala/collection/MapProxyLike.scala +++ b/src/library/scala/collection/MapProxyLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection // Methods could be printed by cat MapLike.scala | egrep '^ (override )?def' diff --git a/src/library/scala/collection/Parallel.scala b/src/library/scala/collection/Parallel.scala index 6731f74bea..174e3ab75e 100644 --- a/src/library/scala/collection/Parallel.scala +++ b/src/library/scala/collection/Parallel.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** A marker trait for collections which have their operations parallelised. * diff --git a/src/library/scala/collection/Parallelizable.scala b/src/library/scala/collection/Parallelizable.scala index 626dfa4032..b737752458 100644 --- a/src/library/scala/collection/Parallelizable.scala +++ b/src/library/scala/collection/Parallelizable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import parallel.Combiner diff --git a/src/library/scala/collection/Searching.scala b/src/library/scala/collection/Searching.scala index 03eb4283ad..fec4bbf502 100644 --- a/src/library/scala/collection/Searching.scala +++ b/src/library/scala/collection/Searching.scala @@ -6,8 +6,10 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection +import scala.language.implicitConversions import scala.annotation.tailrec import scala.collection.generic.IsSeqLike import scala.math.Ordering @@ -50,7 +52,7 @@ object Searching { * sequence, or the `InsertionPoint` where the element would be inserted if * the element is not in the sequence. */ - final def search[B >: A](elem: B)(implicit ord: Ordering[B]): SearchResult = + final def search[B >: A](elem: B)(implicit ord: Ordering[B]): SearchResult = coll match { case _: IndexedSeq[A] => binarySearch(elem, -1, coll.length)(ord) case _ => linearSearch(coll.view, elem, 0)(ord) @@ -77,7 +79,7 @@ object Searching { * the element is not in the sequence. */ final def search[B >: A](elem: B, from: Int, to: Int) - (implicit ord: Ordering[B]): SearchResult = + (implicit ord: Ordering[B]): SearchResult = coll match { case _: IndexedSeq[A] => binarySearch(elem, from-1, to)(ord) case _ => linearSearch(coll.view(from, to), elem, from)(ord) diff --git a/src/library/scala/collection/Seq.scala b/src/library/scala/collection/Seq.scala index 33e66c0874..b21acdd9b7 100644 --- a/src/library/scala/collection/Seq.scala +++ b/src/library/scala/collection/Seq.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/SeqExtractors.scala b/src/library/scala/collection/SeqExtractors.scala index 20ea7f54b7..2398313c77 100644 --- a/src/library/scala/collection/SeqExtractors.scala +++ b/src/library/scala/collection/SeqExtractors.scala @@ -1,4 +1,5 @@ -package scala.collection +package scala +package collection /** An extractor used to head/tail deconstruct sequences. */ object +: { diff --git a/src/library/scala/collection/SeqProxy.scala b/src/library/scala/collection/SeqProxy.scala index 1f8dc4aad1..9c5424a3a6 100644 --- a/src/library/scala/collection/SeqProxy.scala +++ b/src/library/scala/collection/SeqProxy.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection /** This trait implements a proxy for sequence objects. It forwards * all calls to a different sequence object. diff --git a/src/library/scala/collection/SeqProxyLike.scala b/src/library/scala/collection/SeqProxyLike.scala index ee88ee3da3..161b23d3f8 100644 --- a/src/library/scala/collection/SeqProxyLike.scala +++ b/src/library/scala/collection/SeqProxyLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/SeqView.scala b/src/library/scala/collection/SeqView.scala index c26124cf6f..40dfd50212 100644 --- a/src/library/scala/collection/SeqView.scala +++ b/src/library/scala/collection/SeqView.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ import TraversableView.NoBuilder diff --git a/src/library/scala/collection/SeqViewLike.scala b/src/library/scala/collection/SeqViewLike.scala index 27536791a2..1194cd7199 100644 --- a/src/library/scala/collection/SeqViewLike.scala +++ b/src/library/scala/collection/SeqViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import Seq.fill diff --git a/src/library/scala/collection/Set.scala b/src/library/scala/collection/Set.scala index c304323d28..46d5dfa056 100644 --- a/src/library/scala/collection/Set.scala +++ b/src/library/scala/collection/Set.scala @@ -6,8 +6,8 @@ ** |/ ** \* */ - -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/SetLike.scala b/src/library/scala/collection/SetLike.scala index 9fd24317f2..0c5c7e0b29 100644 --- a/src/library/scala/collection/SetLike.scala +++ b/src/library/scala/collection/SetLike.scala @@ -6,8 +6,8 @@ ** |/ ** \* */ - -package scala.collection +package scala +package collection import generic._ import mutable.{ Builder, SetBuilder } diff --git a/src/library/scala/collection/SetProxy.scala b/src/library/scala/collection/SetProxy.scala index 08075a7121..f9f38f148a 100644 --- a/src/library/scala/collection/SetProxy.scala +++ b/src/library/scala/collection/SetProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection /** This is a simple wrapper class for [[scala.collection.Set]]. * It is most useful for assembling customized set abstractions diff --git a/src/library/scala/collection/SetProxyLike.scala b/src/library/scala/collection/SetProxyLike.scala index 265d1c4806..ac3d34dbab 100644 --- a/src/library/scala/collection/SetProxyLike.scala +++ b/src/library/scala/collection/SetProxyLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection // Methods could be printed by cat SetLike.scala | egrep '^ (override )?def' diff --git a/src/library/scala/collection/SortedMap.scala b/src/library/scala/collection/SortedMap.scala index 86fcfac94d..0705a1e9e0 100644 --- a/src/library/scala/collection/SortedMap.scala +++ b/src/library/scala/collection/SortedMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/SortedMapLike.scala b/src/library/scala/collection/SortedMapLike.scala index 934ed831f5..3fc8b0dadc 100644 --- a/src/library/scala/collection/SortedMapLike.scala +++ b/src/library/scala/collection/SortedMapLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ diff --git a/src/library/scala/collection/SortedSet.scala b/src/library/scala/collection/SortedSet.scala index 2d5d4fb55e..43189d2e8c 100644 --- a/src/library/scala/collection/SortedSet.scala +++ b/src/library/scala/collection/SortedSet.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection import generic._ /** A sorted set. diff --git a/src/library/scala/collection/SortedSetLike.scala b/src/library/scala/collection/SortedSetLike.scala index 6d1d1ac111..eb2ac38c59 100644 --- a/src/library/scala/collection/SortedSetLike.scala +++ b/src/library/scala/collection/SortedSetLike.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection import generic._ /** A template for sets which are sorted. diff --git a/src/library/scala/collection/Traversable.scala b/src/library/scala/collection/Traversable.scala index 4ca2095f4c..61d9a42f04 100644 --- a/src/library/scala/collection/Traversable.scala +++ b/src/library/scala/collection/Traversable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/TraversableLike.scala b/src/library/scala/collection/TraversableLike.scala index fdbc5e9857..00f4de82cd 100644 --- a/src/library/scala/collection/TraversableLike.scala +++ b/src/library/scala/collection/TraversableLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.{ Builder } diff --git a/src/library/scala/collection/TraversableOnce.scala b/src/library/scala/collection/TraversableOnce.scala index fcca2da437..526c36dda7 100644 --- a/src/library/scala/collection/TraversableOnce.scala +++ b/src/library/scala/collection/TraversableOnce.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import mutable.{ Buffer, Builder, ListBuffer, ArrayBuffer } import generic.CanBuildFrom diff --git a/src/library/scala/collection/TraversableProxy.scala b/src/library/scala/collection/TraversableProxy.scala index 568298a9d9..65936da0e4 100644 --- a/src/library/scala/collection/TraversableProxy.scala +++ b/src/library/scala/collection/TraversableProxy.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection // Methods could be printed by cat TraversableLike.scala | egrep '^ (override )?def' diff --git a/src/library/scala/collection/TraversableProxyLike.scala b/src/library/scala/collection/TraversableProxyLike.scala index 8896cd1b0f..77d651c5f2 100644 --- a/src/library/scala/collection/TraversableProxyLike.scala +++ b/src/library/scala/collection/TraversableProxyLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection import generic._ import mutable.{Buffer, StringBuilder} diff --git a/src/library/scala/collection/TraversableView.scala b/src/library/scala/collection/TraversableView.scala index af219084b8..bbb5bde464 100644 --- a/src/library/scala/collection/TraversableView.scala +++ b/src/library/scala/collection/TraversableView.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.Builder diff --git a/src/library/scala/collection/TraversableViewLike.scala b/src/library/scala/collection/TraversableViewLike.scala index 36f6210ef4..c507e000ee 100644 --- a/src/library/scala/collection/TraversableViewLike.scala +++ b/src/library/scala/collection/TraversableViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection import generic._ import mutable.{ Builder, ArrayBuffer } diff --git a/src/library/scala/collection/concurrent/Map.scala b/src/library/scala/collection/concurrent/Map.scala index b2276ce5aa..02e5dd01f5 100644 --- a/src/library/scala/collection/concurrent/Map.scala +++ b/src/library/scala/collection/concurrent/Map.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.concurrent +package scala +package collection.concurrent /** A template trait for mutable maps that allow concurrent access. * diff --git a/src/library/scala/collection/concurrent/TrieMap.scala b/src/library/scala/collection/concurrent/TrieMap.scala index 4eeacd7377..0b5ceeb1c7 100644 --- a/src/library/scala/collection/concurrent/TrieMap.scala +++ b/src/library/scala/collection/concurrent/TrieMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package concurrent import java.util.concurrent.atomic._ @@ -428,10 +429,10 @@ extends MainNode[K, V] with KVNode[K, V] { } -private[collection] final class LNode[K, V](final val listmap: ImmutableListMap[K, V]) +private[collection] final class LNode[K, V](final val listmap: immutable.ListMap[K, V]) extends MainNode[K, V] { - def this(k: K, v: V) = this(ImmutableListMap(k -> v)) - def this(k1: K, v1: V, k2: K, v2: V) = this(ImmutableListMap(k1 -> v1, k2 -> v2)) + def this(k: K, v: V) = this(immutable.ListMap(k -> v)) + def this(k1: K, v1: V, k2: K, v2: V) = this(immutable.ListMap(k1 -> v1, k2 -> v2)) def inserted(k: K, v: V) = new LNode(listmap + ((k, v))) def removed(k: K, ct: TrieMap[K, V]): MainNode[K, V] = { val updmap = listmap - k diff --git a/src/library/scala/collection/convert/DecorateAsJava.scala b/src/library/scala/collection/convert/DecorateAsJava.scala index 7447c1bbaf..498bdc5943 100644 --- a/src/library/scala/collection/convert/DecorateAsJava.scala +++ b/src/library/scala/collection/convert/DecorateAsJava.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package convert import java.{ lang => jl, util => ju }, java.util.{ concurrent => juc } diff --git a/src/library/scala/collection/convert/DecorateAsScala.scala b/src/library/scala/collection/convert/DecorateAsScala.scala index 90e8dded6e..c724831c54 100644 --- a/src/library/scala/collection/convert/DecorateAsScala.scala +++ b/src/library/scala/collection/convert/DecorateAsScala.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package convert import java.{ lang => jl, util => ju }, java.util.{ concurrent => juc } diff --git a/src/library/scala/collection/convert/Decorators.scala b/src/library/scala/collection/convert/Decorators.scala index f004e4712b..d232fa04e1 100644 --- a/src/library/scala/collection/convert/Decorators.scala +++ b/src/library/scala/collection/convert/Decorators.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package convert import java.{ util => ju } diff --git a/src/library/scala/collection/convert/WrapAsJava.scala b/src/library/scala/collection/convert/WrapAsJava.scala index 9665ffa045..e75a0e2981 100644 --- a/src/library/scala/collection/convert/WrapAsJava.scala +++ b/src/library/scala/collection/convert/WrapAsJava.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package convert import java.{ lang => jl, util => ju }, java.util.{ concurrent => juc } diff --git a/src/library/scala/collection/convert/WrapAsScala.scala b/src/library/scala/collection/convert/WrapAsScala.scala index f43eae10d6..d4ab451b0d 100644 --- a/src/library/scala/collection/convert/WrapAsScala.scala +++ b/src/library/scala/collection/convert/WrapAsScala.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package convert import java.{ lang => jl, util => ju }, java.util.{ concurrent => juc } diff --git a/src/library/scala/collection/convert/Wrappers.scala b/src/library/scala/collection/convert/Wrappers.scala index 69e9a8fff4..4410ddc7d8 100644 --- a/src/library/scala/collection/convert/Wrappers.scala +++ b/src/library/scala/collection/convert/Wrappers.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package convert import java.{ lang => jl, util => ju }, java.util.{ concurrent => juc } diff --git a/src/library/scala/collection/convert/package.scala b/src/library/scala/collection/convert/package.scala index ea66101aca..13970f9a3e 100644 --- a/src/library/scala/collection/convert/package.scala +++ b/src/library/scala/collection/convert/package.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package object convert { val decorateAsJava = new DecorateAsJava { } diff --git a/src/library/scala/collection/generic/BitOperations.scala b/src/library/scala/collection/generic/BitOperations.scala index c45ebcf982..d430ece2f5 100644 --- a/src/library/scala/collection/generic/BitOperations.scala +++ b/src/library/scala/collection/generic/BitOperations.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** Some bit operations. diff --git a/src/library/scala/collection/generic/BitSetFactory.scala b/src/library/scala/collection/generic/BitSetFactory.scala index 46e2d29612..2e3aae31ac 100644 --- a/src/library/scala/collection/generic/BitSetFactory.scala +++ b/src/library/scala/collection/generic/BitSetFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import scala.collection._ diff --git a/src/library/scala/collection/generic/CanBuildFrom.scala b/src/library/scala/collection/generic/CanBuildFrom.scala index 73fd4fc026..24e5b2a1dd 100644 --- a/src/library/scala/collection/generic/CanBuildFrom.scala +++ b/src/library/scala/collection/generic/CanBuildFrom.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/CanCombineFrom.scala b/src/library/scala/collection/generic/CanCombineFrom.scala index 9ca3332ba0..7f70b4580a 100644 --- a/src/library/scala/collection/generic/CanCombineFrom.scala +++ b/src/library/scala/collection/generic/CanCombineFrom.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import scala.collection.parallel._ diff --git a/src/library/scala/collection/generic/ClassTagTraversableFactory.scala b/src/library/scala/collection/generic/ClassTagTraversableFactory.scala index 85cdbd7276..e3db40123d 100644 --- a/src/library/scala/collection/generic/ClassTagTraversableFactory.scala +++ b/src/library/scala/collection/generic/ClassTagTraversableFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/Clearable.scala b/src/library/scala/collection/generic/Clearable.scala index a04ecb2a68..3c496051c4 100644 --- a/src/library/scala/collection/generic/Clearable.scala +++ b/src/library/scala/collection/generic/Clearable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** This trait forms part of collections that can be cleared diff --git a/src/library/scala/collection/generic/FilterMonadic.scala b/src/library/scala/collection/generic/FilterMonadic.scala index e21f0be898..8aefbdb926 100755 --- a/src/library/scala/collection/generic/FilterMonadic.scala +++ b/src/library/scala/collection/generic/FilterMonadic.scala @@ -6,8 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic - +package scala +package collection +package generic /** A template trait that contains just the `map`, `flatMap`, `foreach` and `withFilter` methods * of trait `TraversableLike`. diff --git a/src/library/scala/collection/generic/GenMapFactory.scala b/src/library/scala/collection/generic/GenMapFactory.scala index 5a183c307b..ae3150115f 100644 --- a/src/library/scala/collection/generic/GenMapFactory.scala +++ b/src/library/scala/collection/generic/GenMapFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.{Builder, MapBuilder} diff --git a/src/library/scala/collection/generic/GenSeqFactory.scala b/src/library/scala/collection/generic/GenSeqFactory.scala index dd375c567c..6afbb2e2fb 100644 --- a/src/library/scala/collection/generic/GenSeqFactory.scala +++ b/src/library/scala/collection/generic/GenSeqFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/GenSetFactory.scala b/src/library/scala/collection/generic/GenSetFactory.scala index 9774805cf8..800f66eb53 100644 --- a/src/library/scala/collection/generic/GenSetFactory.scala +++ b/src/library/scala/collection/generic/GenSetFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/GenTraversableFactory.scala b/src/library/scala/collection/generic/GenTraversableFactory.scala index 0e1a5534c0..2092c0c5f5 100644 --- a/src/library/scala/collection/generic/GenTraversableFactory.scala +++ b/src/library/scala/collection/generic/GenTraversableFactory.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/GenericClassTagCompanion.scala b/src/library/scala/collection/generic/GenericClassTagCompanion.scala index cdfee5252f..a8ac2bf738 100644 --- a/src/library/scala/collection/generic/GenericClassTagCompanion.scala +++ b/src/library/scala/collection/generic/GenericClassTagCompanion.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/GenericClassTagTraversableTemplate.scala b/src/library/scala/collection/generic/GenericClassTagTraversableTemplate.scala index f327710848..090cd729a4 100644 --- a/src/library/scala/collection/generic/GenericClassTagTraversableTemplate.scala +++ b/src/library/scala/collection/generic/GenericClassTagTraversableTemplate.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/GenericCompanion.scala b/src/library/scala/collection/generic/GenericCompanion.scala index 66052d0e6f..67d0a9c7f7 100644 --- a/src/library/scala/collection/generic/GenericCompanion.scala +++ b/src/library/scala/collection/generic/GenericCompanion.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/GenericOrderedCompanion.scala b/src/library/scala/collection/generic/GenericOrderedCompanion.scala index 7a0c0a63e8..5b328bff6c 100644 --- a/src/library/scala/collection/generic/GenericOrderedCompanion.scala +++ b/src/library/scala/collection/generic/GenericOrderedCompanion.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/GenericOrderedTraversableTemplate.scala b/src/library/scala/collection/generic/GenericOrderedTraversableTemplate.scala index a624e8ca93..c1a41ce7c4 100644 --- a/src/library/scala/collection/generic/GenericOrderedTraversableTemplate.scala +++ b/src/library/scala/collection/generic/GenericOrderedTraversableTemplate.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/GenericParCompanion.scala b/src/library/scala/collection/generic/GenericParCompanion.scala index bb39461e7e..432b9135f8 100644 --- a/src/library/scala/collection/generic/GenericParCompanion.scala +++ b/src/library/scala/collection/generic/GenericParCompanion.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection.parallel.Combiner import scala.collection.parallel.ParIterable diff --git a/src/library/scala/collection/generic/GenericParTemplate.scala b/src/library/scala/collection/generic/GenericParTemplate.scala index 94c76630d6..b9b7043270 100644 --- a/src/library/scala/collection/generic/GenericParTemplate.scala +++ b/src/library/scala/collection/generic/GenericParTemplate.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection.parallel.Combiner import scala.collection.parallel.ParIterable diff --git a/src/library/scala/collection/generic/GenericSeqCompanion.scala b/src/library/scala/collection/generic/GenericSeqCompanion.scala index 8b2f8a0fcb..34b20f23a2 100644 --- a/src/library/scala/collection/generic/GenericSeqCompanion.scala +++ b/src/library/scala/collection/generic/GenericSeqCompanion.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/GenericSetTemplate.scala b/src/library/scala/collection/generic/GenericSetTemplate.scala index ecfdcffbc5..2cadd14948 100644 --- a/src/library/scala/collection/generic/GenericSetTemplate.scala +++ b/src/library/scala/collection/generic/GenericSetTemplate.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds /** diff --git a/src/library/scala/collection/generic/GenericTraversableTemplate.scala b/src/library/scala/collection/generic/GenericTraversableTemplate.scala index 908aa5b126..adf4319bb8 100644 --- a/src/library/scala/collection/generic/GenericTraversableTemplate.scala +++ b/src/library/scala/collection/generic/GenericTraversableTemplate.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/Growable.scala b/src/library/scala/collection/generic/Growable.scala index 52a0d32de1..254d4566be 100644 --- a/src/library/scala/collection/generic/Growable.scala +++ b/src/library/scala/collection/generic/Growable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import scala.annotation.tailrec @@ -47,15 +48,15 @@ trait Growable[-A] extends Clearable { * @return the $coll itself. */ def ++=(xs: TraversableOnce[A]): this.type = { - @tailrec def loop(xs: collection.LinearSeq[A]) { + @tailrec def loop(xs: scala.collection.LinearSeq[A]) { if (xs.nonEmpty) { this += xs.head loop(xs.tail) } } xs.seq match { - case xs: collection.LinearSeq[_] => loop(xs) - case xs => xs foreach += + case xs: scala.collection.LinearSeq[_] => loop(xs) + case xs => xs foreach += } this } diff --git a/src/library/scala/collection/generic/HasNewBuilder.scala b/src/library/scala/collection/generic/HasNewBuilder.scala index 1a981b487f..aa0ce6698d 100755 --- a/src/library/scala/collection/generic/HasNewBuilder.scala +++ b/src/library/scala/collection/generic/HasNewBuilder.scala @@ -5,7 +5,8 @@ ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/HasNewCombiner.scala b/src/library/scala/collection/generic/HasNewCombiner.scala index 1ecfba19af..99a0722c3d 100644 --- a/src/library/scala/collection/generic/HasNewCombiner.scala +++ b/src/library/scala/collection/generic/HasNewCombiner.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection.parallel.Combiner diff --git a/src/library/scala/collection/generic/ImmutableMapFactory.scala b/src/library/scala/collection/generic/ImmutableMapFactory.scala index 4ce50a31f9..7d857bf1b4 100644 --- a/src/library/scala/collection/generic/ImmutableMapFactory.scala +++ b/src/library/scala/collection/generic/ImmutableMapFactory.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/ImmutableSetFactory.scala b/src/library/scala/collection/generic/ImmutableSetFactory.scala index 2e960e670d..f4d4e061bb 100644 --- a/src/library/scala/collection/generic/ImmutableSetFactory.scala +++ b/src/library/scala/collection/generic/ImmutableSetFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.{ Builder, SetBuilder } diff --git a/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala b/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala index 7743fc2281..730e58a527 100644 --- a/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala +++ b/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala b/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala index 9914557b51..1fd4a8c99d 100644 --- a/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala +++ b/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/IndexedSeqFactory.scala b/src/library/scala/collection/generic/IndexedSeqFactory.scala index e86d163b3c..ddc0141aa9 100644 --- a/src/library/scala/collection/generic/IndexedSeqFactory.scala +++ b/src/library/scala/collection/generic/IndexedSeqFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import language.higherKinds diff --git a/src/library/scala/collection/generic/IsSeqLike.scala b/src/library/scala/collection/generic/IsSeqLike.scala index d1dffdf8cf..189aea4632 100644 --- a/src/library/scala/collection/generic/IsSeqLike.scala +++ b/src/library/scala/collection/generic/IsSeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** Type class witnessing that a collection representation type `Repr` has @@ -41,7 +42,7 @@ trait IsSeqLike[Repr] { } object IsSeqLike { - import language.higherKinds + import scala.language.higherKinds implicit val stringRepr: IsSeqLike[String] { type A = Char } = new IsSeqLike[String] { diff --git a/src/library/scala/collection/generic/IsTraversableLike.scala b/src/library/scala/collection/generic/IsTraversableLike.scala index c70772d8f9..22cef555cc 100644 --- a/src/library/scala/collection/generic/IsTraversableLike.scala +++ b/src/library/scala/collection/generic/IsTraversableLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** A trait which can be used to avoid code duplication when defining extension diff --git a/src/library/scala/collection/generic/IsTraversableOnce.scala b/src/library/scala/collection/generic/IsTraversableOnce.scala index bb5404c92d..3ee586ae63 100644 --- a/src/library/scala/collection/generic/IsTraversableOnce.scala +++ b/src/library/scala/collection/generic/IsTraversableOnce.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** Type class witnessing that a collection representation type `Repr` has diff --git a/src/library/scala/collection/generic/IterableForwarder.scala b/src/library/scala/collection/generic/IterableForwarder.scala index 8feace3f8b..5a54ed7f78 100644 --- a/src/library/scala/collection/generic/IterableForwarder.scala +++ b/src/library/scala/collection/generic/IterableForwarder.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection._ diff --git a/src/library/scala/collection/generic/MapFactory.scala b/src/library/scala/collection/generic/MapFactory.scala index 565850bee2..b9f3d4b010 100644 --- a/src/library/scala/collection/generic/MapFactory.scala +++ b/src/library/scala/collection/generic/MapFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic diff --git a/src/library/scala/collection/generic/MutableMapFactory.scala b/src/library/scala/collection/generic/MutableMapFactory.scala index ac139cc80c..14c5b6bac3 100644 --- a/src/library/scala/collection/generic/MutableMapFactory.scala +++ b/src/library/scala/collection/generic/MutableMapFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/MutableSetFactory.scala b/src/library/scala/collection/generic/MutableSetFactory.scala index 9c69d53608..63944657fc 100644 --- a/src/library/scala/collection/generic/MutableSetFactory.scala +++ b/src/library/scala/collection/generic/MutableSetFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import mutable.{ Builder, GrowingBuilder } diff --git a/src/library/scala/collection/generic/MutableSortedSetFactory.scala b/src/library/scala/collection/generic/MutableSortedSetFactory.scala index b9be83c3c4..0339a523e9 100644 --- a/src/library/scala/collection/generic/MutableSortedSetFactory.scala +++ b/src/library/scala/collection/generic/MutableSortedSetFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic import scala.collection.mutable.{ Builder, GrowingBuilder } diff --git a/src/library/scala/collection/generic/OrderedTraversableFactory.scala b/src/library/scala/collection/generic/OrderedTraversableFactory.scala index a2de108721..7657aff2aa 100644 --- a/src/library/scala/collection/generic/OrderedTraversableFactory.scala +++ b/src/library/scala/collection/generic/OrderedTraversableFactory.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/ParFactory.scala b/src/library/scala/collection/generic/ParFactory.scala index bb88d26dec..486e2a115e 100644 --- a/src/library/scala/collection/generic/ParFactory.scala +++ b/src/library/scala/collection/generic/ParFactory.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection.parallel.ParIterable import scala.collection.parallel.Combiner diff --git a/src/library/scala/collection/generic/ParMapFactory.scala b/src/library/scala/collection/generic/ParMapFactory.scala index 0a6b08ae34..70797c83e2 100644 --- a/src/library/scala/collection/generic/ParMapFactory.scala +++ b/src/library/scala/collection/generic/ParMapFactory.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection.parallel.ParMap import scala.collection.parallel.ParMapLike diff --git a/src/library/scala/collection/generic/ParSetFactory.scala b/src/library/scala/collection/generic/ParSetFactory.scala index 3727ab89f7..4320635ae6 100644 --- a/src/library/scala/collection/generic/ParSetFactory.scala +++ b/src/library/scala/collection/generic/ParSetFactory.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection.mutable.Builder import scala.collection.parallel.Combiner diff --git a/src/library/scala/collection/generic/SeqFactory.scala b/src/library/scala/collection/generic/SeqFactory.scala index a66074741a..35cce11a79 100644 --- a/src/library/scala/collection/generic/SeqFactory.scala +++ b/src/library/scala/collection/generic/SeqFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/SeqForwarder.scala b/src/library/scala/collection/generic/SeqForwarder.scala index aafaffc159..c23b818c00 100644 --- a/src/library/scala/collection/generic/SeqForwarder.scala +++ b/src/library/scala/collection/generic/SeqForwarder.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection._ import scala.collection.immutable.Range diff --git a/src/library/scala/collection/generic/SetFactory.scala b/src/library/scala/collection/generic/SetFactory.scala index e9bbde92f3..fcd8d00c18 100644 --- a/src/library/scala/collection/generic/SetFactory.scala +++ b/src/library/scala/collection/generic/SetFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.Builder diff --git a/src/library/scala/collection/generic/Shrinkable.scala b/src/library/scala/collection/generic/Shrinkable.scala index b00048fd5d..b7412afde0 100644 --- a/src/library/scala/collection/generic/Shrinkable.scala +++ b/src/library/scala/collection/generic/Shrinkable.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic /** This trait forms part of collections that can be reduced diff --git a/src/library/scala/collection/generic/Signalling.scala b/src/library/scala/collection/generic/Signalling.scala index 442a7c126e..e62eb6ff09 100644 --- a/src/library/scala/collection/generic/Signalling.scala +++ b/src/library/scala/collection/generic/Signalling.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import java.util.concurrent.atomic.AtomicInteger diff --git a/src/library/scala/collection/generic/Sizing.scala b/src/library/scala/collection/generic/Sizing.scala index 1191259b3a..73584ce82e 100644 --- a/src/library/scala/collection/generic/Sizing.scala +++ b/src/library/scala/collection/generic/Sizing.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic /** A trait for objects which have a size. */ diff --git a/src/library/scala/collection/generic/SliceInterval.scala b/src/library/scala/collection/generic/SliceInterval.scala index 244e960454..82acdd1371 100644 --- a/src/library/scala/collection/generic/SliceInterval.scala +++ b/src/library/scala/collection/generic/SliceInterval.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** A container for the endpoints of a collection slice. diff --git a/src/library/scala/collection/generic/Sorted.scala b/src/library/scala/collection/generic/Sorted.scala index 2c3d200d01..3876da3275 100644 --- a/src/library/scala/collection/generic/Sorted.scala +++ b/src/library/scala/collection/generic/Sorted.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package generic /** Any collection (including maps) whose keys (or elements) are ordered. diff --git a/src/library/scala/collection/generic/SortedMapFactory.scala b/src/library/scala/collection/generic/SortedMapFactory.scala index fb3fe0fcb6..afa11e9ab1 100644 --- a/src/library/scala/collection/generic/SortedMapFactory.scala +++ b/src/library/scala/collection/generic/SortedMapFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.{Builder, MapBuilder} diff --git a/src/library/scala/collection/generic/SortedSetFactory.scala b/src/library/scala/collection/generic/SortedSetFactory.scala index f48e1c69e1..c734830e0b 100644 --- a/src/library/scala/collection/generic/SortedSetFactory.scala +++ b/src/library/scala/collection/generic/SortedSetFactory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package generic import mutable.{Builder, SetBuilder} diff --git a/src/library/scala/collection/generic/Subtractable.scala b/src/library/scala/collection/generic/Subtractable.scala index e0fe07a0a4..32a9000296 100644 --- a/src/library/scala/collection/generic/Subtractable.scala +++ b/src/library/scala/collection/generic/Subtractable.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic diff --git a/src/library/scala/collection/generic/TraversableFactory.scala b/src/library/scala/collection/generic/TraversableFactory.scala index 5d1c9d17e2..ad6d8fd198 100644 --- a/src/library/scala/collection/generic/TraversableFactory.scala +++ b/src/library/scala/collection/generic/TraversableFactory.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package generic import scala.language.higherKinds diff --git a/src/library/scala/collection/generic/TraversableForwarder.scala b/src/library/scala/collection/generic/TraversableForwarder.scala index 2662018feb..c71368bba0 100644 --- a/src/library/scala/collection/generic/TraversableForwarder.scala +++ b/src/library/scala/collection/generic/TraversableForwarder.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.collection.generic +package scala +package collection +package generic import scala.collection._ import mutable.{ Buffer, StringBuilder } diff --git a/src/library/scala/collection/generic/package.scala b/src/library/scala/collection/generic/package.scala index dd47b7ace6..1beb4a8599 100644 --- a/src/library/scala/collection/generic/package.scala +++ b/src/library/scala/collection/generic/package.scala @@ -1,4 +1,5 @@ -package scala.collection +package scala +package collection import generic.CanBuildFrom import scala.language.higherKinds diff --git a/src/library/scala/collection/immutable/BitSet.scala b/src/library/scala/collection/immutable/BitSet.scala index 1da6edd740..70543aa3a6 100644 --- a/src/library/scala/collection/immutable/BitSet.scala +++ b/src/library/scala/collection/immutable/BitSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/DefaultMap.scala b/src/library/scala/collection/immutable/DefaultMap.scala index 5ae5ef66fb..42a03e90ee 100755 --- a/src/library/scala/collection/immutable/DefaultMap.scala +++ b/src/library/scala/collection/immutable/DefaultMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable /** A default map which implements the `+` and `-` diff --git a/src/library/scala/collection/immutable/IndexedSeq.scala b/src/library/scala/collection/immutable/IndexedSeq.scala index 9316ff5e72..33170fdd59 100644 --- a/src/library/scala/collection/immutable/IndexedSeq.scala +++ b/src/library/scala/collection/immutable/IndexedSeq.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/Iterable.scala b/src/library/scala/collection/immutable/Iterable.scala index cc64d8ff3c..6e4eb1e45f 100644 --- a/src/library/scala/collection/immutable/Iterable.scala +++ b/src/library/scala/collection/immutable/Iterable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/LinearSeq.scala b/src/library/scala/collection/immutable/LinearSeq.scala index 5ede6d90d0..2109bd5211 100644 --- a/src/library/scala/collection/immutable/LinearSeq.scala +++ b/src/library/scala/collection/immutable/LinearSeq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/List.scala b/src/library/scala/collection/immutable/List.scala index be233d06cb..c01694960c 100644 --- a/src/library/scala/collection/immutable/List.scala +++ b/src/library/scala/collection/immutable/List.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ @@ -85,7 +86,8 @@ sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A, List] - with LinearSeqOptimized[A, List[A]] { + with LinearSeqOptimized[A, List[A]] + with Serializable { override def companion: GenericCompanion[List] = List import scala.collection.{Iterable, Traversable, Seq, IndexedSeq} diff --git a/src/library/scala/collection/immutable/ListMap.scala b/src/library/scala/collection/immutable/ListMap.scala index 75817350e5..47593a07ab 100644 --- a/src/library/scala/collection/immutable/ListMap.scala +++ b/src/library/scala/collection/immutable/ListMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/ListSet.scala b/src/library/scala/collection/immutable/ListSet.scala index def3d7eb23..5836321010 100644 --- a/src/library/scala/collection/immutable/ListSet.scala +++ b/src/library/scala/collection/immutable/ListSet.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/Map.scala b/src/library/scala/collection/immutable/Map.scala index 2ebf5035e1..a3f5c85961 100644 --- a/src/library/scala/collection/immutable/Map.scala +++ b/src/library/scala/collection/immutable/Map.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/MapLike.scala b/src/library/scala/collection/immutable/MapLike.scala index 1c2ab1c662..f6041464e7 100644 --- a/src/library/scala/collection/immutable/MapLike.scala +++ b/src/library/scala/collection/immutable/MapLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/MapProxy.scala b/src/library/scala/collection/immutable/MapProxy.scala index f3f04ec346..f9f19c021d 100644 --- a/src/library/scala/collection/immutable/MapProxy.scala +++ b/src/library/scala/collection/immutable/MapProxy.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable /** diff --git a/src/library/scala/collection/immutable/NumericRange.scala b/src/library/scala/collection/immutable/NumericRange.scala index 5842ff30e6..486c2b6c8f 100644 --- a/src/library/scala/collection/immutable/NumericRange.scala +++ b/src/library/scala/collection/immutable/NumericRange.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import mutable.{ Builder, ListBuffer } diff --git a/src/library/scala/collection/immutable/PagedSeq.scala b/src/library/scala/collection/immutable/PagedSeq.scala index 4069f6f0e4..e190d022d7 100644 --- a/src/library/scala/collection/immutable/PagedSeq.scala +++ b/src/library/scala/collection/immutable/PagedSeq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import java.io._ diff --git a/src/library/scala/collection/immutable/Queue.scala b/src/library/scala/collection/immutable/Queue.scala index 7d2ff95792..c55b46bf05 100644 --- a/src/library/scala/collection/immutable/Queue.scala +++ b/src/library/scala/collection/immutable/Queue.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/Range.scala b/src/library/scala/collection/immutable/Range.scala index 243e3fcb91..09f8143b55 100644 --- a/src/library/scala/collection/immutable/Range.scala +++ b/src/library/scala/collection/immutable/Range.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection.immutable +package scala +package collection.immutable import scala.collection.parallel.immutable.ParRange @@ -81,14 +82,14 @@ extends scala.collection.AbstractSeq[Int] override def min[A1 >: Int](implicit ord: Ordering[A1]): Int = if (ord eq Ordering.Int) { - if (step > 0) start + if (step > 0) head else last } else super.min(ord) override def max[A1 >: Int](implicit ord: Ordering[A1]): Int = if (ord eq Ordering.Int) { if (step > 0) last - else start + else head } else super.max(ord) protected def copy(start: Int, end: Int, step: Int): Range = new Range(start, end, step) diff --git a/src/library/scala/collection/immutable/Seq.scala b/src/library/scala/collection/immutable/Seq.scala index 14610aea33..38855ca6b0 100644 --- a/src/library/scala/collection/immutable/Seq.scala +++ b/src/library/scala/collection/immutable/Seq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/Set.scala b/src/library/scala/collection/immutable/Set.scala index 8433c2b002..2c96f4c194 100644 --- a/src/library/scala/collection/immutable/Set.scala +++ b/src/library/scala/collection/immutable/Set.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/SetProxy.scala b/src/library/scala/collection/immutable/SetProxy.scala index 06c6843181..9e25678435 100644 --- a/src/library/scala/collection/immutable/SetProxy.scala +++ b/src/library/scala/collection/immutable/SetProxy.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable /** This is a simple wrapper class for <a href="Set.html" diff --git a/src/library/scala/collection/immutable/SortedMap.scala b/src/library/scala/collection/immutable/SortedMap.scala index 73cc55df00..4b9fa81a8c 100644 --- a/src/library/scala/collection/immutable/SortedMap.scala +++ b/src/library/scala/collection/immutable/SortedMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/SortedSet.scala b/src/library/scala/collection/immutable/SortedSet.scala index 3f75d50555..4a8859a7ab 100644 --- a/src/library/scala/collection/immutable/SortedSet.scala +++ b/src/library/scala/collection/immutable/SortedSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/Stack.scala b/src/library/scala/collection/immutable/Stack.scala index 357e9a123c..65a34e2310 100644 --- a/src/library/scala/collection/immutable/Stack.scala +++ b/src/library/scala/collection/immutable/Stack.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/Stream.scala b/src/library/scala/collection/immutable/Stream.scala index 0770bd3175..5e1de44749 100644 --- a/src/library/scala/collection/immutable/Stream.scala +++ b/src/library/scala/collection/immutable/Stream.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import generic._ @@ -183,10 +184,12 @@ import scala.language.implicitConversions * @define orderDependentFold * @define willTerminateInf Note: lazily evaluated; will terminate for infinite-sized collections. */ +@deprecatedInheritance("This class will be sealed.", "2.11.0") abstract class Stream[+A] extends AbstractSeq[A] with LinearSeq[A] with GenericTraversableTemplate[A, Stream] - with LinearSeqOptimized[A, Stream[A]] { + with LinearSeqOptimized[A, Stream[A]] + with Serializable { self => override def companion: GenericCompanion[Stream] = Stream @@ -1048,7 +1051,7 @@ object Stream extends SeqFactory[Stream] { def result: Stream[A] = parts.toStream flatMap (_.toStream) } - object Empty extends Stream[Nothing] with Serializable { + object Empty extends Stream[Nothing] { override def isEmpty = true override def head = throw new NoSuchElementException("head of empty stream") override def tail = throw new UnsupportedOperationException("tail of empty stream") @@ -1099,7 +1102,7 @@ object Stream extends SeqFactory[Stream] { /** A lazy cons cell, from which streams are built. */ @SerialVersionUID(-602202424901551803L) - final class Cons[+A](hd: A, tl: => Stream[A]) extends Stream[A] with Serializable { + final class Cons[+A](hd: A, tl: => Stream[A]) extends Stream[A] { override def isEmpty = false override def head = hd @volatile private[this] var tlVal: Stream[A] = _ diff --git a/src/library/scala/collection/immutable/StreamView.scala b/src/library/scala/collection/immutable/StreamView.scala index 5a24b77eb3..127ed76eb5 100644 --- a/src/library/scala/collection/immutable/StreamView.scala +++ b/src/library/scala/collection/immutable/StreamView.scala @@ -1,4 +1,5 @@ -package scala.collection +package scala +package collection package immutable trait StreamView[+A, +Coll] extends StreamViewLike[A, Coll, StreamView[A, Coll]] { } diff --git a/src/library/scala/collection/immutable/StreamViewLike.scala b/src/library/scala/collection/immutable/StreamViewLike.scala index 236308da2e..ccab032cfd 100644 --- a/src/library/scala/collection/immutable/StreamViewLike.scala +++ b/src/library/scala/collection/immutable/StreamViewLike.scala @@ -1,4 +1,5 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/StringLike.scala b/src/library/scala/collection/immutable/StringLike.scala index 389e1579f2..4768413e75 100644 --- a/src/library/scala/collection/immutable/StringLike.scala +++ b/src/library/scala/collection/immutable/StringLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import mutable.Builder diff --git a/src/library/scala/collection/immutable/StringOps.scala b/src/library/scala/collection/immutable/StringOps.scala index 16c1f96cc2..6737692fb1 100644 --- a/src/library/scala/collection/immutable/StringOps.scala +++ b/src/library/scala/collection/immutable/StringOps.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import mutable.StringBuilder diff --git a/src/library/scala/collection/immutable/Traversable.scala b/src/library/scala/collection/immutable/Traversable.scala index 5188343011..775d635fae 100644 --- a/src/library/scala/collection/immutable/Traversable.scala +++ b/src/library/scala/collection/immutable/Traversable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/TreeMap.scala b/src/library/scala/collection/immutable/TreeMap.scala index 5085039da5..4d2ec579db 100644 --- a/src/library/scala/collection/immutable/TreeMap.scala +++ b/src/library/scala/collection/immutable/TreeMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/TreeSet.scala b/src/library/scala/collection/immutable/TreeSet.scala index e25d16408a..dfe1a833ef 100644 --- a/src/library/scala/collection/immutable/TreeSet.scala +++ b/src/library/scala/collection/immutable/TreeSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/immutable/TrieIterator.scala b/src/library/scala/collection/immutable/TrieIterator.scala index dbe013d6e8..d7335e80f1 100644 --- a/src/library/scala/collection/immutable/TrieIterator.scala +++ b/src/library/scala/collection/immutable/TrieIterator.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package immutable import HashMap.{ HashTrieMap, HashMapCollision1, HashMap1 } diff --git a/src/library/scala/collection/immutable/WrappedString.scala b/src/library/scala/collection/immutable/WrappedString.scala index edcab31f33..d6bebf9ef5 100644 --- a/src/library/scala/collection/immutable/WrappedString.scala +++ b/src/library/scala/collection/immutable/WrappedString.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package immutable import generic._ diff --git a/src/library/scala/collection/mutable/AVLTree.scala b/src/library/scala/collection/mutable/AVLTree.scala index dd7a94d677..d2205f9994 100644 --- a/src/library/scala/collection/mutable/AVLTree.scala +++ b/src/library/scala/collection/mutable/AVLTree.scala @@ -10,7 +10,6 @@ package scala package collection package mutable - /** * An immutable AVL Tree implementation used by mutable.TreeSet * diff --git a/src/library/scala/collection/mutable/ArrayBuffer.scala b/src/library/scala/collection/mutable/ArrayBuffer.scala index f1cfd2d69a..2d43b352c5 100644 --- a/src/library/scala/collection/mutable/ArrayBuffer.scala +++ b/src/library/scala/collection/mutable/ArrayBuffer.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/ArrayBuilder.scala b/src/library/scala/collection/mutable/ArrayBuilder.scala index 2fe3e91d68..65b4d52a60 100644 --- a/src/library/scala/collection/mutable/ArrayBuilder.scala +++ b/src/library/scala/collection/mutable/ArrayBuilder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import scala.reflect.ClassTag diff --git a/src/library/scala/collection/mutable/ArrayLike.scala b/src/library/scala/collection/mutable/ArrayLike.scala index 40017aa08e..4a6820856d 100644 --- a/src/library/scala/collection/mutable/ArrayLike.scala +++ b/src/library/scala/collection/mutable/ArrayLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** A common supertrait of `ArrayOps` and `WrappedArray` that factors out most diff --git a/src/library/scala/collection/mutable/ArraySeq.scala b/src/library/scala/collection/mutable/ArraySeq.scala index 334b26ae03..577a838315 100644 --- a/src/library/scala/collection/mutable/ArraySeq.scala +++ b/src/library/scala/collection/mutable/ArraySeq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/BitSet.scala b/src/library/scala/collection/mutable/BitSet.scala index 29c341590d..f252a0bfeb 100644 --- a/src/library/scala/collection/mutable/BitSet.scala +++ b/src/library/scala/collection/mutable/BitSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/Buffer.scala b/src/library/scala/collection/mutable/Buffer.scala index 230799c6f3..d2e33badbe 100644 --- a/src/library/scala/collection/mutable/Buffer.scala +++ b/src/library/scala/collection/mutable/Buffer.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/BufferLike.scala b/src/library/scala/collection/mutable/BufferLike.scala index 322522fdd2..4b3d3bc1cf 100644 --- a/src/library/scala/collection/mutable/BufferLike.scala +++ b/src/library/scala/collection/mutable/BufferLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/BufferProxy.scala b/src/library/scala/collection/mutable/BufferProxy.scala index d3f96f69ad..14946cdfd8 100644 --- a/src/library/scala/collection/mutable/BufferProxy.scala +++ b/src/library/scala/collection/mutable/BufferProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import script._ diff --git a/src/library/scala/collection/mutable/Cloneable.scala b/src/library/scala/collection/mutable/Cloneable.scala index dadcd36257..8b2f3f70de 100644 --- a/src/library/scala/collection/mutable/Cloneable.scala +++ b/src/library/scala/collection/mutable/Cloneable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable /** A trait for cloneable collections. diff --git a/src/library/scala/collection/mutable/DefaultEntry.scala b/src/library/scala/collection/mutable/DefaultEntry.scala index f14cb4ac2b..66db45866c 100644 --- a/src/library/scala/collection/mutable/DefaultEntry.scala +++ b/src/library/scala/collection/mutable/DefaultEntry.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** Class used internally for default map model. diff --git a/src/library/scala/collection/mutable/DefaultMapModel.scala b/src/library/scala/collection/mutable/DefaultMapModel.scala index 903f117466..4dfae047c3 100644 --- a/src/library/scala/collection/mutable/DefaultMapModel.scala +++ b/src/library/scala/collection/mutable/DefaultMapModel.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable /** This class is used internally. It implements the mutable `Map` diff --git a/src/library/scala/collection/mutable/DoubleLinkedList.scala b/src/library/scala/collection/mutable/DoubleLinkedList.scala index a106794912..8654a91cf1 100644 --- a/src/library/scala/collection/mutable/DoubleLinkedList.scala +++ b/src/library/scala/collection/mutable/DoubleLinkedList.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/DoubleLinkedListLike.scala b/src/library/scala/collection/mutable/DoubleLinkedListLike.scala index 3f223f30ec..776ac76c45 100644 --- a/src/library/scala/collection/mutable/DoubleLinkedListLike.scala +++ b/src/library/scala/collection/mutable/DoubleLinkedListLike.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import scala.annotation.migration diff --git a/src/library/scala/collection/mutable/FlatHashTable.scala b/src/library/scala/collection/mutable/FlatHashTable.scala index 49a9427588..1cdf150cb8 100644 --- a/src/library/scala/collection/mutable/FlatHashTable.scala +++ b/src/library/scala/collection/mutable/FlatHashTable.scala @@ -6,11 +6,10 @@ ** |/ ** \* */ - -package scala.collection +package scala +package collection package mutable - /** An implementation class backing a `HashSet`. * * This trait is used internally. It can be mixed in with various collections relying on diff --git a/src/library/scala/collection/mutable/GrowingBuilder.scala b/src/library/scala/collection/mutable/GrowingBuilder.scala index ba7ea60df1..c4b5e546aa 100644 --- a/src/library/scala/collection/mutable/GrowingBuilder.scala +++ b/src/library/scala/collection/mutable/GrowingBuilder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/HashEntry.scala b/src/library/scala/collection/mutable/HashEntry.scala index 5cd976eb47..4c0f6a93e8 100644 --- a/src/library/scala/collection/mutable/HashEntry.scala +++ b/src/library/scala/collection/mutable/HashEntry.scala @@ -5,7 +5,8 @@ ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** Class used internally. diff --git a/src/library/scala/collection/mutable/HashMap.scala b/src/library/scala/collection/mutable/HashMap.scala index 692d6b8d6a..6fca75ffea 100644 --- a/src/library/scala/collection/mutable/HashMap.scala +++ b/src/library/scala/collection/mutable/HashMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ @@ -93,7 +94,7 @@ extends AbstractMap[A, B] def -=(key: A): this.type = { removeEntry(key); this } - def iterator = entriesIterator map {e => (e.key, e.value)} + def iterator = entriesIterator map (e => ((e.key, e.value))) override def foreach[C](f: ((A, B)) => C): Unit = foreachEntry(e => f((e.key, e.value))) diff --git a/src/library/scala/collection/mutable/HashSet.scala b/src/library/scala/collection/mutable/HashSet.scala index 753f7f8d01..886fee5a59 100644 --- a/src/library/scala/collection/mutable/HashSet.scala +++ b/src/library/scala/collection/mutable/HashSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/HashTable.scala b/src/library/scala/collection/mutable/HashTable.scala index 37d2b51a91..0479b51830 100644 --- a/src/library/scala/collection/mutable/HashTable.scala +++ b/src/library/scala/collection/mutable/HashTable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable /** This class can be used to construct data structures that are based diff --git a/src/library/scala/collection/mutable/History.scala b/src/library/scala/collection/mutable/History.scala index 34e8f7d5b8..19148c0ac2 100644 --- a/src/library/scala/collection/mutable/History.scala +++ b/src/library/scala/collection/mutable/History.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala b/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala index 755eea831f..88e9e9db8f 100644 --- a/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala +++ b/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import scala.annotation.migration diff --git a/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala b/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala index 42c757d3bf..3e64747832 100644 --- a/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala +++ b/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/IndexedSeq.scala b/src/library/scala/collection/mutable/IndexedSeq.scala index 4d094e697b..3d9630eea7 100644 --- a/src/library/scala/collection/mutable/IndexedSeq.scala +++ b/src/library/scala/collection/mutable/IndexedSeq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/IndexedSeqLike.scala b/src/library/scala/collection/mutable/IndexedSeqLike.scala index 7b582eb5cb..4cf794c32f 100644 --- a/src/library/scala/collection/mutable/IndexedSeqLike.scala +++ b/src/library/scala/collection/mutable/IndexedSeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** A subtrait of scala.collection.IndexedSeq which represents sequences diff --git a/src/library/scala/collection/mutable/IndexedSeqOptimized.scala b/src/library/scala/collection/mutable/IndexedSeqOptimized.scala index 80b527a7b9..09f0712862 100755 --- a/src/library/scala/collection/mutable/IndexedSeqOptimized.scala +++ b/src/library/scala/collection/mutable/IndexedSeqOptimized.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** A subtrait of scala.collection.IndexedSeq which represents sequences diff --git a/src/library/scala/collection/mutable/IndexedSeqView.scala b/src/library/scala/collection/mutable/IndexedSeqView.scala index a88ed8f123..36c1076b87 100644 --- a/src/library/scala/collection/mutable/IndexedSeqView.scala +++ b/src/library/scala/collection/mutable/IndexedSeqView.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/Iterable.scala b/src/library/scala/collection/mutable/Iterable.scala index b79453e4e9..f7a794e357 100644 --- a/src/library/scala/collection/mutable/Iterable.scala +++ b/src/library/scala/collection/mutable/Iterable.scala @@ -5,7 +5,8 @@ ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/LazyBuilder.scala b/src/library/scala/collection/mutable/LazyBuilder.scala index 0b56c86ac4..ebee38b77f 100644 --- a/src/library/scala/collection/mutable/LazyBuilder.scala +++ b/src/library/scala/collection/mutable/LazyBuilder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** A builder that constructs its result lazily. Iterators or iterables to diff --git a/src/library/scala/collection/mutable/LinearSeq.scala b/src/library/scala/collection/mutable/LinearSeq.scala index f241a2f6d4..3fa10042ef 100644 --- a/src/library/scala/collection/mutable/LinearSeq.scala +++ b/src/library/scala/collection/mutable/LinearSeq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/LinkedEntry.scala b/src/library/scala/collection/mutable/LinkedEntry.scala index e4e29122d8..296e7fde18 100644 --- a/src/library/scala/collection/mutable/LinkedEntry.scala +++ b/src/library/scala/collection/mutable/LinkedEntry.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable /** Class for the linked hash map entry, used internally. diff --git a/src/library/scala/collection/mutable/LinkedHashMap.scala b/src/library/scala/collection/mutable/LinkedHashMap.scala index 14f30d74e8..536f320402 100644 --- a/src/library/scala/collection/mutable/LinkedHashMap.scala +++ b/src/library/scala/collection/mutable/LinkedHashMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/LinkedHashSet.scala b/src/library/scala/collection/mutable/LinkedHashSet.scala index 5641a78d46..d89566793f 100644 --- a/src/library/scala/collection/mutable/LinkedHashSet.scala +++ b/src/library/scala/collection/mutable/LinkedHashSet.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/LinkedList.scala b/src/library/scala/collection/mutable/LinkedList.scala index 29e6fdd375..a772f86d78 100644 --- a/src/library/scala/collection/mutable/LinkedList.scala +++ b/src/library/scala/collection/mutable/LinkedList.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/LinkedListLike.scala b/src/library/scala/collection/mutable/LinkedListLike.scala index 3003080060..6d4565026f 100644 --- a/src/library/scala/collection/mutable/LinkedListLike.scala +++ b/src/library/scala/collection/mutable/LinkedListLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import scala.annotation.tailrec diff --git a/src/library/scala/collection/mutable/ListBuffer.scala b/src/library/scala/collection/mutable/ListBuffer.scala index af1d7e4183..7f54692c8b 100644 --- a/src/library/scala/collection/mutable/ListBuffer.scala +++ b/src/library/scala/collection/mutable/ListBuffer.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ @@ -261,7 +262,7 @@ final class ListBuffer[A] * @param n the index which refers to the first element to remove. * @param count the number of elements to remove. */ - @annotation.migration("Invalid input values will be rejected in future releases.", "2.11") + @scala.annotation.migration("Invalid input values will be rejected in future releases.", "2.11") override def remove(n: Int, count: Int) { if (n >= len) return diff --git a/src/library/scala/collection/mutable/ListMap.scala b/src/library/scala/collection/mutable/ListMap.scala index 7f05deffc8..0b5d34cd81 100644 --- a/src/library/scala/collection/mutable/ListMap.scala +++ b/src/library/scala/collection/mutable/ListMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/Map.scala b/src/library/scala/collection/mutable/Map.scala index f68e4004f2..7280aaec25 100644 --- a/src/library/scala/collection/mutable/Map.scala +++ b/src/library/scala/collection/mutable/Map.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/MapBuilder.scala b/src/library/scala/collection/mutable/MapBuilder.scala index 8468e09e4d..a5a6b12ea9 100644 --- a/src/library/scala/collection/mutable/MapBuilder.scala +++ b/src/library/scala/collection/mutable/MapBuilder.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package mutable /** The canonical builder for immutable maps, working with the map's `+` method diff --git a/src/library/scala/collection/mutable/MapLike.scala b/src/library/scala/collection/mutable/MapLike.scala index 49d1e039f0..dbe32fdb79 100644 --- a/src/library/scala/collection/mutable/MapLike.scala +++ b/src/library/scala/collection/mutable/MapLike.scala @@ -7,12 +7,13 @@ \* */ -package scala.collection +package scala +package collection package mutable import generic._ import scala.annotation.migration -import parallel.mutable.ParMap +import scala.collection.parallel.mutable.ParMap /** A template trait for mutable maps. * $mapNote diff --git a/src/library/scala/collection/mutable/MapProxy.scala b/src/library/scala/collection/mutable/MapProxy.scala index c730e2b7c8..e4f106731c 100644 --- a/src/library/scala/collection/mutable/MapProxy.scala +++ b/src/library/scala/collection/mutable/MapProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** diff --git a/src/library/scala/collection/mutable/MultiMap.scala b/src/library/scala/collection/mutable/MultiMap.scala index 4635bfbe64..78dfc35268 100644 --- a/src/library/scala/collection/mutable/MultiMap.scala +++ b/src/library/scala/collection/mutable/MultiMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/MutableList.scala b/src/library/scala/collection/mutable/MutableList.scala index 03110569c4..5727b12975 100644 --- a/src/library/scala/collection/mutable/MutableList.scala +++ b/src/library/scala/collection/mutable/MutableList.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/ObservableBuffer.scala b/src/library/scala/collection/mutable/ObservableBuffer.scala index 7a2fce9128..7fe794caaf 100644 --- a/src/library/scala/collection/mutable/ObservableBuffer.scala +++ b/src/library/scala/collection/mutable/ObservableBuffer.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import script._ diff --git a/src/library/scala/collection/mutable/ObservableMap.scala b/src/library/scala/collection/mutable/ObservableMap.scala index 3544275300..0dec6fa516 100644 --- a/src/library/scala/collection/mutable/ObservableMap.scala +++ b/src/library/scala/collection/mutable/ObservableMap.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import script._ diff --git a/src/library/scala/collection/mutable/ObservableSet.scala b/src/library/scala/collection/mutable/ObservableSet.scala index 81580316ff..acb6d92c8c 100644 --- a/src/library/scala/collection/mutable/ObservableSet.scala +++ b/src/library/scala/collection/mutable/ObservableSet.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import script._ diff --git a/src/library/scala/collection/mutable/PriorityQueue.scala b/src/library/scala/collection/mutable/PriorityQueue.scala index 4e8b923155..b5b1c1d006 100644 --- a/src/library/scala/collection/mutable/PriorityQueue.scala +++ b/src/library/scala/collection/mutable/PriorityQueue.scala @@ -6,9 +6,8 @@ ** |/ ** \* */ - - -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/PriorityQueueProxy.scala b/src/library/scala/collection/mutable/PriorityQueueProxy.scala index ee54370731..4cb49be9b8 100644 --- a/src/library/scala/collection/mutable/PriorityQueueProxy.scala +++ b/src/library/scala/collection/mutable/PriorityQueueProxy.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package mutable /** This class servers as a proxy for priority queues. The diff --git a/src/library/scala/collection/mutable/Publisher.scala b/src/library/scala/collection/mutable/Publisher.scala index 8c2ef0d3a3..22bbea16ef 100644 --- a/src/library/scala/collection/mutable/Publisher.scala +++ b/src/library/scala/collection/mutable/Publisher.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/Queue.scala b/src/library/scala/collection/mutable/Queue.scala index f1a5723818..e80aae2171 100644 --- a/src/library/scala/collection/mutable/Queue.scala +++ b/src/library/scala/collection/mutable/Queue.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/QueueProxy.scala b/src/library/scala/collection/mutable/QueueProxy.scala index 051b1219cd..bfc5edbeff 100644 --- a/src/library/scala/collection/mutable/QueueProxy.scala +++ b/src/library/scala/collection/mutable/QueueProxy.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable /** `Queue` objects implement data structures that allow to diff --git a/src/library/scala/collection/mutable/RevertibleHistory.scala b/src/library/scala/collection/mutable/RevertibleHistory.scala index 9b8554669b..725a8113ec 100644 --- a/src/library/scala/collection/mutable/RevertibleHistory.scala +++ b/src/library/scala/collection/mutable/RevertibleHistory.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/Seq.scala b/src/library/scala/collection/mutable/Seq.scala index 9d9399ebb4..11fbdd13f3 100644 --- a/src/library/scala/collection/mutable/Seq.scala +++ b/src/library/scala/collection/mutable/Seq.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/SeqLike.scala b/src/library/scala/collection/mutable/SeqLike.scala index ddfde536c9..6987066f2b 100644 --- a/src/library/scala/collection/mutable/SeqLike.scala +++ b/src/library/scala/collection/mutable/SeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import parallel.mutable.ParSeq diff --git a/src/library/scala/collection/mutable/Set.scala b/src/library/scala/collection/mutable/Set.scala index 023ff63056..4439880976 100644 --- a/src/library/scala/collection/mutable/Set.scala +++ b/src/library/scala/collection/mutable/Set.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/SetBuilder.scala b/src/library/scala/collection/mutable/SetBuilder.scala index 40f0b8932c..01bfdc96ed 100644 --- a/src/library/scala/collection/mutable/SetBuilder.scala +++ b/src/library/scala/collection/mutable/SetBuilder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** The canonical builder for mutable Sets. diff --git a/src/library/scala/collection/mutable/SetLike.scala b/src/library/scala/collection/mutable/SetLike.scala index 8dfcde16ce..073bc59f61 100644 --- a/src/library/scala/collection/mutable/SetLike.scala +++ b/src/library/scala/collection/mutable/SetLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/SetProxy.scala b/src/library/scala/collection/mutable/SetProxy.scala index c9f297509f..9568a54276 100644 --- a/src/library/scala/collection/mutable/SetProxy.scala +++ b/src/library/scala/collection/mutable/SetProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** This is a simple wrapper class for [[scala.collection.mutable.Set]]. diff --git a/src/library/scala/collection/mutable/SortedSet.scala b/src/library/scala/collection/mutable/SortedSet.scala index 41f2c6e39f..0f2fa75abd 100644 --- a/src/library/scala/collection/mutable/SortedSet.scala +++ b/src/library/scala/collection/mutable/SortedSet.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/Stack.scala b/src/library/scala/collection/mutable/Stack.scala index 6eef250f9d..34c6d1fbb9 100644 --- a/src/library/scala/collection/mutable/Stack.scala +++ b/src/library/scala/collection/mutable/Stack.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/StackProxy.scala b/src/library/scala/collection/mutable/StackProxy.scala index 8792738339..7d776b99c3 100644 --- a/src/library/scala/collection/mutable/StackProxy.scala +++ b/src/library/scala/collection/mutable/StackProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** A stack implements a data structure which allows to store and retrieve diff --git a/src/library/scala/collection/mutable/StringBuilder.scala b/src/library/scala/collection/mutable/StringBuilder.scala index 4d269a95b1..cfabd9171c 100644 --- a/src/library/scala/collection/mutable/StringBuilder.scala +++ b/src/library/scala/collection/mutable/StringBuilder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import java.lang.{ StringBuilder => JavaStringBuilder } diff --git a/src/library/scala/collection/mutable/Subscriber.scala b/src/library/scala/collection/mutable/Subscriber.scala index 35d31d7316..c2aa9be72d 100644 --- a/src/library/scala/collection/mutable/Subscriber.scala +++ b/src/library/scala/collection/mutable/Subscriber.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable /** `Subscriber[A, B]` objects may subscribe to events of type `A` diff --git a/src/library/scala/collection/mutable/SynchronizedBuffer.scala b/src/library/scala/collection/mutable/SynchronizedBuffer.scala index 14ec85b906..b97191137f 100644 --- a/src/library/scala/collection/mutable/SynchronizedBuffer.scala +++ b/src/library/scala/collection/mutable/SynchronizedBuffer.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import script._ diff --git a/src/library/scala/collection/mutable/SynchronizedMap.scala b/src/library/scala/collection/mutable/SynchronizedMap.scala index 5a3562cb22..643701eda9 100644 --- a/src/library/scala/collection/mutable/SynchronizedMap.scala +++ b/src/library/scala/collection/mutable/SynchronizedMap.scala @@ -6,9 +6,8 @@ ** |/ ** \* */ - - -package scala.collection +package scala +package collection package mutable import scala.annotation.migration diff --git a/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala b/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala index 52e55677bd..05676597db 100644 --- a/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala +++ b/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable /** This class implements synchronized priority queues using a binary heap. diff --git a/src/library/scala/collection/mutable/SynchronizedQueue.scala b/src/library/scala/collection/mutable/SynchronizedQueue.scala index 57beab39b6..263c06b439 100644 --- a/src/library/scala/collection/mutable/SynchronizedQueue.scala +++ b/src/library/scala/collection/mutable/SynchronizedQueue.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/SynchronizedSet.scala b/src/library/scala/collection/mutable/SynchronizedSet.scala index 27a696895d..441efea5fb 100644 --- a/src/library/scala/collection/mutable/SynchronizedSet.scala +++ b/src/library/scala/collection/mutable/SynchronizedSet.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package mutable import script._ diff --git a/src/library/scala/collection/mutable/SynchronizedStack.scala b/src/library/scala/collection/mutable/SynchronizedStack.scala index 09cdcca99e..c92a68ffde 100644 --- a/src/library/scala/collection/mutable/SynchronizedStack.scala +++ b/src/library/scala/collection/mutable/SynchronizedStack.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/Traversable.scala b/src/library/scala/collection/mutable/Traversable.scala index e36ffc847f..d7ea376d28 100644 --- a/src/library/scala/collection/mutable/Traversable.scala +++ b/src/library/scala/collection/mutable/Traversable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/TreeSet.scala b/src/library/scala/collection/mutable/TreeSet.scala index 147bc85383..ea5b859367 100644 --- a/src/library/scala/collection/mutable/TreeSet.scala +++ b/src/library/scala/collection/mutable/TreeSet.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/Undoable.scala b/src/library/scala/collection/mutable/Undoable.scala index 0c0e8fed3e..482d618165 100644 --- a/src/library/scala/collection/mutable/Undoable.scala +++ b/src/library/scala/collection/mutable/Undoable.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable diff --git a/src/library/scala/collection/mutable/UnrolledBuffer.scala b/src/library/scala/collection/mutable/UnrolledBuffer.scala index ac634f43aa..292705c02a 100644 --- a/src/library/scala/collection/mutable/UnrolledBuffer.scala +++ b/src/library/scala/collection/mutable/UnrolledBuffer.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.mutable +package scala +package collection.mutable import scala.collection.AbstractIterator import scala.collection.Iterator diff --git a/src/library/scala/collection/mutable/WeakHashMap.scala b/src/library/scala/collection/mutable/WeakHashMap.scala index 70e428c9b6..433d054bfc 100644 --- a/src/library/scala/collection/mutable/WeakHashMap.scala +++ b/src/library/scala/collection/mutable/WeakHashMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package mutable import generic._ diff --git a/src/library/scala/collection/mutable/WrappedArray.scala b/src/library/scala/collection/mutable/WrappedArray.scala index b83724090c..53fca9f779 100644 --- a/src/library/scala/collection/mutable/WrappedArray.scala +++ b/src/library/scala/collection/mutable/WrappedArray.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import scala.reflect.ClassTag diff --git a/src/library/scala/collection/mutable/WrappedArrayBuilder.scala b/src/library/scala/collection/mutable/WrappedArrayBuilder.scala index 55328a5d3d..bfe95a11ab 100644 --- a/src/library/scala/collection/mutable/WrappedArrayBuilder.scala +++ b/src/library/scala/collection/mutable/WrappedArrayBuilder.scala @@ -8,7 +8,8 @@ -package scala.collection +package scala +package collection package mutable import scala.reflect.ClassTag diff --git a/src/library/scala/collection/parallel/Combiner.scala b/src/library/scala/collection/parallel/Combiner.scala index 00e20e7616..68df572517 100644 --- a/src/library/scala/collection/parallel/Combiner.scala +++ b/src/library/scala/collection/parallel/Combiner.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.Parallel @@ -33,11 +34,11 @@ import scala.collection.generic.Sizing * @since 2.9 */ trait Combiner[-Elem, +To] extends Builder[Elem, To] with Sizing with Parallel { - + @transient @volatile var _combinerTaskSupport = defaultTaskSupport - + def combinerTaskSupport = { val cts = _combinerTaskSupport if (cts eq null) { @@ -45,9 +46,9 @@ trait Combiner[-Elem, +To] extends Builder[Elem, To] with Sizing with Parallel { defaultTaskSupport } else cts } - + def combinerTaskSupport_=(cts: TaskSupport) = _combinerTaskSupport = cts - + /** Combines the contents of the receiver builder and the `other` builder, * producing a new builder containing both their elements. * @@ -81,7 +82,7 @@ trait Combiner[-Elem, +To] extends Builder[Elem, To] with Sizing with Parallel { * By default, this method returns `false`. */ def canBeShared: Boolean = false - + /** Constructs the result and sets the appropriate tasksupport object to the resulting collection * if this is applicable. */ @@ -89,7 +90,7 @@ trait Combiner[-Elem, +To] extends Builder[Elem, To] with Sizing with Parallel { val res = result() setTaskSupport(res, combinerTaskSupport) } - + } diff --git a/src/library/scala/collection/parallel/ParIterable.scala b/src/library/scala/collection/parallel/ParIterable.scala index f170b944eb..2ceeb18eef 100644 --- a/src/library/scala/collection/parallel/ParIterable.scala +++ b/src/library/scala/collection/parallel/ParIterable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.GenIterable import scala.collection.generic._ diff --git a/src/library/scala/collection/parallel/ParIterableLike.scala b/src/library/scala/collection/parallel/ParIterableLike.scala index 961556faff..a0b42f248e 100644 --- a/src/library/scala/collection/parallel/ParIterableLike.scala +++ b/src/library/scala/collection/parallel/ParIterableLike.scala @@ -6,11 +6,8 @@ ** |/ ** \* */ - -package scala.collection.parallel - - - +package scala +package collection.parallel import scala.collection.mutable.Builder import scala.collection.mutable.ArrayBuffer diff --git a/src/library/scala/collection/parallel/ParIterableView.scala b/src/library/scala/collection/parallel/ParIterableView.scala index 7644e1bd12..6dce19db19 100644 --- a/src/library/scala/collection/parallel/ParIterableView.scala +++ b/src/library/scala/collection/parallel/ParIterableView.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.{ Parallel, IterableView, GenIterableView, Iterator } import scala.collection.generic.CanCombineFrom diff --git a/src/library/scala/collection/parallel/ParIterableViewLike.scala b/src/library/scala/collection/parallel/ParIterableViewLike.scala index 0567e7b396..1ec0ff9c32 100644 --- a/src/library/scala/collection/parallel/ParIterableViewLike.scala +++ b/src/library/scala/collection/parallel/ParIterableViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.Parallel import scala.collection.{ IterableView, IterableViewLike } diff --git a/src/library/scala/collection/parallel/ParMap.scala b/src/library/scala/collection/parallel/ParMap.scala index 1f27ae830a..9f92e6c1e8 100644 --- a/src/library/scala/collection/parallel/ParMap.scala +++ b/src/library/scala/collection/parallel/ParMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.Map import scala.collection.GenMap diff --git a/src/library/scala/collection/parallel/ParMapLike.scala b/src/library/scala/collection/parallel/ParMapLike.scala index 798ba71b95..ee14324c41 100644 --- a/src/library/scala/collection/parallel/ParMapLike.scala +++ b/src/library/scala/collection/parallel/ParMapLike.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection.parallel +package scala +package collection.parallel diff --git a/src/library/scala/collection/parallel/ParSeq.scala b/src/library/scala/collection/parallel/ParSeq.scala index dee523ad89..b4a30e5dc2 100644 --- a/src/library/scala/collection/parallel/ParSeq.scala +++ b/src/library/scala/collection/parallel/ParSeq.scala @@ -6,10 +6,8 @@ ** |/ ** \* */ - -package scala.collection.parallel - - +package scala +package collection.parallel import scala.collection.generic.GenericCompanion import scala.collection.generic.GenericParCompanion @@ -53,26 +51,3 @@ object ParSeq extends ParFactory[ParSeq] { def newCombiner[T]: Combiner[T, ParSeq[T]] = ParArrayCombiner[T] } - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/ParSeqLike.scala b/src/library/scala/collection/parallel/ParSeqLike.scala index 68bc1bc12c..6693e30fcd 100644 --- a/src/library/scala/collection/parallel/ParSeqLike.scala +++ b/src/library/scala/collection/parallel/ParSeqLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.{ Parallel, SeqLike, GenSeqLike, GenSeq, GenIterable, Iterator } import scala.collection.generic.DefaultSignalling diff --git a/src/library/scala/collection/parallel/ParSeqView.scala b/src/library/scala/collection/parallel/ParSeqView.scala index 9acc4b0b73..b80994514b 100644 --- a/src/library/scala/collection/parallel/ParSeqView.scala +++ b/src/library/scala/collection/parallel/ParSeqView.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.{ SeqView, Parallel, Iterator } import scala.collection.generic.CanCombineFrom diff --git a/src/library/scala/collection/parallel/ParSeqViewLike.scala b/src/library/scala/collection/parallel/ParSeqViewLike.scala index f3dbe20e67..9d30a052de 100644 --- a/src/library/scala/collection/parallel/ParSeqViewLike.scala +++ b/src/library/scala/collection/parallel/ParSeqViewLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.{ Parallel, SeqView, SeqViewLike, GenSeqView, GenSeqViewLike, GenSeq } import scala.collection.{ GenIterable, GenTraversable, GenTraversableOnce, Iterator } diff --git a/src/library/scala/collection/parallel/ParSet.scala b/src/library/scala/collection/parallel/ParSet.scala index bc6d5c6245..ba3d23f0e4 100644 --- a/src/library/scala/collection/parallel/ParSet.scala +++ b/src/library/scala/collection/parallel/ParSet.scala @@ -6,17 +6,10 @@ ** |/ ** \* */ +package scala +package collection +package parallel -package scala.collection.parallel - - - - - - - -import scala.collection.Set -import scala.collection.GenSet import scala.collection.generic._ /** A template trait for parallel sets. @@ -29,12 +22,12 @@ import scala.collection.generic._ * @since 2.9 */ trait ParSet[T] -extends GenSet[T] + extends GenSet[T] with GenericParTemplate[T, ParSet] with ParIterable[T] with ParSetLike[T, ParSet[T], Set[T]] -{ -self => +{ self => + override def empty: ParSet[T] = mutable.ParHashSet[T]() //protected[this] override def newCombiner: Combiner[T, ParSet[T]] = ParSet.newCombiner[T] @@ -44,39 +37,8 @@ self => override def stringPrefix = "ParSet" } - - object ParSet extends ParSetFactory[ParSet] { def newCombiner[T]: Combiner[T, ParSet[T]] = mutable.ParHashSetCombiner[T] implicit def canBuildFrom[T]: CanCombineFrom[Coll, T, ParSet[T]] = new GenericCanCombineFrom[T] } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/ParSetLike.scala b/src/library/scala/collection/parallel/ParSetLike.scala index 20a5f693ce..a50d2ae430 100644 --- a/src/library/scala/collection/parallel/ParSetLike.scala +++ b/src/library/scala/collection/parallel/ParSetLike.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection.parallel +package scala +package collection.parallel diff --git a/src/library/scala/collection/parallel/PreciseSplitter.scala b/src/library/scala/collection/parallel/PreciseSplitter.scala index 42563f4dc9..2eb202ce05 100644 --- a/src/library/scala/collection/parallel/PreciseSplitter.scala +++ b/src/library/scala/collection/parallel/PreciseSplitter.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.Seq diff --git a/src/library/scala/collection/parallel/RemainsIterator.scala b/src/library/scala/collection/parallel/RemainsIterator.scala index a3a47e2e40..5f2ceac0e0 100644 --- a/src/library/scala/collection/parallel/RemainsIterator.scala +++ b/src/library/scala/collection/parallel/RemainsIterator.scala @@ -6,10 +6,8 @@ ** |/ ** \* */ - -package scala.collection.parallel - - +package scala +package collection.parallel import scala.collection.Parallel import scala.collection.generic.Signalling @@ -21,8 +19,6 @@ import scala.collection.Iterator.empty import scala.collection.GenTraversableOnce import scala.collection.parallel.immutable.repetition - - private[collection] trait RemainsIterator[+T] extends Iterator[T] { /** The number of elements this iterator has yet to iterate. * This method doesn't change the state of the iterator. @@ -35,7 +31,6 @@ private[collection] trait RemainsIterator[+T] extends Iterator[T] { def isRemainingCheap = true } - /** Augments iterators with additional methods, mostly transformers, * assuming they iterate an iterable collection. * @@ -532,10 +527,8 @@ self => } def zipAllParSeq[S, U >: T, R >: S](that: SeqSplitter[S], thisElem: U, thatElem: R) = new ZippedAll[U, R](that, thisElem, thatElem) - } - /** Parallel sequence iterators allow splitting into arbitrary subsets. * * @tparam T type of the elements iterated. @@ -676,37 +669,3 @@ self => def patchParSeq[U >: T](from: Int, patchElems: SeqSplitter[U], replaced: Int) = new Patched(from, patchElems, replaced) } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/Splitter.scala b/src/library/scala/collection/parallel/Splitter.scala index 458742df96..8329f15d88 100644 --- a/src/library/scala/collection/parallel/Splitter.scala +++ b/src/library/scala/collection/parallel/Splitter.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.{ Seq, Iterator } diff --git a/src/library/scala/collection/parallel/TaskSupport.scala b/src/library/scala/collection/parallel/TaskSupport.scala index 1ab41bd296..84bb5e425b 100644 --- a/src/library/scala/collection/parallel/TaskSupport.scala +++ b/src/library/scala/collection/parallel/TaskSupport.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection.parallel +package scala +package collection.parallel diff --git a/src/library/scala/collection/parallel/Tasks.scala b/src/library/scala/collection/parallel/Tasks.scala index 487b3d46d3..b23131c773 100644 --- a/src/library/scala/collection/parallel/Tasks.scala +++ b/src/library/scala/collection/parallel/Tasks.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel diff --git a/src/library/scala/collection/parallel/immutable/ParHashMap.scala b/src/library/scala/collection/parallel/immutable/ParHashMap.scala index f3be47ea03..854d0ba918 100644 --- a/src/library/scala/collection/parallel/immutable/ParHashMap.scala +++ b/src/library/scala/collection/parallel/immutable/ParHashMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.immutable +package scala +package collection.parallel.immutable diff --git a/src/library/scala/collection/parallel/immutable/ParHashSet.scala b/src/library/scala/collection/parallel/immutable/ParHashSet.scala index 4f34993b85..65a632470e 100644 --- a/src/library/scala/collection/parallel/immutable/ParHashSet.scala +++ b/src/library/scala/collection/parallel/immutable/ParHashSet.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.immutable +package scala +package collection.parallel.immutable diff --git a/src/library/scala/collection/parallel/immutable/ParIterable.scala b/src/library/scala/collection/parallel/immutable/ParIterable.scala index ec07e44c4d..417622facc 100644 --- a/src/library/scala/collection/parallel/immutable/ParIterable.scala +++ b/src/library/scala/collection/parallel/immutable/ParIterable.scala @@ -6,13 +6,11 @@ ** |/ ** \* */ - -package scala.collection +package scala +package collection package parallel.immutable - import scala.collection.generic._ - import scala.collection.parallel.ParIterableLike import scala.collection.parallel.Combiner @@ -28,22 +26,18 @@ import scala.collection.parallel.Combiner * @since 2.9 */ trait ParIterable[+T] -extends scala.collection/*.immutable*/.GenIterable[T] +extends scala.collection.GenIterable[T] with scala.collection.parallel.ParIterable[T] with GenericParTemplate[T, ParIterable] with ParIterableLike[T, ParIterable[T], scala.collection.immutable.Iterable[T]] with Immutable { override def companion: GenericCompanion[ParIterable] with GenericParCompanion[ParIterable] = ParIterable - // if `immutable.ParIterableLike` is introduced, please move these 4 methods there override def toIterable: ParIterable[T] = this - override def toSeq: ParSeq[T] = toParCollection[T, ParSeq[T]](() => ParSeq.newCombiner[T]) - } - /** $factoryInfo */ object ParIterable extends ParFactory[ParIterable] { @@ -51,21 +45,5 @@ object ParIterable extends ParFactory[ParIterable] { new GenericCanCombineFrom[T] def newBuilder[T]: Combiner[T, ParIterable[T]] = ParVector.newBuilder[T] - def newCombiner[T]: Combiner[T, ParIterable[T]] = ParVector.newCombiner[T] - } - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/immutable/ParMap.scala b/src/library/scala/collection/parallel/immutable/ParMap.scala index e904a7616b..4d99006d0f 100644 --- a/src/library/scala/collection/parallel/immutable/ParMap.scala +++ b/src/library/scala/collection/parallel/immutable/ParMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package parallel.immutable import scala.collection.generic.ParMapFactory diff --git a/src/library/scala/collection/parallel/immutable/ParRange.scala b/src/library/scala/collection/parallel/immutable/ParRange.scala index 78bbad5933..ec90de3a7d 100644 --- a/src/library/scala/collection/parallel/immutable/ParRange.scala +++ b/src/library/scala/collection/parallel/immutable/ParRange.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.immutable +package scala +package collection.parallel.immutable import scala.collection.immutable.Range import scala.collection.parallel.Combiner @@ -106,7 +107,7 @@ self => cb } } - + } object ParRange { diff --git a/src/library/scala/collection/parallel/immutable/ParSeq.scala b/src/library/scala/collection/parallel/immutable/ParSeq.scala index b54a5f0205..6e98b3102d 100644 --- a/src/library/scala/collection/parallel/immutable/ParSeq.scala +++ b/src/library/scala/collection/parallel/immutable/ParSeq.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package parallel.immutable diff --git a/src/library/scala/collection/parallel/immutable/ParSet.scala b/src/library/scala/collection/parallel/immutable/ParSet.scala index aba8486ab5..7837d6f264 100644 --- a/src/library/scala/collection/parallel/immutable/ParSet.scala +++ b/src/library/scala/collection/parallel/immutable/ParSet.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package parallel.immutable import scala.collection.generic._ diff --git a/src/library/scala/collection/parallel/immutable/ParVector.scala b/src/library/scala/collection/parallel/immutable/ParVector.scala index 1ee7f4ae69..548e7112c7 100644 --- a/src/library/scala/collection/parallel/immutable/ParVector.scala +++ b/src/library/scala/collection/parallel/immutable/ParVector.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package parallel.immutable diff --git a/src/library/scala/collection/parallel/immutable/package.scala b/src/library/scala/collection/parallel/immutable/package.scala index 5ca0724ffc..8fd84eaf4d 100644 --- a/src/library/scala/collection/parallel/immutable/package.scala +++ b/src/library/scala/collection/parallel/immutable/package.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel package immutable { /** A (parallel) sequence consisting of `length` elements `elem`. Used in the `padTo` method. diff --git a/src/library/scala/collection/parallel/mutable/LazyCombiner.scala b/src/library/scala/collection/parallel/mutable/LazyCombiner.scala index 12b2bc5008..cc25b5b4b2 100644 --- a/src/library/scala/collection/parallel/mutable/LazyCombiner.scala +++ b/src/library/scala/collection/parallel/mutable/LazyCombiner.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.mutable +package scala +package collection.parallel.mutable import scala.collection.generic.Growable import scala.collection.generic.Sizing diff --git a/src/library/scala/collection/parallel/mutable/ParArray.scala b/src/library/scala/collection/parallel/mutable/ParArray.scala index f9563cacc7..d0d022db4b 100644 --- a/src/library/scala/collection/parallel/mutable/ParArray.scala +++ b/src/library/scala/collection/parallel/mutable/ParArray.scala @@ -29,8 +29,6 @@ import scala.collection.mutable.Builder import scala.collection.GenTraversableOnce import scala.reflect.ClassTag - - /** Parallel sequence holding elements in a linear array. * * `ParArray` is a parallel sequence with a predefined size. The size of the array @@ -702,7 +700,7 @@ object ParArray extends ParFactory[ParArray] { private def wrapOrRebuild[T](arr: AnyRef, sz: Int) = arr match { case arr: Array[AnyRef] => new ParArray[T](new ExposedArraySeq[T](arr, sz)) - case _ => new ParArray[T](new ExposedArraySeq[T](runtime.ScalaRunTime.toObjectArray(arr), sz)) + case _ => new ParArray[T](new ExposedArraySeq[T](scala.runtime.ScalaRunTime.toObjectArray(arr), sz)) } def createFromCopy[T <: AnyRef : ClassTag](arr: Array[T]): ParArray[T] = { @@ -720,27 +718,3 @@ object ParArray extends ParFactory[ParArray] { } } - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala b/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala index aa790dd548..afc2d6e987 100644 --- a/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala +++ b/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package parallel.mutable import scala.collection.parallel.IterableSplitter diff --git a/src/library/scala/collection/parallel/mutable/ParHashMap.scala b/src/library/scala/collection/parallel/mutable/ParHashMap.scala index e94db89865..42a3302c91 100644 --- a/src/library/scala/collection/parallel/mutable/ParHashMap.scala +++ b/src/library/scala/collection/parallel/mutable/ParHashMap.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection.parallel +package scala +package collection.parallel package mutable diff --git a/src/library/scala/collection/parallel/mutable/ParHashSet.scala b/src/library/scala/collection/parallel/mutable/ParHashSet.scala index 0287171369..1e3d57e0e5 100644 --- a/src/library/scala/collection/parallel/mutable/ParHashSet.scala +++ b/src/library/scala/collection/parallel/mutable/ParHashSet.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.mutable +package scala +package collection.parallel.mutable diff --git a/src/library/scala/collection/parallel/mutable/ParHashTable.scala b/src/library/scala/collection/parallel/mutable/ParHashTable.scala index 5aa1dba17c..a6fada3d42 100644 --- a/src/library/scala/collection/parallel/mutable/ParHashTable.scala +++ b/src/library/scala/collection/parallel/mutable/ParHashTable.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package parallel.mutable diff --git a/src/library/scala/collection/parallel/mutable/ParIterable.scala b/src/library/scala/collection/parallel/mutable/ParIterable.scala index d76e4b1745..4659149106 100644 --- a/src/library/scala/collection/parallel/mutable/ParIterable.scala +++ b/src/library/scala/collection/parallel/mutable/ParIterable.scala @@ -6,12 +6,12 @@ ** |/ ** \* */ -package scala.collection.parallel.mutable - +package scala +package collection +package parallel.mutable import scala.collection.generic._ -import scala.collection.parallel.ParIterableLike -import scala.collection.parallel.Combiner +import scala.collection.parallel.{ ParIterableLike, Combiner } /** A template trait for mutable parallel iterable collections. * @@ -24,7 +24,7 @@ import scala.collection.parallel.Combiner * @author Aleksandar Prokopec * @since 2.9 */ -trait ParIterable[T] extends scala.collection/*.mutable*/.GenIterable[T] +trait ParIterable[T] extends scala.collection.GenIterable[T] with scala.collection.parallel.ParIterable[T] with GenericParTemplate[T, ParIterable] with ParIterableLike[T, ParIterable[T], Iterable[T]] @@ -43,24 +43,8 @@ trait ParIterable[T] extends scala.collection/*.mutable*/.GenIterable[T] /** $factoryInfo */ object ParIterable extends ParFactory[ParIterable] { - implicit def canBuildFrom[T]: CanCombineFrom[Coll, T, ParIterable[T]] = - new GenericCanCombineFrom[T] + implicit def canBuildFrom[T]: CanCombineFrom[Coll, T, ParIterable[T]] = new GenericCanCombineFrom[T] def newBuilder[T]: Combiner[T, ParIterable[T]] = ParArrayCombiner[T] - def newCombiner[T]: Combiner[T, ParIterable[T]] = ParArrayCombiner[T] } - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/mutable/ParMap.scala b/src/library/scala/collection/parallel/mutable/ParMap.scala index 2250a38466..e43e72e559 100644 --- a/src/library/scala/collection/parallel/mutable/ParMap.scala +++ b/src/library/scala/collection/parallel/mutable/ParMap.scala @@ -6,17 +6,13 @@ ** |/ ** \* */ - -package scala.collection.parallel.mutable - - - +package scala +package collection +package parallel.mutable import scala.collection.generic._ import scala.collection.parallel.Combiner - - /** A template trait for mutable parallel maps. * * $sideeffects @@ -28,11 +24,11 @@ import scala.collection.parallel.Combiner * @since 2.9 */ trait ParMap[K, V] -extends scala.collection/*.mutable*/.GenMap[K, V] - with scala.collection.parallel.ParMap[K, V] - with /* mutable */ ParIterable[(K, V)] +extends GenMap[K, V] + with parallel.ParMap[K, V] + with ParIterable[(K, V)] with GenericParMapTemplate[K, V, ParMap] - with /* mutable */ ParMapLike[K, V, ParMap[K, V], scala.collection.mutable.Map[K, V]] + with ParMapLike[K, V, ParMap[K, V], mutable.Map[K, V]] { protected[this] override def newCombiner: Combiner[(K, V), ParMap[K, V]] = ParMap.newCombiner[K, V] @@ -63,11 +59,8 @@ extends scala.collection/*.mutable*/.GenMap[K, V] * @return a wrapper of the map with a default value */ def withDefaultValue(d: V): scala.collection.parallel.mutable.ParMap[K, V] = new ParMap.WithDefault[K, V](this, x => d) - } - - object ParMap extends ParMapFactory[ParMap] { def empty[K, V]: ParMap[K, V] = new ParHashMap[K, V] @@ -94,22 +87,3 @@ object ParMap extends ParMapFactory[ParMap] { override def withDefaultValue(d: V): ParMap[K, V] = new WithDefault[K, V](underlying, x => d) } } - - - - - - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/mutable/ParMapLike.scala b/src/library/scala/collection/parallel/mutable/ParMapLike.scala index 08bc706c8a..d96b5482fe 100644 --- a/src/library/scala/collection/parallel/mutable/ParMapLike.scala +++ b/src/library/scala/collection/parallel/mutable/ParMapLike.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel package mutable diff --git a/src/library/scala/collection/parallel/mutable/ParSeq.scala b/src/library/scala/collection/parallel/mutable/ParSeq.scala index 8a55ab83f1..35be2669f8 100644 --- a/src/library/scala/collection/parallel/mutable/ParSeq.scala +++ b/src/library/scala/collection/parallel/mutable/ParSeq.scala @@ -6,9 +6,8 @@ ** |/ ** \* */ - -package scala.collection.parallel.mutable - +package scala +package collection.parallel.mutable import scala.collection.generic.GenericParTemplate import scala.collection.generic.GenericCompanion @@ -51,18 +50,3 @@ object ParSeq extends ParFactory[ParSeq] { def newCombiner[T]: Combiner[T, ParSeq[T]] = ParArrayCombiner[T] } - - - - - - - - - - - - - - - diff --git a/src/library/scala/collection/parallel/mutable/ParSet.scala b/src/library/scala/collection/parallel/mutable/ParSet.scala index ca41852512..9367f1424d 100644 --- a/src/library/scala/collection/parallel/mutable/ParSet.scala +++ b/src/library/scala/collection/parallel/mutable/ParSet.scala @@ -6,10 +6,8 @@ ** |/ ** \* */ - -package scala.collection.parallel.mutable - - +package scala +package collection.parallel.mutable import scala.collection.generic._ import scala.collection.parallel.Combiner @@ -46,4 +44,3 @@ object ParSet extends ParSetFactory[ParSet] { override def newCombiner[T]: Combiner[T, ParSet[T]] = ParHashSet.newCombiner } - diff --git a/src/library/scala/collection/parallel/mutable/ParSetLike.scala b/src/library/scala/collection/parallel/mutable/ParSetLike.scala index 0941229124..1cfc14b094 100644 --- a/src/library/scala/collection/parallel/mutable/ParSetLike.scala +++ b/src/library/scala/collection/parallel/mutable/ParSetLike.scala @@ -7,7 +7,8 @@ \* */ -package scala.collection +package scala +package collection package parallel.mutable import scala.collection.mutable.Cloneable diff --git a/src/library/scala/collection/parallel/mutable/ParTrieMap.scala b/src/library/scala/collection/parallel/mutable/ParTrieMap.scala index 60f4709a8c..82f2717132 100644 --- a/src/library/scala/collection/parallel/mutable/ParTrieMap.scala +++ b/src/library/scala/collection/parallel/mutable/ParTrieMap.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.mutable +package scala +package collection.parallel.mutable diff --git a/src/library/scala/collection/parallel/mutable/ResizableParArrayCombiner.scala b/src/library/scala/collection/parallel/mutable/ResizableParArrayCombiner.scala index 0b9b51bc5b..79322c85b1 100644 --- a/src/library/scala/collection/parallel/mutable/ResizableParArrayCombiner.scala +++ b/src/library/scala/collection/parallel/mutable/ResizableParArrayCombiner.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.mutable +package scala +package collection.parallel.mutable diff --git a/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala b/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala index 7766f07e23..6b6ea03a6d 100644 --- a/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala +++ b/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel.mutable +package scala +package collection.parallel.mutable import scala.collection.generic.Sizing import scala.collection.mutable.ArraySeq diff --git a/src/library/scala/collection/parallel/mutable/package.scala b/src/library/scala/collection/parallel/mutable/package.scala index 2494d0907e..81121d9398 100644 --- a/src/library/scala/collection/parallel/mutable/package.scala +++ b/src/library/scala/collection/parallel/mutable/package.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection.parallel +package scala +package collection.parallel import scala.collection.mutable.ArrayBuffer import scala.collection.mutable.ArraySeq diff --git a/src/library/scala/collection/script/Location.scala b/src/library/scala/collection/script/Location.scala index cd64fa2d73..e485737972 100644 --- a/src/library/scala/collection/script/Location.scala +++ b/src/library/scala/collection/script/Location.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package script /** Class `Location` describes locations in messages implemented by diff --git a/src/library/scala/collection/script/Message.scala b/src/library/scala/collection/script/Message.scala index 7428cd2b81..dc3e74e170 100644 --- a/src/library/scala/collection/script/Message.scala +++ b/src/library/scala/collection/script/Message.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package script import mutable.ArrayBuffer diff --git a/src/library/scala/collection/script/Scriptable.scala b/src/library/scala/collection/script/Scriptable.scala index ceaf19a464..110a0f4d82 100644 --- a/src/library/scala/collection/script/Scriptable.scala +++ b/src/library/scala/collection/script/Scriptable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.collection +package scala +package collection package script /** Classes that mix in the `Scriptable` class allow messages to be sent to diff --git a/src/library/scala/compat/Platform.scala b/src/library/scala/compat/Platform.scala index 88cb1506ae..875d811b9b 100644 --- a/src/library/scala/compat/Platform.scala +++ b/src/library/scala/compat/Platform.scala @@ -6,9 +6,8 @@ ** |/ ** \* */ - - -package scala.compat +package scala +package compat import java.lang.System diff --git a/src/library/scala/concurrent/duration/Duration.scala b/src/library/scala/concurrent/duration/Duration.scala index 6c6155279d..a24266bf19 100644 --- a/src/library/scala/concurrent/duration/Duration.scala +++ b/src/library/scala/concurrent/duration/Duration.scala @@ -10,6 +10,7 @@ package scala.concurrent.duration import java.lang.{ Double => JDouble, Long => JLong } import scala.language.implicitConversions +import scala.language.postfixOps object Duration { @@ -663,8 +664,8 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio * Long.MinValue is not a legal `length` anyway. */ private def safeMul(_a: Long, _b: Long): Long = { - val a = math.abs(_a) - val b = math.abs(_b) + val a = scala.math.abs(_a) + val b = scala.math.abs(_b) import java.lang.Long.{ numberOfLeadingZeros => leading } if (leading(a) + leading(b) < 64) throw new IllegalArgumentException("multiplication overflow") val product = a * b diff --git a/src/library/scala/concurrent/impl/ExecutionContextImpl.scala b/src/library/scala/concurrent/impl/ExecutionContextImpl.scala index e4a0f464f9..ed04293e0d 100644 --- a/src/library/scala/concurrent/impl/ExecutionContextImpl.scala +++ b/src/library/scala/concurrent/impl/ExecutionContextImpl.scala @@ -30,7 +30,7 @@ private[scala] class ExecutionContextImpl private[impl] (es: Executor, reporter: } // Implement BlockContext on FJP threads - class DefaultThreadFactory(daemonic: Boolean) extends ThreadFactory with ForkJoinPool.ForkJoinWorkerThreadFactory { + class DefaultThreadFactory(daemonic: Boolean) extends ThreadFactory with ForkJoinPool.ForkJoinWorkerThreadFactory { def wire[T <: Thread](thread: T): T = { thread.setDaemon(daemonic) thread.setUncaughtExceptionHandler(uncaughtExceptionHandler) @@ -72,7 +72,7 @@ private[scala] class ExecutionContextImpl private[impl] (es: Executor, reporter: getInt("scala.concurrent.context.maxThreads", _.toInt)) val threadFactory = new DefaultThreadFactory(daemonic = true) - + try { new ForkJoinPool( desiredParallelism, @@ -98,13 +98,13 @@ private[scala] class ExecutionContextImpl private[impl] (es: Executor, reporter: def execute(runnable: Runnable): Unit = executor match { case fj: ForkJoinPool => - val fjt = runnable match { + val fjt: ForkJoinTask[_] = runnable match { case t: ForkJoinTask[_] => t - case r => new ExecutionContextImpl.AdaptedForkJoinTask(r) + case r => new ExecutionContextImpl.AdaptedForkJoinTask(r) } Thread.currentThread match { case fjw: ForkJoinWorkerThread if fjw.getPool eq fj => fjt.fork() - case _ => fj execute fjt + case _ => fj execute fjt } case generic => generic execute runnable } diff --git a/src/library/scala/io/Codec.scala b/src/library/scala/io/Codec.scala index bda4234460..60f99199cb 100644 --- a/src/library/scala/io/Codec.scala +++ b/src/library/scala/io/Codec.scala @@ -6,8 +6,8 @@ ** |/ ** \* */ - -package scala.io +package scala +package io import java.nio.charset.{ Charset, CharsetDecoder, CharsetEncoder, CharacterCodingException, CodingErrorAction => Action } import scala.annotation.migration diff --git a/src/library/scala/io/Position.scala b/src/library/scala/io/Position.scala index b96349803d..85149223ee 100644 --- a/src/library/scala/io/Position.scala +++ b/src/library/scala/io/Position.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.io +package scala +package io /** The object Position provides convenience methods to encode * line and column number in one single integer. The encoded line diff --git a/src/library/scala/io/Source.scala b/src/library/scala/io/Source.scala index f976c7eb0a..74c3e06839 100644 --- a/src/library/scala/io/Source.scala +++ b/src/library/scala/io/Source.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.io +package scala +package io import scala.collection.AbstractIterator import java.io.{ FileInputStream, InputStream, PrintStream, File => JFile } diff --git a/src/library/scala/math/BigDecimal.scala b/src/library/scala/math/BigDecimal.scala index c5e5699468..f75cfad882 100644 --- a/src/library/scala/math/BigDecimal.scala +++ b/src/library/scala/math/BigDecimal.scala @@ -7,7 +7,8 @@ \* */ -package scala.math +package scala +package math import java.{ lang => jl } import java.math.{ MathContext, BigDecimal => BigDec } diff --git a/src/library/scala/math/BigInt.scala b/src/library/scala/math/BigInt.scala index 719099b405..4673aa5d48 100644 --- a/src/library/scala/math/BigInt.scala +++ b/src/library/scala/math/BigInt.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math import java.math.BigInteger import scala.language.implicitConversions diff --git a/src/library/scala/math/Equiv.scala b/src/library/scala/math/Equiv.scala index 5f5e049941..45b2b3629d 100644 --- a/src/library/scala/math/Equiv.scala +++ b/src/library/scala/math/Equiv.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math import java.util.Comparator diff --git a/src/library/scala/math/Fractional.scala b/src/library/scala/math/Fractional.scala index ca33675b0a..b7e0ed5471 100644 --- a/src/library/scala/math/Fractional.scala +++ b/src/library/scala/math/Fractional.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math import scala.language.implicitConversions diff --git a/src/library/scala/math/Integral.scala b/src/library/scala/math/Integral.scala index f3684c4e5d..ff1f695f6d 100644 --- a/src/library/scala/math/Integral.scala +++ b/src/library/scala/math/Integral.scala @@ -8,7 +8,8 @@ -package scala.math +package scala +package math import scala.language.implicitConversions diff --git a/src/library/scala/math/Numeric.scala b/src/library/scala/math/Numeric.scala index 5a76f4f5f2..cb9f9deb70 100644 --- a/src/library/scala/math/Numeric.scala +++ b/src/library/scala/math/Numeric.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math import scala.language.implicitConversions diff --git a/src/library/scala/math/Ordered.scala b/src/library/scala/math/Ordered.scala index e8be92eb4a..51f2765a63 100644 --- a/src/library/scala/math/Ordered.scala +++ b/src/library/scala/math/Ordered.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math import scala.language.implicitConversions diff --git a/src/library/scala/math/PartialOrdering.scala b/src/library/scala/math/PartialOrdering.scala index a9e317d536..9e35381528 100644 --- a/src/library/scala/math/PartialOrdering.scala +++ b/src/library/scala/math/PartialOrdering.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math /** A trait for representing partial orderings. It is important to * distinguish between a type that has a partial order and a representation diff --git a/src/library/scala/math/PartiallyOrdered.scala b/src/library/scala/math/PartiallyOrdered.scala index 7823e5b396..f58210d6a7 100644 --- a/src/library/scala/math/PartiallyOrdered.scala +++ b/src/library/scala/math/PartiallyOrdered.scala @@ -8,7 +8,8 @@ -package scala.math +package scala +package math /** A class for partially ordered data. * diff --git a/src/library/scala/math/ScalaNumber.java b/src/library/scala/math/ScalaNumber.java index 7345147b0d..f03ba7bf08 100644 --- a/src/library/scala/math/ScalaNumber.java +++ b/src/library/scala/math/ScalaNumber.java @@ -6,8 +6,6 @@ ** |/ ** \* */ - - package scala.math; /** A marker class for Number types introduced by Scala diff --git a/src/library/scala/math/ScalaNumericConversions.scala b/src/library/scala/math/ScalaNumericConversions.scala index e748841c12..336991781e 100644 --- a/src/library/scala/math/ScalaNumericConversions.scala +++ b/src/library/scala/math/ScalaNumericConversions.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.math +package scala +package math /** A slightly more specific conversion trait for classes which * extend ScalaNumber (which excludes value classes.) diff --git a/src/library/scala/reflect/ClassManifestDeprecatedApis.scala b/src/library/scala/reflect/ClassManifestDeprecatedApis.scala index 0a3d818fb9..798746851a 100644 --- a/src/library/scala/reflect/ClassManifestDeprecatedApis.scala +++ b/src/library/scala/reflect/ClassManifestDeprecatedApis.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.reflect +package scala +package reflect import scala.collection.mutable.{ WrappedArray, ArrayBuilder } import java.lang.{ Class => jClass } diff --git a/src/library/scala/reflect/Manifest.scala b/src/library/scala/reflect/Manifest.scala index f62d0ecd16..3bc76da295 100644 --- a/src/library/scala/reflect/Manifest.scala +++ b/src/library/scala/reflect/Manifest.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.reflect +package scala +package reflect import scala.collection.mutable.{ ArrayBuilder, WrappedArray } diff --git a/src/library/scala/reflect/NoManifest.scala b/src/library/scala/reflect/NoManifest.scala index 61bc5e28d3..2ef946c80c 100644 --- a/src/library/scala/reflect/NoManifest.scala +++ b/src/library/scala/reflect/NoManifest.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.reflect +package scala +package reflect /** One of the branches of an [[scala.reflect.OptManifest]]. */ diff --git a/src/library/scala/reflect/OptManifest.scala b/src/library/scala/reflect/OptManifest.scala index 5e373c7318..b69f55483c 100644 --- a/src/library/scala/reflect/OptManifest.scala +++ b/src/library/scala/reflect/OptManifest.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.reflect +package scala +package reflect /** A `OptManifest[T]` is an optional [[scala.reflect.Manifest]]. * diff --git a/src/library/scala/runtime/AbstractPartialFunction.scala b/src/library/scala/runtime/AbstractPartialFunction.scala index 57f8e2603b..e3516bc4d9 100644 --- a/src/library/scala/runtime/AbstractPartialFunction.scala +++ b/src/library/scala/runtime/AbstractPartialFunction.scala @@ -6,7 +6,10 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + +import scala.annotation.unspecialized /** `AbstractPartialFunction` reformulates all operations of its supertrait `PartialFunction` * in terms of `isDefinedAt` and `applyOrElse`. diff --git a/src/library/scala/runtime/BooleanRef.java b/src/library/scala/runtime/BooleanRef.java index 889db31e2a..92e8055351 100644 --- a/src/library/scala/runtime/BooleanRef.java +++ b/src/library/scala/runtime/BooleanRef.java @@ -17,4 +17,7 @@ public class BooleanRef implements java.io.Serializable { public boolean elem; public BooleanRef(boolean elem) { this.elem = elem; } public String toString() { return String.valueOf(elem); } + + public static BooleanRef create(boolean e) { return new BooleanRef(e); } + public static BooleanRef zero() { return new BooleanRef(false); } } diff --git a/src/library/scala/runtime/Boxed.scala b/src/library/scala/runtime/Boxed.scala index 8b531076ac..855f0ff41a 100644 --- a/src/library/scala/runtime/Boxed.scala +++ b/src/library/scala/runtime/Boxed.scala @@ -8,7 +8,9 @@ -package scala.runtime +package scala +package runtime + trait Boxed { diff --git a/src/library/scala/runtime/ByteRef.java b/src/library/scala/runtime/ByteRef.java index cc10611e26..27d3259db3 100644 --- a/src/library/scala/runtime/ByteRef.java +++ b/src/library/scala/runtime/ByteRef.java @@ -17,4 +17,7 @@ public class ByteRef implements java.io.Serializable { public byte elem; public ByteRef(byte elem) { this.elem = elem; } public String toString() { return java.lang.Byte.toString(elem); } + + public static ByteRef create(byte e) { return new ByteRef(e); } + public static ByteRef zero() { return new ByteRef((byte)0); } } diff --git a/src/library/scala/runtime/CharRef.java b/src/library/scala/runtime/CharRef.java index 03d3337b3d..31956f5b55 100644 --- a/src/library/scala/runtime/CharRef.java +++ b/src/library/scala/runtime/CharRef.java @@ -17,4 +17,7 @@ public class CharRef implements java.io.Serializable { public char elem; public CharRef(char elem) { this.elem = elem; } public String toString() { return java.lang.Character.toString(elem); } + + public static CharRef create(char e) { return new CharRef(e); } + public static CharRef zero() { return new CharRef((char)0); } } diff --git a/src/library/scala/runtime/DoubleRef.java b/src/library/scala/runtime/DoubleRef.java index 317198ee48..0c7d9156d6 100644 --- a/src/library/scala/runtime/DoubleRef.java +++ b/src/library/scala/runtime/DoubleRef.java @@ -17,4 +17,7 @@ public class DoubleRef implements java.io.Serializable { public double elem; public DoubleRef(double elem) { this.elem = elem; } public String toString() { return java.lang.Double.toString(elem); } + + public static DoubleRef create(double e) { return new DoubleRef(e); } + public static DoubleRef zero() { return new DoubleRef(0); } } diff --git a/src/library/scala/runtime/FloatRef.java b/src/library/scala/runtime/FloatRef.java index e26b89be60..f0e1d5f8f3 100644 --- a/src/library/scala/runtime/FloatRef.java +++ b/src/library/scala/runtime/FloatRef.java @@ -17,4 +17,7 @@ public class FloatRef implements java.io.Serializable { public float elem; public FloatRef(float elem) { this.elem = elem; } public String toString() { return java.lang.Float.toString(elem); } + + public static FloatRef create(float e) { return new FloatRef(e); } + public static FloatRef zero() { return new FloatRef(0); } } diff --git a/src/library/scala/runtime/IntRef.java b/src/library/scala/runtime/IntRef.java index edb6fafe94..adcf474aae 100644 --- a/src/library/scala/runtime/IntRef.java +++ b/src/library/scala/runtime/IntRef.java @@ -17,4 +17,7 @@ public class IntRef implements java.io.Serializable { public int elem; public IntRef(int elem) { this.elem = elem; } public String toString() { return java.lang.Integer.toString(elem); } + + public static IntRef create(int e) { return new IntRef(e); } + public static IntRef zero() { return new IntRef(0); } } diff --git a/src/library/scala/runtime/LongRef.java b/src/library/scala/runtime/LongRef.java index 12004b5bb5..51426ab8f6 100644 --- a/src/library/scala/runtime/LongRef.java +++ b/src/library/scala/runtime/LongRef.java @@ -17,4 +17,7 @@ public class LongRef implements java.io.Serializable { public long elem; public LongRef(long elem) { this.elem = elem; } public String toString() { return java.lang.Long.toString(elem); } + + public static LongRef create(long e) { return new LongRef(e); } + public static LongRef zero() { return new LongRef(0); } } diff --git a/src/library/scala/runtime/MethodCache.scala b/src/library/scala/runtime/MethodCache.scala index 217b51893b..bbf80593db 100644 --- a/src/library/scala/runtime/MethodCache.scala +++ b/src/library/scala/runtime/MethodCache.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + import java.lang.reflect.{ Method => JMethod } import java.lang.{ Class => JClass } diff --git a/src/library/scala/runtime/NonLocalReturnControl.scala b/src/library/scala/runtime/NonLocalReturnControl.scala index b9525ef419..16b2fec6d7 100644 --- a/src/library/scala/runtime/NonLocalReturnControl.scala +++ b/src/library/scala/runtime/NonLocalReturnControl.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + import scala.util.control.ControlThrowable diff --git a/src/library/scala/runtime/Nothing$.scala b/src/library/scala/runtime/Nothing$.scala index 04fcc55a1c..4ecc536223 100644 --- a/src/library/scala/runtime/Nothing$.scala +++ b/src/library/scala/runtime/Nothing$.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + /** * Dummy class which exist only to satisfy the JVM. It corresponds diff --git a/src/library/scala/runtime/Null$.scala b/src/library/scala/runtime/Null$.scala index 25b797a606..1b7685c507 100644 --- a/src/library/scala/runtime/Null$.scala +++ b/src/library/scala/runtime/Null$.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + /** * Dummy class which exist only to satisfy the JVM. It corresponds to diff --git a/src/library/scala/runtime/ObjectRef.java b/src/library/scala/runtime/ObjectRef.java index c8298b8b21..c553c780a8 100644 --- a/src/library/scala/runtime/ObjectRef.java +++ b/src/library/scala/runtime/ObjectRef.java @@ -17,4 +17,7 @@ public class ObjectRef<T> implements java.io.Serializable { public T elem; public ObjectRef(T elem) { this.elem = elem; } public String toString() { return String.valueOf(elem); } + + public static <U> ObjectRef create(U e) { return new ObjectRef(e); } + public static ObjectRef zero() { return new ObjectRef(null); } } diff --git a/src/library/scala/runtime/RichBoolean.scala b/src/library/scala/runtime/RichBoolean.scala index 97e2b77f96..4f867960a0 100644 --- a/src/library/scala/runtime/RichBoolean.scala +++ b/src/library/scala/runtime/RichBoolean.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + final class RichBoolean(val self: Boolean) extends AnyVal with OrderedProxy[Boolean] { protected def ord = scala.math.Ordering.Boolean diff --git a/src/library/scala/runtime/RichByte.scala b/src/library/scala/runtime/RichByte.scala index ca578620cf..ea23cb8867 100644 --- a/src/library/scala/runtime/RichByte.scala +++ b/src/library/scala/runtime/RichByte.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + final class RichByte(val self: Byte) extends AnyVal with ScalaWholeNumberProxy[Byte] { protected def num = scala.math.Numeric.ByteIsIntegral diff --git a/src/library/scala/runtime/RichChar.scala b/src/library/scala/runtime/RichChar.scala index 5124ca00de..c069fd1fef 100644 --- a/src/library/scala/runtime/RichChar.scala +++ b/src/library/scala/runtime/RichChar.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + import java.lang.Character diff --git a/src/library/scala/runtime/RichException.scala b/src/library/scala/runtime/RichException.scala index cf4eb71ded..f01788a4e9 100644 --- a/src/library/scala/runtime/RichException.scala +++ b/src/library/scala/runtime/RichException.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime import scala.compat.Platform.EOL diff --git a/src/library/scala/runtime/RichInt.scala b/src/library/scala/runtime/RichInt.scala index 192f94f939..a39710b146 100644 --- a/src/library/scala/runtime/RichInt.scala +++ b/src/library/scala/runtime/RichInt.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + import scala.collection.immutable.Range diff --git a/src/library/scala/runtime/RichLong.scala b/src/library/scala/runtime/RichLong.scala index ce2d1fdcbd..e5b39b1c09 100644 --- a/src/library/scala/runtime/RichLong.scala +++ b/src/library/scala/runtime/RichLong.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + final class RichLong(val self: Long) extends AnyVal with IntegralProxy[Long] { protected def num = scala.math.Numeric.LongIsIntegral diff --git a/src/library/scala/runtime/RichShort.scala b/src/library/scala/runtime/RichShort.scala index aa24dd2ba6..3e5d8781ff 100644 --- a/src/library/scala/runtime/RichShort.scala +++ b/src/library/scala/runtime/RichShort.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + final class RichShort(val self: Short) extends AnyVal with ScalaWholeNumberProxy[Short] { protected def num = scala.math.Numeric.ShortIsIntegral diff --git a/src/library/scala/runtime/ScalaNumberProxy.scala b/src/library/scala/runtime/ScalaNumberProxy.scala index e8460a203b..6ea6448b1a 100644 --- a/src/library/scala/runtime/ScalaNumberProxy.scala +++ b/src/library/scala/runtime/ScalaNumberProxy.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime import scala.collection.{ mutable, immutable } import scala.math.{ ScalaNumericConversions, ScalaNumericAnyConversions } diff --git a/src/library/scala/runtime/ShortRef.java b/src/library/scala/runtime/ShortRef.java index 461b521e5f..e5e8de3d8b 100644 --- a/src/library/scala/runtime/ShortRef.java +++ b/src/library/scala/runtime/ShortRef.java @@ -17,4 +17,7 @@ public class ShortRef implements java.io.Serializable { public short elem; public ShortRef(short elem) { this.elem = elem; } public String toString() { return java.lang.Short.toString(elem); } + + public static ShortRef create(short e) { return new ShortRef(e); } + public static ShortRef zero() { return new ShortRef((short)0); } } diff --git a/src/library/scala/runtime/StringAdd.scala b/src/library/scala/runtime/StringAdd.scala index 1456d9a4e4..d5b51a6e92 100644 --- a/src/library/scala/runtime/StringAdd.scala +++ b/src/library/scala/runtime/StringAdd.scala @@ -6,7 +6,9 @@ ** ** \* */ -package scala.runtime +package scala +package runtime + /** A wrapper class that adds string concatenation `+` to any value */ @deprecated("Use Predef.StringAdd", "2.11.0") diff --git a/src/library/scala/runtime/StringFormat.scala b/src/library/scala/runtime/StringFormat.scala index 21e5efd1fc..de32ac7e86 100644 --- a/src/library/scala/runtime/StringFormat.scala +++ b/src/library/scala/runtime/StringFormat.scala @@ -6,7 +6,9 @@ ** ** \* */ -package scala.runtime +package scala +package runtime + /** A wrapper class that adds a `formatted` operation to any value */ diff --git a/src/library/scala/runtime/Tuple2Zipped.scala b/src/library/scala/runtime/Tuple2Zipped.scala index bde69a0f54..b28f6d4269 100644 --- a/src/library/scala/runtime/Tuple2Zipped.scala +++ b/src/library/scala/runtime/Tuple2Zipped.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + import scala.collection.{ TraversableLike, IterableLike } import scala.collection.generic.{ CanBuildFrom => CBF } diff --git a/src/library/scala/runtime/Tuple3Zipped.scala b/src/library/scala/runtime/Tuple3Zipped.scala index 34da42462a..7c501380a3 100644 --- a/src/library/scala/runtime/Tuple3Zipped.scala +++ b/src/library/scala/runtime/Tuple3Zipped.scala @@ -6,7 +6,9 @@ ** |/ ** \* */ -package scala.runtime +package scala +package runtime + import scala.collection.{ TraversableLike, IterableLike } import scala.collection.generic.{ CanBuildFrom => CBF } diff --git a/src/library/scala/runtime/VolatileBooleanRef.java b/src/library/scala/runtime/VolatileBooleanRef.java index e3bd182345..ef5b691118 100755 --- a/src/library/scala/runtime/VolatileBooleanRef.java +++ b/src/library/scala/runtime/VolatileBooleanRef.java @@ -17,4 +17,7 @@ public class VolatileBooleanRef implements java.io.Serializable { volatile public boolean elem; public VolatileBooleanRef(boolean elem) { this.elem = elem; } public String toString() { return String.valueOf(elem); } + + public static VolatileBooleanRef create(boolean e) { return new VolatileBooleanRef(e); } + public static VolatileBooleanRef zero() { return new VolatileBooleanRef(false); } } diff --git a/src/library/scala/runtime/VolatileByteRef.java b/src/library/scala/runtime/VolatileByteRef.java index 034b003017..d792b0a386 100755 --- a/src/library/scala/runtime/VolatileByteRef.java +++ b/src/library/scala/runtime/VolatileByteRef.java @@ -17,4 +17,7 @@ public class VolatileByteRef implements java.io.Serializable { volatile public byte elem; public VolatileByteRef(byte elem) { this.elem = elem; } public String toString() { return java.lang.Byte.toString(elem); } + + public static VolatileByteRef create(byte e) { return new VolatileByteRef(e); } + public static VolatileByteRef zero() { return new VolatileByteRef((byte)0); } } diff --git a/src/library/scala/runtime/VolatileCharRef.java b/src/library/scala/runtime/VolatileCharRef.java index f90648c5e9..555b171283 100755 --- a/src/library/scala/runtime/VolatileCharRef.java +++ b/src/library/scala/runtime/VolatileCharRef.java @@ -17,4 +17,7 @@ public class VolatileCharRef implements java.io.Serializable { volatile public char elem; public VolatileCharRef(char elem) { this.elem = elem; } public String toString() { return java.lang.Character.toString(elem); } + + public static VolatileCharRef create(char e) { return new VolatileCharRef(e); } + public static VolatileCharRef zero() { return new VolatileCharRef((char)0); } } diff --git a/src/library/scala/runtime/VolatileDoubleRef.java b/src/library/scala/runtime/VolatileDoubleRef.java index d47c9578c6..1932055c6a 100755 --- a/src/library/scala/runtime/VolatileDoubleRef.java +++ b/src/library/scala/runtime/VolatileDoubleRef.java @@ -16,4 +16,7 @@ public class VolatileDoubleRef implements java.io.Serializable { volatile public double elem; public VolatileDoubleRef(double elem) { this.elem = elem; } public String toString() { return java.lang.Double.toString(elem); } + + public static VolatileDoubleRef create(double e) { return new VolatileDoubleRef(e); } + public static VolatileDoubleRef zero() { return new VolatileDoubleRef(0); } } diff --git a/src/library/scala/runtime/VolatileFloatRef.java b/src/library/scala/runtime/VolatileFloatRef.java index 97da95f7cc..3a81be1146 100755 --- a/src/library/scala/runtime/VolatileFloatRef.java +++ b/src/library/scala/runtime/VolatileFloatRef.java @@ -17,4 +17,7 @@ public class VolatileFloatRef implements java.io.Serializable { volatile public float elem; public VolatileFloatRef(float elem) { this.elem = elem; } public String toString() { return java.lang.Float.toString(elem); } + + public static VolatileFloatRef create(float e) { return new VolatileFloatRef(e); } + public static VolatileFloatRef zero() { return new VolatileFloatRef(0); } } diff --git a/src/library/scala/runtime/VolatileIntRef.java b/src/library/scala/runtime/VolatileIntRef.java index e8a68a1a9a..ae015bc8b1 100755 --- a/src/library/scala/runtime/VolatileIntRef.java +++ b/src/library/scala/runtime/VolatileIntRef.java @@ -16,4 +16,7 @@ public class VolatileIntRef implements java.io.Serializable { volatile public int elem; public VolatileIntRef(int elem) { this.elem = elem; } public String toString() { return java.lang.Integer.toString(elem); } + + public static VolatileIntRef create(int e) { return new VolatileIntRef(e); } + public static VolatileIntRef zero() { return new VolatileIntRef(0); } } diff --git a/src/library/scala/runtime/VolatileLongRef.java b/src/library/scala/runtime/VolatileLongRef.java index 80e627cd4b..e596f5aa69 100755 --- a/src/library/scala/runtime/VolatileLongRef.java +++ b/src/library/scala/runtime/VolatileLongRef.java @@ -17,4 +17,7 @@ public class VolatileLongRef implements java.io.Serializable { volatile public long elem; public VolatileLongRef(long elem) { this.elem = elem; } public String toString() { return java.lang.Long.toString(elem); } + + public static VolatileLongRef create(long e) { return new VolatileLongRef(e); } + public static VolatileLongRef zero() { return new VolatileLongRef(0); } } diff --git a/src/library/scala/runtime/VolatileObjectRef.java b/src/library/scala/runtime/VolatileObjectRef.java index 848b0632ea..9f1f3ac0cf 100755 --- a/src/library/scala/runtime/VolatileObjectRef.java +++ b/src/library/scala/runtime/VolatileObjectRef.java @@ -17,4 +17,7 @@ public class VolatileObjectRef<T> implements java.io.Serializable { volatile public T elem; public VolatileObjectRef(T elem) { this.elem = elem; } public String toString() { return String.valueOf(elem); } + + public static <U> VolatileObjectRef create(U e) { return new VolatileObjectRef(e); } + public static VolatileObjectRef zero() { return new VolatileObjectRef(null); } } diff --git a/src/library/scala/runtime/VolatileShortRef.java b/src/library/scala/runtime/VolatileShortRef.java index 4e91d0dc70..0a2825941f 100755 --- a/src/library/scala/runtime/VolatileShortRef.java +++ b/src/library/scala/runtime/VolatileShortRef.java @@ -17,4 +17,7 @@ public class VolatileShortRef implements java.io.Serializable { volatile public short elem; public VolatileShortRef(short elem) { this.elem = elem; } public String toString() { return java.lang.Short.toString(elem); } + + public static VolatileShortRef create(short e) { return new VolatileShortRef(e); } + public static VolatileShortRef zero() { return new VolatileShortRef((short)0); } } diff --git a/src/library/scala/sys/BooleanProp.scala b/src/library/scala/sys/BooleanProp.scala index e3c25bbd11..74b0a9077b 100644 --- a/src/library/scala/sys/BooleanProp.scala +++ b/src/library/scala/sys/BooleanProp.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys import scala.language.implicitConversions diff --git a/src/library/scala/sys/PropImpl.scala b/src/library/scala/sys/PropImpl.scala index b50e0e18a7..3b451ab1d9 100644 --- a/src/library/scala/sys/PropImpl.scala +++ b/src/library/scala/sys/PropImpl.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys import scala.collection.mutable diff --git a/src/library/scala/sys/ShutdownHookThread.scala b/src/library/scala/sys/ShutdownHookThread.scala index a8f4871870..6018ac852b 100644 --- a/src/library/scala/sys/ShutdownHookThread.scala +++ b/src/library/scala/sys/ShutdownHookThread.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys /** A minimal Thread wrapper to enhance shutdown hooks. It knows * how to unregister itself. diff --git a/src/library/scala/sys/SystemProperties.scala b/src/library/scala/sys/SystemProperties.scala index 294be5cd71..39f66f5030 100644 --- a/src/library/scala/sys/SystemProperties.scala +++ b/src/library/scala/sys/SystemProperties.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys import scala.collection.{ mutable, Iterator } import scala.collection.JavaConverters._ diff --git a/src/library/scala/sys/process/BasicIO.scala b/src/library/scala/sys/process/BasicIO.scala index e2c4f13830..58517de402 100644 --- a/src/library/scala/sys/process/BasicIO.scala +++ b/src/library/scala/sys/process/BasicIO.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import processInternal._ diff --git a/src/library/scala/sys/process/Process.scala b/src/library/scala/sys/process/Process.scala index 715b364e08..402183a1f0 100644 --- a/src/library/scala/sys/process/Process.scala +++ b/src/library/scala/sys/process/Process.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import processInternal._ diff --git a/src/library/scala/sys/process/ProcessBuilder.scala b/src/library/scala/sys/process/ProcessBuilder.scala index 5d89e45001..c8e548c76b 100644 --- a/src/library/scala/sys/process/ProcessBuilder.scala +++ b/src/library/scala/sys/process/ProcessBuilder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import processInternal._ diff --git a/src/library/scala/sys/process/ProcessBuilderImpl.scala b/src/library/scala/sys/process/ProcessBuilderImpl.scala index 91e267d5e4..adf6d1e724 100644 --- a/src/library/scala/sys/process/ProcessBuilderImpl.scala +++ b/src/library/scala/sys/process/ProcessBuilderImpl.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import processInternal._ diff --git a/src/library/scala/sys/process/ProcessIO.scala b/src/library/scala/sys/process/ProcessIO.scala index f5b26680d9..eedf667c88 100644 --- a/src/library/scala/sys/process/ProcessIO.scala +++ b/src/library/scala/sys/process/ProcessIO.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import processInternal._ diff --git a/src/library/scala/sys/process/ProcessImpl.scala b/src/library/scala/sys/process/ProcessImpl.scala index c64ba246fc..7a5fc4ef9b 100644 --- a/src/library/scala/sys/process/ProcessImpl.scala +++ b/src/library/scala/sys/process/ProcessImpl.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import processInternal._ diff --git a/src/library/scala/sys/process/ProcessLogger.scala b/src/library/scala/sys/process/ProcessLogger.scala index a4acb065d0..ae347221ef 100644 --- a/src/library/scala/sys/process/ProcessLogger.scala +++ b/src/library/scala/sys/process/ProcessLogger.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.sys +package scala +package sys package process import java.io._ diff --git a/src/library/scala/util/DynamicVariable.scala b/src/library/scala/util/DynamicVariable.scala index 52cba6850d..963fe1c497 100644 --- a/src/library/scala/util/DynamicVariable.scala +++ b/src/library/scala/util/DynamicVariable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util +package scala +package util import java.lang.InheritableThreadLocal diff --git a/src/library/scala/util/Either.scala b/src/library/scala/util/Either.scala index 5cd35ab6d9..1ed3f4becb 100644 --- a/src/library/scala/util/Either.scala +++ b/src/library/scala/util/Either.scala @@ -8,7 +8,8 @@ -package scala.util +package scala +package util import scala.language.implicitConversions diff --git a/src/library/scala/util/MurmurHash.scala b/src/library/scala/util/MurmurHash.scala index b82259c217..7d1c57ef77 100644 --- a/src/library/scala/util/MurmurHash.scala +++ b/src/library/scala/util/MurmurHash.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util +package scala +package util /** An implementation of Austin Appleby's MurmurHash 3.0 algorithm * (32 bit version); reference: http://code.google.com/p/smhasher diff --git a/src/library/scala/util/Properties.scala b/src/library/scala/util/Properties.scala index cc145134c4..d2d473bf98 100644 --- a/src/library/scala/util/Properties.scala +++ b/src/library/scala/util/Properties.scala @@ -7,7 +7,8 @@ \* */ -package scala.util +package scala +package util import java.io.{ IOException, PrintWriter } import java.util.jar.Attributes.{ Name => AttributeName } @@ -72,7 +73,7 @@ private[scala] trait PropertiesTrait { * it is an RC, Beta, etc. or was built from source, or if the version * cannot be read. */ - val releaseVersion = + val releaseVersion = for { v <- scalaPropOrNone("maven.version.number") if !(v endsWith "-SNAPSHOT") @@ -86,7 +87,7 @@ private[scala] trait PropertiesTrait { * @return Some(version) if this is a non-final version, None if this * is a final release or the version cannot be read. */ - val developmentVersion = + val developmentVersion = for { v <- scalaPropOrNone("maven.version.number") if v endsWith "-SNAPSHOT" diff --git a/src/library/scala/util/Random.scala b/src/library/scala/util/Random.scala index b3a8617f15..8d68c5be38 100644 --- a/src/library/scala/util/Random.scala +++ b/src/library/scala/util/Random.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util +package scala +package util import scala.collection.mutable.ArrayBuffer import scala.collection.generic.CanBuildFrom diff --git a/src/library/scala/util/Try.scala b/src/library/scala/util/Try.scala index fbfeb7d4d9..89db57a55e 100644 --- a/src/library/scala/util/Try.scala +++ b/src/library/scala/util/Try.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util +package scala +package util import scala.collection.Seq import scala.util.control.NonFatal diff --git a/src/library/scala/util/control/Breaks.scala b/src/library/scala/util/control/Breaks.scala index 89e1b58d95..5524b10afa 100644 --- a/src/library/scala/util/control/Breaks.scala +++ b/src/library/scala/util/control/Breaks.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.control +package scala +package util.control /** A class that can be instantiated for the break control abstraction. * Example usage: diff --git a/src/library/scala/util/control/ControlThrowable.scala b/src/library/scala/util/control/ControlThrowable.scala index 33c90c5815..7ed3d95cd3 100644 --- a/src/library/scala/util/control/ControlThrowable.scala +++ b/src/library/scala/util/control/ControlThrowable.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.control +package scala +package util.control /** A marker trait indicating that the `Throwable` it is mixed into is * intended for flow control. diff --git a/src/library/scala/util/control/Exception.scala b/src/library/scala/util/control/Exception.scala index b97914c4b1..be6d03a145 100644 --- a/src/library/scala/util/control/Exception.scala +++ b/src/library/scala/util/control/Exception.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util +package scala +package util package control import scala.collection.immutable.List diff --git a/src/library/scala/util/control/NonFatal.scala b/src/library/scala/util/control/NonFatal.scala index 74478f2a49..11fb988e8e 100644 --- a/src/library/scala/util/control/NonFatal.scala +++ b/src/library/scala/util/control/NonFatal.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.control +package scala +package util.control /** * Extractor of non-fatal Throwables. Will not match fatal errors like `VirtualMachineError` diff --git a/src/library/scala/util/control/TailCalls.scala b/src/library/scala/util/control/TailCalls.scala index 955cee7657..ba3044c718 100644 --- a/src/library/scala/util/control/TailCalls.scala +++ b/src/library/scala/util/control/TailCalls.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.control +package scala +package util.control /** Methods exported by this object implement tail calls via trampolining. * Tail calling methods have to return their result using `done` or call the diff --git a/src/library/scala/util/hashing/ByteswapHashing.scala b/src/library/scala/util/hashing/ByteswapHashing.scala index a96945788c..470479725b 100644 --- a/src/library/scala/util/hashing/ByteswapHashing.scala +++ b/src/library/scala/util/hashing/ByteswapHashing.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.hashing +package scala +package util.hashing @@ -16,20 +17,20 @@ package scala.util.hashing /** A fast multiplicative hash by Phil Bagwell. */ final class ByteswapHashing[T] extends Hashing[T] { - + def hash(v: T) = byteswap32(v.##) - + } object ByteswapHashing { - + private class Chained[T](h: Hashing[T]) extends Hashing[T] { def hash(v: T) = byteswap32(h.hash(v)) } - + /** Composes another `Hashing` with the Byteswap hash. */ def chain[T](h: Hashing[T]): Hashing[T] = new Chained(h) - + } diff --git a/src/library/scala/util/hashing/Hashing.scala b/src/library/scala/util/hashing/Hashing.scala index b57f858bed..2b72c1dbe3 100644 --- a/src/library/scala/util/hashing/Hashing.scala +++ b/src/library/scala/util/hashing/Hashing.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.hashing +package scala +package util.hashing import scala.annotation.implicitNotFound diff --git a/src/library/scala/util/hashing/MurmurHash3.scala b/src/library/scala/util/hashing/MurmurHash3.scala index 0aa7e6f1cb..af0b12d8ba 100644 --- a/src/library/scala/util/hashing/MurmurHash3.scala +++ b/src/library/scala/util/hashing/MurmurHash3.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.hashing +package scala +package util.hashing import java.lang.Integer.{ rotateLeft => rotl } diff --git a/src/library/scala/util/hashing/package.scala b/src/library/scala/util/hashing/package.scala index 7d38f151f9..2c8e0154fc 100644 --- a/src/library/scala/util/hashing/package.scala +++ b/src/library/scala/util/hashing/package.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util +package scala +package util @@ -14,7 +15,7 @@ package scala.util package object hashing { - + /** Fast multiplicative hash with a nice distribution. */ def byteswap32(v: Int): Int = { @@ -22,7 +23,7 @@ package object hashing { hc = java.lang.Integer.reverseBytes(hc) hc * 0x9e3775cd } - + /** Fast multiplicative hash with a nice distribution * for 64-bit values. */ @@ -31,5 +32,5 @@ package object hashing { hc = java.lang.Long.reverseBytes(hc) hc * 0x9e3775cd9e3775cdL } - + } diff --git a/src/library/scala/util/logging/ConsoleLogger.scala b/src/library/scala/util/logging/ConsoleLogger.scala index 74f058b4ec..5e3d957534 100644 --- a/src/library/scala/util/logging/ConsoleLogger.scala +++ b/src/library/scala/util/logging/ConsoleLogger.scala @@ -8,7 +8,8 @@ -package scala.util.logging +package scala +package util.logging /** * The trait `ConsoleLogger` is mixed into a concrete class who diff --git a/src/library/scala/util/logging/Logged.scala b/src/library/scala/util/logging/Logged.scala index f2661d3206..1fc12588db 100644 --- a/src/library/scala/util/logging/Logged.scala +++ b/src/library/scala/util/logging/Logged.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.logging +package scala +package util.logging /** Mixing in Logged indicates that a class provides support for logging. * diff --git a/src/library/scala/util/matching/Regex.scala b/src/library/scala/util/matching/Regex.scala index 981d9af02f..8d135ecf02 100644 --- a/src/library/scala/util/matching/Regex.scala +++ b/src/library/scala/util/matching/Regex.scala @@ -28,7 +28,8 @@ * into a [[java.lang.String]]. * */ -package scala.util.matching +package scala +package util.matching import scala.collection.AbstractIterator import java.util.regex.{ Pattern, Matcher } diff --git a/src/library/scala/util/parsing/ast/AbstractSyntax.scala b/src/library/scala/util/parsing/ast/AbstractSyntax.scala deleted file mode 100644 index 30b20d71c6..0000000000 --- a/src/library/scala/util/parsing/ast/AbstractSyntax.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2013, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.util.parsing.ast - -import scala.util.parsing.input.Positional - -/** This component provides the core abstractions for representing an Abstract Syntax Tree - * - * @author Adriaan Moors - */ -@deprecated("This class will be removed", "2.10.0") -trait AbstractSyntax { - /** The base class for elements of the abstract syntax tree. - */ - trait Element extends Positional - - /** The base class for elements in the AST that represent names [[scala.util.parsing.ast.Binders]]. - */ - trait NameElement extends Element { - def name: String - override def equals(that: Any): Boolean = that match { - case n: NameElement => n.name == name - case _ => false - } - } -} diff --git a/src/library/scala/util/parsing/ast/Binders.scala b/src/library/scala/util/parsing/ast/Binders.scala deleted file mode 100644 index a6ad1907c2..0000000000 --- a/src/library/scala/util/parsing/ast/Binders.scala +++ /dev/null @@ -1,347 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2013, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.util.parsing.ast - -import scala.collection.AbstractIterable -import scala.collection.mutable -import scala.language.implicitConversions - -//DISCLAIMER: this code is highly experimental! - - // TODO: avoid clashes when substituting - // TODO: check binders in the same scope are distinct - -/** This trait provides the core ''Scrap-Your-Boilerplate'' abstractions as - * well as implementations for common datatypes. - * - * (Based on Ralf Lämmel's [[http://homepages.cwi.nl/~ralf/syb3/ SYB papers]].) - * - * @author Adriaan Moors - */ -@deprecated("This class will be removed", "2.10.0") -trait Mappable { - trait Mapper { def apply[T <% Mappable[T]](x: T): T } /* TODO: having type `Forall T. T => T` is too strict: - sometimes we want to allow `Forall T >: precision. T => T` for some type `precision`, so that, - beneath a certain threshold, we have some leeway. - concretely: to use gmap for substitution, we simply require that ast nodes are mapped to ast nodes, - we can't require that the type is preserved precisely: a Name may map to e.g., a MethodCall - */ - - trait Mappable[T] { - // one-layer traversal - def gmap(f: Mapper): T - // everywhere f x = f (gmapT (everywhere f) x) - def everywhere(f: Mapper)(implicit c: T => Mappable[T]): T = - f(gmap(new Mapper { def apply[T <% Mappable[T]](x: T): T = x.everywhere(f)})) - } - - implicit def StringIsMappable(s: String): Mappable[String] = - new Mappable[String] { - def gmap(f: Mapper): String = f(s) - } - - implicit def ListIsMappable[t <% Mappable[t]](xs: List[t]): Mappable[List[t]] = - new Mappable[List[t]] { - def gmap(f: Mapper): List[t] = (for (x <- xs) yield f(x)).toList - } - - implicit def OptionIsMappable[t <% Mappable[t]](xs: Option[t]): Mappable[Option[t]] = - new Mappable[Option[t]] { - def gmap(f: Mapper): Option[t] = (for (x <- xs) yield f(x)) - } -} - -/** This component provides functionality for enforcing variable binding - * during parse-time. - * - * When parsing simple languages, like Featherweight Scala, these parser - * combinators will fully enforce the binding discipline. When names are - * allowed to be left unqualified, these mechanisms would have to be - * complemented by an extra phase that resolves names that couldn't be - * resolved using the naive binding rules. (Maybe some machinery to - * model `implicit` binders (e.g., `this` and imported qualifiers) - * and selection on a binder will suffice?) - * - * @author Adriaan Moors - */ -trait Binders extends AbstractSyntax with Mappable { - /** A `Scope` keeps track of one or more syntactic elements that represent bound names. - * The elements it contains share the same scope and must all be distinct, as determined by `==`. - * - * A `NameElement` `n` in the AST that is conceptually bound by a `Scope` `s`, is replaced by a - * `BoundElement(n, s)`. (For example, in `val x:Int=x+1`, the first `x` is modelled by a - * Scope `s` that contains `x` and the second `x` is represented by a `BoundElement(x, s)`) - * The term (`x+1`) in scope of the Scope becomes an `UnderBinder(s, x+1)`. - * - * A `NameElement` `n` is bound by a `Scope` `s` if it is wrapped as a `BoundElement(n, s)`, and - * `s` has a binder element that is semantically equal (`equals` or `==`) to `n`. - * - * A `Scope` is represented textually by its list of binder elements, followed by the scope's `id`. - * For example: `[x, y]!1` represents the scope with `id` `1` and binder elements `x` and `y`. - * (`id` is solely used for this textual representation.) - */ - class Scope[binderType <: NameElement] extends AbstractIterable[binderType] with Iterable[binderType] { - private val substitution: mutable.Map[binderType, Element] = - new mutable.LinkedHashMap[binderType, Element] // a LinkedHashMap is ordered by insertion order -- important! - - /** Returns a unique number identifying this Scope (only used for representation purposes). */ - val id: Int = _Binder.genId - - /** Returns the binders in this scope. - * For a typical let-binding, this is just the variable name. For an argument list to a method body, - * there is one binder per formal argument. - */ - def iterator = substitution.keysIterator - - /** Return the `i`th binder in this scope. */ - def apply(i: Int): binderType = this.iterator.toList(i) - - /** Returns true if this container has a binder equal (as determined by `==`) to `b`. */ - def binds(b: binderType): Boolean = substitution.contains(b) - - def indexFor(b: binderType): Option[Int] = { - val iter = this.iterator.zipWithIndex - for ((that, count) <- iter) { - if (that.name == b.name) // TODO: why do name equals and structural equals differ? - return Some(count + 1) - else - Console.println(that+"!="+b) - } - - None - } - - /** Adds a new binder, for example the variable name in a local variable declaration. - * - * @param b a new binder that is distinct from the existing binders in this scope, - * and shares their conceptual scope. `canAddBinder(b)` must hold. - * @return `binds(b)` and `getElementFor(b) eq b` will hold. - */ - def addBinder(b: binderType) { substitution += Pair(b, b) } - - // TODO: strengthen this condition so that no binders may be added after this scope has been - // linked to its `UnderBinder` (i.e., while parsing, BoundElements may be added to the Scope - // associated to the UnderBinder, but after that, no changes are allowed, except for substitution)? - /** `canAddElement` indicates whether `b` may be added to this scope. - * - * - * @return true if `b` had not been added yet - */ - def canAddBinder(b: binderType): Boolean = !binds(b) - - /** ''Replaces'' the bound occurrences of a contained binder by their new value. - * The bound occurrences of `b` are not actually replaced; the scope keeps track - * of a substitution that maps every binder to its current value. Since a `BoundElement` is - * a proxy for the element it is bound to by its binder, `substitute` may thus be thought of - * as replacing all the bound occurrences of the given binder `b` by their new value `value`. - * - * @param b the binder whose bound occurrences should be given a new value. `binds(b)` must hold. - * @param value the new value for the bound occurrences of `b` - * @return `getElementFor(b) eq value` will hold. - */ - def substitute(b: binderType, value: Element): Unit = substitution(b) = value - - /** Returns the current value for the bound occurrences of `b`. - * - * @param b the contained binder whose current value should be returned `binds(b)` must hold. - */ - def getElementFor(b: binderType): Element = substitution(b) - - override def toString: String = this.iterator.toList.mkString("[",", ","]")+"!"+id // TODO show substitution? - - /** Returns a list of strings that represent the binder elements, each tagged with this scope's id. */ - def bindersToString: List[String] = (for(b <- this.iterator) yield b+"!"+id).toList - - /** Return a new inheriting scope that won't check whether binding is respected until the scope is left (so as to support forward references). */ - def allowForwardRef: Scope[binderType] = this // TODO - - /** Return a nested scope -- binders entered into it won't be visible in this scope, but if this scope allows forward references, - * the binding in the returned scope also does, and thus the check that all variables are bound is deferred until this scope is left. - */ - def nested: Scope[binderType] = this // TODO - - def onEnter() {} - def onLeft() {} - } - - - trait BindingSensitive { - // would like to specify this as one method: - // def alpha_==[t <: NameElement](other: BoundElement[t]): Boolean - // def alpha_==[bt <: binderType, st <: elementT](other: UnderBinder[bt, st]): Boolean - } - - /** A `BoundElement` is bound in a certain scope `scope`, which keeps track of the actual element that - * `el` stands for. - * - * A `BoundElement` is represented textually by its bound element, followed by its scope's `id`. - * For example: `x@1` represents the variable `x` that is bound in the scope with `id` `1`. - * - * @note `scope.binds(el)` holds before and after. - */ - case class BoundElement[boundElement <: NameElement](el: boundElement, scope: Scope[boundElement]) extends NameElement with Proxy with BindingSensitive { - /** Returns the element this `BoundElement` stands for. - * The `Proxy` trait ensures `equals`, `hashCode` and `toString` are forwarded to - * the result of this method. - */ - def self: Element = scope.getElementFor(el) - - def name = self.asInstanceOf[NameElement].name // TODO: this is only safe when substituted to a NameElement, which certainly isn't required -- I want dynamic inheritance! :) - - // decorate element's representation with the id of the scope it's bound in - override def toString: String = super.toString+"@"+scope.id - - def alpha_==[t <: NameElement](other: BoundElement[t]): Boolean = scope.indexFor(el) == other.scope.indexFor(other.el) - } - - /** A variable that escaped its scope (i.e., a free variable) -- we don't deal very well with these yet. */ - class UnboundElement[N <: NameElement](private val el: N) extends NameElement { - def name = el.name+"@??" - } - - // this is useless, as Element is a supertype of BoundElement --> the coercion will never be inferred - // if we knew a more specific type for the element that the bound element represents, this could make sense - // implicit def BoundElementProxy[t <: NameElement](e: BoundElement[t]): Element = e.self - - /** Represents an element with variables that are bound in a certain scope. */ - class UnderBinder[binderType <: NameElement, elementT <% Mappable[elementT]](val scope: Scope[binderType], private[Binders] val element: elementT) extends Element with BindingSensitive { - override def toString: String = "(" + scope.toString + ") in { "+element.toString+" }" - - /** Alpha-equivalence -- TODO - * Returns true if the `element` of the `other` `UnderBinder` is equal to this `element` up to alpha-conversion. - * - * That is, regular equality is used for all elements but `BoundElement`s: such an element is - * equal to a `BoundElement` in `other` if their binders are equal. Binders are equal if they - * are at the same index in their respective scope. - * - * Example: - * {{{ - * UnderBinder([x, y]!1, x@1) alpha_== UnderBinder([a, b]!2, a@2) - * ! (UnderBinder([x, y]!1, y@1) alpha_== UnderBinder([a, b]!2, a@2)) - * }}} - */ - /*def alpha_==[bt <: binderType, st <: elementT](other: UnderBinder[bt, st]): Boolean = { - var result = true - - // TODO: generic zip or gmap2 - element.gmap2(other.element, new Mapper2 { - def apply[s <% Mappable[s], t <% Mappable[t]](x :{s, t}): {s, t} = x match { - case {be1: BoundElement[_], be2: BoundElement[_]} => result == result && be1.alpha_==(be2) // monadic gmap (cheating using state directly) - case {ub1: UnderBinder[_, _], ub2: UnderBinder[_, _]} => result == result && be1.alpha_==(be2) - case {a, b} => result == result && a.equals(b) - }; x - }) - }*/ - - def cloneElementWithSubst(subst: Map[NameElement, NameElement]) = element.gmap(new Mapper { def apply[t <% Mappable[t]](x :t): t = x match{ - case substable: NameElement if subst.contains(substable) => subst.get(substable).asInstanceOf[t] // TODO: wrong... substitution is not (necessarily) the identity function - //Console.println("substed: "+substable+"-> "+subst.get(substable)+")"); - case x => x // Console.println("subst: "+x+"(keys: "+subst.keys+")");x - }}) - - // TODO - def cloneElementNoBoundElements = element.gmap(new Mapper { def apply[t <% Mappable[t]](x :t): t = x match{ - case BoundElement(el, _) => new UnboundElement(el).asInstanceOf[t] // TODO: precision stuff - case x => x - }}) - - def extract: elementT = cloneElementNoBoundElements - def extract(subst: Map[NameElement, NameElement]): elementT = cloneElementWithSubst(subst) - - /** Get a string representation of element, normally we don't allow direct access to element, but just getting a string representation is ok. */ - def elementToString: String = element.toString - } - - //SYB type class instances - implicit def UnderBinderIsMappable[bt <: NameElement <% Mappable[bt], st <% Mappable[st]](ub: UnderBinder[bt, st]): Mappable[UnderBinder[bt, st]] = - new Mappable[UnderBinder[bt, st]] { - def gmap(f: Mapper): UnderBinder[bt, st] = UnderBinder(f(ub.scope), f(ub.element)) - } - - implicit def ScopeIsMappable[bt <: NameElement <% Mappable[bt]](scope: Scope[bt]): Mappable[Scope[bt]] = - new Mappable[Scope[bt]] { - def gmap(f: Mapper): Scope[bt] = { val newScope = new Scope[bt]() - for(b <- scope) newScope.addBinder(f(b)) - newScope - } - } - - implicit def NameElementIsMappable(self: NameElement): Mappable[NameElement] = new Mappable[NameElement] { - def gmap(f: Mapper): NameElement = self match { - case BoundElement(el, scope) => BoundElement(f(el), f(scope)) - case _ => UserNameElementIsMappable(self).gmap(f) - } - } - - def UserNameElementIsMappable[t <: NameElement](self: t): Mappable[t] - - object UnderBinder { - def apply[binderType <: NameElement, elementT <% Mappable[elementT]](scope: Scope[binderType], element: elementT) = new UnderBinder(scope, element) - def unit[bt <: NameElement, elementT <% Mappable[elementT]](x: elementT) = UnderBinder(new Scope[bt](), x) - } - - /** If a list of `UnderBinder`s all have the same scope, they can be turned in to an `UnderBinder` - * containing a list of the elements in the original `UnderBinder`. - * - * The name `sequence` comes from the fact that this method's type is equal to the type of monadic sequence. - * - * @note `!orig.isEmpty` implies `orig.forall(ub => ub.scope eq orig(0).scope)` - * - */ - def sequence[bt <: NameElement, st <% Mappable[st]](orig: List[UnderBinder[bt, st]]): UnderBinder[bt, List[st]] = - if(orig.isEmpty) UnderBinder.unit(Nil) - else UnderBinder(orig(0).scope, orig.map(_.element)) - - // couldn't come up with a better name... - def unsequence[bt <: NameElement, st <% Mappable[st]](orig: UnderBinder[bt, List[st]]): List[UnderBinder[bt, st]] = - orig.element.map(sc => UnderBinder(orig.scope, sc)) - - //TODO: more documentation - /** An environment that maps a `NameElement` to the scope in which it is bound. - * This can be used to model scoping during parsing. - * - * @note This class uses similar techniques as described by ''Burak Emir'' in - * [[http://library.epfl.ch/theses/?nr=3899 Object-oriented pattern matching]], - * but uses `==` instead of `eq`, thus types can't be unified in general. - */ - abstract class BinderEnv { - def apply[A <: NameElement](v: A): Option[Scope[A]] - def extend[a <: NameElement](v : a, x : Scope[a]) = new BinderEnv { - def apply[b <: NameElement](w : b): Option[Scope[b]] = - if(w == v) Some(x.asInstanceOf[Scope[b]]) - else BinderEnv.this.apply(w) - } - } - - object EmptyBinderEnv extends BinderEnv { - def apply[A <: NameElement](v: A): Option[Scope[A]] = None - } - - // TODO: move this to some utility object higher in the scala hierarchy? - /** Returns a given result, but executes the supplied closure before returning. - * (The effect of this closure does not influence the returned value.) - */ - trait ReturnAndDo[T]{ - /** - * @param block code to be executed, purely for its side-effects - */ - def andDo(block: => Unit): T - } - - def return_[T](result: T): ReturnAndDo[T] = - new ReturnAndDo[T] { - val r = result - def andDo(block: => Unit): T = {block; r} - } - - private object _Binder { - private var currentId = 0 - private[Binders] def genId = return_(currentId) andDo {currentId=currentId+1} - } -} diff --git a/src/library/scala/util/parsing/combinator/ImplicitConversions.scala b/src/library/scala/util/parsing/combinator/ImplicitConversions.scala index ad06749c0d..0683ea927d 100644 --- a/src/library/scala/util/parsing/combinator/ImplicitConversions.scala +++ b/src/library/scala/util/parsing/combinator/ImplicitConversions.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing.combinator +package scala +package util.parsing.combinator import scala.language.implicitConversions diff --git a/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala b/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala index 89832d3fb2..01288a182e 100644 --- a/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala +++ b/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing.combinator +package scala +package util.parsing.combinator import scala.annotation.migration diff --git a/src/library/scala/util/parsing/combinator/PackratParsers.scala b/src/library/scala/util/parsing/combinator/PackratParsers.scala index cd0907e40f..a11dd18e62 100644 --- a/src/library/scala/util/parsing/combinator/PackratParsers.scala +++ b/src/library/scala/util/parsing/combinator/PackratParsers.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.combinator +package scala +package util.parsing.combinator import scala.util.parsing.input.{ Reader, Position } import scala.collection.mutable diff --git a/src/library/scala/util/parsing/combinator/Parsers.scala b/src/library/scala/util/parsing/combinator/Parsers.scala index 542a781b60..8fc2295d9c 100644 --- a/src/library/scala/util/parsing/combinator/Parsers.scala +++ b/src/library/scala/util/parsing/combinator/Parsers.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.combinator +package scala +package util.parsing.combinator import scala.util.parsing.input._ import scala.collection.mutable.ListBuffer diff --git a/src/library/scala/util/parsing/combinator/RegexParsers.scala b/src/library/scala/util/parsing/combinator/RegexParsers.scala index d17d0cac8d..8ebbc573ad 100644 --- a/src/library/scala/util/parsing/combinator/RegexParsers.scala +++ b/src/library/scala/util/parsing/combinator/RegexParsers.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing.combinator +package scala +package util.parsing.combinator import java.util.regex.Pattern import scala.util.matching.Regex diff --git a/src/library/scala/util/parsing/combinator/lexical/Lexical.scala b/src/library/scala/util/parsing/combinator/lexical/Lexical.scala index c25c97278f..d8029d068f 100644 --- a/src/library/scala/util/parsing/combinator/lexical/Lexical.scala +++ b/src/library/scala/util/parsing/combinator/lexical/Lexical.scala @@ -8,7 +8,8 @@ -package scala.util.parsing +package scala +package util.parsing package combinator package lexical diff --git a/src/library/scala/util/parsing/combinator/lexical/Scanners.scala b/src/library/scala/util/parsing/combinator/lexical/Scanners.scala index f6a8daabd9..2e12915bb8 100644 --- a/src/library/scala/util/parsing/combinator/lexical/Scanners.scala +++ b/src/library/scala/util/parsing/combinator/lexical/Scanners.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing +package scala +package util.parsing package combinator package lexical diff --git a/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala b/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala index 2fbc1ec136..32d7502cda 100644 --- a/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala +++ b/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing +package scala +package util.parsing package combinator package lexical diff --git a/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala b/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala index d3ae0ea54a..5b9d14c9a7 100644 --- a/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala +++ b/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing +package scala +package util.parsing package combinator package syntactical diff --git a/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala b/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala index 7283b01da4..adcf85da7a 100644 --- a/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala +++ b/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala @@ -8,7 +8,8 @@ -package scala.util.parsing +package scala +package util.parsing package combinator package syntactical diff --git a/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala b/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala index 1c4b25b999..b06babcd7e 100644 --- a/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala +++ b/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing +package scala +package util.parsing package combinator package syntactical diff --git a/src/library/scala/util/parsing/combinator/testing/RegexTest.scala b/src/library/scala/util/parsing/combinator/testing/RegexTest.scala index 80e9b0df39..727b6caf8d 100644 --- a/src/library/scala/util/parsing/combinator/testing/RegexTest.scala +++ b/src/library/scala/util/parsing/combinator/testing/RegexTest.scala @@ -1,5 +1,6 @@ -package scala.util.parsing.combinator.testing +package scala +package util.parsing.combinator.testing import scala.util.parsing.combinator._ import scala.util.parsing.input._ diff --git a/src/library/scala/util/parsing/combinator/testing/Tester.scala b/src/library/scala/util/parsing/combinator/testing/Tester.scala index 3cdab2a885..86c5d68ebe 100644 --- a/src/library/scala/util/parsing/combinator/testing/Tester.scala +++ b/src/library/scala/util/parsing/combinator/testing/Tester.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.combinator.testing +package scala +package util.parsing.combinator.testing import scala.util.parsing.combinator.lexical.Lexical import scala.util.parsing.combinator.syntactical.TokenParsers diff --git a/src/library/scala/util/parsing/combinator/token/StdTokens.scala b/src/library/scala/util/parsing/combinator/token/StdTokens.scala index 605f53bf1d..a102d1541e 100644 --- a/src/library/scala/util/parsing/combinator/token/StdTokens.scala +++ b/src/library/scala/util/parsing/combinator/token/StdTokens.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing +package scala +package util.parsing package combinator package token diff --git a/src/library/scala/util/parsing/combinator/token/Tokens.scala b/src/library/scala/util/parsing/combinator/token/Tokens.scala index ff92802d77..5c3f1f95b5 100644 --- a/src/library/scala/util/parsing/combinator/token/Tokens.scala +++ b/src/library/scala/util/parsing/combinator/token/Tokens.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing +package scala +package util.parsing package combinator package token diff --git a/src/library/scala/util/parsing/input/CharArrayReader.scala b/src/library/scala/util/parsing/input/CharArrayReader.scala index 3ba69b229b..22530cb9aa 100644 --- a/src/library/scala/util/parsing/input/CharArrayReader.scala +++ b/src/library/scala/util/parsing/input/CharArrayReader.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing.input +package scala +package util.parsing.input /** An object encapsulating basic character constants. * diff --git a/src/library/scala/util/parsing/input/CharSequenceReader.scala b/src/library/scala/util/parsing/input/CharSequenceReader.scala index 02aa2ab7b8..8e7751cc82 100644 --- a/src/library/scala/util/parsing/input/CharSequenceReader.scala +++ b/src/library/scala/util/parsing/input/CharSequenceReader.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing.input +package scala +package util.parsing.input /** An object encapsulating basic character constants. * diff --git a/src/library/scala/util/parsing/input/NoPosition.scala b/src/library/scala/util/parsing/input/NoPosition.scala index 40584b3293..4a32264b79 100644 --- a/src/library/scala/util/parsing/input/NoPosition.scala +++ b/src/library/scala/util/parsing/input/NoPosition.scala @@ -8,7 +8,8 @@ -package scala.util.parsing.input +package scala +package util.parsing.input /** Undefined position. * diff --git a/src/library/scala/util/parsing/input/OffsetPosition.scala b/src/library/scala/util/parsing/input/OffsetPosition.scala index 6b00af4ce2..23f79c74d1 100644 --- a/src/library/scala/util/parsing/input/OffsetPosition.scala +++ b/src/library/scala/util/parsing/input/OffsetPosition.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.input +package scala +package util.parsing.input import scala.collection.mutable.ArrayBuffer diff --git a/src/library/scala/util/parsing/input/PagedSeqReader.scala b/src/library/scala/util/parsing/input/PagedSeqReader.scala index 9140bf2a4f..468f1f9a5f 100644 --- a/src/library/scala/util/parsing/input/PagedSeqReader.scala +++ b/src/library/scala/util/parsing/input/PagedSeqReader.scala @@ -7,7 +7,8 @@ \* */ -package scala.util.parsing.input +package scala +package util.parsing.input import scala.collection.immutable.PagedSeq diff --git a/src/library/scala/util/parsing/input/Position.scala b/src/library/scala/util/parsing/input/Position.scala index 5e0cbbff5e..b7995a6471 100644 --- a/src/library/scala/util/parsing/input/Position.scala +++ b/src/library/scala/util/parsing/input/Position.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.input +package scala +package util.parsing.input /** `Position` is the base trait for objects describing a position in a `document`. * diff --git a/src/library/scala/util/parsing/input/Positional.scala b/src/library/scala/util/parsing/input/Positional.scala index 87cb16eac5..cfde67cadd 100644 --- a/src/library/scala/util/parsing/input/Positional.scala +++ b/src/library/scala/util/parsing/input/Positional.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.input +package scala +package util.parsing.input /** A trait for objects that have a source position. * diff --git a/src/library/scala/util/parsing/input/Reader.scala b/src/library/scala/util/parsing/input/Reader.scala index bded57bee1..9dbf08a7ca 100644 --- a/src/library/scala/util/parsing/input/Reader.scala +++ b/src/library/scala/util/parsing/input/Reader.scala @@ -8,7 +8,8 @@ -package scala.util.parsing.input +package scala +package util.parsing.input /** An interface for streams of values that have positions. diff --git a/src/library/scala/util/parsing/input/StreamReader.scala b/src/library/scala/util/parsing/input/StreamReader.scala index ba7ab65845..30eb097fd7 100644 --- a/src/library/scala/util/parsing/input/StreamReader.scala +++ b/src/library/scala/util/parsing/input/StreamReader.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.input +package scala +package util.parsing.input import java.io.BufferedReader import scala.collection.immutable.PagedSeq @@ -22,7 +23,7 @@ object StreamReader { * * @param in the `java.io.Reader` that provides the underlying * stream of characters for this Reader. - */ + */ def apply(in: java.io.Reader): StreamReader = { new StreamReader(PagedSeq.fromReader(in), 0, 1) } diff --git a/src/library/scala/util/parsing/json/JSON.scala b/src/library/scala/util/parsing/json/JSON.scala index 8f951d519a..6eaa47473f 100644 --- a/src/library/scala/util/parsing/json/JSON.scala +++ b/src/library/scala/util/parsing/json/JSON.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.util.parsing.json +package scala +package util.parsing.json /** * This object provides a simple interface to the JSON parser class. diff --git a/src/library/scala/util/parsing/json/Lexer.scala b/src/library/scala/util/parsing/json/Lexer.scala index 762c1352a7..63df9c28eb 100644 --- a/src/library/scala/util/parsing/json/Lexer.scala +++ b/src/library/scala/util/parsing/json/Lexer.scala @@ -8,7 +8,8 @@ -package scala.util.parsing.json +package scala +package util.parsing.json import scala.util.parsing.combinator._ import scala.util.parsing.combinator.lexical._ diff --git a/src/library/scala/util/parsing/json/Parser.scala b/src/library/scala/util/parsing/json/Parser.scala index bf1162000b..c61e3df181 100644 --- a/src/library/scala/util/parsing/json/Parser.scala +++ b/src/library/scala/util/parsing/json/Parser.scala @@ -8,7 +8,8 @@ -package scala.util.parsing.json +package scala +package util.parsing.json import scala.util.parsing.combinator._ import scala.util.parsing.combinator.syntactical._ diff --git a/src/library/scala/xml/Atom.scala b/src/library/scala/xml/Atom.scala index cba0b96875..33e58ba7e7 100644 --- a/src/library/scala/xml/Atom.scala +++ b/src/library/scala/xml/Atom.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** The class `Atom` provides an XML node for text (`PCDATA`). * It is used in both non-bound and bound XML representations. diff --git a/src/library/scala/xml/Attribute.scala b/src/library/scala/xml/Attribute.scala index 234281163d..e4b2b69fc6 100644 --- a/src/library/scala/xml/Attribute.scala +++ b/src/library/scala/xml/Attribute.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** This singleton object contains the `apply` and `unapply` methods for * convenient construction and deconstruction. diff --git a/src/library/scala/xml/Comment.scala b/src/library/scala/xml/Comment.scala index ff4280d691..b8dccdcb16 100644 --- a/src/library/scala/xml/Comment.scala +++ b/src/library/scala/xml/Comment.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** The class `Comment` implements an XML node for comments. * diff --git a/src/library/scala/xml/Document.scala b/src/library/scala/xml/Document.scala index a064c4d8e8..9a725014fc 100644 --- a/src/library/scala/xml/Document.scala +++ b/src/library/scala/xml/Document.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** A document information item (according to InfoSet spec). The comments * are copied from the Infoset spec, only augmented with some information diff --git a/src/library/scala/xml/Elem.scala b/src/library/scala/xml/Elem.scala index fc32e45a5e..4200b7046a 100755 --- a/src/library/scala/xml/Elem.scala +++ b/src/library/scala/xml/Elem.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** This singleton object contains the `apply` and `unapplySeq` methods for * convenient construction and deconstruction. It is possible to deconstruct diff --git a/src/library/scala/xml/EntityRef.scala b/src/library/scala/xml/EntityRef.scala index a7b9835a7e..7a58831075 100644 --- a/src/library/scala/xml/EntityRef.scala +++ b/src/library/scala/xml/EntityRef.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** The class `EntityRef` implements an XML node for entity references. * diff --git a/src/library/scala/xml/Equality.scala b/src/library/scala/xml/Equality.scala index 20f2405967..021d185812 100644 --- a/src/library/scala/xml/Equality.scala +++ b/src/library/scala/xml/Equality.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** In an attempt to contain the damage being inflicted on consistency by the * ad hoc `equals` methods spread around `xml`, the logic is centralized and diff --git a/src/library/scala/xml/Group.scala b/src/library/scala/xml/Group.scala index 2ee3941aa1..e3af615008 100644 --- a/src/library/scala/xml/Group.scala +++ b/src/library/scala/xml/Group.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** A hack to group XML nodes in one node for output. * diff --git a/src/library/scala/xml/MalformedAttributeException.scala b/src/library/scala/xml/MalformedAttributeException.scala index 3431cb6765..d499ad3e10 100644 --- a/src/library/scala/xml/MalformedAttributeException.scala +++ b/src/library/scala/xml/MalformedAttributeException.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml case class MalformedAttributeException(msg: String) extends RuntimeException(msg) diff --git a/src/library/scala/xml/MetaData.scala b/src/library/scala/xml/MetaData.scala index 3bf3ebb1c0..8b5ea187cb 100644 --- a/src/library/scala/xml/MetaData.scala +++ b/src/library/scala/xml/MetaData.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import Utility.sbToString import scala.annotation.tailrec diff --git a/src/library/scala/xml/NamespaceBinding.scala b/src/library/scala/xml/NamespaceBinding.scala index 32c378f3ef..b320466976 100644 --- a/src/library/scala/xml/NamespaceBinding.scala +++ b/src/library/scala/xml/NamespaceBinding.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import Utility.sbToString diff --git a/src/library/scala/xml/Node.scala b/src/library/scala/xml/Node.scala index 7b1a97e8f2..e121284252 100755 --- a/src/library/scala/xml/Node.scala +++ b/src/library/scala/xml/Node.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** This singleton object contains the `unapplySeq` method for * convenient deconstruction. diff --git a/src/library/scala/xml/NodeBuffer.scala b/src/library/scala/xml/NodeBuffer.scala index 2db4338fb2..ae7c7b2bf8 100644 --- a/src/library/scala/xml/NodeBuffer.scala +++ b/src/library/scala/xml/NodeBuffer.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** * This class acts as a Buffer for nodes. If it is used as a sequence of diff --git a/src/library/scala/xml/NodeSeq.scala b/src/library/scala/xml/NodeSeq.scala index d2efc947b1..b8022472fb 100644 --- a/src/library/scala/xml/NodeSeq.scala +++ b/src/library/scala/xml/NodeSeq.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import scala.collection.{ mutable, immutable, generic, SeqLike, AbstractSeq } import mutable.{ Builder, ListBuffer } diff --git a/src/library/scala/xml/Null.scala b/src/library/scala/xml/Null.scala index b39ef5dc67..f763c023c4 100644 --- a/src/library/scala/xml/Null.scala +++ b/src/library/scala/xml/Null.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import Utility.isNameStart import scala.collection.Iterator diff --git a/src/library/scala/xml/PCData.scala b/src/library/scala/xml/PCData.scala index 64818a9c00..31eea2b6d7 100644 --- a/src/library/scala/xml/PCData.scala +++ b/src/library/scala/xml/PCData.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** This class (which is not used by all XML parsers, but always used by the * XHTML one) represents parseable character data, which appeared as CDATA diff --git a/src/library/scala/xml/PrefixedAttribute.scala b/src/library/scala/xml/PrefixedAttribute.scala index 429cd682d6..4ab79c8677 100644 --- a/src/library/scala/xml/PrefixedAttribute.scala +++ b/src/library/scala/xml/PrefixedAttribute.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml /** prefixed attributes always have a non-null namespace. * diff --git a/src/library/scala/xml/PrettyPrinter.scala b/src/library/scala/xml/PrettyPrinter.scala index 720fe79b1d..9e01905357 100755 --- a/src/library/scala/xml/PrettyPrinter.scala +++ b/src/library/scala/xml/PrettyPrinter.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import Utility.sbToString diff --git a/src/library/scala/xml/ProcInstr.scala b/src/library/scala/xml/ProcInstr.scala index 64a9dd5ca3..189c1c6878 100644 --- a/src/library/scala/xml/ProcInstr.scala +++ b/src/library/scala/xml/ProcInstr.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml /** an XML node for processing instructions (PI) * diff --git a/src/library/scala/xml/QNode.scala b/src/library/scala/xml/QNode.scala index d4d3872181..f9e3f1854b 100644 --- a/src/library/scala/xml/QNode.scala +++ b/src/library/scala/xml/QNode.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** This object provides an extractor method to match a qualified node with * its namespace URI diff --git a/src/library/scala/xml/SpecialNode.scala b/src/library/scala/xml/SpecialNode.scala index 4c1b81c7ff..5fef8ef66c 100644 --- a/src/library/scala/xml/SpecialNode.scala +++ b/src/library/scala/xml/SpecialNode.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** `SpecialNode` is a special XML node which represents either text * `(PCDATA)`, a comment, a `PI`, or an entity ref. diff --git a/src/library/scala/xml/Text.scala b/src/library/scala/xml/Text.scala index 782c80f100..debea0c025 100644 --- a/src/library/scala/xml/Text.scala +++ b/src/library/scala/xml/Text.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** The class `Text` implements an XML node for text (PCDATA). * It is used in both non-bound and bound XML representations. diff --git a/src/library/scala/xml/TextBuffer.scala b/src/library/scala/xml/TextBuffer.scala index 0b96379d85..514b1701af 100644 --- a/src/library/scala/xml/TextBuffer.scala +++ b/src/library/scala/xml/TextBuffer.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml import Utility.isSpace diff --git a/src/library/scala/xml/TopScope.scala b/src/library/scala/xml/TopScope.scala index 1ed1d50e10..474fbbbdb5 100644 --- a/src/library/scala/xml/TopScope.scala +++ b/src/library/scala/xml/TopScope.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml /** top level namespace scope. only contains the predefined binding * for the "xml" prefix which is bound to diff --git a/src/library/scala/xml/TypeSymbol.scala b/src/library/scala/xml/TypeSymbol.scala index f02c0263c0..fb371ee340 100644 --- a/src/library/scala/xml/TypeSymbol.scala +++ b/src/library/scala/xml/TypeSymbol.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml abstract class TypeSymbol diff --git a/src/library/scala/xml/Unparsed.scala b/src/library/scala/xml/Unparsed.scala index ef80823611..bc190eb724 100644 --- a/src/library/scala/xml/Unparsed.scala +++ b/src/library/scala/xml/Unparsed.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml /** An XML node for unparsed content. It will be output verbatim, all bets * are off regarding wellformedness etc. diff --git a/src/library/scala/xml/UnprefixedAttribute.scala b/src/library/scala/xml/UnprefixedAttribute.scala index 2985591c95..6fa827da5f 100644 --- a/src/library/scala/xml/UnprefixedAttribute.scala +++ b/src/library/scala/xml/UnprefixedAttribute.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml /** Unprefixed attributes have the null namespace, and no prefix field * diff --git a/src/library/scala/xml/Utility.scala b/src/library/scala/xml/Utility.scala index fff27c6e30..9134476401 100755 --- a/src/library/scala/xml/Utility.scala +++ b/src/library/scala/xml/Utility.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import scala.collection.mutable import parsing.XhtmlEntities diff --git a/src/library/scala/xml/XML.scala b/src/library/scala/xml/XML.scala index ec5e5e9e1c..020264e509 100755 --- a/src/library/scala/xml/XML.scala +++ b/src/library/scala/xml/XML.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml import parsing.NoBindingFactoryAdapter import factory.XMLLoader diff --git a/src/library/scala/xml/Xhtml.scala b/src/library/scala/xml/Xhtml.scala index 6730548b73..6a12c1a89a 100644 --- a/src/library/scala/xml/Xhtml.scala +++ b/src/library/scala/xml/Xhtml.scala @@ -1,5 +1,6 @@ -package scala.xml +package scala +package xml import parsing.XhtmlEntities import Utility.{ sbToString, isAtomAndNotText } diff --git a/src/library/scala/xml/dtd/ContentModel.scala b/src/library/scala/xml/dtd/ContentModel.scala index debdf37975..4007985dce 100644 --- a/src/library/scala/xml/dtd/ContentModel.scala +++ b/src/library/scala/xml/dtd/ContentModel.scala @@ -6,9 +6,8 @@ ** |/ ** \* */ - - -package scala.xml +package scala +package xml package dtd import scala.xml.dtd.impl._ diff --git a/src/library/scala/xml/dtd/ContentModelParser.scala b/src/library/scala/xml/dtd/ContentModelParser.scala index ca84bcad70..71b391c422 100644 --- a/src/library/scala/xml/dtd/ContentModelParser.scala +++ b/src/library/scala/xml/dtd/ContentModelParser.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package dtd /** Parser for regexps (content models in DTD element declarations) */ diff --git a/src/library/scala/xml/dtd/DTD.scala b/src/library/scala/xml/dtd/DTD.scala index 1f8af3b59e..16a824fe2c 100644 --- a/src/library/scala/xml/dtd/DTD.scala +++ b/src/library/scala/xml/dtd/DTD.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package dtd import scala.collection.mutable diff --git a/src/library/scala/xml/dtd/Decl.scala b/src/library/scala/xml/dtd/Decl.scala index fd2eaa30ba..e6804478bd 100644 --- a/src/library/scala/xml/dtd/Decl.scala +++ b/src/library/scala/xml/dtd/Decl.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package dtd import Utility.sbToString diff --git a/src/library/scala/xml/dtd/DocType.scala b/src/library/scala/xml/dtd/DocType.scala index af7e77e76f..849d560cc9 100644 --- a/src/library/scala/xml/dtd/DocType.scala +++ b/src/library/scala/xml/dtd/DocType.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package dtd /** An XML node for document type declaration. diff --git a/src/library/scala/xml/dtd/ElementValidator.scala b/src/library/scala/xml/dtd/ElementValidator.scala index ad74acb77e..4830769a7d 100644 --- a/src/library/scala/xml/dtd/ElementValidator.scala +++ b/src/library/scala/xml/dtd/ElementValidator.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package dtd import PartialFunction._ diff --git a/src/library/scala/xml/dtd/ExternalID.scala b/src/library/scala/xml/dtd/ExternalID.scala index 80ada0caaa..5a1b5d1a19 100644 --- a/src/library/scala/xml/dtd/ExternalID.scala +++ b/src/library/scala/xml/dtd/ExternalID.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package dtd /** an ExternalIDs - either PublicID or SystemID diff --git a/src/library/scala/xml/dtd/Scanner.scala b/src/library/scala/xml/dtd/Scanner.scala index 53404e34a7..5f9d1ccaed 100644 --- a/src/library/scala/xml/dtd/Scanner.scala +++ b/src/library/scala/xml/dtd/Scanner.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package dtd /** Scanner for regexps (content models in DTD element declarations) diff --git a/src/library/scala/xml/dtd/Tokens.scala b/src/library/scala/xml/dtd/Tokens.scala index eaffba99a4..07e888e77a 100644 --- a/src/library/scala/xml/dtd/Tokens.scala +++ b/src/library/scala/xml/dtd/Tokens.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package dtd diff --git a/src/library/scala/xml/dtd/ValidationException.scala b/src/library/scala/xml/dtd/ValidationException.scala index 15640e2da7..1bfae55286 100644 --- a/src/library/scala/xml/dtd/ValidationException.scala +++ b/src/library/scala/xml/dtd/ValidationException.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package dtd diff --git a/src/library/scala/xml/dtd/impl/Base.scala b/src/library/scala/xml/dtd/impl/Base.scala index dd277779f6..91ff03a93a 100644 --- a/src/library/scala/xml/dtd/impl/Base.scala +++ b/src/library/scala/xml/dtd/impl/Base.scala @@ -8,7 +8,8 @@ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl /** Basic regular expressions. * diff --git a/src/library/scala/xml/dtd/impl/BaseBerrySethi.scala b/src/library/scala/xml/dtd/impl/BaseBerrySethi.scala index 99d5ab62e1..f30309b037 100644 --- a/src/library/scala/xml/dtd/impl/BaseBerrySethi.scala +++ b/src/library/scala/xml/dtd/impl/BaseBerrySethi.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl import scala.collection.{ mutable, immutable } diff --git a/src/library/scala/xml/dtd/impl/DetWordAutom.scala b/src/library/scala/xml/dtd/impl/DetWordAutom.scala index 5c1dcb7ff8..6f8ba4de72 100644 --- a/src/library/scala/xml/dtd/impl/DetWordAutom.scala +++ b/src/library/scala/xml/dtd/impl/DetWordAutom.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl import scala.collection.{ mutable, immutable } diff --git a/src/library/scala/xml/dtd/impl/Inclusion.scala b/src/library/scala/xml/dtd/impl/Inclusion.scala index 0ae78519ca..07b6afaeba 100644 --- a/src/library/scala/xml/dtd/impl/Inclusion.scala +++ b/src/library/scala/xml/dtd/impl/Inclusion.scala @@ -8,7 +8,8 @@ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl /** A fast test of language inclusion between minimal automata. diff --git a/src/library/scala/xml/dtd/impl/NondetWordAutom.scala b/src/library/scala/xml/dtd/impl/NondetWordAutom.scala index 8e0b5a3a4c..0bb19a7e3e 100644 --- a/src/library/scala/xml/dtd/impl/NondetWordAutom.scala +++ b/src/library/scala/xml/dtd/impl/NondetWordAutom.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl import scala.collection.{ immutable, mutable } @@ -51,7 +52,7 @@ private[dtd] abstract class NondetWordAutom[T <: AnyRef] { override def toString = { val finalString = Map(finalStates map (j => j -> finals(j)) : _*).toString - val deltaString = (0 until nstates) + val deltaString = (0 until nstates) .map(i => " %d->%s\n _>%s\n".format(i, delta(i), default(i))).mkString "[NondetWordAutom nstates=%d finals=%s delta=\n%s".format(nstates, finalString, deltaString) diff --git a/src/library/scala/xml/dtd/impl/PointedHedgeExp.scala b/src/library/scala/xml/dtd/impl/PointedHedgeExp.scala index 0b5297510d..1720604132 100644 --- a/src/library/scala/xml/dtd/impl/PointedHedgeExp.scala +++ b/src/library/scala/xml/dtd/impl/PointedHedgeExp.scala @@ -8,7 +8,8 @@ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl /** Pointed regular hedge expressions, a useful subclass of regular hedge expressions. * diff --git a/src/library/scala/xml/dtd/impl/SubsetConstruction.scala b/src/library/scala/xml/dtd/impl/SubsetConstruction.scala index d1ea4b6e9e..632ca1eb18 100644 --- a/src/library/scala/xml/dtd/impl/SubsetConstruction.scala +++ b/src/library/scala/xml/dtd/impl/SubsetConstruction.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl import scala.collection.{ mutable, immutable } diff --git a/src/library/scala/xml/dtd/impl/SyntaxError.scala b/src/library/scala/xml/dtd/impl/SyntaxError.scala index b0e0b8b6cd..a5b8a5aba0 100644 --- a/src/library/scala/xml/dtd/impl/SyntaxError.scala +++ b/src/library/scala/xml/dtd/impl/SyntaxError.scala @@ -8,7 +8,8 @@ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl /** This runtime exception is thrown if an attempt to instantiate a * syntactically incorrect expression is detected. diff --git a/src/library/scala/xml/dtd/impl/WordBerrySethi.scala b/src/library/scala/xml/dtd/impl/WordBerrySethi.scala index 90d7fe760a..9bf3fa518b 100644 --- a/src/library/scala/xml/dtd/impl/WordBerrySethi.scala +++ b/src/library/scala/xml/dtd/impl/WordBerrySethi.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl import scala.collection.{ immutable, mutable } diff --git a/src/library/scala/xml/dtd/impl/WordExp.scala b/src/library/scala/xml/dtd/impl/WordExp.scala index 38f8aea697..a4bb54c1ea 100644 --- a/src/library/scala/xml/dtd/impl/WordExp.scala +++ b/src/library/scala/xml/dtd/impl/WordExp.scala @@ -8,7 +8,8 @@ -package scala.xml.dtd.impl +package scala +package xml.dtd.impl /** * The class `WordExp` provides regular word expressions. diff --git a/src/library/scala/xml/factory/Binder.scala b/src/library/scala/xml/factory/Binder.scala index b463fda5ba..947f99e6a4 100755 --- a/src/library/scala/xml/factory/Binder.scala +++ b/src/library/scala/xml/factory/Binder.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package factory import parsing.ValidatingMarkupHandler diff --git a/src/library/scala/xml/factory/LoggedNodeFactory.scala b/src/library/scala/xml/factory/LoggedNodeFactory.scala index 49a6d622a7..63b4f42150 100644 --- a/src/library/scala/xml/factory/LoggedNodeFactory.scala +++ b/src/library/scala/xml/factory/LoggedNodeFactory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package factory /** This class logs what the nodefactory is actually doing. diff --git a/src/library/scala/xml/factory/NodeFactory.scala b/src/library/scala/xml/factory/NodeFactory.scala index 28a1b6fff4..94801bb554 100644 --- a/src/library/scala/xml/factory/NodeFactory.scala +++ b/src/library/scala/xml/factory/NodeFactory.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package factory import parsing.{ FactoryAdapter, NoBindingFactoryAdapter } diff --git a/src/library/scala/xml/factory/XMLLoader.scala b/src/library/scala/xml/factory/XMLLoader.scala index bd18f2a699..b69f187039 100644 --- a/src/library/scala/xml/factory/XMLLoader.scala +++ b/src/library/scala/xml/factory/XMLLoader.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package factory import javax.xml.parsers.SAXParserFactory diff --git a/src/library/scala/xml/include/CircularIncludeException.scala b/src/library/scala/xml/include/CircularIncludeException.scala index 5e74967d54..351f403008 100644 --- a/src/library/scala/xml/include/CircularIncludeException.scala +++ b/src/library/scala/xml/include/CircularIncludeException.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package include /** diff --git a/src/library/scala/xml/include/UnavailableResourceException.scala b/src/library/scala/xml/include/UnavailableResourceException.scala index f00cc58699..47b176e0f3 100644 --- a/src/library/scala/xml/include/UnavailableResourceException.scala +++ b/src/library/scala/xml/include/UnavailableResourceException.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package include /** diff --git a/src/library/scala/xml/include/XIncludeException.scala b/src/library/scala/xml/include/XIncludeException.scala index 84033f853f..11e1644d83 100644 --- a/src/library/scala/xml/include/XIncludeException.scala +++ b/src/library/scala/xml/include/XIncludeException.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package include /** diff --git a/src/library/scala/xml/include/sax/EncodingHeuristics.scala b/src/library/scala/xml/include/sax/EncodingHeuristics.scala index 8d8ce5b290..57ab5ed91c 100644 --- a/src/library/scala/xml/include/sax/EncodingHeuristics.scala +++ b/src/library/scala/xml/include/sax/EncodingHeuristics.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package include.sax import java.io.InputStream diff --git a/src/library/scala/xml/include/sax/XIncludeFilter.scala b/src/library/scala/xml/include/sax/XIncludeFilter.scala index 9079b5f9c7..3fa3beefb0 100644 --- a/src/library/scala/xml/include/sax/XIncludeFilter.scala +++ b/src/library/scala/xml/include/sax/XIncludeFilter.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package include.sax import scala.xml.include._ diff --git a/src/library/scala/xml/include/sax/XIncluder.scala b/src/library/scala/xml/include/sax/XIncluder.scala index 8fcd66d4c0..531b7196f2 100644 --- a/src/library/scala/xml/include/sax/XIncluder.scala +++ b/src/library/scala/xml/include/sax/XIncluder.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package include.sax import scala.collection.mutable diff --git a/src/library/scala/xml/parsing/ConstructingHandler.scala b/src/library/scala/xml/parsing/ConstructingHandler.scala index 6fda4dabfb..ba416e4301 100755 --- a/src/library/scala/xml/parsing/ConstructingHandler.scala +++ b/src/library/scala/xml/parsing/ConstructingHandler.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing /** Implementation of MarkupHandler that constructs nodes. diff --git a/src/library/scala/xml/parsing/ConstructingParser.scala b/src/library/scala/xml/parsing/ConstructingParser.scala index 404411812e..3caeddabf4 100644 --- a/src/library/scala/xml/parsing/ConstructingParser.scala +++ b/src/library/scala/xml/parsing/ConstructingParser.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing import java.io.File diff --git a/src/library/scala/xml/parsing/DefaultMarkupHandler.scala b/src/library/scala/xml/parsing/DefaultMarkupHandler.scala index 0152e44cda..6ec7474843 100755 --- a/src/library/scala/xml/parsing/DefaultMarkupHandler.scala +++ b/src/library/scala/xml/parsing/DefaultMarkupHandler.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing diff --git a/src/library/scala/xml/parsing/ExternalSources.scala b/src/library/scala/xml/parsing/ExternalSources.scala index aaac588092..bb939bca95 100644 --- a/src/library/scala/xml/parsing/ExternalSources.scala +++ b/src/library/scala/xml/parsing/ExternalSources.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing import java.net.URL diff --git a/src/library/scala/xml/parsing/FactoryAdapter.scala b/src/library/scala/xml/parsing/FactoryAdapter.scala index 8659d3f0c4..2154bdf5ba 100644 --- a/src/library/scala/xml/parsing/FactoryAdapter.scala +++ b/src/library/scala/xml/parsing/FactoryAdapter.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package parsing import java.io.{ InputStream, Reader, File, FileDescriptor, FileInputStream } diff --git a/src/library/scala/xml/parsing/FatalError.scala b/src/library/scala/xml/parsing/FatalError.scala index a8b4f8f8cf..ab3cb2a74d 100644 --- a/src/library/scala/xml/parsing/FatalError.scala +++ b/src/library/scala/xml/parsing/FatalError.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing /** !!! This is poorly named, but I guess it's in the API. diff --git a/src/library/scala/xml/parsing/MarkupHandler.scala b/src/library/scala/xml/parsing/MarkupHandler.scala index 7028161821..0daabedf1c 100755 --- a/src/library/scala/xml/parsing/MarkupHandler.scala +++ b/src/library/scala/xml/parsing/MarkupHandler.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing import scala.collection.mutable diff --git a/src/library/scala/xml/parsing/MarkupParser.scala b/src/library/scala/xml/parsing/MarkupParser.scala index 9c7bb60475..3bbd136b67 100755 --- a/src/library/scala/xml/parsing/MarkupParser.scala +++ b/src/library/scala/xml/parsing/MarkupParser.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package parsing import scala.io.Source diff --git a/src/library/scala/xml/parsing/MarkupParserCommon.scala b/src/library/scala/xml/parsing/MarkupParserCommon.scala index 7bfbcc7fff..57c1651558 100644 --- a/src/library/scala/xml/parsing/MarkupParserCommon.scala +++ b/src/library/scala/xml/parsing/MarkupParserCommon.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package parsing import scala.io.Source diff --git a/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala b/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala index 22dd450072..56ac185f47 100644 --- a/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala +++ b/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package parsing import factory.NodeFactory diff --git a/src/library/scala/xml/parsing/TokenTests.scala b/src/library/scala/xml/parsing/TokenTests.scala index c9cafaeea1..8dd9cdfaa3 100644 --- a/src/library/scala/xml/parsing/TokenTests.scala +++ b/src/library/scala/xml/parsing/TokenTests.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package parsing /** diff --git a/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala b/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala index 018ae4d2cd..cec6b358ff 100644 --- a/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala +++ b/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package parsing import scala.xml.dtd._ diff --git a/src/library/scala/xml/parsing/XhtmlEntities.scala b/src/library/scala/xml/parsing/XhtmlEntities.scala index 1bb843818a..3683af202c 100644 --- a/src/library/scala/xml/parsing/XhtmlEntities.scala +++ b/src/library/scala/xml/parsing/XhtmlEntities.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package parsing import scala.xml.dtd.{ IntDef, ParsedEntityDecl } diff --git a/src/library/scala/xml/parsing/XhtmlParser.scala b/src/library/scala/xml/parsing/XhtmlParser.scala index 33b94c9bd7..6ce5bec8d0 100644 --- a/src/library/scala/xml/parsing/XhtmlParser.scala +++ b/src/library/scala/xml/parsing/XhtmlParser.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package parsing import scala.io.Source diff --git a/src/library/scala/xml/persistent/CachedFileStorage.scala b/src/library/scala/xml/persistent/CachedFileStorage.scala index fc510b5f18..347c11651c 100644 --- a/src/library/scala/xml/persistent/CachedFileStorage.scala +++ b/src/library/scala/xml/persistent/CachedFileStorage.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package persistent import java.io.{ File, FileOutputStream } diff --git a/src/library/scala/xml/persistent/Index.scala b/src/library/scala/xml/persistent/Index.scala index defaf67d52..9ee45e7086 100644 --- a/src/library/scala/xml/persistent/Index.scala +++ b/src/library/scala/xml/persistent/Index.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package persistent /** an Index returns some unique key that is part of a node diff --git a/src/library/scala/xml/persistent/SetStorage.scala b/src/library/scala/xml/persistent/SetStorage.scala index d16c71c9f7..8db56a2e71 100644 --- a/src/library/scala/xml/persistent/SetStorage.scala +++ b/src/library/scala/xml/persistent/SetStorage.scala @@ -7,7 +7,8 @@ \* */ -package scala.xml +package scala +package xml package persistent import scala.collection.mutable diff --git a/src/library/scala/xml/pull/XMLEvent.scala b/src/library/scala/xml/pull/XMLEvent.scala index a266380f87..3beb3648e7 100644 --- a/src/library/scala/xml/pull/XMLEvent.scala +++ b/src/library/scala/xml/pull/XMLEvent.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package pull /** An XML event for pull parsing. All events received during diff --git a/src/library/scala/xml/pull/XMLEventReader.scala b/src/library/scala/xml/pull/XMLEventReader.scala index 3f9584fd04..76e51e17fd 100755 --- a/src/library/scala/xml/pull/XMLEventReader.scala +++ b/src/library/scala/xml/pull/XMLEventReader.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.xml +package scala +package xml package pull import scala.io.Source diff --git a/src/library/scala/xml/pull/package.scala b/src/library/scala/xml/pull/package.scala index 3742c55513..0e3019446b 100644 --- a/src/library/scala/xml/pull/package.scala +++ b/src/library/scala/xml/pull/package.scala @@ -1,4 +1,5 @@ -package scala.xml +package scala +package xml /** * Classes needed to view an XML document as a series of events. The document diff --git a/src/library/scala/xml/transform/BasicTransformer.scala b/src/library/scala/xml/transform/BasicTransformer.scala index e427071177..c98339fd67 100644 --- a/src/library/scala/xml/transform/BasicTransformer.scala +++ b/src/library/scala/xml/transform/BasicTransformer.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package transform /** A class for XML transformations. diff --git a/src/library/scala/xml/transform/RewriteRule.scala b/src/library/scala/xml/transform/RewriteRule.scala index 13210a6fd2..1399ee538d 100644 --- a/src/library/scala/xml/transform/RewriteRule.scala +++ b/src/library/scala/xml/transform/RewriteRule.scala @@ -8,7 +8,8 @@ -package scala.xml +package scala +package xml package transform /** A RewriteRule, when applied to a term, yields either diff --git a/src/library/scala/xml/transform/RuleTransformer.scala b/src/library/scala/xml/transform/RuleTransformer.scala index 85e92e5773..3a222ba759 100644 --- a/src/library/scala/xml/transform/RuleTransformer.scala +++ b/src/library/scala/xml/transform/RuleTransformer.scala @@ -6,9 +6,8 @@ ** |/ ** \* */ - - -package scala.xml +package scala +package xml package transform class RuleTransformer(rules: RewriteRule*) extends BasicTransformer { diff --git a/src/partest/scala/tools/partest/PartestDefaults.scala b/src/partest/scala/tools/partest/PartestDefaults.scala index 16f1a6933f..8478edeb4d 100644 --- a/src/partest/scala/tools/partest/PartestDefaults.scala +++ b/src/partest/scala/tools/partest/PartestDefaults.scala @@ -1,6 +1,7 @@ package scala.tools package partest +import scala.concurrent.duration.Duration import scala.tools.nsc.Properties.{ propOrElse, propOrNone, propOrEmpty } import java.lang.Runtime.{ getRuntime => runtime } @@ -21,6 +22,7 @@ object PartestDefaults { def testBuild = propOrNone("partest.build") def errorCount = propOrElse("partest.errors", "0").toInt def numThreads = propOrNone("partest.threads") map (_.toInt) getOrElse runtime.availableProcessors + def waitTime = propOrNone("partest.timeout") map (Duration.apply) getOrElse Duration("4 hours") - def timeout = "1200000" + //def timeout = "1200000" // per-test timeout } diff --git a/src/partest/scala/tools/partest/TestState.scala b/src/partest/scala/tools/partest/TestState.scala index ce8e72f616..dbe8a222a5 100644 --- a/src/partest/scala/tools/partest/TestState.scala +++ b/src/partest/scala/tools/partest/TestState.scala @@ -12,13 +12,15 @@ sealed abstract class TestState { def isOk = false def isSkipped = false def testIdent = testFile.testIdent - def transcriptString = transcript.mkString("\n") + def transcriptString = transcript mkString EOL def identAndReason = testIdent + reasonString def status = s"$what - $identAndReason" def longStatus = status + transcriptString def reasonString = if (reason == "") "" else s" [$reason]" + def shortStatus = if (isOk) "ok" else "!!" + override def toString = status } @@ -27,18 +29,27 @@ object TestState { def what = "uninitialized" def reason = what def transcript = Nil + override def shortStatus = "??" } case class Pass(testFile: File) extends TestState { - final override def isOk = true def what = "pass" + override def isOk = true def transcript: List[String] = Nil def reason = "" } - case class Skip(testFile: File, reason: String) extends TestState { + case class Updated(testFile: File) extends TestState { + def what = "updated" override def isOk = true - final override def isSkipped = true def transcript: List[String] = Nil + def reason = "updated check file" + override def shortStatus = "++" + } + case class Skip(testFile: File, reason: String) extends TestState { def what = "skip" + override def isOk = true + override def isSkipped = true + def transcript: List[String] = Nil + override def shortStatus = "--" } case class Fail(testFile: File, reason: String, transcript: List[String]) extends TestState { def what = "fail" diff --git a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala index ddd42f5601..5717aabb6a 100644 --- a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala +++ b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala @@ -86,7 +86,7 @@ class ConsoleRunner extends DirectRunner { ) ::: standardArgs private val binaryArgs = List( - "--grep", "--srcpath", "--buildpath", "--classpath" + "--grep", "--srcpath", "--buildpath", "--classpath", "--timeout" ) def main(argstr: String) { @@ -95,6 +95,7 @@ class ConsoleRunner extends DirectRunner { if (parsed isSet "--debug") NestUI.setDebug() if (parsed isSet "--verbose") NestUI.setVerbose() if (parsed isSet "--terse") NestUI.setTerse() + if (parsed isSet "--show-diff") NestUI.setDiffOnFail() // Early return on no args, version, or invalid args if (parsed isSet "--version") return echo(versionMsg) @@ -109,6 +110,7 @@ class ConsoleRunner extends DirectRunner { } parsed get "--srcpath" foreach (x => setProp("partest.srcdir", x)) + parsed get "--timeout" foreach (x => setProp("partest.timeout", x)) fileManager = if (parsed isSet "--buildpath") new ConsoleFileManager(parsed("--buildpath")) diff --git a/src/partest/scala/tools/partest/nest/DirectCompiler.scala b/src/partest/scala/tools/partest/nest/DirectCompiler.scala index 650b6c35c8..8e5ff2abc4 100644 --- a/src/partest/scala/tools/partest/nest/DirectCompiler.scala +++ b/src/partest/scala/tools/partest/nest/DirectCompiler.scala @@ -48,7 +48,7 @@ class DirectCompiler(val fileManager: FileManager) { } def compile(runner: Runner, opts0: List[String], sources: List[File]): TestState = { - import runner._ + import runner.{ sources => _, _ } val testSettings = new TestSettings(ClassPath.join(fileManager.LATEST_LIB, outDir.getPath)) val logWriter = new FileWriter(logFile) diff --git a/src/partest/scala/tools/partest/nest/DirectRunner.scala b/src/partest/scala/tools/partest/nest/DirectRunner.scala deleted file mode 100644 index 49dd39c344..0000000000 --- a/src/partest/scala/tools/partest/nest/DirectRunner.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* NEST (New Scala Test) - * Copyright 2007-2013 LAMP/EPFL - * @author Philipp Haller - */ - -package scala.tools.partest -package nest - -import java.io.File -import scala.util.Properties.setProp -import scala.tools.nsc.util.{ ScalaClassLoader, Exceptional } -import scala.tools.nsc.io.Path -import scala.collection.{ mutable, immutable } -import java.util.concurrent._ - -case class TestRunParams(val scalaCheckParentClassLoader: ScalaClassLoader) - -trait DirectRunner { - def fileManager: FileManager - - import PartestDefaults.numThreads - - Thread.setDefaultUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler { - def uncaughtException(thread: Thread, t: Throwable) { - val t1 = Exceptional unwrap t - System.err.println(s"Uncaught exception on thread $thread: $t1") - t1.printStackTrace() - } - } - ) - def runTestsForFiles(kindFiles: List[File], kind: String): List[TestState] = { - - NestUI.resetTestNumber() - - val allUrls = PathSettings.scalaCheck.toURL :: fileManager.latestUrls - val parentClassLoader = ScalaClassLoader fromURLs allUrls - val pool = Executors newFixedThreadPool numThreads - val manager = new RunnerManager(kind, fileManager, TestRunParams(parentClassLoader)) - val futures = kindFiles map (f => pool submit callable(manager runTest f)) - - pool.shutdown() - try if (!pool.awaitTermination(4, TimeUnit.HOURS)) - NestUI warning "Thread pool timeout elapsed before all tests were complete!" - catch { case t: InterruptedException => - NestUI warning "Thread pool was interrupted" - t.printStackTrace() - } - - futures map (_.get) - } -} diff --git a/src/partest/scala/tools/partest/nest/FileManager.scala b/src/partest/scala/tools/partest/nest/FileManager.scala index 25371b7d54..230ada4803 100644 --- a/src/partest/scala/tools/partest/nest/FileManager.scala +++ b/src/partest/scala/tools/partest/nest/FileManager.scala @@ -85,7 +85,6 @@ trait FileManager extends FileUtil { var SCALAC_OPTS = PartestDefaults.scalacOpts.split(' ').toSeq var JAVA_OPTS = PartestDefaults.javaOpts - var timeout = PartestDefaults.timeout /** Only when --debug is given. */ lazy val testTimings = new mutable.HashMap[String, Long] diff --git a/src/partest/scala/tools/partest/nest/NestUI.scala b/src/partest/scala/tools/partest/nest/NestUI.scala index 2e203bfd91..564270e531 100644 --- a/src/partest/scala/tools/partest/nest/NestUI.scala +++ b/src/partest/scala/tools/partest/nest/NestUI.scala @@ -27,9 +27,14 @@ class Colors(enabled: => Boolean) { object NestUI { private val testNum = new java.util.concurrent.atomic.AtomicInteger(1) + @volatile private var testNumberFmt = "%3d" // @volatile private var testNumber = 1 - private def testNumber = "%3d" format testNum.getAndIncrement() - def resetTestNumber() = testNum set 1 + private def testNumber = testNumberFmt format testNum.getAndIncrement() + def resetTestNumber(max: Int = -1) { + testNum set 1 + val width = if (max > 0) max.toString.length else 3 + testNumberFmt = s"%${width}d" + } var colorEnabled = sys.props contains "partest.colors" val color = new Colors(colorEnabled) @@ -57,12 +62,15 @@ object NestUI { def statusLine(state: TestState) = { import state._ - val word = bold( - if (isSkipped) yellow("--") - else if (isOk) green("ok") - else red("!!") - ) - word + f" $testNumber%3s - $testIdent%-40s$reasonString" + import TestState._ + val colorizer = state match { + case _: Skip => yellow + case _: Updated => cyan + case s if s.isOk => green + case _ => red + } + val word = bold(colorizer(state.shortStatus)) + f"$word $testNumber - $testIdent%-40s$reasonString" } def reportTest(state: TestState) = { @@ -76,7 +84,13 @@ object NestUI { dotCount += 1 } } - else echo(statusLine(state)) + else { + echo(statusLine(state)) + if (!state.isOk && isDiffy) { + val differ = bold(red("% ")) + "diff " + state.transcript find (_ startsWith differ) foreach (echo(_)) + } + } } def echo(message: String): Unit = synchronized { @@ -164,10 +178,12 @@ object NestUI { var _verbose = false var _debug = false var _terse = false + var _diff = false def isVerbose = _verbose def isDebug = _debug def isTerse = _terse + def isDiffy = _diff def setVerbose() { _verbose = true @@ -178,6 +194,9 @@ object NestUI { def setTerse() { _terse = true } + def setDiffOnFail() { + _diff = true + } def verbose(msg: String) { if (isVerbose) System.err.println(msg) diff --git a/src/partest/scala/tools/partest/nest/PathSettings.scala b/src/partest/scala/tools/partest/nest/PathSettings.scala index b1f868c9d2..8e454d8de8 100644 --- a/src/partest/scala/tools/partest/nest/PathSettings.scala +++ b/src/partest/scala/tools/partest/nest/PathSettings.scala @@ -7,9 +7,9 @@ package nest import scala.tools.nsc.Properties.{ setProp, propOrEmpty, propOrNone, propOrElse } import scala.tools.nsc.util.ClassPath -import scala.tools.nsc.io +import scala.tools.nsc.io.{ Path, File, Directory } import scala.util.Properties.{ envOrElse, envOrNone, javaHome, jdkHome } -import io.{ Path, File, Directory } +import Path._ object PathSettings { import PartestDefaults.{ testRootDir, srcDirName } @@ -19,6 +19,8 @@ object PathSettings { private def findJar(d: Directory, name: String): Option[File] = findJar(d.files, name) private def findJar(files: Iterator[File], name: String): Option[File] = files filter (_ hasExtension "jar") find { _.name startsWith name } + private def findJarOrFail(name: String, ds: Directory*): File = findJar(ds flatMap (_.files) iterator, name) getOrElse + sys.error(s"'${name}.jar' not found in '${ds map (_.path) mkString ", "}'.") // Directory <root>/test lazy val testRoot: Directory = testRootDir getOrElse { @@ -27,8 +29,8 @@ object PathSettings { candidates find isPartestDir getOrElse sys.error("Directory 'test' not found.") } - // Directory <root>/test/files - lazy val srcDir = Directory(testRoot / srcDirName toCanonical) + // Directory <root>/test/files or .../scaladoc + def srcDir = Directory(testRoot / srcDirName toCanonical) // Directory <root>/test/files/lib lazy val srcLibDir = Directory(srcDir / "lib") @@ -73,6 +75,8 @@ object PathSettings { sys.error("No scalacheck jar found in '%s' or '%s'".format(buildPackLibDir, srcLibDir)) } + lazy val testInterface: File = findJarOrFail("test-interface", buildPackLibDir, srcLibDir) + lazy val diffUtils: File = findJar(buildPackLibDir.files, "diffutils") getOrElse sys.error(s"No diffutils.jar found in '$buildPackLibDir'.") @@ -82,7 +86,7 @@ object PathSettings { * if one of those environment variables is set, then the lib directory under java.home, * and finally the lib directory under the parent of java.home. Or, as a last resort, * search deeply under those locations (except for the parent of java.home, on the notion - * that if this is not a canonical installation, then that search would have litte + * that if this is not a canonical installation, then that search would have little * chance of succeeding). */ lazy val platformTools: Option[File] = { diff --git a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala index 9780e82cd9..734affa153 100644 --- a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala +++ b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala @@ -55,7 +55,7 @@ class ReflectiveRunner { // we hack into the classloader that will become parent classloader for scalac // this way we ensure that reflective macro lookup will pick correct Code.lift // it's also used to inject diffutils into the classpath when running partest from the test/partest script - val srcCodeLibAndDiff = List(PathSettings.srcCodeLib, PathSettings.diffUtils) + val srcCodeLibAndDiff = List(PathSettings.srcCodeLib, PathSettings.diffUtils, PathSettings.testInterface) val sepUrls = srcCodeLibAndDiff.map(_.toURI.toURL) ::: fileManager.latestUrls // this seems to be the core classloader that determines which classes can be found when running partest from the test/partest script val sepLoader = new URLClassLoader(sepUrls.toArray, null) diff --git a/src/partest/scala/tools/partest/nest/Runner.scala b/src/partest/scala/tools/partest/nest/Runner.scala index fc56818bfc..85679ad0b8 100644 --- a/src/partest/scala/tools/partest/nest/Runner.scala +++ b/src/partest/scala/tools/partest/nest/Runner.scala @@ -7,19 +7,24 @@ package nest import java.io.{ Console => _, _ } import java.net.URL -import scala.tools.nsc.Properties.{ jdkHome, javaHome, propOrElse, propOrEmpty } -import scala.util.Properties.{ envOrElse, isWin } +import java.nio.charset.{ Charset, CharsetDecoder, CharsetEncoder, CharacterCodingException, CodingErrorAction => Action } +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit.NANOSECONDS +import scala.collection.mutable.ListBuffer +import scala.concurrent.duration.Duration +import scala.io.Codec +import scala.sys.process.Process +import scala.tools.nsc.Properties.{ envOrElse, isWin, jdkHome, javaHome, propOrElse, propOrEmpty, setProp } import scala.tools.nsc.{ Settings, CompilerCommand, Global } -import scala.tools.nsc.io.{ AbstractFile, PlainFile, Path, Directory, File => SFile } +import scala.tools.nsc.io.{ AbstractFile, PlainFile } import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.util.{ ClassPath, FakePos, ScalaClassLoader, stackTraceString } -import ClassPath.{ join, split } +import scala.tools.nsc.util.{ Exceptional, ScalaClassLoader, stackTraceString } +import scala.tools.scalap.Main.decompileScala import scala.tools.scalap.scalax.rules.scalasig.ByteCode -import scala.collection.{ mutable, immutable } -import scala.sys.process.Process -import java.util.concurrent.{ Executors, TimeUnit, TimeoutException } +import scala.util.{ Try, Success, Failure } +import ClassPath.{ join, split } import PartestDefaults.{ javaCmd, javacCmd } -import scala.tools.scalap.Main.decompileScala +import TestState.{ Pass, Fail, Crash, Uninitialized, Updated } trait PartestRunSettings { def gitPath: Path @@ -35,7 +40,7 @@ trait PartestRunSettings { class TestTranscript { import NestUI.color._ - private val buf = mutable.ListBuffer[String]() + private val buf = ListBuffer[String]() private def pass(s: String) = bold(green("% ")) + s private def fail(s: String) = bold(red("% ")) + s @@ -49,7 +54,8 @@ class TestTranscript { } } -class Runner(val testFile: File, fileManager: FileManager) { +/** Run a single test. Rubber meets road. */ +class Runner(val testFile: File, fileManager: FileManager, val testRunParams: TestRunParams) { import fileManager._ // Override to true to have the outcome of this test displayed @@ -57,12 +63,10 @@ class Runner(val testFile: File, fileManager: FileManager) { // except for a . per passing test to show progress. def isEnumeratedTest = false - def testRunParams: TestRunParams = ??? - private var _lastState: TestState = null private var _transcript = new TestTranscript - def lastState = if (_lastState == null) TestState.Uninitialized(testFile) else _lastState + def lastState = if (_lastState == null) Uninitialized(testFile) else _lastState def setLastState(s: TestState) = _lastState = s def transcript: List[String] = _transcript.fail ++ logFile.fileLines def pushTranscript(msg: String) = _transcript add msg @@ -94,10 +98,11 @@ class Runner(val testFile: File, fileManager: FileManager) { genCrash(t) } - def genPass() = TestState.Pass(testFile) - def genFail(reason: String) = TestState.Fail(testFile, reason, _transcript.fail) - def genTimeout() = TestState.Fail(testFile, "timed out", _transcript.fail) - def genCrash(caught: Throwable) = TestState.Crash(testFile, caught, _transcript.fail) + def genPass() = Pass(testFile) + def genFail(reason: String) = Fail(testFile, reason, _transcript.fail) + def genTimeout() = Fail(testFile, "timed out", _transcript.fail) + def genCrash(caught: Throwable) = Crash(testFile, caught, _transcript.fail) + def genUpdated() = Updated(testFile) def speclib = PathSettings.srcSpecLib.toString // specialization lib def codelib = PathSettings.srcCodeLib.toString // reify lib @@ -151,14 +156,18 @@ class Runner(val testFile: File, fileManager: FileManager) { case _ => "% " } + /** Evaluate an action body and update the test state. + * @param failFn optionally map a result to a test state. + */ def nextTestAction[T](body: => T)(failFn: PartialFunction[T, TestState]): T = { val result = body setLastState( if (failFn isDefinedAt result) failFn(result) else genPass() ) result } - def nextTestActionExpectTrue[T](reason: String, body: => Boolean): Boolean = { + def nextTestActionExpectTrue(reason: String, body: => Boolean): Boolean = ( nextTestAction(body) { case false => genFail(reason) } - } + ) + def nextTestActionFailing(reason: String): Boolean = nextTestActionExpectTrue(reason, false) private def assembleTestCommand(outDir: File, logFile: File): List[String] = { // check whether there is a ".javaopts" file @@ -218,15 +227,17 @@ class Runner(val testFile: File, fileManager: FileManager) { private def execTest(outDir: File, logFile: File): Boolean = { val cmd = assembleTestCommand(outDir, logFile) - pushTranscript(cmd.mkString(" \\\n ") + " > " + logFile.getName) - nextTestActionExpectTrue("non-zero exit code", runCommand(cmd, logFile)) || { - _transcript append logFile.fileContents - false + pushTranscript((cmd mkString s" \\$EOL ") + " > " + logFile.getName) + nextTestAction(runCommand(cmd, logFile)) { + case false => + _transcript append EOL + logFile.fileContents + genFail("non-zero exit code") } } override def toString = s"""Test($testIdent, lastState = $lastState)""" + // result is unused def newTestWriters() = { val swr = new StringWriter val wr = new PrintWriter(swr, true) @@ -320,18 +331,20 @@ class Runner(val testFile: File, fileManager: FileManager) { def diffIsOk: Boolean = { val diff = currentDiff - val ok: Boolean = (diff == "") || { - fileManager.updateCheck && { + // if diff is not empty, is update needed? + val updating: Option[Boolean] = ( + if (diff == "") None + else Some(fileManager.updateCheck) + ) + pushTranscript(s"diff $logFile $checkFile") + nextTestAction(updating) { + case Some(true) => NestUI.verbose("Updating checkfile " + checkFile) checkFile writeAll file2String(logFile) - true - } - } - pushTranscript(s"diff $logFile $checkFile") - nextTestAction(ok) { - case false => + genUpdated() + case Some(false) => // Get a word-highlighted diff from git if we can find it - val bestDiff = if (ok) "" else { + val bestDiff = if (updating.isEmpty) "" else { if (checkFile.canRead) gitDiff(logFile, checkFile) getOrElse { s"diff $logFile $checkFile\n$diff" @@ -343,11 +356,13 @@ class Runner(val testFile: File, fileManager: FileManager) { // TestState.fail("output differs", "output differs", // genFail("output differs") // TestState.Fail("output differs", bestDiff) - } + case None => genPass() // redundant default case + } getOrElse true } /** 1. Creates log file and output directory. * 2. Runs script function, providing log file and output directory as arguments. + * 2b. or, just run the script without context and return a new context */ def runInContext(body: => Boolean): (Boolean, LogContext) = { val (swr, wr) = newTestWriters() @@ -356,11 +371,16 @@ class Runner(val testFile: File, fileManager: FileManager) { } /** Grouped files in group order, and lex order within each group. */ - def groupedFiles(dir: File): List[List[File]] = { - val testFiles = dir.listFiles.toList filter (_.isJavaOrScala) - val grouped = testFiles groupBy (_.group) - grouped.keys.toList.sorted map (k => grouped(k) sortBy (_.getName)) - } + def groupedFiles(files: List[File]): List[List[File]] = ( + if (files.tail.nonEmpty) { + val grouped = files filter (_.isJavaOrScala) groupBy (_.group) + grouped.keys.toList.sorted map (k => grouped(k) sortBy (_.getName)) + } + else List(files) + ) + + /** Source files for the given test file. */ + def sources(file: File): List[File] = if (file.isDirectory) file.listFiles.toList else List(file) def newCompiler = new DirectCompiler(fileManager) @@ -411,11 +431,9 @@ class Runner(val testFile: File, fileManager: FileManager) { lazy val result = { pushTranscript(description) ; attemptCompile(fs) } } - def compilationRounds(file: File): List[CompileRound] = { - val grouped = if (file.isDirectory) groupedFiles(file) else List(List(file)) - - (grouped map mixedCompileGroup).flatten - } + def compilationRounds(file: File): List[CompileRound] = ( + (groupedFiles(sources(file)) map mixedCompileGroup).flatten + ) def mixedCompileGroup(allFiles: List[File]): List[CompileRound] = { val (scalaFiles, javaFiles) = allFiles partition (_.isScala) val isMixed = javaFiles.nonEmpty && scalaFiles.nonEmpty @@ -429,12 +447,16 @@ class Runner(val testFile: File, fileManager: FileManager) { def runNegTest() = runInContext { val rounds = compilationRounds(testFile) - if (rounds forall (x => nextTestActionExpectTrue("compilation failed", x.isOk))) - nextTestActionExpectTrue("expected compilation failure", false) - else { - normalizeLog // put errors in a normal form - diffIsOk + // failing means Does Not Compile + val failing = rounds find (x => nextTestActionExpectTrue("compilation failed", x.isOk) == false) + + // which means passing if it checks and didn't crash the compiler + def checked(r: CompileRound) = r.result match { + case f: Crash => false + case f => normalizeLog(); diffIsOk } + + failing map (checked) getOrElse nextTestActionFailing("expected compilation failure") } def runTestCommon(andAlso: => Boolean): (Boolean, LogContext) = runInContext { @@ -495,24 +517,68 @@ class Runner(val testFile: File, fileManager: FileManager) { } def runScalacheckTest() = runTestCommon { - NestUI.verbose("compilation of "+testFile+" succeeded\n") + NestUI verbose f"compilation of $testFile succeeded%n" - val outURL = outDir.getAbsoluteFile.toURI.toURL + // this classloader is test specific: its parent contains library classes and others + val loader = { + import PathSettings.scalaCheck + val locations = List(outDir, scalaCheck.jfile) map (_.getAbsoluteFile.toURI.toURL) + ScalaClassLoader.fromURLs(locations, getClass.getClassLoader) + } val logWriter = new PrintStream(new FileOutputStream(logFile), true) - Output.withRedirected(logWriter) { - // this classloader is test specific: its parent contains library classes and others - ScalaClassLoader.fromURLs(List(outURL), testRunParams.scalaCheckParentClassLoader).run("Test", Nil) + def toolArgs(tool: String): List[String] = { + def argsplitter(s: String) = words(s) filter (_.nonEmpty) + def argsFor(f: File): List[String] = { + import scala.util.matching.Regex + val p = new Regex(s"(?:.*\\s)?${tool}:(.*)?", "args") + val max = 10 + val src = Path(f).toFile.chars(codec) + val args = try { + src.getLines take max collectFirst { + case s if (p findFirstIn s).nonEmpty => for (m <- p findFirstMatchIn s) yield m group "args" + } + } finally src.close() + args.flatten map argsplitter getOrElse Nil + } + sources(testFile) flatMap argsFor } - - NestUI.verbose(file2String(logFile)) - // obviously this must be improved upon - val lines = SFile(logFile).lines map (_.trim) filterNot (_ == "") toBuffer; - lines.forall(x => !x.startsWith("!")) || { - NestUI.normal("ScalaCheck test failed. Output:\n") - lines foreach (x => NestUI.normal(x + "\n")) - false + def runInFramework(): Boolean = { + import org.scalatools.testing._ + val f: Framework = loader.instantiate[Framework]("org.scalacheck.ScalaCheckFramework") + val logger = new Logger { + def ansiCodesSupported = false //params.env.isSet("colors") + def error(msg: String) = logWriter println msg + def warn(msg: String) = logWriter println msg + def info(msg: String) = logWriter println msg + def debug(msg: String) = logWriter println msg + def trace(t: Throwable) = t printStackTrace logWriter + } + var bad = 0 + val handler = new EventHandler { + // testName, description, result, error + // Result = Success, Failure, Error, Skipped + def handle(event: Event): Unit = event.result match { + case Result.Success => + //case Result.Skipped => // an exhausted test is skipped, therefore bad + case _ => bad += 1 + } + } + val loggers = Array(logger) + val r = f.testRunner(loader, loggers).asInstanceOf[Runner2] // why? + val claas = "Test" + val fingerprint = f.tests collectFirst { case x: SubclassFingerprint if x.isModule => x } + val args = toolArgs("scalacheck") + vlog(s"Run $testFile with args $args") + // set the context class loader for scaladoc/scalacheck tests (FIX ME) + ScalaClassLoader(testRunParams.scalaCheckParentClassLoader).asContext { + r.run(claas, fingerprint.get, handler, args.toArray) // synchronous? + } + val ok = (bad == 0) + if (!ok) _transcript append logFile.fileContents + ok } + try nextTestActionExpectTrue("ScalaCheck test failed", runInFramework()) finally logWriter.close() } def runResidentTest() = { @@ -626,3 +692,139 @@ class Runner(val testFile: File, fileManager: FileManager) { Directory(outDir).deleteRecursively() } } + +case class TestRunParams(val scalaCheckParentClassLoader: ScalaClassLoader) + +/** Extended by Ant- and ConsoleRunner for running a set of tests. */ +trait DirectRunner { + def fileManager: FileManager + + import PartestDefaults.{ numThreads, waitTime } + + Thread.setDefaultUncaughtExceptionHandler( + new Thread.UncaughtExceptionHandler { + def uncaughtException(thread: Thread, t: Throwable) { + val t1 = Exceptional unwrap t + System.err.println(s"Uncaught exception on thread $thread: $t1") + t1.printStackTrace() + } + } + ) + def runTestsForFiles(kindFiles: List[File], kind: String): List[TestState] = { + + NestUI.resetTestNumber(kindFiles.size) + + // this special class loader is for the benefit of scaladoc tests, which need a class path + import PathSettings.{ testInterface, scalaCheck } + val allUrls = scalaCheck.toURL :: testInterface.toURL :: fileManager.latestUrls + val parentClassLoader = ScalaClassLoader fromURLs allUrls + // add scalacheck.jar to a special classloader, but use our loader as parent with test-interface + //val parentClassLoader = ScalaClassLoader fromURLs (List(scalaCheck.toURL), getClass().getClassLoader) + val pool = Executors newFixedThreadPool numThreads + val manager = new RunnerManager(kind, fileManager, TestRunParams(parentClassLoader)) + val futures = kindFiles map (f => pool submit callable(manager runTest f)) + + pool.shutdown() + Try (pool.awaitTermination(waitTime) { + throw TimeoutException(waitTime) + }) match { + case Success(_) => futures map (_.get) + case Failure(e) => + e match { + case TimeoutException(d) => + NestUI warning "Thread pool timeout elapsed before all tests were complete!" + case ie: InterruptedException => + NestUI warning "Thread pool was interrupted" + ie.printStackTrace() + } + pool.shutdownNow() // little point in continuing + // try to get as many completions as possible, in case someone cares + val results = for (f <- futures) yield { + try { + Some(f.get(0, NANOSECONDS)) + } catch { + case _: Throwable => None + } + } + results.flatten + } + } +} + +case class TimeoutException(duration: Duration) extends RuntimeException + +class LogContext(val file: File, val writers: Option[(StringWriter, PrintWriter)]) + +object LogContext { + def apply(file: File, swr: StringWriter, wr: PrintWriter): LogContext = { + require (file != null) + new LogContext(file, Some((swr, wr))) + } + def apply(file: File): LogContext = new LogContext(file, None) +} + +object Output { + object outRedirect extends Redirecter(out) + object errRedirect extends Redirecter(err) + + System.setOut(outRedirect) + System.setErr(errRedirect) + + import scala.util.DynamicVariable + private def out = java.lang.System.out + private def err = java.lang.System.err + private val redirVar = new DynamicVariable[Option[PrintStream]](None) + + class Redirecter(stream: PrintStream) extends PrintStream(new OutputStream { + def write(b: Int) = withStream(_ write b) + + private def withStream(f: PrintStream => Unit) = f(redirVar.value getOrElse stream) + + override def write(b: Array[Byte]) = withStream(_ write b) + override def write(b: Array[Byte], off: Int, len: Int) = withStream(_.write(b, off, len)) + override def flush = withStream(_.flush) + override def close = withStream(_.close) + }) + + // this supports thread-safe nested output redirects + def withRedirected[T](newstream: PrintStream)(func: => T): T = { + // note down old redirect destination + // this may be None in which case outRedirect and errRedirect print to stdout and stderr + val saved = redirVar.value + // set new redirecter + // this one will redirect both out and err to newstream + redirVar.value = Some(newstream) + + try func + finally { + newstream.flush() + redirVar.value = saved + } + } +} + +/** Use a Runner to run a test. */ +class RunnerManager(kind: String, fileManager: FileManager, params: TestRunParams) { + import fileManager._ + fileManager.CLASSPATH += File.pathSeparator + PathSettings.scalaCheck + fileManager.CLASSPATH += File.pathSeparator + PathSettings.diffUtils // needed to put diffutils on test/partest's classpath + + def runTest(testFile: File): TestState = { + val runner = new Runner(testFile, fileManager, params) + + // when option "--failed" is provided execute test only if log + // is present (which means it failed before) + if (fileManager.failed && !runner.logFile.canRead) + runner.genPass() + else { + val (state, elapsed) = + try timed(runner.run()) + catch { + case t: Throwable => throw new RuntimeException(s"Error running $testFile", t) + } + NestUI.reportTest(state) + runner.cleanup() + state + } + } +} diff --git a/src/partest/scala/tools/partest/nest/RunnerManager.scala b/src/partest/scala/tools/partest/nest/RunnerManager.scala deleted file mode 100644 index fa2b5ea74b..0000000000 --- a/src/partest/scala/tools/partest/nest/RunnerManager.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* NEST (New Scala Test) - * Copyright 2007-2013 LAMP/EPFL - * @author Philipp Haller - */ - -package scala.tools.partest -package nest - -import java.io._ -import java.net.URL -import scala.tools.nsc.Properties.{ jdkHome, javaHome, propOrElse } -import scala.util.Properties.{ envOrElse, isWin } -import scala.tools.nsc.{ Settings, CompilerCommand, Global } -import scala.tools.nsc.io.{ AbstractFile, PlainFile, Path, Directory, File => SFile } -import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.util.{ ClassPath, FakePos, ScalaClassLoader, stackTraceString } -import ClassPath.{ join, split } -import scala.tools.scalap.scalax.rules.scalasig.ByteCode -import scala.collection.{ mutable, immutable } -import scala.sys.process._ -import java.util.concurrent.{ Executors, TimeUnit, TimeoutException } -import PartestDefaults.{ javaCmd, javacCmd } -import scala.tools.scalap.Main.decompileScala - -class LogContext(val file: File, val writers: Option[(StringWriter, PrintWriter)]) - -object LogContext { - def apply(file: File, swr: StringWriter, wr: PrintWriter): LogContext = { - require (file != null) - new LogContext(file, Some((swr, wr))) - } - def apply(file: File): LogContext = new LogContext(file, None) -} - -object Output { - object outRedirect extends Redirecter(out) - object errRedirect extends Redirecter(err) - - System.setOut(outRedirect) - System.setErr(errRedirect) - - import scala.util.DynamicVariable - private def out = java.lang.System.out - private def err = java.lang.System.err - private val redirVar = new DynamicVariable[Option[PrintStream]](None) - - class Redirecter(stream: PrintStream) extends PrintStream(new OutputStream { - def write(b: Int) = withStream(_ write b) - - private def withStream(f: PrintStream => Unit) = f(redirVar.value getOrElse stream) - - override def write(b: Array[Byte]) = withStream(_ write b) - override def write(b: Array[Byte], off: Int, len: Int) = withStream(_.write(b, off, len)) - override def flush = withStream(_.flush) - override def close = withStream(_.close) - }) - - // this supports thread-safe nested output redirects - def withRedirected[T](newstream: PrintStream)(func: => T): T = { - // note down old redirect destination - // this may be None in which case outRedirect and errRedirect print to stdout and stderr - val saved = redirVar.value - // set new redirecter - // this one will redirect both out and err to newstream - redirVar.value = Some(newstream) - - try func - finally { - newstream.flush() - redirVar.value = saved - } - } -} - -class RunnerManager(kind: String, val fileManager: FileManager, params: TestRunParams) { - import fileManager._ - - fileManager.CLASSPATH += File.pathSeparator + PathSettings.scalaCheck - fileManager.CLASSPATH += File.pathSeparator + PathSettings.diffUtils // needed to put diffutils on test/partest's classpath - PathSettings.platformTools foreach (fileManager.CLASSPATH += File.pathSeparator + _) - - def runTest(testFile: File): TestState = { - val runner = new Runner(testFile, fileManager) { - override def testRunParams = params - } - // when option "--failed" is provided execute test only if log - // is present (which means it failed before) - if (fileManager.failed && !runner.logFile.canRead) - runner.genPass() - else { - val (state, elapsed) = timed(runner.run()) - NestUI.reportTest(state) - runner.cleanup() - state - } - } -} diff --git a/src/partest/scala/tools/partest/package.scala b/src/partest/scala/tools/partest/package.scala index 9e21b0f6ba..4a516d620b 100644 --- a/src/partest/scala/tools/partest/package.scala +++ b/src/partest/scala/tools/partest/package.scala @@ -4,8 +4,9 @@ package scala.tools +import java.util.concurrent.{ Callable, ExecutorService } +import scala.concurrent.duration.Duration import scala.sys.process.javaVmArguments -import java.util.concurrent.Callable import scala.tools.partest.nest.NestUI import scala.tools.nsc.util.{ ScalaClassLoader, Exceptional } @@ -31,6 +32,8 @@ package object partest { def ojoin(xs: String*): String = oempty(xs: _*) mkString space def nljoin(xs: String*): String = oempty(xs: _*) mkString EOL + implicit val codec = scala.io.Codec.UTF8 + def setUncaughtHandler() = { Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler { @@ -85,6 +88,25 @@ package object partest { def copyTo(dest: Path): Unit = dest.toFile writeAll f.slurp(scala.io.Codec.UTF8) } + implicit class LoaderOps(val loader: ClassLoader) extends AnyVal { + import scala.util.control.Exception.catching + /** Like ScalaClassLoader.create for the case where the result type is + * available to the current class loader, implying that the current + * loader is a parent of `loader`. + */ + def instantiate[A >: Null](name: String): A = ( + catching(classOf[ClassNotFoundException], classOf[SecurityException]) opt + (loader loadClass name).newInstance.asInstanceOf[A] orNull + ) + } + + implicit class ExecutorOps(val executor: ExecutorService) { + def awaitTermination[A](wait: Duration)(failing: => A = ()): Option[A] = ( + if (executor awaitTermination (wait.length, wait.unit)) None + else Some(failing) + ) + } + implicit def temporaryPath2File(x: Path): File = x.jfile implicit def stringPathToJavaFile(path: String): File = new File(path) diff --git a/src/reflect/scala/reflect/api/Annotations.scala b/src/reflect/scala/reflect/api/Annotations.scala index f87e10c792..e19e0cefad 100644 --- a/src/reflect/scala/reflect/api/Annotations.scala +++ b/src/reflect/scala/reflect/api/Annotations.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api import scala.collection.immutable.ListMap diff --git a/src/reflect/scala/reflect/api/BuildUtils.scala b/src/reflect/scala/reflect/api/BuildUtils.scala index 8f256aa1f5..2e95a01176 100644 --- a/src/reflect/scala/reflect/api/BuildUtils.scala +++ b/src/reflect/scala/reflect/api/BuildUtils.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/Constants.scala b/src/reflect/scala/reflect/api/Constants.scala index 0b7dd5582a..c654961f4a 100644 --- a/src/reflect/scala/reflect/api/Constants.scala +++ b/src/reflect/scala/reflect/api/Constants.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/Exprs.scala b/src/reflect/scala/reflect/api/Exprs.scala index 2ba18a8207..009d9dbfdb 100644 --- a/src/reflect/scala/reflect/api/Exprs.scala +++ b/src/reflect/scala/reflect/api/Exprs.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package api import scala.reflect.runtime.{universe => ru} @@ -174,4 +175,4 @@ private[scala] class SerializedExpr(var treec: TreeCreator, var tag: ru.WeakType import ru._ Expr(rootMirror, treec)(tag) } -}
\ No newline at end of file +} diff --git a/src/reflect/scala/reflect/api/FlagSets.scala b/src/reflect/scala/reflect/api/FlagSets.scala index 712236cce1..8a1d2f7f1d 100644 --- a/src/reflect/scala/reflect/api/FlagSets.scala +++ b/src/reflect/scala/reflect/api/FlagSets.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api import scala.language.implicitConversions diff --git a/src/reflect/scala/reflect/api/ImplicitTags.scala b/src/reflect/scala/reflect/api/ImplicitTags.scala index fdc1d9017b..1b654a4a8d 100644 --- a/src/reflect/scala/reflect/api/ImplicitTags.scala +++ b/src/reflect/scala/reflect/api/ImplicitTags.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** Tags which preserve the identity of abstract types in the face of erasure. diff --git a/src/reflect/scala/reflect/api/Importers.scala b/src/reflect/scala/reflect/api/Importers.scala index afc4f2f25d..e6f314b712 100644 --- a/src/reflect/scala/reflect/api/Importers.scala +++ b/src/reflect/scala/reflect/api/Importers.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/JavaMirrors.scala b/src/reflect/scala/reflect/api/JavaMirrors.scala index b678033e1a..23abc23eb9 100644 --- a/src/reflect/scala/reflect/api/JavaMirrors.scala +++ b/src/reflect/scala/reflect/api/JavaMirrors.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/JavaUniverse.scala b/src/reflect/scala/reflect/api/JavaUniverse.scala index 04d091ee9d..6fc76c9693 100644 --- a/src/reflect/scala/reflect/api/JavaUniverse.scala +++ b/src/reflect/scala/reflect/api/JavaUniverse.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/Mirror.scala b/src/reflect/scala/reflect/api/Mirror.scala index 1223326d7c..e0219c9074 100644 --- a/src/reflect/scala/reflect/api/Mirror.scala +++ b/src/reflect/scala/reflect/api/Mirror.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** @@ -49,16 +50,16 @@ abstract class Mirror[U <: Universe with Singleton] { * If you need a symbol that corresponds to the type alias itself, load it directly from the package class: * * scala> cm.staticClass("scala.List") - * res0: reflect.runtime.universe.ClassSymbol = class List + * res0: scala.reflect.runtime.universe.ClassSymbol = class List * * scala> res0.fullName * res1: String = scala.collection.immutable.List * * scala> cm.staticPackage("scala") - * res2: reflect.runtime.universe.ModuleSymbol = package scala + * res2: scala.reflect.runtime.universe.ModuleSymbol = package scala * * scala> res2.moduleClass.typeSignature member newTypeName("List") - * res3: reflect.runtime.universe.Symbol = type List + * res3: scala.reflect.runtime.universe.Symbol = type List * * scala> res3.fullName * res4: String = scala.List diff --git a/src/reflect/scala/reflect/api/Mirrors.scala b/src/reflect/scala/reflect/api/Mirrors.scala index d30563c706..4fd9943379 100644 --- a/src/reflect/scala/reflect/api/Mirrors.scala +++ b/src/reflect/scala/reflect/api/Mirrors.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/Names.scala b/src/reflect/scala/reflect/api/Names.scala index e7840a13fb..f74e0ce014 100644 --- a/src/reflect/scala/reflect/api/Names.scala +++ b/src/reflect/scala/reflect/api/Names.scala @@ -1,6 +1,9 @@ -package scala.reflect +package scala +package reflect package api +import scala.language.implicitConversions + /** * <span class="badge badge-red" style="float: right;">EXPERIMENTAL</span> * diff --git a/src/reflect/scala/reflect/api/Position.scala b/src/reflect/scala/reflect/api/Position.scala index 63c67627a3..4d5f1f6e67 100644 --- a/src/reflect/scala/reflect/api/Position.scala +++ b/src/reflect/scala/reflect/api/Position.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api import scala.reflect.macros.Attachments diff --git a/src/reflect/scala/reflect/api/Positions.scala b/src/reflect/scala/reflect/api/Positions.scala index 6edf8e13e4..8ad46418f8 100644 --- a/src/reflect/scala/reflect/api/Positions.scala +++ b/src/reflect/scala/reflect/api/Positions.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/Printers.scala b/src/reflect/scala/reflect/api/Printers.scala index 162fe1296b..81d30dec1e 100644 --- a/src/reflect/scala/reflect/api/Printers.scala +++ b/src/reflect/scala/reflect/api/Printers.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api import java.io.{ PrintWriter, StringWriter } diff --git a/src/reflect/scala/reflect/api/Scopes.scala b/src/reflect/scala/reflect/api/Scopes.scala index 4bab6b6a04..2eb477f652 100644 --- a/src/reflect/scala/reflect/api/Scopes.scala +++ b/src/reflect/scala/reflect/api/Scopes.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/StandardDefinitions.scala b/src/reflect/scala/reflect/api/StandardDefinitions.scala index 721b0bc7f2..bbfebcb434 100644 --- a/src/reflect/scala/reflect/api/StandardDefinitions.scala +++ b/src/reflect/scala/reflect/api/StandardDefinitions.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/StandardNames.scala b/src/reflect/scala/reflect/api/StandardNames.scala index 6c78f18716..aec5f19fa0 100644 --- a/src/reflect/scala/reflect/api/StandardNames.scala +++ b/src/reflect/scala/reflect/api/StandardNames.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package api // Q: I have a pretty name. Can I put it here? diff --git a/src/reflect/scala/reflect/api/Symbols.scala b/src/reflect/scala/reflect/api/Symbols.scala index 7225919de5..1250545497 100644 --- a/src/reflect/scala/reflect/api/Symbols.scala +++ b/src/reflect/scala/reflect/api/Symbols.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/TagInterop.scala b/src/reflect/scala/reflect/api/TagInterop.scala index 5de811578e..51b7c519c5 100644 --- a/src/reflect/scala/reflect/api/TagInterop.scala +++ b/src/reflect/scala/reflect/api/TagInterop.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/TreeCreator.scala b/src/reflect/scala/reflect/api/TreeCreator.scala index 6969418470..027c840955 100644 --- a/src/reflect/scala/reflect/api/TreeCreator.scala +++ b/src/reflect/scala/reflect/api/TreeCreator.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** This is an internal implementation class. diff --git a/src/reflect/scala/reflect/api/Trees.scala b/src/reflect/scala/reflect/api/Trees.scala index 99b5ef87f8..f4ada814af 100644 --- a/src/reflect/scala/reflect/api/Trees.scala +++ b/src/reflect/scala/reflect/api/Trees.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/TypeCreator.scala b/src/reflect/scala/reflect/api/TypeCreator.scala index 24271cb48d..37fff90b43 100644 --- a/src/reflect/scala/reflect/api/TypeCreator.scala +++ b/src/reflect/scala/reflect/api/TypeCreator.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** A mirror-aware factory for types. diff --git a/src/reflect/scala/reflect/api/Types.scala b/src/reflect/scala/reflect/api/Types.scala index 1152f97350..9d2d06da69 100644 --- a/src/reflect/scala/reflect/api/Types.scala +++ b/src/reflect/scala/reflect/api/Types.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** @@ -209,6 +210,12 @@ trait Types { /******************* helpers *******************/ + /** Provides an alternate if type is NoType. + * + * @group Helpers + */ + def orElse(alt: => Type): Type + /** Substitute symbols in `to` for corresponding occurrences of references to * symbols `from` in this type. */ diff --git a/src/reflect/scala/reflect/api/Universe.scala b/src/reflect/scala/reflect/api/Universe.scala index 16e533cf7b..799fbd0dfb 100644 --- a/src/reflect/scala/reflect/api/Universe.scala +++ b/src/reflect/scala/reflect/api/Universe.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package api /** diff --git a/src/reflect/scala/reflect/api/package.scala b/src/reflect/scala/reflect/api/package.scala index dbda84dd0e..14dcc9247f 100644 --- a/src/reflect/scala/reflect/api/package.scala +++ b/src/reflect/scala/reflect/api/package.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect import scala.reflect.api.{Universe => ApiUniverse} diff --git a/src/reflect/scala/reflect/internal/AnnotationCheckers.scala b/src/reflect/scala/reflect/internal/AnnotationCheckers.scala index 73cc7fbbd6..74310e1c34 100644 --- a/src/reflect/scala/reflect/internal/AnnotationCheckers.scala +++ b/src/reflect/scala/reflect/internal/AnnotationCheckers.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal /** Additions to the type checker that can be added at diff --git a/src/reflect/scala/reflect/internal/AnnotationInfos.scala b/src/reflect/scala/reflect/internal/AnnotationInfos.scala index f9a026744c..90534a9865 100644 --- a/src/reflect/scala/reflect/internal/AnnotationInfos.scala +++ b/src/reflect/scala/reflect/internal/AnnotationInfos.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import pickling.ByteCodecs @@ -121,25 +122,32 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => * must be `String`. This specialised class is used to encode Scala * signatures for reasons of efficiency, both in term of class-file size * and in term of compiler performance. + * Details about the storage format of pickles at the bytecode level (classfile annotations) can be found in SIP-10. */ case class ScalaSigBytes(bytes: Array[Byte]) extends ClassfileAnnotArg { override def toString = (bytes map { byte => (byte & 0xff).toHexString }).mkString("[ ", " ", " ]") - lazy val encodedBytes = ByteCodecs.encode(bytes) // TODO remove after migration to ASM-based GenJVM complete - def isLong: Boolean = (encodedBytes.length > 65535) // TODO remove after migration to ASM-based GenJVM complete lazy val sevenBitsMayBeZero: Array[Byte] = { mapToNextModSevenBits(scala.reflect.internal.pickling.ByteCodecs.encode8to7(bytes)) } + + /* In order to store a byte array (the pickle) using a bytecode-level annotation, + * the most compact representation is used (which happens to be string-constant and not byte array as one would expect). + * However, a String constant in a classfile annotation is limited to a maximum of 65535 characters. + * Method `fitsInOneString` tells us whether the pickle can be held by a single classfile-annotation of string-type. + * Otherwise an array of strings will be used. + */ def fitsInOneString: Boolean = { + // due to escaping, a zero byte in a classfile-annotation of string-type takes actually two characters. val numZeros = (sevenBitsMayBeZero count { b => b == 0 }) - val res = (sevenBitsMayBeZero.length + numZeros) <= 65535 - assert(this.isLong == !res, "As things stand, can't just swap in `fitsInOneString()` for `isLong()`") - res + + (sevenBitsMayBeZero.length + numZeros) <= 65535 } + def sigAnnot: Type = - if (this.isLong) - definitions.ScalaLongSignatureAnnotation.tpe - else + if (fitsInOneString) definitions.ScalaSignatureAnnotation.tpe + else + definitions.ScalaLongSignatureAnnotation.tpe private def mapToNextModSevenBits(src: Array[Byte]): Array[Byte] = { var i = 0 diff --git a/src/reflect/scala/reflect/internal/BaseTypeSeqs.scala b/src/reflect/scala/reflect/internal/BaseTypeSeqs.scala index 9daf9504f1..66eddd7ec0 100644 --- a/src/reflect/scala/reflect/internal/BaseTypeSeqs.scala +++ b/src/reflect/scala/reflect/internal/BaseTypeSeqs.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal // todo implement in terms of BitSet diff --git a/src/reflect/scala/reflect/internal/BuildUtils.scala b/src/reflect/scala/reflect/internal/BuildUtils.scala index 175943d264..ece2d28be3 100644 --- a/src/reflect/scala/reflect/internal/BuildUtils.scala +++ b/src/reflect/scala/reflect/internal/BuildUtils.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal trait BuildUtils { self: SymbolTable => diff --git a/src/reflect/scala/reflect/internal/CapturedVariables.scala b/src/reflect/scala/reflect/internal/CapturedVariables.scala index c262c8474a..2c5e87b95d 100644 --- a/src/reflect/scala/reflect/internal/CapturedVariables.scala +++ b/src/reflect/scala/reflect/internal/CapturedVariables.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import Flags._ diff --git a/src/reflect/scala/reflect/internal/Chars.scala b/src/reflect/scala/reflect/internal/Chars.scala index 2d07092862..74413fdaba 100644 --- a/src/reflect/scala/reflect/internal/Chars.scala +++ b/src/reflect/scala/reflect/internal/Chars.scala @@ -2,7 +2,8 @@ * Copyright 2006-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.annotation.{ tailrec, switch } diff --git a/src/reflect/scala/reflect/internal/ClassfileConstants.scala b/src/reflect/scala/reflect/internal/ClassfileConstants.scala index b682b7d0ca..a7ce044780 100644 --- a/src/reflect/scala/reflect/internal/ClassfileConstants.scala +++ b/src/reflect/scala/reflect/internal/ClassfileConstants.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.annotation.switch diff --git a/src/reflect/scala/reflect/internal/Constants.scala b/src/reflect/scala/reflect/internal/Constants.scala index 5ed2f675b2..905c7caa52 100644 --- a/src/reflect/scala/reflect/internal/Constants.scala +++ b/src/reflect/scala/reflect/internal/Constants.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import java.lang.Integer.toOctalString diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index 5392daf674..a0ddc1e1b2 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -3,9 +3,11 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal +import scala.language.postfixOps import scala.annotation.{ switch, meta } import scala.collection.{ mutable, immutable } import Flags._ @@ -322,7 +324,9 @@ trait Definitions extends api.StandardDefinitions { lazy val ThrowableClass = getClassByName(sn.Throwable) lazy val UninitializedErrorClass = requiredClass[UninitializedFieldError] + @deprecated("Same effect but more compact: `throw null`. Details in JVM spec, `athrow` instruction.", "2.11.0") lazy val NPEConstructor = getMemberMethod(NullPointerExceptionClass, nme.CONSTRUCTOR) suchThat (_.paramss.flatten.isEmpty) + lazy val UninitializedFieldConstructor = UninitializedErrorClass.primaryConstructor // fundamental reference classes @@ -403,6 +407,10 @@ trait Definitions extends api.StandardDefinitions { lazy val JavaRepeatedParamClass = specialPolyClass(tpnme.JAVA_REPEATED_PARAM_CLASS_NAME, COVARIANT)(tparam => arrayType(tparam.tpe)) lazy val RepeatedParamClass = specialPolyClass(tpnme.REPEATED_PARAM_CLASS_NAME, COVARIANT)(tparam => seqType(tparam.tpe)) + def dropByName(tp: Type): Type = tp match { + case TypeRef(_, ByNameParamClass, arg :: Nil) => arg + case _ => tp + } def isByNameParamType(tp: Type) = tp.typeSymbol == ByNameParamClass def isScalaRepeatedParamType(tp: Type) = tp.typeSymbol == RepeatedParamClass def isJavaRepeatedParamType(tp: Type) = tp.typeSymbol == JavaRepeatedParamClass diff --git a/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala b/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala index 34bd400186..6251849182 100644 --- a/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala +++ b/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.collection.{ mutable, immutable } diff --git a/src/reflect/scala/reflect/internal/FatalError.scala b/src/reflect/scala/reflect/internal/FatalError.scala index a084fc24f3..08a9a635af 100644 --- a/src/reflect/scala/reflect/internal/FatalError.scala +++ b/src/reflect/scala/reflect/internal/FatalError.scala @@ -2,5 +2,6 @@ * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect.internal +package scala +package reflect.internal case class FatalError(msg: String) extends Exception(msg) diff --git a/src/reflect/scala/reflect/internal/FlagSets.scala b/src/reflect/scala/reflect/internal/FlagSets.scala index 6a3b6870a0..961adb2c57 100644 --- a/src/reflect/scala/reflect/internal/FlagSets.scala +++ b/src/reflect/scala/reflect/internal/FlagSets.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import scala.language.implicitConversions diff --git a/src/reflect/scala/reflect/internal/Flags.scala b/src/reflect/scala/reflect/internal/Flags.scala index fe46a0471e..1d5fe3685c 100644 --- a/src/reflect/scala/reflect/internal/Flags.scala +++ b/src/reflect/scala/reflect/internal/Flags.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.collection.{ mutable, immutable } diff --git a/src/reflect/scala/reflect/internal/HasFlags.scala b/src/reflect/scala/reflect/internal/HasFlags.scala index 6f8befd23e..420b5fef81 100644 --- a/src/reflect/scala/reflect/internal/HasFlags.scala +++ b/src/reflect/scala/reflect/internal/HasFlags.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import Flags._ diff --git a/src/reflect/scala/reflect/internal/Importers.scala b/src/reflect/scala/reflect/internal/Importers.scala index f736202e13..b0d3cda629 100644 --- a/src/reflect/scala/reflect/internal/Importers.scala +++ b/src/reflect/scala/reflect/internal/Importers.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import scala.collection.mutable.WeakHashMap diff --git a/src/reflect/scala/reflect/internal/InfoTransformers.scala b/src/reflect/scala/reflect/internal/InfoTransformers.scala index 4e84a29fd0..3814259e22 100644 --- a/src/reflect/scala/reflect/internal/InfoTransformers.scala +++ b/src/reflect/scala/reflect/internal/InfoTransformers.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal trait InfoTransformers { diff --git a/src/reflect/scala/reflect/internal/JMethodOrConstructor.scala b/src/reflect/scala/reflect/internal/JMethodOrConstructor.scala index 3d1d1bf451..fb1cdb34e1 100644 --- a/src/reflect/scala/reflect/internal/JMethodOrConstructor.scala +++ b/src/reflect/scala/reflect/internal/JMethodOrConstructor.scala @@ -2,9 +2,11 @@ * Copyright 2005-2013 LAMP/EPFL * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package internal +import scala.language.implicitConversions import java.lang.{ Class => jClass } import java.lang.annotation.{ Annotation => jAnnotation } import java.lang.reflect.{ diff --git a/src/reflect/scala/reflect/internal/JavaAccFlags.scala b/src/reflect/scala/reflect/internal/JavaAccFlags.scala index 4be1f828d3..0a33b8cf0d 100644 --- a/src/reflect/scala/reflect/internal/JavaAccFlags.scala +++ b/src/reflect/scala/reflect/internal/JavaAccFlags.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package internal import java.lang.{ Class => jClass } diff --git a/src/reflect/scala/reflect/internal/Kinds.scala b/src/reflect/scala/reflect/internal/Kinds.scala index 3c49aef05a..4612e65e7a 100644 --- a/src/reflect/scala/reflect/internal/Kinds.scala +++ b/src/reflect/scala/reflect/internal/Kinds.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.collection.{ mutable, immutable } diff --git a/src/reflect/scala/reflect/internal/Mirrors.scala b/src/reflect/scala/reflect/internal/Mirrors.scala index 81d7619f22..bf38c3bf1e 100644 --- a/src/reflect/scala/reflect/internal/Mirrors.scala +++ b/src/reflect/scala/reflect/internal/Mirrors.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import Flags._ @@ -35,7 +36,7 @@ trait Mirrors extends api.Mirrors { else definitions.findNamedMember(segs.tail, RootClass.info member segs.head) } - /** Todo: organize similar to mkStatic in reflect.Base */ + /** Todo: organize similar to mkStatic in scala.reflect.Base */ private def getModuleOrClass(path: Name, len: Int): Symbol = { val point = path lastPos('.', len - 1) val owner = diff --git a/src/reflect/scala/reflect/internal/MissingRequirementError.scala b/src/reflect/scala/reflect/internal/MissingRequirementError.scala index 48203caa83..66dbf535d7 100644 --- a/src/reflect/scala/reflect/internal/MissingRequirementError.scala +++ b/src/reflect/scala/reflect/internal/MissingRequirementError.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal class MissingRequirementError private (msg: String) extends FatalError(msg) { diff --git a/src/reflect/scala/reflect/internal/Mode.scala b/src/reflect/scala/reflect/internal/Mode.scala index 850e3b5669..516e96cbb3 100644 --- a/src/reflect/scala/reflect/internal/Mode.scala +++ b/src/reflect/scala/reflect/internal/Mode.scala @@ -3,9 +3,12 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal +import scala.language.implicitConversions + object Mode { private implicit def liftIntBitsToMode(bits: Int): Mode = apply(bits) def apply(bits: Int): Mode = new Mode(bits) @@ -95,7 +98,7 @@ object Mode { /** Translates a mask of mode flags into something readable. */ - private val modeNameMap = Map[Int, String]( + private val modeNameMap = Map[Int, String]( // TODO why duplicate the bitmasks here, rather than just referring to this.EXPRmode etc? (1 << 0) -> "EXPRmode", (1 << 1) -> "PATTERNmode", (1 << 2) -> "TYPEmode", diff --git a/src/reflect/scala/reflect/internal/Names.scala b/src/reflect/scala/reflect/internal/Names.scala index b8141d25f5..ed5b92565d 100644 --- a/src/reflect/scala/reflect/internal/Names.scala +++ b/src/reflect/scala/reflect/internal/Names.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.io.Codec diff --git a/src/reflect/scala/reflect/internal/Phase.scala b/src/reflect/scala/reflect/internal/Phase.scala index c0f4232724..450c90ed56 100644 --- a/src/reflect/scala/reflect/internal/Phase.scala +++ b/src/reflect/scala/reflect/internal/Phase.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal abstract class Phase(val prev: Phase) { diff --git a/src/reflect/scala/reflect/internal/Positions.scala b/src/reflect/scala/reflect/internal/Positions.scala index 3cf4f4a1df..eef8159ad4 100644 --- a/src/reflect/scala/reflect/internal/Positions.scala +++ b/src/reflect/scala/reflect/internal/Positions.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import util._ diff --git a/src/reflect/scala/reflect/internal/Printers.scala b/src/reflect/scala/reflect/internal/Printers.scala index 5b80889225..1603029340 100644 --- a/src/reflect/scala/reflect/internal/Printers.scala +++ b/src/reflect/scala/reflect/internal/Printers.scala @@ -5,7 +5,8 @@ // todo. we need to unify this prettyprinter with NodePrinters -package scala.reflect +package scala +package reflect package internal import java.io.{ OutputStream, PrintWriter, StringWriter, Writer } @@ -421,13 +422,20 @@ trait Printers extends api.Printers { self: SymbolTable => print(tp); printRow(args, "[", ", ", "]") case TypeBoundsTree(lo, hi) => - printOpt(" >: ", lo); printOpt(" <: ", hi) + // Avoid printing noisy empty typebounds everywhere + // Untyped empty bounds are not printed by printOpt, + // but after they are typed we have to exclude Nothing/Any. + if ((lo.tpe eq null) || !(lo.tpe =:= definitions.NothingTpe)) + printOpt(" >: ", lo) + + if ((hi.tpe eq null) || !(hi.tpe =:= definitions.AnyTpe)) + printOpt(" <: ", hi) case ExistentialTypeTree(tpt, whereClauses) => print(tpt) printColumn(whereClauses, " forSome { ", ";", "}") -// SelectFromArray is no longer visible in reflect.internal. +// SelectFromArray is no longer visible in scala.reflect.internal. // eliminated until we figure out what we will do with both Printers and // SelectFromArray. // case SelectFromArray(qualifier, name, _) => diff --git a/src/reflect/scala/reflect/internal/PrivateWithin.scala b/src/reflect/scala/reflect/internal/PrivateWithin.scala index 5646ac82ae..996f9c13bb 100644 --- a/src/reflect/scala/reflect/internal/PrivateWithin.scala +++ b/src/reflect/scala/reflect/internal/PrivateWithin.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import java.lang.{ Class => jClass } diff --git a/src/reflect/scala/reflect/internal/Required.scala b/src/reflect/scala/reflect/internal/Required.scala index 93383f5376..14db252a16 100644 --- a/src/reflect/scala/reflect/internal/Required.scala +++ b/src/reflect/scala/reflect/internal/Required.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import settings.MutableSettings diff --git a/src/reflect/scala/reflect/internal/Scopes.scala b/src/reflect/scala/reflect/internal/Scopes.scala index 371eddbc4f..8d20c8e546 100644 --- a/src/reflect/scala/reflect/internal/Scopes.scala +++ b/src/reflect/scala/reflect/internal/Scopes.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.annotation.tailrec diff --git a/src/reflect/scala/reflect/internal/StdAttachments.scala b/src/reflect/scala/reflect/internal/StdAttachments.scala index 6c5bbc9774..9eb66db01e 100644 --- a/src/reflect/scala/reflect/internal/StdAttachments.scala +++ b/src/reflect/scala/reflect/internal/StdAttachments.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal trait StdAttachments { diff --git a/src/reflect/scala/reflect/internal/StdCreators.scala b/src/reflect/scala/reflect/internal/StdCreators.scala index 5e5e4f9043..a0084dc95c 100644 --- a/src/reflect/scala/reflect/internal/StdCreators.scala +++ b/src/reflect/scala/reflect/internal/StdCreators.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal import scala.reflect.api.{TreeCreator, TypeCreator} diff --git a/src/reflect/scala/reflect/internal/StdNames.scala b/src/reflect/scala/reflect/internal/StdNames.scala index ae2cf09c2e..a20307882d 100644 --- a/src/reflect/scala/reflect/internal/StdNames.scala +++ b/src/reflect/scala/reflect/internal/StdNames.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import java.security.MessageDigest @@ -589,6 +590,7 @@ trait StdNames { val clone_ : NameType = "clone" val conforms: NameType = "conforms" val copy: NameType = "copy" + val create: NameType = "create" val currentMirror: NameType = "currentMirror" val delayedInit: NameType = "delayedInit" val delayedInitArg: NameType = "delayedInit$body" @@ -697,6 +699,7 @@ trait StdNames { val view_ : NameType = "view" val wait_ : NameType = "wait" val withFilter: NameType = "withFilter" + val zero: NameType = "zero" // unencoded operators object raw { diff --git a/src/reflect/scala/reflect/internal/SymbolTable.scala b/src/reflect/scala/reflect/internal/SymbolTable.scala index 336c2748c6..01cf0dd8d7 100644 --- a/src/reflect/scala/reflect/internal/SymbolTable.scala +++ b/src/reflect/scala/reflect/internal/SymbolTable.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.annotation.elidable @@ -47,6 +48,7 @@ abstract class SymbolTable extends macros.Universe def log(msg: => AnyRef): Unit def warning(msg: String): Unit = Console.err.println(msg) + def inform(msg: String): Unit = Console.err.println(msg) def globalError(msg: String): Unit = abort(msg) def abort(msg: String): Nothing = throw new FatalError(supplementErrorMessage(msg)) diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala index a87d002f25..9c706f650e 100644 --- a/src/reflect/scala/reflect/internal/Symbols.scala +++ b/src/reflect/scala/reflect/internal/Symbols.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.collection.{ mutable, immutable } @@ -659,8 +660,29 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def hasGetter = isTerm && nme.isLocalName(name) + /** A little explanation for this confusing situation. + * Nested modules which have no static owner when ModuleDefs + * are eliminated (refchecks) are given the lateMETHOD flag, + * which makes them appear as methods after refchecks. + * Here's an example where one can see all four of FF FT TF TT + * for (isStatic, isMethod) at various phases. + * + * trait A1 { case class Quux() } + * object A2 extends A1 { object Flax } + * // -- namer object Quux in trait A1 + * // -M flatten object Quux in trait A1 + * // S- flatten object Flax in object A2 + * // -M posterasure object Quux in trait A1 + * // -M jvm object Quux in trait A1 + * // SM jvm object Quux in object A2 + * + * So "isModuleNotMethod" exists not for its achievement in + * brevity, but to encapsulate the relevant condition. + */ + def isModuleNotMethod = isModule && !isMethod + def isStaticModule = isModuleNotMethod && isStatic + final def isInitializedToDefault = !isType && hasAllFlags(DEFAULTINIT | ACCESSOR) - final def isStaticModule = isModule && isStatic && !isMethod final def isThisSym = isTerm && owner.thisSym == this final def isError = hasFlag(IS_ERROR) final def isErroneous = isError || isInitialized && tpe_*.isErroneous @@ -1110,12 +1132,13 @@ trait Symbols extends api.Symbols { self: SymbolTable => new TermSymbol(this, pos, name) initFlags newFlags final def newTermSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = { - if ((newFlags & METHOD) != 0) - createMethodSymbol(name, pos, newFlags) - else if ((newFlags & PACKAGE) != 0) + // Package before Module, Module before Method, or we might grab the wrong guy. + if ((newFlags & PACKAGE) != 0) createPackageSymbol(name, pos, newFlags | PackageFlags) else if ((newFlags & MODULE) != 0) createModuleSymbol(name, pos, newFlags) + else if ((newFlags & METHOD) != 0) + createMethodSymbol(name, pos, newFlags) else if ((newFlags & PARAM) != 0) createValueParameterSymbol(name, pos, newFlags) else @@ -3027,8 +3050,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => * returned, otherwise, `NoSymbol` is returned. */ protected final def companionModule0: Symbol = - flatOwnerInfo.decl(name.toTermName).suchThat( - sym => sym.isModule && (sym isCoDefinedWith this) && !sym.isMethod) + flatOwnerInfo.decl(name.toTermName).suchThat(sym => sym.isModuleNotMethod && (sym isCoDefinedWith this)) override def companionModule = companionModule0 override def companionSymbol = companionModule0 diff --git a/src/reflect/scala/reflect/internal/TreeGen.scala b/src/reflect/scala/reflect/internal/TreeGen.scala index d3e486311e..d25189516e 100644 --- a/src/reflect/scala/reflect/internal/TreeGen.scala +++ b/src/reflect/scala/reflect/internal/TreeGen.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal abstract class TreeGen extends macros.TreeBuilder { @@ -298,4 +299,9 @@ abstract class TreeGen extends macros.TreeBuilder { def mkPackageDef(packageName: String, stats: List[Tree]): PackageDef = { PackageDef(mkUnattributedRef(newTermName(packageName)), stats) } + + def mkSeqApply(arg: Tree): Apply = { + val factory = Select(gen.mkAttributedRef(SeqModule), nme.apply) + Apply(factory, List(arg)) + } } diff --git a/src/reflect/scala/reflect/internal/TreeInfo.scala b/src/reflect/scala/reflect/internal/TreeInfo.scala index 3296353b6b..2f1b3208df 100644 --- a/src/reflect/scala/reflect/internal/TreeInfo.scala +++ b/src/reflect/scala/reflect/internal/TreeInfo.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import Flags._ @@ -17,7 +18,7 @@ abstract class TreeInfo { val global: SymbolTable import global._ - import definitions.{ isVarArgsList, isCastSymbol, ThrowableClass, TupleClass, MacroContextClass, MacroContextPrefixType } + import definitions.{ isTupleSymbol, isVarArgsList, isCastSymbol, ThrowableClass, TupleClass, MacroContextClass, MacroContextPrefixType } /* Does not seem to be used. Not sure what it does anyway. def isOwnerDefinition(tree: Tree): Boolean = tree match { @@ -401,8 +402,15 @@ abstract class TreeInfo { /** Is this argument node of the form <expr> : _* ? */ def isWildcardStarArg(tree: Tree): Boolean = tree match { - case Typed(_, Ident(tpnme.WILDCARD_STAR)) => true - case _ => false + case WildcardStarArg(_) => true + case _ => false + } + + object WildcardStarArg { + def unapply(tree: Typed): Option[Tree] = tree match { + case Typed(expr, Ident(tpnme.WILDCARD_STAR)) => Some(expr) + case _ => None + } } /** If this tree has type parameters, those. Otherwise Nil. @@ -524,6 +532,20 @@ abstract class TreeInfo { case _ => false } + /** + * {{{ + * //------------------------ => effectivePatternArity(args) + * case Extractor(a) => 1 + * case Extractor(a, b) => 2 + * case Extractor((a, b)) => 2 + * case Extractor(a @ (b, c)) => 2 + * }}} + */ + def effectivePatternArity(args: List[Tree]): Int = (args.map(unbind) match { + case Apply(fun, xs) :: Nil if isTupleSymbol(fun.symbol) => xs + case xs => xs + }).length + // used in the symbols for labeldefs and valdefs emitted by the pattern matcher // tailcalls, cps,... use this flag combination to detect translated matches diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index 7467ccc6b9..de0b4e8247 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import Flags._ @@ -1649,6 +1650,21 @@ trait Trees extends api.Trees { self: SymbolTable => sys.error("Not a ClassDef: " + t + "/" + t.getClass) } + def copyModuleDef(tree: Tree)( + mods: Modifiers = null, + name: Name = null, + impl: Template = null + ): ModuleDef = tree match { + case ModuleDef(mods0, name0, impl0) => + treeCopy.ModuleDef(tree, + if (mods eq null) mods0 else mods, + if (name eq null) name0 else name, + if (impl eq null) impl0 else impl + ) + case t => + sys.error("Not a ModuleDef: " + t + "/" + t.getClass) + } + def deriveDefDef(ddef: Tree)(applyToRhs: Tree => Tree): DefDef = ddef match { case DefDef(mods0, name0, tparams0, vparamss0, tpt0, rhs0) => treeCopy.DefDef(ddef, mods0, name0, tparams0, vparamss0, tpt0, applyToRhs(rhs0)) diff --git a/src/reflect/scala/reflect/internal/TypeDebugging.scala b/src/reflect/scala/reflect/internal/TypeDebugging.scala index d437b1b058..71f84ab557 100644 --- a/src/reflect/scala/reflect/internal/TypeDebugging.scala +++ b/src/reflect/scala/reflect/internal/TypeDebugging.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package internal trait TypeDebugging { diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index cd41f533bb..a8fc55e677 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import scala.collection.{ mutable, immutable, generic } @@ -742,6 +743,8 @@ trait Types def map[T](f: Type => T): List[T] = collect(Type.this) map f } + @inline final def orElse(alt: => Type): Type = if (this ne NoType) this else alt + /** Returns optionally first type (in a preorder traversal) which satisfies predicate `p`, * or None if none exists. */ @@ -4327,7 +4330,7 @@ trait Types // transpose freaked out because of irregular argss // catching just in case (shouldn't happen, but also doesn't cost us) // [JZ] It happens: see SI-5683. - debuglog("transposed irregular matrix!?" +(tps, argss)) + debuglog(s"transposed irregular matrix!? tps=$tps argss=$argss") None case Some(argsst) => val args = map2(sym.typeParams, argsst) { (tparam, as0) => @@ -4432,11 +4435,11 @@ trait Types /** Perform operation `p` on arguments `tp1`, `arg2` and print trace of computation. */ protected def explain[T](op: String, p: (Type, T) => Boolean, tp1: Type, arg2: T): Boolean = { - Console.println(indent + tp1 + " " + op + " " + arg2 + "?" /* + "("+tp1.getClass+","+arg2.getClass+")"*/) + inform(indent + tp1 + " " + op + " " + arg2 + "?" /* + "("+tp1.getClass+","+arg2.getClass+")"*/) indent = indent + " " val result = p(tp1, arg2) indent = indent stripSuffix " " - Console.println(indent + result) + inform(indent + result) result } diff --git a/src/reflect/scala/reflect/internal/Variance.scala b/src/reflect/scala/reflect/internal/Variance.scala index 007d56eb35..3480161567 100644 --- a/src/reflect/scala/reflect/internal/Variance.scala +++ b/src/reflect/scala/reflect/internal/Variance.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package internal import Variance._ diff --git a/src/reflect/scala/reflect/internal/Variances.scala b/src/reflect/scala/reflect/internal/Variances.scala index 716e49b303..78df3c9617 100644 --- a/src/reflect/scala/reflect/internal/Variances.scala +++ b/src/reflect/scala/reflect/internal/Variances.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal import Variance._ diff --git a/src/reflect/scala/reflect/internal/annotations/compileTimeOnly.scala b/src/reflect/scala/reflect/internal/annotations/compileTimeOnly.scala index 058ff61fbf..2c9f909629 100644 --- a/src/reflect/scala/reflect/internal/annotations/compileTimeOnly.scala +++ b/src/reflect/scala/reflect/internal/annotations/compileTimeOnly.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package annotations diff --git a/src/reflect/scala/reflect/internal/pickling/ByteCodecs.scala b/src/reflect/scala/reflect/internal/pickling/ByteCodecs.scala index 367a3b8b19..18d7e05c4c 100644 --- a/src/reflect/scala/reflect/internal/pickling/ByteCodecs.scala +++ b/src/reflect/scala/reflect/internal/pickling/ByteCodecs.scala @@ -5,7 +5,8 @@ ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ -package scala.reflect.internal.pickling +package scala +package reflect.internal.pickling object ByteCodecs { @@ -195,10 +196,10 @@ object ByteCodecs { * * Sometimes returns (length+1) of the decoded array. Example: * - * scala> val enc = reflect.generic.ByteCodecs.encode(Array(1,2,3)) + * scala> val enc = scala.reflect.generic.ByteCodecs.encode(Array(1,2,3)) * enc: Array[Byte] = Array(2, 5, 13, 1) * - * scala> reflect.generic.ByteCodecs.decode(enc) + * scala> scala.reflect.generic.ByteCodecs.decode(enc) * res43: Int = 4 * * scala> enc diff --git a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala index c9dfb7fe71..c953b5df22 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal package pickling diff --git a/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala b/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala index 3722c77aa2..ce0ceec688 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package pickling diff --git a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala index c940d863f7..6cffdbc193 100644 --- a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala +++ b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package internal package pickling @@ -851,7 +852,8 @@ abstract class UnPickler { private val p = phase override def complete(sym: Symbol) : Unit = try { val tp = at(i, () => readType(sym.isTerm)) // after NMT_TRANSITION, revert `() => readType(sym.isTerm)` to `readType` - enteringPhase(p) (sym setInfo tp) + if (p ne null) + enteringPhase(p) (sym setInfo tp) if (currentRunId != definedAtRunId) sym.setInfo(adaptToNewRunMap(tp)) } diff --git a/src/reflect/scala/reflect/internal/settings/AbsSettings.scala b/src/reflect/scala/reflect/internal/settings/AbsSettings.scala index a6fb4187ca..859f703d97 100644 --- a/src/reflect/scala/reflect/internal/settings/AbsSettings.scala +++ b/src/reflect/scala/reflect/internal/settings/AbsSettings.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect.internal +package scala +package reflect.internal package settings /** A Settings abstraction boiled out of the original highly mutable Settings diff --git a/src/reflect/scala/reflect/internal/settings/MutableSettings.scala b/src/reflect/scala/reflect/internal/settings/MutableSettings.scala index 68f9fc8e83..e21e95903b 100644 --- a/src/reflect/scala/reflect/internal/settings/MutableSettings.scala +++ b/src/reflect/scala/reflect/internal/settings/MutableSettings.scala @@ -4,7 +4,8 @@ */ // $Id$ -package scala.reflect.internal +package scala +package reflect.internal package settings /** A mutable Settings object. diff --git a/src/reflect/scala/reflect/internal/tpe/CommonOwners.scala b/src/reflect/scala/reflect/internal/tpe/CommonOwners.scala index e5ddd8f359..f879960407 100644 --- a/src/reflect/scala/reflect/internal/tpe/CommonOwners.scala +++ b/src/reflect/scala/reflect/internal/tpe/CommonOwners.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package tpe diff --git a/src/reflect/scala/reflect/internal/tpe/GlbLubs.scala b/src/reflect/scala/reflect/internal/tpe/GlbLubs.scala index 921d2e3d66..2da9960c81 100644 --- a/src/reflect/scala/reflect/internal/tpe/GlbLubs.scala +++ b/src/reflect/scala/reflect/internal/tpe/GlbLubs.scala @@ -1,8 +1,10 @@ -package scala.reflect +package scala +package reflect package internal package tpe -import scala.collection.{ mutable } +import scala.collection.mutable +import scala.annotation.tailrec import util.Statistics import Variance._ @@ -11,7 +13,7 @@ private[internal] trait GlbLubs { import definitions._ import TypesStats._ - private final val printLubs = sys.props contains "scalac.debug.lub" + private final val printLubs = scala.sys.props contains "scalac.debug.lub" /** In case anyone wants to turn off lub verification without reverting anything. */ private final val verifyLubs = true @@ -86,7 +88,7 @@ private[internal] trait GlbLubs { case _ => tp } // pretypes is a tail-recursion-preserving accumulator. - @annotation.tailrec def loop(pretypes: List[Type], tsBts: List[List[Type]]): List[Type] = { + @tailrec def loop(pretypes: List[Type], tsBts: List[List[Type]]): List[Type] = { lubListDepth += 1 if (tsBts.isEmpty || (tsBts exists typeListIsEmpty)) pretypes.reverse @@ -214,11 +216,34 @@ private[internal] trait GlbLubs { (strippedTypes, quantified) } - def weakLub(ts: List[Type]) = - if (ts.nonEmpty && (ts forall isNumericValueType)) (numericLub(ts), true) - else if (ts exists typeHasAnnotations) - (annotationsLub(lub(ts map (_.withoutAnnotations)), ts), true) - else (lub(ts), false) + /** Does this set of types have the same weak lub as + * it does regular lub? This is exposed so lub callers + * can discover whether the trees they are typing will + * may require further adaptation. It may return false + * negatives, but it will not return false positives. + */ + def sameWeakLubAsLub(tps: List[Type]) = tps match { + case Nil => true + case tp :: Nil => !typeHasAnnotations(tp) + case tps => !(tps exists typeHasAnnotations) && !(tps forall isNumericValueType) + } + + /** If the arguments are all numeric value types, the numeric + * lub according to the weak conformance spec. If any argument + * has type annotations, take the lub of the unannotated type + * and call the analyzerPlugin method annotationsLub so it can + * be further altered. Otherwise, the regular lub. + */ + def weakLub(tps: List[Type]): Type = ( + if (tps.isEmpty) + NothingClass.tpe + else if (tps forall isNumericValueType) + numericLub(tps) + else if (tps exists typeHasAnnotations) + annotationsLub(lub(tps map (_.withoutAnnotations)), tps) + else + lub(tps) + ) def numericLub(ts: List[Type]) = ts reduceLeft ((t1, t2) => @@ -247,9 +272,9 @@ private[internal] trait GlbLubs { } def lub(ts: List[Type]): Type = ts match { - case List() => NothingClass.tpe - case List(t) => t - case _ => + case Nil => NothingClass.tpe + case t :: Nil => t + case _ => if (Statistics.canEnable) Statistics.incCounter(lubCount) val start = if (Statistics.canEnable) Statistics.pushTimer(typeOpsStack, lubNanos) else null try { @@ -291,7 +316,7 @@ private[internal] trait GlbLubs { case ts @ AnnotatedType(annots, tpe, _) :: rest => annotationsLub(lub0(ts map (_.withoutAnnotations)), ts) case ts => - lubResults get (depth, ts) match { + lubResults get ((depth, ts)) match { case Some(lubType) => lubType case None => @@ -449,7 +474,7 @@ private[internal] trait GlbLubs { case ts @ TypeBounds(_, _) :: rest => TypeBounds(lub(ts map (_.bounds.lo), depth), glb(ts map (_.bounds.hi), depth)) case ts => - glbResults get (depth, ts) match { + glbResults get ((depth, ts)) match { case Some(glbType) => glbType case _ => diff --git a/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala b/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala index c1fb0c0107..711a94d7bd 100644 --- a/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala +++ b/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala @@ -1,9 +1,9 @@ -package scala.reflect +package scala +package reflect package internal package tpe import scala.collection.{ mutable } -import Flags._ import util.Statistics import scala.annotation.tailrec diff --git a/src/reflect/scala/reflect/internal/tpe/TypeConstraints.scala b/src/reflect/scala/reflect/internal/tpe/TypeConstraints.scala index b0feb0a7fb..39e427f588 100644 --- a/src/reflect/scala/reflect/internal/tpe/TypeConstraints.scala +++ b/src/reflect/scala/reflect/internal/tpe/TypeConstraints.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package tpe diff --git a/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala b/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala index 0f9db31ec1..7665e7c0f4 100644 --- a/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala +++ b/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package tpe @@ -525,15 +526,39 @@ private[internal] trait TypeMaps { val TypeRef(_, rhsSym, rhsArgs) = rhs require(lhsSym.safeOwner == rhsSym, s"$lhsSym is not a type parameter of $rhsSym") - // Find the type parameter position; we'll use the corresponding argument - val argIndex = rhsSym.typeParams indexOf lhsSym - - if (argIndex >= 0 && argIndex < rhsArgs.length) // @M! don't just replace the whole thing, might be followed by type application - appliedType(rhsArgs(argIndex), lhsArgs mapConserve this) - else if (rhsSym.tpe_*.parents exists typeIsErroneous) // don't be too zealous with the exceptions, see #2641 + // Find the type parameter position; we'll use the corresponding argument. + // Why are we checking by name rather than by equality? Because for + // reasons which aren't yet fully clear, we can arrive here holding a type + // parameter whose owner is rhsSym, and which shares the name of an actual + // type parameter of rhsSym, but which is not among the type parameters of + // rhsSym. One can see examples of it at SI-4365. + val argIndex = rhsSym.typeParams indexWhere (lhsSym.name == _.name) + // don't be too zealous with the exceptions, see #2641 + if (argIndex < 0 && rhs.parents.exists(typeIsErroneous)) ErrorType - else - abort(s"something is wrong: cannot make sense of type application\n $lhs\n $rhs") + else { + // It's easy to get here when working on hardcore type machinery (not to + // mention when not doing so, see above) so let's provide a standout error. + def own_s(s: Symbol) = s.nameString + " in " + s.safeOwner.nameString + def explain = + sm"""| sought ${own_s(lhsSym)} + | classSym ${own_s(rhsSym)} + | tparams ${rhsSym.typeParams map own_s mkString ", "} + |""" + + if (argIndex < 0) + abort(s"Something is wrong: cannot find $lhs in applied type $rhs\n" + explain) + else { + val targ = rhsArgs(argIndex) + // @M! don't just replace the whole thing, might be followed by type application + val result = appliedType(targ, lhsArgs mapConserve this) + def msg = s"Created $result, though could not find ${own_s(lhsSym)} among tparams of ${own_s(rhsSym)}" + if (!rhsSym.typeParams.contains(lhsSym)) + devWarning(s"Inconsistent tparam/owner views: had to fall back on names\n$msg\n$explain") + + result + } + } } // 0) @pre: `classParam` is a class type parameter diff --git a/src/reflect/scala/reflect/internal/tpe/TypeToStrings.scala b/src/reflect/scala/reflect/internal/tpe/TypeToStrings.scala index c86383e9e3..16929cca0f 100644 --- a/src/reflect/scala/reflect/internal/tpe/TypeToStrings.scala +++ b/src/reflect/scala/reflect/internal/tpe/TypeToStrings.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package tpe diff --git a/src/reflect/scala/reflect/internal/transform/Erasure.scala b/src/reflect/scala/reflect/internal/transform/Erasure.scala index b8a8e4d0c0..24da8d20cc 100644 --- a/src/reflect/scala/reflect/internal/transform/Erasure.scala +++ b/src/reflect/scala/reflect/internal/transform/Erasure.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package transform diff --git a/src/reflect/scala/reflect/internal/transform/RefChecks.scala b/src/reflect/scala/reflect/internal/transform/RefChecks.scala index d6108ab665..4ca114e781 100644 --- a/src/reflect/scala/reflect/internal/transform/RefChecks.scala +++ b/src/reflect/scala/reflect/internal/transform/RefChecks.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package transform @@ -10,4 +11,4 @@ trait RefChecks { def transformInfo(sym: Symbol, tp: Type): Type = if (sym.isModule && !sym.isStatic) NullaryMethodType(tp) else tp -}
\ No newline at end of file +} diff --git a/src/reflect/scala/reflect/internal/transform/Transforms.scala b/src/reflect/scala/reflect/internal/transform/Transforms.scala index 71cc80895d..fa185db22f 100644 --- a/src/reflect/scala/reflect/internal/transform/Transforms.scala +++ b/src/reflect/scala/reflect/internal/transform/Transforms.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package transform diff --git a/src/reflect/scala/reflect/internal/transform/UnCurry.scala b/src/reflect/scala/reflect/internal/transform/UnCurry.scala index 1f7638a621..c525e794a9 100644 --- a/src/reflect/scala/reflect/internal/transform/UnCurry.scala +++ b/src/reflect/scala/reflect/internal/transform/UnCurry.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package transform diff --git a/src/reflect/scala/reflect/internal/util/Collections.scala b/src/reflect/scala/reflect/internal/util/Collections.scala index d6fca9d186..51b2f9f4e4 100644 --- a/src/reflect/scala/reflect/internal/util/Collections.scala +++ b/src/reflect/scala/reflect/internal/util/Collections.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect.internal.util +package scala +package reflect.internal.util import scala.collection.{ mutable, immutable } import scala.annotation.tailrec diff --git a/src/reflect/scala/reflect/internal/util/HashSet.scala b/src/reflect/scala/reflect/internal/util/HashSet.scala index 74b6a54c6e..b4178e055d 100644 --- a/src/reflect/scala/reflect/internal/util/HashSet.scala +++ b/src/reflect/scala/reflect/internal/util/HashSet.scala @@ -3,7 +3,9 @@ * @author Martin Odersky */ -package scala.reflect.internal.util +package scala +package reflect +package internal.util object HashSet { def apply[T >: Null <: AnyRef](initialCapacity: Int): HashSet[T] = this("No Label", initialCapacity) diff --git a/src/reflect/scala/reflect/internal/util/Origins.scala b/src/reflect/scala/reflect/internal/util/Origins.scala index a2b9e24ebc..2eb4fa29d5 100644 --- a/src/reflect/scala/reflect/internal/util/Origins.scala +++ b/src/reflect/scala/reflect/internal/util/Origins.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package internal.util import scala.collection.{ mutable, immutable } diff --git a/src/reflect/scala/reflect/internal/util/Position.scala b/src/reflect/scala/reflect/internal/util/Position.scala index fe6c7db989..ddd0a64675 100644 --- a/src/reflect/scala/reflect/internal/util/Position.scala +++ b/src/reflect/scala/reflect/internal/util/Position.scala @@ -4,7 +4,8 @@ * */ -package scala.reflect.internal.util +package scala +package reflect.internal.util import scala.reflect.ClassTag import scala.reflect.internal.FatalError @@ -210,7 +211,7 @@ abstract class Position extends scala.reflect.api.Position { self => */ def lineWithCarat(maxWidth: Int): (String, String) = { val radius = maxWidth / 2 - var start = math.max(column - radius, 0) + var start = scala.math.max(column - radius, 0) var result = lineContent drop start take maxWidth if (result.length < maxWidth) { diff --git a/src/reflect/scala/reflect/internal/util/RangePosition.scala b/src/reflect/scala/reflect/internal/util/RangePosition.scala index 3712aa0a52..0d09a53cd9 100644 --- a/src/reflect/scala/reflect/internal/util/RangePosition.scala +++ b/src/reflect/scala/reflect/internal/util/RangePosition.scala @@ -3,12 +3,13 @@ * @author Paul Phillips */ -package scala.reflect.internal.util +package scala +package reflect.internal.util /** new for position ranges */ class RangePosition(source: SourceFile, override val start: Int, point: Int, override val end: Int) extends OffsetPosition(source, point) { - if (start > end) sys.error("bad position: "+show) + if (start > end) scala.sys.error("bad position: "+show) override def isRange: Boolean = true override def isOpaqueRange: Boolean = true override def startOrPoint: Int = start diff --git a/src/reflect/scala/reflect/internal/util/Set.scala b/src/reflect/scala/reflect/internal/util/Set.scala index 57e5e0c0b9..75dcfaa59b 100644 --- a/src/reflect/scala/reflect/internal/util/Set.scala +++ b/src/reflect/scala/reflect/internal/util/Set.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky */ -package scala.reflect.internal.util +package scala +package reflect.internal.util /** A common class for lightweight sets. */ diff --git a/src/reflect/scala/reflect/internal/util/SourceFile.scala b/src/reflect/scala/reflect/internal/util/SourceFile.scala index dd2a6e21f1..ea4c9a9b68 100644 --- a/src/reflect/scala/reflect/internal/util/SourceFile.scala +++ b/src/reflect/scala/reflect/internal/util/SourceFile.scala @@ -4,7 +4,8 @@ */ -package scala.reflect.internal.util +package scala +package reflect.internal.util import scala.reflect.io.{ AbstractFile, VirtualFile } import scala.collection.mutable.ArrayBuffer diff --git a/src/reflect/scala/reflect/internal/util/Statistics.scala b/src/reflect/scala/reflect/internal/util/Statistics.scala index 0fa798058d..5b1e8ffdf8 100644 --- a/src/reflect/scala/reflect/internal/util/Statistics.scala +++ b/src/reflect/scala/reflect/internal/util/Statistics.scala @@ -1,4 +1,5 @@ -package scala.reflect.internal.util +package scala +package reflect.internal.util import scala.collection.mutable diff --git a/src/reflect/scala/reflect/internal/util/StringOps.scala b/src/reflect/scala/reflect/internal/util/StringOps.scala index 93bbfdd273..4d98a344d8 100644 --- a/src/reflect/scala/reflect/internal/util/StringOps.scala +++ b/src/reflect/scala/reflect/internal/util/StringOps.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.reflect.internal.util +package scala +package reflect.internal.util /** This object provides utility methods to extract elements * from Strings. diff --git a/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala b/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala index 9259c5abf1..e622e78d57 100644 --- a/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala +++ b/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package internal package util diff --git a/src/reflect/scala/reflect/internal/util/TableDef.scala b/src/reflect/scala/reflect/internal/util/TableDef.scala index d57c59757d..1626da2c93 100644 --- a/src/reflect/scala/reflect/internal/util/TableDef.scala +++ b/src/reflect/scala/reflect/internal/util/TableDef.scala @@ -1,4 +1,5 @@ -package scala.reflect.internal.util +package scala +package reflect.internal.util import TableDef._ import scala.language.postfixOps diff --git a/src/reflect/scala/reflect/internal/util/ThreeValues.scala b/src/reflect/scala/reflect/internal/util/ThreeValues.scala index f89bd9e199..18410510cb 100644 --- a/src/reflect/scala/reflect/internal/util/ThreeValues.scala +++ b/src/reflect/scala/reflect/internal/util/ThreeValues.scala @@ -1,4 +1,5 @@ -package scala.reflect.internal.util +package scala +package reflect.internal.util /** A simple three value type for booleans with an unknown value */ object ThreeValues { diff --git a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala index 632890d600..97cc19952c 100644 --- a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala +++ b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala @@ -1,4 +1,5 @@ -package scala.reflect.internal +package scala +package reflect.internal package util import scala.collection.{ mutable, immutable } diff --git a/src/reflect/scala/reflect/internal/util/WeakHashSet.scala b/src/reflect/scala/reflect/internal/util/WeakHashSet.scala index 41e74f80e9..ef62fa481b 100644 --- a/src/reflect/scala/reflect/internal/util/WeakHashSet.scala +++ b/src/reflect/scala/reflect/internal/util/WeakHashSet.scala @@ -1,4 +1,5 @@ -package scala.reflect.internal.util +package scala +package reflect.internal.util import scala.collection.mutable import scala.collection.generic.Clearable diff --git a/src/reflect/scala/reflect/internal/util/package.scala b/src/reflect/scala/reflect/internal/util/package.scala index 1ca57b81ed..49164d366c 100644 --- a/src/reflect/scala/reflect/internal/util/package.scala +++ b/src/reflect/scala/reflect/internal/util/package.scala @@ -2,6 +2,8 @@ package scala package reflect package internal +import scala.language.existentials // SI-6541 + package object util { import StringOps.longestCommonPrefix @@ -25,11 +27,10 @@ package object util { if (isModule) (name split '$' filterNot (_ == "")).last + "$" - else if (isAnon) { - val parents = clazz.getSuperclass :: clazz.getInterfaces.toList - parents map (c => shortClass(c)) mkString " with " - } - else shortenName(name) + else if (isAnon) + clazz.getSuperclass :: clazz.getInterfaces.toList map (c => shortClass(c)) mkString " with " + else + shortenName(name) } /** * Adds the `sm` String interpolator to a [[scala.StringContext]]. diff --git a/src/reflect/scala/reflect/io/AbstractFile.scala b/src/reflect/scala/reflect/io/AbstractFile.scala index 4ac56da628..ac1159b2ac 100644 --- a/src/reflect/scala/reflect/io/AbstractFile.scala +++ b/src/reflect/scala/reflect/io/AbstractFile.scala @@ -4,7 +4,8 @@ */ -package scala.reflect +package scala +package reflect package io import java.io.{ FileOutputStream, IOException, InputStream, OutputStream, BufferedOutputStream, ByteArrayOutputStream } diff --git a/src/reflect/scala/reflect/io/Directory.scala b/src/reflect/scala/reflect/io/Directory.scala index 4bf9ed8a36..2b965e6d69 100644 --- a/src/reflect/scala/reflect/io/Directory.scala +++ b/src/reflect/scala/reflect/io/Directory.scala @@ -6,7 +6,8 @@ ** |/ ** \* */ -package scala.reflect +package scala +package reflect package io import java.io.{ File => JFile } @@ -14,7 +15,7 @@ import java.io.{ File => JFile } * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Directory { - import scala.util.Properties.{ userHome, userDir } + import scala.util.Properties.userDir private def normalizePath(s: String) = Some(apply(Path(s).normalize)) def Current: Option[Directory] = if (userDir == "") None else normalizePath(userDir) diff --git a/src/reflect/scala/reflect/io/File.scala b/src/reflect/scala/reflect/io/File.scala index 64651dcfbd..a9c6807e88 100644 --- a/src/reflect/scala/reflect/io/File.scala +++ b/src/reflect/scala/reflect/io/File.scala @@ -7,13 +7,16 @@ \* */ -package scala.reflect +package scala +package reflect package io import java.io.{ FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter, - BufferedInputStream, BufferedOutputStream, IOException, PrintStream, PrintWriter, Closeable => JCloseable } -import java.io.{ File => JFile } + BufferedInputStream, BufferedOutputStream, IOException, PrintStream, PrintWriter, Closeable => JCloseable, + File => JFile +} + import java.nio.channels.{ Channel, FileChannel } import scala.io.Codec import scala.language.{reflectiveCalls, implicitConversions} diff --git a/src/reflect/scala/reflect/io/FileOperationException.scala b/src/reflect/scala/reflect/io/FileOperationException.scala index 13a1322798..fdfe0234e0 100644 --- a/src/reflect/scala/reflect/io/FileOperationException.scala +++ b/src/reflect/scala/reflect/io/FileOperationException.scala @@ -7,7 +7,8 @@ \* */ -package scala.reflect +package scala +package reflect package io /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ case class FileOperationException(msg: String) extends RuntimeException(msg) diff --git a/src/reflect/scala/reflect/io/IOStats.scala b/src/reflect/scala/reflect/io/IOStats.scala index 64e1e952cd..71f8be330d 100644 --- a/src/reflect/scala/reflect/io/IOStats.scala +++ b/src/reflect/scala/reflect/io/IOStats.scala @@ -1,4 +1,5 @@ -package scala.reflect.io +package scala +package reflect.io import scala.reflect.internal.util.Statistics diff --git a/src/reflect/scala/reflect/io/NoAbstractFile.scala b/src/reflect/scala/reflect/io/NoAbstractFile.scala index 2c59fd8aae..a4e869ed41 100644 --- a/src/reflect/scala/reflect/io/NoAbstractFile.scala +++ b/src/reflect/scala/reflect/io/NoAbstractFile.scala @@ -3,15 +3,15 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package io import java.io.InputStream -import java.io.{ File => JFile } /** A distinguished object so you can avoid both null * and Option. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object NoAbstractFile extends AbstractFile { @@ -19,7 +19,7 @@ object NoAbstractFile extends AbstractFile { def container: AbstractFile = this def create(): Unit = ??? def delete(): Unit = ??? - def file: JFile = null + def file: java.io.File = null def input: InputStream = null def isDirectory: Boolean = false override def isVirtual: Boolean = true diff --git a/src/reflect/scala/reflect/io/Path.scala b/src/reflect/scala/reflect/io/Path.scala index 1e1fb5a98b..15fce953f2 100644 --- a/src/reflect/scala/reflect/io/Path.scala +++ b/src/reflect/scala/reflect/io/Path.scala @@ -3,13 +3,13 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package io import java.io.{ FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter, - BufferedInputStream, BufferedOutputStream, RandomAccessFile } -import java.io.{ File => JFile } + BufferedInputStream, BufferedOutputStream, RandomAccessFile, File => JFile } import java.net.{ URI, URL } import scala.util.Random.alphanumeric import scala.language.implicitConversions diff --git a/src/reflect/scala/reflect/io/PlainFile.scala b/src/reflect/scala/reflect/io/PlainFile.scala index b892fe7cef..8f24d84488 100644 --- a/src/reflect/scala/reflect/io/PlainFile.scala +++ b/src/reflect/scala/reflect/io/PlainFile.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package io import java.io.{ FileInputStream, FileOutputStream, IOException } diff --git a/src/reflect/scala/reflect/io/Streamable.scala b/src/reflect/scala/reflect/io/Streamable.scala index 1d51ad7f54..aa47947672 100644 --- a/src/reflect/scala/reflect/io/Streamable.scala +++ b/src/reflect/scala/reflect/io/Streamable.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package io import java.net.{ URI, URL } diff --git a/src/reflect/scala/reflect/io/VirtualDirectory.scala b/src/reflect/scala/reflect/io/VirtualDirectory.scala index 210167e5c6..aa6ceaa09f 100644 --- a/src/reflect/scala/reflect/io/VirtualDirectory.scala +++ b/src/reflect/scala/reflect/io/VirtualDirectory.scala @@ -2,7 +2,8 @@ * Copyright 2005-2013 LAMP/EPFL */ -package scala.reflect +package scala +package reflect package io import scala.collection.mutable diff --git a/src/reflect/scala/reflect/io/VirtualFile.scala b/src/reflect/scala/reflect/io/VirtualFile.scala index 8cc83b6a50..45f38db745 100644 --- a/src/reflect/scala/reflect/io/VirtualFile.scala +++ b/src/reflect/scala/reflect/io/VirtualFile.scala @@ -3,11 +3,11 @@ * @author Martin Odersky */ -package scala.reflect +package scala +package reflect package io -import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream } -import java.io.{ File => JFile } +import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream, File => JFile } /** This class implements an in-memory file. * @@ -60,9 +60,13 @@ class VirtualFile(val name: String, override val path: String) extends AbstractF /** @inheritdoc */ override def isVirtual: Boolean = true + // private var _lastModified: Long = 0 + // _lastModified + /** Returns the time that this abstract file was last modified. */ - private var _lastModified: Long = 0 - def lastModified: Long = _lastModified + // !!! Except it doesn't - it's private and never set - so I replaced it + // with constant 0 to save the field. + def lastModified: Long = 0 /** Returns all abstract subfiles of this abstract directory. */ def iterator: Iterator[AbstractFile] = { diff --git a/src/reflect/scala/reflect/io/ZipArchive.scala b/src/reflect/scala/reflect/io/ZipArchive.scala index 11d04538e9..eabf1dcbab 100644 --- a/src/reflect/scala/reflect/io/ZipArchive.scala +++ b/src/reflect/scala/reflect/io/ZipArchive.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect +package scala +package reflect package io import java.net.URL @@ -267,8 +268,8 @@ final class ManifestResources(val url: URL) extends ZipArchive(null) { def input = url.openStream() def lastModified = try url.openConnection().getLastModified() - catch { case _: IOException => 0 } - + catch { case _: IOException => 0 } + override def canEqual(other: Any) = other.isInstanceOf[ManifestResources] override def hashCode() = url.hashCode override def equals(that: Any) = that match { diff --git a/src/reflect/scala/reflect/macros/Aliases.scala b/src/reflect/scala/reflect/macros/Aliases.scala index 92d76f4370..9e05f343e6 100644 --- a/src/reflect/scala/reflect/macros/Aliases.scala +++ b/src/reflect/scala/reflect/macros/Aliases.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Attachments.scala b/src/reflect/scala/reflect/macros/Attachments.scala index eeb87fafcc..c1ab269268 100644 --- a/src/reflect/scala/reflect/macros/Attachments.scala +++ b/src/reflect/scala/reflect/macros/Attachments.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Context.scala b/src/reflect/scala/reflect/macros/Context.scala index f4a4631e53..434b7c1b9c 100644 --- a/src/reflect/scala/reflect/macros/Context.scala +++ b/src/reflect/scala/reflect/macros/Context.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros // todo. introduce context hierarchy diff --git a/src/reflect/scala/reflect/macros/Enclosures.scala b/src/reflect/scala/reflect/macros/Enclosures.scala index fd91333dae..8ea05500e4 100644 --- a/src/reflect/scala/reflect/macros/Enclosures.scala +++ b/src/reflect/scala/reflect/macros/Enclosures.scala @@ -1,6 +1,9 @@ -package scala.reflect +package scala +package reflect package macros +import scala.language.existentials // SI-6541 + /** * <span class="badge badge-red" style="float: right;">EXPERIMENTAL</span> * @@ -100,4 +103,4 @@ trait Enclosures { */ case class EnclosureException(expected: Class[_], enclosingTrees: List[Tree]) extends Exception(s"Couldn't find a tree of type $expected among enclosing trees $enclosingTrees") -}
\ No newline at end of file +} diff --git a/src/reflect/scala/reflect/macros/Evals.scala b/src/reflect/scala/reflect/macros/Evals.scala index 37680c219b..70b2ab58d4 100644 --- a/src/reflect/scala/reflect/macros/Evals.scala +++ b/src/reflect/scala/reflect/macros/Evals.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** @@ -54,4 +55,4 @@ trait Evals { * refers to a runtime value `x`, which is unknown at compile time. */ def eval[T](expr: Expr[T]): T -}
\ No newline at end of file +} diff --git a/src/reflect/scala/reflect/macros/ExprUtils.scala b/src/reflect/scala/reflect/macros/ExprUtils.scala index 458cde9692..af11bd6efc 100644 --- a/src/reflect/scala/reflect/macros/ExprUtils.scala +++ b/src/reflect/scala/reflect/macros/ExprUtils.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/FrontEnds.scala b/src/reflect/scala/reflect/macros/FrontEnds.scala index 67b24088b5..6abd8c335b 100644 --- a/src/reflect/scala/reflect/macros/FrontEnds.scala +++ b/src/reflect/scala/reflect/macros/FrontEnds.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** @@ -44,4 +45,4 @@ trait FrontEnds { * Use `enclosingPosition` if you're in doubt what position to pass to `pos`. */ def abort(pos: Position, msg: String): Nothing -}
\ No newline at end of file +} diff --git a/src/reflect/scala/reflect/macros/Infrastructure.scala b/src/reflect/scala/reflect/macros/Infrastructure.scala index 99706e84fe..eb63fb7b7f 100644 --- a/src/reflect/scala/reflect/macros/Infrastructure.scala +++ b/src/reflect/scala/reflect/macros/Infrastructure.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** @@ -22,4 +23,4 @@ trait Infrastructure { /** Exposes current classpath. */ def classPath: List[java.net.URL] -}
\ No newline at end of file +} diff --git a/src/reflect/scala/reflect/macros/Names.scala b/src/reflect/scala/reflect/macros/Names.scala index 7e2ac5e02d..8773175561 100644 --- a/src/reflect/scala/reflect/macros/Names.scala +++ b/src/reflect/scala/reflect/macros/Names.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Parsers.scala b/src/reflect/scala/reflect/macros/Parsers.scala index b4b93da3fa..3b25309614 100644 --- a/src/reflect/scala/reflect/macros/Parsers.scala +++ b/src/reflect/scala/reflect/macros/Parsers.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Reifiers.scala b/src/reflect/scala/reflect/macros/Reifiers.scala index 1eae3e3fce..6ebd2db730 100644 --- a/src/reflect/scala/reflect/macros/Reifiers.scala +++ b/src/reflect/scala/reflect/macros/Reifiers.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Synthetics.scala b/src/reflect/scala/reflect/macros/Synthetics.scala index 14c6c930b3..5e422ee89f 100644 --- a/src/reflect/scala/reflect/macros/Synthetics.scala +++ b/src/reflect/scala/reflect/macros/Synthetics.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/TreeBuilder.scala b/src/reflect/scala/reflect/macros/TreeBuilder.scala index 19230010e6..427b4f70d1 100644 --- a/src/reflect/scala/reflect/macros/TreeBuilder.scala +++ b/src/reflect/scala/reflect/macros/TreeBuilder.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Typers.scala b/src/reflect/scala/reflect/macros/Typers.scala index 09a2373205..eaf79f2dab 100644 --- a/src/reflect/scala/reflect/macros/Typers.scala +++ b/src/reflect/scala/reflect/macros/Typers.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/Universe.scala b/src/reflect/scala/reflect/macros/Universe.scala index 31f3192a85..d1d90f53c9 100644 --- a/src/reflect/scala/reflect/macros/Universe.scala +++ b/src/reflect/scala/reflect/macros/Universe.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package macros /** diff --git a/src/reflect/scala/reflect/macros/package.scala b/src/reflect/scala/reflect/macros/package.scala index 21d189bb25..2e2e8e79f8 100644 --- a/src/reflect/scala/reflect/macros/package.scala +++ b/src/reflect/scala/reflect/macros/package.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect /** * <span class="badge badge-red" style="float: right;">EXPERIMENTAL</span> diff --git a/src/reflect/scala/reflect/runtime/JavaMirrors.scala b/src/reflect/scala/reflect/runtime/JavaMirrors.scala index 3211bb7919..c46ec691ae 100644 --- a/src/reflect/scala/reflect/runtime/JavaMirrors.scala +++ b/src/reflect/scala/reflect/runtime/JavaMirrors.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import scala.ref.WeakReference @@ -13,9 +14,7 @@ import java.lang.reflect.{ import java.lang.annotation.{Annotation => jAnnotation} import java.io.IOException import scala.reflect.internal.{ MissingRequirementError, JavaAccFlags, JMethodOrConstructor } -import JavaAccFlags._ import internal.pickling.ByteCodecs -import internal.ClassfileConstants._ import internal.pickling.UnPickler import scala.collection.mutable.{ HashMap, ListBuffer } import internal.Flags._ @@ -1280,14 +1279,12 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni if (name.isTermName && !owner.isEmptyPackageClass) return mirror.makeScalaPackage( if (owner.isRootSymbol) name.toString else owner.fullName+"."+name) - syntheticCoreClasses get (owner.fullName, name) match { - case Some(tsym) => - // synthetic core classes are only present in root mirrors - // because Definitions.scala, which initializes and enters them, only affects rootMirror - // therefore we need to enter them manually for non-root mirrors - if (mirror ne thisUniverse.rootMirror) owner.info.decls enter tsym - return tsym - case None => + syntheticCoreClasses get ((owner.fullName, name)) foreach { tsym => + // synthetic core classes are only present in root mirrors + // because Definitions.scala, which initializes and enters them, only affects rootMirror + // therefore we need to enter them manually for non-root mirrors + if (mirror ne thisUniverse.rootMirror) owner.info.decls enter tsym + return tsym } } info("*** missing: "+name+"/"+name.isTermName+"/"+owner+"/"+owner.hasPackageFlag+"/"+owner.info.decls.getClass) diff --git a/src/reflect/scala/reflect/runtime/JavaUniverse.scala b/src/reflect/scala/reflect/runtime/JavaUniverse.scala index 4d90afcdc3..4805c36ce8 100644 --- a/src/reflect/scala/reflect/runtime/JavaUniverse.scala +++ b/src/reflect/scala/reflect/runtime/JavaUniverse.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime /** An implementation of [[scala.reflect.api.Universe]] for runtime reflection using JVM classloaders. @@ -9,12 +10,12 @@ package runtime */ class JavaUniverse extends internal.SymbolTable with ReflectSetup with runtime.SymbolTable { self => - def inform(msg: String): Unit = log(msg) + override def inform(msg: String): Unit = log(msg) def picklerPhase = internal.SomePhase lazy val settings = new Settings private val isLogging = sys.props contains "scala.debug.reflect" - def log(msg: => AnyRef): Unit = if (isLogging) Console.err.println("[reflect] " + msg) + def log(msg: => AnyRef): Unit = if (isLogging) Console.err.println("[reflect] " + msg) type TreeCopier = InternalTreeCopierOps def newStrictTreeCopier: TreeCopier = new StrictTreeCopier diff --git a/src/reflect/scala/reflect/runtime/ReflectSetup.scala b/src/reflect/scala/reflect/runtime/ReflectSetup.scala index 6e28fc8520..84f159be00 100644 --- a/src/reflect/scala/reflect/runtime/ReflectSetup.scala +++ b/src/reflect/scala/reflect/runtime/ReflectSetup.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import internal.{SomePhase, NoPhase, Phase, TreeGen} diff --git a/src/reflect/scala/reflect/runtime/ReflectionUtils.scala b/src/reflect/scala/reflect/runtime/ReflectionUtils.scala index aebaea40af..536bdc815d 100644 --- a/src/reflect/scala/reflect/runtime/ReflectionUtils.scala +++ b/src/reflect/scala/reflect/runtime/ReflectionUtils.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.reflect.runtime +package scala +package reflect.runtime import java.lang.{Class => jClass} import java.lang.reflect.{ Method, InvocationTargetException, UndeclaredThrowableException } diff --git a/src/reflect/scala/reflect/runtime/Settings.scala b/src/reflect/scala/reflect/runtime/Settings.scala index 6714bae1e0..a14eafff24 100644 --- a/src/reflect/scala/reflect/runtime/Settings.scala +++ b/src/reflect/scala/reflect/runtime/Settings.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import scala.reflect.internal.settings.MutableSettings diff --git a/src/reflect/scala/reflect/runtime/SymbolLoaders.scala b/src/reflect/scala/reflect/runtime/SymbolLoaders.scala index ea14e8ad43..815cc0c885 100644 --- a/src/reflect/scala/reflect/runtime/SymbolLoaders.scala +++ b/src/reflect/scala/reflect/runtime/SymbolLoaders.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import internal.Flags diff --git a/src/reflect/scala/reflect/runtime/SymbolTable.scala b/src/reflect/scala/reflect/runtime/SymbolTable.scala index ade7a4a21a..bcd4d16cde 100644 --- a/src/reflect/scala/reflect/runtime/SymbolTable.scala +++ b/src/reflect/scala/reflect/runtime/SymbolTable.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import scala.reflect.internal.Flags._ diff --git a/src/reflect/scala/reflect/runtime/SynchronizedOps.scala b/src/reflect/scala/reflect/runtime/SynchronizedOps.scala index 7b280e59b9..132470b2e7 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedOps.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedOps.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime // SI-6240: test thread-safety, make trees synchronized as well diff --git a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala index 1154927279..98cad45db1 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import scala.reflect.io.AbstractFile diff --git a/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala b/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala index a3e7c28ca4..f4b02c5bcd 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import scala.collection.mutable.WeakHashMap diff --git a/src/reflect/scala/reflect/runtime/TwoWayCache.scala b/src/reflect/scala/reflect/runtime/TwoWayCache.scala index 05debcba65..181ca6014a 100644 --- a/src/reflect/scala/reflect/runtime/TwoWayCache.scala +++ b/src/reflect/scala/reflect/runtime/TwoWayCache.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect package runtime import scala.collection.mutable.WeakHashMap diff --git a/src/reflect/scala/reflect/runtime/package.scala b/src/reflect/scala/reflect/runtime/package.scala index eadbc0c52e..0354b424d2 100644 --- a/src/reflect/scala/reflect/runtime/package.scala +++ b/src/reflect/scala/reflect/runtime/package.scala @@ -1,4 +1,5 @@ -package scala.reflect +package scala +package reflect /** Entry points into runtime reflection. * See [[scala.reflect.api.package the overview page]] for details on how to use them. diff --git a/src/repl/scala/tools/nsc/MainGenericRunner.scala b/src/repl/scala/tools/nsc/MainGenericRunner.scala index 9e87b6ba55..43f0ea1256 100644 --- a/src/repl/scala/tools/nsc/MainGenericRunner.scala +++ b/src/repl/scala/tools/nsc/MainGenericRunner.scala @@ -3,7 +3,8 @@ * @author Lex Spoon */ -package scala.tools.nsc +package scala +package tools.nsc import io.{ File } import util.{ ClassPath, ScalaClassLoader } diff --git a/src/repl/scala/tools/nsc/interpreter/ILoop.scala b/src/repl/scala/tools/nsc/interpreter/ILoop.scala index df28e428ce..197e76d990 100644 --- a/src/repl/scala/tools/nsc/interpreter/ILoop.scala +++ b/src/repl/scala/tools/nsc/interpreter/ILoop.scala @@ -3,7 +3,8 @@ * @author Alexander Spoon */ -package scala.tools.nsc +package scala +package tools.nsc package interpreter import Predef.{ println => _, _ } diff --git a/src/repl/scala/tools/nsc/interpreter/IMain.scala b/src/repl/scala/tools/nsc/interpreter/IMain.scala index 4ba81b634a..66129e0be8 100644 --- a/src/repl/scala/tools/nsc/interpreter/IMain.scala +++ b/src/repl/scala/tools/nsc/interpreter/IMain.scala @@ -3,7 +3,8 @@ * @author Martin Odersky */ -package scala.tools.nsc +package scala +package tools.nsc package interpreter import Predef.{ println => _, _ } @@ -29,6 +30,7 @@ import java.util.concurrent.Future import scala.reflect.runtime.{ universe => ru } import scala.reflect.{ ClassTag, classTag } import StdReplTags._ +import scala.language.implicitConversions /** An interpreter for Scala code. * @@ -555,7 +557,7 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set @throws(classOf[ScriptException]) def compile(script: String): CompiledScript = { if (!bound) { - quietBind("engine", this.asInstanceOf[ScriptEngine]) + quietBind("engine" -> this.asInstanceOf[ScriptEngine]) bound = true } val cat = code + script diff --git a/src/repl/scala/tools/nsc/interpreter/JavapClass.scala b/src/repl/scala/tools/nsc/interpreter/JavapClass.scala index a895944c15..ef6f4c2920 100644 --- a/src/repl/scala/tools/nsc/interpreter/JavapClass.scala +++ b/src/repl/scala/tools/nsc/interpreter/JavapClass.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.tools.nsc +package scala +package tools.nsc package interpreter import java.lang.{ ClassLoader => JavaClassLoader, Iterable => JIterable } @@ -234,8 +235,6 @@ class JavapClass( } class JavapTool7 extends JavapTool { - - import JavapTool._ type Task = { def call(): Boolean // true = ok //def run(args: Array[String]): Int // all args @@ -606,7 +605,7 @@ object JavapClass { // s = "f" and $line.$read$$etc$#f is what we're after, // ignoring any #member (except take # as filter on #apply) orElse (intp flatMap (_ translateEnclosingClass k) map ((_, Some(k), filter, true))) - getOrElse (k, member, filter, false)) + getOrElse ((k, member, filter, false))) } /** Find the classnames of anonfuns associated with k, * where k may be an available class or a symbol in scope. diff --git a/src/repl/scala/tools/nsc/interpreter/LoopCommands.scala b/src/repl/scala/tools/nsc/interpreter/LoopCommands.scala index 4bba27b714..12d6ee5112 100644 --- a/src/repl/scala/tools/nsc/interpreter/LoopCommands.scala +++ b/src/repl/scala/tools/nsc/interpreter/LoopCommands.scala @@ -3,7 +3,9 @@ * @author Paul Phillips */ -package scala.tools.nsc +package scala +package tools +package nsc package interpreter import scala.collection.{ mutable, immutable } diff --git a/src/repl/scala/tools/nsc/interpreter/Naming.scala b/src/repl/scala/tools/nsc/interpreter/Naming.scala index 57f3675ada..7f577b3a8b 100644 --- a/src/repl/scala/tools/nsc/interpreter/Naming.scala +++ b/src/repl/scala/tools/nsc/interpreter/Naming.scala @@ -3,7 +3,8 @@ * @author Paul Phillips */ -package scala.tools.nsc +package scala +package tools.nsc package interpreter import scala.util.Properties.lineSeparator diff --git a/src/repl/scala/tools/nsc/interpreter/SimpleReader.scala b/src/repl/scala/tools/nsc/interpreter/SimpleReader.scala index 2d0917d91f..6634dc6944 100644 --- a/src/repl/scala/tools/nsc/interpreter/SimpleReader.scala +++ b/src/repl/scala/tools/nsc/interpreter/SimpleReader.scala @@ -3,7 +3,8 @@ * @author Stepan Koltsov */ -package scala.tools.nsc +package scala +package tools.nsc package interpreter import java.io.{ BufferedReader } diff --git a/src/scalacheck/org/scalacheck/Arbitrary.scala b/src/scalacheck/org/scalacheck/Arbitrary.scala index 8c43cdaafe..db4163c8af 100644 --- a/src/scalacheck/org/scalacheck/Arbitrary.scala +++ b/src/scalacheck/org/scalacheck/Arbitrary.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -10,49 +10,44 @@ package org.scalacheck import util.{FreqMap,Buildable} -import scala.reflect.ClassTag sealed abstract class Arbitrary[T] { val arbitrary: Gen[T] } -/** Defines implicit <code>Arbitrary</code> instances for common types. +/** Defines implicit [[org.scalacheck.Arbitrary]] instances for common types. * <p> * ScalaCheck - * uses implicit <code>Arbitrary</code> instances when creating properties - * out of functions with the <code>Prop.property</code> method, and when - * the <code>Arbitrary.arbitrary</code> method is used. For example, the + * uses implicit [[org.scalacheck.Arbitrary]] instances when creating properties + * out of functions with the `Prop.property` method, and when + * the `Arbitrary.arbitrary` method is used. For example, the * following code requires that there exists an implicit - * <code>Arbitrary[MyClass]</code> instance: + * `Arbitrary[MyClass]` instance: * </p> * - * <p> - * <code> - * val myProp = Prop.forAll { myClass: MyClass =><br /> - * ...<br /> - * }<br /> + * {{{ + * val myProp = Prop.forAll { myClass: MyClass => + * ... + * } * * val myGen = Arbitrary.arbitrary[MyClass] - * </code> - * </p> + * }}} * * <p> * The required implicit definition could look like this: * </p> * - * <p> - * <code> + * {{{ * implicit val arbMyClass: Arbitrary[MyClass] = Arbitrary(...) - * </code> - * </p> + * }}} * * <p> - * The factory method <code>Arbitrary(...)</code> takes a generator of type - * <code>Gen[T]</code> and returns an instance of <code>Arbitrary[T]</code>. + * The factory method `Arbitrary(...)` takes a generator of type + * `Gen[T]` and returns an instance of `Arbitrary[T]`. * </p> * * <p> - * The <code>Arbitrary</code> module defines implicit <code>Arbitrary</code> + * The `Arbitrary` module defines implicit [[org.scalacheck.Arbitrary]] * instances for common types, for convenient use in your properties and * generators. * </p> @@ -93,7 +88,7 @@ object Arbitrary { /** Arbitrary instance of Long */ implicit lazy val arbLong: Arbitrary[Long] = Arbitrary( - Gen.chooseNum(Long.MinValue / 2, Long.MaxValue / 2) + Gen.chooseNum(Long.MinValue, Long.MaxValue) ) /** Arbitrary instance of Float */ @@ -182,7 +177,13 @@ object Arbitrary { mc <- mcGen limit <- value(if(mc == UNLIMITED) 0 else math.max(x.abs.toString.length - mc.getPrecision, 0)) scale <- Gen.chooseNum(Int.MinValue + limit , Int.MaxValue) - } yield BigDecimal(x, scale, mc) + } yield { + try { + BigDecimal(x, scale, mc) + } catch { + case ae: java.lang.ArithmeticException => BigDecimal(x, scale, UNLIMITED) // Handle the case where scale/precision conflict + } + } Arbitrary(bdGen) } @@ -213,23 +214,43 @@ object Arbitrary { )) } - /** Arbitrary instance of test params */ + /** Arbitrary instance of test params + * @deprecated (in 1.10.0) Use `arbTestParameters` instead. + */ + @deprecated("Use 'arbTestParameters' instead", "1.10.0") implicit lazy val arbTestParams: Arbitrary[Test.Params] = Arbitrary(for { minSuccTests <- choose(10,200) - maxDiscardRatio <- choose(0.2f,10f) - minSize <- choose(0,500) + maxDiscTests <- choose(100,500) + mnSize <- choose(0,500) sizeDiff <- choose(0,500) - maxSize <- choose(minSize, minSize + sizeDiff) + mxSize <- choose(mnSize, mnSize + sizeDiff) ws <- choose(1,4) } yield Test.Params( minSuccessfulTests = minSuccTests, - maxDiscardRatio = maxDiscardRatio, - minSize = minSize, - maxSize = maxSize, + maxDiscardedTests = maxDiscTests, + minSize = mnSize, + maxSize = mxSize, workers = ws )) + /** Arbitrary instance of test parameters */ + implicit lazy val arbTestParameters: Arbitrary[Test.Parameters] = + Arbitrary(for { + _minSuccTests <- choose(10,200) + _maxDiscardRatio <- choose(0.2f,10f) + _minSize <- choose(0,500) + sizeDiff <- choose(0,500) + _maxSize <- choose(_minSize, _minSize + sizeDiff) + _workers <- choose(1,4) + } yield new Test.Parameters.Default { + override val minSuccessfulTests = _minSuccTests + override val maxDiscardRatio = _maxDiscardRatio + override val minSize = _minSize + override val maxSize = _maxSize + override val workers = _workers + }) + /** Arbitrary instance of gen params */ implicit lazy val arbGenParams: Arbitrary[Gen.Params] = Arbitrary(for { @@ -278,7 +299,7 @@ object Arbitrary { ): Arbitrary[C[T]] = Arbitrary(containerOf[C,T](arbitrary[T])) /** Arbitrary instance of any array. */ - implicit def arbArray[T](implicit a: Arbitrary[T], c: ClassTag[T] + implicit def arbArray[T](implicit a: Arbitrary[T], c: ClassManifest[T] ): Arbitrary[Array[T]] = Arbitrary(containerOf[Array,T](arbitrary[T])) diff --git a/src/scalacheck/org/scalacheck/Arg.scala b/src/scalacheck/org/scalacheck/Arg.scala index 8959211f09..4961c78a26 100644 --- a/src/scalacheck/org/scalacheck/Arg.scala +++ b/src/scalacheck/org/scalacheck/Arg.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** diff --git a/src/scalacheck/org/scalacheck/Commands.scala b/src/scalacheck/org/scalacheck/Commands.scala index 2acc460b5e..604b68cb36 100644 --- a/src/scalacheck/org/scalacheck/Commands.scala +++ b/src/scalacheck/org/scalacheck/Commands.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -53,7 +53,7 @@ trait Commands extends Prop { * takes the current abstract state as parameter and returns a boolean * that says if the precondition is fulfilled or not. You can add several * conditions to the precondition list */ - val preConditions = new scala.collection.mutable.ListBuffer[State => Boolean] + val preConditions = new collection.mutable.ListBuffer[State => Boolean] /** Returns all postconditions merged into a single function */ def postCondition: (State,State,Any) => Prop = (s0,s1,r) => all(postConditions.map(_.apply(s0,s1,r)): _*) @@ -65,7 +65,7 @@ trait Commands extends Prop { * method. The postcondition function should return a Boolean (or * a Prop instance) that says if the condition holds or not. You can add several * conditions to the postConditions list. */ - val postConditions = new scala.collection.mutable.ListBuffer[(State,State,Any) => Prop] + val postConditions = new collection.mutable.ListBuffer[(State,State,Any) => Prop] } /** A command that binds its result for later use */ @@ -87,6 +87,11 @@ trait Commands extends Prop { private val bindings = new scala.collection.mutable.ListBuffer[(State,Any)] + private def initState() = { + bindings.clear() + initialState() + } + private def genCmds: Gen[Cmds] = { def sizedCmds(s: State)(sz: Int): Gen[Cmds] = if(sz <= 0) value(Cmds(Nil, Nil)) else for { diff --git a/src/scalacheck/org/scalacheck/ConsoleReporter.scala b/src/scalacheck/org/scalacheck/ConsoleReporter.scala index 93f1dc222e..d565322d99 100644 --- a/src/scalacheck/org/scalacheck/ConsoleReporter.scala +++ b/src/scalacheck/org/scalacheck/ConsoleReporter.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** diff --git a/src/scalacheck/org/scalacheck/Gen.scala b/src/scalacheck/org/scalacheck/Gen.scala index 64bb61c2d3..aec67159f1 100644 --- a/src/scalacheck/org/scalacheck/Gen.scala +++ b/src/scalacheck/org/scalacheck/Gen.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -23,7 +23,7 @@ object Choose { implicit val chooseLong: Choose[Long] = new Choose[Long] { def choose(low: Long, high: Long) = - if(low > high || (high-low < 0)) fail + if (low > high) fail else parameterized(prms => value(prms.choose(low,high))) } @@ -204,9 +204,17 @@ object Gen { /** @throws IllegalArgumentException if l is greater than h, or if * the range between l and h doesn't fit in a Long. */ def choose(l: Long, h: Long): Long = { - val d = h-l - if (d < 0) throw new IllegalArgumentException("Invalid range") - else l + math.abs(rng.nextLong % (d+1)) + if (h < l) throw new IllegalArgumentException("Invalid range") + val d = h - l + 1 + if (d <= 0) { + var n = rng.nextLong + while (n < l || n > h) { + n = rng.nextLong + } + n + } else { + l + math.abs(rng.nextLong % d) + } } /** @throws IllegalArgumentException if l is greater than h, or if @@ -225,8 +233,11 @@ object Gen { def apply(p: Gen.Params) = g(p) } - /* Convenience method for using the <code>frequency</code> method like this: - * <code>frequency((1, "foo"), (3, "bar"))</code> */ + /* Convenience method for using the `frequency` method like this: + * {{{ + * frequency((1, "foo"), (3, "bar")) + * }}} + */ implicit def freqTuple[T](t: (Int, T)): (Int, Gen[T]) = (t._1, value(t._2)) @@ -308,9 +319,9 @@ object Gen { //// List Generators //// /** Generates a container of any type for which there exists an implicit - * <code>Buildable</code> instance. The elements in the container will + * [[org.scalacheck.util.Buildable]] instance. The elements in the container will * be generated by the given generator. The size of the generated container - * is given by <code>n</code>. */ + * is given by `n`. */ def containerOfN[C[_],T](n: Int, g: Gen[T])(implicit b: Buildable[T,C] ): Gen[C[T]] = sequence[C,T](new Iterable[Gen[T]] { def iterator = new Iterator[Gen[T]] { @@ -321,14 +332,14 @@ object Gen { }) /** Generates a container of any type for which there exists an implicit - * <code>Buildable</code> instance. The elements in the container will - * be generated by the given generator. The size of the container is + * [[org.scalacheck.util.Buildable]] instance. The elements in the container + * will be generated by the given generator. The size of the container is * bounded by the size parameter used when generating values. */ def containerOf[C[_],T](g: Gen[T])(implicit b: Buildable[T,C]): Gen[C[T]] = sized(size => for(n <- choose(0,size); c <- containerOfN[C,T](n,g)) yield c) /** Generates a non-empty container of any type for which there exists an - * implicit <code>Buildable</code> instance. The elements in the container + * implicit [[org.scalacheck.util.Buildable]] instance. The elements in the container * will be generated by the given generator. The size of the container is * bounded by the size parameter used when generating values. */ def containerOf1[C[_],T](g: Gen[T])(implicit b: Buildable[T,C]): Gen[C[T]] = @@ -336,16 +347,16 @@ object Gen { /** Generates a list of random length. The maximum length depends on the * size parameter. This method is equal to calling - * <code>containerOf[List,T](g)</code>. */ + * `containerOf[List,T](g)`. */ def listOf[T](g: => Gen[T]) = containerOf[List,T](g) /** Generates a non-empty list of random length. The maximum length depends * on the size parameter. This method is equal to calling - * <code>containerOf1[List,T](g)</code>. */ + * `containerOf1[List,T](g)`. */ def listOf1[T](g: => Gen[T]) = containerOf1[List,T](g) /** Generates a list of the given length. This method is equal to calling - * <code>containerOfN[List,T](n,g)</code>. */ + * `containerOfN[List,T](n,g)`. */ def listOfN[T](n: Int, g: Gen[T]) = containerOfN[List,T](n,g) /** A generator that picks a random number of elements from a list */ diff --git a/src/scalacheck/org/scalacheck/Pretty.scala b/src/scalacheck/org/scalacheck/Pretty.scala index eeb5936086..3e8f6de5f6 100644 --- a/src/scalacheck/org/scalacheck/Pretty.scala +++ b/src/scalacheck/org/scalacheck/Pretty.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -96,7 +96,7 @@ object Pretty { } implicit def prettyTestRes(res: Test.Result) = Pretty { prms => - def labels(ls: scala.collection.immutable.Set[String]) = + def labels(ls: collection.immutable.Set[String]) = if(ls.isEmpty) "" else "> Labels of failing property: " / ls.mkString("\n") val s = res.status match { diff --git a/src/scalacheck/org/scalacheck/Prop.scala b/src/scalacheck/org/scalacheck/Prop.scala index dfd85a832a..38e00f260f 100644 --- a/src/scalacheck/org/scalacheck/Prop.scala +++ b/src/scalacheck/org/scalacheck/Prop.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -31,16 +31,27 @@ trait Prop { /** Convenience method that checks this property with the given parameters * and reports the result on the console. If you need to get the results - * from the test use the <code>check</code> methods in <code>Test</code> - * instead. */ + * from the test use the `check` methods in [[org.scalacheck.Test]] + * instead. + * @deprecated (in 1.10.0) Use `check(Test.Parameters)` instead. + */ + @deprecated("Use 'check(Test.Parameters)' instead", "1.10.0") def check(prms: Test.Params): Unit = Test.check( prms copy (testCallback = ConsoleReporter(1) chain prms.testCallback), this ) + /** Convenience method that checks this property with the given parameters + * and reports the result on the console. If you need to get the results + * from the test use the `check` methods in [[org.scalacheck.Test]] + * instead. */ + def check(prms: Test.Parameters): Unit = Test.check( + prms copy (_testCallback = ConsoleReporter(1) chain prms.testCallback), this + ) + /** Convenience method that checks this property and reports the * result on the console. If you need to get the results from the test use - * the <code>check</code> methods in <code>Test</code> instead. */ - def check: Unit = check(Test.Params()) + * the `check` methods in [[org.scalacheck.Test]] instead. */ + def check: Unit = check(Test.Parameters.default) /** The logic for main, separated out to make it easier to * avoid System.exit calls. Returns exit code. @@ -60,7 +71,7 @@ trait Prop { /** Whether main should call System.exit with an exit code. * Defaults to true; override to change. */ - def mainCallsExit = false + def mainCallsExit = true /** Convenience method that makes it possible to use this property * as an application that checks itself on execution */ @@ -274,20 +285,51 @@ object Prop { def apply(r: Result): Prop = Prop(prms => r) + def apply(b: Boolean): Prop = if(b) proved else falsified - // Implicit defs + // Implicits + + /** A collection of property operators on [[Any]] values. + * Import [[Prop.AnyOperators]] to make the operators available. */ class ExtendedAny[T <% Pretty](x: => T) { + /** See [[Prop.imply]] */ def imply(f: PartialFunction[T,Prop]) = Prop.imply(x,f) + /** See [[Prop.iff]] */ def iff(f: PartialFunction[T,Prop]) = Prop.iff(x,f) - def throws[U <: Throwable](c: Class[U]) = Prop.throws(x, c) + @deprecated("Use 'Prop.throws' instead", "1.10.1") + def throws[U <: Throwable](c: Class[U]): Prop = Prop.throws(c)(x) + /** See [[Prop.?=]] */ def ?=(y: T) = Prop.?=(x, y) + /** See [[Prop.=?]] */ def =?(y: T) = Prop.=?(x, y) } + /** A collection of property operators on [[Boolean]] values. + * Import [[Prop.BooleanOperators]] to make the operators available. */ + class ExtendedBoolean(b: => Boolean) { + /** See [[Prop.==>]] */ + def ==>(p: => Prop) = Prop(b) ==> p + } + + /** Implicit method that makes a number of property operators on values of + * type [[Any]] available in the current scope. See [[Prop.ExtendedAny]] for + * documentation on the operators. */ + @deprecated("Use 'Prop.AnyOperators' instead", "1.10.1") implicit def extendedAny[T <% Pretty](x: => T) = new ExtendedAny[T](x) - implicit def propBoolean(b: Boolean): Prop = if(b) proved else falsified + /** Implicit method that makes a number of property operators on values of + * type [[Any]] available in the current scope. See [[Prop.ExtendedAny]] for + * documentation on the operators. */ + implicit def AnyOperators[T <% Pretty](x: => T) = new ExtendedAny[T](x) + + /** Implicit method that makes a number of property operators on boolean + * values available in the current scope. See [[Prop.ExtendedBoolean]] for + * documentation on the operators. */ + implicit def BooleanOperators(b: => Boolean) = new ExtendedBoolean(b) + + /** Implicit conversion of Boolean values to Prop values. */ + implicit def propBoolean(b: Boolean): Prop = Prop(b) // Private support functions @@ -318,6 +360,9 @@ object Prop { /** A property that denotes an exception */ lazy val exception: Prop = exception(null) + /** Create a property that compares to values. If the values aren't equal, + * the property will fail and report that first value doesn't match the + * expected (second) value. */ def ?=[T](x: T, y: T)(implicit pp: T => Pretty): Prop = if(x == y) proved else falsified :| { val exp = Pretty.pretty[T](y, Pretty.Params(0)) @@ -325,6 +370,9 @@ object Prop { "Expected "+exp+" but got "+act } + /** Create a property that compares to values. If the values aren't equal, + * the property will fail and report that second value doesn't match the + * expected (first) value. */ def =?[T](x: T, y: T)(implicit pp: T => Pretty): Prop = ?=(y, x) /** A property that depends on the generator size */ @@ -340,7 +388,7 @@ object Prop { secure(if(f.isDefinedAt(x)) f(x) else undecided) /** Property holds only if the given partial function is defined at - * <code>x</code>, and returns a property that holds */ + * `x`, and returns a property that holds */ def iff[T](x: T, f: PartialFunction[T,Prop]): Prop = secure(if(f.isDefinedAt(x)) f(x) else falsified) @@ -365,9 +413,16 @@ object Prop { def noneFailing[T](gs: Seq[Gen[T]]) = all(gs.map(_ !== fail):_*) /** A property that holds if the given statement throws an exception + * of the specified type + * @deprecated (in 1.10.1) Use `throws(...): Boolean` instead. + */ + @deprecated("Use 'throws(...): Boolean' instead", "1.10.1") + def throws[T <: Throwable](x: => Any, c: Class[T]): Prop = throws(c)(x) + + /** Returns true if the given statement throws an exception * of the specified type */ - def throws[T <: Throwable](x: => Any, c: Class[T]) = - try { x; falsified } catch { case e if c.isInstance(e) => proved } + def throws[T <: Throwable](c: Class[T])(x: => Any): Boolean = + try { x; false } catch { case e if c.isInstance(e) => true } /** Collect data for presentation in test report */ def collect[T, P <% Prop](f: T => P): T => Prop = t => Prop { prms => @@ -390,7 +445,7 @@ object Prop { /** Wraps and protects a property */ def secure[P <% Prop](p: => P): Prop = - try { p: Prop } catch { case e => exception(e) } + try { p: Prop } catch { case e: Throwable => exception(e) } /** Existential quantifier for an explicit generator. */ def exists[A,P](f: A => P)(implicit diff --git a/src/scalacheck/org/scalacheck/Properties.scala b/src/scalacheck/org/scalacheck/Properties.scala index 26059231d6..d4836d7420 100644 --- a/src/scalacheck/org/scalacheck/Properties.scala +++ b/src/scalacheck/org/scalacheck/Properties.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -14,15 +14,15 @@ package org.scalacheck * holds if and only if all of the contained properties hold. * <p>Properties are added in the following way:</p> * - * <p> - * <code> + * {{{ * object MyProps extends Properties("MyProps") { - * property("myProp1") = forAll { (n:Int, m:Int) => + * property("myProp1") = forAll { (n:Int, m:Int) => * n+m == m+n * } * * property("myProp2") = ((0/1) throws classOf[ArithmeticException]) * } + * }}} */ class Properties(val name: String) extends Prop { @@ -42,16 +42,27 @@ class Properties(val name: String) extends Prop { /** Convenience method that checks the properties with the given parameters * and reports the result on the console. If you need to get the results - * from the test use the <code>check</code> methods in <code>Test</code> + * from the test use the `check` methods in [[org.scalacheck.Test]] * instead. */ + override def check(prms: Test.Parameters): Unit = Test.checkProperties( + prms copy (_testCallback = ConsoleReporter(1) chain prms.testCallback), this + ) + + /** Convenience method that checks the properties with the given parameters + * and reports the result on the console. If you need to get the results + * from the test use the `check` methods in [[org.scalacheck.Test]] + * instead. + * @deprecated (in 1.10.0) Use `check(Test.Parameters)` instead. + */ + @deprecated("Use 'check(Test.Parameters)' instead", "1.10.0") override def check(prms: Test.Params): Unit = Test.checkProperties( prms copy (testCallback = ConsoleReporter(1) chain prms.testCallback), this ) /** Convenience method that checks the properties and reports the * result on the console. If you need to get the results from the test use - * the <code>check</code> methods in <code>Test</code> instead. */ - override def check: Unit = check(Test.Params()) + * the `check` methods in [[org.scalacheck.Test]] instead. */ + override def check: Unit = check(Test.Parameters.default) /** The logic for main, separated out to make it easier to * avoid System.exit calls. Returns exit code. @@ -73,7 +84,10 @@ class Properties(val name: String) extends Prop { def include(ps: Properties) = for((n,p) <- ps.properties) property(n) = p /** Used for specifying properties. Usage: - * <code>property("myProp") = ...</code> */ + * {{{ + * property("myProp") = ... + * }}} + */ class PropertySpecifier() { def update(propName: String, p: Prop) = props += ((name+"."+propName, p)) } diff --git a/src/scalacheck/org/scalacheck/ScalaCheckFramework.scala b/src/scalacheck/org/scalacheck/ScalaCheckFramework.scala new file mode 100644 index 0000000000..7764101844 --- /dev/null +++ b/src/scalacheck/org/scalacheck/ScalaCheckFramework.scala @@ -0,0 +1,92 @@ +/*-------------------------------------------------------------------------*\ +** ScalaCheck ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** +** http://www.scalacheck.org ** +** ** +** This software is released under the terms of the Revised BSD License. ** +** There is NO WARRANTY. See the file LICENSE for the full text. ** +\*------------------------------------------------------------------------ */ + +// vim: set ts=2 sw=2 et: + +package org.scalacheck + +import org.scalatools.testing._ + +class ScalaCheckFramework extends Framework { + + private case object PropFingerprint extends TestFingerprint { + val superClassName = "org.scalacheck.Prop" + val isModule = false + } + + private case object PropsFingerprint extends TestFingerprint { + val superClassName = "org.scalacheck.Properties" + val isModule = true + } + + val name = "ScalaCheck" + + val tests = Array[Fingerprint](PropsFingerprint, PropsFingerprint) + + def testRunner(loader: ClassLoader, loggers: Array[Logger]) = new Runner2 { + + private def asEvent(nr: (String, Test.Result)) = nr match { + case (n: String, r: Test.Result) => new Event { + val testName = n + val description = n + val result = r.status match { + case Test.Passed => Result.Success + case _:Test.Proved => Result.Success + case _:Test.Failed => Result.Failure + case Test.Exhausted => Result.Skipped + case _:Test.PropException | _:Test.GenException => Result.Error + } + val error = r.status match { + case Test.PropException(_, e, _) => e + case _:Test.Failed => new Exception(Pretty.pretty(r,Pretty.Params(0))) + case _ => null + } + } + } + + def run(testClassName: String, fingerprint: Fingerprint, handler: EventHandler, args: Array[String]) { + + val testCallback = new Test.TestCallback { + override def onPropEval(n: String, w: Int, s: Int, d: Int) = {} + + override def onTestResult(n: String, r: Test.Result) = { + for (l <- loggers) { + import Pretty._ + l.info( + (if (r.passed) "+ " else "! ") + n + ": " + pretty(r, Params(0)) + ) + } + handler.handle(asEvent((n,r))) + } + } + + import Test.cmdLineParser.{Success, NoSuccess} + val prms = Test.cmdLineParser.parseParams(args) match { + case Success(params, _) => + params.copy(_testCallback = testCallback, _customClassLoader = Some(loader)) + // TODO: Maybe handle this a bit better than throwing exception? + case e: NoSuccess => throw new Exception(e.toString) + } + + fingerprint match { + case fp: SubclassFingerprint => + if(fp.isModule) { + val obj = Class.forName(testClassName + "$", true, loader) + val ps = obj.getField("MODULE$").get(null).asInstanceOf[Properties] + Test.checkProperties(prms, ps) + } else { + val p = Class.forName(testClassName, true, loader).newInstance.asInstanceOf[Prop] + handler.handle(asEvent((testClassName, Test.check(prms, p)))) + } + } + } + + } + +} diff --git a/src/scalacheck/org/scalacheck/Shrink.scala b/src/scalacheck/org/scalacheck/Shrink.scala index ae15bd9616..4895171a35 100644 --- a/src/scalacheck/org/scalacheck/Shrink.scala +++ b/src/scalacheck/org/scalacheck/Shrink.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** diff --git a/src/scalacheck/org/scalacheck/Test.scala b/src/scalacheck/org/scalacheck/Test.scala index 4368184823..6e9b6b88fd 100644 --- a/src/scalacheck/org/scalacheck/Test.scala +++ b/src/scalacheck/org/scalacheck/Test.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -16,23 +16,120 @@ object Test { import Prop.FM import util.CmdLineParser - /** Test parameters */ + /** Test parameters used by the `Test.check` method. + */ + trait Parameters { + /** The minimum number of tests that must succeed for ScalaCheck to + * consider a property passed. */ + def minSuccessfulTests: Int + + /** The starting size given as parameter to the generators. */ + def minSize: Int + + /** The maximum size given as parameter to the generators. */ + def maxSize: Int + + /** The random numbe generator used. */ + def rng: java.util.Random + + /** The number of tests run in parallell. */ + def workers: Int + + /** A callback that ScalaCheck calls each time a test is executed. */ + def testCallback: TestCallback + + /** The maximum ratio between discarded and passed tests allowed before + * ScalaCheck gives up and discards the property. At least + * `minSuccesfulTests` will always be run, though. */ + def maxDiscardRatio: Float + + /** A custom class loader that should be used during test execution. */ + def customClassLoader: Option[ClassLoader] + + // private since we can't guarantee binary compatibility for this one + private[scalacheck] def copy( + _minSuccessfulTests: Int = Parameters.this.minSuccessfulTests, + _minSize: Int = Parameters.this.minSize, + _maxSize: Int = Parameters.this.maxSize, + _rng: java.util.Random = Parameters.this.rng, + _workers: Int = Parameters.this.workers, + _testCallback: TestCallback = Parameters.this.testCallback, + _maxDiscardRatio: Float = Parameters.this.maxDiscardRatio, + _customClassLoader: Option[ClassLoader] = Parameters.this.customClassLoader + ): Parameters = new Parameters { + val minSuccessfulTests: Int = _minSuccessfulTests + val minSize: Int = _minSize + val maxSize: Int = _maxSize + val rng: java.util.Random = _rng + val workers: Int = _workers + val testCallback: TestCallback = _testCallback + val maxDiscardRatio: Float = _maxDiscardRatio + val customClassLoader: Option[ClassLoader] = _customClassLoader + } + } + + /** Test parameters used by the `Test.check` method. + * + * To override default values, extend the + * [[org.scalacheck.Test.Parameters.Default]] trait: + * + * {{{ + * val myParams = new Parameters.Default { + * override val minSuccesfulTests = 600 + * override val maxDiscardRatio = 8 + * } + * }}} + */ + object Parameters { + /** Default test parameters trait. This can be overriden if you need to + * tweak the parameters. */ + trait Default extends Parameters { + val minSuccessfulTests: Int = 100 + val minSize: Int = 0 + val maxSize: Int = Gen.Params().size + val rng: java.util.Random = Gen.Params().rng + val workers: Int = 1 + val testCallback: TestCallback = new TestCallback {} + val maxDiscardRatio: Float = 5 + val customClassLoader: Option[ClassLoader] = None + } + + /** Default test parameters instance. */ + val default: Parameters = new Default {} + } + + /** Test parameters + * @deprecated (in 1.10.0) Use [[org.scalacheck.Test.Parameters]] instead. + */ + @deprecated("Use [[org.scalacheck.Test.Parameters]] instead", "1.10.0") case class Params( minSuccessfulTests: Int = 100, - - /** @deprecated Use maxDiscardRatio instead. */ - @deprecated("Use maxDiscardRatio instead.", "1.10") maxDiscardedTests: Int = -1, - minSize: Int = 0, maxSize: Int = Gen.Params().size, rng: java.util.Random = Gen.Params().rng, workers: Int = 1, - testCallback: TestCallback = new TestCallback {}, - maxDiscardRatio: Float = 5, - customClassLoader: Option[ClassLoader] = None + testCallback: TestCallback = new TestCallback {} ) + @deprecated("Use [[org.scalacheck.Test.Parameters]] instead", "1.10.0") + private def paramsToParameters(params: Params) = new Parameters { + val minSuccessfulTests = params.minSuccessfulTests + val minSize = params.minSize + val maxSize = params.maxSize + val rng = params.rng + val workers = params.workers + val testCallback = params.testCallback + + // maxDiscardedTests is deprecated, but if someone + // uses it let it override maxDiscardRatio + val maxDiscardRatio = + if(params.maxDiscardedTests < 0) Parameters.default.maxDiscardRatio + else (params.maxDiscardedTests: Float)/(params.minSuccessfulTests: Float) + + val customClassLoader = Parameters.default.customClassLoader + } + /** Test statistics */ case class Result(status: Status, succeeded: Int, discarded: Int, freqMap: FM, time: Long = 0) { def passed = status match { @@ -92,7 +189,7 @@ object Test { } } - private def assertParams(prms: Params) = { + private def assertParams(prms: Parameters) = { import prms._ if( minSuccessfulTests <= 0 || @@ -104,16 +201,24 @@ object Test { } private def secure[T](x: => T): Either[T,Throwable] = - try { Left(x) } catch { case e => Right(e) } + try { Left(x) } catch { case e: Throwable => Right(e) } private[scalacheck] lazy val cmdLineParser = new CmdLineParser { object OptMinSuccess extends IntOpt { - val default = Test.Params().minSuccessfulTests + val default = Parameters.default.minSuccessfulTests val names = Set("minSuccessfulTests", "s") val help = "Number of tests that must succeed in order to pass a property" } + object OptMaxDiscarded extends IntOpt { + val default = -1 + val names = Set("maxDiscardedTests", "d") + val help = + "Number of tests that can be discarded before ScalaCheck stops " + + "testing a property. NOTE: this option is deprecated, please use " + + "the option maxDiscardRatio (-r) instead." + } object OptMaxDiscardRatio extends FloatOpt { - val default = Test.Params().maxDiscardRatio + val default = Parameters.default.maxDiscardRatio val names = Set("maxDiscardRatio", "r") val help = "The maximum ratio between discarded and succeeded tests " + @@ -121,17 +226,17 @@ object Test { "least minSuccessfulTests will always be tested, though." } object OptMinSize extends IntOpt { - val default = Test.Params().minSize + val default = Parameters.default.minSize val names = Set("minSize", "n") val help = "Minimum data generation size" } object OptMaxSize extends IntOpt { - val default = Test.Params().maxSize + val default = Parameters.default.maxSize val names = Set("maxSize", "x") val help = "Maximum data generation size" } object OptWorkers extends IntOpt { - val default = Test.Params().workers + val default = Parameters.default.workers val names = Set("workers", "w") val help = "Number of threads to execute in parallel for testing" } @@ -142,54 +247,63 @@ object Test { } val opts = Set[Opt[_]]( - OptMinSuccess, OptMaxDiscardRatio, OptMinSize, + OptMinSuccess, OptMaxDiscarded, OptMaxDiscardRatio, OptMinSize, OptMaxSize, OptWorkers, OptVerbosity ) def parseParams(args: Array[String]) = parseArgs(args) { - optMap => Test.Params( - minSuccessfulTests = optMap(OptMinSuccess), - maxDiscardRatio = optMap(OptMaxDiscardRatio), - minSize = optMap(OptMinSize), - maxSize = optMap(OptMaxSize), - rng = Test.Params().rng, - workers = optMap(OptWorkers), - testCallback = ConsoleReporter(optMap(OptVerbosity)) + optMap => Parameters.default.copy( + _minSuccessfulTests = optMap(OptMinSuccess), + _maxDiscardRatio = + if (optMap(OptMaxDiscarded) < 0) optMap(OptMaxDiscardRatio) + else optMap(OptMaxDiscarded).toFloat / optMap(OptMinSuccess), + _minSize = optMap(OptMinSize), + _maxSize = optMap(OptMaxSize), + _workers = optMap(OptWorkers), + _testCallback = ConsoleReporter(optMap(OptVerbosity)) ) } } /** Tests a property with the given testing parameters, and returns - * the test results. */ + * the test results. + * @deprecated (in 1.10.0) Use + * `check(Parameters, Properties)` instead. + */ + @deprecated("Use 'checkProperties(Parameters, Properties)' instead", "1.10.0") def check(params: Params, p: Prop): Result = { + check(paramsToParameters(params), p) + } - // maxDiscardedTests is deprecated, but if someone - // uses it let it override maxDiscardRatio - val mdr = - if(params.maxDiscardedTests < 0) params.maxDiscardRatio - else (params.maxDiscardedTests: Float)/(params.minSuccessfulTests: Float) - val prms = params.copy( maxDiscardRatio = mdr) - - import prms._ - import scala.actors.Futures.future + /** Tests a property with the given testing parameters, and returns + * the test results. */ + def check(params: Parameters, p: Prop): Result = { + import params._ - assertParams(prms) - if(workers > 1) + assertParams(params) + if(workers > 1) { assert(!p.isInstanceOf[Commands], "Commands cannot be checked multi-threaded") + } val iterations = math.ceil(minSuccessfulTests / (workers: Double)) val sizeStep = (maxSize-minSize) / (iterations*workers) var stop = false - def worker(workerIdx: Int) = future { - params.customClassLoader.map(Thread.currentThread.setContextClassLoader(_)) + def worker(workerIdx: Int) = + if (workers < 2) () => workerFun(workerIdx) + else actors.Futures.future { + params.customClassLoader.map(Thread.currentThread.setContextClassLoader(_)) + workerFun(workerIdx) + } + + def workerFun(workerIdx: Int) = { var n = 0 // passed tests var d = 0 // discarded tests var res: Result = null var fm = FreqMap.empty[immutable.Set[Any]] while(!stop && res == null && n < iterations) { val size = (minSize: Double) + (sizeStep * (workerIdx + (workers*(n+d)))) - val propPrms = Prop.Params(Gen.Params(size.round.toInt, prms.rng), fm) + val propPrms = Prop.Params(Gen.Params(size.round.toInt, params.rng), fm) secure(p(propPrms)) match { case Right(e) => res = Result(GenException(e), n, d, FreqMap.empty[immutable.Set[Any]]) @@ -250,11 +364,20 @@ object Test { stop = true results foreach (_.apply()) val timedRes = r.copy(time = System.currentTimeMillis-start) - prms.testCallback.onTestResult("", timedRes) + params.testCallback.onTestResult("", timedRes) timedRes } + /** Check a set of properties. + * @deprecated (in 1.10.0) Use + * `checkProperties(Parameters, Properties)` instead. + */ + @deprecated("Use 'checkProperties(Parameters, Properties)' instead", "1.10.0") def checkProperties(prms: Params, ps: Properties): Seq[(String,Result)] = + checkProperties(paramsToParameters(prms), ps) + + /** Check a set of properties. */ + def checkProperties(prms: Parameters, ps: Properties): Seq[(String,Result)] = ps.properties.map { case (name,p) => val testCallback = new TestCallback { override def onPropEval(n: String, t: Int, s: Int, d: Int) = @@ -262,7 +385,7 @@ object Test { override def onTestResult(n: String, r: Result) = prms.testCallback.onTestResult(name,r) } - val res = check(prms copy (testCallback = testCallback), p) + val res = check(prms copy (_testCallback = testCallback), p) (name,res) } diff --git a/src/scalacheck/org/scalacheck/util/Buildable.scala b/src/scalacheck/org/scalacheck/util/Buildable.scala index 221b8a61c3..140c541a95 100644 --- a/src/scalacheck/org/scalacheck/util/Buildable.scala +++ b/src/scalacheck/org/scalacheck/util/Buildable.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -10,7 +10,6 @@ package org.scalacheck.util import scala.collection._ -import scala.reflect.ClassTag trait Buildable[T,C[_]] { def builder: mutable.Builder[T,C[T]] @@ -31,7 +30,7 @@ object Buildable { def builder = (new mutable.ListBuffer[T]).mapResult(_.toStream) } - implicit def buildableArray[T](implicit cm: ClassTag[T]) = + implicit def buildableArray[T](implicit cm: ClassManifest[T]) = new Buildable[T,Array] { def builder = mutable.ArrayBuilder.make[T] } diff --git a/src/scalacheck/org/scalacheck/util/CmdLineParser.scala b/src/scalacheck/org/scalacheck/util/CmdLineParser.scala index 4683c34a65..eb3a91fe59 100644 --- a/src/scalacheck/org/scalacheck/util/CmdLineParser.scala +++ b/src/scalacheck/org/scalacheck/util/CmdLineParser.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** @@ -30,7 +30,7 @@ trait CmdLineParser extends Parsers { trait StrOpt extends Opt[String] class OptMap { - private val opts = new scala.collection.mutable.HashMap[Opt[_], Any] + private val opts = new collection.mutable.HashMap[Opt[_], Any] def apply(flag: Flag): Boolean = opts.contains(flag) def apply[T](opt: Opt[T]): T = opts.get(opt) match { case None => opt.default diff --git a/src/scalacheck/org/scalacheck/util/FreqMap.scala b/src/scalacheck/org/scalacheck/util/FreqMap.scala index c7474d3b87..d0686aec72 100644 --- a/src/scalacheck/org/scalacheck/util/FreqMap.scala +++ b/src/scalacheck/org/scalacheck/util/FreqMap.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** diff --git a/src/scalacheck/org/scalacheck/util/StdRand.scala b/src/scalacheck/org/scalacheck/util/StdRand.scala index 317b0ccd10..7c1dc8dcc4 100644 --- a/src/scalacheck/org/scalacheck/util/StdRand.scala +++ b/src/scalacheck/org/scalacheck/util/StdRand.scala @@ -1,6 +1,6 @@ /*-------------------------------------------------------------------------*\ ** ScalaCheck ** -** Copyright (c) 2007-2011 Rickard Nilsson. All rights reserved. ** +** Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved. ** ** http://www.scalacheck.org ** ** ** ** This software is released under the terms of the Revised BSD License. ** diff --git a/src/scaladoc/scala/tools/nsc/doc/ScaladocAnalyzer.scala b/src/scaladoc/scala/tools/nsc/doc/ScaladocAnalyzer.scala index 003c439f65..d407b93a4b 100644 --- a/src/scaladoc/scala/tools/nsc/doc/ScaladocAnalyzer.scala +++ b/src/scaladoc/scala/tools/nsc/doc/ScaladocAnalyzer.scala @@ -11,6 +11,8 @@ import scala.reflect.internal.Chars._ import symtab._ import typechecker.Analyzer import scala.reflect.internal.util.{ BatchSourceFile, RangePosition } +import scala.tools.nsc.doc.base.{ CommentFactoryBase, MemberLookupBase, LinkTo, LinkToExternal } +import scala.language.postfixOps trait ScaladocAnalyzer extends Analyzer { val global : Global // generally, a ScaladocGlobal @@ -151,27 +153,25 @@ abstract class ScaladocSyntaxAnalyzer[G <: Global](val global: G) extends Syntax private var docBuffer: StringBuilder = null // buffer for comments (non-null while scanning) private var inDocComment = false // if buffer contains double-star doc comment - private var lastDoc: DocComment = null // last comment if it was double-star doc + private var lastDoc: DocComment = null // last comment if it was double-star doc - private lazy val unmooredParser = { // minimalist comment parser - import scala.tools.nsc.doc.base.{comment => _, _} - new { - val global: Global = ScaladocSyntaxAnalyzer.this.global - } with CommentFactoryBase with MemberLookupBase { - import global.{ settings, Symbol } - def parseComment(comment: DocComment) = { - val nowarnings = settings.nowarn.value - settings.nowarn.value = true - try parseAtSymbol(comment.raw, comment.raw, comment.pos) - finally settings.nowarn.value = nowarnings - } - - override def internalLink(sym: Symbol, site: Symbol): Option[LinkTo] = None - override def chooseLink(links: List[LinkTo]): LinkTo = links.headOption orNull - override def toString(link: LinkTo): String = "No link" - override def findExternalLink(sym: Symbol, name: String): Option[LinkToExternal] = None - override def warnNoLink: Boolean = false + private object unmooredParser extends { // minimalist comment parser + val global: Global = ScaladocSyntaxAnalyzer.this.global + } + with CommentFactoryBase with MemberLookupBase { + import global.{ settings, Symbol } + def parseComment(comment: DocComment) = { + val nowarnings = settings.nowarn.value + settings.nowarn.value = true + try parseAtSymbol(comment.raw, comment.raw, comment.pos) + finally settings.nowarn.value = nowarnings } + + override def internalLink(sym: Symbol, site: Symbol): Option[LinkTo] = None + override def chooseLink(links: List[LinkTo]): LinkTo = links.headOption orNull + override def toString(link: LinkTo): String = "No link" + override def findExternalLink(sym: Symbol, name: String): Option[LinkToExternal] = None + override def warnNoLink: Boolean = false } /** diff --git a/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala b/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala index 9edd5afa13..159e16375c 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala @@ -3,7 +3,9 @@ * @author David Bernard, Manohar Jonnalagedda */ -package scala.tools.nsc +package scala +package tools +package nsc package doc package html diff --git a/src/scaladoc/scala/tools/nsc/doc/html/Page.scala b/src/scaladoc/scala/tools/nsc/doc/html/Page.scala index 91939cf3de..93950fd0a7 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/Page.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/Page.scala @@ -3,7 +3,8 @@ * @author David Bernard, Manohar Jonnalagedda */ -package scala.tools.nsc.doc.html +package scala +package tools.nsc.doc.html import scala.tools.nsc.doc.model._ import java.io.{FileOutputStream, File} diff --git a/src/scaladoc/scala/tools/nsc/doc/html/SyntaxHigh.scala b/src/scaladoc/scala/tools/nsc/doc/html/SyntaxHigh.scala index 348ea97c5b..fe0fc64033 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/SyntaxHigh.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/SyntaxHigh.scala @@ -3,7 +3,8 @@ * @author Stephane Micheloud */ -package scala.tools.nsc.doc.html +package scala +package tools.nsc.doc.html import scala.xml.NodeSeq import scala.annotation.tailrec diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala index a74c2eedbd..84ee82f994 100755 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala @@ -3,10 +3,13 @@ * @author Pedro Furlanetto */ -package scala.tools.nsc +package scala +package tools +package nsc package doc package html package page + import doc.model._ class ReferenceIndex(letter: Char, index: doc.Index, universe: Universe) extends HtmlPage { diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala index 63509de4b5..45b169cdfc 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala @@ -3,7 +3,9 @@ * @author David Bernard, Manohar Jonnalagedda */ -package scala.tools.nsc +package scala +package tools +package nsc package doc package html package page diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala index 7d146b4a5f..4ff436bdc6 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala @@ -2,7 +2,9 @@ * @author Damien Obrist * @author Vlad Ureche */ -package scala.tools.nsc +package scala +package tools +package nsc package doc package html package page diff --git a/src/scaladoc/scala/tools/nsc/doc/model/IndexModelFactory.scala b/src/scaladoc/scala/tools/nsc/doc/model/IndexModelFactory.scala index 1272906df5..53410fd4ad 100755 --- a/src/scaladoc/scala/tools/nsc/doc/model/IndexModelFactory.scala +++ b/src/scaladoc/scala/tools/nsc/doc/model/IndexModelFactory.scala @@ -3,7 +3,8 @@ * @author Pedro Furlanetto */ -package scala.tools.nsc +package scala +package tools.nsc package doc package model diff --git a/src/scaladoc/scala/tools/nsc/doc/model/ModelFactory.scala b/src/scaladoc/scala/tools/nsc/doc/model/ModelFactory.scala index cc228082c1..aeae9b8a78 100644 --- a/src/scaladoc/scala/tools/nsc/doc/model/ModelFactory.scala +++ b/src/scaladoc/scala/tools/nsc/doc/model/ModelFactory.scala @@ -1,6 +1,7 @@ /* NSC -- new Scala compiler -- Copyright 2007-2013 LAMP/EPFL */ -package scala.tools.nsc +package scala +package tools.nsc package doc package model @@ -9,11 +10,9 @@ import diagram._ import scala.collection._ import scala.util.matching.Regex - import symtab.Flags import io._ - import model.{ RootPackage => RootPackageEntity } /** This trait extracts all required information for documentation from compilation units */ @@ -837,36 +836,36 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { } } - /** */ def makeAnnotation(annot: AnnotationInfo): scala.tools.nsc.doc.model.Annotation = { val aSym = annot.symbol new EntityImpl(aSym, makeTemplate(aSym.owner)) with scala.tools.nsc.doc.model.Annotation { lazy val annotationClass = makeTemplate(annot.symbol) - val arguments = { // lazy - def annotArgs = annot.args match { - case Nil => annot.assocs collect { case (_, LiteralAnnotArg(const)) => Literal(const) } - case xs => xs - } - def noParams = annotArgs map (_ => None) - - val params: List[Option[ValueParam]] = annotationClass match { + val arguments = { + val paramsOpt: Option[List[ValueParam]] = annotationClass match { case aClass: DocTemplateEntity with Class => - (aClass.primaryConstructor map { _.valueParams.head }) match { - case Some(vps) => vps map { Some(_) } - case _ => noParams + val constr = aClass.constructors collectFirst { + case c: MemberImpl if c.sym == annot.original.symbol => c } - case _ => noParams + constr flatMap (_.valueParams.headOption) + case _ => None } - assert(params.length == annotArgs.length, (params, annotArgs)) - - params zip annotArgs flatMap { case (param, arg) => - makeTree(arg) map { tree => - new ValueArgument { - def parameter = param - def value = tree + val argTrees = annot.args map makeTree + paramsOpt match { + case Some (params) => + params zip argTrees map { case (param, tree) => + new ValueArgument { + def parameter = Some(param) + def value = tree + } + } + case None => + argTrees map { tree => + new ValueArgument { + def parameter = None + def value = tree + } } - } } } } @@ -906,9 +905,8 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { sym.name == aSym.name && sym.isParamWithDefault ) - (unit.body find (t => isCorrespondingParam(t.symbol))) match { - case Some(ValDef(_,_,_,rhs)) => makeTree(rhs) - case _ => None + unit.body find (t => isCorrespondingParam(t.symbol)) collect { + case ValDef(_,_,_,rhs) if rhs ne EmptyTree => makeTree(rhs) } case _ => None } diff --git a/src/scaladoc/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala b/src/scaladoc/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala index 1f87f935f2..6cefe34887 100644 --- a/src/scaladoc/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala +++ b/src/scaladoc/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala @@ -226,12 +226,9 @@ trait ModelFactoryImplicitSupport { // look for type variables in the type. If there are none, we can decide if the implicit is there or not if (implType.isTrivial) { try { - context.flushBuffer() /* any errors here should not prevent future findings */ - // TODO: Not sure this is the right thing to do -- seems similar to what scalac should be doing - val context2 = context.make(context.unit, context.tree, sym.owner, context.scope, context.imports) - val search = inferImplicit(EmptyTree, tpe, false, false, context2, false) - context.flushBuffer() /* any errors here should not prevent future findings */ - + // TODO: Not sure if `owner = sym.owner` is the right thing to do -- seems similar to what scalac should be doing + val silentContext = context.make(owner = sym.owner).makeSilent(reportAmbiguousErrors = false) + val search = inferImplicit(EmptyTree, tpe, false, false, silentContext, false) available = Some(search.tree != EmptyTree) } catch { case _: TypeError => diff --git a/src/scaladoc/scala/tools/nsc/doc/model/TreeFactory.scala b/src/scaladoc/scala/tools/nsc/doc/model/TreeFactory.scala index b972649194..b381176b17 100755 --- a/src/scaladoc/scala/tools/nsc/doc/model/TreeFactory.scala +++ b/src/scaladoc/scala/tools/nsc/doc/model/TreeFactory.scala @@ -19,7 +19,7 @@ trait TreeFactory { thisTreeFactory: ModelFactory with TreeFactory => val global: Global import global._ - def makeTree(rhs: Tree): Option[TreeEntity] = { + def makeTree(rhs: Tree): TreeEntity = { val expr = new StringBuilder var refs = new immutable.TreeMap[Int, (Entity, Int)] // start, (Entity to be linked to , end) @@ -80,17 +80,16 @@ trait TreeFactory { thisTreeFactory: ModelFactory with TreeFactory => traverser.traverse(rhs) - Some(new TreeEntity { + new TreeEntity { val expression = expr.toString val refEntity = refs - }) + } } - case pos: OffsetPosition => - Some(new TreeEntity { + case _ => + new TreeEntity { val expression = rhs.toString val refEntity = new immutable.TreeMap[Int, (Entity, Int)] - }) - case _ => None + } } } } diff --git a/src/scalap/scala/tools/scalap/ByteArrayReader.scala b/src/scalap/scala/tools/scalap/ByteArrayReader.scala index bb001623a8..9c72bdbf1e 100644 --- a/src/scalap/scala/tools/scalap/ByteArrayReader.scala +++ b/src/scalap/scala/tools/scalap/ByteArrayReader.scala @@ -6,7 +6,8 @@ */ -package scala.tools.scalap +package scala +package tools.scalap class ByteArrayReader(content: Array[Byte]) { diff --git a/src/scalap/scala/tools/scalap/CodeWriter.scala b/src/scalap/scala/tools/scalap/CodeWriter.scala index 8254c2dfce..fe594c14cf 100644 --- a/src/scalap/scala/tools/scalap/CodeWriter.scala +++ b/src/scalap/scala/tools/scalap/CodeWriter.scala @@ -6,7 +6,8 @@ */ -package scala.tools.scalap +package scala +package tools.scalap import java.io._ diff --git a/src/scalap/scala/tools/scalap/Main.scala b/src/scalap/scala/tools/scalap/Main.scala index 90f8cb8d71..5da4227e53 100644 --- a/src/scalap/scala/tools/scalap/Main.scala +++ b/src/scalap/scala/tools/scalap/Main.scala @@ -5,7 +5,8 @@ ** */ -package scala.tools.scalap +package scala +package tools.scalap import java.io.{ PrintStream, OutputStreamWriter, ByteArrayOutputStream } import scala.reflect.NameTransformer diff --git a/src/scalap/scala/tools/scalap/MetaParser.scala b/src/scalap/scala/tools/scalap/MetaParser.scala index 00678ab504..8b4ffb3efd 100644 --- a/src/scalap/scala/tools/scalap/MetaParser.scala +++ b/src/scalap/scala/tools/scalap/MetaParser.scala @@ -6,7 +6,8 @@ */ -package scala.tools.scalap +package scala +package tools.scalap import java.io._ import java.util._ diff --git a/src/swing/scala/swing/Action.scala b/src/swing/scala/swing/Action.scala index 8740f63e98..98b9fee2ee 100644 --- a/src/swing/scala/swing/Action.scala +++ b/src/swing/scala/swing/Action.scala @@ -35,7 +35,12 @@ object Action { // TODO: we need an action cache private var _action: Action = Action.NoAction def action: Action = _action - def action_=(a: Action) { _action = a; peer.setAction(a.peer) } + def action_=(a: Action) { + _action = a; + + import scala.language.reflectiveCalls + peer.setAction(a.peer) + } //1.6: def hideActionText: Boolean = peer.getHideActionText //def hideActionText_=(b: Boolean) = peer.setHideActionText(b) diff --git a/src/swing/scala/swing/ComboBox.scala b/src/swing/scala/swing/ComboBox.scala index ce2b3ba6fb..a075d22a7e 100644 --- a/src/swing/scala/swing/ComboBox.scala +++ b/src/swing/scala/swing/ComboBox.scala @@ -11,6 +11,7 @@ package scala.swing import event._ import javax.swing.{JList, JComponent, JComboBox, JTextField, ComboBoxModel, AbstractListModel, ListCellRenderer} import java.awt.event.ActionListener +import scala.language.implicitConversions object ComboBox { /** diff --git a/src/swing/scala/swing/GridBagPanel.scala b/src/swing/scala/swing/GridBagPanel.scala index 7d181af4d8..c58d398737 100644 --- a/src/swing/scala/swing/GridBagPanel.scala +++ b/src/swing/scala/swing/GridBagPanel.scala @@ -9,6 +9,7 @@ package scala.swing import java.awt.{GridBagConstraints, GridBagLayout} +import scala.language.implicitConversions object GridBagPanel { object Fill extends Enumeration { diff --git a/src/swing/scala/swing/Orientable.scala b/src/swing/scala/swing/Orientable.scala index a73bafb9d3..db7cf09f27 100644 --- a/src/swing/scala/swing/Orientable.scala +++ b/src/swing/scala/swing/Orientable.scala @@ -12,7 +12,10 @@ package scala.swing object Orientable { trait Wrapper extends Oriented.Wrapper with Orientable { - def orientation_=(o: Orientation.Value) { peer.setOrientation(o.id) } + def orientation_=(o: Orientation.Value) { + import scala.language.reflectiveCalls + peer.setOrientation(o.id) + } } } diff --git a/src/swing/scala/swing/Oriented.scala b/src/swing/scala/swing/Oriented.scala index 7996d21898..72d7d574e2 100644 --- a/src/swing/scala/swing/Oriented.scala +++ b/src/swing/scala/swing/Oriented.scala @@ -22,6 +22,7 @@ object Oriented { def getOrientation(): Int def setOrientation(n: Int) } + import scala.language.reflectiveCalls def orientation: Orientation.Value = Orientation(peer.getOrientation) } } diff --git a/src/swing/scala/swing/Slider.scala b/src/swing/scala/swing/Slider.scala index e329c31a01..241876587b 100644 --- a/src/swing/scala/swing/Slider.scala +++ b/src/swing/scala/swing/Slider.scala @@ -53,7 +53,7 @@ class Slider extends Component with Orientable.Wrapper with Publisher { def labels: scala.collection.Map[Int, Label] = { val labelTable = peer.getLabelTable.asInstanceOf[java.util.Hashtable[Int, JLabel]] - new scala.collection.JavaConversions.JMapWrapper(labelTable) + new scala.collection.convert.Wrappers.JMapWrapper(labelTable) .mapValues(v => UIElement.cachedWrapper[Label](v)) } def labels_=(l: scala.collection.Map[Int, Label]) { diff --git a/src/swing/scala/swing/Swing.scala b/src/swing/scala/swing/Swing.scala index cd5bbf2c4f..e2c8479354 100644 --- a/src/swing/scala/swing/Swing.scala +++ b/src/swing/scala/swing/Swing.scala @@ -14,6 +14,7 @@ import java.awt.event._ import javax.swing.event._ import javax.swing.border._ import javax.swing.{JComponent, Icon, BorderFactory, SwingUtilities} +import scala.language.implicitConversions /** diff --git a/src/swing/scala/swing/package.scala b/src/swing/scala/swing/package.scala index 45497665d7..d5095f021b 100644 --- a/src/swing/scala/swing/package.scala +++ b/src/swing/scala/swing/package.scala @@ -14,9 +14,6 @@ package object swing { type Image = java.awt.Image type Font = java.awt.Font - implicit lazy val reflectiveCalls = scala.language.reflectiveCalls - implicit lazy val implicitConversions = scala.language.implicitConversions - private[swing] def ifNull[A](o: Object, a: A): A = if(o eq null) a else o.asInstanceOf[A] private[swing] def toOption[A](o: Object): Option[A] = if(o eq null) None else Some(o.asInstanceOf[A]) private[swing] def toAnyRef(x: Any): AnyRef = x.asInstanceOf[AnyRef] |