diff options
27 files changed, 310 insertions, 126 deletions
diff --git a/src/compiler/scala/tools/nsc/doc/model/Links.scala b/src/compiler/scala/tools/nsc/doc/model/LinkTo.scala index b76dee0f14..b76dee0f14 100644 --- a/src/compiler/scala/tools/nsc/doc/model/Links.scala +++ b/src/compiler/scala/tools/nsc/doc/model/LinkTo.scala diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala index bbe22ca314..28dfd3fc77 100644 --- a/src/compiler/scala/tools/nsc/matching/Patterns.scala +++ b/src/compiler/scala/tools/nsc/matching/Patterns.scala @@ -402,7 +402,7 @@ trait Patterns extends ast.TreeDSL { case _ => toPats(args) } - def resTypes = analyzer.unapplyTypeList(unfn.symbol, unfn.tpe) + def resTypes = analyzer.unapplyTypeList(unfn.symbol, unfn.tpe, args.length) def resTypesString = resTypes match { case Nil => "Boolean" case xs => xs.mkString(", ") diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 2983c65e78..5c0207e5c7 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -618,7 +618,7 @@ abstract class UnCurry extends InfoTransform val fn1 = withInPattern(false)(transform(fn)) val args1 = transformTrees(fn.symbol.name match { case nme.unapply => args - case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeListFromReturnTypeSeq(fn.tpe)) + case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeList(fn.symbol, fn.tpe, args.length)) case _ => sys.error("internal error: UnApply node has wrong symbol") }) treeCopy.UnApply(tree, fn1, args1) diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala index 960c210649..bcbcb96400 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -49,6 +49,69 @@ trait Infer { } else formals1 } + /** Returns `(formals, formalsExpanded)` where `formalsExpanded` are the expected types + * for the `nbSubPats` sub-patterns of an extractor pattern, of which the corresponding + * unapply[Seq] call is assumed to have result type `resTp`. + * + * `formals` are the formal types before expanding a potential repeated parameter (must come last in `formals`, if at all) + * + * @throws TypeError when the unapply[Seq] definition is ill-typed + * @returns (null, null) when the expected number of sub-patterns cannot be satisfied by the given extractor + * + * From the spec: + * 8.1.8 ExtractorPatterns + * + * An extractor pattern x(p1, ..., pn) where n ≥ 0 is of the same syntactic form as a constructor pattern. + * However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matches the pattern. + * An unapply method in an object x matches the pattern x(p1, ..., pn) if it takes exactly one argument and one of the following applies: + * + * n = 0 and unapply’s result type is Boolean. + * + * n = 1 and unapply’s result type is Option[T], for some type T. + * the (only) argument pattern p1 is typed in turn with expected type T + * + * n > 1 and unapply’s result type is Option[(T1, ..., Tn)], for some types T1, ..., Tn. + * the argument patterns p1, ..., pn are typed in turn with expected types T1, ..., Tn + */ + def extractorFormalTypes(resTp: Type, nbSubPats: Int, unappSym: Symbol): (List[Type], List[Type]) = { + val isUnapplySeq = unappSym.name == nme.unapplySeq + val booleanExtractor = resTp.typeSymbolDirect == BooleanClass + + @inline def seqToRepeatedChecked(tp: Type) = { + val toRepeated = seqToRepeated(tp) + if (tp eq toRepeated) throw new TypeError("(the last tuple-component of) the result type of an unapplySeq must be a Seq[_]") + else toRepeated + } + + val formals = + if (nbSubPats == 0 && booleanExtractor && !isUnapplySeq) Nil + else resTp.baseType(OptionClass).typeArgs match { + case optionTArg :: Nil => + if (nbSubPats == 1) + if (isUnapplySeq) List(seqToRepeatedChecked(optionTArg)) + else List(optionTArg) + // TODO: update spec to reflect we allow any ProductN, not just TupleN + else getProductArgs(optionTArg) match { + case Nil if isUnapplySeq => List(seqToRepeatedChecked(optionTArg)) + case tps if isUnapplySeq => tps.init :+ seqToRepeatedChecked(tps.last) + case tps => tps + } + case _ => + if (isUnapplySeq) + throw new TypeError(s"result type $resTp of unapplySeq defined in ${unappSym.owner+unappSym.owner.locationString} not in {Option[_], Some[_]}") + else + throw new TypeError(s"result type $resTp of unapply defined in ${unappSym.owner+unappSym.owner.locationString} not in {Boolean, Option[_], Some[_]}") + } + + // for unapplySeq, replace last vararg by as many instances as required by nbSubPats + val formalsExpanded = + if (isUnapplySeq && formals.nonEmpty) formalTypes(formals, nbSubPats) + else formals + + if (formalsExpanded.lengthCompare(nbSubPats) != 0) (null, null) + else (formals, formalsExpanded) + } + def actualTypes(actuals: List[Type], nformals: Int): List[Type] = if (nformals == 1 && !hasLength(actuals, 1)) List(if (actuals.isEmpty) UnitClass.tpe else tupleType(actuals)) @@ -445,7 +508,7 @@ trait Infer { val tvars = tparams map freshVar if (isConservativelyCompatible(restpe.instantiateTypeParams(tparams, tvars), pt)) map2(tparams, tvars)((tparam, tvar) => - instantiateToBound(tvar, varianceInTypes(formals)(tparam))) + instantiateToBound(tvar, inferVariance(formals, restpe)(tparam))) else tvars map (tvar => WildcardType) } @@ -575,13 +638,24 @@ trait Infer { "argument expression's type is not compatible with formal parameter type" + foundReqMsg(tp1, pt1)) } } + val targs = solvedTypes( - tvars, tparams, tparams map varianceInTypes(formals), + tvars, tparams, tparams map inferVariance(formals, restpe), false, lubDepth(formals) max lubDepth(argtpes) ) adjustTypeArgs(tparams, tvars, targs, restpe) } + /** Determine which variance to assume for the type paraneter. We first chose the variance + * that minimizes any formal parameters. If that is still undetermined, because the type parameter + * does not appear as a formal parameter type, then we pick the variance so that it minimizes the + * method's result type instead. + */ + private def inferVariance(formals: List[Type], restpe: Type)(tparam: Symbol): Int = { + val v = varianceInTypes(formals)(tparam) + if (v != VarianceFlags) v else varianceInType(restpe)(tparam) + } + private[typechecker] def followApply(tp: Type): Type = tp match { case NullaryMethodType(restp) => val restp1 = followApply(restp) @@ -1278,8 +1352,10 @@ trait Infer { } else { for (arg <- args) { if (sym == ArrayClass) check(arg, bound) - else if (arg.typeArgs.nonEmpty) () // avoid spurious warnings with higher-kinded types - else if (sym == NonLocalReturnControlClass) () // no way to suppress unchecked warnings on try/catch + // avoid spurious warnings with higher-kinded types + else if (arg.typeArgs exists (_.typeSymbol.isTypeParameterOrSkolem)) () + // no way to suppress unchecked warnings on try/catch + else if (sym == NonLocalReturnControlClass) () else arg match { case TypeRef(_, sym, _) if isLocalBinding(sym) => ; @@ -1423,7 +1499,7 @@ trait Infer { ) // Intentionally *not* using `Type#typeSymbol` here, which would normalize `tp` - // and collect symbols from the result type of any resulting `PolyType`s, which + // and collect symbols from the result type of any resulting `PolyType`s, which // are not free type parameters of `tp`. // // Contrast with `isFreeTypeParamNoSkolem`. @@ -1456,7 +1532,7 @@ trait Infer { def inferExprAlternative(tree: Tree, pt: Type) = tree.tpe match { case OverloadedType(pre, alts) => tryTwice { isSecondTry => val alts0 = alts filter (alt => isWeaklyCompatible(pre.memberType(alt), pt)) - val noAlternatives = alts0.isEmpty + val noAlternatives = alts0.isEmpty val alts1 = if (noAlternatives) alts else alts0 //println("trying "+alts1+(alts1 map (_.tpe))+(alts1 map (_.locationString))+" for "+pt) @@ -1614,7 +1690,7 @@ trait Infer { val saved = context.state var fallback = false context.setBufferErrors() - // We cache the current buffer because it is impossible to + // We cache the current buffer because it is impossible to // distinguish errors that occurred before entering tryTwice // and our first attempt in 'withImplicitsDisabled'. If the // first attempt fails we try with implicits on *and* clean diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 43edad3576..8b7c70c048 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -218,11 +218,6 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL if(phase.id >= currentRun.uncurryPhase.id) debugwarn("running translateMatch at "+ phase +" on "+ selector +" match "+ cases) patmatDebug("translating "+ cases.mkString("{", "\n", "}")) - def repeatedToSeq(tp: Type): Type = (tp baseType RepeatedParamClass) match { - case TypeRef(_, RepeatedParamClass, arg :: Nil) => seqType(arg) - case _ => tp - } - val start = Statistics.startTimer(patmatNanos) val selectorTp = repeatedToSeq(elimAnonymousClass(selector.tpe.widen.withoutAnnotations)) diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index dbe65c16d8..51753baa4f 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2749,6 +2749,14 @@ trait Typers extends Modes with Adaptations with Tags { def typedArgs(args: List[Tree], mode: Int) = args mapConserve (arg => typedArg(arg, mode, 0, WildcardType)) + /** Type trees in `args0` against corresponding expected type in `adapted0`. + * + * The mode in which each argument is typed is derived from `mode` and + * whether the arg was originally by-name or var-arg (need `formals0` for that) + * the default is by-val, of course. + * + * (docs reverse-engineered -- AM) + */ def typedArgs(args0: List[Tree], mode: Int, formals0: List[Type], adapted0: List[Type]): List[Tree] = { val sticky = onlyStickyModes(mode) def loop(args: List[Tree], formals: List[Type], adapted: List[Type]): List[Tree] = { @@ -3157,12 +3165,13 @@ trait Typers extends Modes with Adaptations with Tags { if (fun1.tpe.isErroneous) duplErrTree else { - val formals0 = unapplyTypeList(fun1.symbol, fun1.tpe) - val formals1 = formalTypes(formals0, args.length) + val resTp = fun1.tpe.finalResultType.normalize + val nbSubPats = args.length - if (!sameLength(formals1, args)) duplErrorTree(WrongNumberArgsPatternError(tree, fun)) + val (formals, formalsExpanded) = extractorFormalTypes(resTp, nbSubPats, fun1.symbol) + if (formals == null) duplErrorTree(WrongNumberArgsPatternError(tree, fun)) else { - val args1 = typedArgs(args, mode, formals0, formals1) + val args1 = typedArgs(args, mode, formals, formalsExpanded) // This used to be the following (failing) assert: // assert(isFullyDefined(pt), tree+" ==> "+UnApply(fun1, args1)+", pt = "+pt) // I modified as follows. See SI-1048. @@ -4652,15 +4661,28 @@ trait Typers extends Modes with Adaptations with Tags { // If the ambiguous name is a monomorphic type, we can relax this far. def mt1 = t1 memberType impSym def mt2 = t2 memberType impSym1 + def characterize = List( + s"types: $t1 =:= $t2 ${t1 =:= t2} members: ${mt1 =:= mt2}", + s"member type 1: $mt1", + s"member type 2: $mt2", + s"$impSym == $impSym1 ${impSym == impSym1}", + s"${impSym.debugLocationString} ${impSym.getClass}", + s"${impSym1.debugLocationString} ${impSym1.getClass}" + ).mkString("\n ") + + // The symbol names are checked rather than the symbols themselves because + // each time an overloaded member is looked up it receives a new symbol. + // So foo.member("x") != foo.member("x") if x is overloaded. This seems + // likely to be the cause of other bugs too... + if (t1 =:= t2 && impSym.name == impSym1.name) + log(s"Suppressing ambiguous import: $t1 =:= $t2 && $impSym == $impSym1") // Monomorphism restriction on types is in part because type aliases could have the // same target type but attach different variance to the parameters. Maybe it can be // relaxed, but doesn't seem worth it at present. - if (t1 =:= t2 && impSym == impSym1) - log(s"Suppressing ambiguous import: $t1 =:= $t2 && $impSym == $impSym1") else if (mt1 =:= mt2 && name.isTypeName && impSym.isMonomorphicType && impSym1.isMonomorphicType) log(s"Suppressing ambiguous import: $mt1 =:= $mt2 && $impSym and $impSym1 are equivalent") else { - log(s"Import is genuinely ambiguous: !($t1 =:= $t2)") + log(s"Import is genuinely ambiguous:\n " + characterize) ambiguousError(s"it is imported twice in the same scope by\n${imports.head}\nand ${imports1.head}") } } @@ -4880,7 +4902,7 @@ trait Typers extends Modes with Adaptations with Tags { case UnApply(fun, args) => val fun1 = typed(fun) - val tpes = formalTypes(unapplyTypeList(fun.symbol, fun1.tpe), args.length) + val tpes = formalTypes(unapplyTypeList(fun.symbol, fun1.tpe, args.length), args.length) val args1 = map2(args, tpes)(typedPattern) treeCopy.UnApply(tree, fun1, args1) setType pt diff --git a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala index ad936ac39d..d508e10813 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala @@ -31,59 +31,18 @@ trait Unapplies extends ast.TreeDSL // moduleClass symbol of the companion module. class ClassForCaseCompanionAttachment(val caseClass: ClassDef) - /** returns type list for return type of the extraction */ - def unapplyTypeList(ufn: Symbol, ufntpe: Type) = { + /** returns type list for return type of the extraction + * @see extractorFormalTypes + */ + def unapplyTypeList(ufn: Symbol, ufntpe: Type, nbSubPats: Int) = { assert(ufn.isMethod, ufn) //Console.println("utl "+ufntpe+" "+ufntpe.typeSymbol) ufn.name match { - case nme.unapply => unapplyTypeListFromReturnType(ufntpe) - case nme.unapplySeq => unapplyTypeListFromReturnTypeSeq(ufntpe) - case _ => throw new TypeError(ufn+" is not an unapply or unapplySeq") - } - } - /** (the inverse of unapplyReturnTypeSeq) - * for type Boolean, returns Nil - * for type Option[T] or Some[T]: - * - returns T0...Tn if n>0 and T <: Product[T0...Tn]] - * - returns T otherwise - */ - def unapplyTypeListFromReturnType(tp1: Type): List[Type] = { - val tp = unapplyUnwrap(tp1) - tp.typeSymbol match { // unapplySeqResultToMethodSig - case BooleanClass => Nil - case OptionClass | SomeClass => - val prod = tp.typeArgs.head -// the spec doesn't allow just any subtype of Product, it *must* be TupleN[...] -- see run/virtpatmat_extends_product.scala -// this breaks plenty of stuff, though... -// val targs = -// if (isTupleType(prod)) getProductArgs(prod) -// else List(prod) - val targs = getProductArgs(prod) - - if (targs.isEmpty || targs.tail.isEmpty) List(prod) // special n == 0 || n == 1 - else targs // n > 1 - case _ => - throw new TypeError("result type "+tp+" of unapply not in {Boolean, Option[_], Some[_]}") - } - } - - /** let type be the result type of the (possibly polymorphic) unapply method - * for type Option[T] or Some[T] - * -returns T0...Tn-1,Tn* if n>0 and T <: Product[T0...Tn-1,Seq[Tn]]], - * -returns R* if T = Seq[R] - */ - def unapplyTypeListFromReturnTypeSeq(tp1: Type): List[Type] = { - val tp = unapplyUnwrap(tp1) - tp.typeSymbol match { - case OptionClass | SomeClass => - val ts = unapplyTypeListFromReturnType(tp1) - val last1 = (ts.last baseType SeqClass) match { - case TypeRef(pre, SeqClass, args) => typeRef(pre, RepeatedParamClass, args) - case _ => throw new TypeError("last not seq") - } - ts.init :+ last1 - case _ => - throw new TypeError("result type "+tp+" of unapply not in {Option[_], Some[_]}") + case nme.unapply | nme.unapplySeq => + val (formals, _) = extractorFormalTypes(unapplyUnwrap(ufntpe), nbSubPats, ufn) + if (formals == null) throw new TypeError(s"$ufn of type $ufntpe cannot extract $nbSubPats sub-patterns") + else formals + case _ => throw new TypeError(ufn+" is not an unapply or unapplySeq") } } diff --git a/src/library/scala/math/Ordering.scala b/src/library/scala/math/Ordering.scala index ab685815a1..9020bb9edd 100644 --- a/src/library/scala/math/Ordering.scala +++ b/src/library/scala/math/Ordering.scala @@ -28,7 +28,7 @@ import language.{implicitConversions, higherKinds} * Sorting.quickSort(pairs)(Ordering.by[(String, Int, Int), Int](_._2) * * // sort by the 3rd element, then 1st - * Sorting.quickSort(pairs)(Ordering[(Int, String)].on[(String, Int, Int)]((_._3, _._1)) + * Sorting.quickSort(pairs)(Ordering[(Int, String)].on(x => (x._3, x._1))) * }}} * * An Ordering[T] is implemented by specifying compare(a:T, b:T), which diff --git a/src/library/scala/reflect/ClassManifest.scala b/src/library/scala/reflect/ClassManifestDeprecatedApis.scala index d226e43e77..d226e43e77 100644 --- a/src/library/scala/reflect/ClassManifest.scala +++ b/src/library/scala/reflect/ClassManifestDeprecatedApis.scala diff --git a/src/library/scala/reflect/base/Base.scala b/src/library/scala/reflect/base/Base.scala index 4457a6cf14..5df48307fe 100644 --- a/src/library/scala/reflect/base/Base.scala +++ b/src/library/scala/reflect/base/Base.scala @@ -96,8 +96,8 @@ class Base extends Universe { self => // todo. write a decent toString that doesn't crash on recursive types class Type extends TypeBase { - def typeSymbol: Symbol = NoSymbol def termSymbol: Symbol = NoSymbol + def typeSymbol: Symbol = NoSymbol } implicit val TypeTagg = ClassTag[Type](classOf[Type]) diff --git a/src/library/scala/reflect/base/Types.scala b/src/library/scala/reflect/base/Types.scala index 6e8ffc7984..28aaf2d04d 100644 --- a/src/library/scala/reflect/base/Types.scala +++ b/src/library/scala/reflect/base/Types.scala @@ -3,25 +3,14 @@ package base trait Types { self: Universe => - /** The base API that all types support */ - abstract class TypeBase { - - /** The term symbol associated with the type, or `NoSymbol` for types - * that do not refer to a term symbol. - */ - def termSymbol: Symbol - - /** The type symbol associated with the type, or `NoSymbol` for types - * that do not refer to a type symbol. - */ - def typeSymbol: Symbol - } - /** The type of Scala types, and also Scala type signatures. * (No difference is internally made between the two). */ type Type >: Null <: TypeBase + /** The base API that all types support */ + abstract class TypeBase + /** A tag that preserves the identity of the `Type` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. */ diff --git a/src/reflect/scala/reflect/api/Types.scala b/src/reflect/scala/reflect/api/Types.scala index 231b9b248b..01de5fa9a7 100644 --- a/src/reflect/scala/reflect/api/Types.scala +++ b/src/reflect/scala/reflect/api/Types.scala @@ -8,6 +8,15 @@ trait Types extends base.Types { self: Universe => /** The extended API of types */ abstract class TypeApi extends TypeBase { + /** The term symbol associated with the type, or `NoSymbol` for types + * that do not refer to a term symbol. + */ + def termSymbol: Symbol + + /** The type symbol associated with the type, or `NoSymbol` for types + * that do not refer to a type symbol. + */ + def typeSymbol: Symbol /** The defined or declared members with name `name` in this type; * an OverloadedSymbol if several exist, NoSymbol if none exist. diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index d9b63529eb..90aa0b732c 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -397,6 +397,16 @@ trait Definitions extends api.StandardDefinitions { case _ => false } + def repeatedToSeq(tp: Type): Type = (tp baseType RepeatedParamClass) match { + case TypeRef(_, RepeatedParamClass, arg :: Nil) => seqType(arg) + case _ => tp + } + + def seqToRepeated(tp: Type): Type = (tp baseType SeqClass) match { + case TypeRef(_, SeqClass, arg :: Nil) => scalaRepeatedType(arg) + case _ => tp + } + def isPrimitiveArray(tp: Type) = tp match { case TypeRef(_, ArrayClass, arg :: Nil) => isPrimitiveValueClass(arg.typeSymbol) case _ => false diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index e92d644f4a..619e3bc170 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -469,7 +469,7 @@ trait Trees extends api.Trees { self: SymbolTable => private var orig: Tree = null private[scala] var wasEmpty: Boolean = false - override def symbol = if (tpe == null) null else tpe.typeSymbol + override def symbol = typeTreeSymbol(this) // if (tpe == null) null else tpe.typeSymbol override def isEmpty = (tpe eq null) || tpe == NoType def original: Tree = orig @@ -1024,6 +1024,14 @@ trait Trees extends api.Trees { self: SymbolTable => } } + + /** Delegate for a TypeTree symbol. This operation is unsafe because + * it may trigger type checking when forcing the type symbol of the + * underlying type. + */ + protected def typeTreeSymbol(tree: TypeTree): Symbol = + if (tree.tpe == null) null else tree.tpe.typeSymbol + // --- generic traversers and transformers override protected def itraverse(traverser: Traverser, tree: Tree): Unit = { diff --git a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala index 5fbeb5f576..cecf8e4658 100644 --- a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala +++ b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala @@ -8,7 +8,8 @@ trait TraceSymbolActivity { val global: SymbolTable import global._ - if (traceSymbolActivity && global.isCompilerUniverse) + private[this] var enabled = traceSymbolActivity + if (enabled && global.isCompilerUniverse) scala.sys addShutdownHook showAllSymbols() private type Set[T] = scala.collection.immutable.Set[T] @@ -21,23 +22,26 @@ trait TraceSymbolActivity { val allTrees = mutable.Set[Tree]() def recordSymbolsInTree(tree: Tree) { - allTrees += tree + if (enabled) + allTrees += tree } def recordNewSymbol(sym: Symbol) { - if (sym.id > 1) { + if (enabled && sym.id > 1) { allSymbols(sym.id) = sym allChildren(sym.owner.id) ::= sym.id } } def recordNewSymbolOwner(sym: Symbol, newOwner: Symbol) { - val sid = sym.id - val oid = sym.owner.id - val nid = newOwner.id - - prevOwners(sid) ::= (oid -> phase) - allChildren(oid) = allChildren(oid) filterNot (_ == sid) - allChildren(nid) ::= sid + if (enabled) { + val sid = sym.id + val oid = sym.owner.id + val nid = newOwner.id + + prevOwners(sid) ::= (oid -> phase) + allChildren(oid) = allChildren(oid) filterNot (_ == sid) + allChildren(nid) ::= sid + } } /** TODO. @@ -86,7 +90,7 @@ trait TraceSymbolActivity { def prefix = (" " * (sym.ownerChain.length - 1)) + sym.id try println("%s#%s %s".format(prefix, sym.accurateKindString, sym.name.decode)) catch { - case x => println(prefix + " failed: " + x) + case x: Throwable => println(prefix + " failed: " + x) } allChildren(sym.id).sorted foreach showIdAndRemove } @@ -128,7 +132,8 @@ trait TraceSymbolActivity { private def runBeforeErasure[T](body: => T): T = atPhase(findErasurePhase)(body) def showAllSymbols() { - if (!traceSymbolActivity) return + if (!enabled) return + enabled = false allSymbols(1) = NoSymbol println("" + allSymbols.size + " symbols created.") diff --git a/src/reflect/scala/reflect/runtime/TwoWayCache.scala b/src/reflect/scala/reflect/runtime/TwoWayCache.scala index c7bfb3435d..e2bf5773d2 100644 --- a/src/reflect/scala/reflect/runtime/TwoWayCache.scala +++ b/src/reflect/scala/reflect/runtime/TwoWayCache.scala @@ -1,27 +1,40 @@ package scala.reflect package runtime +import collection.mutable.WeakHashMap +import java.lang.ref.WeakReference + /** A cache that maintains a bijection between Java reflection type `J` * and Scala reflection type `S`. + * + * The cache is two-way weak (i.e. is powered by weak references), + * so that neither Java artifacts prevent Scala artifacts from being garbage collected, + * nor the other way around. */ -import collection.mutable.HashMap - private[runtime] class TwoWayCache[J, S] { - private val toScalaMap = new HashMap[J, S] - private val toJavaMap = new HashMap[S, J] + private val toScalaMap = new WeakHashMap[J, WeakReference[S]] + private val toJavaMap = new WeakHashMap[S, WeakReference[J]] def enter(j: J, s: S) = synchronized { // debugInfo("cached: "+j+"/"+s) - toScalaMap(j) = s - toJavaMap(s) = j + toScalaMap(j) = new WeakReference(s) + toJavaMap(s) = new WeakReference(j) + } + + private object SomeRef { + def unapply[T](optRef: Option[WeakReference[T]]): Option[T] = + if (optRef.nonEmpty) { + val result = optRef.get.get + if (result != null) Some(result) else None + } else None } def toScala(key: J)(body: => S): S = synchronized { toScalaMap get key match { - case Some(v) => + case SomeRef(v) => v - case none => + case _ => val result = body enter(key, result) result @@ -30,9 +43,9 @@ private[runtime] class TwoWayCache[J, S] { def toJava(key: S)(body: => J): J = synchronized { toJavaMap get key match { - case Some(v) => + case SomeRef(v) => v - case none => + case _ => val result = body enter(result, key) result @@ -41,11 +54,12 @@ private[runtime] class TwoWayCache[J, S] { def toJavaOption(key: S)(body: => Option[J]): Option[J] = synchronized { toJavaMap get key match { - case None => + case SomeRef(v) => + Some(v) + case _ => val result = body for (value <- result) enter(value, key) result - case some => some } } } diff --git a/test/files/neg/t5845.check b/test/files/neg/t5845.check index 8c6100d6de..c0b402fccb 100644 --- a/test/files/neg/t5845.check +++ b/test/files/neg/t5845.check @@ -1,7 +1,4 @@ -t5845.scala:9: error: value +++ is not a member of Int - println(5 +++ 5) - ^ t5845.scala:15: error: value +++ is not a member of Int println(5 +++ 5) ^ -two errors found +one error found diff --git a/test/files/neg/t997.check b/test/files/neg/t997.check index c9fe0de756..186095f44a 100644 --- a/test/files/neg/t997.check +++ b/test/files/neg/t997.check @@ -1,13 +1,7 @@ -t997.scala:7: error: wrong number of arguments for object Foo -"x" match { case Foo(a) => Console.println(a) } - ^ -t997.scala:7: error: not found: value a -"x" match { case Foo(a) => Console.println(a) } - ^ t997.scala:13: error: wrong number of arguments for object Foo "x" match { case Foo(a, b, c) => Console.println((a,b,c)) } ^ t997.scala:13: error: not found: value a "x" match { case Foo(a, b, c) => Console.println((a,b,c)) } ^ -four errors found +two errors found diff --git a/test/files/neg/t997.scala b/test/files/neg/t997.scala index 42b46174d6..e8d10f4317 100644 --- a/test/files/neg/t997.scala +++ b/test/files/neg/t997.scala @@ -3,7 +3,7 @@ object Foo { def unapply(x : String) = Some(Pair(x, x)) } object Test extends App { -// Prints 'x'; ought not to compile (or maybe a should be the Pair?). +// Prints '(x, x)'. Should compile as per SI-6111. "x" match { case Foo(a) => Console.println(a) } // Prints '(x,x)' as expected. diff --git a/test/files/neg/unchecked2.check b/test/files/neg/unchecked2.check new file mode 100644 index 0000000000..2c0be9ce00 --- /dev/null +++ b/test/files/neg/unchecked2.check @@ -0,0 +1,19 @@ +unchecked2.scala:2: error: non variable type-argument Int in type Option[Int] is unchecked since it is eliminated by erasure + Some(123).isInstanceOf[Option[Int]] + ^ +unchecked2.scala:3: error: non variable type-argument String in type Option[String] is unchecked since it is eliminated by erasure + Some(123).isInstanceOf[Option[String]] + ^ +unchecked2.scala:4: error: non variable type-argument List[String] in type Option[List[String]] is unchecked since it is eliminated by erasure + Some(123).isInstanceOf[Option[List[String]]] + ^ +unchecked2.scala:5: error: non variable type-argument List[Int => String] in type Option[List[Int => String]] is unchecked since it is eliminated by erasure + Some(123).isInstanceOf[Option[List[Int => String]]] + ^ +unchecked2.scala:6: error: non variable type-argument (String, Double) in type Option[(String, Double)] is unchecked since it is eliminated by erasure + Some(123).isInstanceOf[Option[(String, Double)]] + ^ +unchecked2.scala:7: error: non variable type-argument String => Double in type Option[String => Double] is unchecked since it is eliminated by erasure + Some(123).isInstanceOf[Option[String => Double]] + ^ +6 errors found diff --git a/test/files/neg/unchecked2.flags b/test/files/neg/unchecked2.flags new file mode 100644 index 0000000000..144ddac9d3 --- /dev/null +++ b/test/files/neg/unchecked2.flags @@ -0,0 +1 @@ +-unchecked -Xfatal-warnings diff --git a/test/files/neg/unchecked2.scala b/test/files/neg/unchecked2.scala new file mode 100644 index 0000000000..a2e757e1dc --- /dev/null +++ b/test/files/neg/unchecked2.scala @@ -0,0 +1,8 @@ +object Test { + Some(123).isInstanceOf[Option[Int]] + Some(123).isInstanceOf[Option[String]] + Some(123).isInstanceOf[Option[List[String]]] + Some(123).isInstanceOf[Option[List[Int => String]]] + Some(123).isInstanceOf[Option[(String, Double)]] + Some(123).isInstanceOf[Option[String => Double]] +} diff --git a/test/files/pos/t1439.scala b/test/files/pos/t1439.scala index 68a7332b2a..0efcc74b65 100644 --- a/test/files/pos/t1439.scala +++ b/test/files/pos/t1439.scala @@ -2,7 +2,7 @@ class View[C[A]] { } object Test { - null match { + (null: Any) match { case v: View[_] => } } diff --git a/test/files/pos/t4881.scala b/test/files/pos/t4881.scala new file mode 100644 index 0000000000..46cfad9793 --- /dev/null +++ b/test/files/pos/t4881.scala @@ -0,0 +1,31 @@ +class Contra[-T] +trait A +trait B extends A +trait C extends B + +// test improved variance inference: first try formals to see in which variance positions the type param appears; +// only when that fails to determine variance, look at result type +object Test { + def contraLBUB[a >: C <: A](): Contra[a] = null + def contraLB[a >: C](): Contra[a] = null + +{ + val x = contraLBUB() //inferred Contra[C] instead of Contra[A] + val x1: Contra[A] = x +} + +{ + val x = contraLB() //inferred Contra[C] instead of Contra[Any] + val x1: Contra[Any] = x +} + +{ + val x = contraLBUB // make sure it does the same thing as its ()-less counterpart + val x1: Contra[A] = x +} + +{ + val x = contraLB + val x1: Contra[Any] = x +} +} diff --git a/test/files/pos/t6117.scala b/test/files/pos/t6117.scala new file mode 100644 index 0000000000..6aca84f72c --- /dev/null +++ b/test/files/pos/t6117.scala @@ -0,0 +1,19 @@ +package test + +trait ImportMe { + def foo(i: Int) = 1 + def foo(s: String) = 2 +} + +class Test(val importMe: ImportMe) { + import importMe._ + import importMe._ + + // A.scala:12: error: reference to foo is ambiguous; + // it is imported twice in the same scope by + // import importMe._ + // and import importMe._ + // println(foo(1)) + // ^ + println(foo(1)) +} diff --git a/test/files/run/t6111.check b/test/files/run/t6111.check new file mode 100644 index 0000000000..7fd2e33526 --- /dev/null +++ b/test/files/run/t6111.check @@ -0,0 +1,2 @@ +(8,8) +(x,x) diff --git a/test/files/run/t6111.scala b/test/files/run/t6111.scala new file mode 100644 index 0000000000..7cceea1d09 --- /dev/null +++ b/test/files/run/t6111.scala @@ -0,0 +1,26 @@ +// slightly overkill, but a good test case for implicit resolution in extractor calls, +// along with the real fix: an extractor pattern with 1 sub-pattern should type check for all extractors +// that return Option[T], whatever T (even if it's a tuple) +object Foo { + def unapply[S, T](scrutinee: S)(implicit witness: FooHasType[S, T]): Option[T] = scrutinee match { + case i: Int => Some((i, i).asInstanceOf[T]) + } +} + +class FooHasType[S, T] +object FooHasType { + implicit object int extends FooHasType[Int, (Int, Int)] +} + +// resurrected from neg/t997 +object Foo997 { def unapply(x : String): Option[(String, String)] = Some((x, x)) } + +object Test extends App { + val x = 8 + println(x match { + case Foo(p) => p // p should be a pair of Int + }) + + // Prints '(x, x)' + "x" match { case Foo997(a) => println(a) } +}
\ No newline at end of file |