diff options
85 files changed, 1032 insertions, 798 deletions
@@ -1358,11 +1358,10 @@ TODO: <attribute name="Class-Path" value="scala-reflect.jar scala-library.jar"/> </manifest> </pre> - <!-- script api is 2.11-only so far + <!-- JSR-223 support introduced in 2.11 --> <jar-opts> <service type="javax.script.ScriptEngineFactory" provider="scala.tools.nsc.interpreter.IMain$Factory"/> </jar-opts> - --> </staged-pack> </target> diff --git a/src/build/genprod.scala b/src/build/genprod.scala index cd01363cb6..ed436fe2e4 100644 --- a/src/build/genprod.scala +++ b/src/build/genprod.scala @@ -113,8 +113,8 @@ object FunctionZero extends Function(0) { object FunctionOne extends Function(1) { override def classAnnotation = "@annotation.implicitNotFound(msg = \"No implicit view available from ${T1} => ${R}.\")\n" - override def contravariantSpecs = "@specialized(scala.Int, scala.Long, scala.Float, scala.Double/*, scala.AnyRef*/) " - override def covariantSpecs = "@specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double/*, scala.AnyRef*/) " + override def contravariantSpecs = "@specialized(scala.Int, scala.Long, scala.Float, scala.Double) " + override def covariantSpecs = "@specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) " override def descriptiveComment = " " + functionNTemplate.format("succ", "anonfun1", """ diff --git a/src/compiler/scala/reflect/macros/contexts/Parsers.scala b/src/compiler/scala/reflect/macros/contexts/Parsers.scala index 3dab02beba..ae6488b5a8 100644 --- a/src/compiler/scala/reflect/macros/contexts/Parsers.scala +++ b/src/compiler/scala/reflect/macros/contexts/Parsers.scala @@ -1,24 +1,20 @@ package scala.reflect.macros package contexts -import scala.language.existentials -import scala.tools.reflect.ToolBox -import scala.tools.reflect.ToolBoxError +import scala.tools.nsc.reporters.StoreReporter trait Parsers { self: Context => + import global._ - def parse(code: String): Tree = - // todo. provide decent implementation - // see `Typers.typedUseCase` for details - try { - import scala.reflect.runtime.{universe => ru} - val parsed = ru.rootMirror.mkToolBox().parse(code) - val importer = universe.mkImporter(ru) - importer.importTree(parsed) - } catch { - case ToolBoxError(msg, cause) => - // todo. provide a position - throw new ParseException(universe.NoPosition, msg) + def parse(code: String) = { + val sreporter = new StoreReporter() + val unit = new CompilationUnit(newSourceFile(code, "<macro>")) { override def reporter = sreporter } + val parser = newUnitParser(unit) + val tree = gen.mkTreeOrBlock(parser.parseStats()) + sreporter.infos.foreach { + case sreporter.Info(pos, msg, sreporter.ERROR) => throw ParseException(pos, msg) } -} + tree + } +}
\ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/CompilationUnits.scala b/src/compiler/scala/tools/nsc/CompilationUnits.scala index f7437e4e6c..1de5c1f626 100644 --- a/src/compiler/scala/tools/nsc/CompilationUnits.scala +++ b/src/compiler/scala/tools/nsc/CompilationUnits.scala @@ -9,8 +9,9 @@ import util.FreshNameCreator import scala.reflect.internal.util.{ SourceFile, NoSourceFile } import scala.collection.mutable import scala.collection.mutable.{ LinkedHashSet, ListBuffer } +import scala.tools.nsc.reporters.Reporter -trait CompilationUnits { self: Global => +trait CompilationUnits { global: Global => /** An object representing a missing compilation unit. */ @@ -119,6 +120,8 @@ trait CompilationUnits { self: Global => */ val icode: LinkedHashSet[icodes.IClass] = new LinkedHashSet + def reporter = global.reporter + def echo(pos: Position, msg: String) = reporter.echo(pos, msg) diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index f6d4b26cda..f3a2d49697 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -110,7 +110,10 @@ class Global(var currentSettings: Settings, var reporter: Reporter) } /** A spare instance of TreeBuilder left for backwards compatibility. */ - lazy val treeBuilder: TreeBuilder { val global: Global.this.type } = new syntaxAnalyzer.ParserTreeBuilder + lazy val treeBuilder: TreeBuilder { val global: Global.this.type } = new UnitTreeBuilder { + val global: Global.this.type = Global.this; + val unit = currentUnit + } /** Fold constants */ object constfold extends { @@ -629,7 +632,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) object terminal extends { val global: Global.this.type = Global.this } with SubComponent { - final val phaseName = "terminal" + val phaseName = "terminal" val runsAfter = List("jvm") val runsRightAfter = None override val terminal = true @@ -1159,11 +1162,20 @@ class Global(var currentSettings: Settings, var reporter: Reporter) warning("there were %d %s warning(s); re-run with %s for details".format(warnings.size, what, option.name)) } - def newCompilationUnit(code: String) = new CompilationUnit(newSourceFile(code)) - def newSourceFile(code: String) = new BatchSourceFile("<console>", code) - def newUnitScanner(unit: CompilationUnit): UnitScanner = new UnitScanner(unit) - def newUnitParser(unit: CompilationUnit): UnitParser = new UnitParser(unit) - def newUnitParser(code: String): UnitParser = newUnitParser(newCompilationUnit(code)) + def newSourceFile(code: String, filename: String = "<console>") = + new BatchSourceFile(filename, code) + + def newCompilationUnit(code: String, filename: String = "<console>") = + new CompilationUnit(newSourceFile(code, filename)) + + def newUnitScanner(unit: CompilationUnit): UnitScanner = + new UnitScanner(unit) + + def newUnitParser(unit: CompilationUnit): UnitParser = + new UnitParser(unit) + + def newUnitParser(code: String, filename: String = "<console>"): UnitParser = + newUnitParser(newCompilationUnit(code, filename)) /** A Run is a single execution of the compiler on a set of units. */ diff --git a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala index d7a32c3be0..5922b4bbbf 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala @@ -133,90 +133,6 @@ trait TreeDSL { def ==>(body: Tree): CaseDef = CaseDef(pat, guard, body) } - /** VODD, if it's not obvious, means ValOrDefDef. This is the - * common code between a tree based on a pre-existing symbol and - * one being built from scratch. - */ - trait VODDStart { - def name: Name - def defaultMods: Modifiers - def defaultTpt: Tree - def defaultPos: Position - - type ResultTreeType <: ValOrDefDef - def mkTree(rhs: Tree): ResultTreeType - def ===(rhs: Tree): ResultTreeType - - private var _tpt: Tree = null - private var _pos: Position = null - - def withType(tp: Type): this.type = { - _tpt = TypeTree(tp) - this - } - def withPos(pos: Position): this.type = { - _pos = pos - this - } - - final def mods = defaultMods - final def tpt = if (_tpt == null) defaultTpt else _tpt - final def pos = if (_pos == null) defaultPos else _pos - } - trait SymVODDStart extends VODDStart { - def sym: Symbol - def symType: Type - - def name = sym.name - def defaultMods = Modifiers(sym.flags) - def defaultTpt = TypeTree(symType) setPos sym.pos.focus - def defaultPos = sym.pos - - final def ===(rhs: Tree): ResultTreeType = - atPos(pos)(mkTree(rhs) setSymbol sym) - } - trait ValCreator { - self: VODDStart => - - type ResultTreeType = ValDef - def mkTree(rhs: Tree): ValDef = ValDef(mods, name.toTermName, tpt, rhs) - } - trait DefCreator { - self: VODDStart => - - def tparams: List[TypeDef] - def vparamss: List[List[ValDef]] - - type ResultTreeType = DefDef - def mkTree(rhs: Tree): DefDef = DefDef(mods, name.toTermName, tparams, vparamss, tpt, rhs) - } - - class DefSymStart(val sym: Symbol) extends SymVODDStart with DefCreator { - def symType = sym.tpe.finalResultType - def tparams = sym.typeParams map TypeDef - def vparamss = mapParamss(sym)(ValDef) - } - class ValSymStart(val sym: Symbol) extends SymVODDStart with ValCreator { - def symType = sym.tpe - } - - trait TreeVODDStart extends VODDStart { - def defaultMods = NoMods - def defaultTpt = TypeTree() - def defaultPos = NoPosition - - final def ===(rhs: Tree): ResultTreeType = - if (pos == NoPosition) mkTree(rhs) - else atPos(pos)(mkTree(rhs)) - } - - class ValTreeStart(val name: Name) extends TreeVODDStart with ValCreator { - } - class DefTreeStart(val name: Name) extends TreeVODDStart with DefCreator { - def tparams: List[TypeDef] = Nil - def vparamss: List[List[ValDef]] = ListOfNil - } - class IfStart(cond: Tree, thenp: Tree) { def THEN(x: Tree) = new IfStart(cond, x) def ELSE(elsep: Tree) = If(cond, thenp, elsep) @@ -230,46 +146,23 @@ trait TreeDSL { def CASE(pat: Tree): CaseStart = new CaseStart(pat, EmptyTree) def DEFAULT: CaseStart = new CaseStart(WILD.empty, EmptyTree) - class SymbolMethods(target: Symbol) { - def IS_NULL() = REF(target) OBJ_EQ NULL - def GET() = fn(REF(target), nme.get) - def ARGS = target.paramss.head - } - - /** Top level accessible. */ - def MATCHERROR(arg: Tree) = Throw(MatchErrorClass.tpe, arg) - def THROW(sym: Symbol, msg: Tree): Throw = Throw(sym.tpe, msg.TOSTRING()) - def NEW(tpt: Tree, args: Tree*): Tree = New(tpt, List(args.toList)) - def DEF(sym: Symbol): DefSymStart = new DefSymStart(sym) - def VAL(sym: Symbol): ValSymStart = new ValSymStart(sym) - def AND(guards: Tree*) = - if (guards.isEmpty) EmptyTree - else guards reduceLeft gen.mkAnd + def NOT(tree: Tree) = Select(tree, Boolean_not) + def AND(guards: Tree*) = if (guards.isEmpty) EmptyTree else guards reduceLeft gen.mkAnd def IF(tree: Tree) = new IfStart(tree, EmptyTree) def TRY(tree: Tree) = new TryStart(tree, Nil, EmptyTree) def BLOCK(xs: Tree*) = Block(xs.init.toList, xs.last) - def NOT(tree: Tree) = Select(tree, Boolean_not) - def SOME(xs: Tree*) = Apply(SomeClass.companionSymbol, makeTupleTerm(xs.toList, flattenUnary = true)) + def SOME(xs: Tree*) = Apply(SomeClass.companionSymbol, treeBuilder.makeTupleTerm(xs.toList, flattenUnary = true)) /** Typed trees from symbols. */ - def THIS(sym: Symbol) = gen.mkAttributedThis(sym) - def ID(sym: Symbol) = gen.mkAttributedIdent(sym) - def REF(sym: Symbol) = gen.mkAttributedRef(sym) - def REF(pre: Type, sym: Symbol) = gen.mkAttributedRef(pre, sym) - - def makeTupleTerm(trees: List[Tree], flattenUnary: Boolean): Tree = trees match { - case Nil => UNIT - case List(tree) if flattenUnary => tree - case _ => Apply(TupleClass(trees.length).companionModule, trees: _*) - } + def REF(sym: Symbol) = gen.mkAttributedRef(sym) + def REF(pre: Type, sym: Symbol) = gen.mkAttributedRef(pre, sym) /** Implicits - some of these should probably disappear **/ implicit def mkTreeMethods(target: Tree): TreeMethods = new TreeMethods(target) implicit def mkTreeMethodsFromSymbol(target: Symbol): TreeMethods = new TreeMethods(Ident(target)) - implicit def mkSymbolMethodsFromSymbol(target: Symbol): SymbolMethods = new SymbolMethods(target) /** (foo DOT bar) might be simply a Select, but more likely it is to be immediately * followed by an Apply. We don't want to add an actual apply method to arbitrary diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index bd31c548c7..07e24900e9 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -28,20 +28,14 @@ import util.FreshNameCreator */ trait ParsersCommon extends ScannersCommon { self => val global : Global - import global._ + // the use of currentUnit in the parser should be avoided as it might + // cause unexpected behaviour when you work with two units at the + // same time; use Parser.unit instead + import global.{currentUnit => _, _} def newLiteral(const: Any) = Literal(Constant(const)) def literalUnit = newLiteral(()) - class ParserTreeBuilder extends TreeBuilder { - val global: self.global.type = self.global - 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) - } - /** This is now an abstract class, only to work around the optimizer: * methods in traits are never inlined. */ @@ -172,6 +166,7 @@ self => private val globalFresh = new FreshNameCreator.Default + def unit = global.currentUnit def freshName(prefix: String): Name = freshTermName(prefix) def freshTermName(prefix: String): TermName = newTermName(globalFresh.newName(prefix)) def freshTypeName(prefix: String): TypeName = newTypeName(globalFresh.newName(prefix)) @@ -196,7 +191,7 @@ self => * that we don't have the xml library on the compilation classpath. */ private[this] lazy val xmlp = { - currentUnit.encounteredXml(o2p(in.offset)) + unit.encounteredXml(o2p(in.offset)) new MarkupParser(this, preserveWS = true) } @@ -225,7 +220,7 @@ self => override def templateBody(isPre: Boolean) = skipBraces((emptyValDef, EmptyTree.asList)) } - class UnitParser(val unit: global.CompilationUnit, patches: List[BracePatch]) extends SourceFileParser(unit.source) { + class UnitParser(override val unit: global.CompilationUnit, patches: List[BracePatch]) extends SourceFileParser(unit.source) { uself => def this(unit: global.CompilationUnit) = this(unit, Nil) override def newScanner() = new UnitScanner(unit, patches) @@ -298,9 +293,10 @@ self => import nme.raw - abstract class Parser extends ParserCommon { + abstract class Parser extends ParserCommon { parser => val in: Scanner + def unit: CompilationUnit def freshName(prefix: String): Name def freshTermName(prefix: String): TermName def freshTypeName(prefix: String): TypeName @@ -310,8 +306,12 @@ self => /** whether a non-continuable syntax error has been seen */ private var lastErrorOffset : Int = -1 + class ParserTreeBuilder extends UnitTreeBuilder { + val global: self.global.type = self.global + def unit = parser.unit + } val treeBuilder = new ParserTreeBuilder - import treeBuilder.{global => _, _} + import treeBuilder.{global => _, unit => _, _} /** The types of the context bounds of type parameters of the surrounding class */ @@ -703,14 +703,10 @@ self => /* ---------- TREE CONSTRUCTION ------------------------------------------- */ - def atPos[T <: Tree](offset: Int)(t: T): T = - global.atPos(r2p(offset, offset, in.lastOffset max offset))(t) - def atPos[T <: Tree](start: Int, point: Int)(t: T): T = - global.atPos(r2p(start, point, in.lastOffset max start))(t) - def atPos[T <: Tree](start: Int, point: Int, end: Int)(t: T): T = - global.atPos(r2p(start, point, end))(t) - def atPos[T <: Tree](pos: Position)(t: T): T = - global.atPos(pos)(t) + def atPos[T <: Tree](offset: Int)(t: T): T = atPos(r2p(offset, offset, in.lastOffset max offset))(t) + def atPos[T <: Tree](start: Int, point: Int)(t: T): T = atPos(r2p(start, point, in.lastOffset max start))(t) + def atPos[T <: Tree](start: Int, point: Int, end: Int)(t: T): T = atPos(r2p(start, point, end))(t) + def atPos[T <: Tree](pos: Position)(t: T): T = global.atPos(pos)(t) def atInPos[T <: Tree](t: T): T = atPos(o2p(in.offset))(t) def setInPos[T <: Tree](t: T): T = t setPos o2p(in.offset) @@ -946,21 +942,23 @@ self => ts += annotType() } newLineOptWhenFollowedBy(LBRACE) - atPos(t.pos.startOrPoint) { - if (in.token == LBRACE) { - // Warn if they are attempting to refine Unit; we can't be certain it's - // scala.Unit they're refining because at this point all we have is an - // identifier, but at a later stage we lose the ability to tell an empty - // refinement from no refinement at all. See bug #284. - for (Ident(name) <- ts) name.toString match { - case "Unit" | "scala.Unit" => - warning("Detected apparent refinement of Unit; are you missing an '=' sign?") - case _ => - } - CompoundTypeTree(Template(ts.toList, emptyValDef, refinement())) - } - else - makeIntersectionTypeTree(ts.toList) + val types = ts.toList + val braceOffset = in.offset + val hasRefinement = in.token == LBRACE + val refinements = if (hasRefinement) refinement() else Nil + // Warn if they are attempting to refine Unit; we can't be certain it's + // scala.Unit they're refining because at this point all we have is an + // identifier, but at a later stage we lose the ability to tell an empty + // refinement from no refinement at all. See bug #284. + if (hasRefinement) types match { + case Ident(name) :: Nil if name endsWith "Unit" => warning(braceOffset, "Detected apparent refinement of Unit; are you missing an '=' sign?") + case _ => + } + // The second case includes an empty refinement - refinements is empty, but + // it still gets a CompoundTypeTree. + ts.toList match { + case tp :: Nil if !hasRefinement => tp // single type, no refinement, already positioned + case tps => atPos(t.pos.startOrPoint)(CompoundTypeTree(Template(tps, emptyValDef, refinements))) } } @@ -2776,8 +2774,10 @@ self => def readAppliedParent() = { val start = in.offset val parent = startAnnotType() - val argss = if (in.token == LPAREN) multipleArgumentExprs() else Nil - parents += atPos(start)((parent /: argss)(Apply.apply)) + parents += (in.token match { + case LPAREN => atPos(start)((parent /: multipleArgumentExprs())(Apply.apply)) + case _ => parent + }) } readAppliedParent() while (in.token == WITH) { in.nextToken(); readAppliedParent() } diff --git a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala index 28e3217449..91ff530e05 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala @@ -8,6 +8,7 @@ package ast.parser import symtab.Flags._ import scala.collection.mutable.ListBuffer +import scala.reflect.internal.util.OffsetPosition /** Methods for building trees, used in the parser. All the trees * returned by this class must be untyped. @@ -204,11 +205,6 @@ abstract class TreeBuilder { atPos(r2p(start, end, end + op.length)) { new PostfixSelect(od, op.encode) } } - /** A type tree corresponding to (possibly unary) intersection type */ - def makeIntersectionTypeTree(tps: List[Tree]): Tree = - if (tps.tail.isEmpty) tps.head - else CompoundTypeTree(Template(tps, emptyValDef, Nil)) - /** Create tree representing a while loop */ def makeWhile(startPos: Int, cond: Tree, body: Tree): Tree = { val lname = freshTermName(nme.WHILE_PREFIX) @@ -534,3 +530,13 @@ abstract class TreeBuilder { } } } + +abstract class UnitTreeBuilder extends TreeBuilder { + import global._ + def unit: CompilationUnit + def freshName(prefix: String): Name = freshTermName(prefix) + def freshTermName(prefix: String): TermName = unit.freshTermName(prefix) + def freshTypeName(prefix: String): TypeName = unit.freshTypeName(prefix) + def o2p(offset: Int): Position = new OffsetPosition(unit.source, offset) + def r2p(start: Int, mid: Int, end: Int): Position = rangePos(unit.source, start, mid, end) +} diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala b/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala index 182209dfe6..eff7d3211e 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala @@ -866,11 +866,7 @@ abstract class BCodeHelpers extends BCodeTypes with BytecodeWriters { // a plain class lacking companion module, for details see `isCandidateForForwarders`). // ----------------------------------------------------------------------------------------- - val ExcludedForwarderFlags = { - import symtab.Flags._ - // Should include DEFERRED but this breaks findMember. - ( CASE | SPECIALIZED | LIFTED | PROTECTED | STATIC | EXPANDEDNAME | BridgeAndPrivateFlags | MACRO ) - } + val ExcludedForwarderFlags = genASM.ExcludedForwarderFlags /* Adds a @remote annotation, actual use unknown. * diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala index edb1c55224..8d025b5451 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -1479,7 +1479,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { sym.owner.isSynthetic && sym.owner.tpe.parents.exists { t => val TypeRef(_, sym, _) = t - FunctionClass contains sym + FunctionClass.seq contains sym } } diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala index 2c3bf26958..01c4ff5a52 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVMASM.scala @@ -18,10 +18,10 @@ trait GenJVMASM { import icodes._ import definitions._ - protected val ExcludedForwarderFlags = { + val ExcludedForwarderFlags = { import Flags._ // Should include DEFERRED but this breaks findMember. - ( CASE | SPECIALIZED | LIFTED | PROTECTED | STATIC | EXPANDEDNAME | BridgeAndPrivateFlags | MACRO ) + ( SPECIALIZED | LIFTED | PROTECTED | STATIC | EXPANDEDNAME | BridgeAndPrivateFlags | MACRO ) } protected def isJavaEntryPoint(icls: IClass) = { diff --git a/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala b/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala index 34e2a8a96a..04c5bdf824 100644 --- a/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala +++ b/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala @@ -14,7 +14,7 @@ import scala.reflect.internal.util.Position * console. */ class StoreReporter extends Reporter { - class Info(val pos: Position, val msg: String, val severity: Severity) { + case class Info(pos: Position, msg: String, severity: Severity) { override def toString() = "pos: " + pos + " " + msg + " " + severity } val infos = new mutable.LinkedHashSet[Info] diff --git a/src/compiler/scala/tools/nsc/transform/CleanUp.scala b/src/compiler/scala/tools/nsc/transform/CleanUp.scala index b16ba91916..0135190256 100644 --- a/src/compiler/scala/tools/nsc/transform/CleanUp.scala +++ b/src/compiler/scala/tools/nsc/transform/CleanUp.scala @@ -94,7 +94,7 @@ abstract class CleanUp extends Transform with ast.TreeDSL { if (!isFinal) varSym.addAnnotation(VolatileAttr) - val varDef = typedPos( VAL(varSym) === forInit ) + val varDef = typedPos(ValDef(varSym, forInit)) newStaticMembers append transform(varDef) val varInit = typedPos( REF(varSym) === forInit ) @@ -155,13 +155,13 @@ abstract class CleanUp extends Transform with ast.TreeDSL { val methodSym = reflMethodSym.newVariable(mkTerm("method"), ad.pos) setInfo MethodClass.tpe BLOCK( - VAL(methodCache) === getPolyCache, + ValDef(methodCache, getPolyCache), IF (REF(methodCache) OBJ_EQ NULL) THEN BLOCK( REF(methodCache) === NEW(TypeTree(EmptyMethodCacheClass.tpe)), REF(reflPolyCacheSym) === gen.mkSoftRef(REF(methodCache)) ) ENDIF, - VAL(methodSym) === (REF(methodCache) DOT methodCache_find)(REF(forReceiverSym)), + ValDef(methodSym, (REF(methodCache) DOT methodCache_find)(REF(forReceiverSym))), IF (REF(methodSym) OBJ_NE NULL) . THEN (Return(REF(methodSym))) ELSE { @@ -372,7 +372,7 @@ abstract class CleanUp extends Transform with ast.TreeDSL { qual = REF(sym) BLOCK( - VAL(sym) === qual0, + ValDef(sym, qual0), callAsReflective(mparams map (_.tpe), resType) ) } @@ -543,7 +543,7 @@ abstract class CleanUp extends Transform with ast.TreeDSL { ) // create field definition and initialization - val stfieldDef = theTyper.typedPos(pos)(VAL(stfieldSym) === rhs) + val stfieldDef = theTyper.typedPos(pos)(ValDef(stfieldSym, rhs)) val stfieldInit = theTyper.typedPos(pos)(REF(stfieldSym) === rhs) // add field definition to new defs diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala index c74fc620ca..31855bc1ad 100644 --- a/src/compiler/scala/tools/nsc/transform/Erasure.scala +++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala @@ -268,7 +268,7 @@ abstract class Erasure extends AddInterfaces else abbrvTag(sym).toString } else if (sym.isDerivedValueClass) { - val unboxed = sym.derivedValueClassUnbox.info.finalResultType + val unboxed = sym.derivedValueClassUnbox.tpe_*.finalResultType val unboxedSeen = (tp memberType sym.derivedValueClassUnbox).finalResultType def unboxedMsg = if (unboxed == unboxedSeen) "" else s", seen within ${sym.simpleName} as $unboxedSeen" logResult(s"Erasure of value class $sym (underlying type $unboxed$unboxedMsg) is") { @@ -513,7 +513,7 @@ abstract class Erasure extends AddInterfaces maybeWrap(bridgingCall) } - atPos(bridge.pos)(DefDef(bridge, rhs)) + DefDef(bridge, rhs) } } diff --git a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala index d6a6e027cb..a2bf5bf9e5 100644 --- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala +++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala @@ -90,7 +90,7 @@ abstract class ExplicitOuter extends InfoTransform sym expandName clazz sym.referenced = clazz - sym setInfo MethodType(Nil, restpe) + sym setInfo MethodType(Nil, restpe.widen) } def newOuterField(clazz: Symbol) = { val accFlags = SYNTHETIC | ARTIFACT | PARAMACCESSOR | ( if (clazz.isEffectivelyFinal) PrivateLocal else PROTECTED ) @@ -216,7 +216,7 @@ abstract class ExplicitOuter extends InfoTransform * values for outer parameters of constructors. * The class provides methods for referencing via outer. */ - abstract class OuterPathTransformer(unit: CompilationUnit) extends TypingTransformer(unit) { + abstract class OuterPathTransformer(unit: CompilationUnit) extends TypingTransformer(unit) with UnderConstructionTransformer { /** The directly enclosing outer parameter, if we are in a constructor */ protected var outerParam: Symbol = NoSymbol @@ -225,9 +225,10 @@ abstract class ExplicitOuter extends InfoTransform * * Will return `EmptyTree` if there is no outer accessor because of a premature self reference. */ - protected def outerValue: Tree = - if (outerParam != NoSymbol) ID(outerParam) - else outerSelect(THIS(currentClass)) + protected def outerValue: Tree = outerParam match { + case NoSymbol => outerSelect(gen.mkAttributedThis(currentClass)) + case outerParam => gen.mkAttributedIdent(outerParam) + } /** Select and apply outer accessor from 'base' * The result is typed but not positioned. @@ -276,16 +277,6 @@ abstract class ExplicitOuter extends InfoTransform } - /** The stack of class symbols in which a call to this() or to the super - * constructor, or early definition is active - */ - protected def isUnderConstruction(clazz: Symbol) = selfOrSuperCalls contains clazz - protected val selfOrSuperCalls = mutable.Stack[Symbol]() - @inline protected def inSelfOrSuperCall[A](sym: Symbol)(a: => A) = { - selfOrSuperCalls push sym - try a finally selfOrSuperCalls.pop() - } - override def transform(tree: Tree): Tree = { val savedOuterParam = outerParam try { @@ -299,10 +290,7 @@ abstract class ExplicitOuter extends InfoTransform } case _ => } - if ((treeInfo isSelfOrSuperConstrCall tree) || (treeInfo isEarlyDef tree)) - inSelfOrSuperCall(currentOwner.owner)(super.transform(tree)) - else - super.transform(tree) + super.transform(tree) } finally outerParam = savedOuterParam } @@ -368,8 +356,7 @@ abstract class ExplicitOuter extends InfoTransform /** The definition tree of the outer accessor of current class */ - def outerFieldDef: Tree = - VAL(outerField(currentClass)) === EmptyTree + def outerFieldDef: Tree = ValDef(outerField(currentClass)) /** The definition tree of the outer accessor of current class */ diff --git a/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala b/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala index 1c32721444..6a405295cf 100644 --- a/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala +++ b/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala @@ -205,7 +205,7 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { def makeExtensionMethodSymbol = { val extensionName = extensionNames(origMeth).head.toTermName val extensionMeth = ( - companion.moduleClass.newMethod(extensionName, origMeth.pos, origMeth.flags & ~OVERRIDE & ~PROTECTED | FINAL) + companion.moduleClass.newMethod(extensionName, tree.pos.focus, origMeth.flags & ~OVERRIDE & ~PROTECTED | FINAL) setAnnotations origMeth.annotations ) origMeth.removeAnnotation(TailrecClass) // it's on the extension method, now. @@ -234,10 +234,10 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { if (extensionBody.tpe <:< extensionMono.finalResultType) extensionBody else - gen.mkCastPreservingAnnotations(extensionBody, extensionMono.finalResultType) // SI-7818 e.g. mismatched existential skolems + gen.mkCastPreservingAnnotations(extensionBody, extensionMono.finalResultType) // SI-7818 e.g. mismatched existential skolems // Record the extension method. Later, in `Extender#transformStats`, these will be added to the companion object. - extensionDefs(companion) += atPos(tree.pos)(DefDef(extensionMeth, castBody)) + extensionDefs(companion) += DefDef(extensionMeth, castBody) // These three lines are assembling Foo.bar$extension[T1, T2, ...]($this) // which leaves the actual argument application for extensionCall. @@ -294,7 +294,7 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { val origThis = extensionMeth.owner.companionClass val baseType = qual.tpe.baseType(origThis) val allTargs = targs.map(_.tpe) ::: baseType.typeArgs - val fun = gen.mkAttributedTypeApply(THIS(extensionMeth.owner), extensionMeth, allTargs) + val fun = gen.mkAttributedTypeApply(gen.mkAttributedThis(extensionMeth.owner), extensionMeth, allTargs) allArgss.foldLeft(fun)(Apply(_, _)) } case _ => super.transform(tree) diff --git a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala index 515fa66cfa..acef2a50d8 100644 --- a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala +++ b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala @@ -436,8 +436,15 @@ abstract class LambdaLift extends InfoTransform { private def liftDef(tree: Tree): Tree = { val sym = tree.symbol val oldOwner = sym.owner - if (sym.owner.isAuxiliaryConstructor && sym.isMethod) // # bug 1909 - sym setFlag STATIC + if (sym.isMethod && isUnderConstruction(sym.owner.owner)) { // # bug 1909 + if (sym.isModule) { // Yes, it can be a module and a method, see comments on `isModuleNotMethod`! + // TODO promote to an implementation restriction if we can reason that this *always* leads to VerifyError. + // See neg/t1909-object.scala + def msg = s"SI-1909 Unable to STATICally lift $sym, which is defined in the self- or super-constructor call of ${sym.owner.owner}. A VerifyError is likely." + devWarning(tree.pos, msg) + } else sym setFlag STATIC + } + sym.owner = sym.owner.enclClass if (sym.isClass) sym.owner = sym.owner.toInterface if (sym.isMethod) sym setFlag LIFTED diff --git a/src/compiler/scala/tools/nsc/transform/LazyVals.scala b/src/compiler/scala/tools/nsc/transform/LazyVals.scala index 15ca916ac1..b71d14a04f 100644 --- a/src/compiler/scala/tools/nsc/transform/LazyVals.scala +++ b/src/compiler/scala/tools/nsc/transform/LazyVals.scala @@ -199,14 +199,15 @@ abstract class LazyVals extends Transform with TypingTransformers with ast.TreeD if (bitmaps.contains(lzyVal)) bitmaps(lzyVal).map(_.owner = defSym) val rhs: Tree = (gen.mkSynchronizedCheck(clazz, cond, syncBody, stats)).changeOwner(currentOwner -> defSym) - DEF(defSym).mkTree(addBitmapDefs(lzyVal, BLOCK(rhs, retVal))) setSymbol defSym + + DefDef(defSym, addBitmapDefs(lzyVal, BLOCK(rhs, retVal))) } def mkFastPathBody(clazz: Symbol, lzyVal: Symbol, cond: Tree, syncBody: List[Tree], stats: List[Tree], retVal: Tree): (Tree, Tree) = { val slowPathDef: Tree = mkSlowPathDef(clazz, lzyVal, cond, syncBody, stats, retVal) - (If(cond, Apply(ID(slowPathDef.symbol), List()), retVal), slowPathDef) + (If(cond, Apply(Ident(slowPathDef.symbol), Nil), retVal), slowPathDef) } /** return a 'lazified' version of rhs. Rhs should conform to the diff --git a/src/compiler/scala/tools/nsc/transform/Mixin.scala b/src/compiler/scala/tools/nsc/transform/Mixin.scala index 3ec4d16bf5..7b545be07e 100644 --- a/src/compiler/scala/tools/nsc/transform/Mixin.scala +++ b/src/compiler/scala/tools/nsc/transform/Mixin.scala @@ -472,7 +472,6 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { /** The typer */ private var localTyper: erasure.Typer = _ private def typedPos(pos: Position)(tree: Tree): Tree = localTyper.typedPos(pos)(tree) - private def localTyped(pos: Position, tree: Tree, pt: Type) = localTyper.typed(atPos(pos)(tree), pt) /** Map lazy values to the fields they should null after initialization. */ private var lazyValNullables: Map[Symbol, Set[Symbol]] = _ @@ -695,10 +694,10 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { */ def completeSuperAccessor(stat: Tree) = stat match { case DefDef(_, _, _, vparams :: Nil, _, EmptyTree) if stat.symbol.isSuperAccessor => - val rhs0 = (Super(clazz, tpnme.EMPTY) DOT stat.symbol.alias)(vparams map (v => Ident(v.symbol)): _*) - val rhs1 = localTyped(stat.pos, rhs0, stat.symbol.tpe.resultType) + val body = atPos(stat.pos)(Apply(Select(Super(clazz, tpnme.EMPTY), stat.symbol.alias), vparams map (v => Ident(v.symbol)))) + val pt = stat.symbol.tpe.resultType - deriveDefDef(stat)(_ => enteringMixin(transform(rhs1))) + copyDefDef(stat)(rhs = enteringMixin(transform(localTyper.typed(body, pt)))) case _ => stat } @@ -724,8 +723,8 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { case _ => } val init = bitmapKind match { - case BooleanClass => VAL(sym) === FALSE - case _ => VAL(sym) === ZERO + case BooleanClass => ValDef(sym, FALSE) + case _ => ValDef(sym, ZERO) } sym setFlag PrivateLocal @@ -775,7 +774,7 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { defSym setInfoAndEnter MethodType(params, lzyVal.tpe.resultType) val rhs: Tree = (gen.mkSynchronizedCheck(attrThis, cond, syncBody, stats)).changeOwner(currentOwner -> defSym) val strictSubst = new TreeSymSubstituterWithCopying(args.map(_.symbol), params) - addDef(position(defSym), DEF(defSym).mkTree(strictSubst(BLOCK(rhs, retVal))) setSymbol defSym) + addDef(position(defSym), DefDef(defSym, strictSubst(BLOCK(rhs, retVal)))) defSym } diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala index 4bc4e06fa7..5a440039d6 100644 --- a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala +++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala @@ -1836,12 +1836,12 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { } // ctor - mbrs += atPos(m.pos)(DefDef(m, Modifiers(m.flags), mmap(List(vparams))(ValDef), EmptyTree)) + mbrs += DefDef(m, Modifiers(m.flags), mmap(List(vparams))(ValDef), EmptyTree) } else { - mbrs += atPos(m.pos)(DefDef(m, { paramss => EmptyTree })) + mbrs += DefDef(m, { paramss => EmptyTree }) } } else if (m.isValue) { - mbrs += ValDef(m, EmptyTree).setType(NoType).setPos(m.pos) + mbrs += ValDef(m).setType(NoType) } else if (m.isClass) { // mbrs += // ClassDef(m, Template(m.info.parents map TypeTree, emptyValDef, List()) @@ -1853,9 +1853,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { val isSpecializedInstance = sClass :: sClass.parentSymbols exists (_ hasFlag SPECIALIZED) val sym = sClass.newMethod(nme.SPECIALIZED_INSTANCE, sClass.pos) setInfoAndEnter MethodType(Nil, BooleanTpe) - mbrs += atPos(sym.pos) { - DefDef(sym, Literal(Constant(isSpecializedInstance)).setType(BooleanTpe)).setType(NoType) - } + mbrs += DefDef(sym, Literal(Constant(isSpecializedInstance)).setType(BooleanTpe)).setType(NoType) } mbrs.toList } diff --git a/src/compiler/scala/tools/nsc/transform/TailCalls.scala b/src/compiler/scala/tools/nsc/transform/TailCalls.scala index 6f422fcc90..b471d16ddd 100644 --- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala +++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala @@ -156,7 +156,7 @@ abstract class TailCalls extends Transform { private def mkLabel() = { val label = method.newLabel(newTermName("_" + method.name), method.pos) val thisParam = method.newSyntheticValueParam(currentClass.typeOfThis) - label setInfo MethodType(thisParam :: method.tpe.params, method.tpe.finalResultType) + label setInfo MethodType(thisParam :: method.tpe.params, method.tpe_*.finalResultType) if (isEligible) label substInfo (method.tpe.typeParams, tparams) diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 16c803e2e8..e68f55a09e 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -158,11 +158,12 @@ abstract class UnCurry extends InfoTransform */ private def nonLocalReturnTry(body: Tree, key: Symbol, meth: Symbol) = { localTyper typed { - val extpe = nonLocalReturnExceptionType(meth.tpe.finalResultType) + val restpe = meth.tpe_*.finalResultType + val extpe = nonLocalReturnExceptionType(restpe) val ex = meth.newValue(nme.ex, body.pos) setInfo extpe - val argType = meth.tpe.finalResultType withAnnotation (AnnotationInfo marker UncheckedClass.tpe) + val argType = restpe withAnnotation (AnnotationInfo marker UncheckedClass.tpe) val pat = gen.mkBindForCase(ex, NonLocalReturnControlClass, List(argType)) - val rhs = ( + val rhs = ( IF ((ex DOT nme.key)() OBJ_EQ Ident(key)) THEN ((ex DOT nme.value)()) ELSE (Throw(Ident(ex))) @@ -739,7 +740,7 @@ abstract class UnCurry extends InfoTransform case p if rpsymbols(p.symbol) => toArrayType(p.symbol.tpe) case p => p.symbol.tpe } - val forwresult = dd.symbol.tpe.finalResultType + val forwresult = dd.symbol.tpe_*.finalResultType val forwformsyms = map2(forwformals, flatparams)((tp, oldparam) => currentClass.newValueParameter(oldparam.name, oldparam.symbol.pos).setInfo(tp) ) @@ -751,10 +752,11 @@ abstract class UnCurry extends InfoTransform // create the symbol val forwsym = currentClass.newMethod(dd.name.toTermName, dd.pos, VARARGS | SYNTHETIC | flatdd.symbol.flags) setInfo forwtype + def forwParams = forwsym.info.paramss.flatten // create the tree val forwtree = theTyper.typedPos(dd.pos) { - val locals = map2(forwsym ARGS, flatparams) { + val locals = map2(forwParams, flatparams) { case (_, fp) if !rpsymbols(fp.symbol) => null case (argsym, fp) => Block(Nil, @@ -764,15 +766,13 @@ abstract class UnCurry extends InfoTransform ) ) } - val seqargs = map2(locals, forwsym ARGS) { + val seqargs = map2(locals, forwParams) { case (null, argsym) => Ident(argsym) case (l, _) => l } val end = if (forwsym.isConstructor) List(UNIT) else Nil - DEF(forwsym) === BLOCK( - Apply(gen.mkAttributedRef(flatdd.symbol), seqargs) :: end : _* - ) + DefDef(forwsym, BLOCK(Apply(gen.mkAttributedRef(flatdd.symbol), seqargs) :: end : _*)) } // check if the method with that name and those arguments already exists in the template diff --git a/src/compiler/scala/tools/nsc/transform/patmat/MatchCodeGen.scala b/src/compiler/scala/tools/nsc/transform/patmat/MatchCodeGen.scala index cf74f0fb11..c8dbbb02bb 100644 --- a/src/compiler/scala/tools/nsc/transform/patmat/MatchCodeGen.scala +++ b/src/compiler/scala/tools/nsc/transform/patmat/MatchCodeGen.scala @@ -170,7 +170,7 @@ trait MatchCodeGen extends Interface { } toList // at most 1 element // scrutSym == NoSymbol when generating an alternatives matcher - val scrutDef = scrutSym.fold(List[Tree]())(sym => (VAL(sym) === scrut) :: Nil) // for alternatives + val scrutDef = scrutSym.fold(List[Tree]())(ValDef(_, scrut) :: Nil) // for alternatives // the generated block is taken apart in TailCalls under the following assumptions // the assumption is once we encounter a case, the remainder of the block will consist of cases @@ -199,7 +199,7 @@ trait MatchCodeGen extends Interface { def flatMap(prev: Tree, b: Symbol, next: Tree): Tree = { val prevSym = freshSym(prev.pos, prev.tpe, "o") BLOCK( - VAL(prevSym) === prev, + ValDef(prevSym, prev), // must be isEmpty and get as we don't control the target of the call (prev is an extractor call) ifThenElseZero( NOT(prevSym DOT vpmName.isEmpty), @@ -214,14 +214,12 @@ trait MatchCodeGen extends Interface { // next == MatchMonad[U] // returns MatchMonad[U] def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree = { - val rest = + val rest = ( // only emit a local val for `nextBinder` if it's actually referenced in `next` if (next.exists(_.symbol eq nextBinder)) - BLOCK( - VAL(nextBinder) === res, - next - ) + BLOCK(ValDef(nextBinder, res), next) else next + ) ifThenElseZero(cond, rest) } diff --git a/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala b/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala index ec45789687..ba78438b66 100644 --- a/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala +++ b/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala @@ -146,7 +146,7 @@ trait MatchOptimization extends MatchTreeMaking with MatchAnalysis { lazy val storedCond = freshSym(pos, BooleanTpe, "rc") setFlag MUTABLE lazy val treesToHoist: List[Tree] = { nextBinder setFlag MUTABLE - List(storedCond, nextBinder) map { b => VAL(b) === codegen.mkZero(b.info) } + List(storedCond, nextBinder) map (b => ValDef(b, codegen.mkZero(b.info))) } // TODO: finer-grained duplication @@ -528,7 +528,7 @@ trait MatchOptimization extends MatchTreeMaking with MatchAnalysis { } def defaultSym: Symbol = scrutSym - def defaultBody: Tree = { import CODE._; matchFailGenOverride map (gen => gen(REF(scrutSym))) getOrElse MATCHERROR(REF(scrutSym)) } + def defaultBody: Tree = { import CODE._; matchFailGenOverride map (gen => gen(REF(scrutSym))) getOrElse Throw(MatchErrorClass.tpe, REF(scrutSym)) } def defaultCase(scrutSym: Symbol = defaultSym, guard: Tree = EmptyTree, body: Tree = defaultBody): CaseDef = { import CODE._; atPos(body.pos) { (DEFAULT IF guard) ==> body }} @@ -546,7 +546,7 @@ trait MatchOptimization extends MatchTreeMaking with MatchAnalysis { if (scrutSym.tpe =:= IntTpe) REF(scrutSym) else (REF(scrutSym) DOT (nme.toInt)) Some(BLOCK( - VAL(scrutSym) === scrut, + ValDef(scrutSym, scrut), Match(scrutToInt, caseDefsWithDefault) // a switch )) } diff --git a/src/compiler/scala/tools/nsc/transform/patmat/MatchTreeMaking.scala b/src/compiler/scala/tools/nsc/transform/patmat/MatchTreeMaking.scala index 942aa80c34..cf26ec3398 100644 --- a/src/compiler/scala/tools/nsc/transform/patmat/MatchTreeMaking.scala +++ b/src/compiler/scala/tools/nsc/transform/patmat/MatchTreeMaking.scala @@ -174,7 +174,7 @@ trait MatchTreeMaking extends MatchCodeGen with Debugging { else { // only store binders actually used val (subPatBindersStored, subPatRefsStored) = stored.filter{case (b, _) => usedBinders(b)}.unzip - Block(map2(subPatBindersStored.toList, subPatRefsStored.toList)(VAL(_) === _), in) + Block(map2(subPatBindersStored.toList, subPatRefsStored.toList)(ValDef(_, _)), in) } } } @@ -328,9 +328,9 @@ trait MatchTreeMaking extends MatchCodeGen with Debugging { def outerTest(testedBinder: Symbol, expectedTp: Type): Tree = { val expectedOuter = expectedTp.prefix match { - case ThisType(clazz) => THIS(clazz) - case pre if pre != NoType => REF(pre.prefix, pre.termSymbol) - case _ => mkTRUE // fallback for SI-6183 + case ThisType(clazz) => This(clazz) + case NoType => mkTRUE // fallback for SI-6183 + case pre => REF(pre.prefix, pre.termSymbol) } // ExplicitOuter replaces `Select(q, outerSym) OBJ_EQ expectedPrefix` by `Select(q, outerAccessor(outerSym.owner)) OBJ_EQ expectedPrefix` @@ -527,8 +527,9 @@ trait MatchTreeMaking extends MatchCodeGen with Debugging { // pt is the fully defined type of the cases (either pt or the lub of the types of the cases) def combineCasesNoSubstOnly(scrut: Tree, scrutSym: Symbol, casesNoSubstOnly: List[List[TreeMaker]], pt: Type, owner: Symbol, matchFailGenOverride: Option[Tree => Tree]): Tree = - fixerUpper(owner, scrut.pos){ - def matchFailGen = (matchFailGenOverride orElse Some(CODE.MATCHERROR(_: Tree))) + fixerUpper(owner, scrut.pos) { + def matchFailGen = matchFailGenOverride orElse Some(Throw(MatchErrorClass.tpe, _: Tree)) + debug.patmat("combining cases: "+ (casesNoSubstOnly.map(_.mkString(" >> ")).mkString("{", "\n", "}"))) val (suppression, requireSwitch): (Suppression, Boolean) = diff --git a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala index 263b5ad784..ec2b7d49f5 100644 --- a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala +++ b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala @@ -21,32 +21,17 @@ trait MethodSynthesis { import definitions._ import CODE._ - object synthesisUtil { - type TT[T] = ru.TypeTag[T] - type CT[T] = ClassTag[T] - - def newValOrDefDef(sym: Symbol, body: Tree) = - if (sym.isLazy) ValDef(sym, body) - else DefDef(sym, body) - - /** The annotations amongst those found on the original symbol which - * should be propagated to this kind of accessor. - */ - def deriveAnnotations(initial: List[AnnotationInfo], category: Symbol, keepClean: Boolean): List[AnnotationInfo] = { - initial filter { ann => - // There are no meta-annotation arguments attached to `ann` - if (ann.metaAnnotations.isEmpty) { - // A meta-annotation matching `annotKind` exists on `ann`'s definition. - (ann.defaultTargets contains category) || - // `ann`'s definition has no meta-annotations, and `keepClean` is true. - (ann.defaultTargets.isEmpty && keepClean) - } - // There are meta-annotation arguments, and one of them matches `annotKind` - else ann.metaAnnotations exists (_ matches category) - } + /** The annotations amongst those found on the original symbol which + * should be propagated to this kind of accessor. + */ + def deriveAnnotations(initial: List[AnnotationInfo], category: Symbol, keepClean: Boolean): List[AnnotationInfo] = { + def annotationFilter(ann: AnnotationInfo) = ann.metaAnnotations match { + case Nil if ann.defaultTargets.isEmpty => keepClean // no meta-annotations or default targets + case Nil => ann.defaultTargets contains category // default targets exist for ann + case metas => metas exists (_ matches category) // meta-annotations attached to ann } + initial filter annotationFilter } - import synthesisUtil._ class ClassMethodSynthesis(val clazz: Symbol, localTyper: Typer) { def mkThis = This(clazz) setPos clazz.pos.focus @@ -67,7 +52,10 @@ trait MethodSynthesis { } private def finishMethod(method: Symbol, f: Symbol => Tree): Tree = - localTyper typed newValOrDefDef(method, f(method)) + localTyper typed ( + if (method.isLazy) ValDef(method, f(method)) + else DefDef(method, f(method)) + ) private def createInternal(name: Name, f: Symbol => Tree, info: Type): Tree = { val name1 = name.toTermName @@ -105,7 +93,7 @@ trait MethodSynthesis { def createSwitchMethod(name: Name, range: Seq[Int], returnType: Type)(f: Int => Tree) = { createMethod(name, List(IntTpe), returnType) { m => val arg0 = Ident(m.firstParam) - val default = DEFAULT ==> THROW(IndexOutOfBoundsExceptionClass, arg0) + val default = DEFAULT ==> Throw(IndexOutOfBoundsExceptionClass.tpe_*, fn(arg0, nme.toString_)) val cases = range.map(num => CASE(LIT(num)) ==> f(num)).toList :+ default Match(arg0, cases) @@ -393,18 +381,9 @@ trait MethodSynthesis { } } case class Getter(tree: ValDef) extends BaseGetter(tree) { - override def derivedSym = ( - if (mods.isDeferred) basisSym - else basisSym.getter(enclClass) - ) - // Range position errors ensue if we don't duplicate this in some - // circumstances (at least: concrete vals with existential types.) - private def tptOriginal = ( - if (mods.isDeferred) tree.tpt // keep type tree of original abstract field - else tree.tpt.duplicate setPos tree.tpt.pos.focus // focused position of original tpt - ) - - override def derivedTree: DefDef = { + override def derivedSym = if (mods.isDeferred) basisSym else basisSym.getter(enclClass) + private def derivedRhs = if (mods.isDeferred) EmptyTree else fieldSelection + private def derivedTpt = { // For existentials, don't specify a type for the getter, even one derived // from the symbol! This leads to incompatible existentials for the field and // the getter. Let the typer do all the work. You might think "why only for @@ -413,24 +392,16 @@ trait MethodSynthesis { // starts compiling (instead of failing like it's supposed to) because the typer // expects to be able to identify escaping locals in typedDefDef, and fails to // spot that brand of them. In other words it's an artifact of the implementation. - val tpt = atPos(derivedSym.pos.focus)(derivedSym.tpe.finalResultType match { - case ExistentialType(_, _) => TypeTree() - case _ if mods.isDeferred => TypeTree() + val tpt = derivedSym.tpe_*.finalResultType.widen match { + // Range position errors ensue if we don't duplicate this in some + // circumstances (at least: concrete vals with existential types.) + case ExistentialType(_, _) => TypeTree() setOriginal (tree.tpt.duplicate setPos tree.tpt.pos.focus) + case _ if mods.isDeferred => TypeTree() setOriginal tree.tpt // keep type tree of original abstract field case tp => TypeTree(tp) - }) - // TODO - reconcile this with the DefDef creator in Trees (which - // at this writing presented no way to pass a tree in for tpt.) - atPos(derivedSym.pos) { - DefDef( - Modifiers(derivedSym.flags), - derivedSym.name.toTermName, - Nil, - Nil, - tpt setOriginal tptOriginal, - if (mods.isDeferred) EmptyTree else fieldSelection - ) setSymbol derivedSym } + tpt setPos tree.tpt.pos.focus } + override def derivedTree: DefDef = newDefDef(derivedSym, derivedRhs)(tpt = derivedTpt) } /** Implements lazy value accessors: * - for lazy values of type Unit and all lazy fields inside traits, @@ -461,8 +432,8 @@ trait MethodSynthesis { if (tree.symbol.owner.isTrait || hasUnitType(basisSym)) rhs1 else gen.mkAssignAndReturn(basisSym, rhs1) ) - derivedSym.setPos(tree.pos) // cannot set it at createAndEnterSymbol because basisSym can possible stil have NoPosition - val ddefRes = atPos(tree.pos)(DefDef(derivedSym, new ChangeOwnerAndModuleClassTraverser(basisSym, derivedSym)(body))) + derivedSym setPos tree.pos // cannot set it at createAndEnterSymbol because basisSym can possible stil have NoPosition + val ddefRes = DefDef(derivedSym, new ChangeOwnerAndModuleClassTraverser(basisSym, derivedSym)(body)) // ValDef will have its position focused whereas DefDef will have original correct rangepos // ideally positions would be correct at the creation time but lazy vals are really a special case // here so for the sake of keeping api clean we fix positions manually in LazyValGetter diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index 454f913412..9ac0b0835a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -135,7 +135,8 @@ trait Namers extends MethodSynthesis { setPrivateWithin(tree, sym, tree.mods) def inConstructorFlag: Long = { - val termOwnedContexts: List[Context] = context.enclosingContextChain.takeWhile(_.owner.isTerm) + val termOwnedContexts: List[Context] = + context.enclosingContextChain.takeWhile(c => c.owner.isTerm && !c.owner.isAnonymousFunction) val constructorNonSuffix = termOwnedContexts exists (c => c.owner.isConstructor && !c.inConstructorSuffix) val earlyInit = termOwnedContexts exists (_.owner.isEarlyInitialized) if (constructorNonSuffix || earlyInit) INCONSTRUCTOR else 0L diff --git a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala index 12d6bb2e6a..b706e1af6b 100644 --- a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala @@ -296,8 +296,8 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT } transformSelect - case DefDef(mods, name, tparams, vparamss, tpt, rhs) if tree.symbol.isMethodWithExtension => - treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt, withInvalidOwner(transform(rhs))) + case DefDef(_, _, _, _, _, _) if tree.symbol.isMethodWithExtension => + deriveDefDef(tree)(rhs => withInvalidOwner(transform(rhs))) case TypeApply(sel @ Select(qual, name), args) => mayNeedProtectedAccessor(sel, args, goToSuper = true) diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 629513ada3..3ac0b398ee 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -363,7 +363,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper check(owner, scope, pt, tree setType tp1.typeSymbol.classBound) else if (owner == NoSymbol) tree setType packSymbols(hiddenSymbols.reverse, tp1) - else if (!phase.erasedTypes) { // privates + else if (!isPastTyper) { // privates val badSymbol = hiddenSymbols.head SymbolEscapesScopeError(tree, badSymbol) } else tree @@ -2103,7 +2103,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper case PolyType(_, restpe) => paramssTypes(restpe) case _ => Nil } - def resultType = meth.tpe.finalResultType + def resultType = meth.tpe_*.finalResultType def nthParamPos(n1: Int, n2: Int) = try ddef.vparamss(n1)(n2).pos catch { case _: IndexOutOfBoundsException => meth.pos } @@ -2598,8 +2598,15 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper default -> gen.scalaFunctionConstr(List(A1Tpt), B1Tpt) ) } - val rhs = methodBodyTyper.virtualizedMatch(match_, mode, B1.tpe) - val defdef = DefDef(methodSym, Modifiers(methodSym.flags), originals, rhs) + def newParam(param: Symbol): ValDef = { + val vd = ValDef(param, EmptyTree) + val tt @ TypeTree() = vd.tpt + tt setOriginal (originals(param) setPos param.pos.focus) + vd + } + + val rhs = methodBodyTyper.virtualizedMatch(match_, mode, B1.tpe) + val defdef = newDefDef(methodSym, rhs)(vparamss = mapParamss(methodSym)(newParam)) (defdef, matchResTp) } diff --git a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala index 5049fec65b..af19e3cf80 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala @@ -46,11 +46,8 @@ trait Unapplies extends ast.TreeDSL { def copyUntyped[T <: Tree](tree: T): T = returning[T](tree.duplicate)(UnTyper traverse _) - def copyUntypedInvariant(td: TypeDef): TypeDef = { - val copy = treeCopy.TypeDef(td, td.mods &~ (COVARIANT | CONTRAVARIANT), td.name, td.tparams, td.rhs) - - returning[TypeDef](copy.duplicate)(UnTyper traverse _) - } + def copyUntypedInvariant(td: TypeDef): TypeDef = + copyTypeDef(copyUntyped(td))(mods = td.mods &~ (COVARIANT | CONTRAVARIANT)) private def toIdent(x: DefTree) = Ident(x.name) setPos x.pos.focus diff --git a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala index 57ebe1b30d..b77a536caf 100644 --- a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala +++ b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala @@ -273,15 +273,9 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => def parse(code: String): Tree = { reporter.reset() - val file = new BatchSourceFile("<toolbox>", code) - val unit = new CompilationUnit(file) - val parsed = newUnitParser(unit).parseStats() + val tree = gen.mkTreeOrBlock(newUnitParser(code, "<toolbox>").parseStats()) throwIfErrors() - parsed match { - case Nil => EmptyTree - case expr :: Nil => expr - case stats :+ expr => Block(stats, expr) - } + tree } def showAttributed(artifact: Any, printTypes: Boolean = true, printIds: Boolean = true, printKinds: Boolean = false): String = { @@ -355,7 +349,8 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => } def inferImplicitView(tree: u.Tree, from: u.Type, to: u.Type, silent: Boolean = true, withMacrosDisabled: Boolean = false, pos: u.Position = u.NoPosition): u.Tree = { - val viewTpe = u.appliedType(u.definitions.FunctionClass(1).toTypeConstructor, List(from, to)) + val functionTypeCtor = u.definitions.FunctionClass(1).asClass.toTypeConstructor + val viewTpe = u.appliedType(functionTypeCtor, List(from, to)) inferImplicit(tree, viewTpe, isView = true, silent = silent, withMacrosDisabled = withMacrosDisabled, pos = pos) } diff --git a/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala b/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala index 19888fa8d2..5a1a25cfa1 100644 --- a/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala +++ b/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala @@ -49,7 +49,7 @@ trait Parsers { self: Quasiquotes => def entryPoint: QuasiquoteParser => Tree - class QuasiquoteParser(source0: SourceFile) extends SourceFileParser(source0) { + class QuasiquoteParser(source0: SourceFile) extends SourceFileParser(source0) { parser => def isHole: Boolean = isIdent && isHole(in.name) def isHole(name: Name): Boolean = holeMap.contains(name) @@ -73,7 +73,7 @@ trait Parsers { self: Quasiquotes => override def makeFunctionTypeTree(argtpes: List[Tree], restpe: Tree): Tree = AppliedTypeTree(Ident(tpnme.QUASIQUOTE_FUNCTION), argtpes :+ restpe) } - import treeBuilder.{global => _, _} + import treeBuilder.{global => _, unit => _, _} // q"def foo($x)" override def allowTypelessParams = true @@ -144,11 +144,7 @@ trait Parsers { self: Quasiquotes => } object TermParser extends Parser { - def entryPoint = _.templateStats() match { - case Nil => EmptyTree - case tree :: Nil => tree - case stats :+ tree => Block(stats, tree) - } + def entryPoint = { parser => gen.mkTreeOrBlock(parser.templateStats()) } } object TypeParser extends Parser { diff --git a/src/compiler/scala/tools/reflect/quasiquotes/Reifiers.scala b/src/compiler/scala/tools/reflect/quasiquotes/Reifiers.scala index af4e34536c..c2d8bcdcd6 100644 --- a/src/compiler/scala/tools/reflect/quasiquotes/Reifiers.scala +++ b/src/compiler/scala/tools/reflect/quasiquotes/Reifiers.scala @@ -228,6 +228,8 @@ trait Reifiers { self: Quasiquotes => override def reifyTreeSyntactically(tree: Tree): Tree = tree match { case RefTree(qual, SymbolPlaceholder(tree)) => mirrorBuildCall(nme.RefTree, reify(qual), tree) + case This(SymbolPlaceholder(tree)) => + mirrorCall(nme.This, tree) case _ => super.reifyTreeSyntactically(tree) } diff --git a/src/intellij/setup.sh b/src/intellij/setup.sh index d0e1abeb96..bd324ba5bd 100755 --- a/src/intellij/setup.sh +++ b/src/intellij/setup.sh @@ -9,7 +9,7 @@ export BASE="$( cd "$( dirname "$0" )"/../.. && pwd )" echo "About to delete .ipr and .iml files and replace with the .SAMPLE files. Press enter to continue or CTRL-C to cancel." read -(rm *.ipr *.iml 2>/dev/null) +(rm -f *.ipr *.iml 2>/dev/null) for f in $(ls "$SCRIPT_DIR"/*.SAMPLE); do NEW_FILE=`echo $f | perl -pe 's/.SAMPLE//'`; diff --git a/src/library/scala/Function0.scala b/src/library/scala/Function0.scala index 54cba021e0..e13aaad7bc 100644 --- a/src/library/scala/Function0.scala +++ b/src/library/scala/Function0.scala @@ -6,7 +6,7 @@ ** |/ ** \* */ // GENERATED CODE: DO NOT EDIT. -// genprod generated these sources at: Sun Mar 24 14:14:12 CET 2013 +// genprod generated these sources at: Sun Sep 15 20:42:00 CEST 2013 package scala diff --git a/src/library/scala/Function1.scala b/src/library/scala/Function1.scala index 2e3de54c5a..620dcc19aa 100644 --- a/src/library/scala/Function1.scala +++ b/src/library/scala/Function1.scala @@ -32,7 +32,7 @@ package scala */ @annotation.implicitNotFound(msg = "No implicit view available from ${T1} => ${R}.") -trait Function1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double/*, scala.AnyRef*/) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double/*, scala.AnyRef*/) +R] extends AnyRef { self => +trait Function1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends AnyRef { self => /** Apply the body of this function to the argument. * @return the result of function application. */ diff --git a/src/library/scala/runtime/AbstractFunction1.scala b/src/library/scala/runtime/AbstractFunction1.scala index 8d68017a6f..178280cb46 100644 --- a/src/library/scala/runtime/AbstractFunction1.scala +++ b/src/library/scala/runtime/AbstractFunction1.scala @@ -9,6 +9,6 @@ package scala.runtime -abstract class AbstractFunction1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double/*, scala.AnyRef*/) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double/*, scala.AnyRef*/) +R] extends Function1[T1, R] { +abstract class AbstractFunction1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends Function1[T1, R] { } diff --git a/src/library/scala/runtime/AbstractPartialFunction.scala b/src/library/scala/runtime/AbstractPartialFunction.scala index e3516bc4d9..7129f22f60 100644 --- a/src/library/scala/runtime/AbstractPartialFunction.scala +++ b/src/library/scala/runtime/AbstractPartialFunction.scala @@ -25,7 +25,7 @@ import scala.annotation.unspecialized * @author Pavel Pavlov * @since 2.10 */ -abstract class AbstractPartialFunction[@specialized(scala.Int, scala.Long, scala.Float, scala.Double, scala.AnyRef) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double, scala.AnyRef) +R] extends Function1[T1, R] with PartialFunction[T1, R] { self => +abstract class AbstractPartialFunction[@specialized(scala.Int, scala.Long, scala.Float, scala.Double) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends Function1[T1, R] with PartialFunction[T1, R] { self => // this method must be overridden for better performance, // for backwards compatibility, fall back to the one inherited from PartialFunction // this assumes the old-school partial functions override the apply method, though @@ -35,3 +35,15 @@ abstract class AbstractPartialFunction[@specialized(scala.Int, scala.Long, scala // let's not make it final so as not to confuse anyone /*final*/ def apply(x: T1): R = applyOrElse(x, PartialFunction.empty) } + +// Manual stand-ins for formerly specialized variations. +// Not comprehensive, only sufficent to run scala-check built scala 2.11.0-M5 +// TODO Scala 2.10.0.M6 Remove this once scalacheck is published against M6. +private[runtime] abstract class AbstractPartialFunction$mcIL$sp extends scala.runtime.AbstractPartialFunction[Any, Int] { + override def apply(x: Any): Int = apply$mcIL$sp(x) + def apply$mcIL$sp(x: Any): Int = applyOrElse(x, PartialFunction.empty) +} +private[runtime] abstract class AbstractPartialFunction$mcFL$sp extends scala.runtime.AbstractPartialFunction[Any, Float] { + override def apply(x: Any): Float = apply$mcIL$sp(x) + def apply$mcIL$sp(x: Any): Float = applyOrElse(x, PartialFunction.empty) +} diff --git a/src/reflect/scala/reflect/api/FlagSets.scala b/src/reflect/scala/reflect/api/FlagSets.scala index 8a1d2f7f1d..3d5a213f2f 100644 --- a/src/reflect/scala/reflect/api/FlagSets.scala +++ b/src/reflect/scala/reflect/api/FlagSets.scala @@ -166,6 +166,9 @@ trait FlagSets { self: Universe => /** Flag indicating that tree represents a variable or a member initialized to the default value */ val DEFAULTINIT: FlagSet + + /** Flag indicating that tree was generated by the compiler */ + val SYNTHETIC: FlagSet } /** The empty set of flags diff --git a/src/reflect/scala/reflect/api/StandardDefinitions.scala b/src/reflect/scala/reflect/api/StandardDefinitions.scala index bbfebcb434..e255d305f7 100644 --- a/src/reflect/scala/reflect/api/StandardDefinitions.scala +++ b/src/reflect/scala/reflect/api/StandardDefinitions.scala @@ -214,29 +214,35 @@ trait StandardDefinitions { /** The module symbol of module `scala.Some`. */ def SomeModule: ModuleSymbol - /** The array of class symbols for classes `scala.ProductX`. + /** Function-like object that maps arity to symbols for classes `scala.ProductX`. * - 0th element is `Unit` * - 1st element is `Product1` * - ... * - 22nd element is `Product22` + * - 23nd element is `NoSymbol` + * - ... */ - def ProductClass : Array[ClassSymbol] + def ProductClass: Int => Symbol - /** The array of class symbols for classes `scala.FunctionX`. + /** Function-like object that maps arity to symbols for classes `scala.FunctionX`. * - 0th element is `Function0` * - 1st element is `Function1` * - ... * - 22nd element is `Function22` + * - 23nd element is `NoSymbol` + * - ... */ - def FunctionClass : Array[ClassSymbol] + def FunctionClass: Int => Symbol - /** The array of class symbols for classes `scala.TupleX`. + /** Function-like object that maps arity to symbols for classes `scala.TupleX`. * - 0th element is `NoSymbol` * - 1st element is `Product1` * - ... * - 22nd element is `Product22` + * - 23nd element is `NoSymbol` + * - ... */ - def TupleClass: Array[Symbol] // cannot make it Array[ClassSymbol], because TupleClass(0) is supposed to be NoSymbol. weird + def TupleClass: Int => Symbol /** Contains Scala primitive value classes: * - Byte diff --git a/src/reflect/scala/reflect/api/Trees.scala b/src/reflect/scala/reflect/api/Trees.scala index 443f34ccae..7a627bc875 100644 --- a/src/reflect/scala/reflect/api/Trees.scala +++ b/src/reflect/scala/reflect/api/Trees.scala @@ -2210,13 +2210,13 @@ trait Trees { self: Universe => * Flattens directly nested blocks. * @group Factories */ - @deprecated("Use the canonical Block constructor, explicitly specifying its expression if necessary. Flatten directly nested blocks manually if needed", "2.10.1") + @deprecated("Use q\"{..$stats}\" instead. Flatten directly nested blocks manually if needed", "2.10.1") def Block(stats: Tree*): Block /** A factory method for `CaseDef` nodes. * @group Factories */ - @deprecated("Use the canonical CaseDef constructor passing EmptyTree for guard", "2.10.1") + @deprecated("Use cq\"$pat => $body\" instead", "2.10.1") def CaseDef(pat: Tree, body: Tree): CaseDef /** A factory method for `Bind` nodes. @@ -2228,50 +2228,50 @@ trait Trees { self: Universe => /** A factory method for `Try` nodes. * @group Factories */ - @deprecated("Use canonical CaseDef constructors to to create exception catching expressions and then wrap them in Try", "2.10.1") + @deprecated("Convert cases into casedefs and use q\"try $body catch { case ..$newcases }\" instead", "2.10.1") def Try(body: Tree, cases: (Tree, Tree)*): Try /** A factory method for `Throw` nodes. * @group Factories */ - @deprecated("Use the canonical New constructor to create an object instantiation expression and then wrap it in Throw", "2.10.1") + @deprecated("Use q\"throw new $tpe(..$args)\" instead", "2.10.1") def Throw(tpe: Type, args: Tree*): Throw /** Factory method for object creation `new tpt(args_1)...(args_n)` * A `New(t, as)` is expanded to: `(new t).<init>(as)` * @group Factories */ - @deprecated("Use Apply(...Apply(Select(New(tpt), nme.CONSTRUCTOR), args1)...argsN) instead", "2.10.1") + @deprecated("Use q\"new $tpt(...$argss)\" instead", "2.10.1") def New(tpt: Tree, argss: List[List[Tree]]): Tree /** 0-1 argument list new, based on a type. * @group Factories */ - @deprecated("Use New(TypeTree(tpe), args.toList) instead", "2.10.1") + @deprecated("Use q\"new $tpe(..$args)\" instead", "2.10.1") def New(tpe: Type, args: Tree*): Tree /** 0-1 argument list new, based on a symbol. * @group Factories */ - @deprecated("Use New(sym.toType, args) instead", "2.10.1") + @deprecated("Use q\"new ${sym.toType}(..$args)\" instead", "2.10.1") def New(sym: Symbol, args: Tree*): Tree /** A factory method for `Apply` nodes. * @group Factories */ - @deprecated("Use Apply(Ident(sym), args.toList) instead", "2.10.1") + @deprecated("Use q\"$sym(..$args)\" instead", "2.10.1") def Apply(sym: Symbol, args: Tree*): Tree /** 0-1 argument list new, based on a type tree. * @group Factories */ - @deprecated("Use Apply(Select(New(tpt), nme.CONSTRUCTOR), args) instead", "2.10.1") + @deprecated("Use q\"new $tpt(..$args)\" instead", "2.10.1") def ApplyConstructor(tpt: Tree, args: List[Tree]): Tree /** A factory method for `Super` nodes. * @group Factories */ - @deprecated("Use Super(This(sym), mix) instead", "2.10.1") + @deprecated("Use q\"$sym.super[$mix].x\".qualifier instead", "2.10.1") def Super(sym: Symbol, mix: TypeName): Tree /** A factory method for `This` nodes. @@ -2283,7 +2283,7 @@ trait Trees { self: Universe => * The string `name` argument is assumed to represent a [[scala.reflect.api.Names#TermName `TermName`]]. * @group Factories */ - @deprecated("Use Select(tree, newTermName(name)) instead", "2.10.1") + @deprecated("Use Select(tree, TermName(name)) instead", "2.10.1") def Select(qualifier: Tree, name: String): Select /** A factory method for `Select` nodes. @@ -2294,7 +2294,7 @@ trait Trees { self: Universe => /** A factory method for `Ident` nodes. * @group Factories */ - @deprecated("Use Ident(newTermName(name)) instead", "2.10.1") + @deprecated("Use Ident(TermName(name)) instead", "2.10.1") def Ident(name: String): Ident /** A factory method for `Ident` nodes. diff --git a/src/reflect/scala/reflect/internal/BuildUtils.scala b/src/reflect/scala/reflect/internal/BuildUtils.scala index 06a6e10c30..2584dcb117 100644 --- a/src/reflect/scala/reflect/internal/BuildUtils.scala +++ b/src/reflect/scala/reflect/internal/BuildUtils.scala @@ -5,7 +5,7 @@ package internal import Flags._ trait BuildUtils { self: SymbolTable => - import definitions.{TupleClass, FunctionClass, MaxTupleArity, MaxFunctionArity, ScalaPackage, UnitClass} + import definitions.{TupleClass, FunctionClass, ScalaPackage, UnitClass} class BuildImpl extends BuildApi { @@ -271,32 +271,30 @@ trait BuildUtils { self: SymbolTable => } } private object TupleClassRef extends ScalaMemberRef { - val symbols = TupleClass.filter { _ != null }.toSeq + val symbols = TupleClass.seq } private object TupleCompanionRef extends ScalaMemberRef { - val symbols = TupleClassRef.symbols.map { _.companionModule } + val symbols = TupleClass.seq.map { _.companionModule } } private object UnitClassRef extends ScalaMemberRef { val symbols = Seq(UnitClass) } private object FunctionClassRef extends ScalaMemberRef { - val symbols = FunctionClass.toSeq + val symbols = FunctionClass.seq } object SyntacticTuple extends SyntacticTupleExtractor { def apply(args: List[Tree]): Tree = args match { case Nil => Literal(Constant(())) case _ => - require(args.length <= MaxTupleArity, s"Tuples with arity bigger than $MaxTupleArity aren't supported") + require(TupleClass(args.length).exists, s"Tuples with ${args.length} arity aren't supported") self.Apply(TupleClass(args.length).companionModule, args: _*) } def unapply(tree: Tree): Option[List[Tree]] = tree match { case Literal(Constant(())) => Some(Nil) - case Apply(TupleCompanionRef(sym), args) - if args.length <= MaxTupleArity - && sym == TupleClass(args.length).companionModule => + case Apply(TupleCompanionRef(sym), args) if sym == TupleClass(args.length).companionModule => Some(args) case _ => None @@ -307,15 +305,14 @@ trait BuildUtils { self: SymbolTable => def apply(args: List[Tree]): Tree = args match { case Nil => self.Select(self.Ident(nme.scala_), tpnme.Unit) case _ => - require(args.length <= MaxTupleArity, s"Tuples with arity bigger than $MaxTupleArity aren't supported") + require(TupleClass(args.length).exists, s"Tuples with ${args.length} arity aren't supported") AppliedTypeTree(Ident(TupleClass(args.length)), args) } def unapply(tree: Tree): Option[List[Tree]] = tree match { case UnitClassRef(_) => Some(Nil) - case AppliedTypeTree(TupleClassRef(sym), args) - if args.length <= MaxTupleArity && sym == TupleClass(args.length) => + case AppliedTypeTree(TupleClassRef(sym), args) if sym == TupleClass(args.length) => Some(args) case _ => None @@ -324,13 +321,12 @@ trait BuildUtils { self: SymbolTable => object SyntacticFunctionType extends SyntacticFunctionTypeExtractor { def apply(argtpes: List[Tree], restpe: Tree): Tree = { - require(argtpes.length <= MaxFunctionArity + 1, s"Function types with arity bigger than $MaxFunctionArity aren't supported") + require(FunctionClass(argtpes.length).exists, s"Function types with ${argtpes.length} arity aren't supported") gen.mkFunctionTypeTree(argtpes, restpe) } def unapply(tree: Tree): Option[(List[Tree], Tree)] = tree match { - case AppliedTypeTree(FunctionClassRef(sym), args @ (argtpes :+ restpe)) - if args.length - 1 <= MaxFunctionArity && sym == FunctionClass(args.length - 1) => + case AppliedTypeTree(FunctionClassRef(sym), args @ (argtpes :+ restpe)) if sym == FunctionClass(args.length - 1) => Some((argtpes, restpe)) case _ => None } diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index 90a1ab39d5..ed1c3f1044 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -585,30 +585,29 @@ trait Definitions extends api.StandardDefinitions { def hasJavaMainMethod(sym: Symbol): Boolean = (sym.tpe member nme.main).alternatives exists isJavaMainMethod - // Product, Tuple, Function, AbstractFunction - private def mkArityArray(name: String, arity: Int, countFrom: Int): Array[ClassSymbol] = { - val list = countFrom to arity map (i => getRequiredClass("scala." + name + i)) - list.toArray - } - def prepend[S >: ClassSymbol : ClassTag](elem0: S, elems: Array[ClassSymbol]): Array[S] = elem0 +: elems - - private def aritySpecificType[S <: Symbol](symbolArray: Array[S], args: List[Type], others: Type*): Type = { - val arity = args.length - if (arity >= symbolArray.length) NoType - else appliedType(symbolArray(arity), args ++ others: _*) + class VarArityClass(name: String, maxArity: Int, countFrom: Int = 0, init: Option[ClassSymbol] = None) extends (Int => Symbol) { + private val offset = countFrom - init.size + private def isDefinedAt(i: Int) = i < seq.length + offset && i >= offset + val seq: IndexedSeq[ClassSymbol] = (init ++: countFrom.to(maxArity).map { i => getRequiredClass("scala." + name + i) }).toVector + def apply(i: Int) = if (isDefinedAt(i)) seq(i - offset) else NoSymbol + def specificType(args: List[Type], others: Type*): Type = { + val arity = args.length + if (!isDefinedAt(arity)) NoType + else appliedType(apply(arity), args ++ others: _*) + } } val MaxTupleArity, MaxProductArity, MaxFunctionArity = 22 - lazy val ProductClass: Array[ClassSymbol] = prepend(UnitClass, mkArityArray("Product", MaxProductArity, 1)) - lazy val TupleClass: Array[Symbol] = prepend(null, mkArityArray("Tuple", MaxTupleArity, 1)) - lazy val FunctionClass = mkArityArray("Function", MaxFunctionArity, 0) - lazy val AbstractFunctionClass = mkArityArray("runtime.AbstractFunction", MaxFunctionArity, 0) + lazy val ProductClass = new VarArityClass("Product", MaxProductArity, countFrom = 1, init = Some(UnitClass)) + lazy val TupleClass = new VarArityClass("Tuple", MaxTupleArity, countFrom = 1) + lazy val FunctionClass = new VarArityClass("Function", MaxFunctionArity) + lazy val AbstractFunctionClass = new VarArityClass("runtime.AbstractFunction", MaxFunctionArity) /** Creators for TupleN, ProductN, FunctionN. */ - def tupleType(elems: List[Type]) = aritySpecificType(TupleClass, elems) - def functionType(formals: List[Type], restpe: Type) = aritySpecificType(FunctionClass, formals, restpe) - def abstractFunctionType(formals: List[Type], restpe: Type) = aritySpecificType(AbstractFunctionClass, formals, restpe) + def tupleType(elems: List[Type]) = TupleClass.specificType(elems) + def functionType(formals: List[Type], restpe: Type) = FunctionClass.specificType(formals, restpe) + def abstractFunctionType(formals: List[Type], restpe: Type) = AbstractFunctionClass.specificType(formals, restpe) def wrapArrayMethodName(elemtp: Type): TermName = elemtp.typeSymbol match { case ByteClass => nme.wrapByteArray @@ -625,12 +624,11 @@ trait Definitions extends api.StandardDefinitions { else nme.genericWrapArray } - // NOTE: returns true for NoSymbol since it's included in the TupleClass array -- is this intensional? - def isTupleSymbol(sym: Symbol) = TupleClass contains unspecializedSymbol(sym) - def isProductNClass(sym: Symbol) = ProductClass contains sym + def isTupleSymbol(sym: Symbol) = TupleClass.seq contains unspecializedSymbol(sym) + def isProductNClass(sym: Symbol) = ProductClass.seq contains sym def tupleField(n: Int, j: Int) = getMemberValue(TupleClass(n), nme.productAccessorName(j)) - def isFunctionSymbol(sym: Symbol) = FunctionClass contains unspecializedSymbol(sym) - def isProductNSymbol(sym: Symbol) = ProductClass contains unspecializedSymbol(sym) + def isFunctionSymbol(sym: Symbol) = FunctionClass.seq contains unspecializedSymbol(sym) + def isProductNSymbol(sym: Symbol) = ProductClass.seq contains unspecializedSymbol(sym) def unspecializedSymbol(sym: Symbol): Symbol = { if (sym hasFlag SPECIALIZED) { @@ -695,6 +693,19 @@ trait Definitions extends api.StandardDefinitions { case NullaryMethodType(restpe) => restpe case _ => tp } + + /** An implementation of finalResultType which does only what + * finalResultType is documented to do. Defining it externally to + * Type helps ensure people can't come to depend on accidental + * aspects of its behavior. This is all of it! + */ + def finalResultType(tp: Type): Type = tp match { + case PolyType(_, restpe) => finalResultType(restpe) + case MethodType(_, restpe) => finalResultType(restpe) + case NullaryMethodType(restpe) => finalResultType(restpe) + case _ => tp + } + def abstractFunctionForFunctionType(tp: Type) = { assert(isFunctionType(tp), tp) abstractFunctionType(tp.typeArgs.init, tp.typeArgs.last) @@ -1220,7 +1231,7 @@ trait Definitions extends api.StandardDefinitions { lazy val symbolsNotPresentInBytecode = syntheticCoreClasses ++ syntheticCoreMethods ++ hijackedCoreClasses /** Is the symbol that of a parent which is added during parsing? */ - lazy val isPossibleSyntheticParent = ProductClass.toSet[Symbol] + ProductRootClass + SerializableClass + lazy val isPossibleSyntheticParent = ProductClass.seq.toSet[Symbol] + ProductRootClass + SerializableClass private lazy val boxedValueClassesSet = boxedClass.values.toSet[Symbol] + BoxedUnitClass diff --git a/src/reflect/scala/reflect/internal/FlagSets.scala b/src/reflect/scala/reflect/internal/FlagSets.scala index 961adb2c57..84825ff2da 100644 --- a/src/reflect/scala/reflect/internal/FlagSets.scala +++ b/src/reflect/scala/reflect/internal/FlagSets.scala @@ -42,5 +42,6 @@ trait FlagSets extends api.FlagSets { self: SymbolTable => val DEFAULTPARAM : FlagSet = Flags.DEFAULTPARAM val PRESUPER : FlagSet = Flags.PRESUPER val DEFAULTINIT : FlagSet = Flags.DEFAULTINIT + val SYNTHETIC : FlagSet = Flags.SYNTHETIC } } diff --git a/src/reflect/scala/reflect/internal/Names.scala b/src/reflect/scala/reflect/internal/Names.scala index ed248d6e1e..f998d95349 100644 --- a/src/reflect/scala/reflect/internal/Names.scala +++ b/src/reflect/scala/reflect/internal/Names.scala @@ -90,6 +90,8 @@ trait Names extends api.Names { */ final def newTermName(cs: Array[Char], offset: Int, len: Int, cachedString: String): TermName = { def body = { + require(offset >= 0, "offset must be non-negative, got " + offset) + require(len >= 0, "length must be non-negative, got " + len) val h = hashValue(cs, offset, len) & HASH_MASK var n = termHashtable(h) while ((n ne null) && (n.length != len || !equals(n.start, cs, offset, len))) diff --git a/src/reflect/scala/reflect/internal/StdNames.scala b/src/reflect/scala/reflect/internal/StdNames.scala index 686ebf5a1e..6407a3979c 100644 --- a/src/reflect/scala/reflect/internal/StdNames.scala +++ b/src/reflect/scala/reflect/internal/StdNames.scala @@ -413,32 +413,43 @@ trait StdNames { @deprecated("Use Name#getterName", "2.11.0") def getterName(name: TermName): TermName = name.getterName @deprecated("Use Name#getterName", "2.11.0") def setterToGetter(name: TermName): TermName = name.getterName + /** + * Convert `Tuple2$mcII` to `Tuple2`, or `T1$sp` to `T1`. + */ def unspecializedName(name: Name): Name = ( - if (name endsWith SPECIALIZED_SUFFIX) - name.subName(0, name.lastIndexOf('m') - 1) + // DUPLICATED LOGIC WITH `splitSpecializedName` + if (name endsWith SPECIALIZED_SUFFIX) { + val idxM = name.lastIndexOf('m') + val to = (if (idxM > 0) idxM - 1 else name.length - SPECIALIZED_SUFFIX.length) + name.subName(0, to) + } else name ) /** Return the original name and the types on which this name * is specialized. For example, * {{{ - * splitSpecializedName("foo$mIcD$sp") == ('foo', "I", "D") + * splitSpecializedName("foo$mIcD$sp") == ('foo', "D", "I") * }}} * `foo$mIcD$sp` is the name of a method specialized on two type * parameters, the first one belonging to the method itself, on Int, * and another one belonging to the enclosing class, on Double. + * + * @return (unspecializedName, class tparam specializations, method tparam specializations) */ - def splitSpecializedName(name: Name): (Name, String, String) = - if (name endsWith SPECIALIZED_SUFFIX) { - val name1 = name dropRight SPECIALIZED_SUFFIX.length - val idxC = name1 lastIndexOf 'c' - val idxM = name1 lastIndexOf 'm' - - (name1.subName(0, idxM - 1), - name1.subName(idxC + 1, name1.length).toString, - name1.subName(idxM + 1, idxC).toString) - } else - (name, "", "") + def splitSpecializedName(name: Name): (Name, String, String) = { + // DUPLICATED LOGIC WITH `unspecializedName` + if (name endsWith SPECIALIZED_SUFFIX) { + val name1 = name dropRight SPECIALIZED_SUFFIX.length + val idxC = name1 lastIndexOf 'c' + val idxM = name1 lastIndexOf 'm' + if (idxC > idxM && idxM > 0) + (name1.subName(0, idxM - 1), name1.subName(idxC + 1, name1.length).toString, name1.subName(idxM + 1, idxC).toString) + else + (name.subName(0, name.length - SPECIALIZED_SUFFIX.length), "", "") + } + else (name, "", "") + } // Nominally, name$default$N, encoded for <init> def defaultGetterName(name: Name, pos: Int): TermName = ( diff --git a/src/reflect/scala/reflect/internal/TreeGen.scala b/src/reflect/scala/reflect/internal/TreeGen.scala index 07fa6fb317..26adf20c52 100644 --- a/src/reflect/scala/reflect/internal/TreeGen.scala +++ b/src/reflect/scala/reflect/internal/TreeGen.scala @@ -437,4 +437,10 @@ abstract class TreeGen extends macros.TreeBuilder { else if (!stats.last.isTerm) Block(stats, Literal(Constant(()))) else if (stats.length == 1) stats.head else Block(stats.init, stats.last) + + def mkTreeOrBlock(stats: List[Tree]) = stats match { + case Nil => EmptyTree + case head :: Nil => head + case _ => gen.mkBlock(stats) + } } diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index 84818a6f42..38f1f0f725 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -589,6 +589,10 @@ trait Trees extends api.Trees { self: SymbolTable => object TypeTree extends TypeTreeExtractor def TypeTree(tp: Type): TypeTree = TypeTree() setType tp + def TypeTree(sym: Symbol): TypeTree = atPos(sym.pos.focus)(TypeTree(sym.tpe_*.finalResultType)) + + def TypeBoundsTree(bounds: TypeBounds): TypeBoundsTree = TypeBoundsTree(TypeTree(bounds.lo), TypeTree(bounds.hi)) + def TypeBoundsTree(sym: Symbol): TypeBoundsTree = atPos(sym.pos)(TypeBoundsTree(sym.info.bounds)) override type TreeCopier <: InternalTreeCopierOps abstract class InternalTreeCopierOps extends TreeCopierOps { @@ -1013,15 +1017,6 @@ trait Trees extends api.Trees { self: SymbolTable => ModuleDef(Modifiers(sym.flags), sym.name.toTermName, impl) setSymbol sym } - def ValDef(sym: Symbol, rhs: Tree): ValDef = - atPos(sym.pos) { - ValDef(Modifiers(sym.flags), sym.name.toTermName, - TypeTree(sym.tpe) setPos sym.pos.focus, - rhs) setSymbol sym - } - - def ValDef(sym: Symbol): ValDef = ValDef(sym, EmptyTree) - trait CannotHaveAttrs extends Tree { override def canHaveAttrs = false @@ -1041,50 +1036,44 @@ trait Trees extends api.Trees { self: SymbolTable => object emptyValDef extends ValDef(Modifiers(PRIVATE), nme.WILDCARD, TypeTree(NoType), EmptyTree) with CannotHaveAttrs object pendingSuperCall extends Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List()) with CannotHaveAttrs - def DefDef(sym: Symbol, mods: Modifiers, vparamss: List[List[ValDef]], rhs: Tree): DefDef = - atPos(sym.pos) { - assert(sym != NoSymbol) - DefDef(mods, - sym.name.toTermName, - sym.typeParams map TypeDef, - vparamss, - TypeTree(sym.tpe.finalResultType) setPos sym.pos.focus, - rhs) setSymbol sym - } - - def DefDef(sym: Symbol, vparamss: List[List[ValDef]], rhs: Tree): DefDef = - DefDef(sym, Modifiers(sym.flags), vparamss, rhs) - - def DefDef(sym: Symbol, mods: Modifiers, rhs: Tree): DefDef = - DefDef(sym, mods, mapParamss(sym)(ValDef), rhs) - - /** A DefDef with original trees attached to the TypeTree of each parameter */ - def DefDef(sym: Symbol, mods: Modifiers, originalParamTpts: Symbol => Tree, rhs: Tree): DefDef = { - val paramms = mapParamss(sym){ sym => - val vd = ValDef(sym, EmptyTree) - (vd.tpt : @unchecked) match { - case tt: TypeTree => tt setOriginal (originalParamTpts(sym) setPos sym.pos.focus) - } - vd - } - DefDef(sym, mods, paramms, rhs) - } - - def DefDef(sym: Symbol, rhs: Tree): DefDef = - DefDef(sym, Modifiers(sym.flags), rhs) - - def DefDef(sym: Symbol, rhs: List[List[Symbol]] => Tree): DefDef = - DefDef(sym, rhs(sym.info.paramss)) - - /** A TypeDef node which defines given `sym` with given tight hand side `rhs`. */ - def TypeDef(sym: Symbol, rhs: Tree): TypeDef = - atPos(sym.pos) { - TypeDef(Modifiers(sym.flags), sym.name.toTypeName, sym.typeParams map TypeDef, rhs) setSymbol sym - } + def newValDef(sym: Symbol, rhs: Tree)( + mods: Modifiers = Modifiers(sym.flags), + name: TermName = sym.name.toTermName, + tpt: Tree = TypeTree(sym) + ): ValDef = ( + atPos(sym.pos)(ValDef(mods, name, tpt, rhs)) setSymbol sym + ) + + def newDefDef(sym: Symbol, rhs: Tree)( + mods: Modifiers = Modifiers(sym.flags), + name: TermName = sym.name.toTermName, + tparams: List[TypeDef] = sym.typeParams map TypeDef, + vparamss: List[List[ValDef]] = mapParamss(sym)(ValDef), + tpt: Tree = TypeTree(sym) + ): DefDef = ( + atPos(sym.pos)(DefDef(mods, name, tparams, vparamss, tpt, rhs)) setSymbol sym + ) + + def newTypeDef(sym: Symbol, rhs: Tree)( + mods: Modifiers = Modifiers(sym.flags), + name: TypeName = sym.name.toTypeName, + tparams: List[TypeDef] = sym.typeParams map TypeDef + ): TypeDef = ( + atPos(sym.pos)(TypeDef(mods, name, tparams, rhs)) setSymbol sym + ) + + def DefDef(sym: Symbol, rhs: Tree): DefDef = newDefDef(sym, rhs)() + def DefDef(sym: Symbol, vparamss: List[List[ValDef]], rhs: Tree): DefDef = newDefDef(sym, rhs)(vparamss = vparamss) + def DefDef(sym: Symbol, mods: Modifiers, rhs: Tree): DefDef = newDefDef(sym, rhs)(mods = mods) + def DefDef(sym: Symbol, mods: Modifiers, vparamss: List[List[ValDef]], rhs: Tree): DefDef = newDefDef(sym, rhs)(mods = mods, vparamss = vparamss) + def DefDef(sym: Symbol, rhs: List[List[Symbol]] => Tree): DefDef = newDefDef(sym, rhs(sym.info.paramss))() + + def ValDef(sym: Symbol): ValDef = newValDef(sym, EmptyTree)() + def ValDef(sym: Symbol, rhs: Tree): ValDef = newValDef(sym, rhs)() /** A TypeDef node which defines abstract type or type parameter for given `sym` */ - def TypeDef(sym: Symbol): TypeDef = - TypeDef(sym, TypeBoundsTree(TypeTree(sym.info.bounds.lo), TypeTree(sym.info.bounds.hi))) + def TypeDef(sym: Symbol): TypeDef = newTypeDef(sym, TypeBoundsTree(sym))() + def TypeDef(sym: Symbol, rhs: Tree): TypeDef = newTypeDef(sym, rhs)() def LabelDef(sym: Symbol, params: List[Symbol], rhs: Tree): LabelDef = atPos(sym.pos) { @@ -1617,6 +1606,25 @@ trait Trees extends api.Trees { self: SymbolTable => } } + /** Tracks the classes currently under construction during a transform */ + trait UnderConstructionTransformer extends Transformer { + import collection.mutable + + protected def isUnderConstruction(clazz: Symbol) = selfOrSuperCalls contains clazz + + /** The stack of class symbols in which a call to this() or to the super + * constructor, or early definition is active */ + private val selfOrSuperCalls = mutable.Stack[Symbol]() + + abstract override def transform(tree: Tree) = { + if ((treeInfo isSelfOrSuperConstrCall tree) || (treeInfo isEarlyDef tree)) { + selfOrSuperCalls push currentOwner.owner + try super.transform(tree) + finally selfOrSuperCalls.pop() + } else super.transform(tree) + } + } + def duplicateAndKeepPositions(tree: Tree) = new Duplicator(focusPositions = false) transform tree // ------ copiers ------------------------------------------- diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index ad9001ca4e..3adbbf13fc 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -144,7 +144,6 @@ trait Types override def isErroneous = underlying.isErroneous override def isStable: Boolean = underlying.isStable override def isVolatile = underlying.isVolatile - override def finalResultType = underlying.finalResultType override def paramSectionCount = underlying.paramSectionCount override def paramss = underlying.paramss override def params = underlying.params @@ -189,7 +188,6 @@ trait Types override def deconst = maybeRewrap(underlying.deconst) override def resultType = maybeRewrap(underlying.resultType) override def resultType(actuals: List[Type]) = maybeRewrap(underlying.resultType(actuals)) - override def finalResultType = maybeRewrap(underlying.finalResultType) override def paramSectionCount = 0 override def paramss: List[List[Symbol]] = List() override def params: List[Symbol] = List() @@ -440,7 +438,7 @@ trait Types /** For a curried/nullary method or poly type its non-method result type, * the type itself for all other types */ - def finalResultType: Type = this + final def finalResultType: Type = definitions finalResultType this /** For a method type, the number of its value parameter sections, * 0 for all other types */ @@ -1240,7 +1238,6 @@ trait Types if (pre.isOmittablePrefix) pre.fullName + ".type" else prefixString + "type" } - /* override def typeOfThis: Type = typeSymbol.typeOfThis override def bounds: TypeBounds = TypeBounds(this, this) @@ -2564,8 +2561,6 @@ trait Types //TODO this may be generalised so that the only constraint is dependencies are acyclic def approximate: MethodType = MethodType(params, resultApprox) - override def finalResultType: Type = resultType.finalResultType - override def safeToString = paramString(this) + resultType override def cloneInfo(owner: Symbol) = { @@ -2592,7 +2587,6 @@ trait Types override def isTrivial = resultType.isTrivial && (resultType eq resultType.withoutAnnotations) override def prefix: Type = resultType.prefix override def narrow: Type = resultType.narrow - override def finalResultType: Type = resultType.finalResultType override def termSymbol: Symbol = resultType.termSymbol override def typeSymbol: Symbol = resultType.typeSymbol override def parents: List[Type] = resultType.parents @@ -2642,7 +2636,6 @@ trait Types override def baseType(clazz: Symbol): Type = resultType.baseType(clazz) override def narrow: Type = resultType.narrow override def isVolatile = resultType.isVolatile - override def finalResultType: Type = resultType.finalResultType /** @M: typeDefSig wraps a TypeBounds in a PolyType * to represent a higher-kinded type parameter diff --git a/src/reflect/scala/reflect/internal/util/Position.scala b/src/reflect/scala/reflect/internal/util/Position.scala index ddd0a64675..8e7df28167 100644 --- a/src/reflect/scala/reflect/internal/util/Position.scala +++ b/src/reflect/scala/reflect/internal/util/Position.scala @@ -1,273 +1,213 @@ /* NSC -- new Scala compiler * Copyright 2005-2013 LAMP/EPFL * @author Martin Odersky - * */ package scala -package reflect.internal.util - -import scala.reflect.ClassTag -import scala.reflect.internal.FatalError -import scala.reflect.macros.Attachments - -object Position { - val tabInc = 8 - - /** Prints the message with the given position indication. */ - def formatMessage(posIn: Position, msg: String, shortenFile: Boolean): String = { - val pos = ( - if (posIn eq null) NoPosition - else if (posIn.isDefined) posIn.inUltimateSource(posIn.source) - else posIn - ) - val prefix = if (shortenFile) pos.sourceName else pos.sourcePath - - pos match { - case FakePos(fmsg) => fmsg+" "+msg - case NoPosition => msg - case _ => "%s:%s: %s\n%s\n%s".format(prefix, pos.line, msg, pos.lineContent, pos.lineCarat) - } - } -} +package reflect +package internal +package util /** The Position class and its subclasses represent positions of ASTs and symbols. - * Except for NoPosition and FakePos, every position refers to a SourceFile - * and to an offset in the sourcefile (its `point`). For batch compilation, - * that's all. For interactive IDE's there are also RangePositions - * and TransparentPositions. A RangePosition indicates a start and an end - * in addition to its point. TransparentPositions are a subclass of RangePositions. - * Range positions that are not transparent are called opaque. - * Trees with RangePositions need to satisfy the following invariants. + * Every subclass of DefinedPosition refers to a SourceFile and three character + * offsets within it: start, end, and point. The point is where the ^ belongs when + * issuing an error message, usually a Name. A range position can be designated + * as transparent, which excuses it from maintaining the invariants to follow. If + * a transparent position has opaque children, those are considered as if they were + * the direct children of the transparent position's parent. + * + * Note: some of these invariants actually apply to the trees which carry + * the positions, but they are phrased as if the positions themselves were + * the parent/children for conciseness. * - * INV1: A tree with an offset position never contains a child - * with a range position - * INV2: If the child of a tree with a range position also has a range position, - * then the child's range is contained in the parent's range. - * INV3: Opaque range positions of children of the same node are non-overlapping - * (this means their overlap is at most a single point). + * Invariant 1: in a focused/offset position, start == point == end + * Invariant 2: in a range position, start <= point < end + * Invariant 3: an offset position never has a child with a range position + * Invariant 4: every range position child of a range position parent is contained within its parent + * Invariant 5: opaque range position siblings overlap at most at a single point * * The following tests are useful on positions: * - * pos.isDefined true if position is not a NoPosition nor a FakePosition - * pos.isRange true if position is a range + * pos.isDefined true if position is not an UndefinedPosition (those being NoPosition and FakePos) + * pos.isRange true if position is a range (opaque or transparent) which implies start < end * pos.isOpaqueRange true if position is an opaque range * - * The following accessor methods are provided: + * The following accessor methods are provided - an exception will be thrown if + * point/start/end are attempted on an UndefinedPosition. * - * pos.source The source file of the position, which must be defined - * pos.point The offset of the position's point, which must be defined - * pos.start The start of the position, which must be a range - * pos.end The end of the position, which must be a range - * - * There are also convenience methods, such as - * - * pos.startOrPoint - * pos.endOrPoint - * pos.pointOrElse(default) - * - * These are less strict about the kind of position on which they can be applied. + * pos.source The source file of the position, or NoSourceFile if unavailable + * pos.point The offset of the point + * pos.start The (inclusive) start offset, or the point of an offset position + * pos.end The (exclusive) end offset, or the point of an offset position * * The following conversion methods are often used: * - * pos.focus converts a range position to an offset position, keeping its point; - * returns all other positions unchanged. - * pos.makeTransparent converts an opaque range position into a transparent one. - * returns all other positions unchanged. + * pos.focus Converts a range position to an offset position focused on the point + * pos.makeTransparent Convert an opaque range into a transparent range */ -abstract class Position extends scala.reflect.api.Position { self => - +class Position extends scala.reflect.api.Position with InternalPositionImpl with DeprecatedPosition { type Pos = Position - def pos: Position = this + def withPos(newPos: Position): macros.Attachments { type Pos = Position.this.Pos } = newPos + + protected def fail(what: String) = throw new UnsupportedOperationException(s"Position.$what on $this") + + // If scala-refactoring extends Position directly it seems I have no + // choice but to offer all the concrete methods. + def isDefined = false + def isRange = false + def source: SourceFile = NoSourceFile + def start: Int = fail("start") + def point: Int = fail("point") + def end: Int = fail("end") +} - def withPos(newPos: Position): Attachments { type Pos = self.Pos } = newPos - - /** An optional value containing the source file referred to by this position, or - * None if not defined. - */ - def source: SourceFile = throw new UnsupportedOperationException(s"Position.source on ${this.getClass}") - - /** Is this position neither a NoPosition nor a FakePosition? - * If isDefined is true, offset and source are both defined. - */ - def isDefined: Boolean = false - - /** Is this position a transparent position? */ - def isTransparent: Boolean = false - - /** Is this position a range position? */ - def isRange: Boolean = false - - /** Is this position a non-transparent range position? */ - def isOpaqueRange: Boolean = false - - /** if opaque range, make this position transparent */ - def makeTransparent: Position = this - - /** The start of the position's range, error if not a range position */ - def start: Int = throw new UnsupportedOperationException(s"Position.start on ${this.getClass}") - - /** The start of the position's range, or point if not a range position */ - def startOrPoint: Int = point - - /** The point (where the ^ is) of the position */ - def point: Int = throw new UnsupportedOperationException(s"Position.point on ${this.getClass}") - - /** The point (where the ^ is) of the position, or else `default` if undefined */ - def pointOrElse(default: Int): Int = default - - /** The end of the position's range, error if not a range position */ - def end: Int = throw new UnsupportedOperationException(s"Position.end on ${this.getClass}") - - /** The end of the position's range, or point if not a range position */ - def endOrPoint: Int = point - - @deprecated("use point instead", "2.9.0") - def offset: Option[Int] = if (isDefined) Some(point) else None // used by sbt - - /** The same position with a different start value (if a range) */ - def withStart(off: Int): Position = this - - /** The same position with a different end value (if a range) */ - def withEnd(off: Int): Position = this - - /** The same position with a different point value (if a range or offset) */ - def withPoint(off: Int): Position = this - - /** The same position with a different source value, and its values shifted by given offset */ - def withSource(source: SourceFile, shift: Int): Position = this - - /** If this is a range, the union with the other range, with the point of this position. - * Otherwise, this position - */ - def union(pos: Position): Position = this - - /** If this is a range position, the offset position of its start. - * Otherwise the position itself - */ - def focusStart: Position = this - - /** If this is a range position, the offset position of its point. - * Otherwise the position itself - */ - def focus: Position = this - - /** If this is a range position, the offset position of its end. - * Otherwise the position itself - */ - def focusEnd: Position = this - - /** Does this position include the given position `pos`. - * This holds if `this` is a range position and its range [start..end] - * is the same or covers the range of the given position, which may or may not be a range position. - */ - def includes(pos: Position): Boolean = false - - /** Does this position properly include the given position `pos` ("properly" meaning their - * ranges are not the same)? - */ - def properlyIncludes(pos: Position): Boolean = - includes(pos) && (start < pos.startOrPoint || pos.endOrPoint < end) - - /** Does this position precede that position? - * This holds if both positions are defined and the end point of this position - * is not larger than the start point of the given position. - */ - def precedes(pos: Position): Boolean = - isDefined && pos.isDefined && endOrPoint <= pos.startOrPoint - - /** Does this position properly precede the given position `pos` ("properly" meaning their ranges - * do not share a common point). - */ - def properlyPrecedes(pos: Position): Boolean = - isDefined && pos.isDefined && endOrPoint < pos.startOrPoint - - /** Does this position overlap with that position? - * This holds if both positions are ranges and there is an interval of - * non-zero length that is shared by both position ranges. - */ - def overlaps(pos: Position): Boolean = - isRange && pos.isRange && - ((pos.start < end && start < pos.end) || (start < pos.end && pos.start < end)) - - /** Does this position cover the same range as that position? - * Holds only if both position are ranges - */ - def sameRange(pos: Position): Boolean = - isRange && pos.isRange && start == pos.start && end == pos.end - - def line: Int = throw new UnsupportedOperationException("Position.line") +object Position { + val tabInc = 8 - def column: Int = throw new UnsupportedOperationException("Position.column") + private def validate[T <: Position](pos: T): T = { + if (pos.isRange) + assert(pos.start <= pos.end, s"bad position: ${pos.show}") - /** A line with a ^ padded with the right number of spaces. - */ - def lineCarat: String = " " * (column - 1) + "^" + pos + } - /** The line of code and the corresponding carat pointing line, trimmed - * to the maximum specified width, with the trimmed versions oriented - * around the point to give maximum context. - */ - def lineWithCarat(maxWidth: Int): (String, String) = { - val radius = maxWidth / 2 - var start = scala.math.max(column - radius, 0) - var result = lineContent drop start take maxWidth - - if (result.length < maxWidth) { - result = lineContent takeRight maxWidth - start = lineContent.length - result.length + /** Prints the message with the given position indication. */ + def formatMessage(posIn: Position, msg: String, shortenFile: Boolean): String = { + val pos = if (posIn eq null) NoPosition else posIn + val prefix = pos.source match { + case NoSourceFile => "" + case s if shortenFile => s.file.name + ":" + case s => s.file.path + ":" } - - (result, lineCarat drop start take maxWidth) + prefix + (pos showError msg) } - /** Convert this to a position around `point` that spans a single source line */ - def toSingleLine: Position = this - - /** The source code corresponding to the range, if this is a range position. - * Otherwise the empty string. - */ - def sourceCode = "" - def sourceName = "<none>" - def sourcePath = "<none>" - def lineContent = "<none>" - def lengthInChars = 0 - def lengthInLines = 0 - - /** Map this position to a position in an original source - * file. If the SourceFile is a normal SourceFile, simply - * return this. - */ - def inUltimateSource(source : SourceFile): Position = - if (source == null) this else source.positionInUltimateSource(this) - - def dbgString: String = toString - def safeLine: Int = try line catch { case _: UnsupportedOperationException => -1 } - - def show: String = "["+toString+"]" + def offset(source: SourceFile, point: Int): Position = validate(new OffsetPosition(source, point)) + def range(source: SourceFile, start: Int, point: Int, end: Int): Position = validate(new RangePosition(source, start, point, end)) + def transparent(source: SourceFile, start: Int, point: Int, end: Int): Position = validate(new TransparentPosition(source, start, point, end)) } -case object NoPosition extends Position { - override def dbgString = toString +class OffsetPosition(sourceIn: SourceFile, pointIn: Int) extends DefinedPosition { + override def isRange = false + override def source = sourceIn + override def point = pointIn + override def start = point + override def end = point } - -case class FakePos(msg: String) extends Position { +class RangePosition(sourceIn: SourceFile, startIn: Int, pointIn: Int, endIn: Int) extends OffsetPosition(sourceIn, pointIn) { + override def isRange = true + override def start = startIn + override def end = endIn +} +class TransparentPosition(sourceIn: SourceFile, startIn: Int, pointIn: Int, endIn: Int) extends RangePosition(sourceIn, startIn, pointIn, endIn) { + override def isTransparent = true +} +case object NoPosition extends UndefinedPosition +case class FakePos(msg: String) extends UndefinedPosition { override def toString = msg } -class OffsetPosition(override val source: SourceFile, override val point: Int) extends Position { - override def isDefined = true - override def pointOrElse(default: Int): Int = point - override def withPoint(off: Int) = new OffsetPosition(source, off) - override def withSource(source: SourceFile, shift: Int) = new OffsetPosition(source, point + shift) +sealed abstract class DefinedPosition extends Position { + final override def isDefined = true + override def equals(that: Any) = that match { + case that: DefinedPosition => source.file == that.source.file && start == that.start && point == that.point && end == that.end + case _ => false + } + override def hashCode = Seq[Any](source.file, start, point, end).## + override def toString = ( + if (isRange) s"RangePosition($canonicalPath, $start, $point, $end)" + else s"source-$canonicalPath,line-$line,$pointMessage$point" + ) + private def pointMessage = if (point > source.length) "out-of-bounds-" else "offset=" + private def canonicalPath = source.file.canonicalPath +} - override def line = source.offsetToLine(point) + 1 - override def sourceName = source.file.name - override def sourcePath = source.file.path - override def lineContent = source.lineToString(line - 1) +sealed abstract class UndefinedPosition extends Position { + final override def isDefined = false + override def isRange = false + override def source = NoSourceFile + override def start = fail("start") + override def point = fail("point") + override def end = fail("end") +} - override def column: Int = { +private[util] trait InternalPositionImpl { + self: Position => + + // The methods which would be abstract in Position if it were + // possible to change Position. + def isDefined: Boolean + def isRange: Boolean + def source: SourceFile + def start: Int + def point: Int + def end: Int + + /** Map this position to its position in the original source file + * (which may be this position unchanged.) + */ + def finalPosition: Pos = source positionInUltimateSource this + + def isTransparent = false + def isOffset = isDefined && !isRange + def isOpaqueRange = isRange && !isTransparent + def pointOrElse(alt: Int): Int = if (isDefined) point else alt + def makeTransparent: Position = if (isOpaqueRange) Position.transparent(source, start, point, end) else this + + /** Copy a range position with a changed value. + */ + def withStart(start: Int): Position = copyRange(start = start) + def withPoint(point: Int): Position = if (isRange) copyRange(point = point) else Position.offset(source, point) + def withEnd(end: Int): Position = copyRange(end = end) + def withSource(source: SourceFile): Position = copyRange(source = source) + def withShift(shift: Int): Position = Position.range(source, start + shift, point + shift, end + shift) + + /** Convert a range position to a simple offset. + */ + def focusStart: Position = if (this.isRange) asOffset(start) else this + def focus: Position = if (this.isRange) asOffset(point) else this + def focusEnd: Position = if (this.isRange) asOffset(end) else this + + def union(pos: Position): Position = ( + if (!pos.isRange) this + else if (this.isRange) copyRange(start = start min pos.start, end = end max pos.end) + else pos + ) + + def includes(pos: Position): Boolean = isRange && pos.isDefined && start <= pos.start && pos.end <= end + def properlyIncludes(pos: Position): Boolean = includes(pos) && (start < pos.start || pos.end < end) + def precedes(pos: Position): Boolean = bothDefined(pos) && end <= pos.start + def properlyPrecedes(pos: Position): Boolean = bothDefined(pos) && end < pos.start + def sameRange(pos: Position): Boolean = bothRanges(pos) && start == pos.start && end == pos.end + // This works because it's a range position invariant that S1 < E1 and S2 < E2. + // So if S1 < E2 and S2 < E1, then both starts precede both ends, which is the + // necessary condition to establish that there is overlap. + def overlaps(pos: Position): Boolean = bothRanges(pos) && start < pos.end && pos.start < end + + def line: Int = if (hasSource) source.offsetToLine(point) + 1 else 0 + def column: Int = if (hasSource) calculateColumn() else 0 + def lineContent: String = if (hasSource) source.lineToString(line - 1) else "" + def lineCarat: String = if (hasSource) " " * (column - 1) + "^" else "" + + def showError(msg: String): String = finalPosition match { + case FakePos(fmsg) => s"$fmsg $msg" + case NoPosition => msg + case pos => s"${pos.line}: $msg\n${pos.lineContent}\n${pos.lineCarat}" + } + def showDebug: String = toString + def show = ( + if (isOpaqueRange) s"[$start:$end]" + else if (isTransparent) s"<$start:$end>" + else if (isDefined) s"[$point]" + else "[NoPosition]" + ) + + private def asOffset(point: Int): Position = Position.offset(source, point) + private def copyRange(source: SourceFile = source, start: Int = start, point: Int = point, end: Int = end): Position = + Position.range(source, start, point, end) + + private def calculateColumn(): Int = { var idx = source.lineToOffset(source.offsetToLine(point)) var col = 0 while (idx != point) { @@ -276,18 +216,39 @@ class OffsetPosition(override val source: SourceFile, override val point: Int) e } col + 1 } + private def hasSource = source ne NoSourceFile + private def bothRanges(that: Position) = isRange && that.isRange + private def bothDefined(that: Position) = isDefined && that.isDefined +} - override def union(pos: Position) = if (pos.isRange) pos else this +/** Holding cell for methods unused and/or unnecessary. */ +private[util] trait DeprecatedPosition { + self: Position => - override def equals(that : Any) = that match { - case that : OffsetPosition => point == that.point && source.file == that.source.file - case that => false - } - override def hashCode = point * 37 + source.file.hashCode + @deprecated("use `point`", "2.9.0") + def offset: Option[Int] = if (isDefined) Some(point) else None // used by sbt - override def toString = { - val pointmsg = if (point > source.length) "out-of-bounds-" else "offset=" - "source-%s,line-%s,%s%s".format(source.file.canonicalPath, line, pointmsg, point) - } - override def show = "["+point+"]" + @deprecated("use `focus`", "2.11.0") + def toSingleLine: Position = this + + @deprecated("use `line`", "2.11.0") + def safeLine: Int = line + + @deprecated("use `showDebug`", "2.11.0") + def dbgString: String = showDebug + + @deprecated("use `finalPosition`", "2.11.0") + def inUltimateSource(source: SourceFile): Position = source positionInUltimateSource this + + @deprecated("use `lineCarat`", "2.11.0") + def lineWithCarat(maxWidth: Int): (String, String) = ("", "") + + @deprecated("Use `withSource(source)` and `withShift`", "2.11.0") + def withSource(source: SourceFile, shift: Int): Position = this withSource source withShift shift + + @deprecated("Use `start`", "2.11.0") + def startOrPoint: Int = if (isRange) start else point + + @deprecated("Use `end`", "2.11.0") + def endOrPoint: Int = if (isRange) end else point } diff --git a/src/reflect/scala/reflect/internal/util/RangePosition.scala b/src/reflect/scala/reflect/internal/util/RangePosition.scala deleted file mode 100644 index 0d09a53cd9..0000000000 --- a/src/reflect/scala/reflect/internal/util/RangePosition.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2013 LAMP/EPFL - * @author Paul Phillips - */ - -package scala -package reflect.internal.util - -/** new for position ranges */ -class RangePosition(source: SourceFile, override val start: Int, point: Int, override val end: Int) -extends OffsetPosition(source, point) { - if (start > end) scala.sys.error("bad position: "+show) - override def isRange: Boolean = true - override def isOpaqueRange: Boolean = true - override def startOrPoint: Int = start - override def endOrPoint: Int = end - override def withStart(off: Int) = new RangePosition(source, off, point, end) - override def withEnd(off: Int) = new RangePosition(source, start, point, off) - override def withPoint(off: Int) = new RangePosition(source, start, off, end) - override def withSource(source: SourceFile, shift: Int) = new RangePosition(source, start + shift, point + shift, end + shift) - override def focusStart = new OffsetPosition(source, start) - override def focus = { - if (focusCache eq NoPosition) focusCache = new OffsetPosition(source, point) - focusCache - } - override def focusEnd = new OffsetPosition(source, end) - override def makeTransparent = new TransparentPosition(source, start, point, end) - override def includes(pos: Position) = pos.isDefined && start <= pos.startOrPoint && pos.endOrPoint <= end - override def union(pos: Position): Position = - if (pos.isRange) new RangePosition(source, start min pos.start, point, end max pos.end) else this - - override def toSingleLine: Position = source match { - case bs: BatchSourceFile - if end > 0 && bs.offsetToLine(start) < bs.offsetToLine(end - 1) => - val pointLine = bs.offsetToLine(point) - new RangePosition(source, bs.lineToOffset(pointLine), point, bs.lineToOffset(pointLine + 1)) - case _ => this - } - - override def toString = "RangePosition("+source.file.canonicalPath+", "+start+", "+point+", "+end+")" - override def show = "["+start+":"+end+"]" - private var focusCache: Position = NoPosition -} - -class TransparentPosition(source: SourceFile, start: Int, point: Int, end: Int) extends RangePosition(source, start, point, end) { - override def isOpaqueRange: Boolean = false - override def isTransparent = true - override def makeTransparent = this - override def show = "<"+start+":"+end+">" -} diff --git a/src/repl/scala/tools/nsc/interpreter/ExprTyper.scala b/src/repl/scala/tools/nsc/interpreter/ExprTyper.scala index 6406dacc24..bb5fe07fc9 100644 --- a/src/repl/scala/tools/nsc/interpreter/ExprTyper.scala +++ b/src/repl/scala/tools/nsc/interpreter/ExprTyper.scala @@ -28,7 +28,7 @@ trait ExprTyper { case IR.Success => val sym0 = symbolOfTerm(name) // drop NullaryMethodType - sym0.cloneSymbol setInfo exitingTyper(sym0.info.finalResultType) + sym0.cloneSymbol setInfo exitingTyper(sym0.tpe_*.finalResultType) case _ => NoSymbol } } diff --git a/test/disabled/run/t7843-jsr223-service.check b/test/disabled/run/t7843-jsr223-service.check new file mode 100644 index 0000000000..a668df3567 --- /dev/null +++ b/test/disabled/run/t7843-jsr223-service.check @@ -0,0 +1,2 @@ +n: Object = 10 +12345678910 diff --git a/test/disabled/run/t7843-jsr223-service.scala b/test/disabled/run/t7843-jsr223-service.scala new file mode 100644 index 0000000000..e2ea850698 --- /dev/null +++ b/test/disabled/run/t7843-jsr223-service.scala @@ -0,0 +1,18 @@ +/*DISABLED: + For Paul, it steals focus when it runs. + + For me, it fails with some platform specific extra output: + + -ScriptEngineManager providers.next(): javax.script.ScriptEngineFactory: Provider apple.applescript.AppleScriptEngin + n: Object = 10 + 12345678910 +*/ +import javax.script._ +import scala.tools.nsc.interpreter.IMain + +object Test extends App { + val engine = new ScriptEngineManager getEngineByName "scala" + engine.asInstanceOf[IMain].settings.usejavacp.value = true + engine put ("n", 10) + engine eval "1 to n.asInstanceOf[Int] foreach print" +} diff --git a/test/files/neg/t1909-object.check b/test/files/neg/t1909-object.check new file mode 100644 index 0000000000..401c1f7ebf --- /dev/null +++ b/test/files/neg/t1909-object.check @@ -0,0 +1,4 @@ +t1909-object.scala:4: error: !!! SI-1909 Unable to STATICally lift object InnerTrouble$1, which is defined in the self- or super-constructor call of class Kaboom. A VerifyError is likely. + object InnerTrouble + ^ +one error found diff --git a/test/files/neg/t1909-object.flags b/test/files/neg/t1909-object.flags new file mode 100644 index 0000000000..eb8b40661b --- /dev/null +++ b/test/files/neg/t1909-object.flags @@ -0,0 +1 @@ +-Xdev -Xfatal-warnings
\ No newline at end of file diff --git a/test/files/neg/t1909-object.scala b/test/files/neg/t1909-object.scala new file mode 100644 index 0000000000..d6011ba4a5 --- /dev/null +++ b/test/files/neg/t1909-object.scala @@ -0,0 +1,12 @@ +class Kaboom(a: Any) { + def this() = { + this({ + object InnerTrouble + InnerTrouble + }) + } +} + +object Test extends App { + new Kaboom() +}
\ No newline at end of file diff --git a/test/files/neg/t284.check b/test/files/neg/t284.check index 37801af1b5..7c2e9be03e 100644 --- a/test/files/neg/t284.check +++ b/test/files/neg/t284.check @@ -1,8 +1,6 @@ t284.scala:2: warning: Detected apparent refinement of Unit; are you missing an '=' sign? - def f1(a: T): Unit { } - ^ -t284.scala:5: error: Unmatched closing brace '}' ignored here - } - ^ + def f1(a: T): Unit { } + ^ +error: No warnings can be incurred under -Xfatal-warnings. one warning found one error found diff --git a/test/files/neg/t284.flags b/test/files/neg/t284.flags new file mode 100644 index 0000000000..e8fb65d50c --- /dev/null +++ b/test/files/neg/t284.flags @@ -0,0 +1 @@ +-Xfatal-warnings
\ No newline at end of file diff --git a/test/files/neg/t284.scala b/test/files/neg/t284.scala index a210130102..f75bc3d4ba 100644 --- a/test/files/neg/t284.scala +++ b/test/files/neg/t284.scala @@ -1,6 +1,5 @@ trait B[T] { - def f1(a: T): Unit { } - def f2(a: T): Unit - def f3(a: T) { } - } + def f1(a: T): Unit { } + def f2(a: T): Unit + def f3(a: T) { } } diff --git a/test/files/neg/t7007.check b/test/files/neg/t7007.check new file mode 100644 index 0000000000..e22ecb9e4e --- /dev/null +++ b/test/files/neg/t7007.check @@ -0,0 +1,7 @@ +t7007.scala:5: error: Implementation restriction: <$anon: A => B> requires premature access to class Crash. + def this(a: Seq[A]) = this(a.collect{ case b: B => b}, a.collect{ case b: B => b}) + ^ +t7007.scala:5: error: Implementation restriction: <$anon: A => B> requires premature access to class Crash. + def this(a: Seq[A]) = this(a.collect{ case b: B => b}, a.collect{ case b: B => b}) + ^ +two errors found diff --git a/test/files/neg/t7007.scala b/test/files/neg/t7007.scala new file mode 100644 index 0000000000..e41dccf550 --- /dev/null +++ b/test/files/neg/t7007.scala @@ -0,0 +1,14 @@ +class A +class B extends A + +class Crash(b1: Seq[B], b2: Seq[B]) { + def this(a: Seq[A]) = this(a.collect{ case b: B => b}, a.collect{ case b: B => b}) +} + +object Main extends App { + + // runtime exception with either constructor + val c1 = new Crash(Seq(new B, new B)) + val c2 = new Crash(Seq(new B), Seq(new B)) + +} diff --git a/test/files/pos/infersingle.scala b/test/files/pos/infersingle.scala index 6830fcd799..60f4ff07e6 100644 --- a/test/files/pos/infersingle.scala +++ b/test/files/pos/infersingle.scala @@ -1,5 +1,52 @@ -object Test { +object Test1 { def one[T](x: T): Option[T] = Some(x) val x = "one" val y: Option[x.type] = one(x) -}
\ No newline at end of file +} + +object Test2 { + // Has never worked, but seems desirable given the recent changes to + // pattern type inference. + val a = "" + object Id { + def unapply(xxxx: Any): Some[a.type] = Some[a.type](a) + } + val b: a.type = (a: a.type) match { + case Id(x) => x + } +} + +object Test3 { + val a = "" + object Id { + def unapply(xxxx: Any): Some[Test3.type] = Some[Test3.type](Test3) + } + val b: Test3.type = a match { + case Id(x) => x + } +} + +class Test4 { + val a = "" + object Id { + def unapply(xxxx: Any): Some[Test4.this.type] = Some[Test4.this.type](Test4.this) + } + val b: Test4.this.type = a match { + case Id(x) => x + } +} + +class Super5 { + final val q = "" + def q1: q.type = q +} + +class Test5 extends Super5 { + val a = "" + object Id { + def unapply(xxxx: Any): Some[Test5.super.q.type] = Some[Test5.super.q.type](q1) + } + val b: Test5.super.q.type = a match { + case Id(x) => x + } +} diff --git a/test/files/pos/private-types-after-typer.scala b/test/files/pos/private-types-after-typer.scala new file mode 100644 index 0000000000..79ef934063 --- /dev/null +++ b/test/files/pos/private-types-after-typer.scala @@ -0,0 +1,9 @@ +// Testing that the type of the outer accessor in O2 +// doesn't crash the compiler over private type escaping scope. +trait T { + class C { + private object O1 { + object O2 + } + } +}
\ No newline at end of file diff --git a/test/files/pos/t7847/A.scala b/test/files/pos/t7847/A.scala new file mode 100644 index 0000000000..b6cce6ee79 --- /dev/null +++ b/test/files/pos/t7847/A.scala @@ -0,0 +1,5 @@ +case class Blah(a: Int) + +object Blah { + def apply2(a: Int) = apply(a) +} diff --git a/test/files/pos/t7847/B.java b/test/files/pos/t7847/B.java new file mode 100644 index 0000000000..c214f2dcab --- /dev/null +++ b/test/files/pos/t7847/B.java @@ -0,0 +1,10 @@ +public final class B { + void blah() { + Blah x = Blah.apply2(1); + Blah y = Blah.apply(1); + Blah z = Blah$.MODULE$.apply(1); + + scala.Option un1 = Blah.unapply(null); + scala.Option un2 = Blah$.MODULE$.unapply(null); + } +} diff --git a/test/files/run/compiler-asSeenFrom.check b/test/files/run/compiler-asSeenFrom.check index 47d40b0331..a1826c2784 100644 --- a/test/files/run/compiler-asSeenFrom.check +++ b/test/files/run/compiler-asSeenFrom.check @@ -1,6 +1,54 @@ class C { type seen from prefix is ---- ---------------- -- + C.this.I[Int] C[List[T3]] C[List[T3]]#I[Int] + C.this.I[Int] C[T1] C[T1]#I[Int] + C.this.I[Int] D[A1] D[A1]#I[Int] + C.this.I[Int] D[T3] D[T3]#I[Int] + C.this.I[List[Int]] C[List[T3]] C[List[T3]]#I[List[Int]] + C.this.I[List[Int]] C[T1] C[T1]#I[List[Int]] + C.this.I[List[Int]] D[A1] D[A1]#I[List[Int]] + C.this.I[List[Int]] D[T3] D[T3]#I[List[Int]] + C.this.I[T1] C[List[T3]] C[List[T3]]#I[List[T3]] + C.this.I[T1] C[T1] C[T1]#I[T1] + C.this.I[T1] D[A1] D[A1]#I[A1] + C.this.I[T1] D[T3] D[T3]#I[T3] + C.this.I[T2] C[List[T3]] C[List[T3]]#I[T2] + C.this.I[T2] C[T1] C[T1]#I[T2] + C.this.I[T2] D[A1] D[A1]#I[T2] + C.this.I[T2] D[T3] D[T3]#I[T2] + C.this.I[T3] C[List[T3]] C[List[T3]]#I[T3] + C.this.I[T3] C[T1] C[T1]#I[T3] + C.this.I[T3] D[A1] D[A1]#I[T3] + C.this.I[T3] D[T3] D[T3]#I[T3] + C.this.I[T4] C[List[T3]] C[List[T3]]#I[T4] + C.this.I[T4] C[T1] C[T1]#I[T4] + C.this.I[T4] D[A1] D[A1]#I[T4] + C.this.I[T4] D[T3] D[T3]#I[T4] + C.this.J[Int] C[List[T3]] C[List[T3]]#J[Int] + C.this.J[Int] C[T1] C[T1]#J[Int] + C.this.J[Int] D[A1] D[A1]#J[Int] + C.this.J[Int] D[T3] D[T3]#J[Int] + C.this.J[List[Int]] C[List[T3]] C[List[T3]]#J[List[Int]] + C.this.J[List[Int]] C[T1] C[T1]#J[List[Int]] + C.this.J[List[Int]] D[A1] D[A1]#J[List[Int]] + C.this.J[List[Int]] D[T3] D[T3]#J[List[Int]] + C.this.J[T1] C[List[T3]] C[List[T3]]#J[List[T3]] + C.this.J[T1] C[T1] C[T1]#J[T1] + C.this.J[T1] D[A1] D[A1]#J[A1] + C.this.J[T1] D[T3] D[T3]#J[T3] + C.this.J[T2] C[List[T3]] C[List[T3]]#J[T2] + C.this.J[T2] C[T1] C[T1]#J[T2] + C.this.J[T2] D[A1] D[A1]#J[T2] + C.this.J[T2] D[T3] D[T3]#J[T2] + C.this.J[T3] C[List[T3]] C[List[T3]]#J[T3] + C.this.J[T3] C[T1] C[T1]#J[T3] + C.this.J[T3] D[A1] D[A1]#J[T3] + C.this.J[T3] D[T3] D[T3]#J[T3] + C.this.J[T4] C[List[T3]] C[List[T3]]#J[T4] + C.this.J[T4] C[T1] C[T1]#J[T4] + C.this.J[T4] D[A1] D[A1]#J[T4] + C.this.J[T4] D[T3] D[T3]#J[T4] C[List[T3]]#I[T1] D[A1] C[List[T3]]#I[A1] C[List[T3]]#I[T1] D[T3] C[List[T3]]#I[T3] C[List[T3]]#J[T1] D[A1] C[List[T3]]#J[A1] @@ -49,6 +97,8 @@ class C { class D { type seen from prefix is ---- ---------------- -- + C.this.I[T3] D[A1] C.this.I[A1] + C.this.J[T3] D[A1] C.this.J[A1] C[List[T3]]#I[Int] D[A1] C[List[A1]]#I[Int] C[List[T3]]#I[List[Int]] D[A1] C[List[A1]]#I[List[Int]] C[List[T3]]#I[T1] D[A1] C[List[A1]]#I[T1] @@ -73,6 +123,42 @@ class D { class I { type seen from prefix is ---- ---------------- -- + C.this.I[Int] D.this.J[T4] D.this.cD.I[Int] + C.this.I[Int] Z.dZ.J[A2] Z.dZ.cD.I[Int] + C.this.I[Int] Z.dZ.J[P] Z.dZ.cD.I[Int] + C.this.I[List[Int]] D.this.J[T4] D.this.cD.I[List[Int]] + C.this.I[List[Int]] Z.dZ.J[A2] Z.dZ.cD.I[List[Int]] + C.this.I[List[Int]] Z.dZ.J[P] Z.dZ.cD.I[List[Int]] + C.this.I[T1] D.this.J[T4] D.this.cD.I[List[T3]] + C.this.I[T1] Z.dZ.J[A2] Z.dZ.cD.I[List[A1]] + C.this.I[T1] Z.dZ.J[P] Z.dZ.cD.I[List[A1]] + C.this.I[T2] D.this.J[T4] D.this.cD.I[T4] + C.this.I[T2] Z.dZ.J[A2] Z.dZ.cD.I[A2] + C.this.I[T2] Z.dZ.J[P] Z.dZ.cD.I[P] + C.this.I[T3] D.this.J[T4] D.this.cD.I[T3] + C.this.I[T3] Z.dZ.J[A2] Z.dZ.cD.I[T3] + C.this.I[T3] Z.dZ.J[P] Z.dZ.cD.I[T3] + C.this.I[T4] D.this.J[T4] D.this.cD.I[T4] + C.this.I[T4] Z.dZ.J[A2] Z.dZ.cD.I[T4] + C.this.I[T4] Z.dZ.J[P] Z.dZ.cD.I[T4] + C.this.J[Int] D.this.J[T4] D.this.cD.J[Int] + C.this.J[Int] Z.dZ.J[A2] Z.dZ.cD.J[Int] + C.this.J[Int] Z.dZ.J[P] Z.dZ.cD.J[Int] + C.this.J[List[Int]] D.this.J[T4] D.this.cD.J[List[Int]] + C.this.J[List[Int]] Z.dZ.J[A2] Z.dZ.cD.J[List[Int]] + C.this.J[List[Int]] Z.dZ.J[P] Z.dZ.cD.J[List[Int]] + C.this.J[T1] D.this.J[T4] D.this.cD.J[List[T3]] + C.this.J[T1] Z.dZ.J[A2] Z.dZ.cD.J[List[A1]] + C.this.J[T1] Z.dZ.J[P] Z.dZ.cD.J[List[A1]] + C.this.J[T2] D.this.J[T4] D.this.cD.J[T4] + C.this.J[T2] Z.dZ.J[A2] Z.dZ.cD.J[A2] + C.this.J[T2] Z.dZ.J[P] Z.dZ.cD.J[P] + C.this.J[T3] D.this.J[T4] D.this.cD.J[T3] + C.this.J[T3] Z.dZ.J[A2] Z.dZ.cD.J[T3] + C.this.J[T3] Z.dZ.J[P] Z.dZ.cD.J[T3] + C.this.J[T4] D.this.J[T4] D.this.cD.J[T4] + C.this.J[T4] Z.dZ.J[A2] Z.dZ.cD.J[T4] + C.this.J[T4] Z.dZ.J[P] Z.dZ.cD.J[T4] C[List[T3]]#I[T1] D.this.J[T4] C[List[T3]]#I[List[T3]] C[List[T3]]#I[T1] Z.dZ.J[A2] C[List[T3]]#I[List[A1]] C[List[T3]]#I[T1] Z.dZ.J[P] C[List[T3]]#I[List[A1]] @@ -137,6 +223,14 @@ class I { class J { type seen from prefix is ---- ---------------- -- + C.this.I[T3] Z.dZ.J[A2] C.this.I[A1] + C.this.I[T3] Z.dZ.J[P] C.this.I[A1] + C.this.I[T4] Z.dZ.J[A2] C.this.I[A2] + C.this.I[T4] Z.dZ.J[P] C.this.I[P] + C.this.J[T3] Z.dZ.J[A2] C.this.J[A1] + C.this.J[T3] Z.dZ.J[P] C.this.J[A1] + C.this.J[T4] Z.dZ.J[A2] C.this.J[A2] + C.this.J[T4] Z.dZ.J[P] C.this.J[P] C[List[T3]]#I[Int] Z.dZ.J[A2] C[List[A1]]#I[Int] C[List[T3]]#I[Int] Z.dZ.J[P] C[List[A1]]#I[Int] C[List[T3]]#I[List[Int]] Z.dZ.J[A2] C[List[A1]]#I[List[Int]] @@ -269,8 +363,8 @@ value jZ { // after parser value jZ { // after explicitouter protected val $outer: D.this.type - val $outer(): D.this.type - val $outer(): C.this.type + val $outer(): ll.D[T3] + val $outer(): ll.C[T1] def thisI(): I.this.type def thisC(): C.this.type def t2(): T2 diff --git a/test/files/run/idempotency-case-classes.check b/test/files/run/idempotency-case-classes.check index e0453883ff..5a8d0ad9d3 100644 --- a/test/files/run/idempotency-case-classes.check +++ b/test/files/run/idempotency-case-classes.check @@ -47,7 +47,7 @@ C(2,3) case <synthetic> def unapply(x$0: C): Option[(Int, Int)] = if (x$0.==(null)) scala.this.None else - Some.apply[(Int, Int)](Tuple2.apply[Int, Int](x$0.x, x$0.y)); + Some.apply[(Int, Int)](scala.Tuple2.apply[Int, Int](x$0.x, x$0.y)); <synthetic> private def readResolve(): Object = C }; Predef.println(C.apply(2, 3)) diff --git a/test/files/run/macro-parse-position-malformed.check b/test/files/run/macro-parse-position-malformed.check new file mode 100644 index 0000000000..00f0bc5b62 --- /dev/null +++ b/test/files/run/macro-parse-position-malformed.check @@ -0,0 +1 @@ +failed with 'source-<macro>,line-1,offset=7' position and '')' expected but eof found.' message diff --git a/test/files/run/macro-parse-position-malformed/Impls_Macros_1.scala b/test/files/run/macro-parse-position-malformed/Impls_Macros_1.scala new file mode 100644 index 0000000000..2417eb6897 --- /dev/null +++ b/test/files/run/macro-parse-position-malformed/Impls_Macros_1.scala @@ -0,0 +1,17 @@ +import scala.language.experimental.macros +import scala.reflect.macros.{Context => Ctx, ParseException} + +object Macros { + def impl(c: Ctx)() = { + import c.universe._ + val out = try { + c.parse("foo(bar") + "didn't fail" + } catch { + case e: ParseException => + s"failed with '${e.pos}' position and '${e.msg}' message" + } + c.Expr[String](Literal(Constant(out))) + } + def foo(): String = macro impl +}
\ No newline at end of file diff --git a/test/files/run/macro-parse-position-malformed/Test_2.scala b/test/files/run/macro-parse-position-malformed/Test_2.scala new file mode 100644 index 0000000000..cff569bd81 --- /dev/null +++ b/test/files/run/macro-parse-position-malformed/Test_2.scala @@ -0,0 +1,3 @@ +object Test extends App { + println(Macros.foo) +} diff --git a/test/files/run/macro-parse-position.check b/test/files/run/macro-parse-position.check new file mode 100644 index 0000000000..3da0320696 --- /dev/null +++ b/test/files/run/macro-parse-position.check @@ -0,0 +1,5 @@ +false +source-<macro>,line-1,offset=4 +8 +foo bar + diff --git a/test/files/run/macro-parse-position/Impls_Macros_1.scala b/test/files/run/macro-parse-position/Impls_Macros_1.scala new file mode 100644 index 0000000000..b6f1ebbcd5 --- /dev/null +++ b/test/files/run/macro-parse-position/Impls_Macros_1.scala @@ -0,0 +1,12 @@ +import scala.language.experimental.macros +import scala.reflect.macros.{Context => Ctx} + +object Macros { + def impl(c: Ctx)() = { + import c.universe._ + val t = c.parse("foo bar") + val out = s"${t.pos == NoPosition}\n${t.pos}\n${t.pos.source.content.length}\n${new String(t.pos.source.content)}" + c.Expr[String](Literal(Constant(out))) + } + def foo(): String = macro impl +}
\ No newline at end of file diff --git a/test/files/run/macro-parse-position/Test_2.scala b/test/files/run/macro-parse-position/Test_2.scala new file mode 100644 index 0000000000..cff569bd81 --- /dev/null +++ b/test/files/run/macro-parse-position/Test_2.scala @@ -0,0 +1,3 @@ +object Test extends App { + println(Macros.foo) +} diff --git a/test/files/run/reify_copypaste1.scala b/test/files/run/reify_copypaste1.scala index b2eef28026..cf813182ae 100644 --- a/test/files/run/reify_copypaste1.scala +++ b/test/files/run/reify_copypaste1.scala @@ -12,7 +12,7 @@ object Test extends App { val reify = Select(Select(Select(Select(Ident(ScalaPackage), TermName("reflect")), TermName("runtime")), TermName("universe")), TermName("reify")) val reifee = Block(List(ValDef(Modifiers(LAZY), TermName("x"), TypeTree(), Apply(Ident(ListModule), List(Literal(Constant(1)), Literal(Constant(2)))))), Ident(TermName("x"))) toolBox.eval(Apply(reify, List(reifee))) - val Block(List(tpeCopypaste), exprCopypaste @ ModuleDef(_, _, Template(_, _, (_ :: stats) :+ expr))) = toolBox.parse(output.toString()) + val Block(List(tpeCopypaste, exprCopypaste @ ModuleDef(_, _, Template(_, _, (_ :: stats) :+ expr))), Literal(Constant(()))) = toolBox.parse(output.toString()) output.reset() toolBox.eval(Block(stats, expr)) stdout.println(output.toString) diff --git a/test/files/run/t1909.check b/test/files/run/t1909.check new file mode 100644 index 0000000000..7d25be60fd --- /dev/null +++ b/test/files/run/t1909.check @@ -0,0 +1,3 @@ +t1909.scala:7: warning: A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled. + def this(p: String) = this(try 0) + ^ diff --git a/test/files/pos/t1909.scala b/test/files/run/t1909.scala index 01213f62a3..8ead7bacf2 100644 --- a/test/files/pos/t1909.scala +++ b/test/files/run/t1909.scala @@ -6,3 +6,7 @@ class Ticket1909 { def this(value: Int) = this() def this(p: String) = this(try 0) } + +object Test extends App { + new Ticket1909("") +} diff --git a/test/files/pos/t1909b-pos.scala b/test/files/run/t1909b.scala index b914bee366..89b2af57dc 100644 --- a/test/files/pos/t1909b-pos.scala +++ b/test/files/run/t1909b.scala @@ -3,4 +3,7 @@ class Ticket1909 (x: Int) { def bar() = 5 bar }) -}
\ No newline at end of file +} +object Test extends App { + new Ticket1909() +} diff --git a/test/files/run/t1909c.scala b/test/files/run/t1909c.scala new file mode 100644 index 0000000000..87c0eb08b5 --- /dev/null +++ b/test/files/run/t1909c.scala @@ -0,0 +1,9 @@ +class Base(a: Any) + +// java.lang.VerifyError: (class: Sub, method: <init> signature: ()V) Expecting to find object/array on stack +// at Test$.<init>(t1909c.scala) +class Sub() extends Base({ def bippy = 5; bippy }) + +object Test extends App { + new Sub() +} diff --git a/test/files/run/t3832.scala b/test/files/run/t3832.scala new file mode 100644 index 0000000000..ac44358bc7 --- /dev/null +++ b/test/files/run/t3832.scala @@ -0,0 +1,17 @@ +class t3832 { + def this(un: Int) = { + this() + def bippy = this + () + } + def this(un: Boolean) = { + this() + def boppy = () => this + () + } +} + +object Test extends App { + new t3832(0) + new t3832(true) +} diff --git a/test/files/run/t7223.check b/test/files/run/t7223.check new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/test/files/run/t7223.check @@ -0,0 +1 @@ +0 diff --git a/test/files/run/t7223.scala b/test/files/run/t7223.scala new file mode 100644 index 0000000000..a707e957df --- /dev/null +++ b/test/files/run/t7223.scala @@ -0,0 +1,11 @@ +class D(val a: () => Int => () => Any) { + a()(0)() +} + +object Crash extends D(() => { + (x: Int) => {() => { new { println(x.toString) } }} +}) + +object Test extends App { + Crash +} diff --git a/test/files/scalacheck/quasiquotes/DeprecationProps.scala b/test/files/scalacheck/quasiquotes/DeprecationProps.scala new file mode 100644 index 0000000000..8e1601cf9d --- /dev/null +++ b/test/files/scalacheck/quasiquotes/DeprecationProps.scala @@ -0,0 +1,52 @@ +import org.scalacheck._, Prop._, Gen._, Arbitrary._ +import scala.reflect.runtime.universe._ + +object DeprecationProps extends QuasiquoteProperties("deprecation") { + val tname = TypeName("Foo") + val tpt = tq"Foo" + val tpe = typeOf[Int] + val sym = tpe.typeSymbol.asType + val argss = List(q"x") :: List(q"y") :: Nil + val args = q"x" :: q"y" :: Nil + + property("new tpt argss") = test { + assert(q"new $tpt(...$argss)" ≈ New(tpt, argss)) + } + + property("new tpe args") = test { + assert(q"new $tpe(..$args)" ≈ New(tpe, args: _*)) + } + + property("new tpe args") = test { + assert(q"new ${sym.toType}(..$args)" ≈ New(sym, args: _*)) + } + + property("apply sym args") = test { + assert(q"$sym(..$args)" ≈ Apply(sym, args: _*)) + } + + property("applyconstructor") = test { + assert(q"new $tpt(..$args)" ≈ ApplyConstructor(tpt, args)) + } + + property("super sym name") = test { + assert(q"$sym.super[$tname].x".qualifier ≈ Super(sym, tname)) + } + + property("throw tpe args") = test { + assert(q"throw new $tpe(..$args)" ≈ Throw(tpe, args: _*)) + } + + property("casedef pat body") = test { + val pat = pq"foo" + val body = q"bar" + assert(cq"$pat => $body" ≈ CaseDef(pat, body)) + } + + property("try body cases") = test { + val cases = (pq"a", q"b") :: (pq"c", q"d") :: Nil + val newcases = cases.map { case (pat, body) => cq"$pat => $body" } + val body = q"foo" + assert(q"try $body catch { case ..$newcases }" ≈ Try(body, cases: _*)) + } +}
\ No newline at end of file diff --git a/test/files/scalacheck/quasiquotes/Test.scala b/test/files/scalacheck/quasiquotes/Test.scala index 05097711ef..f41d961888 100644 --- a/test/files/scalacheck/quasiquotes/Test.scala +++ b/test/files/scalacheck/quasiquotes/Test.scala @@ -11,4 +11,5 @@ object Test extends Properties("quasiquotes") { include(ErrorProps) include(DefinitionConstructionProps) include(DefinitionDeconstructionProps) -}
\ No newline at end of file + include(DeprecationProps) +} diff --git a/test/junit/scala/tools/nsc/symtab/StdNamesTest.scala b/test/junit/scala/tools/nsc/symtab/StdNamesTest.scala new file mode 100644 index 0000000000..05e69978c6 --- /dev/null +++ b/test/junit/scala/tools/nsc/symtab/StdNamesTest.scala @@ -0,0 +1,46 @@ +package scala.tools.nsc +package symtab + +import org.junit.Assert._ +import scala.tools.testing.AssertUtil._ +import org.junit.{Ignore, Test} +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(classOf[JUnit4]) +class StdNamesTest { + object symbolTable extends SymbolTableForUnitTesting + import symbolTable._ + import nme.{SPECIALIZED_SUFFIX, unspecializedName, splitSpecializedName} + + @Test + def testNewTermNameInvalid(): Unit = { + assertThrows[IllegalArgumentException](newTermName("foo".toCharArray, 0, -1)) + assertThrows[IllegalArgumentException](newTermName("foo".toCharArray, 0, 0)) + assertThrows[IllegalArgumentException](newTermName("foo".toCharArray, -1, 1)) + } + + @Test + def testUnspecializedName(): Unit = { + def test(expected: Name, nme: Name) { + assertEquals(expected, unspecializedName(nme)) + } + test(TermName("Tuple2"), TermName("Tuple2$mcII" + SPECIALIZED_SUFFIX)) + test(TermName("foo"), TermName("foo$mIcD" + SPECIALIZED_SUFFIX)) + test(TermName("foo"), TermName("foo$mIc" + SPECIALIZED_SUFFIX)) + test(TermName("T1"), TermName(s"T1$SPECIALIZED_SUFFIX")) + test(TermName(""), SPECIALIZED_SUFFIX) + } + + @Test + def testSplitSpecializedName(): Unit = { + def test(expected: (Name, String, String), nme: Name) { + assertEquals(expected, splitSpecializedName(nme)) + } + test((TermName("Tuple2"), "II", ""), TermName("Tuple2$mcII" + SPECIALIZED_SUFFIX)) + test((TermName("foo"), "D", "I"), TermName("foo$mIcD" + SPECIALIZED_SUFFIX)) + test((TermName("foo"), "", "I"), TermName("foo$mIc" + SPECIALIZED_SUFFIX)) + test((TermName("T1"), "", ""), TermName(s"T1$SPECIALIZED_SUFFIX")) + test((TermName(""), "", ""), SPECIALIZED_SUFFIX) + } +} |