diff options
author | Paul Phillips <paulp@improving.org> | 2012-09-14 12:10:57 -0700 |
---|---|---|
committer | Paul Phillips <paulp@improving.org> | 2012-09-15 08:01:19 -0700 |
commit | 3262f7072b4060b1058acb6d772eaa61d4dec1d4 (patch) | |
tree | 8a4e0f285145d1f429096ad8dc08b90e846b5c38 /src/compiler | |
parent | 930c85d6c96507d798d1847ea078eebf93dc0acb (diff) | |
parent | 83c1b1062957e50e5336c1b3409e54e0a5cce275 (diff) | |
download | scala-3262f7072b4060b1058acb6d772eaa61d4dec1d4.tar.gz scala-3262f7072b4060b1058acb6d772eaa61d4dec1d4.tar.bz2 scala-3262f7072b4060b1058acb6d772eaa61d4dec1d4.zip |
Merge remote-tracking branch 'origin/2.10.x' into merge-210
* origin/2.10.x: (68 commits)
Eliminate breaking relative names in source.
"Hot fix" for broken build.
Fix SI-4813 - Clone doesn't work on LinkedList.
Made 'def clone()' consistent with parens everywhere.
accommodates pull request feedback
SI-6310 redeploys the starr
SI-6310 AbsTypeTag => WeakTypeTag
SI-6323 outlaws free types from TypeTag
SI-6323 prohibits reflection against free types
improvements for reification of free symbols
removes build.newFreeExistential
SI-6359 Deep prohibition of templates in value class
Fixes SI-6259. Unable to use typeOf in super call of top-level object.
Fixes binary repo push for new typesafe repo layouts.
Better error message for pattern arity errors.
Rescued TreeBuilder from the parser.
Pending test for SI-3943
Test case for a bug fixed in M7.
Fix for SI-6367, exponential time in inference.
SI-6306 Remove incorrect eta-expansion optimization in Uncurry
...
Conflicts:
src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala
Diffstat (limited to 'src/compiler')
144 files changed, 730 insertions, 616 deletions
diff --git a/src/compiler/scala/reflect/macros/runtime/Aliases.scala b/src/compiler/scala/reflect/macros/runtime/Aliases.scala index 5e15b61dbd..30e72997f7 100644 --- a/src/compiler/scala/reflect/macros/runtime/Aliases.scala +++ b/src/compiler/scala/reflect/macros/runtime/Aliases.scala @@ -17,12 +17,12 @@ trait Aliases { override type Expr[+T] = universe.Expr[T] override val Expr = universe.Expr - override type AbsTypeTag[T] = universe.AbsTypeTag[T] + override type WeakTypeTag[T] = universe.WeakTypeTag[T] override type TypeTag[T] = universe.TypeTag[T] - override val AbsTypeTag = universe.AbsTypeTag + override val WeakTypeTag = universe.WeakTypeTag override val TypeTag = universe.TypeTag - override def absTypeTag[T](implicit attag: AbsTypeTag[T]) = attag + override def weakTypeTag[T](implicit attag: WeakTypeTag[T]) = attag override def typeTag[T](implicit ttag: TypeTag[T]) = ttag - override def absTypeOf[T](implicit attag: AbsTypeTag[T]): Type = attag.tpe + override def weakTypeOf[T](implicit attag: WeakTypeTag[T]): Type = attag.tpe override def typeOf[T](implicit ttag: TypeTag[T]): Type = ttag.tpe }
\ No newline at end of file diff --git a/src/compiler/scala/reflect/macros/runtime/Exprs.scala b/src/compiler/scala/reflect/macros/runtime/Exprs.scala index 4217a6a404..ebf8fa2b96 100644 --- a/src/compiler/scala/reflect/macros/runtime/Exprs.scala +++ b/src/compiler/scala/reflect/macros/runtime/Exprs.scala @@ -4,5 +4,5 @@ package runtime trait Exprs { self: Context => - def Expr[T: AbsTypeTag](tree: Tree): Expr[T] = universe.Expr[T](mirror, universe.FixedMirrorTreeCreator(mirror, tree)) + def Expr[T: WeakTypeTag](tree: Tree): Expr[T] = universe.Expr[T](mirror, universe.FixedMirrorTreeCreator(mirror, tree)) } diff --git a/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala b/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala index 0a8a8d015d..77ac8c6581 100644 --- a/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala +++ b/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala @@ -34,7 +34,7 @@ trait Infrastructure { val currentMacro: Symbol = expandee.symbol - val globalCache: collection.mutable.Map[Any, Any] = universe.analyzer.globalMacroCache + val globalCache: scala.collection.mutable.Map[Any, Any] = universe.analyzer.globalMacroCache - val cache: collection.mutable.Map[Any, Any] = universe.analyzer.perRunMacroCache.getOrElseUpdate(currentMacro, collection.mutable.Map[Any, Any]()) -}
\ No newline at end of file + val cache: scala.collection.mutable.Map[Any, Any] = universe.analyzer.perRunMacroCache.getOrElseUpdate(currentMacro, collection.mutable.Map[Any, Any]()) +} diff --git a/src/compiler/scala/reflect/macros/runtime/Parsers.scala b/src/compiler/scala/reflect/macros/runtime/Parsers.scala index 6d89b71f39..e4acf104e3 100644 --- a/src/compiler/scala/reflect/macros/runtime/Parsers.scala +++ b/src/compiler/scala/reflect/macros/runtime/Parsers.scala @@ -1,7 +1,7 @@ package scala.reflect.macros package runtime -import language.existentials +import scala.language.existentials import scala.tools.reflect.ToolBox import scala.tools.reflect.ToolBoxError @@ -22,4 +22,4 @@ trait Parsers { case class ParseError(val pos: Position, val msg: String) extends Throwable(msg) object ParseError extends ParseErrorExtractor -}
\ No newline at end of file +} diff --git a/src/compiler/scala/reflect/macros/runtime/TypeTags.scala b/src/compiler/scala/reflect/macros/runtime/TypeTags.scala index 2bc2fe6384..19b60159de 100644 --- a/src/compiler/scala/reflect/macros/runtime/TypeTags.scala +++ b/src/compiler/scala/reflect/macros/runtime/TypeTags.scala @@ -4,6 +4,6 @@ package runtime trait TypeTags { self: Context => - def AbsTypeTag[T](tpe: Type): AbsTypeTag[T] = universe.AbsTypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) + def WeakTypeTag[T](tpe: Type): WeakTypeTag[T] = universe.WeakTypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) def TypeTag[T](tpe: Type): TypeTag[T] = universe.TypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) } diff --git a/src/compiler/scala/reflect/reify/Errors.scala b/src/compiler/scala/reflect/reify/Errors.scala index 5e15c5ad3a..73c13901b6 100644 --- a/src/compiler/scala/reflect/reify/Errors.scala +++ b/src/compiler/scala/reflect/reify/Errors.scala @@ -27,8 +27,8 @@ trait Errors { throw new ReificationError(defaultErrorPosition, msg) } - def CannotReifyTypeTagHavingUnresolvedTypeParameters(tpe: Type) = { - val msg = "cannot reify TypeTag having unresolved type parameter %s".format(tpe) + def CannotReifyWeakType(details: Any) = { + val msg = "cannot create a TypeTag" + details throw new ReificationError(defaultErrorPosition, msg) } diff --git a/src/compiler/scala/reflect/reify/States.scala b/src/compiler/scala/reflect/reify/States.scala index a01cfe5d74..58455c9f3c 100644 --- a/src/compiler/scala/reflect/reify/States.scala +++ b/src/compiler/scala/reflect/reify/States.scala @@ -34,9 +34,11 @@ trait States { def reificationIsConcrete_=(value: Boolean): Unit = { _reificationIsConcrete = value if (!value && concrete) { - assert(current.isInstanceOf[Type], current) - val offender = current.asInstanceOf[Type] - CannotReifyTypeTagHavingUnresolvedTypeParameters(offender) + current match { + case tpe: Type => CannotReifyWeakType(s" having unresolved type parameter $tpe") + case sym: Symbol => CannotReifyWeakType(s" referring to local ${sym.kindString} ${sym.fullName}") + case _ => CannotReifyWeakType("") + } } } var reifyStack = reifee :: Nil diff --git a/src/compiler/scala/reflect/reify/Taggers.scala b/src/compiler/scala/reflect/reify/Taggers.scala index a8523fe686..bc12d383a4 100644 --- a/src/compiler/scala/reflect/reify/Taggers.scala +++ b/src/compiler/scala/reflect/reify/Taggers.scala @@ -37,7 +37,7 @@ abstract class Taggers { } def materializeTypeTag(universe: Tree, mirror: Tree, tpe: Type, concrete: Boolean): Tree = { - val tagType = if (concrete) TypeTagClass else AbsTypeTagClass + val tagType = if (concrete) TypeTagClass else WeakTypeTagClass // what we need here is to compose a type BaseUniverse # TypeTag[$tpe] // to look for an implicit that conforms to this type // that's why neither appliedType(tagType, List(tpe)) aka TypeRef(TypeTagsClass.thisType, tagType, List(tpe)) @@ -50,7 +50,7 @@ abstract class Taggers { case success if !success.isEmpty => Apply(Select(success, nme.in), List(mirror orElse mkDefaultMirrorRef(c.universe)(universe, c.callsiteTyper))) case _ => - val tagModule = if (concrete) TypeTagModule else AbsTypeTagModule + val tagModule = if (concrete) TypeTagModule else WeakTypeTagModule materializeTag(universe, tpe, tagModule, c.reifyType(universe, mirror, tpe, concrete = concrete)) } } diff --git a/src/compiler/scala/reflect/reify/codegen/GenSymbols.scala b/src/compiler/scala/reflect/reify/codegen/GenSymbols.scala index ca6e14cfd3..c4b674955a 100644 --- a/src/compiler/scala/reflect/reify/codegen/GenSymbols.scala +++ b/src/compiler/scala/reflect/reify/codegen/GenSymbols.scala @@ -90,49 +90,61 @@ trait GenSymbols { } } else { // todo. make sure that free methods and free local defs work correctly - if (sym.isTerm) reifyFreeTerm(sym, Ident(sym)) - else reifyFreeType(sym, Ident(sym)) + if (sym.isExistential) reifySymDef(sym) + else if (sym.isTerm) reifyFreeTerm(Ident(sym)) + else reifyFreeType(Ident(sym)) } } - def reifyFreeTerm(sym: Symbol, value: Tree): Tree = - reifyIntoSymtab(sym) { + def reifyFreeTerm(binding: Tree): Tree = + reifyIntoSymtab(binding.symbol) { sym => if (reifyDebug) println("Free term" + (if (sym.isCapturedVariable) " (captured)" else "") + ": " + sym + "(" + sym.accurateKindString + ")") - var name = newTermName(nme.REIFY_FREE_PREFIX + sym.name) - if (sym.isType) name = name.append(nme.REIFY_FREE_THIS_SUFFIX) + val name = newTermName(nme.REIFY_FREE_PREFIX + sym.name + (if (sym.isType) nme.REIFY_FREE_THIS_SUFFIX else "")) if (sym.isCapturedVariable) { - assert(value.isInstanceOf[Ident], showRaw(value)) - val capturedTpe = capturedVariableType(sym) - val capturedValue = referenceCapturedVariable(sym) - (name, mirrorBuildCall(nme.newFreeTerm, reify(sym.name.toString), reify(capturedTpe), capturedValue, mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(origin(sym)))) + assert(binding.isInstanceOf[Ident], showRaw(binding)) + val capturedBinding = referenceCapturedVariable(sym) + Reification(name, capturedBinding, mirrorBuildCall(nme.newFreeTerm, reify(sym.name.toString), capturedBinding, mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(origin(sym)))) } else { - (name, mirrorBuildCall(nme.newFreeTerm, reify(sym.name.toString), reify(sym.tpe), value, mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(origin(sym)))) + Reification(name, binding, mirrorBuildCall(nme.newFreeTerm, reify(sym.name.toString), binding, mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(origin(sym)))) } } - def reifyFreeType(sym: Symbol, value: Tree): Tree = - reifyIntoSymtab(sym) { + def reifyFreeType(binding: Tree): Tree = + reifyIntoSymtab(binding.symbol) { sym => if (reifyDebug) println("Free type: %s (%s)".format(sym, sym.accurateKindString)) - var name = newTermName(nme.REIFY_FREE_PREFIX + sym.name) - val phantomTypeTag = Apply(TypeApply(Select(Ident(nme.UNIVERSE_SHORT), nme.TypeTag), List(value)), List(Literal(Constant(null)), Literal(Constant(null)))) - val flavor = if (sym.isExistential) nme.newFreeExistential else nme.newFreeType - (name, mirrorBuildCall(flavor, reify(sym.name.toString), reify(sym.info), phantomTypeTag, mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(origin(sym)))) + state.reificationIsConcrete = false + val name = newTermName(nme.REIFY_FREE_PREFIX + sym.name) + Reification(name, binding, mirrorBuildCall(nme.newFreeType, reify(sym.name.toString), mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(origin(sym)))) } def reifySymDef(sym: Symbol): Tree = - reifyIntoSymtab(sym) { + reifyIntoSymtab(sym) { sym => if (reifyDebug) println("Sym def: %s (%s)".format(sym, sym.accurateKindString)) - assert(!sym.isLocatable, sym) // if this assertion fires, then tough type reification needs to be rethought - sym.owner.ownersIterator find (!_.isLocatable) foreach reifySymDef - var name = newTermName(nme.REIFY_SYMDEF_PREFIX + sym.name) - (name, mirrorBuildCall(nme.newNestedSymbol, reify(sym.owner), reify(sym.name), reify(sym.pos), mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(sym.isClass))) + val name = newTermName(nme.REIFY_SYMDEF_PREFIX + sym.name) + def reifiedOwner = if (sym.owner.isLocatable) reify(sym.owner) else reifySymDef(sym.owner) + Reification(name, Ident(sym), mirrorBuildCall(nme.newNestedSymbol, reifiedOwner, reify(sym.name), reify(sym.pos), mirrorBuildCall(nme.flagsFromBits, reify(sym.flags)), reify(sym.isClass))) } - private def reifyIntoSymtab(sym: Symbol)(reificode: => (TermName, Tree)): Tree ={ + case class Reification(name: Name, binding: Tree, tree: Tree) + + private def reifyIntoSymtab(sym: Symbol)(reificode: Symbol => Reification): Tree = { def fromSymtab = symtab symRef sym if (fromSymtab == EmptyTree) { - val reification = reificode - state.symtab += (sym, reification._1, reification._2) + // reification is lazy, so that we can carefully choose where to evaluate it + // and we choose this place to be exactly here: + // + // reasons: + // 1) reification happens at maximum once per symbol to prevent repeated reifications + // 2) reification happens before putting the symbol itself into the symbol table to ensure correct initialization order: + // for example, if reification of symbol A refers to reification of symbol B + // (this might happen when we're doing `reifySymDef`, which expands into `newNestedSymbol`, which needs `sym.owner`) + // then we have to put reification-B into the symbol table before reification-A + // so that subsequent code generation that traverses the symbol table in the first-added first-codegenned order + // produces valid Scala code (with vals in a block depending only on lexically preceding vals) + val reification = reificode(sym) + import reification.{name, binding} + val tree = reification.tree addAttachment ReifyBindingAttachment(binding) + state.symtab += (sym, name, tree) } fromSymtab } diff --git a/src/compiler/scala/reflect/reify/codegen/GenTrees.scala b/src/compiler/scala/reflect/reify/codegen/GenTrees.scala index f48df8df65..bdcc7383b0 100644 --- a/src/compiler/scala/reflect/reify/codegen/GenTrees.scala +++ b/src/compiler/scala/reflect/reify/codegen/GenTrees.scala @@ -124,7 +124,7 @@ trait GenTrees { val sym = tree.symbol if (reifyDebug) println("This for %s, reified as freeVar".format(sym)) if (reifyDebug) println("Free: " + sym) - mirrorBuildCall(nme.Ident, reifyFreeTerm(sym, This(sym))) + mirrorBuildCall(nme.Ident, reifyFreeTerm(This(sym))) case tree @ This(_) if !tree.symbol.isLocalToReifee => if (reifyDebug) println("This for %s, reified as This".format(tree.symbol)) mirrorBuildCall(nme.This, reify(tree.symbol)) diff --git a/src/compiler/scala/reflect/reify/codegen/GenTypes.scala b/src/compiler/scala/reflect/reify/codegen/GenTypes.scala index 1d2e177688..7aa87dc2f8 100644 --- a/src/compiler/scala/reflect/reify/codegen/GenTypes.scala +++ b/src/compiler/scala/reflect/reify/codegen/GenTypes.scala @@ -73,7 +73,7 @@ trait GenTypes { if (tpe.isSpliceable && !(quantified contains tpe.typeSymbol)) { if (reifyDebug) println("splicing " + tpe) - val tagFlavor = if (concrete) tpnme.TypeTag.toString else tpnme.AbsTypeTag.toString + val tagFlavor = if (concrete) tpnme.TypeTag.toString else tpnme.WeakTypeTag.toString val key = (tagFlavor, tpe.typeSymbol) // if this fails, it might produce the dreaded "erroneous or inaccessible type" error // to find out the whereabouts of the error run scalac with -Ydebug diff --git a/src/compiler/scala/reflect/reify/codegen/GenUtils.scala b/src/compiler/scala/reflect/reify/codegen/GenUtils.scala index 2b7733fb6c..8aef8d772f 100644 --- a/src/compiler/scala/reflect/reify/codegen/GenUtils.scala +++ b/src/compiler/scala/reflect/reify/codegen/GenUtils.scala @@ -131,7 +131,7 @@ trait GenUtils { def isCrossStageTypeBearer(tree: Tree): Boolean = tree match { case TypeApply(hk, _) => isCrossStageTypeBearer(hk) - case Select(sym @ Select(_, ctor), nme.apply) if ctor == nme.AbsTypeTag || ctor == nme.TypeTag || ctor == nme.Expr => true + case Select(sym @ Select(_, ctor), nme.apply) if ctor == nme.WeakTypeTag || ctor == nme.TypeTag || ctor == nme.Expr => true case _ => false } diff --git a/src/compiler/scala/reflect/reify/package.scala b/src/compiler/scala/reflect/reify/package.scala index a253effc1c..a76f147dc4 100644 --- a/src/compiler/scala/reflect/reify/package.scala +++ b/src/compiler/scala/reflect/reify/package.scala @@ -1,6 +1,6 @@ package scala.reflect -import language.implicitConversions +import scala.language.implicitConversions import scala.reflect.base.{Universe => BaseUniverse} import scala.reflect.macros.{Context, ReificationError, UnexpectedReificationError} import scala.tools.nsc.Global @@ -26,7 +26,14 @@ package object reify { private[reify] def mkDefaultMirrorRef(global: Global)(universe: global.Tree, typer0: global.analyzer.Typer): global.Tree = { import global._ import definitions._ - val enclosingErasure = reifyEnclosingRuntimeClass(global)(typer0) + val enclosingErasure = { + val rClassTree = reifyEnclosingRuntimeClass(global)(typer0) + // HACK around SI-6259 + // If we're in the constructor of an object or others don't have easy access to `this`, we have no good way to grab + // the class of that object. Instead, we construct an anonymous class and grab his class file, assuming + // this is enough to get the correct class loadeer for the class we *want* a mirror for, the object itself. + rClassTree orElse Apply(Select(treeBuilder.makeAnonymousNew(Nil), sn.GetClass), Nil) + } // JavaUniverse is defined in scala-reflect.jar, so we must be very careful in case someone reifies stuff having only scala-library.jar on the classpath val isJavaUniverse = JavaUniverseClass != NoSymbol && universe.tpe <:< JavaUniverseClass.toTypeConstructor if (isJavaUniverse && !enclosingErasure.isEmpty) Apply(Select(universe, nme.runtimeMirror), List(Select(enclosingErasure, sn.GetClassLoader))) @@ -61,6 +68,8 @@ package object reify { } } + // Note: If current context is inside the constructor of an object or otherwise not inside + // a class/object body, this will return an EmptyTree. def reifyEnclosingRuntimeClass(global: Global)(typer0: global.analyzer.Typer): global.Tree = { import global._ import definitions._ @@ -68,8 +77,15 @@ package object reify { if (isThisInScope) { val enclosingClasses = typer0.context.enclosingContextChain map (_.tree) collect { case classDef: ClassDef => classDef } val classInScope = enclosingClasses.headOption getOrElse EmptyTree + def isUnsafeToUseThis = { + val isInsideConstructorSuper = typer0.context.enclosingContextChain exists (_.inSelfSuperCall) + // Note: It's ok to check for any object here, because if we were in an enclosing class, we'd already have returned its classOf + val isInsideObject = typer0.context.enclosingContextChain map (_.tree) exists { case _: ModuleDef => true; case _ => false } + isInsideConstructorSuper && isInsideObject + } if (!classInScope.isEmpty) reifyRuntimeClass(global)(typer0, classInScope.symbol.toTypeConstructor, concrete = true) - else Select(This(tpnme.EMPTY), sn.GetClass) + else if(!isUnsafeToUseThis) Select(This(tpnme.EMPTY), sn.GetClass) + else EmptyTree } else EmptyTree } } diff --git a/src/compiler/scala/reflect/reify/phases/Reshape.scala b/src/compiler/scala/reflect/reify/phases/Reshape.scala index fcf3c0e65c..0b07c47c0f 100644 --- a/src/compiler/scala/reflect/reify/phases/Reshape.scala +++ b/src/compiler/scala/reflect/reify/phases/Reshape.scala @@ -103,8 +103,8 @@ trait Reshape { // of, say, ClassTag or TypeTag case Apply(TypeApply(_, List(tt)), _) if original.symbol == MacroInternal_materializeClassTag => gen.mkNullaryCall(Predef_implicitly, List(appliedType(ClassTagClass, tt.tpe))) - case Apply(TypeApply(_, List(tt)), List(pre)) if original.symbol == MacroInternal_materializeAbsTypeTag => - gen.mkNullaryCall(Predef_implicitly, List(typeRef(pre.tpe, AbsTypeTagClass, List(tt.tpe)))) + case Apply(TypeApply(_, List(tt)), List(pre)) if original.symbol == MacroInternal_materializeWeakTypeTag => + gen.mkNullaryCall(Predef_implicitly, List(typeRef(pre.tpe, WeakTypeTagClass, List(tt.tpe)))) case Apply(TypeApply(_, List(tt)), List(pre)) if original.symbol == MacroInternal_materializeTypeTag => gen.mkNullaryCall(Predef_implicitly, List(typeRef(pre.tpe, TypeTagClass, List(tt.tpe)))) case _ => diff --git a/src/compiler/scala/reflect/reify/utils/Extractors.scala b/src/compiler/scala/reflect/reify/utils/Extractors.scala index ebe3957e69..1df9efbb82 100644 --- a/src/compiler/scala/reflect/reify/utils/Extractors.scala +++ b/src/compiler/scala/reflect/reify/utils/Extractors.scala @@ -94,7 +94,7 @@ trait Extractors { object ReifiedTree { def apply(universe: Tree, mirror: Tree, symtab: SymbolTable, rtree: Tree, tpe: Type, rtpe: Tree, concrete: Boolean): Tree = { - val tagFactory = if (concrete) nme.TypeTag else nme.AbsTypeTag + val tagFactory = if (concrete) nme.TypeTag else nme.WeakTypeTag val tagCtor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), tagFactory), nme.apply), List(TypeTree(tpe))) val exprCtor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), nme.Expr), nme.apply), List(TypeTree(tpe))) val tagArgs = List(Ident(nme.MIRROR_SHORT), mkCreator(tpnme.REIFY_TYPECREATOR_PREFIX, symtab, rtpe)) @@ -122,7 +122,7 @@ trait Extractors { object ReifiedType { def apply(universe: Tree, mirror: Tree, symtab: SymbolTable, tpe: Type, rtpe: Tree, concrete: Boolean) = { - val tagFactory = if (concrete) nme.TypeTag else nme.AbsTypeTag + val tagFactory = if (concrete) nme.TypeTag else nme.WeakTypeTag val ctor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), tagFactory), nme.apply), List(TypeTree(tpe))) val args = List(Ident(nme.MIRROR_SHORT), mkCreator(tpnme.REIFY_TYPECREATOR_PREFIX, symtab, rtpe)) val unwrapped = Apply(ctor, args) @@ -176,12 +176,11 @@ trait Extractors { List( _, _, - binding, Apply(Select(Select(uref2 @ Ident(_), build2), flagsFromBits), List(Literal(Constant(flags: Long)))), Literal(Constant(origin: String))))) if uref1.name == nme.UNIVERSE_SHORT && build1 == nme.build && newFreeTerm == nme.newFreeTerm && uref2.name == nme.UNIVERSE_SHORT && build2 == nme.build && flagsFromBits == nme.flagsFromBits => - Some(uref1, name, binding, flags, origin) + Some(uref1, name, reifyBinding(tree), flags, origin) case _ => None } @@ -194,22 +193,11 @@ trait Extractors { Select(Select(uref1 @ Ident(_), build1), newFreeType), List( _, - _, - value, Apply(Select(Select(uref2 @ Ident(_), build2), flagsFromBits), List(Literal(Constant(flags: Long)))), Literal(Constant(origin: String))))) - if uref1.name == nme.UNIVERSE_SHORT && build1 == nme.build && (newFreeType == nme.newFreeType || newFreeType == nme.newFreeExistential) && + if uref1.name == nme.UNIVERSE_SHORT && build1 == nme.build && newFreeType == nme.newFreeType && uref2.name == nme.UNIVERSE_SHORT && build2 == nme.build && flagsFromBits == nme.flagsFromBits => - value match { - case Apply(TypeApply(Select(Select(uref3 @ Ident(_), typeTag), apply), List(binding)), List(Literal(Constant(null)), _)) - if uref3.name == nme.UNIVERSE_SHORT && typeTag == nme.TypeTag && apply == nme.apply => - Some(uref1, name, binding, flags, origin) - case Apply(TypeApply(Select(uref3 @ Ident(_), typeTag), List(binding)), List(Literal(Constant(null)), _)) - if uref3.name == nme.UNIVERSE_SHORT && typeTag == nme.TypeTag => - Some(uref1, name, binding, flags, origin) - case _ => - throw new Error("unsupported free type def: %s%n%s".format(value, showRaw(value))) - } + Some(uref1, name, reifyBinding(tree), flags, origin) case _ => None } diff --git a/src/compiler/scala/reflect/reify/utils/StdAttachments.scala b/src/compiler/scala/reflect/reify/utils/StdAttachments.scala index abbed814e0..0b9cf58c89 100644 --- a/src/compiler/scala/reflect/reify/utils/StdAttachments.scala +++ b/src/compiler/scala/reflect/reify/utils/StdAttachments.scala @@ -6,7 +6,13 @@ trait StdAttachments { import global._ - case class ReifyBindingAttachment(binding: Symbol) + case class ReifyBindingAttachment(binding: Tree) - case class ReifyAliasAttachment(binding: Symbol, alias: TermName) + def reifyBinding(tree: Tree): Tree = + tree.attachments.get[ReifyBindingAttachment] match { + case Some(ReifyBindingAttachment(binding)) => binding + case other => Ident(NoSymbol) + } + + case class ReifyAliasAttachment(sym: Symbol, alias: TermName) }
\ No newline at end of file diff --git a/src/compiler/scala/reflect/reify/utils/SymbolTables.scala b/src/compiler/scala/reflect/reify/utils/SymbolTables.scala index 3892c86dd3..2e17558f54 100644 --- a/src/compiler/scala/reflect/reify/utils/SymbolTables.scala +++ b/src/compiler/scala/reflect/reify/utils/SymbolTables.scala @@ -17,6 +17,7 @@ trait SymbolTables { private[SymbolTable] val original: Option[List[Tree]] = None) { def syms: List[Symbol] = symtab.keys.toList + def isConcrete: Boolean = symtab.values forall (sym => !FreeTypeDef.unapply(sym).isDefined) // def aliases: Map[Symbol, List[TermName]] = aliases.distinct groupBy (_._1) mapValues (_ map (_._2)) @@ -45,28 +46,27 @@ trait SymbolTables { def symRef(sym: Symbol): Tree = symtab.get(sym) match { - case Some(FreeDef(_, name, _, _, _)) => Ident(name) addAttachment ReifyBindingAttachment(sym) - case Some(SymDef(_, name, _, _)) => Ident(name) addAttachment ReifyBindingAttachment(sym) + case Some(FreeDef(_, name, binding, _, _)) => Ident(name) addAttachment binding + case Some(SymDef(_, name, _, _)) => Ident(name) addAttachment ReifyBindingAttachment(Ident(sym)) case None => EmptyTree } def +(sym: Symbol, name: TermName, reification: Tree): SymbolTable = add(sym, name, reification) - def +(sym: Symbol, name: TermName): SymbolTable = add(sym, name) def +(symDef: Tree): SymbolTable = add(symDef) def ++(symDefs: TraversableOnce[Tree]): SymbolTable = (this /: symDefs)((symtab, symDef) => symtab.add(symDef)) def ++(symtab: SymbolTable): SymbolTable = { val updated = this ++ symtab.symtab.values; new SymbolTable(updated.symtab, updated.aliases ++ symtab.aliases) } def -(sym: Symbol): SymbolTable = remove(sym) def -(name: TermName): SymbolTable = remove(name) - def -(symDef: Tree): SymbolTable = remove(binding(symDef)) + def -(symDef: Tree): SymbolTable = remove(reifyBinding(symDef).symbol) def --(syms: GenTraversableOnce[Symbol]): SymbolTable = (this /: syms)((symtab, sym) => symtab.remove(sym)) def --(names: Iterable[TermName]): SymbolTable = (this /: names)((symtab, name) => symtab.remove(name)) - def --(symDefs: TraversableOnce[Tree]): SymbolTable = this -- (symDefs map (binding(_))) + def --(symDefs: TraversableOnce[Tree]): SymbolTable = this -- (symDefs map (reifyBinding(_))) def --(symtab: SymbolTable): SymbolTable = { val updated = this -- symtab.symtab.values; new SymbolTable(updated.symtab, updated.aliases diff symtab.aliases) } def filterSyms(p: Symbol => Boolean): SymbolTable = this -- (syms filterNot p) def filterAliases(p: (Symbol, TermName) => Boolean): SymbolTable = this -- (aliases filterNot (tuple => p(tuple._1, tuple._2)) map (_._2)) private def add(symDef: Tree): SymbolTable = { - val sym = binding(symDef) + val sym = reifyBinding(symDef).symbol assert(sym != NoSymbol, showRaw(symDef)) val name = symDef match { case FreeDef(_, name, _, _, _) => name @@ -85,7 +85,8 @@ trait SymbolTables { val fresh = typer.context.unit.fresh newTermName(fresh.newName(name)) } - add(ValDef(NoMods, freshName(name0), TypeTree(), reification) addAttachment ReifyBindingAttachment(sym)) + val bindingAttachment = reification.attachments.get[ReifyBindingAttachment].get + add(ValDef(NoMods, freshName(name0), TypeTree(), reification) addAttachment bindingAttachment) } private def add(sym: Symbol, name: TermName): SymbolTable = { @@ -115,12 +116,6 @@ trait SymbolTables { new SymbolTable(newSymtab, newAliases) } - private def binding(tree: Tree): Symbol = - tree.attachments.get[ReifyBindingAttachment] match { - case Some(ReifyBindingAttachment(binding)) => binding - case other => NoSymbol - } - private val cache = mutable.Map[SymbolTable, List[Tree]]() def encode: List[Tree] = cache.getOrElseUpdate(this, SymbolTable.encode(this)) map (_.duplicate) @@ -147,7 +142,7 @@ trait SymbolTables { def apply(encoded: List[Tree]): SymbolTable = { var result = new SymbolTable(original = Some(encoded)) encoded foreach (entry => (entry.attachments.get[ReifyBindingAttachment], entry.attachments.get[ReifyAliasAttachment]) match { - case (Some(ReifyBindingAttachment(sym)), _) => result += entry + case (Some(ReifyBindingAttachment(_)), _) => result += entry case (_, Some(ReifyAliasAttachment(sym, alias))) => result = new SymbolTable(result.symtab, result.aliases :+ (sym, alias)) case _ => // do nothing, this is boilerplate that can easily be recreated by subsequent `result.encode` }) @@ -169,30 +164,26 @@ trait SymbolTables { def fillInSymbol(sym: Symbol): Tree = { if (reifyDebug) println("Filling in: %s (%s)".format(sym, sym.accurateKindString)) - val isFree = currtab.symName(sym) startsWith nme.REIFY_FREE_PREFIX - if (isFree) { - if (sym.annotations.isEmpty) EmptyTree - else Apply(Select(currtab.symRef(sym), nme.setAnnotations), List(reifier.reify(sym.annotations))) - } else { - // SI-6204 don't reify signatures for incomplete symbols, because this might lead to cyclic reference errors - val signature = - if (sym.isInitialized) { - if (sym.isCapturedVariable) capturedVariableType(sym) - else sym.info - } else NoType - val rset = reifier.mirrorBuildCall(nme.setTypeSignature, currtab.symRef(sym), reifier.reify(signature)) - // `Symbol.annotations` doesn't initialize the symbol, so we don't need to do anything special here - // also since we call `sym.info` a few lines above, by now the symbol will be initialized (if possible) - // so the annotations will be filled in and will be waiting to be reified (unless symbol initialization is prohibited as described above) - if (sym.annotations.isEmpty) rset - else reifier.mirrorBuildCall(nme.setAnnotations, rset, reifier.mkList(sym.annotations map reifier.reifyAnnotationInfo)) - } + val isFreeTerm = FreeTermDef.unapply(currtab.symDef(sym)).isDefined + // SI-6204 don't reify signatures for incomplete symbols, because this might lead to cyclic reference errors + val signature = + if (sym.isInitialized) { + if (sym.isCapturedVariable) capturedVariableType(sym) + else if (isFreeTerm) sym.tpe + else sym.info + } else NoType + val rset = reifier.mirrorBuildCall(nme.setTypeSignature, currtab.symRef(sym), reifier.reify(signature)) + // `Symbol.annotations` doesn't initialize the symbol, so we don't need to do anything special here + // also since we call `sym.info` a few lines above, by now the symbol will be initialized (if possible) + // so the annotations will be filled in and will be waiting to be reified (unless symbol initialization is prohibited as described above) + if (sym.annotations.isEmpty) rset + else reifier.mirrorBuildCall(nme.setAnnotations, rset, reifier.mkList(sym.annotations map reifier.reifyAnnotationInfo)) } // `fillInSymbol` might add symbols to `symtab`, that's why this is done iteratively var progress = 0 while (progress < cumulativeSymtab.length) { - val sym = currtab.binding(cumulativeSymtab(progress)) + val sym = reifyBinding(cumulativeSymtab(progress)).symbol if (sym != NoSymbol) { val symtabProgress = currtab.symtab.size val aliasesProgress = currtab.aliases.length @@ -207,7 +198,7 @@ trait SymbolTables { val withAliases = cumulativeSymtab flatMap (entry => { val result = mutable.ListBuffer[Tree]() result += entry - val sym = currtab.binding(entry) + val sym = reifyBinding(entry).symbol if (sym != NoSymbol) result ++= cumulativeAliases.distinct filter (alias => alias._1 == sym && alias._2 != currtab.symName(sym)) map (alias => { val canonicalName = currtab.symName(sym) diff --git a/src/compiler/scala/tools/ant/ClassloadVerify.scala b/src/compiler/scala/tools/ant/ClassloadVerify.scala index 33a20f6894..d1d557b9d3 100644 --- a/src/compiler/scala/tools/ant/ClassloadVerify.scala +++ b/src/compiler/scala/tools/ant/ClassloadVerify.scala @@ -10,7 +10,7 @@ package scala.tools.ant import org.apache.tools.ant.Project import org.apache.tools.ant.types.{Path, Reference} -import collection.JavaConverters._ +import scala.collection.JavaConverters._ import scala.tools.util.VerifyClass class ClassloadVerify extends ScalaMatchingTask { diff --git a/src/compiler/scala/tools/ant/sabbus/Compilers.scala b/src/compiler/scala/tools/ant/sabbus/Compilers.scala index 843ee043ea..bb32149a75 100644 --- a/src/compiler/scala/tools/ant/sabbus/Compilers.scala +++ b/src/compiler/scala/tools/ant/sabbus/Compilers.scala @@ -11,7 +11,7 @@ package scala.tools.ant.sabbus import java.net.URL -object Compilers extends collection.DefaultMap[String, Compiler] { +object Compilers extends scala.collection.DefaultMap[String, Compiler] { val debug = false diff --git a/src/compiler/scala/tools/cmd/Property.scala b/src/compiler/scala/tools/cmd/Property.scala index aae5bebcc8..bde7bb8cb8 100644 --- a/src/compiler/scala/tools/cmd/Property.scala +++ b/src/compiler/scala/tools/cmd/Property.scala @@ -64,7 +64,7 @@ trait Property extends Reference { propertiesToOptions(loadProperties(file)) def propertiesToOptions(props: java.util.Properties): List[String] = { - import collection.JavaConversions._ + import scala.collection.JavaConversions._ propertiesToOptions(props.toList) } def propertiesToOptions(props: List[(String, String)]) = props flatMap propMapper diff --git a/src/compiler/scala/tools/cmd/Reference.scala b/src/compiler/scala/tools/cmd/Reference.scala index 77fe01051e..b6c564e9fb 100644 --- a/src/compiler/scala/tools/cmd/Reference.scala +++ b/src/compiler/scala/tools/cmd/Reference.scala @@ -6,7 +6,7 @@ package scala.tools package cmd -import collection.mutable.ListBuffer +import scala.collection.mutable.ListBuffer import nsc.Properties.envOrNone /** Mixes in the specification trait and uses the vals therein to diff --git a/src/compiler/scala/tools/cmd/gen/AnyVals.scala b/src/compiler/scala/tools/cmd/gen/AnyVals.scala index 7842603af7..910804245b 100644 --- a/src/compiler/scala/tools/cmd/gen/AnyVals.scala +++ b/src/compiler/scala/tools/cmd/gen/AnyVals.scala @@ -14,7 +14,7 @@ trait AnyValReps { sealed abstract class AnyValNum(name: String, repr: Option[String], javaEquiv: String) extends AnyValRep(name,repr,javaEquiv) { case class Op(val op : String, val doc : String) - + private def companionCoercions(tos: AnyValRep*) = { tos.toList map (to => """implicit def @javaequiv@2%s(x: @name@): %s = x.to%s""".format(to.javaEquiv, to.name, to.name) @@ -24,7 +24,7 @@ trait AnyValReps { def coercionComment = """ /** Language mandated coercions from @name@ to "wider" types.%s */""".format(coercionCommentExtra) - + def implicitCoercions: List[String] = { val coercions = this match { case B => companionCoercions(S, I, L, F, D) @@ -247,7 +247,7 @@ trait AnyValReps { def classDoc = interpolate(classDocTemplate) def objectDoc = "" def mkImports = "" - + def mkClass = assemble("final abstract class " + name + " private extends AnyVal", classLines) def mkObject = assemble("object " + name + " extends AnyValCompanion", objectLines) def make() = List[String]( @@ -281,7 +281,7 @@ trait AnyValTemplates { %s package scala -import language.implicitConversions +import scala.language.implicitConversions """.trim.format(timestampString) + "\n\n") diff --git a/src/compiler/scala/tools/cmd/gen/Codegen.scala b/src/compiler/scala/tools/cmd/gen/Codegen.scala index b94c640f1c..ff3d41c8b7 100644 --- a/src/compiler/scala/tools/cmd/gen/Codegen.scala +++ b/src/compiler/scala/tools/cmd/gen/Codegen.scala @@ -6,7 +6,7 @@ package scala.tools.cmd package gen -import language.postfixOps +import scala.language.postfixOps class Codegen(args: List[String]) extends { val parsed = CodegenSpec(args: _*) diff --git a/src/compiler/scala/tools/nsc/EvalLoop.scala b/src/compiler/scala/tools/nsc/EvalLoop.scala index da03419d8a..bd1381faf5 100644 --- a/src/compiler/scala/tools/nsc/EvalLoop.scala +++ b/src/compiler/scala/tools/nsc/EvalLoop.scala @@ -5,7 +5,7 @@ package scala.tools.nsc -import annotation.tailrec +import scala.annotation.tailrec import java.io.EOFException trait EvalLoop { diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 187cba8410..16fd4e956d 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -7,13 +7,13 @@ package scala.tools.nsc import java.io.{ File, FileOutputStream, PrintWriter, IOException, FileNotFoundException } import java.nio.charset.{ Charset, CharsetDecoder, IllegalCharsetNameException, UnsupportedCharsetException } -import compat.Platform.currentTime +import scala.compat.Platform.currentTime import scala.tools.util.PathResolver import scala.collection.{ mutable, immutable } import io.{ SourceReader, AbstractFile, Path } import reporters.{ Reporter, ConsoleReporter } import util.{ Exceptional, ClassPath, MergedClassPath, StatisticsInfo, ScalaClassLoader, returning } -import scala.reflect.internal.util.{ NoPosition, SourceFile, NoSourceFile, BatchSourceFile, ScriptSourceFile } +import scala.reflect.internal.util.{ NoPosition, OffsetPosition, SourceFile, NoSourceFile, BatchSourceFile, ScriptSourceFile } import scala.reflect.internal.pickling.{ PickleBuffer, PickleFormat } import symtab.{ Flags, SymbolTable, SymbolLoaders, SymbolTrackers } import symtab.classfile.Pickler @@ -28,8 +28,8 @@ import backend.{ ScalaPrimitives, Platform, MSILPlatform, JavaPlatform } import backend.jvm.{GenJVM, GenASM} import backend.opt.{ Inliners, InlineExceptionHandlers, ClosureElimination, DeadCodeElimination } import backend.icode.analysis._ -import language.postfixOps -import reflect.internal.StdAttachments +import scala.language.postfixOps +import scala.reflect.internal.StdAttachments import scala.reflect.ClassTag class Global(var currentSettings: Settings, var reporter: Reporter) @@ -95,6 +95,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) /** Generate ASTs */ type TreeGen = scala.tools.nsc.ast.TreeGen + /** Tree generation, usually based on existing symbols. */ override object gen extends { val global: Global.this.type = Global.this } with TreeGen { @@ -102,6 +103,17 @@ class Global(var currentSettings: Settings, var reporter: Reporter) typer.typed(mkCast(tree, pt)) } + /** Trees fresh from the oven, mostly for use by the parser. */ + object treeBuilder extends { + val global: Global.this.type = Global.this + } with TreeBuilder { + def freshName(prefix: String): Name = freshTermName(prefix) + def freshTermName(prefix: String): TermName = currentUnit.freshTermName(prefix) + def freshTypeName(prefix: String): TypeName = currentUnit.freshTypeName(prefix) + def o2p(offset: Int): Position = new OffsetPosition(currentUnit.source, offset) + def r2p(start: Int, mid: Int, end: Int): Position = rangePos(currentUnit.source, start, mid, end) + } + /** Fold constants */ object constfold extends { val global: Global.this.type = Global.this @@ -265,9 +277,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) log("Running operation '%s' after every phase.\n".format(msg) + describeAfterEveryPhase(op)) } - def shouldLogAtThisPhase = ( - (settings.log.isSetByUser) - && ((settings.log containsPhase globalPhase) || (settings.log containsPhase phase)) + override def shouldLogAtThisPhase = settings.log.isSetByUser && ( + (settings.log containsPhase globalPhase) || (settings.log containsPhase phase) ) // Over 200 closure objects are eliminated by inlining this. @inline final def log(msg: => AnyRef) { @@ -883,7 +894,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) reSync(RootClass, Some(classPath), Some(oldEntries), Some(newEntries), invalidated, failed) } } - def show(msg: String, syms: collection.Traversable[Symbol]) = + def show(msg: String, syms: scala.collection.Traversable[Symbol]) = if (syms.nonEmpty) informProgress(s"$msg: ${syms map (_.fullName) mkString ","}") show("invalidated packages", invalidated) diff --git a/src/compiler/scala/tools/nsc/PhaseAssembly.scala b/src/compiler/scala/tools/nsc/PhaseAssembly.scala index e69382be21..46cdc6a4a0 100644 --- a/src/compiler/scala/tools/nsc/PhaseAssembly.scala +++ b/src/compiler/scala/tools/nsc/PhaseAssembly.scala @@ -8,7 +8,7 @@ package scala.tools.nsc import java.io.{ BufferedWriter, FileWriter } import scala.collection.mutable -import language.postfixOps +import scala.language.postfixOps /** * PhaseAssembly diff --git a/src/compiler/scala/tools/nsc/Phases.scala b/src/compiler/scala/tools/nsc/Phases.scala index d2274b108b..c80be474a6 100644 --- a/src/compiler/scala/tools/nsc/Phases.scala +++ b/src/compiler/scala/tools/nsc/Phases.scala @@ -6,8 +6,8 @@ package scala.tools.nsc import symtab.Flags -import reflect.internal.util.TableDef -import language.postfixOps +import scala.reflect.internal.util.TableDef +import scala.language.postfixOps object Phases { val MaxPhases = 64 diff --git a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala index 0b54eda66d..d1faa4d219 100644 --- a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala +++ b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala @@ -6,9 +6,9 @@ package scala.tools.nsc package ast -import compat.Platform.EOL +import scala.compat.Platform.EOL import symtab.Flags._ -import language.postfixOps +import scala.language.postfixOps /** The object `nodePrinter` converts the internal tree * representation to a string. diff --git a/src/compiler/scala/tools/nsc/ast/Printers.scala b/src/compiler/scala/tools/nsc/ast/Printers.scala index 885fc3f518..3392b78595 100644 --- a/src/compiler/scala/tools/nsc/ast/Printers.scala +++ b/src/compiler/scala/tools/nsc/ast/Printers.scala @@ -10,7 +10,7 @@ import java.io.{ OutputStream, PrintWriter, StringWriter, Writer } import symtab.Flags._ import symtab.SymbolTable -trait Printers extends reflect.internal.Printers { this: Global => +trait Printers extends scala.reflect.internal.Printers { this: Global => import treeInfo.{ IsTrue, IsFalse } diff --git a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala index 043834ae55..267a5dcefd 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala @@ -18,7 +18,7 @@ import scala.concurrent.Lock import scala.text._ import symtab.Flags._ import symtab.SymbolTable -import language.implicitConversions +import scala.language.implicitConversions /** * Tree browsers can show the AST in a graphical and interactive diff --git a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala index e90d779885..01bd0bbb06 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala @@ -9,7 +9,7 @@ package ast import PartialFunction._ import symtab.Flags -import language.implicitConversions +import scala.language.implicitConversions /** A DSL for generating scala code. The goal is that the * code generating code should look a lot like the code it diff --git a/src/compiler/scala/tools/nsc/ast/TreeGen.scala b/src/compiler/scala/tools/nsc/ast/TreeGen.scala index 3177ceefcd..20da5f0087 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala @@ -9,12 +9,12 @@ package ast import scala.collection.mutable.ListBuffer import symtab.Flags._ import symtab.SymbolTable -import language.postfixOps +import scala.language.postfixOps /** XXX to resolve: TreeGen only assumes global is a SymbolTable, but * TreeDSL at the moment expects a Global. Can we get by with SymbolTable? */ -abstract class TreeGen extends reflect.internal.TreeGen with TreeDSL { +abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { val global: Global import global._ diff --git a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala index e755553e25..9e46155d14 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala @@ -6,8 +6,8 @@ package scala.tools.nsc package ast -import reflect.internal.HasFlags -import reflect.internal.Flags._ +import scala.reflect.internal.HasFlags +import scala.reflect.internal.Flags._ import symtab._ /** This class ... @@ -15,7 +15,7 @@ import symtab._ * @author Martin Odersky * @version 1.0 */ -abstract class TreeInfo extends reflect.internal.TreeInfo { +abstract class TreeInfo extends scala.reflect.internal.TreeInfo { val global: Global import global._ diff --git a/src/compiler/scala/tools/nsc/ast/Trees.scala b/src/compiler/scala/tools/nsc/ast/Trees.scala index 30fc1778b1..acf0a8ee6f 100644 --- a/src/compiler/scala/tools/nsc/ast/Trees.scala +++ b/src/compiler/scala/tools/nsc/ast/Trees.scala @@ -15,7 +15,7 @@ import scala.reflect.internal.Flags.PRESUPER import scala.reflect.internal.Flags.TRAIT import scala.compat.Platform.EOL -trait Trees extends reflect.internal.Trees { self: Global => +trait Trees extends scala.reflect.internal.Trees { self: Global => def treeLine(t: Tree): String = if (t.pos.isDefined && t.pos.isRange) t.pos.lineContent.drop(t.pos.column - 1).take(t.pos.end - t.pos.start + 1) @@ -48,12 +48,12 @@ trait Trees extends reflect.internal.Trees { self: Global => override def isType = definition.isType } - /** Array selection <qualifier> . <name> only used during erasure */ + /** Array selection `<qualifier> . <name>` only used during erasure */ case class SelectFromArray(qualifier: Tree, name: Name, erasure: Type) extends RefTree with TermTree - /** Derived value class injection (equivalent to: new C(arg) after easure); only used during erasure - * The class C is stored as the symbol of the tree node. + /** Derived value class injection (equivalent to: `new C(arg)` after erasure); only used during erasure. + * The class `C` is stored as a tree attachment. */ case class InjectDerivedValue(arg: Tree) extends SymTree diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index bf21899438..8c131850e9 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -280,14 +280,6 @@ self => /** whether a non-continuable syntax error has been seen */ private var lastErrorOffset : Int = -1 - object treeBuilder extends TreeBuilder { - val global: self.global.type = self.global - def freshName(prefix: String): Name = freshTermName(prefix) - def freshTermName(prefix: String): TermName = Parser.this.freshTermName(prefix) - def freshTypeName(prefix: String): TypeName = Parser.this.freshTypeName(prefix) - def o2p(offset: Int) = Parser.this.o2p(offset) - def r2p(start: Int, point: Int, end: Int) = Parser.this.r2p(start, point, end) - } import treeBuilder.{global => _, _} /** The types of the context bounds of type parameters of the surrounding class @@ -404,8 +396,7 @@ self => def mainParamType = AppliedTypeTree(Ident(tpnme.Array), List(Ident(tpnme.String))) def mainParameter = List(ValDef(Modifiers(Flags.PARAM), nme.argv, mainParamType, EmptyTree)) def mainSetArgv = List(ValDef(NoMods, nme.args, TypeTree(), Ident(nme.argv))) - def mainNew = makeNew(Nil, emptyValDef, stmts, ListOfNil, NoPosition, NoPosition) - def mainDef = DefDef(NoMods, nme.main, Nil, List(mainParameter), scalaDot(tpnme.Unit), Block(mainSetArgv, mainNew)) + def mainDef = DefDef(NoMods, nme.main, Nil, List(mainParameter), scalaDot(tpnme.Unit), Block(mainSetArgv, makeAnonymousNew(stmts))) // object Main def moduleName = newTermName(ScriptRunner scriptMain settings) diff --git a/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala index 146329183c..9466b7222d 100755 --- a/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala @@ -7,11 +7,11 @@ package scala.tools.nsc package ast.parser import scala.collection.{ mutable, immutable } -import xml.{ EntityRef, Text } -import xml.XML.{ xmlns } +import scala.xml.{ EntityRef, Text } +import scala.xml.XML.{ xmlns } import symtab.Flags.MUTABLE import scala.reflect.internal.util.StringOps.splitWhere -import language.implicitConversions +import scala.language.implicitConversions /** This class builds instance of `Tree` that represent XML. * @@ -144,7 +144,7 @@ abstract class SymbolicXMLBuilder(p: Parsers#Parser, preserveWS: Boolean) { (buf map convertToTextPat).toList def parseAttribute(pos: Position, s: String): Tree = { - val ts = xml.Utility.parseAttributeValue(s) map { + val ts = scala.xml.Utility.parseAttributeValue(s) map { case Text(s) => text(pos, s) case EntityRef(s) => entityRef(pos, s) } diff --git a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala index 7e7972f9dd..9ce74b2b17 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package ast.parser -import annotation.switch +import scala.annotation.switch /** Common code between JavaTokens and Tokens. Not as much (and not as concrete) * as one might like because JavaTokens for no clear reason chose new numbers for diff --git a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala index 1cd1b63691..c6a38f5be6 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala @@ -199,6 +199,15 @@ abstract class TreeBuilder { } } + /** Creates a tree representing new Object { stats }. + * To make sure an anonymous subclass of Object is created, + * if there are no stats, a () is added. + */ + def makeAnonymousNew(stats: List[Tree]): Tree = { + val stats1 = if (stats.isEmpty) List(Literal(Constant(()))) else stats + makeNew(Nil, emptyValDef, stats1, ListOfNil, NoPosition, NoPosition) + } + /** Create positioned tree representing an object creation <new parents { stats } * @param npos the position of the new * @param cpos the position of the anonymous class starting with parents diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala index 486a43614b..06492e4ac6 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala @@ -11,7 +11,7 @@ import scala.collection.{ mutable, immutable } import mutable.{ ListBuffer, ArrayBuffer } import scala.reflect.internal.util.{ Position, NoPosition } import backend.icode.analysis.ProgramPoint -import language.postfixOps +import scala.language.postfixOps trait BasicBlocks { self: ICodes => diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala index 142aacfdf7..147e0eb23c 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala @@ -13,7 +13,7 @@ import scala.collection.mutable.{ ListBuffer, Buffer } import scala.tools.nsc.symtab._ import scala.annotation.switch import PartialFunction._ -import language.postfixOps +import scala.language.postfixOps /** This class ... * @@ -128,7 +128,6 @@ abstract class GenICode extends SubComponent { if (staticfield != NoSymbol) { // in companion object accessors to @static fields, we access the static field directly val hostClass = m.symbol.owner.companionClass - if (m.symbol.isGetter) { ctx1.bb.emit(LOAD_FIELD(staticfield, true) setHostClass hostClass, tree.pos) ctx1.bb.closeWith(RETURN(m.returnType)) @@ -1000,14 +999,16 @@ abstract class GenICode extends SubComponent { fun match { case Select(qual, _) => val qualSym = findHostClass(qual.tpe, sym) - - if (qualSym == ArrayClass) cm setTargetTypeKind toTypeKind(qual.tpe) - else cm setHostClass qualSym - - log( - if (qualSym == ArrayClass) "Stored target type kind " + toTypeKind(qual.tpe) + " for " + sym.fullName - else s"Set more precise host class for ${sym.fullName} hostClass: $qualSym" - ) + if (qualSym == ArrayClass) { + val kind = toTypeKind(qual.tpe) + cm setTargetTypeKind kind + log(s"Stored target type kind for {$sym.fullName} as $kind") + } + else { + cm setHostClass qualSym + if (qual.tpe.typeSymbol != qualSym) + log(s"Precisified host class for $sym from ${qual.tpe.typeSymbol.fullName} to ${qualSym.fullName}") + } case _ => } ctx1.bb.emit(cm, tree.pos) diff --git a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala index 1c5c9224f2..4739750daa 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala @@ -231,7 +231,7 @@ trait Linearizers { val handlersByCovered = m.exh.groupBy(_.covered) // number of basic blocks covered by the entire try-catch expression - def size(covered: collection.immutable.Set[BasicBlock]) = { + def size(covered: scala.collection.immutable.Set[BasicBlock]) = { val hs = handlersByCovered(covered) covered.size + (hs :\ 0)((h, s) => h.blocks.length + s) } diff --git a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala index 1fcb406e96..63f0ab683b 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala @@ -128,7 +128,7 @@ trait Opcodes { self: ICodes => } /** Clone this instruction. */ - override def clone: Instruction = + override def clone(): Instruction = super.clone.asInstanceOf[Instruction] } 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 d1d8e4a385..df158a29ea 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala @@ -200,7 +200,7 @@ abstract class CopyPropagation { in(b) = lattice.bottom out(b) = lattice.bottom assert(out.contains(b), out) - log("Added point: " + b) + debuglog("CopyAnalysis added point: " + b) } m.exh foreach { e => in(e.startBlock) = new copyLattice.State(copyLattice.emptyBinding, copyLattice.exceptionHandlerStack); @@ -531,11 +531,11 @@ abstract class CopyPropagation { case 0 => () case 1 if ctor.tpe.paramTypes.head == ctor.owner.rawowner.tpe => // it's an unused outer - log("considering unused outer at position 0 in " + ctor.tpe.paramTypes) + debuglog("considering unused outer at position 0 in " + ctor.tpe.paramTypes) paramTypes = paramTypes.tail values = values.tail case _ => - log("giving up on " + ctor + "(diff: " + diff + ")") + debuglog("giving up on " + ctor + "(diff: " + diff + ")") return bindings } @@ -566,7 +566,7 @@ abstract class CopyPropagation { 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) - } + } ).mkString } /* class CopyAnalysis */ 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 6bd3ac5791..31c2077097 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala @@ -640,7 +640,7 @@ abstract class TypeFlowAnalysis { For each of them, its `lastInstruction` (after which no more typeflows are needed) is found. */ - def reinit(m: icodes.IMethod, staleOut: List[BasicBlock], inlined: collection.Set[BasicBlock], staleIn: collection.Set[BasicBlock]) { + def reinit(m: icodes.IMethod, staleOut: List[BasicBlock], inlined: scala.collection.Set[BasicBlock], staleIn: scala.collection.Set[BasicBlock]) { if (this.method == null || this.method.symbol != m.symbol) { init(m) return @@ -691,7 +691,7 @@ abstract class TypeFlowAnalysis { bs foreach enqueue } - private def blankOut(blocks: collection.Set[BasicBlock]) { + private def blankOut(blocks: scala.collection.Set[BasicBlock]) { blocks foreach { b => in(b) = typeFlowLattice.bottom out(b) = typeFlowLattice.bottom diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala b/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala index b9d8fb18a1..086327934b 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala @@ -12,7 +12,7 @@ import scala.tools.nsc.util.ScalaClassLoader import scala.tools.util.JavapClass import java.util.jar.{ JarEntry, JarOutputStream, Attributes } import Attributes.Name -import language.postfixOps +import scala.language.postfixOps /** For the last mile: turning generated bytecode in memory into * something you can use. Has implementations for writing to class diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala index 2e0ac727f9..99d019ecd2 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -154,8 +154,10 @@ abstract class GenASM extends SubComponent with BytecodeWriters { inform("[running phase " + name + " on icode]") if (settings.Xdce.value) - for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym)) + for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym)) { + log(s"Optimizer eliminated ${sym.fullNameString}") icodes.classes -= sym + } // For predictably ordered error messages. var sortedClasses = classes.values.toList sortBy ("" + _.symbol.fullName) @@ -2042,12 +2044,12 @@ abstract class GenASM extends SubComponent with BytecodeWriters { var isModuleInitialized = false - val labels: collection.Map[BasicBlock, asm.Label] = mutable.HashMap(linearization map (_ -> new asm.Label()) : _*) + val labels: scala.collection.Map[BasicBlock, asm.Label] = mutable.HashMap(linearization map (_ -> new asm.Label()) : _*) val onePastLast = new asm.Label // token for the mythical instruction past the last instruction in the method being emitted // maps a BasicBlock b to the Label that corresponds to b's successor in the linearization. The last BasicBlock is mapped to the onePastLast label. - val linNext: collection.Map[BasicBlock, asm.Label] = { + val linNext: scala.collection.Map[BasicBlock, asm.Label] = { val result = mutable.HashMap.empty[BasicBlock, asm.Label] var rest = linearization var prev = rest.head @@ -2225,7 +2227,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { } } - def getMerged(): collection.Map[Local, List[Interval]] = { + def getMerged(): scala.collection.Map[Local, List[Interval]] = { // TODO should but isn't: unbalanced start(s) of scope(s) val shouldBeEmpty = pending filter { p => val Pair(k, st) = p; st.nonEmpty }; val merged = mutable.Map[Local, List[Interval]]() diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala index aa857235b0..98e55bf435 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala @@ -18,7 +18,7 @@ import JAccessFlags._ import JObjectType.{ JAVA_LANG_STRING, JAVA_LANG_OBJECT } import java.util.jar.{ JarEntry, JarOutputStream } import scala.tools.nsc.io.AbstractFile -import language.postfixOps +import scala.language.postfixOps /** This class ... * @@ -122,8 +122,10 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with inform("[running phase " + name + " on icode]") if (settings.Xdce.value) - for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym)) + for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym)) { + log(s"Optimizer eliminated ${sym.fullNameString}") icodes.classes -= sym + } // For predictably ordered error messages. val sortedClasses = classes.values.toList sortBy ("" + _.symbol.fullName) diff --git a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala index 5a0c30bdb7..242b60c769 100644 --- a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala +++ b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala @@ -15,7 +15,7 @@ import scala.tools.nsc.symtab._ import ch.epfl.lamp.compiler.msil.{Type => MsilType, _} import ch.epfl.lamp.compiler.msil.emit._ import ch.epfl.lamp.compiler.msil.util.PECustomMod -import language.postfixOps +import scala.language.postfixOps abstract class GenMSIL extends SubComponent { import global._ diff --git a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala index 7772ccbdd5..eb2da72401 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala @@ -35,7 +35,7 @@ abstract class ClosureElimination extends SubComponent { case (STORE_LOCAL(x), LOAD_LOCAL(y)) if (x == y) => var liveOut = liveness.out(bb) if (!liveOut(x)) { - log("store/load to a dead local? " + x) + debuglog("store/load to a dead local? " + x) val instrs = bb.getArray var idx = instrs.length - 1 while (idx > 0 && (instrs(idx) ne i2)) { @@ -43,7 +43,7 @@ abstract class ClosureElimination extends SubComponent { idx -= 1 } if (!liveOut(x)) { - log("removing dead store/load " + x) + log("Removing dead store/load of " + x.sym.initialize.defString) Some(Nil) } else None } else @@ -84,6 +84,7 @@ abstract class ClosureElimination extends SubComponent { */ class ClosureElim { def analyzeClass(cls: IClass): Unit = if (settings.Xcloselim.value) { + log(s"Analyzing ${cls.methods.size} methods in $cls.") cls.methods foreach { m => analyzeMethod(m) peephole(m) @@ -95,7 +96,6 @@ abstract class ClosureElimination extends SubComponent { /* Some embryonic copy propagation. */ def analyzeMethod(m: IMethod): Unit = try {if (m.hasCode) { - log("Analyzing " + m) cpp.init(m) cpp.run @@ -110,23 +110,20 @@ abstract class ClosureElimination extends SubComponent { t match { case Deref(This) | Const(_) => bb.replaceInstruction(i, valueToInstruction(t)); - log("replaced " + i + " with " + t) + debuglog(s"replaced $i with $t") case _ => - bb.replaceInstruction(i, LOAD_LOCAL(info.getAlias(l))) - log("replaced " + i + " with " + info.getAlias(l)) - + val t = info.getAlias(l) + bb.replaceInstruction(i, LOAD_LOCAL(t)) + debuglog(s"replaced $i with $t") } case LOAD_FIELD(f, false) /* if accessible(f, m.symbol) */ => def replaceFieldAccess(r: Record) { val Record(cls, bindings) = r - info.getFieldNonRecordValue(r, f) match { - case Some(v) => - bb.replaceInstruction(i, - DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil); - log("Replaced " + i + " with " + info.getFieldNonRecordValue(r, f)); - case None => + info.getFieldNonRecordValue(r, f) foreach { v => + bb.replaceInstruction(i, DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil) + debuglog(s"replaced $i with $v") } } @@ -157,14 +154,14 @@ abstract class ClosureElimination extends SubComponent { value match { case Boxed(LocalVar(loc2)) => bb.replaceInstruction(i, DROP(icodes.ObjectReference) :: valueToInstruction(info.getBinding(loc2)) :: Nil) - log("replaced " + i + " with " + info.getBinding(loc2)) + debuglog("replaced " + i + " with " + info.getBinding(loc2)) case _ => () } case Boxed(LocalVar(loc1)) :: _ => val loc2 = info.getAlias(loc1) bb.replaceInstruction(i, DROP(icodes.ObjectReference) :: valueToInstruction(Deref(LocalVar(loc2))) :: Nil) - log("replaced " + i + " with " + LocalVar(loc2)) + debuglog("replaced " + i + " with " + LocalVar(loc2)) case _ => } diff --git a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala index fd949576e1..36a5d61cfb 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala @@ -44,6 +44,7 @@ abstract class DeadCodeElimination extends SubComponent { class DeadCode { def analyzeClass(cls: IClass) { + log(s"Analyzing ${cls.methods.size} methods in $cls.") cls.methods.foreach { m => this.method = m dieCodeDie(m) @@ -73,7 +74,7 @@ abstract class DeadCodeElimination extends SubComponent { def dieCodeDie(m: IMethod) { if (m.hasCode) { - log("dead code elimination on " + m); + debuglog("dead code elimination on " + m); dropOf.clear() m.code.blocks.clear() accessedLocals = m.params.reverse @@ -82,8 +83,10 @@ abstract class DeadCodeElimination extends SubComponent { mark sweep(m) accessedLocals = accessedLocals.distinct - if ((m.locals diff accessedLocals).nonEmpty) { - log("Removed dead locals: " + (m.locals diff accessedLocals)) + val diff = m.locals diff accessedLocals + if (diff.nonEmpty) { + val msg = diff.map(_.sym.name)mkString(", ") + log(s"Removed ${diff.size} dead locals: $msg") m.locals = accessedLocals.reverse } } @@ -126,7 +129,7 @@ abstract class DeadCodeElimination extends SubComponent { case RETURN(_) | JUMP(_) | CJUMP(_, _, _, _) | CZJUMP(_, _, _, _) | STORE_FIELD(_, _) | THROW(_) | LOAD_ARRAY_ITEM(_) | STORE_ARRAY_ITEM(_) | SCOPE_ENTER(_) | SCOPE_EXIT(_) | STORE_THIS(_) | LOAD_EXCEPTION(_) | SWITCH(_, _) | MONITOR_ENTER() | MONITOR_EXIT() => worklist += ((bb, idx)) - case CALL_METHOD(m1, _) if isSideEffecting(m1) => worklist += ((bb, idx)); log("marking " + m1) + case CALL_METHOD(m1, _) if isSideEffecting(m1) => worklist += ((bb, idx)); debuglog("marking " + m1) case CALL_METHOD(m1, SuperCall(_)) => worklist += ((bb, idx)) // super calls to constructor case DROP(_) => @@ -173,7 +176,7 @@ abstract class DeadCodeElimination extends SubComponent { instr match { case LOAD_LOCAL(l1) => for ((l2, bb1, idx1) <- defs((bb, idx)) if l1 == l2; if !useful(bb1)(idx1)) { - log("\tAdding " + bb1(idx1)) + debuglog("\tAdding " + bb1(idx1)) worklist += ((bb1, idx1)) } @@ -197,7 +200,7 @@ abstract class DeadCodeElimination extends SubComponent { case _ => for ((bb1, idx1) <- rdef.findDefs(bb, idx, instr.consumed) if !useful(bb1)(idx1)) { - log("\tAdding " + bb1(idx1)) + debuglog("\tAdding " + bb1(idx1)) worklist += ((bb1, idx1)) } } @@ -232,7 +235,7 @@ abstract class DeadCodeElimination extends SubComponent { } else { i match { case NEW(REFERENCE(sym)) => - log("skipped object creation: " + sym + "inside " + m) + log(s"Eliminated instantation of $sym inside $m") case _ => () } debuglog("Skipped: bb_" + bb + ": " + idx + "( " + i + ")") @@ -240,7 +243,7 @@ abstract class DeadCodeElimination extends SubComponent { } if (bb.nonEmpty) bb.close - else log("empty block encountered") + else log(s"empty block encountered in $m") } } @@ -252,7 +255,7 @@ abstract class DeadCodeElimination extends SubComponent { foreachWithIndex(bb.toList) { (i, idx) => if (!useful(bb)(idx)) { foreachWithIndex(i.consumedTypes.reverse) { (consumedType, depth) => - log("Finding definitions of: " + i + "\n\t" + consumedType + " at depth: " + depth) + debuglog("Finding definitions of: " + i + "\n\t" + consumedType + " at depth: " + depth) val defs = rdef.findDefs(bb, idx, 1, depth) for (d <- defs) { val (bb, idx) = d diff --git a/src/compiler/scala/tools/nsc/backend/opt/InlineExceptionHandlers.scala b/src/compiler/scala/tools/nsc/backend/opt/InlineExceptionHandlers.scala index f1f597322e..98120f0614 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/InlineExceptionHandlers.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/InlineExceptionHandlers.scala @@ -93,10 +93,9 @@ abstract class InlineExceptionHandlers extends SubComponent { val startTime = System.currentTimeMillis currentClass = c - log("Starting " + c) + debuglog("Starting InlineExceptionHandlers on " + c) c.methods foreach applyMethod - - log("Finished " + c + "... " + (System.currentTimeMillis - startTime) + "ms") + debuglog("Finished InlineExceptionHandlers on " + c + "... " + (System.currentTimeMillis - startTime) + "ms") currentClass = null } diff --git a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala index 5828a6200e..5c2c2a37e6 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala @@ -44,7 +44,7 @@ abstract class Inliners extends SubComponent { import definitions.{ NullClass, NothingClass, ObjectClass, PredefModule, RuntimePackage, ScalaInlineClass, ScalaNoInlineClass, - isFunctionType + isFunctionType, isByNameParamType } val phaseName = "inliner" @@ -143,7 +143,6 @@ abstract class Inliners extends SubComponent { } def isBottomType(sym: Symbol) = sym == NullClass || sym == NothingClass - def posToStr(pos: scala.reflect.internal.util.Position) = if (pos.isDefined) pos.point.toString else "<nopos>" /** Is the given class a closure? */ def isClosureClass(cls: Symbol): Boolean = @@ -194,6 +193,27 @@ abstract class Inliners extends SubComponent { private var currentIClazz: IClass = _ private def warn(pos: Position, msg: String) = currentIClazz.cunit.inlinerWarning(pos, msg) + private def ownedName(sym: Symbol): String = exitingUncurry { + val count = ( + if (!sym.isMethod) 1 + else if (sym.owner.isAnonymousFunction) 3 + else 2 + ) + (sym.ownerChain take count filterNot (_.isPackageClass)).reverseMap(_.nameString).mkString(".") + } + private def inlineLog(what: String, main: => String, comment: => String) { + def cstr = comment match { + case "" => "" + case str => " // " + str + } + val width = if (currentIClazz eq null) 40 else currentIClazz.symbol.enclosingPackage.fullName.length + 25 + val fmt = "%8s %-" + width + "s" + cstr + log(fmt.format(what, main)) + } + private def inlineLog(what: String, main: Symbol, comment: => String) { + inlineLog(what, ownedName(main), comment) + } + val recentTFAs = mutable.Map.empty[Symbol, Tuple2[Boolean, analysis.MethodTFA]] private def getRecentTFA(incm: IMethod, forceable: Boolean): (Boolean, analysis.MethodTFA) = { @@ -244,14 +264,15 @@ abstract class Inliners extends SubComponent { def analyzeClass(cls: IClass): Unit = if (settings.inline.value) { - debuglog("Analyzing " + cls) + inlineLog("class", s"${cls.symbol.decodedName}", s"analyzing ${cls.methods.size} methods in $cls") this.currentIClazz = cls val ms = cls.methods sorted imethodOrdering ms foreach { im => - if(hasInline(im.symbol)) { - log("Not inlining into " + im.symbol.originalName.decode + " because it is marked @inline.") - } else if(im.hasCode && !im.symbol.isBridge) { + if (hasInline(im.symbol)) { + inlineLog("skip", im.symbol, "no inlining into @inline methods") + } + else if(im.hasCode && !im.symbol.isBridge) { analyzeMethod(im) } } @@ -296,6 +317,8 @@ abstract class Inliners extends SubComponent { * */ def analyzeMethod(m: IMethod): Unit = { // m.normalize + if (settings.debug.value) + inlineLog("caller", ownedName(m.symbol), "in " + m.symbol.owner.fullName) var sizeBeforeInlining = m.code.blockCount var instrBeforeInlining = m.code.instructionCount @@ -306,8 +329,8 @@ abstract class Inliners extends SubComponent { val fresh = mutable.HashMap.empty[String, Int] withDefaultValue 0 // how many times have we already inlined this method here? val inlinedMethodCount = mutable.HashMap.empty[Symbol, Int] withDefaultValue 0 - val caller = new IMethodInfo(m) + def analyzeMessage = s"Analyzing ${caller.length} blocks of $m for inlining sites." def preInline(isFirstRound: Boolean): Int = { val inputBlocks = caller.m.linearizedBlocks() @@ -354,15 +377,17 @@ abstract class Inliners extends SubComponent { */ def analyzeInc(i: CALL_METHOD, bb: BasicBlock, receiver: Symbol, stackLength: Int, concreteMethod: Symbol): Boolean = { assert(bb.toList contains i, "Candidate callsite does not belong to BasicBlock.") - - var inlined = false val shouldWarn = hasInline(i.method) - def warnNoInline(reason: String) = { - if (shouldWarn) { - warn(i.pos, "Could not inline required method %s because %s.".format(i.method.originalName.decode, reason)) - } - } + def warnNoInline(reason: String): Boolean = { + def msg = "Could not inline required method %s because %s.".format(i.method.originalName.decode, reason) + if (settings.debug.value) + inlineLog("fail", i.method.fullName, reason) + if (shouldWarn) + warn(i.pos, msg) + + false + } var isAvailable = icodes available concreteMethod.enclClass @@ -378,92 +403,69 @@ abstract class Inliners extends SubComponent { isAvailable = icodes.load(concreteMethod.enclClass) } - def isCandidate = ( - isClosureClass(receiver) - || concreteMethod.isEffectivelyFinal - || receiver.isEffectivelyFinal - ) + def isCandidate = ( + isClosureClass(receiver) + || concreteMethod.isEffectivelyFinal + || receiver.isEffectivelyFinal + ) - def isApply = concreteMethod.name == nme.apply + def isApply = concreteMethod.name == nme.apply - def isCountable = !( - isClosureClass(receiver) - || isApply - || isMonadicMethod(concreteMethod) - || receiver.enclosingPackage == definitions.RuntimePackage - ) // only count non-closures + def isCountable = !( + isClosureClass(receiver) + || isApply + || isMonadicMethod(concreteMethod) + || receiver.enclosingPackage == definitions.RuntimePackage + ) // only count non-closures debuglog("Treating " + i + "\n\treceiver: " + receiver + "\n\ticodes.available: " + isAvailable + "\n\tconcreteMethod.isEffectivelyFinal: " + concreteMethod.isEffectivelyFinal) - if (isAvailable && isCandidate) { - lookupIMethod(concreteMethod, receiver) match { - - case Some(callee) if callee.hasCode => - val inc = new IMethodInfo(callee) - val pair = new CallerCalleeInfo(caller, inc, fresh, inlinedMethodCount) - - if(inc.hasHandlers && (stackLength == -1)) { - // no inlining is done, yet don't warn about it, stackLength == -1 indicates we're trying to inlineWithoutTFA. - // Shortly, a TFA will be computed and an error message reported if indeed inlining not possible. - return false - } - - (pair isStampedForInlining stackLength) match { - - case inlInfo if inlInfo.isSafe => - - (inlInfo: @unchecked) match { - - case FeasibleInline(accessNeeded, toBecomePublic) => - for(f <- toBecomePublic) { - debuglog("Making public (synthetic) field-symbol: " + f) - f setFlag Flags.notPRIVATE - f setFlag Flags.notPROTECTED - } - // only add to `knownSafe` after all `toBecomePublic` fields actually made public. - if(accessNeeded == NonPublicRefs.Public) { tfa.knownSafe += inc.sym } - - case InlineableAtThisCaller => () - - } - - retry = true - inlined = true - if (isCountable) { count += 1 }; + if (!isCandidate) warnNoInline("it can be overridden") + else if (!isAvailable) warnNoInline("bytecode unavailable") + else lookupIMethod(concreteMethod, receiver) filter (callee => callee.hasCode || warnNoInline("callee has no code")) exists { callee => + val inc = new IMethodInfo(callee) + val pair = new CallerCalleeInfo(caller, inc, fresh, inlinedMethodCount) - pair.doInline(bb, i) - if (!pair.isInlineForced || inc.isMonadic) { caller.inlinedCalls += 1 }; - inlinedMethodCount(inc.sym) += 1 - - // Remove the caller from the cache (this inlining might have changed its calls-private relation). - usesNonPublics -= m - recentTFAs -= m.symbol - - - case DontInlineHere(msg) => - debuglog("inline failed, reason: " + msg) - warnNoInline(msg) - - case NeverSafeToInline => () - } - - case Some(callee) => - assert(!callee.hasCode, "The case clause right before this one should have handled this case.") - warnNoInline("callee (" + callee + ") has no code") - () + if (inc.hasHandlers && (stackLength == -1)) { + // no inlining is done, yet don't warn about it, stackLength == -1 indicates we're trying to inlineWithoutTFA. + // Shortly, a TFA will be computed and an error message reported if indeed inlining not possible. + false + } + else { + val isSafe = pair isStampedForInlining stackLength match { + case DontInlineHere(msg) => warnNoInline(msg) + case NeverSafeToInline => false + case InlineableAtThisCaller => true + case inl @ FeasibleInline(_, _) if !inl.isSafe => false + case FeasibleInline(required, toPublicize) => + for (f <- toPublicize) { + inlineLog("access", f, "making public") + f setFlag Flags.notPRIVATE + f setFlag Flags.notPROTECTED + } + // only add to `knownSafe` after all `toPublicize` fields actually made public. + if (required == NonPublicRefs.Public) + tfa.knownSafe += inc.sym - case None => - warnNoInline("bytecode was not available") - debuglog("could not find icode\n\treceiver: " + receiver + "\n\tmethod: " + concreteMethod) + true + } + isSafe && { + retry = true + if (isCountable) count += 1 + pair.doInline(bb, i) + if (!pair.isInlineForced || inc.isMonadic) caller.inlinedCalls += 1 + inlinedMethodCount(inc.sym) += 1 + + // Remove the caller from the cache (this inlining might have changed its calls-private relation). + usesNonPublics -= m + recentTFAs -= m.symbol + true + } } - } else { - warnNoInline(if(!isAvailable) "bytecode was not available" else "it can be overridden") } - - inlined } /* Pre-inlining consists in invoking the usual inlining subroutine with (receiver class, concrete method) pairs as input @@ -485,7 +487,7 @@ abstract class Inliners extends SubComponent { do { retry = false - log("Analyzing " + m + " count " + count + " with " + caller.length + " blocks") + debuglog(analyzeMessage) /* it's important not to inline in unreachable basic blocks. linearizedBlocks() returns only reachable ones. */ tfa.callerLin = caller.m.linearizedBlocks() @@ -567,9 +569,16 @@ abstract class Inliners extends SubComponent { m.normalize if (sizeBeforeInlining > 0) { val instrAfterInlining = m.code.instructionCount - val prefix = if ((instrAfterInlining > 2 * instrBeforeInlining) && (instrAfterInlining > 200)) " !! " else "" - log(prefix + " %s blocks before inlining: %d (%d) after: %d (%d)".format( - m.symbol.fullName, sizeBeforeInlining, instrBeforeInlining, m.code.blockCount, instrAfterInlining)) + val prefix = if ((instrAfterInlining > 2 * instrBeforeInlining) && (instrAfterInlining > 200)) "!!" else "" + val inlinings = caller.inlinedCalls + if (inlinings > 0) { + val s1 = s"instructions $instrBeforeInlining -> $instrAfterInlining" + val s2 = if (sizeBeforeInlining == m.code.blockCount) "" else s", blocks $sizeBeforeInlining -> ${m.code.blockCount}" + val callees = inlinedMethodCount.toList map { case (k, v) => k.fullNameString + ( if (v == 1) "" else "/" + v ) } + + inlineLog("inlined", m.symbol.fullName, callees.sorted.mkString(inlinings + " inlined: ", ", ", "")) + inlineLog("<<tldr>>", m.symbol.fullName, s"${m.symbol.nameString}: $s1$s2") + } } } @@ -589,6 +598,8 @@ abstract class Inliners extends SubComponent { } class IMethodInfo(val m: IMethod) { + override def toString = m.toString + val sym = m.symbol val name = sym.name def owner = sym.owner @@ -608,10 +619,11 @@ abstract class Inliners extends SubComponent { def instructions = m.code.instructions // def linearized = linearizer linearize m - def isSmall = (length <= SMALL_METHOD_SIZE) && blocks(0).length < 10 - def isLarge = length > MAX_INLINE_SIZE - def isRecursive = m.recursive - def hasHandlers = handlers.nonEmpty || m.bytecodeHasEHs + def isSmall = (length <= SMALL_METHOD_SIZE) && blocks(0).length < 10 + def isLarge = length > MAX_INLINE_SIZE + def isRecursive = m.recursive + def hasHandlers = handlers.nonEmpty || m.bytecodeHasEHs + def hasClosureParam = paramTypes exists (tp => isByNameParamType(tp) || isFunctionType(tp)) def isSynchronized = sym.hasFlag(Flags.SYNCHRONIZED) def hasNonFinalizerHandler = handlers exists { @@ -661,9 +673,9 @@ abstract class Inliners extends SubComponent { * * TODO handle more robustly the case of a trait var changed at the source-level from public to private[this] * (eg by having ICodeReader use unpickler, see SI-5442). - + DISABLED - + def potentiallyPublicized(f: Symbol): Boolean = { (m.sourceFile eq NoSourceFile) && f.name.containsChar('$') } @@ -687,7 +699,7 @@ abstract class Inliners extends SubComponent { val i = iter.next() getAccess(i) match { case Private => - log("instruction " + i + " requires private access.") + inlineLog("access", s"instruction $i requires private access", "pos=" + i.pos) toBecomePublic = Nil seen = Private case Protected => seen = Protected @@ -734,7 +746,7 @@ abstract class Inliners extends SubComponent { toBecomePublic: List[Symbol] ) - final class CallerCalleeInfo(val caller: IMethodInfo, val inc: IMethodInfo, fresh: mutable.Map[String, Int], inlinedMethodCount: collection.Map[Symbol, Int]) { + final class CallerCalleeInfo(val caller: IMethodInfo, val inc: IMethodInfo, fresh: mutable.Map[String, Int], inlinedMethodCount: scala.collection.Map[Symbol, Int]) { assert(!caller.isBridge && inc.m.hasCode, "A guard in Inliner.analyzeClass() should have prevented from getting here.") @@ -764,11 +776,10 @@ abstract class Inliners extends SubComponent { tfa.warnIfInlineFails.remove(instr) val targetPos = instr.pos - log("Inlining " + inc.m + " in " + caller.m + " at pos: " + posToStr(targetPos)) def blockEmit(i: Instruction) = block.emit(i, targetPos) def newLocal(baseName: String, kind: TypeKind) = - new Local(caller.sym.newVariable(freshName(baseName), targetPos), kind, false) + new Local(caller.sym.newVariable(freshName(baseName), targetPos) setInfo kind.toType, kind, false) val (hasRETURN, a) = getRecentTFA(inc.m, isInlineForced) @@ -955,6 +966,7 @@ abstract class Inliners extends SubComponent { if(reasonWhyNever != null) { tfa.knownNever += inc.sym + inlineLog("never", inc.sym, reasonWhyNever) // next time around NeverSafeToInline is returned, thus skipping (duplicate) msg, this is intended. return DontInlineHere(inc.m + " " + reasonWhyNever) } @@ -977,10 +989,15 @@ abstract class Inliners extends SubComponent { * As a result of (b), some synthetic private members can be chosen to become public. */ - if(!isInlineForced && !isScoreOK) { + val score = inlinerScore + val scoreStr = if (score > 0) "+" + score else "" + score + val what = if (score > 0) "ok to" else "don't" + inlineLog(scoreStr, inc.m.symbol, s"$what inline into ${ownedName(caller.m.symbol)}") + + if (!isInlineForced && score <= 0) { // During inlining retry, a previous caller-callee pair that scored low may pass. // Thus, adding the callee to tfa.knownUnsafe isn't warranted. - return DontInlineHere("too low score (heuristics)") + return DontInlineHere(s"inliner heuristic") } if(inc.hasHandlers && (stackLength > inc.minimumStack)) { @@ -999,7 +1016,9 @@ abstract class Inliners extends SubComponent { val accReq = inc.accessRequirements if(!canAccess(accReq.accessNeeded)) { tfa.knownUnsafe += inc.sym - return DontInlineHere("access level required by callee not matched by caller") + val msg = "access level required by callee not matched by caller" + inlineLog("fail", inc.sym, msg) + return DontInlineHere(msg) } FeasibleInline(accReq.accessNeeded, accReq.toBecomePublic) @@ -1021,9 +1040,7 @@ abstract class Inliners extends SubComponent { * - it's good to inline closures functions. * - it's bad (useless) to inline inside bridge methods */ - def isScoreOK: Boolean = { - debuglog("shouldInline: " + caller.m + " , callee:" + inc.m) - + def inlinerScore: Int = { var score = 0 // better not inline inside closures, but hope that the closure itself is repeatedly inlined @@ -1031,10 +1048,11 @@ abstract class Inliners extends SubComponent { else if (caller.inlinedCalls < 1) score -= 1 // only monadic methods can trigger the first inline if (inc.isSmall) score += 1; + // if (inc.hasClosureParam) score += 2 if (inc.isLarge) score -= 1; if (caller.isSmall && isLargeSum) { score -= 1 - debuglog("shouldInline: score decreased to " + score + " because small " + caller + " would become large") + debuglog(s"inliner score decreased to $score because small caller $caller would become large") } if (inc.isMonadic) score += 3 @@ -1042,10 +1060,7 @@ abstract class Inliners extends SubComponent { if (inc.isInClosure) score += 2; if (inlinedMethodCount(inc.sym) > 2) score -= 2; - - log("shouldInline(" + inc.m + ") score: " + score) - - score > 0 + score } } diff --git a/src/compiler/scala/tools/nsc/dependencies/Changes.scala b/src/compiler/scala/tools/nsc/dependencies/Changes.scala index 176c00c025..7f5f412a20 100644 --- a/src/compiler/scala/tools/nsc/dependencies/Changes.scala +++ b/src/compiler/scala/tools/nsc/dependencies/Changes.scala @@ -3,7 +3,7 @@ package dependencies import symtab.Flags -import collection._ +import scala.collection._ /** A component that describes the possible changes between successive * compilations of a class. diff --git a/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala b/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala index e35191ca20..ad6ca68fec 100644 --- a/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala +++ b/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala @@ -2,7 +2,7 @@ package scala.tools.nsc package dependencies import io.Path -import collection._ +import scala.collection._ import symtab.Flags import scala.tools.nsc.io.AbstractFile import scala.reflect.internal.util.SourceFile diff --git a/src/compiler/scala/tools/nsc/doc/Settings.scala b/src/compiler/scala/tools/nsc/doc/Settings.scala index dbc34bd7b3..f5df772d7d 100644 --- a/src/compiler/scala/tools/nsc/doc/Settings.scala +++ b/src/compiler/scala/tools/nsc/doc/Settings.scala @@ -8,7 +8,7 @@ package doc import java.io.File import java.lang.System -import language.postfixOps +import scala.language.postfixOps /** An extended version of compiler settings, with additional Scaladoc-specific options. * @param error A function that prints a string to the appropriate error stream @@ -257,7 +257,7 @@ class Settings(error: String => Unit, val printMsg: String => Unit = println(_)) ("scala.reflect.ClassManifest" -> ((tparam: String) => tparam + " is accompanied by a ClassManifest, which is a runtime representation of its type that survives erasure")) + ("scala.reflect.OptManifest" -> ((tparam: String) => tparam + " is accompanied by an OptManifest, which can be either a runtime representation of its type or the NoManifest, which means the runtime type is not available")) + ("scala.reflect.ClassTag" -> ((tparam: String) => tparam + " is accompanied by a ClassTag, which is a runtime representation of its type that survives erasure")) + - ("scala.reflect.AbsTypeTag" -> ((tparam: String) => tparam + " is accompanied by an AbsTypeTag, which is a runtime representation of its type that survives erasure")) + + ("scala.reflect.WeakTypeTag" -> ((tparam: String) => tparam + " is accompanied by an WeakTypeTag, which is a runtime representation of its type that survives erasure")) + ("scala.reflect.base.TypeTags.TypeTag" -> ((tparam: String) => tparam + " is accompanied by a TypeTag, which is a runtime representation of its type that survives erasure")) /** diff --git a/src/compiler/scala/tools/nsc/doc/Uncompilable.scala b/src/compiler/scala/tools/nsc/doc/Uncompilable.scala index 7e57f9fd9f..812b62a1c6 100644 --- a/src/compiler/scala/tools/nsc/doc/Uncompilable.scala +++ b/src/compiler/scala/tools/nsc/doc/Uncompilable.scala @@ -5,8 +5,8 @@ package scala.tools.nsc package doc -import language.implicitConversions -import language.postfixOps +import scala.language.implicitConversions +import scala.language.postfixOps /** Some glue between DocParser (which reads source files which can't be compiled) * and the scaladoc model. diff --git a/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala b/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala index 7a74c569f3..f7c5611b8a 100644 --- a/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala +++ b/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala @@ -10,8 +10,8 @@ package html import model._ import comment._ -import xml.{XML, NodeSeq} -import xml.dtd.{DocType, PublicID} +import scala.xml.{XML, NodeSeq} +import scala.xml.dtd.{DocType, PublicID} import scala.collection._ import java.io.Writer @@ -87,7 +87,7 @@ abstract class HtmlPage extends Page { thisPage => case Title(in, _) => <h6>{ inlineToHtml(in) }</h6> case Paragraph(in) => <p>{ inlineToHtml(in) }</p> case Code(data) => - <pre>{ SyntaxHigh(data) }</pre> //<pre>{ xml.Text(data) }</pre> + <pre>{ SyntaxHigh(data) }</pre> //<pre>{ scala.xml.Text(data) }</pre> case UnorderedList(items) => <ul>{ listItemsToHtml(items) }</ul> case OrderedList(items, listStyle) => @@ -119,9 +119,9 @@ abstract class HtmlPage extends Page { thisPage => case Subscript(in) => <sub>{ inlineToHtml(in) }</sub> case Link(raw, title) => <a href={ raw }>{ inlineToHtml(title) }</a> case Monospace(in) => <code>{ inlineToHtml(in) }</code> - case Text(text) => xml.Text(text) + case Text(text) => scala.xml.Text(text) case Summary(in) => inlineToHtml(in) - case HtmlTag(tag) => xml.Unparsed(tag) + case HtmlTag(tag) => scala.xml.Unparsed(tag) case EntityLink(target, link) => linkToHtml(target, link, true) } @@ -158,11 +158,11 @@ abstract class HtmlPage extends Page { thisPage => if (starts.isEmpty && (inPos == string.length)) NodeSeq.Empty else if (starts.isEmpty) - xml.Text(string.slice(inPos, string.length)) + scala.xml.Text(string.slice(inPos, string.length)) else if (inPos == starts.head) toLinksIn(inPos, starts) else { - xml.Text(string.slice(inPos, starts.head)) ++ toLinksIn(starts.head, starts) + scala.xml.Text(string.slice(inPos, starts.head)) ++ toLinksIn(starts.head, starts) } } def toLinksIn(inPos: Int, starts: List[Int]): NodeSeq = { @@ -173,7 +173,7 @@ abstract class HtmlPage extends Page { thisPage => if (hasLinks) toLinksOut(0, tpe.refEntity.keySet.toList) else - xml.Text(string) + scala.xml.Text(string) } def typesToHtml(tpess: List[model.TypeEntity], hasLinks: Boolean, sep: NodeSeq): NodeSeq = tpess match { @@ -192,10 +192,10 @@ abstract class HtmlPage extends Page { thisPage => if (hasPage(dTpl)) { <a href={ relativeLinkTo(dTpl) } class="extype" name={ dTpl.qualifiedName }>{ if (name eq null) dTpl.name else name }</a> } else { - xml.Text(if (name eq null) dTpl.name else name) + scala.xml.Text(if (name eq null) dTpl.name else name) } case ndTpl: NoDocTemplate => - xml.Text(if (name eq null) ndTpl.name else name) + scala.xml.Text(if (name eq null) ndTpl.name else name) } /** Returns the HTML code that represents the templates in `tpls` as a list of hyperlinked names. */ diff --git a/src/compiler/scala/tools/nsc/doc/html/SyntaxHigh.scala b/src/compiler/scala/tools/nsc/doc/html/SyntaxHigh.scala index f1eab841f9..e21ee07963 100644 --- a/src/compiler/scala/tools/nsc/doc/html/SyntaxHigh.scala +++ b/src/compiler/scala/tools/nsc/doc/html/SyntaxHigh.scala @@ -5,7 +5,7 @@ package scala.tools.nsc.doc.html -import xml.NodeSeq +import scala.xml.NodeSeq /** Highlight the syntax of Scala code appearing in a `{{{` wiki block * (see method `HtmlPage.blockToHtml`). @@ -40,7 +40,7 @@ private[html] object SyntaxHigh { /** Standard library classes/objects, sorted alphabetically */ val standards = Array ( - "AbsTypeTag", "Any", "AnyRef", "AnyVal", "App", "Application", "Array", + "WeakTypeTag", "Any", "AnyRef", "AnyVal", "App", "Application", "Array", "Boolean", "Byte", "Char", "Class", "ClassTag", "ClassManifest", "Console", "Double", "Enumeration", "Float", "Function", "Int", "List", "Long", "Manifest", "Map", @@ -281,6 +281,6 @@ private[html] object SyntaxHigh { } parse("", 0) - xml.Unparsed(out.toString) + scala.xml.Unparsed(out.toString) } } diff --git a/src/compiler/scala/tools/nsc/doc/html/page/ReferenceIndex.scala b/src/compiler/scala/tools/nsc/doc/html/page/ReferenceIndex.scala index 6d83b4e6a5..cd76f84a37 100755 --- a/src/compiler/scala/tools/nsc/doc/html/page/ReferenceIndex.scala +++ b/src/compiler/scala/tools/nsc/doc/html/page/ReferenceIndex.scala @@ -44,7 +44,7 @@ class ReferenceIndex(letter: Char, index: doc.Index, universe: Universe) extends <strike>{ name }</strike> }</div> <div class="occurrences">{ - for (owner <- occurrences) yield owner ++ xml.Text(" ") + for (owner <- occurrences) yield owner ++ scala.xml.Text(" ") }</div> </div> } diff --git a/src/compiler/scala/tools/nsc/doc/html/page/Source.scala b/src/compiler/scala/tools/nsc/doc/html/page/Source.scala index a51d66c6cc..edc0736400 100644 --- a/src/compiler/scala/tools/nsc/doc/html/page/Source.scala +++ b/src/compiler/scala/tools/nsc/doc/html/page/Source.scala @@ -10,7 +10,7 @@ package page import model._ import comment._ -import xml.{NodeSeq, Unparsed} +import scala.xml.{NodeSeq, Unparsed} import java.io.File class Source(sourceFile: File) extends HtmlPage { diff --git a/src/compiler/scala/tools/nsc/doc/html/page/Template.scala b/src/compiler/scala/tools/nsc/doc/html/page/Template.scala index 24a26b2ad3..d4e52ba120 100644 --- a/src/compiler/scala/tools/nsc/doc/html/page/Template.scala +++ b/src/compiler/scala/tools/nsc/doc/html/page/Template.scala @@ -13,7 +13,7 @@ import model.diagram._ import diagram._ import scala.xml.{ NodeSeq, Text, UnprefixedAttribute } -import language.postfixOps +import scala.language.postfixOps import model._ import model.diagram._ @@ -51,7 +51,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp var hash = '{ val p = templateToPath(tpl); (p.tail.reverse ::: List(p.head.replace(".html", ""))).mkString(".") }'; var anchor = window.location.hash; var anchor_opt = ''; - if (anchor.length { scala.xml.Unparsed(">=") /* unless we use Unparsed, it gets escaped and crashes the script */ } 1) + if (anchor.length { scala.xml.Unparsed(">=") /* unless we use Unparsed, it gets escaped and crashes the script */ } 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; }} @@ -93,7 +93,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp if (tpl.isRootPackage || tpl.inTemplate.isRootPackage) NodeSeq.Empty else - <p id="owner">{ templatesToHtml(tpl.inTemplate.toRoot.reverse.tail, xml.Text(".")) }</p> + <p id="owner">{ templatesToHtml(tpl.inTemplate.toRoot.reverse.tail, scala.xml.Text(".")) }</p> } <body class={ if (tpl.isType) "type" else "value" }> @@ -152,7 +152,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp <div id="ancestors"> <span class="filtertype">Implicitly<br/> </span> - <ol id="implicits"> { + <ol id="implicits"> { tpl.conversions.map { conv => val name = conv.conversionQualifiedName val hide = universe.settings.hiddenImplicits(name) @@ -415,14 +415,14 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp case Nil => NodeSeq.Empty case List(constraint) => - xml.Text("This conversion will take place only if ") ++ constraintToHtml(constraint) ++ xml.Text(".") + scala.xml.Text("This conversion will take place only if ") ++ constraintToHtml(constraint) ++ scala.xml.Text(".") case List(constraint1, constraint2) => - xml.Text("This conversion will take place only if ") ++ constraintToHtml(constraint1) ++ - xml.Text(" and at the same time ") ++ constraintToHtml(constraint2) ++ xml.Text(".") + scala.xml.Text("This conversion will take place only if ") ++ constraintToHtml(constraint1) ++ + scala.xml.Text(" and at the same time ") ++ constraintToHtml(constraint2) ++ scala.xml.Text(".") case constraints => <br/> ++ "This conversion will take place only if all of the following constraints are met:" ++ <br/> ++ { var index = 0 - constraints map { constraint => xml.Text({ index += 1; index } + ". ") ++ constraintToHtml(constraint) ++ <br/> } + constraints map { constraint => scala.xml.Text({ index += 1; index } + ". ") ++ constraintToHtml(constraint) ++ <br/> } } } @@ -440,18 +440,18 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp case d: Def => d.valueParams map (_ map (_ name) mkString("(", ", ", ")")) mkString case _ => "" // no parameters } - <br/> ++ xml.Text("To access this member you can use a ") ++ + <br/> ++ scala.xml.Text("To access this member you can use a ") ++ <a href="http://stackoverflow.com/questions/2087250/what-is-the-purpose-of-type-ascription-in-scala" - target="_blank">type ascription</a> ++ xml.Text(":") ++ + target="_blank">type ascription</a> ++ scala.xml.Text(":") ++ <br/> ++ <div class="cmt"><pre>{"(" + Template.lowerFirstLetter(tpl.name) + ": " + conv.targetType.name + ")." + mbr.name + params }</pre></div> } val shadowingWarning: NodeSeq = if (mbr.isShadowedImplicit) - xml.Text("This implicitly inherited member is shadowed by one or more members in this " + + scala.xml.Text("This implicitly inherited member is shadowed by one or more members in this " + "class.") ++ shadowingSuggestion else if (mbr.isAmbiguousImplicit) - xml.Text("This implicitly inherited member is ambiguous. One or more implicitly " + + scala.xml.Text("This implicitly inherited member is ambiguous. One or more implicitly " + "inherited members have similar signatures, so calling this member may produce an ambiguous " + "implicit conversion compiler error.") ++ shadowingSuggestion else NodeSeq.Empty @@ -471,7 +471,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp if (fvs.isEmpty || isReduced) NodeSeq.Empty else { <dt>Attributes</dt> - <dd>{ fvs map { fv => { inlineToHtml(fv.text) ++ xml.Text(" ") } } }</dd> + <dd>{ fvs map { fv => { inlineToHtml(fv.text) ++ scala.xml.Text(" ") } } }</dd> } } @@ -480,7 +480,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp if ((inDefTpls.tail.isEmpty && (inDefTpls.head == inTpl)) || isReduced) NodeSeq.Empty else { <dt>Definition Classes</dt> - <dd>{ templatesToHtml(inDefTpls, xml.Text(" → ")) }</dd> + <dd>{ templatesToHtml(inDefTpls, scala.xml.Text(" → ")) }</dd> } } @@ -628,7 +628,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp <div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent">{ - typesToHtml(dtpl.linearizationTypes, hasLinks = true, sep = xml.Text(", ")) + typesToHtml(dtpl.linearizationTypes, hasLinks = true, sep = scala.xml.Text(", ")) }</div> </div> case _ => NodeSeq.Empty @@ -639,7 +639,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp <div class="toggleContainer block"> <span class="toggle">Known Subclasses</span> <div class="subClasses hiddenContent">{ - templatesToHtml(dtpl.allSubClasses.sortBy(_.name), xml.Text(", ")) + templatesToHtml(dtpl.allSubClasses.sortBy(_.name), scala.xml.Text(", ")) }</div> </div> case _ => NodeSeq.Empty @@ -663,7 +663,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp def boundsToHtml(hi: Option[TypeEntity], lo: Option[TypeEntity], hasLinks: Boolean): NodeSeq = { def bound0(bnd: Option[TypeEntity], pre: String): NodeSeq = bnd match { case None => NodeSeq.Empty - case Some(tpe) => xml.Text(pre) ++ typeToHtml(tpe, hasLinks) + case Some(tpe) => scala.xml.Text(pre) ++ typeToHtml(tpe, hasLinks) } bound0(lo, " >: ") ++ bound0(hi, " <: ") } @@ -694,7 +694,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp def inside(hasLinks: Boolean, nameLink: String = ""): NodeSeq = <xml:group> <span class="modifier_kind"> - <span class="modifier">{ mbr.flags.map(flag => inlineToHtml(flag.text) ++ xml.Text(" ")) }</span> + <span class="modifier">{ mbr.flags.map(flag => inlineToHtml(flag.text) ++ scala.xml.Text(" ")) }</span> <span class="kind">{ kindToString(mbr) }</span> </span> <span class="symbol"> @@ -872,7 +872,7 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp def argumentsToHtml0(argss: List[ValueArgument]): NodeSeq = argss match { case Nil => NodeSeq.Empty case arg :: Nil => argumentToHtml(arg) - case arg :: args => argumentToHtml(arg) ++ xml.Text(", ") ++ argumentsToHtml0(args) + case arg :: args => argumentToHtml(arg) ++ scala.xml.Text(", ") ++ argumentsToHtml0(args) } <span class="args">({ argumentsToHtml0(argss) })</span> } @@ -922,29 +922,29 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp private def constraintToHtml(constraint: Constraint): NodeSeq = constraint match { case ktcc: KnownTypeClassConstraint => - xml.Text(ktcc.typeExplanation(ktcc.typeParamName) + " (" + ktcc.typeParamName + ": ") ++ - templateToHtml(ktcc.typeClassEntity) ++ xml.Text(")") + scala.xml.Text(ktcc.typeExplanation(ktcc.typeParamName) + " (" + ktcc.typeParamName + ": ") ++ + templateToHtml(ktcc.typeClassEntity) ++ scala.xml.Text(")") case tcc: TypeClassConstraint => - xml.Text(tcc.typeParamName + " is ") ++ + scala.xml.Text(tcc.typeParamName + " is ") ++ <a href="http://stackoverflow.com/questions/2982276/what-is-a-context-bound-in-scala" target="_blank"> - context-bounded</a> ++ xml.Text(" by " + tcc.typeClassEntity.qualifiedName + " (" + tcc.typeParamName + ": ") ++ - templateToHtml(tcc.typeClassEntity) ++ xml.Text(")") + context-bounded</a> ++ scala.xml.Text(" by " + tcc.typeClassEntity.qualifiedName + " (" + tcc.typeParamName + ": ") ++ + templateToHtml(tcc.typeClassEntity) ++ scala.xml.Text(")") case impl: ImplicitInScopeConstraint => - xml.Text("an implicit value of type ") ++ typeToHtml(impl.implicitType, true) ++ xml.Text(" is in scope") + scala.xml.Text("an implicit value of type ") ++ typeToHtml(impl.implicitType, true) ++ scala.xml.Text(" is in scope") case eq: EqualTypeParamConstraint => - xml.Text(eq.typeParamName + " is " + eq.rhs.name + " (" + eq.typeParamName + " =:= ") ++ - typeToHtml(eq.rhs, true) ++ xml.Text(")") + scala.xml.Text(eq.typeParamName + " is " + eq.rhs.name + " (" + eq.typeParamName + " =:= ") ++ + typeToHtml(eq.rhs, true) ++ scala.xml.Text(")") case bt: BoundedTypeParamConstraint => - xml.Text(bt.typeParamName + " is a superclass of " + bt.lowerBound.name + " and a subclass of " + + scala.xml.Text(bt.typeParamName + " is a superclass of " + bt.lowerBound.name + " and a subclass of " + bt.upperBound.name + " (" + bt.typeParamName + " >: ") ++ - typeToHtml(bt.lowerBound, true) ++ xml.Text(" <: ") ++ - typeToHtml(bt.upperBound, true) ++ xml.Text(")") + typeToHtml(bt.lowerBound, true) ++ scala.xml.Text(" <: ") ++ + typeToHtml(bt.upperBound, true) ++ scala.xml.Text(")") case lb: LowerBoundedTypeParamConstraint => - xml.Text(lb.typeParamName + " is a superclass of " + lb.lowerBound.name + " (" + lb.typeParamName + " >: ") ++ - typeToHtml(lb.lowerBound, true) ++ xml.Text(")") + scala.xml.Text(lb.typeParamName + " is a superclass of " + lb.lowerBound.name + " (" + lb.typeParamName + " >: ") ++ + typeToHtml(lb.lowerBound, true) ++ scala.xml.Text(")") case ub: UpperBoundedTypeParamConstraint => - xml.Text(ub.typeParamName + " is a subclass of " + ub.upperBound.name + " (" + ub.typeParamName + " <: ") ++ - typeToHtml(ub.upperBound, true) ++ xml.Text(")") + scala.xml.Text(ub.typeParamName + " is a subclass of " + ub.upperBound.name + " (" + ub.typeParamName + " <: ") ++ + typeToHtml(ub.upperBound, true) ++ scala.xml.Text(")") } def makeDiagramHtml(tpl: DocTemplateEntity, diagram: Option[Diagram], description: String, id: String) = { diff --git a/src/compiler/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala b/src/compiler/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala index c46c33c1ee..304c534bdc 100644 --- a/src/compiler/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala +++ b/src/compiler/scala/tools/nsc/doc/html/page/diagram/DotDiagramGenerator.scala @@ -426,7 +426,7 @@ class DotDiagramGenerator(settings: doc.Settings) extends DiagramGenerator { else if (klass.contains("object")) "object" else "" - def getPosition(g: xml.Node, axis: String, offset: Double): Option[Double] = { + def getPosition(g: scala.xml.Node, axis: String, offset: Double): Option[Double] = { val node = g \ "a" \ "text" \ ("@" + axis) if (node.isEmpty) None @@ -508,4 +508,4 @@ class DotDiagramGenerator(settings: doc.Settings) extends DiagramGenerator { private val graphAttributesStr = graphAttributes.map{ case (key, value) => key + "=\"" + value + "\";\n" }.mkString private val nodeAttributesStr = flatten(nodeAttributes) private val edgeAttributesStr = flatten(edgeAttributes) -}
\ No newline at end of file +} diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala index 2b9638076c..0468d2c0f1 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala @@ -156,7 +156,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { if (!sym.isTrait && (sym hasFlag Flags.ABSTRACT)) fgs += Paragraph(Text("abstract")) /* Resetting the DEFERRED flag is a little trick here for refined types: (example from scala.collections) * {{{ - * implicit def traversable2ops[T](t: collection.GenTraversableOnce[T]) = new TraversableOps[T] { + * implicit def traversable2ops[T](t: scala.collection.GenTraversableOnce[T]) = new TraversableOps[T] { * def isParallel = ... * }}} * the type the method returns is TraversableOps, which has all-abstract symbols. But in reality, it couldn't have diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala index 59cdf05957..47eea52095 100644 --- a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala @@ -13,7 +13,7 @@ import scala.collection._ import scala.util.matching.Regex import scala.annotation.switch import scala.reflect.internal.util.{NoPosition, Position} -import language.postfixOps +import scala.language.postfixOps /** The comment parser transforms raw comment strings into `Comment` objects. * Call `parse` to run the parser. Note that the parser is stateless and diff --git a/src/compiler/scala/tools/nsc/doc/model/diagram/DiagramFactory.scala b/src/compiler/scala/tools/nsc/doc/model/diagram/DiagramFactory.scala index 2645d8fd14..fa698afaa6 100644 --- a/src/compiler/scala/tools/nsc/doc/model/diagram/DiagramFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/diagram/DiagramFactory.scala @@ -4,7 +4,7 @@ package diagram import model._ import comment.CommentFactory -import collection.mutable +import scala.collection.mutable // statistics import html.page.diagram.DiagramStats diff --git a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala index e31c5eda31..7067daec26 100644 --- a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala +++ b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala @@ -13,7 +13,7 @@ import scala.reflect.internal.util.FakePos import dependencies._ import io.AbstractFile -import language.implicitConversions +import scala.language.implicitConversions trait BuildManager { diff --git a/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala b/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala index 4a60211254..a906d1454c 100644 --- a/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala +++ b/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala @@ -5,7 +5,7 @@ package scala.tools.nsc package interactive -import collection.mutable.ArrayBuffer +import scala.collection.mutable.ArrayBuffer import scala.reflect.internal.util.Position trait ContextTrees { self: Global => diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala index cd0cc93ba8..ec3ed110fd 100644 --- a/src/compiler/scala/tools/nsc/interactive/Global.scala +++ b/src/compiler/scala/tools/nsc/interactive/Global.scala @@ -20,7 +20,7 @@ import scala.tools.nsc.io.Pickler._ import scala.tools.nsc.typechecker.DivergentImplicit import scala.annotation.tailrec import symtab.Flags.{ACCESSOR, PARAMACCESSOR} -import language.implicitConversions +import scala.language.implicitConversions /** The main class of the presentation compiler in an interactive environment such as an IDE */ diff --git a/src/compiler/scala/tools/nsc/interactive/InteractiveReporter.scala b/src/compiler/scala/tools/nsc/interactive/InteractiveReporter.scala index f57786578a..104a69897d 100644 --- a/src/compiler/scala/tools/nsc/interactive/InteractiveReporter.scala +++ b/src/compiler/scala/tools/nsc/interactive/InteractiveReporter.scala @@ -5,7 +5,7 @@ package scala.tools.nsc package interactive -import collection.mutable.ArrayBuffer +import scala.collection.mutable.ArrayBuffer import scala.reflect.internal.util.Position import reporters.Reporter diff --git a/src/compiler/scala/tools/nsc/interactive/Picklers.scala b/src/compiler/scala/tools/nsc/interactive/Picklers.scala index f4ec03bb47..8ed7a67058 100644 --- a/src/compiler/scala/tools/nsc/interactive/Picklers.scala +++ b/src/compiler/scala/tools/nsc/interactive/Picklers.scala @@ -13,7 +13,7 @@ import util.EmptyAction import scala.reflect.internal.util.{Position, RangePosition, NoPosition, OffsetPosition, TransparentPosition} import io.{Pickler, CondPickler} import io.Pickler._ -import collection.mutable +import scala.collection.mutable import mutable.ListBuffer trait Picklers { self: Global => diff --git a/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala b/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala index 9afaa10449..f3d454ad3e 100644 --- a/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala +++ b/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala @@ -220,7 +220,7 @@ class RefinedBuildManager(val settings: Settings) extends Changes with BuildMana } /** Return the set of source files that are invalidated by the given changes. */ - def invalidated(files: Set[AbstractFile], changesOf: collection.Map[Symbol, List[Change]], + def invalidated(files: Set[AbstractFile], changesOf: scala.collection.Map[Symbol, List[Change]], processed: Set[AbstractFile] = Set.empty): Set[AbstractFile] = { val buf = new mutable.HashSet[AbstractFile] diff --git a/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala b/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala index 0f52258b7e..ca5bdd632f 100644 --- a/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala +++ b/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package interactive import scala.reflect.internal.util.{SourceFile, Position, NoPosition} -import collection.mutable.ArrayBuffer +import scala.collection.mutable.ArrayBuffer trait RichCompilationUnits { self: Global => diff --git a/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala b/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala index 0080cfd753..dfbbb6ff88 100644 --- a/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala +++ b/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala @@ -2,8 +2,8 @@ package scala.tools.nsc package interactive import scala.reflect.internal.util.{SourceFile, BatchSourceFile, RangePosition} -import collection.mutable.ArrayBuffer -import reflect.internal.Chars.{isLineBreakChar, isWhitespace} +import scala.collection.mutable.ArrayBuffer +import scala.reflect.internal.Chars.{isLineBreakChar, isWhitespace} import ast.parser.Tokens._ trait ScratchPadMaker { self: Global => diff --git a/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala b/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala index deeb398d39..cb46c0fdca 100644 --- a/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala +++ b/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala @@ -15,7 +15,7 @@ import scala.annotation.migration import scala.reflect.internal.util.Position import scala.reflect.internal.util.SourceFile -import collection.mutable.ListBuffer +import scala.collection.mutable.ListBuffer /** A base class for writing interactive compiler tests. * @@ -127,4 +127,4 @@ abstract class InteractiveTest // the presentation compiler sys.exit(0) } -}
\ No newline at end of file +} diff --git a/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala b/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala index 5270b1971a..aadffe2da5 100644 --- a/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala +++ b/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala @@ -9,7 +9,7 @@ package tests import scala.reflect.internal.util._ import reporters._ import io.AbstractFile -import collection.mutable.ArrayBuffer +import scala.collection.mutable.ArrayBuffer class Tester(ntests: Int, inputs: Array[SourceFile], settings: Settings) { @@ -168,7 +168,7 @@ class Tester(ntests: Int, inputs: Array[SourceFile], settings: Settings) { } case class ErrorTrace( - sfidx: Int, changes: Seq[Change], infos: collection.Set[reporter.Info], content: Array[Char]) { + sfidx: Int, changes: Seq[Change], infos: scala.collection.Set[reporter.Info], content: Array[Char]) { override def toString = "Sourcefile: "+inputs(sfidx)+ "\nChanges:\n "+changes.mkString("\n ")+ diff --git a/src/compiler/scala/tools/nsc/interactive/tests/core/TestMarker.scala b/src/compiler/scala/tools/nsc/interactive/tests/core/TestMarker.scala index b5ea6ab7ce..ba1722382b 100644 --- a/src/compiler/scala/tools/nsc/interactive/tests/core/TestMarker.scala +++ b/src/compiler/scala/tools/nsc/interactive/tests/core/TestMarker.scala @@ -3,7 +3,7 @@ package scala.tools.nsc.interactive.tests.core case class DuplicateTestMarker(msg: String) extends Exception(msg) object TestMarker { - import collection.mutable.Map + import scala.collection.mutable.Map private val markers: Map[String, TestMarker] = Map.empty private def checkForDuplicate(marker: TestMarker) { @@ -24,4 +24,4 @@ object CompletionMarker extends TestMarker("/*!*/") object TypeMarker extends TestMarker("/*?*/") -object HyperlinkMarker extends TestMarker("/*#*/")
\ No newline at end of file +object HyperlinkMarker extends TestMarker("/*#*/") diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala index abf326e746..5475410a84 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala @@ -77,7 +77,7 @@ object CompletionAware { /** Convenience factories. */ def apply(terms: () => List[String]): CompletionAware = apply(terms, _ => None) - def apply(map: collection.Map[String, CompletionAware]): CompletionAware = + def apply(map: scala.collection.Map[String, CompletionAware]): CompletionAware = apply(() => map.keys.toList, map.get _) } diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala index 61c390b07f..1d6ec77ef2 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala @@ -23,7 +23,7 @@ import scala.reflect.NameTransformer._ import util.ScalaClassLoader import ScalaClassLoader._ import scala.tools.util._ -import language.{implicitConversions, existentials} +import scala.language.{implicitConversions, existentials} import scala.reflect.{ClassTag, classTag} import scala.tools.reflect.StdRuntimeTags._ @@ -839,7 +839,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) addThunk({ import scala.tools.nsc.io._ import Properties.userHome - import compat.Platform.EOL + import scala.compat.Platform.EOL val autorun = replProps.replAutorunCode.option flatMap (f => io.File(f).safeSlurp()) if (autorun.isDefined) intp.quietRun(autorun.get) }) diff --git a/src/compiler/scala/tools/nsc/interpreter/IMain.scala b/src/compiler/scala/tools/nsc/interpreter/IMain.scala index c340b72ec3..790a1ac8d4 100644 --- a/src/compiler/scala/tools/nsc/interpreter/IMain.scala +++ b/src/compiler/scala/tools/nsc/interpreter/IMain.scala @@ -25,7 +25,7 @@ import scala.util.control.Exception.{ ultimately } import IMain._ import java.util.concurrent.Future import typechecker.Analyzer -import language.implicitConversions +import scala.language.implicitConversions import scala.reflect.runtime.{ universe => ru } import scala.reflect.{ ClassTag, classTag } import scala.tools.reflect.StdRuntimeTags._ @@ -387,8 +387,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends newSym <- req.definedSymbols get name oldSym <- oldReq.definedSymbols get name.companionName } { - replwarn("warning: previously defined %s is not a companion to %s.".format( - stripString("" + oldSym), stripString("" + newSym))) + exitingTyper(replwarn(s"warning: previously defined $oldSym is not a companion to $newSym.")) replwarn("Companions must be defined together; you may wish to use :paste mode for this.") } diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala index cf5871ea6f..b390ad5417 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala @@ -9,7 +9,7 @@ package interpreter import scala.tools.jline._ import scala.tools.jline.console.completer._ import Completion._ -import collection.mutable.ListBuffer +import scala.collection.mutable.ListBuffer // REPL completor - queries supplied interpreter for valid // completions based on current contents of buffer. diff --git a/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala b/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala index 2dc394a081..f0e643d572 100644 --- a/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala +++ b/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala @@ -6,12 +6,12 @@ package scala.tools.nsc package interpreter -import collection.{ mutable, immutable } +import scala.collection.{ mutable, immutable } import mutable.ListBuffer -import language.implicitConversions +import scala.language.implicitConversions class ProcessResult(val line: String) { - import sys.process._ + import scala.sys.process._ private val buffer = new ListBuffer[String] val builder = Process(line) diff --git a/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala b/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala index 5cc6c8e6d0..df96a27291 100644 --- a/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala +++ b/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala @@ -10,7 +10,7 @@ import scala.collection.{ mutable, immutable } import scala.PartialFunction.cond import scala.reflect.internal.Chars import scala.reflect.internal.Flags._ -import language.implicitConversions +import scala.language.implicitConversions trait MemberHandlers { val intp: IMain diff --git a/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala b/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala index a2b42aeefc..3203e2ba49 100644 --- a/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala +++ b/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala @@ -7,7 +7,7 @@ package scala.tools.nsc package interpreter import NamedParam._ -import language.implicitConversions +import scala.language.implicitConversions import scala.reflect.runtime.{universe => ru} import scala.reflect.{ClassTag, classTag} diff --git a/src/compiler/scala/tools/nsc/interpreter/Phased.scala b/src/compiler/scala/tools/nsc/interpreter/Phased.scala index 98ac86587b..83d7012bb1 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Phased.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Phased.scala @@ -7,7 +7,7 @@ package scala.tools.nsc package interpreter import scala.collection.{ mutable, immutable } -import language.implicitConversions +import scala.language.implicitConversions /** Mix this into an object and use it as a phasing * swiss army knife. diff --git a/src/compiler/scala/tools/nsc/interpreter/Power.scala b/src/compiler/scala/tools/nsc/interpreter/Power.scala index 1852b2d94b..4aef54bce5 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Power.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Power.scala @@ -13,7 +13,7 @@ import session.{ History } import scala.io.Codec import java.net.{ URL, MalformedURLException } import io.{ Path } -import language.implicitConversions +import scala.language.implicitConversions import scala.reflect.runtime.{universe => ru} import scala.reflect.{ClassTag, classTag} diff --git a/src/compiler/scala/tools/nsc/interpreter/ReplVals.scala b/src/compiler/scala/tools/nsc/interpreter/ReplVals.scala index 5b8e4c3d92..f27c4a8123 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplVals.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplVals.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package interpreter -import language.implicitConversions +import scala.language.implicitConversions import scala.reflect.base.{Universe => BaseUniverse} import scala.reflect.runtime.{universe => ru} @@ -65,7 +65,7 @@ object ReplVals { * I have this forwarder which widens the type and then cast the result back * to the dependent type. */ - def compilerTypeFromTag(t: BaseUniverse # AbsTypeTag[_]): Global#Type = + def compilerTypeFromTag(t: BaseUniverse # WeakTypeTag[_]): Global#Type = definitions.compilerTypeFromTag(t) class AppliedTypeFromTags(sym: Symbol) { diff --git a/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala b/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala index 04ccb87389..fe1c4c0ca8 100644 --- a/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala @@ -14,7 +14,7 @@ import scala.reflect.runtime.{universe => ru} import scala.reflect.{ClassTag, classTag} import typechecker.DestructureTypes import scala.reflect.internal.util.StringOps.ojoin -import language.implicitConversions +import scala.language.implicitConversions /** A more principled system for turning types into strings. */ diff --git a/src/compiler/scala/tools/nsc/interpreter/package.scala b/src/compiler/scala/tools/nsc/interpreter/package.scala index 98129aded8..89006be8e2 100644 --- a/src/compiler/scala/tools/nsc/interpreter/package.scala +++ b/src/compiler/scala/tools/nsc/interpreter/package.scala @@ -5,7 +5,7 @@ package scala.tools.nsc -import language.implicitConversions +import scala.language.implicitConversions /** The main REPL related classes and values are as follows. * In addition to standard compiler classes Global and Settings, there are: @@ -38,7 +38,7 @@ package object interpreter extends ReplConfig with ReplStrings { implicit def postfixOps = language.postfixOps // make all postfix ops in this package compile without warning private[interpreter] implicit def javaCharSeqCollectionToScala(xs: JCollection[_ <: CharSequence]): List[String] = { - import collection.JavaConverters._ + import scala.collection.JavaConverters._ xs.asScala.toList map ("" + _) } diff --git a/src/compiler/scala/tools/nsc/interpreter/session/package.scala b/src/compiler/scala/tools/nsc/interpreter/session/package.scala index c1cd599941..58232e6b9a 100644 --- a/src/compiler/scala/tools/nsc/interpreter/session/package.scala +++ b/src/compiler/scala/tools/nsc/interpreter/session/package.scala @@ -5,7 +5,7 @@ package scala.tools.nsc package interpreter -import language.implicitConversions +import scala.language.implicitConversions /** Files having to do with the state of a repl session: * lines of text entered, types and terms defined, etc. diff --git a/src/compiler/scala/tools/nsc/io/Jar.scala b/src/compiler/scala/tools/nsc/io/Jar.scala index 12ba3e4bd7..f66f3daa32 100644 --- a/src/compiler/scala/tools/nsc/io/Jar.scala +++ b/src/compiler/scala/tools/nsc/io/Jar.scala @@ -8,10 +8,10 @@ package io import java.io.{ InputStream, OutputStream, IOException, FileNotFoundException, FileInputStream, DataOutputStream } import java.util.jar._ -import collection.JavaConverters._ +import scala.collection.JavaConverters._ import Attributes.Name import util.ClassPath -import language.implicitConversions +import scala.language.implicitConversions // Attributes.Name instances: // diff --git a/src/compiler/scala/tools/nsc/io/Pickler.scala b/src/compiler/scala/tools/nsc/io/Pickler.scala index 48361cd157..b03a921e87 100644 --- a/src/compiler/scala/tools/nsc/io/Pickler.scala +++ b/src/compiler/scala/tools/nsc/io/Pickler.scala @@ -1,10 +1,10 @@ package scala.tools.nsc.io -import annotation.unchecked +import scala.annotation.unchecked import Lexer._ import java.io.Writer -import language.implicitConversions -import reflect.ClassTag +import scala.language.implicitConversions +import scala.reflect.ClassTag /** An abstract class for writing and reading Scala objects to and * from a legible representation. The presesentation follows the following grammar: diff --git a/src/compiler/scala/tools/nsc/io/package.scala b/src/compiler/scala/tools/nsc/io/package.scala index 3c4f004198..6385706830 100644 --- a/src/compiler/scala/tools/nsc/io/package.scala +++ b/src/compiler/scala/tools/nsc/io/package.scala @@ -8,7 +8,7 @@ package scala.tools.nsc import java.util.concurrent.{ Future, Callable } import java.util.{ Timer, TimerTask } import java.util.jar.{ Attributes } -import language.implicitConversions +import scala.language.implicitConversions package object io { implicit def postfixOps = language.postfixOps // make all postfix ops in this package compile without warning diff --git a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala index c5da8822d5..a30ae1cb36 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala @@ -12,7 +12,7 @@ import scala.reflect.internal.util.OffsetPosition import scala.collection.mutable.ListBuffer import symtab.Flags import JavaTokens._ -import language.implicitConversions +import scala.language.implicitConversions trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { val global : Global diff --git a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala index 0367119547..7aeae485d0 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala @@ -11,7 +11,7 @@ import scala.reflect.internal.util._ import scala.reflect.internal.Chars._ import JavaTokens._ import scala.annotation.switch -import language.implicitConversions +import scala.language.implicitConversions // Todo merge these better with Scanners trait JavaScanners extends ast.parser.ScannersCommon { diff --git a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala index 6d8c80d1d0..be8f1e3d9e 100644 --- a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala +++ b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala @@ -9,8 +9,8 @@ package matching import transform.ExplicitOuter import ast.{ Printers, Trees } import java.io.{ StringWriter, PrintWriter } -import annotation.elidable -import language.postfixOps +import scala.annotation.elidable +import scala.language.postfixOps /** Ancillary bits of ParallelMatching which are better off * out of the way. diff --git a/src/compiler/scala/tools/nsc/matching/Matrix.scala b/src/compiler/scala/tools/nsc/matching/Matrix.scala index 1cf4bccb40..93e936fe1f 100644 --- a/src/compiler/scala/tools/nsc/matching/Matrix.scala +++ b/src/compiler/scala/tools/nsc/matching/Matrix.scala @@ -9,7 +9,7 @@ package matching import transform.ExplicitOuter import symtab.Flags import scala.collection.mutable -import language.implicitConversions +import scala.language.implicitConversions trait Matrix extends MatrixAdditions { self: ExplicitOuter with ParallelMatching => diff --git a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala index 71deb2d356..1d21e4952f 100644 --- a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala +++ b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala @@ -13,8 +13,8 @@ import scala.reflect.internal.util.Position import transform.ExplicitOuter import symtab.Flags import mutable.ListBuffer -import annotation.elidable -import language.postfixOps +import scala.annotation.elidable +import scala.language.postfixOps trait ParallelMatching extends ast.TreeDSL with MatchSupport diff --git a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala index 8e043613b8..ee96f15f40 100644 --- a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala +++ b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala @@ -8,7 +8,7 @@ package matching import transform.ExplicitOuter import PartialFunction._ -import language.postfixOps +import scala.language.postfixOps trait PatternBindings extends ast.TreeDSL { diff --git a/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala b/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala index 67ff916b11..f7ad39bd95 100644 --- a/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala +++ b/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala @@ -5,7 +5,7 @@ import java.io.{FileInputStream, InputStreamReader, IOException} import scala.runtime.ScalaRunTime.stringOf import java.lang.reflect.InvocationTargetException import scala.reflect.runtime.ReflectionUtils._ -import collection.mutable.ArrayBuffer +import scala.collection.mutable.ArrayBuffer class Mixer { diff --git a/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala b/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala index 1c4fad5511..5eeab53fca 100644 --- a/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala +++ b/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala @@ -3,8 +3,7 @@ package scratchpad import java.io.Writer import scala.reflect.internal.util.SourceFile - -import reflect.internal.Chars._ +import scala.reflect.internal.Chars._ object SourceInserter { def stripRight(cs: Array[Char]): Array[Char] = { diff --git a/src/compiler/scala/tools/nsc/settings/AbsSettings.scala b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala index 120ada965a..78b56a8596 100644 --- a/src/compiler/scala/tools/nsc/settings/AbsSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala @@ -15,7 +15,7 @@ trait AbsSettings extends scala.reflect.internal.settings.AbsSettings { type Setting <: AbsSetting // Fix to the concrete Setting type type ResultOfTryToSet // List[String] in mutable, (Settings, List[String]) in immutable def errorFn: String => Unit - protected def allSettings: collection.Set[Setting] + protected def allSettings: scala.collection.Set[Setting] // settings minus internal usage settings def visibleSettings = allSettings filterNot (_.isInternalOnly) diff --git a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala index 116eed0f31..2ff81ae603 100644 --- a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala @@ -536,7 +536,7 @@ class MutableSettings(val errorFn: String => Unit) } override def tryToSetColon(args: List[String]) = tryToSet(args) override def tryToSetFromPropertyValue(s: String) = tryToSet(s.trim.split(',').toList) - def unparse: List[String] = name :: value + def unparse: List[String] = value map (name + ":" + _) withHelpSyntax(name + ":<" + arg + ">") } diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index 19392ec23a..3ff7af791b 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala @@ -8,10 +8,10 @@ package scala.tools package nsc package settings -import annotation.elidable +import scala.annotation.elidable import scala.tools.util.PathResolver.Defaults import scala.collection.mutable -import language.{implicitConversions, existentials} +import scala.language.{implicitConversions, existentials} trait ScalaSettings extends AbsScalaSettings with StandardScalaSettings diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala b/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala index 8e77f8b6f4..f7c3a55954 100644 --- a/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala +++ b/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala @@ -10,9 +10,9 @@ import java.io.IOException import scala.compat.Platform.currentTime import scala.tools.nsc.util.{ ClassPath } import classfile.ClassfileParser -import reflect.internal.Flags._ -import reflect.internal.MissingRequirementError -import reflect.internal.util.Statistics +import scala.reflect.internal.Flags._ +import scala.reflect.internal.MissingRequirementError +import scala.reflect.internal.util.Statistics import scala.tools.nsc.io.{ AbstractFile, MsilFile } /** This class ... @@ -300,6 +300,6 @@ abstract class SymbolLoaders { } object SymbolLoadersStats { - import reflect.internal.TypesStats.typerNanos + import scala.reflect.internal.TypesStats.typerNanos val classReadNanos = Statistics.newSubTimer ("time classfilereading", typerNanos) } diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala b/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala index c6bd236e8a..7e2741f6bc 100644 --- a/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala +++ b/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala @@ -6,4 +6,4 @@ package scala.tools.nsc package symtab -abstract class SymbolTable extends reflect.internal.SymbolTable
\ No newline at end of file +abstract class SymbolTable extends scala.reflect.internal.SymbolTable diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala b/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala index c596eb014a..d9d25bf95a 100644 --- a/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala +++ b/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala @@ -7,8 +7,8 @@ package scala.tools.nsc package symtab import scala.collection.{ mutable, immutable } -import language.implicitConversions -import language.postfixOps +import scala.language.implicitConversions +import scala.language.postfixOps /** Printing the symbol graph (for those symbols attached to an AST node) * after each phase. diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index b358785714..3c1377e081 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -1164,7 +1164,7 @@ abstract class ClassfileParser { originalName + " in " + outerName + "(" + externalName +")" } - object innerClasses extends collection.mutable.HashMap[Name, InnerClassEntry] { + object innerClasses extends scala.collection.mutable.HashMap[Name, InnerClassEntry] { /** Return the Symbol of the top level class enclosing `name`, * or 'name's symbol if no entry found for `name`. */ diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala index e4338a6421..c02503902e 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala @@ -37,7 +37,7 @@ abstract class ICodeReader extends ClassfileParser { cls.info // ensure accurate type information isScalaModule = cls.isModule && !cls.isJavaDefined - log("Reading class: " + cls + " isScalaModule?: " + isScalaModule) + log("ICodeReader reading " + cls) val name = cls.javaClassName classPath.findSourceFile(name) match { @@ -99,11 +99,9 @@ abstract class ICodeReader extends ClassfileParser { if (sym == NoSymbol) sym = owner.info.findMember(newTermName(name + nme.LOCAL_SUFFIX_STRING), 0, 0, false).suchThat(_.tpe =:= tpe) if (sym == NoSymbol) { - log("Could not find symbol for " + name + ": " + tpe) - log(owner.info.member(name).tpe + " : " + tpe) sym = if (field) owner.newValue(name, owner.pos, toScalaFieldFlags(jflags)) else dummySym sym setInfoAndEnter tpe - log("added " + sym + ": " + sym.tpe) + log(s"ICodeReader could not locate ${name.decode} in $owner. Created ${sym.defString}.") } (jflags, sym) } @@ -172,10 +170,7 @@ abstract class ICodeReader extends ClassfileParser { } else if (nme.isModuleName(name)) { val strippedName = nme.stripModuleSuffix(name) - val sym = forceMangledName(newTermName(strippedName.decode), true) - - if (sym == NoSymbol) rootMirror.getModule(strippedName) - else sym + forceMangledName(newTermName(strippedName.decode), true) orElse rootMirror.getModule(strippedName) } else { forceMangledName(name, false) @@ -956,7 +951,7 @@ abstract class ICodeReader extends ClassfileParser { case None => checkValidIndex val l = freshLocal(idx, kind, false) - log("Added new local for idx " + idx + ": " + kind) + debuglog("Added new local for idx " + idx + ": " + kind) locals += (idx -> List((l, kind))) l } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala index 3c34cf1c80..b30969d451 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala @@ -512,7 +512,7 @@ abstract class Pickler extends SubComponent { private def writeName(name: Name) { ensureCapacity(name.length * 3) val utfBytes = Codec toUTF8 name.toString - compat.Platform.arraycopy(utfBytes, 0, bytes, writeIndex, utfBytes.length) + scala.compat.Platform.arraycopy(utfBytes, 0, bytes, writeIndex, utfBytes.length) writeIndex += utfBytes.length } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/package.scala b/src/compiler/scala/tools/nsc/symtab/classfile/package.scala index fe66c515de..1f9a823bb4 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/package.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/package.scala @@ -2,6 +2,6 @@ package scala.tools.nsc.symtab package object classfile { - val ClassfileConstants = reflect.internal.ClassfileConstants + val ClassfileConstants = scala.reflect.internal.ClassfileConstants } diff --git a/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala b/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala index 5e52415ab2..18b95ba191 100644 --- a/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala @@ -12,7 +12,7 @@ import ch.epfl.lamp.compiler.msil.{Type => MSILType, Attribute => MSILAttribute, import scala.collection.{ mutable, immutable } import scala.reflect.internal.pickling.UnPickler import ch.epfl.lamp.compiler.msil.Type.TMVarUsage -import language.implicitConversions +import scala.language.implicitConversions /** * @author Nikolay Mihaylov diff --git a/src/compiler/scala/tools/nsc/symtab/package.scala b/src/compiler/scala/tools/nsc/symtab/package.scala index 1cf0d2c2ae..0e6719f225 100644 --- a/src/compiler/scala/tools/nsc/symtab/package.scala +++ b/src/compiler/scala/tools/nsc/symtab/package.scala @@ -2,6 +2,6 @@ package scala.tools.nsc package object symtab { - val Flags = reflect.internal.Flags + val Flags = scala.reflect.internal.Flags } diff --git a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala index 182a9505f8..9073fa4504 100644 --- a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala +++ b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala @@ -9,7 +9,7 @@ package transform import symtab._ import Flags._ import scala.collection.{ mutable, immutable } -import collection.mutable.ListBuffer +import scala.collection.mutable.ListBuffer abstract class AddInterfaces extends InfoTransform { self: Erasure => import global._ // the global environment @@ -79,12 +79,11 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => // -optimise and not otherwise, but the classpath can use arbitrary // logic so the classpath must be queried. if (classPath.context.isValidName(implName + ".class")) { - log("unlinking impl class " + implSym) iface.owner.info.decls unlink implSym NoSymbol } else { - log("not unlinking existing " + implSym + " as the impl class is not visible on the classpath.") + log(s"not unlinking $iface's existing implClass ${implSym.name} because it is not on the classpath.") implSym } } @@ -113,9 +112,10 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => iface.info implClassMap.getOrElse(iface, enteringPhase(implClassPhase) { - log("Creating implClass for " + iface) - if (iface.implClass ne NoSymbol) - log("%s.implClass already exists: %s".format(iface, iface.implClass)) + if (iface.implClass eq NoSymbol) + debuglog(s"${iface.fullLocationString} has no implClass yet, creating it now.") + else + log(s"${iface.fullLocationString} impl class is ${iface.implClass.nameString}") newImplClass(iface) }) @@ -137,7 +137,7 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => * given the decls ifaceDecls of its interface. */ private def implDecls(implClass: Symbol, ifaceDecls: Scope): Scope = { - log("LazyImplClassType calculating decls for " + implClass) + debuglog("LazyImplClassType calculating decls for " + implClass) val decls = newScope if ((ifaceDecls lookup nme.MIXIN_CONSTRUCTOR) == NoSymbol) { @@ -152,16 +152,16 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => for (sym <- ifaceDecls) { if (isInterfaceMember(sym)) { if (needsImplMethod(sym)) { - log("Cloning " + sym + " for implementation method in " + implClass) val clone = sym.cloneSymbol(implClass).resetFlag(lateDEFERRED) if (currentRun.compiles(implClass)) implMethodMap(sym) = clone decls enter clone sym setFlag lateDEFERRED + if (!sym.isSpecialized) + log(s"Cloned ${sym.name} from ${sym.owner} into implClass ${implClass.fullName}") } - else log(sym + " needs no implementation method in " + implClass) } else { - log("Destructively modifying owner of %s from %s to %s".format(sym, sym.owner, implClass)) + log(s"Destructively modifying owner of $sym from ${sym.owner} to $implClass") sym.owner = implClass // note: OK to destructively modify the owner here, // because symbol will not be accessible from outside the sourcefile. @@ -174,7 +174,7 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => } override def complete(implSym: Symbol) { - log("LazyImplClassType completing " + implSym) + debuglog("LazyImplClassType completing " + implSym) /** If `tp` refers to a non-interface trait, return a * reference to its implementation class. Otherwise return `tp`. diff --git a/src/compiler/scala/tools/nsc/transform/CleanUp.scala b/src/compiler/scala/tools/nsc/transform/CleanUp.scala index 3630cb3dbe..d69c8eb831 100644 --- a/src/compiler/scala/tools/nsc/transform/CleanUp.scala +++ b/src/compiler/scala/tools/nsc/transform/CleanUp.scala @@ -9,7 +9,7 @@ package transform import symtab._ import Flags._ import scala.collection._ -import language.postfixOps +import scala.language.postfixOps abstract class CleanUp extends Transform with ast.TreeDSL { import global._ @@ -351,8 +351,8 @@ abstract class CleanUp extends Transform with ast.TreeDSL { /** Normal non-Array call */ def genDefaultCall = { // reflective method call machinery - val invokeName = MethodClass.tpe member nme.invoke_ // reflect.Method.invoke(...) - def cache = REF(reflectiveMethodCache(ad.symbol.name.toString, paramTypes)) // cache Symbol + val invokeName = MethodClass.tpe member nme.invoke_ // scala.reflect.Method.invoke(...) + def cache = REF(reflectiveMethodCache(ad.symbol.name.toString, paramTypes)) // cache Symbol def lookup = Apply(cache, List(qual1() GETCLASS)) // get Method object from cache def invokeArgs = ArrayValue(TypeTree(ObjectClass.tpe), params) // args for invocation def invocation = (lookup DOT invokeName)(qual1(), invokeArgs) // .invoke(qual1, ...) diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala index 6c8417eb56..2c989af003 100644 --- a/src/compiler/scala/tools/nsc/transform/Erasure.scala +++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala @@ -12,7 +12,7 @@ import symtab._ import Flags._ abstract class Erasure extends AddInterfaces - with reflect.internal.transform.Erasure + with scala.reflect.internal.transform.Erasure with typechecker.Analyzer with TypingTransformers with ast.TreeDSL @@ -326,7 +326,7 @@ abstract class Erasure extends AddInterfaces } // Methods on Any/Object which we rewrite here while we still know what // is a primitive and what arrived boxed. - private lazy val interceptedMethods = Set[Symbol](Any_##, Object_##, Any_getClass) ++ ( + private lazy val interceptedMethods = Set[Symbol](Any_##, Object_##, Any_getClass, AnyVal_getClass) ++ ( // Each value class has its own getClass for ultra-precise class object typing. ScalaValueClasses map (_.tpe member nme.getClass_) ) @@ -490,7 +490,7 @@ abstract class Erasure extends AddInterfaces @inline private def box(tree: Tree, target: => String): Tree = { val result = box1(tree) - log("boxing "+tree+":"+tree.tpe+" to "+target+" = "+result+":"+result.tpe) + log(s"boxing ${tree.summaryString}: ${tree.tpe} into $target: ${result.tpe}") result } @@ -525,7 +525,7 @@ abstract class Erasure extends AddInterfaces * fields (see TupleX). (ID) */ case Apply(boxFun, List(arg)) if isUnbox(tree.symbol) && safeToRemoveUnbox(arg.tpe.typeSymbol) => - log("boxing an unbox: " + tree + "/" + tree.symbol + " and replying with " + arg + " of type " + arg.tpe) + log(s"boxing an unbox: ${tree.symbol} -> ${arg.tpe}") arg case _ => (REF(boxMethod(x)) APPLY tree) setPos (tree.pos) setType ObjectClass.tpe @@ -537,7 +537,7 @@ abstract class Erasure extends AddInterfaces private def unbox(tree: Tree, pt: Type): Tree = { val result = unbox1(tree, pt) - log("unboxing "+tree+":"+tree.tpe+" to "+pt+" = "+result+":"+result.tpe) + log(s"unboxing ${tree.summaryString}: ${tree.tpe} with pt=$pt as type ${result.tpe}") result } @@ -614,7 +614,7 @@ abstract class Erasure extends AddInterfaces * @return the adapted tree */ private def adaptToType(tree: Tree, pt: Type): Tree = { - //if (settings.debug.value && pt != WildcardType) + if (settings.debug.value && pt != WildcardType) log("adapting " + tree + ":" + tree.tpe + " : " + tree.tpe.parents + " to " + pt)//debug if (tree.tpe <:< pt) tree @@ -1085,6 +1085,8 @@ abstract class Erasure extends AddInterfaces } else if (isPrimitiveValueClass(qual.tpe.typeSymbol)) { // Rewrite 5.getClass to ScalaRunTime.anyValClass(5) global.typer.typed(gen.mkRuntimeCall(nme.anyValClass, List(qual, typer.resolveClassTag(tree.pos, qual.tpe.widen)))) + } else if (fn.symbol == AnyVal_getClass) { + tree setSymbol Object_getClass } else { tree } @@ -1092,8 +1094,8 @@ abstract class Erasure extends AddInterfaces case New(tpt) if name == nme.CONSTRUCTOR && tpt.tpe.typeSymbol.isDerivedValueClass => // println("inject derived: "+arg+" "+tpt.tpe) val List(arg) = args - InjectDerivedValue(arg) addAttachment //@@@ setSymbol tpt.tpe.typeSymbol - new TypeRefAttachment(tree.tpe.asInstanceOf[TypeRef]) + val attachment = new TypeRefAttachment(tree.tpe.asInstanceOf[TypeRef]) + InjectDerivedValue(arg) addAttachment attachment case _ => preEraseNormalApply(tree) } diff --git a/src/compiler/scala/tools/nsc/transform/Flatten.scala b/src/compiler/scala/tools/nsc/transform/Flatten.scala index de2f96c378..e2913bea0d 100644 --- a/src/compiler/scala/tools/nsc/transform/Flatten.scala +++ b/src/compiler/scala/tools/nsc/transform/Flatten.scala @@ -22,12 +22,14 @@ abstract class Flatten extends InfoTransform { */ private def replaceSymbolInCurrentScope(sym: Symbol): Symbol = exitingFlatten { val scope = sym.owner.info.decls - val old = scope lookup sym.name - if (old ne NoSymbol) - scope unlink old - + val old = scope lookup sym.name andAlso scope.unlink scope enter sym - log("lifted " + sym.fullLocationString) + + if (old eq NoSymbol) + log(s"lifted ${sym.fullLocationString}") + else + log(s"lifted ${sym.fullLocationString} after unlinking existing $old from scope.") + old } @@ -35,9 +37,7 @@ abstract class Flatten extends InfoTransform { if (!sym.isLifted) { sym setFlag LIFTED debuglog("re-enter " + sym.fullLocationString) - val old = replaceSymbolInCurrentScope(sym) - if (old ne NoSymbol) - log("unlinked " + old.fullLocationString + " after lifting " + sym) + replaceSymbolInCurrentScope(sym) } } private def liftSymbol(sym: Symbol) { diff --git a/src/compiler/scala/tools/nsc/transform/Mixin.scala b/src/compiler/scala/tools/nsc/transform/Mixin.scala index e5d365f1d2..27ceb66af4 100644 --- a/src/compiler/scala/tools/nsc/transform/Mixin.scala +++ b/src/compiler/scala/tools/nsc/transform/Mixin.scala @@ -430,7 +430,7 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { * * Such fields will be nulled after the initializer has memoized the lazy value. */ - def singleUseFields(templ: Template): collection.Map[Symbol, List[Symbol]] = { + def singleUseFields(templ: Template): scala.collection.Map[Symbol, List[Symbol]] = { val usedIn = mutable.HashMap[Symbol, List[Symbol]]() withDefaultValue Nil object SingleUseTraverser extends Traverser { diff --git a/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala b/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala index 982b7a680e..1e360c09d3 100644 --- a/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala +++ b/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala @@ -9,7 +9,7 @@ package transform import scala.collection.mutable import symtab.Flags._ import util.HashSet -import annotation.tailrec +import scala.annotation.tailrec /** A class that yields a kind of iterator (`Cursor`), * which yields all pairs of overriding/overridden symbols diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala index 6a6d0cdea1..998cf17716 100644 --- a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala +++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala @@ -8,8 +8,8 @@ package transform import scala.tools.nsc.symtab.Flags import scala.collection.{ mutable, immutable } -import language.postfixOps -import language.existentials +import scala.language.postfixOps +import scala.language.existentials /** Specialize code on types. * @@ -461,7 +461,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { val sClassMap = anyrefSpecCache.getOrElseUpdate(sClass, mutable.Map[Symbol, Symbol]()) sClassMap.getOrElseUpdate(tparam, - tparam.cloneSymbol(sClass, tparam.flags, (tparam.name append tpnme.SPECIALIZED_SUFFIX).asInstanceOf[Name]) // [Eugene] why do we need this cast? + tparam.cloneSymbol(sClass, tparam.flags, tparam.name append tpnme.SPECIALIZED_SUFFIX) modifyInfo (info => TypeBounds(info.bounds.lo, AnyRefClass.tpe)) ).tpe } @@ -836,12 +836,17 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { specializingOn = specializingOn filterNot (unusedStvars contains) } for (env0 <- specializations(specializingOn) if needsSpecialization(env0, sym)) yield { + // !!! Can't this logic be structured so that the new symbol's name is + // known when the symbol is cloned? It is much cleaner not to be mutating + // names after the fact. And it adds about a billion lines of + // "Renaming value _1 in class Tuple2 to _1$mcZ$sp" to obscure the small + // number of other (important) actual symbol renamings. val tps = survivingParams(sym.info.typeParams, env0) - val specMember = sym.cloneSymbol(owner, (sym.flags | SPECIALIZED) & ~DEFERRED) + val specMember = sym.cloneSymbol(owner, (sym.flags | SPECIALIZED) & ~DEFERRED) // <-- this needs newName = ... val env = mapAnyRefsInSpecSym(env0, sym, specMember) val (keys, vals) = env.toList.unzip - specMember setName specializedName(sym, env) + specMember setName specializedName(sym, env) // <-- but the name is calculated based on the cloned symbol // debuglog("%s normalizes to %s%s".format(sym, specMember, // if (tps.isEmpty) "" else " with params " + tps.mkString(", "))) @@ -923,7 +928,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { val newFlags = (sym.flags | SPECIALIZED) & ~(DEFERRED | CASEACCESSOR) // this method properly duplicates the symbol's info val specname = specializedName(nameSymbol orElse sym, env) - ( sym.cloneSymbol(owner, newFlags, specname) + ( sym.cloneSymbol(owner, newFlags, newName = specname) modifyInfo (info => subst(env, info.asSeenFrom(owner.thisType, sym.owner))) ) } @@ -938,7 +943,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { * * this method will return List('apply$mcII$sp') */ - private def specialOverrides(clazz: Symbol) = logResultIf[List[Symbol]]("specialOverrides(" + clazz + ")", _.nonEmpty) { + private def specialOverrides(clazz: Symbol) = logResultIf[List[Symbol]]("specialized overrides in " + clazz, _.nonEmpty) { /** Return the overridden symbol in syms that needs a specialized overriding symbol, * together with its specialization environment. The overridden symbol may not be * the closest to 'overriding', in a given hierarchy. diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 816fedb0ed..d541b7be0a 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -8,7 +8,7 @@ package transform import symtab.Flags._ import scala.collection.{ mutable, immutable } -import language.postfixOps +import scala.language.postfixOps /*<export> */ /** - uncurry all symbol and tree types (@see UnCurryPhase) -- this includes normalizing all proper types. @@ -44,7 +44,7 @@ import language.postfixOps */ /*</export> */ abstract class UnCurry extends InfoTransform - with reflect.internal.transform.UnCurry + with scala.reflect.internal.transform.UnCurry with TypingTransformers with ast.TreeDSL { val global: Global // need to repeat here because otherwise last mixin defines global as // SymbolTable. If we had DOT this would not be an issue @@ -218,11 +218,6 @@ abstract class UnCurry extends InfoTransform /** Undo eta expansion for parameterless and nullary methods */ def deEta(fun: Function): Tree = fun match { - case Function(List(), Apply(expr, List())) if treeInfo.isExprSafeToInline(expr) => - if (expr hasSymbolWhich (_.isLazy)) - fun - else - expr case Function(List(), expr) if isByNameRef(expr) => noApply += expr expr @@ -490,11 +485,7 @@ abstract class UnCurry extends InfoTransform arg setType functionType(Nil, arg.tpe) } else { - log("byname | %s | %s | %s".format( - arg.pos.source.path + ":" + arg.pos.line, fun.fullName, - if (fun.isPrivate) "private" else "") - ) - + log(s"Argument '$arg' at line ${arg.pos.safeLine} is $formal from ${fun.fullName}") arg match { // don't add a thunk for by-name argument if argument already is an application of // a Function0. We can then remove the application and use the existing Function0. diff --git a/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala b/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala index 8218289f93..3526d932d3 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package typechecker -import reflect.internal.util.Statistics +import scala.reflect.internal.util.Statistics /** The main attribution phase. */ @@ -72,7 +72,7 @@ trait Analyzer extends AnyRef } object typerFactory extends SubComponent { - import reflect.internal.TypesStats.typerNanos + import scala.reflect.internal.TypesStats.typerNanos val global: Analyzer.this.global.type = Analyzer.this.global val phaseName = "typer" val runsAfter = List[String]() diff --git a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala index 6b69184d0a..f9f61b10a4 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala @@ -467,9 +467,6 @@ trait ContextErrors { def NamedAndDefaultArgumentsNotSupportedForMacros(tree: Tree, fun: Tree) = NormalTypeError(tree, "macros application do not support named and/or default arguments") - def WrongNumberOfArgsError(tree: Tree, fun: Tree) = - NormalTypeError(tree, "wrong number of arguments for "+ treeSymTypeMsg(fun)) - def TooManyArgsNamesDefaultsError(tree: Tree, fun: Tree) = NormalTypeError(tree, "too many arguments for "+treeSymTypeMsg(fun)) @@ -509,8 +506,8 @@ trait ContextErrors { def TooManyArgsPatternError(fun: Tree) = NormalTypeError(fun, "too many arguments for unapply pattern, maximum = "+definitions.MaxTupleArity) - def WrongNumberArgsPatternError(tree: Tree, fun: Tree) = - NormalTypeError(tree, "wrong number of arguments for "+treeSymTypeMsg(fun)) + def WrongNumberOfArgsError(tree: Tree, fun: Tree) = + NormalTypeError(tree, "wrong number of arguments for "+ treeSymTypeMsg(fun)) def ApplyWithoutArgsError(tree: Tree, fun: Tree) = NormalTypeError(tree, fun.tpe+" does not take parameters") @@ -738,7 +735,7 @@ trait ContextErrors { ) val forgotten = ( if (sym.isTerm) "splice when splicing this variable into a reifee" - else "c.AbsTypeTag annotation for this type parameter" + else "c.WeakTypeTag annotation for this type parameter" ) macroExpansionError(expandee, template(sym.name.nameKind).format(sym.name + " " + sym.origin, forgotten)) } @@ -1234,7 +1231,7 @@ trait ContextErrors { message + suffix } - private def abbreviateCoreAliases(s: String): String = List("AbsTypeTag", "Expr").foldLeft(s)((res, x) => res.replace("c.universe." + x, "c." + x)) + private def abbreviateCoreAliases(s: String): String = List("WeakTypeTag", "Expr").foldLeft(s)((res, x) => res.replace("c.universe." + x, "c." + x)) private def showMeth(pss: List[List[Symbol]], restpe: Type, abbreviate: Boolean) = { var argsPart = (pss map (ps => ps map (_.defString) mkString ("(", ", ", ")"))).mkString @@ -1313,7 +1310,7 @@ trait ContextErrors { // aXXX (e.g. aparams) => characteristics of the macro impl ("a" stands for "actual") // rXXX (e.g. rparams) => characteristics of a reference macro impl signature synthesized from the macro def ("r" stands for "reference") - def MacroImplNonTagImplicitParameters(params: List[Symbol]) = compatibilityError("macro implementations cannot have implicit parameters other than AbsTypeTag evidences") + def MacroImplNonTagImplicitParameters(params: List[Symbol]) = compatibilityError("macro implementations cannot have implicit parameters other than WeakTypeTag evidences") def MacroImplParamssMismatchError() = compatibilityError("number of parameter sections differ") diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala index 6a908c6c65..dbf769c79f 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala @@ -8,7 +8,7 @@ package typechecker import symtab.Flags._ import scala.collection.mutable.{LinkedHashSet, Set} -import annotation.tailrec +import scala.annotation.tailrec /** * @author Martin Odersky diff --git a/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala b/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala index 5802d36878..6a21639391 100644 --- a/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala +++ b/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package typechecker -import language.implicitConversions +import scala.language.implicitConversions /** A generic means of breaking down types into their subcomponents. * Types are decomposed top down, and recognizable substructure is diff --git a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala index 745250e167..2dd0836322 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala @@ -29,7 +29,7 @@ abstract class Duplicators extends Analyzer { * the old class with the new class, and map symbols through the given 'env'. The * environment is a map from type skolems to concrete types (see SpecializedTypes). */ - def retyped(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol, env: collection.Map[Symbol, Type]): Tree = { + def retyped(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol, env: scala.collection.Map[Symbol, Type]): Tree = { if (oldThis ne newThis) { oldClassOwner = oldThis newClassOwner = newThis diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index 6a91922b4c..e3f0756b6c 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -11,13 +11,13 @@ package scala.tools.nsc package typechecker -import annotation.tailrec +import scala.annotation.tailrec import scala.collection.{ mutable, immutable } import mutable.{ LinkedHashMap, ListBuffer } import scala.util.matching.Regex import symtab.Flags._ import scala.reflect.internal.util.Statistics -import language.implicitConversions +import scala.language.implicitConversions /** This trait provides methods to find various kinds of implicits. * @@ -1151,7 +1151,7 @@ trait Implicits { private def TagSymbols = TagMaterializers.keySet private val TagMaterializers = Map[Symbol, Symbol]( ClassTagClass -> MacroInternal_materializeClassTag, - AbsTypeTagClass -> MacroInternal_materializeAbsTypeTag, + WeakTypeTagClass -> MacroInternal_materializeWeakTypeTag, TypeTagClass -> MacroInternal_materializeTypeTag ) @@ -1217,14 +1217,14 @@ trait Implicits { private val ManifestSymbols = Set[Symbol](PartialManifestClass, FullManifestClass, OptManifestClass) /** Creates a tree that calls the relevant factory method in object - * reflect.Manifest for type 'tp'. An EmptyTree is returned if + * scala.reflect.Manifest for type 'tp'. An EmptyTree is returned if * no manifest is found. todo: make this instantiate take type params as well? */ private def manifestOfType(tp: Type, flavor: Symbol): SearchResult = { val full = flavor == FullManifestClass val opt = flavor == OptManifestClass - /** Creates a tree that calls the factory method called constructor in object reflect.Manifest */ + /** Creates a tree that calls the factory method called constructor in object scala.reflect.Manifest */ def manifestFactoryCall(constructor: String, tparg: Type, args: Tree*): Tree = if (args contains EmptyTree) EmptyTree else typedPos(tree.pos.focus) { @@ -1472,7 +1472,7 @@ trait Implicits { interpolate(msg, Map((typeParamNames zip typeArgs): _*)) // TODO: give access to the name and type of the implicit argument, etc? def validate: Option[String] = { - import scala.util.matching.Regex; import collection.breakOut + import scala.util.matching.Regex; import scala.collection.breakOut // is there a shorter way to avoid the intermediate toList? val refs = """\$\{([^}]+)\}""".r.findAllIn(msg).matchData.map(_ group 1).toSet val decls = typeParamNames.toSet @@ -1492,7 +1492,7 @@ trait Implicits { object ImplicitsStats { - import reflect.internal.TypesStats._ + import scala.reflect.internal.TypesStats._ val rawTypeImpl = Statistics.newSubCounter (" of which in implicits", rawTypeCount) val subtypeImpl = Statistics.newSubCounter(" of which in implicit", subtypeCount) diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala index 96dcbb5b80..12766116d1 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -941,10 +941,13 @@ trait Infer { /** Is sym1 (or its companion class in case it is a module) a subclass of * sym2 (or its companion class in case it is a module)? */ - def isProperSubClassOrObject(sym1: Symbol, sym2: Symbol): Boolean = - sym1 != sym2 && sym1 != NoSymbol && (sym1 isSubClass sym2) || - sym1.isModuleClass && isProperSubClassOrObject(sym1.linkedClassOfClass, sym2) || - sym2.isModuleClass && isProperSubClassOrObject(sym1, sym2.linkedClassOfClass) + def isProperSubClassOrObject(sym1: Symbol, sym2: Symbol): Boolean = ( + (sym1 != sym2) && (sym1 != NoSymbol) && ( + (sym1 isSubClass sym2) + || (sym1.isModuleClass && isProperSubClassOrObject(sym1.linkedClassOfClass, sym2)) + || (sym2.isModuleClass && isProperSubClassOrObject(sym1, sym2.linkedClassOfClass)) + ) + ) /** is symbol `sym1` defined in a proper subclass of symbol `sym2`? */ diff --git a/src/compiler/scala/tools/nsc/typechecker/Macros.scala b/src/compiler/scala/tools/nsc/typechecker/Macros.scala index 01e773e528..7e9b288853 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Macros.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Macros.scala @@ -7,7 +7,7 @@ import scala.tools.nsc.util.ClassPath._ import scala.reflect.runtime.ReflectionUtils import scala.collection.mutable.ListBuffer import scala.compat.Platform.EOL -import reflect.internal.util.Statistics +import scala.reflect.internal.util.Statistics import scala.reflect.macros.util._ import java.lang.{Class => jClass} import java.lang.reflect.{Array => jArray, Method => jMethod} @@ -26,7 +26,7 @@ import scala.reflect.macros.runtime.AbortMacroException * * Then fooBar needs to point to a static method of the following form: * - * def fooBar[T: c.AbsTypeTag] // type tag annotation is optional + * def fooBar[T: c.WeakTypeTag] // type tag annotation is optional * (c: scala.reflect.macros.Context) * (xs: c.Expr[List[T]]) * : c.Expr[T] = { @@ -84,7 +84,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { val methName: String, // flattens the macro impl's parameter lists having symbols replaced with metadata // currently metadata is an index of the type parameter corresponding to that type tag (if applicable) - // f.ex. for: def impl[T: AbsTypeTag, U: AbsTypeTag, V](c: Context)(x: c.Expr[T]): (U, V) = ??? + // f.ex. for: def impl[T: WeakTypeTag, U: WeakTypeTag, V](c: Context)(x: c.Expr[T]): (U, V) = ??? // `signature` will be equal to List(-1, -1, 0, 1) val signature: List[Int], // type arguments part of a macro impl ref (the right-hand side of a macro definition) @@ -216,7 +216,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { } /** Transforms parameters lists of a macro impl. - * The `transform` function is invoked only for AbsTypeTag evidence parameters. + * The `transform` function is invoked only for WeakTypeTag evidence parameters. * * The transformer takes two arguments: a value parameter from the parameter list * and a type parameter that is witnesses by the value parameter. @@ -232,7 +232,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { if (paramss.isEmpty || paramss.last.isEmpty) return paramss // no implicit parameters in the signature => nothing to do if (paramss.head.isEmpty || !(paramss.head.head.tpe <:< MacroContextClass.tpe)) return paramss // no context parameter in the signature => nothing to do def transformTag(param: Symbol): Symbol = param.tpe.dealias match { - case TypeRef(SingleType(SingleType(NoPrefix, c), universe), AbsTypeTagClass, targ :: Nil) + case TypeRef(SingleType(SingleType(NoPrefix, c), universe), WeakTypeTagClass, targ :: Nil) if c == paramss.head.head && universe == MacroContextUniverse => transform(param, targ.typeSymbol) case _ => @@ -336,7 +336,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { RepeatedParamClass.typeConstructor, List(implType(isType, sigma(origTpe.typeArgs.head)))) else { - val tsym = getMember(MacroContextClass, if (isType) tpnme.AbsTypeTag else tpnme.Expr) + val tsym = getMember(MacroContextClass, if (isType) tpnme.WeakTypeTag else tpnme.Expr) typeRef(singleType(NoPrefix, ctxParam), tsym, List(sigma(origTpe))) } val paramCache = collection.mutable.Map[Symbol, Symbol]() @@ -630,7 +630,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { macroDef.owner) } else targ.tpe - if (tpe.isConcrete) context.TypeTag(tpe) else context.AbsTypeTag(tpe) + context.WeakTypeTag(tpe) }) macroTraceVerbose("tags: ")(tags) @@ -832,7 +832,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { var hasPendingMacroExpansions = false private val delayed = perRunCaches.newWeakMap[Tree, collection.mutable.Set[Int]] private def isDelayed(expandee: Tree) = delayed contains expandee - private def calculateUndetparams(expandee: Tree): collection.mutable.Set[Int] = + private def calculateUndetparams(expandee: Tree): scala.collection.mutable.Set[Int] = delayed.get(expandee).getOrElse { val calculated = collection.mutable.Set[Symbol]() expandee foreach (sub => { @@ -872,13 +872,13 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { new Transformer { override def transform(tree: Tree) = super.transform(tree match { // todo. expansion should work from the inside out - case wannabe if (delayed contains wannabe) && calculateUndetparams(wannabe).isEmpty => - val context = wannabe.attachments.get[MacroRuntimeAttachment].get.typerContext - delayed -= wannabe + case tree if (delayed contains tree) && calculateUndetparams(tree).isEmpty => + val context = tree.attachments.get[MacroRuntimeAttachment].get.typerContext + delayed -= tree context.implicitsEnabled = typer.context.implicitsEnabled context.enrichmentEnabled = typer.context.enrichmentEnabled context.macrosEnabled = typer.context.macrosEnabled - macroExpand(newTyper(context), wannabe, EXPRmode, WildcardType) + macroExpand(newTyper(context), tree, EXPRmode, WildcardType) case _ => tree }) @@ -886,7 +886,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { } object MacrosStats { - import reflect.internal.TypesStats.typerNanos + import scala.reflect.internal.TypesStats.typerNanos val macroExpandCount = Statistics.newCounter ("#macro expansions", "typer") val macroExpandNanos = Statistics.newSubTimer("time spent in macroExpand", typerNanos) } diff --git a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala index 4f597f97c9..91dcd90962 100644 --- a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala +++ b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala @@ -10,7 +10,7 @@ import scala.collection.{ mutable, immutable } import scala.reflect.internal.util.StringOps.{ ojoin } import scala.reflect.ClassTag import scala.reflect.runtime.{ universe => ru } -import language.higherKinds +import scala.language.higherKinds /** Logic related to method synthesis which involves cooperation between * Namer and Typer. @@ -369,7 +369,7 @@ trait MethodSynthesis { } /** A synthetic method which performs the implicit conversion implied by - * the declaration of an implicit class. Yet to be written. + * the declaration of an implicit class. */ case class ImplicitClassWrapper(tree: ClassDef) extends DerivedFromClassDef { def completer(sym: Symbol): Type = ??? // not needed @@ -377,7 +377,7 @@ trait MethodSynthesis { def derivedSym: Symbol = { // Only methods will do! Don't want to pick up any stray // companion objects of the same name. - val result = enclClass.info decl name suchThat (_.isMethod) + val result = enclClass.info decl name suchThat (x => x.isMethod && x.isSynthetic) assert(result != NoSymbol, "not found: "+name+" in "+enclClass+" "+enclClass.info.decls) result } diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index 18b3fe5f4c..7f14216e76 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -359,10 +359,39 @@ trait Namers extends MethodSynthesis { } } + /** Given a ClassDef or ModuleDef, verifies there isn't a companion which + * has been defined in a separate file. + */ + private def validateCompanionDefs(tree: ImplDef) { + val sym = tree.symbol + if (sym eq NoSymbol) return + + val ctx = if (context.owner.isPackageObjectClass) context.outer else context + val module = if (sym.isModule) sym else ctx.scope lookup tree.name.toTermName + val clazz = if (sym.isClass) sym else ctx.scope lookup tree.name.toTypeName + val fails = ( + module.isModule + && clazz.isClass + && !module.isSynthetic + && !clazz.isSynthetic + && (clazz.sourceFile ne null) + && (module.sourceFile ne null) + && !(module isCoDefinedWith clazz) + ) + if (fails) { + context.unit.error(tree.pos, ( + s"Companions '$clazz' and '$module' must be defined in same file:\n" + + s" Found in ${clazz.sourceFile.canonicalPath} and ${module.sourceFile.canonicalPath}") + ) + } + } + def enterModuleDef(tree: ModuleDef) = { val sym = enterModuleSymbol(tree) sym.moduleClass setInfo namerOf(sym).moduleClassTypeCompleter(tree) sym setInfo completerOf(tree) + validateCompanionDefs(tree) + sym } /** Enter a module symbol. The tree parameter can be either @@ -467,7 +496,6 @@ trait Namers extends MethodSynthesis { // for Java code importing Scala objects if (!nme.isModuleName(from) || isValid(nme.stripModuleSuffix(from))) { typer.TyperErrorGen.NotAMemberError(tree, expr, from) - typer.infer.setError(tree) } } // Setting the position at the import means that if there is @@ -635,6 +663,7 @@ trait Namers extends MethodSynthesis { } else context.unit.error(tree.pos, "implicit classes must accept exactly one primary constructor parameter") } + validateCompanionDefs(tree) } // this logic is needed in case typer was interrupted half @@ -699,7 +728,7 @@ trait Namers extends MethodSynthesis { // } } - def moduleClassTypeCompleter(tree: Tree) = { + def moduleClassTypeCompleter(tree: ModuleDef) = { mkTypeCompleter(tree) { sym => val moduleSymbol = tree.symbol assert(moduleSymbol.moduleClass == sym, moduleSymbol.moduleClass) @@ -1545,18 +1574,11 @@ trait Namers extends MethodSynthesis { * call this method? */ def companionSymbolOf(original: Symbol, ctx: Context): Symbol = { - try { - original.companionSymbol orElse { - ctx.lookup(original.name.companionName, original.owner).suchThat(sym => - (original.isTerm || sym.hasModuleFlag) && - (sym isCoDefinedWith original) - ) - } - } - catch { - case e: InvalidCompanions => - ctx.unit.error(original.pos, e.getMessage) - NoSymbol + original.companionSymbol orElse { + ctx.lookup(original.name.companionName, original.owner).suchThat(sym => + (original.isTerm || sym.hasModuleFlag) && + (sym isCoDefinedWith original) + ) } } } diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 14c9aca078..7a035bb33b 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -9,12 +9,12 @@ package typechecker import symtab._ import Flags.{MUTABLE, METHOD, LABEL, SYNTHETIC, ARTIFACT} -import language.postfixOps +import scala.language.postfixOps import scala.tools.nsc.transform.TypingTransformers import scala.tools.nsc.transform.Transform import scala.collection.mutable.HashSet import scala.collection.mutable.HashMap -import reflect.internal.util.Statistics +import scala.reflect.internal.util.Statistics import scala.reflect.internal.Types /** Translate pattern matching. @@ -2941,7 +2941,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL } // node in the tree that describes how to construct a counter-example - case class VariableAssignment(variable: Var, equalTo: List[Const], notEqualTo: List[Const], fields: collection.mutable.Map[Symbol, VariableAssignment]) { + case class VariableAssignment(variable: Var, equalTo: List[Const], notEqualTo: List[Const], fields: scala.collection.mutable.Map[Symbol, VariableAssignment]) { // need to prune since the model now incorporates all super types of a constant (needed for reachability) private lazy val uniqueEqualTo = equalTo filterNot (subsumed => equalTo.exists(better => (better ne subsumed) && instanceOfTpImplies(better.tp, subsumed.tp))) private lazy val prunedEqualTo = uniqueEqualTo filterNot (subsumed => variable.staticTpCheckable <:< subsumed.tp) diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala index 93a8dfc9cb..2335a9e3b6 100644 --- a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala +++ b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala @@ -7,10 +7,10 @@ package scala.tools.nsc package typechecker import symtab.Flags._ -import collection.{ mutable, immutable } +import scala.collection.{ mutable, immutable } import transform.InfoTransform import scala.collection.mutable.ListBuffer -import language.postfixOps +import scala.language.postfixOps /** <p> * Post-attribution checking and transformation. @@ -38,7 +38,7 @@ import language.postfixOps * * @todo Check whether we always check type parameter bounds. */ -abstract class RefChecks extends InfoTransform with reflect.internal.transform.RefChecks { +abstract class RefChecks extends InfoTransform with scala.reflect.internal.transform.RefChecks { val global: Global // need to repeat here because otherwise last mixin defines global as // SymbolTable. If we had DOT this would not be an issue @@ -430,6 +430,7 @@ abstract class RefChecks extends InfoTransform with reflect.internal.transform.R overrideError("cannot override a macro") } else { checkOverrideTypes() + checkOverrideDeprecated() if (settings.warnNullaryOverride.value) { if (other.paramss.isEmpty && !member.paramss.isEmpty) { unit.warning(member.pos, "non-nullary method overrides nullary method") @@ -508,6 +509,14 @@ abstract class RefChecks extends InfoTransform with reflect.internal.transform.R } } } + + def checkOverrideDeprecated() { + if (other.hasDeprecatedOverridingAnnotation) { + val suffix = other.deprecatedOverridingMessage map (": " + _) getOrElse "" + val msg = s"overriding ${other.fullLocationString} is deprecated$suffix" + unit.deprecationWarning(member.pos, msg) + } + } } val opc = new overridingPairs.Cursor(clazz) @@ -1199,6 +1208,23 @@ abstract class RefChecks extends InfoTransform with reflect.internal.transform.R case _ => } + // SI-6276 warn for `def foo = foo` or `val bar: X = bar`, which come up more frequently than you might think. + def checkInfiniteLoop(valOrDef: ValOrDefDef) { + def callsSelf = valOrDef.rhs match { + case t @ (Ident(_) | Select(This(_), _)) => + t hasSymbolWhich (_.accessedOrSelf == valOrDef.symbol) + case _ => false + } + val trivialInifiniteLoop = ( + !valOrDef.isErroneous + && !valOrDef.symbol.isValueParameter + && valOrDef.symbol.paramss.isEmpty + && callsSelf + ) + if (trivialInifiniteLoop) + unit.warning(valOrDef.rhs.pos, s"${valOrDef.symbol.fullLocationString} does nothing other than call itself recursively") + } + // Transformation ------------------------------------------------------------ /* Convert a reference to a case factory of type `tpe` to a new of the class it produces. */ @@ -1642,6 +1668,7 @@ abstract class RefChecks extends InfoTransform with reflect.internal.transform.R case ValDef(_, _, _, _) | DefDef(_, _, _, _, _, _) => checkDeprecatedOvers(tree) + checkInfiniteLoop(tree.asInstanceOf[ValOrDefDef]) if (settings.warnNullaryUnit.value) checkNullaryMethodReturnType(sym) if (settings.warnInaccessible.value) { diff --git a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala index 0c9ed29182..2fe8925c95 100644 --- a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala +++ b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala @@ -63,7 +63,7 @@ trait SyntheticMethods extends ast.TreeDSL { // in the original order. def accessors = clazz.caseFieldAccessors sortBy { acc => originalAccessors indexWhere { orig => - (acc.name == orig.name) || (acc.name startsWith (orig.name append "$").asInstanceOf[Name]) // [Eugene] why do we need this cast? + (acc.name == orig.name) || (acc.name startsWith (orig.name append "$")) } } val arity = accessors.size @@ -87,7 +87,7 @@ trait SyntheticMethods extends ast.TreeDSL { ) def forwardToRuntime(method: Symbol): Tree = - forwardMethod(method, getMember(ScalaRunTimeModule, (method.name prepend "_").asInstanceOf[Name]))(mkThis :: _) // [Eugene] why do we need this cast? + forwardMethod(method, getMember(ScalaRunTimeModule, (method.name prepend "_")))(mkThis :: _) def callStaticsMethod(name: String)(args: Tree*): Tree = { val method = termMember(RuntimeStaticsModule, name) diff --git a/src/compiler/scala/tools/nsc/typechecker/Tags.scala b/src/compiler/scala/tools/nsc/typechecker/Tags.scala index d4e4100dfa..44fa9a5d7a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Tags.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Tags.scala @@ -26,7 +26,7 @@ trait Tags { /** Finds in scope or materializes a ClassTag. * Should be used instead of ClassManifest every time compiler needs to persist an erasure. * - * Once upon a time, we had an `ErasureTag` which was to `ClassTag` the same that `AbsTypeTag` is for `TypeTag`. + * Once upon a time, we had an `ErasureTag` which was to `ClassTag` the same that `WeakTypeTag` is for `TypeTag`. * However we found out that we don't really need this concept, so it got removed. * * @param pos Position for error reporting. Please, provide meaningful value. @@ -43,7 +43,7 @@ trait Tags { resolveTag(pos, taggedTp, allowMaterialization) } - /** Finds in scope or materializes an AbsTypeTag (if `concrete` is false) or a TypeTag (if `concrete` is true). + /** Finds in scope or materializes an WeakTypeTag (if `concrete` is false) or a TypeTag (if `concrete` is true). * * @param pos Position for error reporting. Please, provide meaningful value. * @param pre Prefix that represents a universe this type tag will be bound to. @@ -60,7 +60,7 @@ trait Tags { * EmptyTree if `allowMaterialization` is false, and there is no array tag in scope. */ def resolveTypeTag(pos: Position, pre: Type, tp: Type, concrete: Boolean, allowMaterialization: Boolean = true): Tree = { - val tagSym = if (concrete) TypeTagClass else AbsTypeTagClass + val tagSym = if (concrete) TypeTagClass else WeakTypeTagClass val tagTp = if (pre == NoType) TypeRef(BaseUniverseClass.toTypeConstructor, tagSym, List(tp)) else singleType(pre, pre member tagSym.name) val taggedTp = appliedType(tagTp, List(tp)) resolveTag(pos, taggedTp, allowMaterialization) diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala index f8a5c401df..e5c0f5767c 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala @@ -59,6 +59,19 @@ trait TypeDiagnostics { * the map, the addendum should also be printed. */ private var addendums = perRunCaches.newMap[Position, () => String]() + private var isTyperInPattern = false + + /** Devising new ways of communicating error info out of + * desperation to work on error messages. This is used + * by typedPattern to wrap its business so we can generate + * a sensible error message when things go south. + */ + def typingInPattern[T](body: => T): T = { + val saved = isTyperInPattern + isTyperInPattern = true + try body + finally isTyperInPattern = saved + } def setAddendum(pos: Position, msg: () => String) = if (pos != NoPosition) @@ -138,13 +151,17 @@ trait TypeDiagnostics { def hasParams = tree.tpe.paramSectionCount > 0 def preResultString = if (hasParams) ": " else " of type " - def nullMessage = "expression of type " + tree.tpe - def overloadedMessage = "overloaded method " + sym + " with alternatives:\n" + alternativesString(tree) + def patternMessage = "pattern " + tree.tpe.finalResultType + valueParamsString(tree.tpe) + def exprMessage = "expression of type " + tree.tpe + def overloadedMessage = s"overloaded method $sym with alternatives:\n" + alternativesString(tree) def moduleMessage = "" + sym def defaultMessage = moduleMessage + preResultString + tree.tpe def applyMessage = defaultMessage + tree.symbol.locationString - if (sym == null) nullMessage + if ((sym eq null) || (sym eq NoSymbol)) { + if (isTyperInPattern) patternMessage + else exprMessage + } else if (sym.isOverloaded) overloadedMessage else if (sym.isModule) moduleMessage else if (sym.name == nme.apply) applyMessage diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 87937519fc..a58d73bd69 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -13,10 +13,9 @@ package scala.tools.nsc package typechecker import scala.collection.mutable -import scala.reflect.internal.util.BatchSourceFile +import scala.reflect.internal.util.{ BatchSourceFile, Statistics } import mutable.ListBuffer import symtab.Flags._ -import reflect.internal.util.Statistics // Suggestion check whether we can do without priming scopes with symbols of outer scopes, // like the IDE does. @@ -779,7 +778,7 @@ trait Typers extends Modes with Adaptations with Tags { var raw = featureDesc + " " + req + " be enabled\n" + "by making the implicit value language." + featureName + " visible." if (!(currentRun.reportedFeature contains featureTrait)) - raw += "\nThis can be achieved by adding the import clause 'import language." + featureName + "'\n" + + raw += "\nThis can be achieved by adding the import clause 'import scala.language." + featureName + "'\n" + "or by setting the compiler option -language:" + featureName + ".\n" + "See the Scala docs for value scala.language." + featureName + " for a discussion\n" + "why the feature " + req + " be explicitly enabled." @@ -1405,14 +1404,15 @@ trait Typers extends Modes with Adaptations with Tags { unit.error(clazz.pos, "value class needs to have exactly one public val parameter") } } - body foreach { - case md: ModuleDef => - unit.error(md.pos, "value class may not have nested module definitions") - case cd: ClassDef => - unit.error(cd.pos, "value class may not have nested class definitions") - case md: DefDef if md.symbol.isConstructor && !md.symbol.isPrimaryConstructor => - unit.error(md.pos, "value class may not have secondary constructors") - case _ => + + def valueClassMayNotHave(at: Tree, what: String) = unit.error(at.pos, s"value class may not have $what") + body.foreach { + case dd: DefDef if dd.symbol.isAuxiliaryConstructor => valueClassMayNotHave(dd, "secondary constructors") + case t => t.foreach { + case md: ModuleDef => valueClassMayNotHave(md, "nested module definitions") + case cd: ClassDef => valueClassMayNotHave(cd, "nested class definitions") + case _ => + } } for (tparam <- clazz.typeParams) if (tparam hasAnnotation definitions.SpecializedClass) @@ -1577,6 +1577,12 @@ trait Typers extends Modes with Adaptations with Tags { if (psym.isFinal) pending += ParentFinalInheritanceError(parent, psym) + if (psym.hasDeprecatedInheritanceAnnotation) { + val suffix = psym.deprecatedInheritanceMessage map (": " + _) getOrElse "" + val msg = s"inheritance from ${psym.fullLocationString} is deprecated$suffix" + unit.deprecationWarning(parent.pos, msg) + } + if (psym.isSealed && !phase.erasedTypes) if (context.unit.source.file == psym.sourceFile) psym addChild context.owner @@ -1868,7 +1874,7 @@ trait Typers extends Modes with Adaptations with Tags { * @param rhs ... */ def computeParamAliases(clazz: Symbol, vparamss: List[List[ValDef]], rhs: Tree) { - log("computing param aliases for "+clazz+":"+clazz.primaryConstructor.tpe+":"+rhs)//debug + debuglog(s"computing param aliases for $clazz:${clazz.primaryConstructor.tpe}:$rhs") def decompose(call: Tree): (Tree, List[Tree]) = call match { case Apply(fn, args) => val (superConstr, args1) = decompose(fn) @@ -2392,7 +2398,7 @@ trait Typers extends Modes with Adaptations with Tags { else targs.init def mkParams(methodSym: Symbol, formals: List[Type] = deriveFormals) = - if (formals.isEmpty) { MissingParameterTypeAnonMatchError(tree, pt); Nil } + if (formals.isEmpty || !formals.forall(isFullyDefined)) { MissingParameterTypeAnonMatchError(tree, pt); Nil } else methodSym newSyntheticValueParams formals def mkSel(params: List[Symbol]) = @@ -3227,7 +3233,7 @@ trait Typers extends Modes with Adaptations with Tags { val nbSubPats = args.length val (formals, formalsExpanded) = extractorFormalTypes(resTp, nbSubPats, fun1.symbol) - if (formals == null) duplErrorTree(WrongNumberArgsPatternError(tree, fun)) + if (formals == null) duplErrorTree(WrongNumberOfArgsError(tree, fun)) else { val args1 = typedArgs(args, mode, formals, formalsExpanded) // This used to be the following (failing) assert: @@ -3434,7 +3440,7 @@ trait Typers extends Modes with Adaptations with Tags { } if (hasError) annotationError - else AnnotationInfo(annType, List(), nvPairs map {p => (p._1.asInstanceOf[Name], p._2.get)}).setOriginal(Apply(typedFun, args).setPos(ann.pos)) // [Eugene] why do we need this cast? + else AnnotationInfo(annType, List(), nvPairs map {p => (p._1, p._2.get)}).setOriginal(Apply(typedFun, args).setPos(ann.pos)) } } else if (requireJava) { reportAnnotationError(NestedAnnotationError(ann, annType)) @@ -3813,18 +3819,23 @@ trait Typers extends Modes with Adaptations with Tags { * - simplest solution: have two method calls * */ - def mkInvoke(cxTree: Tree, tree: Tree, qual: Tree, name: Name): Option[Tree] = + def mkInvoke(cxTree: Tree, tree: Tree, qual: Tree, name: Name): Option[Tree] = { + debuglog(s"mkInvoke($cxTree, $tree, $qual, $name)") acceptsApplyDynamicWithType(qual, name) map { tp => // tp eq NoType => can call xxxDynamic, but not passing any type args (unless specified explicitly by the user) // in scala-virtualized, when not NoType, tp is passed as type argument (for selection on a staged Struct) - // strip off type application -- we're not doing much with outer, so don't bother preserving cxTree's attributes etc - val (outer, explicitTargs) = cxTree match { - case TypeApply(fun, targs) => (fun, targs) - case Apply(TypeApply(fun, targs), args) => (Apply(fun, args), targs) - case t => (t, Nil) + // strip off type application -- we're not doing much with outer, + // so don't bother preserving cxTree's attributes etc + val cxTree1 = cxTree match { + case t: ValOrDefDef => t.rhs + case t => t + } + val (outer, explicitTargs) = cxTree1 match { + case TypeApply(fun, targs) => (fun, targs) + case Apply(TypeApply(fun, targs), args) => (Apply(fun, args), targs) + case t => (t, Nil) } - @inline def hasNamedArg(as: List[Tree]) = as.collectFirst{case AssignOrNamedArg(lhs, rhs) =>}.nonEmpty // note: context.tree includes at most one Apply node @@ -3849,6 +3860,7 @@ trait Typers extends Modes with Adaptations with Tags { atPos(qual.pos)(Apply(tappSel, List(Literal(Constant(name.decode))))) } + } } @inline final def deindentTyping() = context.typingIndentLevel -= 2 @@ -4069,7 +4081,7 @@ trait Typers extends Modes with Adaptations with Tags { if ( !settings.XoldPatmat.value && !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, false) // use unpacked type + ) (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) @@ -5454,7 +5466,7 @@ trait Typers extends Modes with 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? - context.withImplicitsDisabledAllowEnrichment(typed(tree, PATTERNmode, pt)) + typingInPattern(context.withImplicitsDisabledAllowEnrichment(typed(tree, PATTERNmode, pt))) } /** Types a (fully parameterized) type tree */ @@ -5559,8 +5571,8 @@ trait Typers extends Modes with Adaptations with Tags { } object TypersStats { - import reflect.internal.TypesStats._ - import reflect.internal.BaseTypeSeqsStats._ + import scala.reflect.internal.TypesStats._ + import scala.reflect.internal.BaseTypeSeqsStats._ val typedIdentCount = Statistics.newCounter("#typechecked identifiers") val typedSelectCount = Statistics.newCounter("#typechecked selections") val typedApplyCount = Statistics.newCounter("#typechecked applications") diff --git a/src/compiler/scala/tools/nsc/util/Exceptional.scala b/src/compiler/scala/tools/nsc/util/Exceptional.scala index 90d032518a..34344263e8 100644 --- a/src/compiler/scala/tools/nsc/util/Exceptional.scala +++ b/src/compiler/scala/tools/nsc/util/Exceptional.scala @@ -4,7 +4,7 @@ package util import java.util.concurrent.ExecutionException import java.lang.reflect.{ InvocationTargetException, UndeclaredThrowableException } import scala.reflect.internal.util.StringOps._ -import language.implicitConversions +import scala.language.implicitConversions object Exceptional { def unwrap(x: Throwable): Throwable = x match { diff --git a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala index 25caae9ecb..9de3a2427f 100644 --- a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala +++ b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala @@ -14,7 +14,7 @@ import java.net.URL import scala.reflect.runtime.ReflectionUtils.unwrapHandler import ScalaClassLoader._ import scala.util.control.Exception.{ catching } -import language.implicitConversions +import scala.language.implicitConversions import scala.reflect.{ ClassTag, classTag } trait HasClassPath { diff --git a/src/compiler/scala/tools/nsc/util/StatisticsInfo.scala b/src/compiler/scala/tools/nsc/util/StatisticsInfo.scala index 8cdb96c586..3682b9fb54 100644 --- a/src/compiler/scala/tools/nsc/util/StatisticsInfo.scala +++ b/src/compiler/scala/tools/nsc/util/StatisticsInfo.scala @@ -6,13 +6,13 @@ package scala.tools.nsc package util -import reflect.internal.util.Statistics +import scala.reflect.internal.util.Statistics abstract class StatisticsInfo { val global: Global import global._ - import reflect.internal.TreesStats.nodeByType + import scala.reflect.internal.TreesStats.nodeByType val phasesShown = List("parser", "typer", "patmat", "erasure", "cleanup") @@ -35,4 +35,4 @@ abstract class StatisticsInfo { for (q <- quants if q.showAt(phase.name)) inform(q.line) } -}
\ No newline at end of file +} diff --git a/src/compiler/scala/tools/reflect/FastTrack.scala b/src/compiler/scala/tools/reflect/FastTrack.scala index 07c972899e..38e4e3c9f1 100644 --- a/src/compiler/scala/tools/reflect/FastTrack.scala +++ b/src/compiler/scala/tools/reflect/FastTrack.scala @@ -13,7 +13,7 @@ trait FastTrack { import global._ import definitions._ - import language.implicitConversions + import scala.language.implicitConversions private implicit def context2taggers(c0: MacroContext): Taggers { val c: c0.type } = new { val c: c0.type = c0 } with Taggers private implicit def context2macroimplementations(c0: MacroContext): MacroImplementations { val c: c0.type } = new { val c: c0.type = c0 } with MacroImplementations @@ -23,7 +23,7 @@ trait FastTrack { def validate(c: MacroContext): Boolean = expander.isDefinedAt((c, c.expandee)) def run(c: MacroContext): Any = { val result = expander((c, c.expandee)) - c.Expr[Nothing](result)(c.AbsTypeTag.Nothing) + c.Expr[Nothing](result)(c.WeakTypeTag.Nothing) } } @@ -31,11 +31,11 @@ trait FastTrack { var registry = Map[Symbol, FastTrackEntry]() implicit class BindTo(sym: Symbol) { def bindTo(expander: FastTrackExpander): Unit = if (sym != NoSymbol) registry += sym -> FastTrackEntry(sym, expander) } MacroInternal_materializeClassTag bindTo { case (c, Apply(TypeApply(_, List(tt)), List(u))) => c.materializeClassTag(u, tt.tpe) } - MacroInternal_materializeAbsTypeTag bindTo { case (c, Apply(TypeApply(_, List(tt)), List(u))) => c.materializeTypeTag(u, EmptyTree, tt.tpe, concrete = false) } + MacroInternal_materializeWeakTypeTag bindTo { case (c, Apply(TypeApply(_, List(tt)), List(u))) => c.materializeTypeTag(u, EmptyTree, tt.tpe, concrete = false) } MacroInternal_materializeTypeTag bindTo { case (c, Apply(TypeApply(_, List(tt)), List(u))) => c.materializeTypeTag(u, EmptyTree, tt.tpe, concrete = true) } BaseUniverseReify bindTo { case (c, Apply(TypeApply(_, List(tt)), List(expr))) => c.materializeExpr(c.prefix.tree, EmptyTree, expr) } ReflectRuntimeCurrentMirror bindTo { case (c, _) => scala.reflect.runtime.Macros.currentMirror(c).tree } StringContext_f bindTo { case (c, app@Apply(Select(Apply(_, parts), _), args)) => c.macro_StringInterpolation_f(parts, args, app.pos) } registry } -}
\ No newline at end of file +} diff --git a/src/compiler/scala/tools/reflect/package.scala b/src/compiler/scala/tools/reflect/package.scala index 3008930823..d5569e448d 100644 --- a/src/compiler/scala/tools/reflect/package.scala +++ b/src/compiler/scala/tools/reflect/package.scala @@ -6,7 +6,7 @@ package scala.tools import scala.reflect.api.JavaUniverse -import language.implicitConversions +import scala.language.implicitConversions package object reflect extends FrontEnds { // [todo: can we generalize this? diff --git a/src/compiler/scala/tools/util/Javap.scala b/src/compiler/scala/tools/util/Javap.scala index ce149a5aa0..70f71a222a 100644 --- a/src/compiler/scala/tools/util/Javap.scala +++ b/src/compiler/scala/tools/util/Javap.scala @@ -12,7 +12,7 @@ import scala.tools.nsc.util.ScalaClassLoader import java.io.{ InputStream, PrintWriter, ByteArrayInputStream, FileNotFoundException } import scala.tools.nsc.io.File import Javap._ -import language.reflectiveCalls +import scala.language.reflectiveCalls trait Javap { def loader: ScalaClassLoader diff --git a/src/compiler/scala/tools/util/PathResolver.scala b/src/compiler/scala/tools/util/PathResolver.scala index 739878c282..f6dc92f96e 100644 --- a/src/compiler/scala/tools/util/PathResolver.scala +++ b/src/compiler/scala/tools/util/PathResolver.scala @@ -13,7 +13,7 @@ import nsc.util.{ ClassPath, JavaClassPath, ScalaClassLoader } import nsc.io.{ File, Directory, Path, AbstractFile } import ClassPath.{ JavaContext, DefaultJavaContext, join, split } import PartialFunction.condOpt -import language.postfixOps +import scala.language.postfixOps // Loosely based on the draft specification at: // https://wiki.scala-lang.org/display/SW/Classpath diff --git a/src/compiler/scala/tools/util/VerifyClass.scala b/src/compiler/scala/tools/util/VerifyClass.scala index e0e089d0b2..d208a9f9c2 100644 --- a/src/compiler/scala/tools/util/VerifyClass.scala +++ b/src/compiler/scala/tools/util/VerifyClass.scala @@ -2,7 +2,7 @@ package scala.tools.util import scala.tools.nsc.io._ import java.net.URLClassLoader -import collection.JavaConverters._ +import scala.collection.JavaConverters._ object VerifyClass { |