From 103a478dfc1b3f918e0643333635e3d8d254a9a0 Mon Sep 17 00:00:00 2001 From: Eugene Vigdorchik Date: Tue, 18 Dec 2012 18:20:37 +0400 Subject: SI-6803: do not use java.net.URI, even more so incorrectly. --- src/compiler/scala/tools/nsc/doc/Settings.scala | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/doc/Settings.scala b/src/compiler/scala/tools/nsc/doc/Settings.scala index 10a0d8d879..02630a99b2 100644 --- a/src/compiler/scala/tools/nsc/doc/Settings.scala +++ b/src/compiler/scala/tools/nsc/doc/Settings.scala @@ -7,8 +7,6 @@ package scala.tools.nsc package doc import java.io.File -import java.net.URI -import java.lang.System import scala.language.postfixOps /** An extended version of compiler settings, with additional Scaladoc-specific options. @@ -72,10 +70,10 @@ class Settings(error: String => Unit, val printMsg: String => Unit = println(_)) "" ) - val docExternalUris = MultiStringSetting ( - "-doc-external-uris", + val docExternalDoc = MultiStringSetting ( + "-doc-external-doc", "external-doc", - "comma-separated list of file://classpath_entry_path#doc_URL URIs for external dependencies" + "comma-separated list of classpath_entry_path#doc_URL pairs describing external dependencies." ) val useStupidTypes = BooleanSetting ( @@ -265,9 +263,15 @@ class Settings(error: String => Unit, val printMsg: String => Unit = println(_)) map ++ (pkgs map (_ -> url)) } - lazy val extUrlMapping: Map[String, String] = docExternalUris.value map { s => - val uri = new URI(s) - uri.getSchemeSpecificPart -> appendIndex(uri.getFragment) + lazy val extUrlMapping: Map[String, String] = docExternalDoc.value flatMap { s => + val idx = s.indexOf("#") + if (idx > 0) { + val (first, last) = s.splitAt(idx) + Some(new File(first).getAbsolutePath -> appendIndex(last.substring(1))) + } else { + error(s"Illegal -doc-external-doc option; expected a pair with '#' separator, found: '$s'") + None + } } toMap /** -- cgit v1.2.3 From c58647f5f25e9d99cb1890a32af4621c4d4645fa Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Sun, 6 Jan 2013 12:25:03 -0800 Subject: SI-6928, VerifyError with self reference to super. A bug in typers mishandled varargs. We should get more aggressive about eliminating all the ad hoc parameter/argument handling code spread everywhere. For varargs especially: any code which tries to make an adjustment based on a repeated parameter is more likely to be wrong than right. In aggregate these reinventions are a huge source of bugs. --- .../scala/tools/nsc/typechecker/Typers.scala | 91 +++++++++++----------- test/files/neg/t6928.check | 7 ++ test/files/neg/t6928.scala | 10 +++ test/files/run/t6928-run.check | 1 + test/files/run/t6928-run.scala | 10 +++ 5 files changed, 75 insertions(+), 44 deletions(-) create mode 100644 test/files/neg/t6928.check create mode 100644 test/files/neg/t6928.scala create mode 100644 test/files/run/t6928-run.check create mode 100644 test/files/run/t6928-run.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 9d390476db..1dce2c633d 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2070,57 +2070,60 @@ trait Typers extends Modes with Adaptations with Tags { */ def computeParamAliases(clazz: Symbol, vparamss: List[List[ValDef]], rhs: Tree) { debuglog(s"computing param aliases for $clazz:${clazz.primaryConstructor.tpe}:$rhs") + val pending = ListBuffer[AbsTypeError]() + + // !!! This method is redundant with other, less buggy ones. def decompose(call: Tree): (Tree, List[Tree]) = call match { case Apply(fn, args) => - val (superConstr, args1) = decompose(fn) + // an object cannot be allowed to pass a reference to itself to a superconstructor + // because of initialization issues; SI-473, SI-3913, SI-6928. + foreachSubTreeBoundTo(args, clazz) { tree => + if (tree.symbol.isModule) + pending += SuperConstrReferenceError(tree) + tree match { + case This(qual) => + pending += SuperConstrArgsThisReferenceError(tree) + case _ => () + } + } + val (superConstr, preArgs) = decompose(fn) val params = fn.tpe.params - val args2 = if (params.isEmpty || !isRepeatedParamType(params.last.tpe)) args - else args.take(params.length - 1) :+ EmptyTree - assert(sameLength(args2, params) || call.isErrorTyped, "mismatch " + clazz + " " + (params map (_.tpe)) + " " + args2)//debug - (superConstr, args1 ::: args2) - case Block(stats, expr) if !stats.isEmpty => - decompose(stats.last) + // appending a dummy tree to represent Nil for an empty varargs (is this really necessary?) + val applyArgs = if (args.length < params.length) args :+ EmptyTree else args take params.length + + assert(sameLength(applyArgs, params) || call.isErrorTyped, + s"arity mismatch but call is not error typed: $clazz (params=$params, args=$applyArgs)") + + (superConstr, preArgs ::: applyArgs) + case Block(_ :+ superCall, _) => + decompose(superCall) case _ => - (call, List()) + (call, Nil) } val (superConstr, superArgs) = decompose(rhs) assert(superConstr.symbol ne null, superConstr)//debug - - val pending = ListBuffer[AbsTypeError]() - // an object cannot be allowed to pass a reference to itself to a superconstructor - // because of initialization issues; bug #473 - foreachSubTreeBoundTo(superArgs, clazz) { tree => - if (tree.symbol.isModule) - pending += SuperConstrReferenceError(tree) - tree match { - case This(qual) => - pending += SuperConstrArgsThisReferenceError(tree) - case _ => () - } - } - - if (superConstr.symbol.isPrimaryConstructor) { - val superClazz = superConstr.symbol.owner - if (!superClazz.isJavaDefined) { - val superParamAccessors = superClazz.constrParamAccessors - if (sameLength(superParamAccessors, superArgs)) { - for ((superAcc, superArg @ Ident(name)) <- superParamAccessors zip superArgs) { - if (vparamss.exists(_.exists(_.symbol == superArg.symbol))) { - var alias = superAcc.initialize.alias - if (alias == NoSymbol) - alias = superAcc.getter(superAcc.owner) - if (alias != NoSymbol && - superClazz.info.nonPrivateMember(alias.name) != alias) - alias = NoSymbol - if (alias != NoSymbol) { - var ownAcc = clazz.info.decl(name).suchThat(_.isParamAccessor) - if ((ownAcc hasFlag ACCESSOR) && !ownAcc.isDeferred) - ownAcc = ownAcc.accessed - if (!ownAcc.isVariable && !alias.accessed.isVariable) { - debuglog("" + ownAcc + " has alias "+alias.fullLocationString) //debug - ownAcc.asInstanceOf[TermSymbol].setAlias(alias) - } - } + def superClazz = superConstr.symbol.owner + def superParamAccessors = superClazz.constrParamAccessors + + // associate superclass paramaccessors with their aliases + if (superConstr.symbol.isPrimaryConstructor && !superClazz.isJavaDefined && sameLength(superParamAccessors, superArgs)) { + for ((superAcc, superArg @ Ident(name)) <- superParamAccessors zip superArgs) { + if (mexists(vparamss)(_.symbol == superArg.symbol)) { + val alias = ( + superAcc.initialize.alias + orElse (superAcc getter superAcc.owner) + filter (alias => superClazz.info.nonPrivateMember(alias.name) != alias) + ) + if (alias.exists && !alias.accessed.isVariable) { + val ownAcc = clazz.info decl name suchThat (_.isParamAccessor) match { + case acc if !acc.isDeferred && acc.hasAccessorFlag => acc.accessed + case acc => acc + } + ownAcc match { + case acc: TermSymbol if !acc.isVariable => + debuglog(s"$acc has alias ${alias.fullLocationString}") + acc setAlias alias + case _ => } } } diff --git a/test/files/neg/t6928.check b/test/files/neg/t6928.check new file mode 100644 index 0000000000..28b8e382dc --- /dev/null +++ b/test/files/neg/t6928.check @@ -0,0 +1,7 @@ +t6928.scala:2: error: super constructor cannot be passed a self reference unless parameter is declared by-name +object B extends A(B) + ^ +t6928.scala:3: error: super constructor cannot be passed a self reference unless parameter is declared by-name +object C extends A(null, null, C) + ^ +two errors found diff --git a/test/files/neg/t6928.scala b/test/files/neg/t6928.scala new file mode 100644 index 0000000000..84bdcde45a --- /dev/null +++ b/test/files/neg/t6928.scala @@ -0,0 +1,10 @@ +abstract class A( val someAs: A* ) +object B extends A(B) +object C extends A(null, null, C) + +object Test { + def main(args: Array[String]): Unit = { + println(B.someAs) + println(C.someAs) + } +} diff --git a/test/files/run/t6928-run.check b/test/files/run/t6928-run.check new file mode 100644 index 0000000000..a640c3e5fd --- /dev/null +++ b/test/files/run/t6928-run.check @@ -0,0 +1 @@ +3 As diff --git a/test/files/run/t6928-run.scala b/test/files/run/t6928-run.scala new file mode 100644 index 0000000000..87a8884d60 --- /dev/null +++ b/test/files/run/t6928-run.scala @@ -0,0 +1,10 @@ +abstract class A( val someAs: A* ) { + override def toString = someAs.length + " As" +} +object B extends A(null, null, null) + +object Test { + def main(args: Array[String]): Unit = { + println(B) + } +} -- cgit v1.2.3 From 7a23562431e3e9673112b0f5ec5624eb28194ee5 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Tue, 8 Jan 2013 12:10:10 +0100 Subject: SI-6912 Avoid a typer cycle in overload resolution. c800d1fe, and followup commits 1ddc9358 and b10b5821 modified error handling in `Infer#inferExprAlternative`. After these changes, this method could fail to resolve the overloaded alternative if: best != NoSymbol && !competing.isEmpty && !noAlternatives && pt.isErroneous This commit calls `setError` in that case, which prevents the cycle in `adapt`. While I didn't extract a reproduction from the original code base, I've included a test case that exhibits the same symptom. It was actually pretty tough to find an program that got close to this code path, but luckilly we've been pretty close to this bug in SI-5553 / 4f99c2e5, and those test cases formed the basis for this one. --- src/compiler/scala/tools/nsc/typechecker/Infer.scala | 7 +++++++ test/files/neg/t6912.check | 4 ++++ test/files/neg/t6912.scala | 9 +++++++++ 3 files changed, 20 insertions(+) create mode 100644 test/files/neg/t6912.check create mode 100644 test/files/neg/t6912.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala index 7ae8923e43..771b1255d3 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -1510,6 +1510,13 @@ trait Infer extends Checkable { } else if (!competing.isEmpty) { if (noAlternatives) NoBestExprAlternativeError(tree, pt, isSecondTry) else if (!pt.isErroneous) AmbiguousExprAlternativeError(tree, pre, best, competing.head, pt, isSecondTry) + else { + // SI-6912 Don't give up and leave an OverloadedType on the tree. + // Originally I wrote this as `if (secondTry) ... `, but `tryTwice` won't attempt the second try + // unless an error is issued. We're not issuing an error, in the assumption that it would be + // spurious in light of the erroneous expected type + setError(tree) + } } else { // val applicable = alts1 filter (alt => // global.typer.infer.isWeaklyCompatible(pre.memberType(alt), pt)) diff --git a/test/files/neg/t6912.check b/test/files/neg/t6912.check new file mode 100644 index 0000000000..137b651705 --- /dev/null +++ b/test/files/neg/t6912.check @@ -0,0 +1,4 @@ +t6912.scala:8: error: not found: type Xxxx + def test[T]: Xxxx = Foo1[T] + ^ +one error found diff --git a/test/files/neg/t6912.scala b/test/files/neg/t6912.scala new file mode 100644 index 0000000000..f2540ee8c6 --- /dev/null +++ b/test/files/neg/t6912.scala @@ -0,0 +1,9 @@ +object Foo1 { + def apply[T](a: Int = 0): Nothing = sys.error("") + def apply[T](z: String = ""): Nothing = sys.error("") +} + +object Test { + // Triggered a cycle in Typers#adapt + def test[T]: Xxxx = Foo1[T] +} -- cgit v1.2.3 From e5da30b843fe8bfe1638e3e08cdeaa4b6ae2f2d1 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Tue, 8 Jan 2013 19:18:36 +0100 Subject: Backport of SI-6846. Squashed commit of the following: commit 55806cc0e6177820c12a35a18b4f2a12dc07bb39 Author: Paul Phillips Date: Wed Dec 19 07:32:19 2012 -0800 SI-6846, regression in type constructor inference. In 658ba1b4e6 some inference was gained and some was lost. In this commit we regain what was lost and gain even more. Dealiasing and widening should be fully handled now, as illustrated by the test case. (cherry picked from commit dbebcd509e4013ce02655a2687b27d0967b3650e) commit e6ef58447d0f4ef6de956fcc03ee283bb9028c02 Author: Paul Phillips Date: Fri Dec 21 15:11:29 2012 -0800 Cleaning up type alias usage. I determined that many if not most of the calls to .normalize have no intent beyond dealiasing the type. In light of this I went call site to call site knocking on doors and asking why exactly they were calling any of .normalize .widen.normalize .normalize.widen and if I didn't like their answers they found themselves introduced to 'dropAliasesAndSingleTypes', the recursive widener and dealiaser which I concluded is necessary after all. Discovered that the object called 'deAlias' actually depends upon calling 'normalize', not 'dealias'. Decided this was sufficient cause to rename it to 'normalizeAliases'. Created dealiasWiden and dealiasWidenChain. Dropped dropAliasesAndSingleTypes in favor of methods on Type alongside dealias and widen (Type#dealiasWiden). These should reduce the number of "hey, the type alias doesn't work" bugs. (cherry picked from commit 3bf51189f979eb0dd41744ca844fd12dfdaa0dee) Conflicts: src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala commit c1d8803cea1523f458730103386d8e14324a9446 Author: Paul Phillips Date: Sat Dec 22 08:13:48 2012 -0800 Shored up a hidden dealiasing dependency. Like the comment says: // This way typedNew always returns a dealiased type. This // used to happen by accident for instantiations without type // arguments due to ad hoc code in typedTypeConstructor, and // annotations depended on it (to the extent that they worked, // which they did not when given a parameterized type alias // which dealiased to an annotation.) typedTypeConstructor // dealiases nothing now, but it makes sense for a "new" to // always be given a dealiased type. PS: Simply running the test suite is becoming more difficult all the time. Running "ant test" includes time consuming activities of niche interest such as all the osgi tests, but test.suite manages to miss the continuations tests. (cherry picked from commit 422f461578ae0547181afe6d2c0c52ea1071d37b) commit da4748502792b260161baa10939554564c488051 Author: Paul Phillips Date: Fri Dec 21 12:39:02 2012 -0800 Fix and simplify typedTypeConstructor. Investigating the useful output of devWarning (-Xdev people, it's good for you) led back to this comment: "normalize to get rid of type aliases" You may know that this is not all the normalizing does. Normalizing also turns TypeRefs with unapplied arguments (type constructors) into PolyTypes. That means that when typedParentType would call typedTypeConstructor it would find its parent had morphed into a PolyType. Not that it noticed; it would blithely continue and unwittingly discard the type arguments by way of appliedType (which smoothly logged the incident, thank you appliedType.) The simplification of typedTypeConstructor: There was a whole complicated special treatment of AnyRef here which appears to have become unnecessary. Removed special treatment and lit a candle for regularity. Updated lots of tests regarding newly not-so-special AnyRef. (cherry picked from commit 394cc426c1ff1da53146679b4e2995ece52a133e) commit 1f3c77bacb2fbb3ba9e4ad0a8a733e0f9263b234 Author: Paul Phillips Date: Fri Dec 21 15:06:10 2012 -0800 Removed dead implementation. Another "attractive nuisance" burning off time until I realized it was commented out. (cherry picked from commit ed40f5cbdf35d09b02898e9c0950b9bd34c1f858) --- .../tools/nsc/interpreter/CompletionOutput.scala | 10 +- .../scala/tools/nsc/interpreter/IMain.scala | 2 +- .../scala/tools/nsc/typechecker/Implicits.scala | 113 +++------------------ .../scala/tools/nsc/typechecker/Infer.scala | 12 ++- .../scala/tools/nsc/typechecker/Typers.scala | 55 +++++----- src/reflect/scala/reflect/internal/Types.scala | 60 +++++++---- test/files/continuations-neg/function2.check | 2 +- .../files/continuations-neg/t5314-type-error.check | 4 +- test/files/jvm/annotations.check | 12 +++ test/files/jvm/annotations.scala | 6 ++ test/files/neg/override-object-no.check | 4 +- test/files/neg/t2078.check | 2 +- test/files/neg/t2336.check | 2 +- test/files/neg/t3691.check | 2 +- test/files/neg/t4877.check | 6 +- test/files/neg/t5060.check | 4 +- test/files/neg/t5063.check | 2 +- test/files/neg/t6436.check | 4 +- test/files/neg/t6436b.check | 4 +- test/files/neg/t963.check | 2 +- test/files/pos/t6846.scala | 28 +++++ test/files/run/existentials-in-compiler.check | 104 +++++++++---------- test/files/run/existentials3-new.check | 4 +- test/files/run/existentials3-old.check | 4 +- test/files/run/macro-declared-in-trait.check | 2 +- test/files/run/reflection-equality.check | 2 +- test/files/run/repl-colon-type.check | 8 +- test/files/run/repl-parens.check | 2 +- test/files/run/t4172.check | 2 +- test/files/run/t5256a.check | 2 +- test/files/run/t5256b.check | 2 +- test/files/run/t5256d.check | 2 +- test/files/run/t5256e.check | 2 +- test/files/run/t5256f.check | 4 +- test/files/scalap/abstractClass/result.test | 2 +- test/files/scalap/abstractMethod/result.test | 2 +- test/files/scalap/cbnParam/result.test | 2 +- test/files/scalap/classPrivate/result.test | 4 +- test/files/scalap/classWithExistential/result.test | 2 +- .../scalap/classWithSelfAnnotation/result.test | 2 +- test/files/scalap/covariantParam/result.test | 2 +- test/files/scalap/defaultParameter/result.test | 4 +- test/files/scalap/implicitParam/result.test | 2 +- test/files/scalap/packageObject/result.test | 2 +- test/files/scalap/paramClauses/result.test | 2 +- test/files/scalap/paramNames/result.test | 2 +- test/files/scalap/sequenceParam/result.test | 2 +- test/files/scalap/simpleClass/result.test | 2 +- test/files/scalap/traitObject/result.test | 4 +- test/files/scalap/typeAnnotations/result.test | 2 +- test/files/scalap/valAndVar/result.test | 2 +- test/files/scalap/wildcardType/result.test | 2 +- 52 files changed, 248 insertions(+), 270 deletions(-) create mode 100644 test/files/pos/t6846.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala index 13880bb8af..d14b5c79e0 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala @@ -37,8 +37,8 @@ trait CompletionOutput { val pkg = method.ownerChain find (_.isPackageClass) map (_.fullName) getOrElse "" def relativize(str: String): String = quietString(str stripPrefix (pkg + ".")) - def relativize(tp: Type): String = relativize(tp.normalize.toString) - def relativize(sym: Symbol): String = relativize(sym.info) + def relativize(tp: Type): String = relativize(tp.dealiasWiden.toString) + def relativize(sym: Symbol): String = relativize(sym.info) def braceList(tparams: List[String]) = if (tparams.isEmpty) "" else (tparams map relativize).mkString("[", ", ", "]") def parenList(params: List[Any]) = params.mkString("(", ", ", ")") @@ -56,8 +56,8 @@ trait CompletionOutput { } ) - def tupleString(tp: Type) = parenList(tp.normalize.typeArgs map relativize) - def functionString(tp: Type) = tp.normalize.typeArgs match { + def tupleString(tp: Type) = parenList(tp.dealiasWiden.typeArgs map relativize) + def functionString(tp: Type) = tp.dealiasWiden.typeArgs match { case List(t, r) => t + " => " + r case xs => parenList(xs.init) + " => " + xs.last } @@ -65,7 +65,7 @@ trait CompletionOutput { def tparamsString(tparams: List[Symbol]) = braceList(tparams map (_.defString)) def paramsString(params: List[Symbol]) = { def paramNameString(sym: Symbol) = if (sym.isSynthetic) "" else sym.nameString + ": " - def paramString(sym: Symbol) = paramNameString(sym) + typeToString(sym.info.normalize) + def paramString(sym: Symbol) = paramNameString(sym) + typeToString(sym.info.dealiasWiden) val isImplicit = params.nonEmpty && params.head.isImplicit val strs = (params map paramString) match { diff --git a/src/compiler/scala/tools/nsc/interpreter/IMain.scala b/src/compiler/scala/tools/nsc/interpreter/IMain.scala index 2b97f81024..b46d28dec3 100644 --- a/src/compiler/scala/tools/nsc/interpreter/IMain.scala +++ b/src/compiler/scala/tools/nsc/interpreter/IMain.scala @@ -550,7 +550,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends // normalize non-public types so we don't see protected aliases like Self def normalizeNonPublic(tp: Type) = tp match { - case TypeRef(_, sym, _) if sym.isAliasType && !sym.isPublic => tp.normalize + case TypeRef(_, sym, _) if sym.isAliasType && !sym.isPublic => tp.dealias case _ => tp } diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index 70a736c91f..10003723fd 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -443,8 +443,8 @@ trait Implicits { val start = if (Statistics.canEnable) Statistics.startTimer(matchesPtNanos) else null val result = normSubType(tp, pt) || isView && { pt match { - case TypeRef(_, Function1.Sym, args) => - matchesPtView(tp, args.head, args.tail.head, undet) + case TypeRef(_, Function1.Sym, arg1 :: arg2 :: Nil) => + matchesPtView(tp, arg1, arg2, undet) case _ => false } @@ -488,7 +488,7 @@ trait Implicits { loop(restpe, pt) else pt match { case tr @ TypeRef(pre, sym, args) => - if (sym.isAliasType) loop(tp, pt.normalize) + if (sym.isAliasType) loop(tp, pt.dealias) else if (sym.isAbstractType) loop(tp, pt.bounds.lo) else { val len = args.length - 1 @@ -532,18 +532,15 @@ trait Implicits { * to a final true or false. */ private def isPlausiblySubType(tp1: Type, tp2: Type) = !isImpossibleSubType(tp1, tp2) - private def isImpossibleSubType(tp1: Type, tp2: Type) = tp1.normalize.widen match { - case tr1 @ TypeRef(_, sym1, _) => - // We can only rule out a subtype relationship if the left hand - // side is a class, else we may not know enough. - sym1.isClass && (tp2.normalize.widen match { - case TypeRef(_, sym2, _) => - sym2.isClass && !(sym1 isWeakSubClass sym2) - case RefinedType(parents, decls) => - decls.nonEmpty && - tr1.member(decls.head.name) == NoSymbol - case _ => false - }) + private def isImpossibleSubType(tp1: Type, tp2: Type) = tp1.dealiasWiden match { + // We can only rule out a subtype relationship if the left hand + // side is a class, else we may not know enough. + case tr1 @ TypeRef(_, sym1, _) if sym1.isClass => + tp2.dealiasWiden match { + case TypeRef(_, sym2, _) => sym2.isClass && !(sym1 isWeakSubClass sym2) + case RefinedType(parents, decls) => decls.nonEmpty && tr1.member(decls.head.name) == NoSymbol + case _ => false + } case _ => false } @@ -1018,7 +1015,7 @@ trait Implicits { args foreach (getParts(_)) } } else if (sym.isAliasType) { - getParts(tp.normalize) + getParts(tp.dealias) } else if (sym.isAbstractType) { getParts(tp.bounds.hi) } @@ -1049,88 +1046,6 @@ trait Implicits { infoMap } - /** The parts of a type is the smallest set of types that contains - * - the type itself - * - the parts of its immediate components (prefix and argument) - * - the parts of its base types - * - for alias types and abstract types, we take instead the parts - * - of their upper bounds. - * @return For those parts that refer to classes with companion objects that - * can be accessed with unambiguous stable prefixes, the implicits infos - * which are members of these companion objects. - - private def companionImplicits(tp: Type): Infoss = { - val partMap = new LinkedHashMap[Symbol, Type] - val seen = mutable.HashSet[Type]() // cycle detection - - /** Enter all parts of `tp` into `parts` set. - * This method is performance critical: about 2-4% of all type checking is spent here - */ - def getParts(tp: Type) { - if (seen(tp)) - return - seen += tp - tp match { - case TypeRef(pre, sym, args) => - if (sym.isClass) { - if (!((sym.name == tpnme.REFINE_CLASS_NAME) || - (sym.name startsWith tpnme.ANON_CLASS_NAME) || - (sym.name == tpnme.ROOT))) - partMap get sym match { - case Some(pre1) => - if (!(pre =:= pre1)) partMap(sym) = NoType // ambiguous prefix - ignore implicit members - case None => - if (pre.isStable) partMap(sym) = pre - val bts = tp.baseTypeSeq - var i = 1 - while (i < bts.length) { - getParts(bts(i)) - i += 1 - } - getParts(pre) - args foreach getParts - } - } else if (sym.isAliasType) { - getParts(tp.normalize) - } else if (sym.isAbstractType) { - getParts(tp.bounds.hi) - } - case ThisType(_) => - getParts(tp.widen) - case _: SingletonType => - getParts(tp.widen) - case RefinedType(ps, _) => - for (p <- ps) getParts(p) - case AnnotatedType(_, t, _) => - getParts(t) - case ExistentialType(_, t) => - getParts(t) - case PolyType(_, t) => - getParts(t) - case _ => - } - } - - getParts(tp) - - val buf = new ListBuffer[Infos] - for ((clazz, pre) <- partMap) { - if (pre != NoType) { - val companion = clazz.companionModule - companion.moduleClass match { - case mc: ModuleClassSymbol => - buf += (mc.implicitMembers map (im => - new ImplicitInfo(im.name, singleType(pre, companion), im))) - case _ => - } - } - } - //println("companion implicits of "+tp+" = "+buf.toList) // DEBUG - buf.toList - } - -*/ - /** The implicits made available by type `pt`. * These are all implicits found in companion objects of classes C * such that some part of `tp` has C as one of its superclasses. @@ -1258,7 +1173,7 @@ trait Implicits { implicit def wrapResult(tree: Tree): SearchResult = if (tree == EmptyTree) SearchFailure else new SearchResult(tree, if (from.isEmpty) EmptyTreeTypeSubstituter else new TreeTypeSubstituter(from, to)) - val tp1 = tp0.normalize + val tp1 = tp0.dealias tp1 match { case ThisType(_) | SingleType(_, _) => // can't generate a reference to a value that's abstracted over by an existential diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala index 7ae8923e43..0f52687c75 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -44,7 +44,7 @@ trait Infer extends Checkable { case formal => formal } else formals if (isVarArgTypes(formals1) && (removeRepeated || formals.length != nargs)) { - val ft = formals1.last.normalize.typeArgs.head + val ft = formals1.last.dealiasWiden.typeArgs.head formals1.init ::: (for (i <- List.range(formals1.length - 1, nargs)) yield ft) } else formals1 } @@ -1060,15 +1060,17 @@ trait Infer extends Checkable { */ def inferExprInstance(tree: Tree, tparams: List[Symbol], pt: Type = WildcardType, treeTp0: Type = null, keepNothings: Boolean = true, useWeaklyCompatible: Boolean = false): List[Symbol] = { val treeTp = if(treeTp0 eq null) tree.tpe else treeTp0 // can't refer to tree in default for treeTp0 + val (targs, tvars) = exprTypeArgs(tparams, treeTp, pt, useWeaklyCompatible) printInference( ptBlock("inferExprInstance", "tree" -> tree, "tree.tpe"-> tree.tpe, "tparams" -> tparams, - "pt" -> pt + "pt" -> pt, + "targs" -> targs, + "tvars" -> tvars ) ) - val (targs, tvars) = exprTypeArgs(tparams, treeTp, pt, useWeaklyCompatible) if (keepNothings || (targs eq null)) { //@M: adjustTypeArgs fails if targs==null, neg/t0226 substExpr(tree, tparams, targs, pt) @@ -1422,9 +1424,9 @@ trait Infer extends Checkable { } object approximateAbstracts extends TypeMap { - def apply(tp: Type): Type = tp.normalize match { + def apply(tp: Type): Type = tp.dealiasWiden match { case TypeRef(pre, sym, _) if sym.isAbstractType => WildcardType - case _ => mapOver(tp) + case _ => mapOver(tp) } } diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 9d390476db..38221ad199 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -224,7 +224,7 @@ trait Typers extends Modes with Adaptations with Tags { case ExistentialType(tparams, tpe) => new SubstWildcardMap(tparams).apply(tp) case TypeRef(_, sym, _) if sym.isAliasType => - val tp0 = tp.normalize + val tp0 = tp.dealias val tp1 = dropExistential(tp0) if (tp1 eq tp0) tp else tp1 case _ => tp @@ -439,7 +439,7 @@ trait Typers extends Modes with Adaptations with Tags { if (!hiddenSymbols.isEmpty && hiddenSymbols.head == sym && sym.isAliasType && sameLength(sym.typeParams, args)) { hiddenSymbols = hiddenSymbols.tail - t.normalize + t.dealias } else t case SingleType(_, sym) => checkNoEscape(sym) @@ -1075,9 +1075,9 @@ trait Typers extends Modes with Adaptations with Tags { adapt(tree setType restpe, mode, pt, original) case TypeRef(_, ByNameParamClass, List(arg)) if ((mode & EXPRmode) != 0) => // (2) adapt(tree setType arg, mode, pt, original) - case tr @ TypeRef(_, sym, _) if sym.isAliasType && tr.normalize.isInstanceOf[ExistentialType] && + case tr @ TypeRef(_, sym, _) if sym.isAliasType && tr.dealias.isInstanceOf[ExistentialType] && ((mode & (EXPRmode | LHSmode)) == EXPRmode) => - adapt(tree setType tr.normalize.skolemizeExistential(context.owner, tree), mode, pt, original) + adapt(tree setType tr.dealias.skolemizeExistential(context.owner, tree), mode, pt, original) case et @ ExistentialType(_, _) if ((mode & (EXPRmode | LHSmode)) == EXPRmode) => adapt(tree setType et.skolemizeExistential(context.owner, tree), mode, pt, original) case PolyType(tparams, restpe) if inNoModes(mode, TAPPmode | PATTERNmode | HKmode) => // (3) @@ -1147,7 +1147,7 @@ trait Typers extends Modes with Adaptations with Tags { if (tree1.tpe <:< pt) adapt(tree1, mode, pt, original) else { if (inExprModeButNot(mode, FUNmode)) { - pt.normalize match { + pt.dealias match { case TypeRef(_, sym, _) => // note: was if (pt.typeSymbol == UnitClass) but this leads to a potentially // infinite expansion if pt is constant type () @@ -1302,7 +1302,7 @@ trait Typers extends Modes with Adaptations with Tags { def adaptToMember(qual: Tree, searchTemplate: Type, reportAmbiguous: Boolean = true, saveErrors: Boolean = true): Tree = { if (isAdaptableWithView(qual)) { - qual.tpe.widen.normalize match { + qual.tpe.dealiasWiden match { case et: ExistentialType => qual setType et.skolemizeExistential(context.owner, qual) // open the existential case _ => @@ -1840,7 +1840,7 @@ trait Typers extends Modes with Adaptations with Tags { _.typedTemplate(cdef.impl, parentTypes(cdef.impl)) } val impl2 = finishMethodSynthesis(impl1, clazz, context) - if (clazz.isTrait && clazz.info.parents.nonEmpty && clazz.info.firstParent.normalize.typeSymbol == AnyClass) + if (clazz.isTrait && clazz.info.parents.nonEmpty && clazz.info.firstParent.typeSymbol == AnyClass) checkEphemeral(clazz, impl2.body) if ((clazz != ClassfileAnnotationClass) && (clazz isNonBottomSubClass ClassfileAnnotationClass)) @@ -3865,7 +3865,7 @@ trait Typers extends Modes with Adaptations with Tags { val normalizeLocals = new TypeMap { def apply(tp: Type): Type = tp match { case TypeRef(pre, sym, args) => - if (sym.isAliasType && containsLocal(tp)) apply(tp.normalize) + if (sym.isAliasType && containsLocal(tp)) apply(tp.dealias) else { if (pre.isVolatile) InferTypeWithVolatileTypeSelectionError(tree, pre) @@ -4393,7 +4393,13 @@ trait Typers extends Modes with Adaptations with Tags { def typedNew(tree: New) = { val tpt = tree.tpt val tpt1 = { - val tpt0 = typedTypeConstructor(tpt) + // This way typedNew always returns a dealiased type. This used to happen by accident + // for instantiations without type arguments due to ad hoc code in typedTypeConstructor, + // and annotations depended on it (to the extent that they worked, which they did + // not when given a parameterized type alias which dealiased to an annotation.) + // typedTypeConstructor dealiases nothing now, but it makes sense for a "new" to always be + // given a dealiased type. + val tpt0 = typedTypeConstructor(tpt) modifyType (_.dealias) if (checkStablePrefixClassType(tpt0)) if (tpt0.hasSymbol && !tpt0.symbol.typeParams.isEmpty) { context.undetparams = cloneSymbols(tpt0.symbol.typeParams) @@ -5733,29 +5739,18 @@ trait Typers extends Modes with Adaptations with Tags { def typedTypeConstructor(tree: Tree, mode: Int): Tree = { val result = typed(tree, forTypeMode(mode) | FUNmode, WildcardType) - val restpe = result.tpe.normalize // normalize to get rid of type aliases for the following check (#1241) - if (!phase.erasedTypes && restpe.isInstanceOf[TypeRef] && !restpe.prefix.isStable && !context.unit.isJava) { - // The isJava exception if OK only because the only type constructors scalac gets - // to see are those in the signatures. These do not need a unique object as a prefix. - // The situation is different for new's and super's, but scalac does not look deep - // enough to see those. See #3938 - ConstructorPrefixError(tree, restpe) - } else { - //@M fix for #2208 - // if there are no type arguments, normalization does not bypass any checks, so perform it to get rid of AnyRef - if (result.tpe.typeArgs.isEmpty) { - // minimal check: if(result.tpe.typeSymbolDirect eq AnyRefClass) { - // must expand the fake AnyRef type alias, because bootstrapping (init in Definitions) is not - // designed to deal with the cycles in the scala package (ScalaObject extends - // AnyRef, but the AnyRef type alias is entered after the scala package is - // loaded and completed, so that ScalaObject is unpickled while AnyRef is not - // yet defined ) - // !!! TODO - revisit now that ScalaObject is gone. - result setType(restpe) - } else { // must not normalize: type application must be (bounds-)checked (during RefChecks), see #2208 + // get rid of type aliases for the following check (#1241) + result.tpe.dealias match { + case restpe @ TypeRef(pre, _, _) if !phase.erasedTypes && !pre.isStable && !context.unit.isJava => + // The isJava exception if OK only because the only type constructors scalac gets + // to see are those in the signatures. These do not need a unique object as a prefix. + // The situation is different for new's and super's, but scalac does not look deep + // enough to see those. See #3938 + ConstructorPrefixError(tree, restpe) + case _ => + // must not normalize: type application must be (bounds-)checked (during RefChecks), see #2208 // during uncurry (after refchecks), all types are normalized result - } } } diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index bfd18f6a43..c2637e6967 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -593,6 +593,26 @@ trait Types extends api.Types { self: SymbolTable => /** Expands type aliases. */ def dealias = this + /** Repeatedly apply widen and dealias until they have no effect. + * This compensates for the fact that type aliases can hide beneath + * singleton types and singleton types can hide inside type aliases. + */ + def dealiasWiden: Type = ( + if (this ne widen) widen.dealiasWiden + else if (this ne dealias) dealias.dealiasWiden + else this + ) + + /** All the types encountered in the course of dealiasing/widening, + * including each intermediate beta reduction step (whereas calling + * dealias applies as many as possible.) + */ + def dealiasWidenChain: List[Type] = this :: ( + if (this ne widen) widen.dealiasWidenChain + else if (this ne betaReduce) betaReduce.dealiasWidenChain + else Nil + ) + def etaExpand: Type = this /** Performs a single step of beta-reduction on types. @@ -3173,23 +3193,20 @@ trait Types extends api.Types { self: SymbolTable => * Checks subtyping of higher-order type vars, and uses variances as defined in the * type parameter we're trying to infer (the result will be sanity-checked later). */ - def unifyFull(tpe: Type) = { - // The alias/widen variations are often no-ops. - val tpes = ( - if (isLowerBound) List(tpe, tpe.widen, tpe.dealias, tpe.widen.dealias).distinct - else List(tpe) - ) - tpes exists { tp => - val lhs = if (isLowerBound) tp.typeArgs else typeArgs - val rhs = if (isLowerBound) typeArgs else tp.typeArgs - - sameLength(lhs, rhs) && { + def unifyFull(tpe: Type): Boolean = { + def unifySpecific(tp: Type) = { + sameLength(typeArgs, tp.typeArgs) && { + val lhs = if (isLowerBound) tp.typeArgs else typeArgs + val rhs = if (isLowerBound) typeArgs else tp.typeArgs // this is a higher-kinded type var with same arity as tp. // side effect: adds the type constructor itself as a bound addBound(tp.typeConstructor) isSubArgs(lhs, rhs, params, AnyDepth) } } + // The type with which we can successfully unify can be hidden + // behind singleton types and type aliases. + tpe.dealiasWidenChain exists unifySpecific } // There's a <: test taking place right now, where tp is a concrete type and this is a typevar @@ -3282,7 +3299,7 @@ trait Types extends api.Types { self: SymbolTable => if (constr.instValid) constr.inst // get here when checking higher-order subtyping of the typevar by itself // TODO: check whether this ever happens? - else if (isHigherKinded) typeFun(params, applyArgs(params map (_.typeConstructor))) + else if (isHigherKinded) logResult("Normalizing HK $this")(typeFun(params, applyArgs(params map (_.typeConstructor)))) else super.normalize ) override def typeSymbol = origin.typeSymbol @@ -3754,7 +3771,7 @@ trait Types extends api.Types { self: SymbolTable => def existentialAbstraction(tparams: List[Symbol], tpe0: Type): Type = if (tparams.isEmpty) tpe0 else { - val tpe = deAlias(tpe0) + val tpe = normalizeAliases(tpe0) val tpe1 = new ExistentialExtrapolation(tparams) extrapolate tpe var tparams0 = tparams var tparams1 = tparams0 filter tpe1.contains @@ -3768,13 +3785,16 @@ trait Types extends api.Types { self: SymbolTable => newExistentialType(tparams1, tpe1) } - /** Remove any occurrences of type aliases from this type */ - object deAlias extends TypeMap { - def apply(tp: Type): Type = mapOver { - tp match { - case TypeRef(pre, sym, args) if sym.isAliasType => tp.normalize - case _ => tp - } + /** Normalize any type aliases within this type (@see Type#normalize). + * Note that this depends very much on the call to "normalize", not "dealias", + * so it is no longer carries the too-stealthy name "deAlias". + */ + object normalizeAliases extends TypeMap { + def apply(tp: Type): Type = tp match { + case TypeRef(_, sym, _) if sym.isAliasType => + def msg = if (tp.isHigherKinded) s"Normalizing type alias function $tp" else s"Dealiasing type alias $tp" + mapOver(logResult(msg)(tp.normalize)) + case _ => mapOver(tp) } } diff --git a/test/files/continuations-neg/function2.check b/test/files/continuations-neg/function2.check index 82b81c1444..4b1a6227bc 100644 --- a/test/files/continuations-neg/function2.check +++ b/test/files/continuations-neg/function2.check @@ -1,6 +1,6 @@ function2.scala:11: error: type mismatch; found : () => Int - required: () => Int @util.continuations.cps[Int] + required: () => Int @scala.util.continuations.cpsParam[Int,Int] val g: () => Int @cps[Int] = f ^ one error found diff --git a/test/files/continuations-neg/t5314-type-error.check b/test/files/continuations-neg/t5314-type-error.check index 1f4e46a7f2..e66c9d833f 100644 --- a/test/files/continuations-neg/t5314-type-error.check +++ b/test/files/continuations-neg/t5314-type-error.check @@ -1,6 +1,6 @@ t5314-type-error.scala:7: error: type mismatch; - found : Int @util.continuations.cps[Int] - required: Int @util.continuations.cps[String] + found : Int @scala.util.continuations.cpsParam[Int,Int] + required: Int @scala.util.continuations.cpsParam[String,String] def bar(x:Int): Int @cps[String] = return foo(x) ^ one error found diff --git a/test/files/jvm/annotations.check b/test/files/jvm/annotations.check index e307f8930d..a8dc5ecdd1 100644 --- a/test/files/jvm/annotations.check +++ b/test/files/jvm/annotations.check @@ -28,9 +28,21 @@ public Test4$Foo8(int) @test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://eppli.com) private int Test4$Foo9.z +@test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://eppli.com) +private int Test4$Foo9.z2 + +@test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://eppli.com) +private int Test4$Foo9.z3 + @test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://eppli.com) public int Test4$Foo9.getZ() +@test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://eppli.com) +public int Test4$Foo9.getZ2() + +@test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://eppli.com) +public int Test4$Foo9.getZ3() + @test.SourceAnnotation(mails={bill.gates@bloodsuckers.com}, value=http://apple.com) public int Test4$Foo9.x() diff --git a/test/files/jvm/annotations.scala b/test/files/jvm/annotations.scala index 66ebde592b..77a45fae89 100644 --- a/test/files/jvm/annotations.scala +++ b/test/files/jvm/annotations.scala @@ -101,6 +101,12 @@ object Test4 { type myAnn = SourceAnnotation @beanGetter @field @BeanProperty @myAnn("http://eppli.com") var z = 0 + + type myAnn2[T] = SourceAnnotation @beanGetter @field + @BeanProperty @myAnn2[String]("http://eppli.com") var z2 = 0 + + type myAnn3[CC[_]] = SourceAnnotation @beanGetter @field + @BeanProperty @myAnn3[List]("http://eppli.com") var z3 = 0 } class Foo10(@SourceAnnotation("on param 1") val name: String) class Foo11(@(SourceAnnotation @scala.annotation.meta.field)("on param 2") val name: String) diff --git a/test/files/neg/override-object-no.check b/test/files/neg/override-object-no.check index 52bad2b937..9cfda80fc3 100644 --- a/test/files/neg/override-object-no.check +++ b/test/files/neg/override-object-no.check @@ -6,8 +6,8 @@ an overriding object must conform to the overridden object's class bound; ^ override-object-no.scala:21: error: overriding object Bar in trait Quux1 with object Bar in trait Quux2: an overriding object must conform to the overridden object's class bound; - found : Object{def g: String} - required: Object{def g: Int} + found : AnyRef{def g: String} + required: AnyRef{def g: Int} trait Quux2 extends Quux1 { override object Bar { def g = "abc" } } // err ^ override-object-no.scala:25: error: overriding object Bar in trait Quux3; diff --git a/test/files/neg/t2078.check b/test/files/neg/t2078.check index 3cdaa7d27a..00bb323a0b 100644 --- a/test/files/neg/t2078.check +++ b/test/files/neg/t2078.check @@ -1,4 +1,4 @@ -t2078.scala:2: error: contravariant type S occurs in covariant position in type => Object{val x: S} of value f +t2078.scala:2: error: contravariant type S occurs in covariant position in type => AnyRef{val x: S} of value f val f = new { val x = y } ^ one error found diff --git a/test/files/neg/t2336.check b/test/files/neg/t2336.check index 983717469c..28acd4d179 100644 --- a/test/files/neg/t2336.check +++ b/test/files/neg/t2336.check @@ -1,4 +1,4 @@ -t2336.scala:6: error: type Foo[Int] is not a stable prefix +t2336.scala:6: error: Foo[Int] is not a legal prefix for a constructor new Foo[Int]#Bar(0) ^ one error found diff --git a/test/files/neg/t3691.check b/test/files/neg/t3691.check index bdf6c268b2..6a7e13049a 100644 --- a/test/files/neg/t3691.check +++ b/test/files/neg/t3691.check @@ -9,7 +9,7 @@ t3691.scala:5: error: type mismatch; val c = (new A[String]{}): { type A } // not ok ^ t3691.scala:7: error: type mismatch; - found : Object{type A = String} + found : AnyRef{type A = String} required: AnyRef{type A[X]} val x = (new { type A = String }): { type A[X] } // not ok ^ diff --git a/test/files/neg/t4877.check b/test/files/neg/t4877.check index a4b1e6a50d..5a2413ca8b 100644 --- a/test/files/neg/t4877.check +++ b/test/files/neg/t4877.check @@ -1,10 +1,10 @@ t4877.scala:4: error: type mismatch; - found : Object{def bar: Int} + found : AnyRef{def bar: Int} required: AnyRef{def bar: String} def foo: AnyRef { def bar: String } = new AnyRef { def bar = 42 } ^ t4877.scala:6: error: type mismatch; - found : Object{def bar(x: Int): String} + found : AnyRef{def bar(x: Int): String} required: AnyRef{def bar(x: Int): Int} def foo3: AnyRef { def bar(x: Int): Int } = new AnyRef { def bar(x: Int) = "abc" } ^ @@ -14,7 +14,7 @@ t4877.scala:7: error: type mismatch; def foo4: C { def bar(x: Int): Int ; def quux(x: Int): Int } = new C { def bar(x: Int) = 5 } ^ t4877.scala:17: error: type mismatch; - found : Object{type Mom = String; def bar(x: Int): Int; def bippy(): List[Int]} + found : AnyRef{type Mom = String; def bar(x: Int): Int; def bippy(): List[Int]} required: B.this.Bippy (which expands to) AnyRef{type Mom; def bar(x: Int): this.Mom; def bippy(): List[this.Mom]} val x: Bippy = new AnyRef { diff --git a/test/files/neg/t5060.check b/test/files/neg/t5060.check index e71f30ccdb..09b2d9a4b1 100644 --- a/test/files/neg/t5060.check +++ b/test/files/neg/t5060.check @@ -1,7 +1,7 @@ -t5060.scala:2: error: covariant type T occurs in contravariant position in type => Object{def contains(x: T): Unit} of value foo0 +t5060.scala:2: error: covariant type T occurs in contravariant position in type => AnyRef{def contains(x: T): Unit} of value foo0 val foo0 = { ^ -t5060.scala:6: error: covariant type T occurs in contravariant position in type => Object{def contains(x: T): Unit} of method foo1 +t5060.scala:6: error: covariant type T occurs in contravariant position in type => AnyRef{def contains(x: T): Unit} of method foo1 def foo1 = { ^ two errors found diff --git a/test/files/neg/t5063.check b/test/files/neg/t5063.check index 84690d0a1d..c6e553c1b5 100644 --- a/test/files/neg/t5063.check +++ b/test/files/neg/t5063.check @@ -1,4 +1,4 @@ -t5063.scala:2: error: value + is not a member of Object +t5063.scala:2: error: value + is not a member of AnyRef super.+("") ^ one error found diff --git a/test/files/neg/t6436.check b/test/files/neg/t6436.check index ecb28f9100..5cee6fb558 100644 --- a/test/files/neg/t6436.check +++ b/test/files/neg/t6436.check @@ -2,8 +2,8 @@ t6436.scala:8: error: type mismatch; found : StringContext required: ?{def q: ?} Note that implicit conversions are not applicable because they are ambiguous: - both method foo1 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} - and method foo2 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} + both method foo1 in object quasiquotes of type (ctx: StringContext)AnyRef{def q: Nothing} + and method foo2 in object quasiquotes of type (ctx: StringContext)AnyRef{def q: Nothing} are possible conversion functions from StringContext to ?{def q: ?} println(q"a") ^ diff --git a/test/files/neg/t6436b.check b/test/files/neg/t6436b.check index b3c2d73739..21ab972b79 100644 --- a/test/files/neg/t6436b.check +++ b/test/files/neg/t6436b.check @@ -2,8 +2,8 @@ t6436b.scala:8: error: type mismatch; found : StringContext required: ?{def q: ?} Note that implicit conversions are not applicable because they are ambiguous: - both method foo1 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} - and method foo2 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} + both method foo1 in object quasiquotes of type (ctx: StringContext)AnyRef{def q: Nothing} + and method foo2 in object quasiquotes of type (ctx: StringContext)AnyRef{def q: Nothing} are possible conversion functions from StringContext to ?{def q: ?} println(StringContext("a").q()) ^ diff --git a/test/files/neg/t963.check b/test/files/neg/t963.check index 1f2d0687b3..4dc202c7bd 100644 --- a/test/files/neg/t963.check +++ b/test/files/neg/t963.check @@ -5,7 +5,7 @@ t963.scala:17: error: stable identifier required, but Test.this.y4.x found. val w4 : y4.x.type = y4.x ^ t963.scala:10: error: type mismatch; - found : Object{def x: Integer} + found : AnyRef{def x: Integer} required: AnyRef{val x: Integer} val y2 : { val x : java.lang.Integer } = new { def x = new java.lang.Integer(r.nextInt) } ^ diff --git a/test/files/pos/t6846.scala b/test/files/pos/t6846.scala new file mode 100644 index 0000000000..009566493f --- /dev/null +++ b/test/files/pos/t6846.scala @@ -0,0 +1,28 @@ +object Test { + class Arb[_] + implicit def foo[M[_], A]: Arb[M[A]] = null + foo: Arb[List[Int]] + type ListInt = List[Int] + foo: Arb[ListInt] +} + +object Test2 { + import scala.collection.immutable.List + + class Carb[_] + implicit def narrow[N, M[_], A](x: Carb[M[A]])(implicit ev: N <:< M[A]): Carb[N] = null + implicit def bar[M[_], A]: Carb[M[A]] = null + + type ListInt = List[Int] + + val x: List[Int] = List(1) + val y: ListInt = List(1) + + type ListSingletonX = x.type + type ListSingletonY = y.type + + bar: Carb[List[Int]] + bar: Carb[ListInt] + bar: Carb[ListSingletonX] + bar: Carb[ListSingletonY] +} diff --git a/test/files/run/existentials-in-compiler.check b/test/files/run/existentials-in-compiler.check index 4df4b0ca96..0d7a9298b4 100644 --- a/test/files/run/existentials-in-compiler.check +++ b/test/files/run/existentials-in-compiler.check @@ -1,156 +1,156 @@ -abstract trait Bippy[A <: AnyRef, B] extends Object +abstract trait Bippy[A <: AnyRef, B] extends AnyRef extest.Bippy[_ <: AnyRef, _] -abstract trait BippyBud[A <: AnyRef, B, C <: List[A]] extends Object +abstract trait BippyBud[A <: AnyRef, B, C <: List[A]] extends AnyRef extest.BippyBud[A,B,C] forSome { A <: AnyRef; B; C <: List[A] } -abstract trait BippyLike[A <: AnyRef, B <: List[A], This <: extest.BippyLike[A,B,This] with extest.Bippy[A,B]] extends Object +abstract trait BippyLike[A <: AnyRef, B <: List[A], This <: extest.BippyLike[A,B,This] with extest.Bippy[A,B]] extends AnyRef extest.BippyLike[A,B,This] forSome { A <: AnyRef; B <: List[A]; This <: extest.BippyLike[A,B,This] with extest.Bippy[A,B] } -abstract trait Contra[-A >: AnyRef, -B] extends Object +abstract trait Contra[-A >: AnyRef, -B] extends AnyRef extest.Contra[_ >: AnyRef, _] -abstract trait ContraLike[-A >: AnyRef, -B >: List[A]] extends Object +abstract trait ContraLike[-A >: AnyRef, -B >: List[A]] extends AnyRef extest.ContraLike[A,B] forSome { -A >: AnyRef; -B >: List[A] } -abstract trait Cov01[+A <: AnyRef, +B] extends Object +abstract trait Cov01[+A <: AnyRef, +B] extends AnyRef extest.Cov01[_ <: AnyRef, _] -abstract trait Cov02[+A <: AnyRef, B] extends Object +abstract trait Cov02[+A <: AnyRef, B] extends AnyRef extest.Cov02[_ <: AnyRef, _] -abstract trait Cov03[+A <: AnyRef, -B] extends Object +abstract trait Cov03[+A <: AnyRef, -B] extends AnyRef extest.Cov03[_ <: AnyRef, _] -abstract trait Cov04[A <: AnyRef, +B] extends Object +abstract trait Cov04[A <: AnyRef, +B] extends AnyRef extest.Cov04[_ <: AnyRef, _] -abstract trait Cov05[A <: AnyRef, B] extends Object +abstract trait Cov05[A <: AnyRef, B] extends AnyRef extest.Cov05[_ <: AnyRef, _] -abstract trait Cov06[A <: AnyRef, -B] extends Object +abstract trait Cov06[A <: AnyRef, -B] extends AnyRef extest.Cov06[_ <: AnyRef, _] -abstract trait Cov07[-A <: AnyRef, +B] extends Object +abstract trait Cov07[-A <: AnyRef, +B] extends AnyRef extest.Cov07[_ <: AnyRef, _] -abstract trait Cov08[-A <: AnyRef, B] extends Object +abstract trait Cov08[-A <: AnyRef, B] extends AnyRef extest.Cov08[_ <: AnyRef, _] -abstract trait Cov09[-A <: AnyRef, -B] extends Object +abstract trait Cov09[-A <: AnyRef, -B] extends AnyRef extest.Cov09[_ <: AnyRef, _] -abstract trait Cov11[+A <: AnyRef, +B <: List[_]] extends Object +abstract trait Cov11[+A <: AnyRef, +B <: List[_]] extends AnyRef extest.Cov11[_ <: AnyRef, _ <: List[_]] -abstract trait Cov12[+A <: AnyRef, B <: List[_]] extends Object +abstract trait Cov12[+A <: AnyRef, B <: List[_]] extends AnyRef extest.Cov12[_ <: AnyRef, _ <: List[_]] -abstract trait Cov13[+A <: AnyRef, -B <: List[_]] extends Object +abstract trait Cov13[+A <: AnyRef, -B <: List[_]] extends AnyRef extest.Cov13[_ <: AnyRef, _ <: List[_]] -abstract trait Cov14[A <: AnyRef, +B <: List[_]] extends Object +abstract trait Cov14[A <: AnyRef, +B <: List[_]] extends AnyRef extest.Cov14[_ <: AnyRef, _ <: List[_]] -abstract trait Cov15[A <: AnyRef, B <: List[_]] extends Object +abstract trait Cov15[A <: AnyRef, B <: List[_]] extends AnyRef extest.Cov15[_ <: AnyRef, _ <: List[_]] -abstract trait Cov16[A <: AnyRef, -B <: List[_]] extends Object +abstract trait Cov16[A <: AnyRef, -B <: List[_]] extends AnyRef extest.Cov16[_ <: AnyRef, _ <: List[_]] -abstract trait Cov17[-A <: AnyRef, +B <: List[_]] extends Object +abstract trait Cov17[-A <: AnyRef, +B <: List[_]] extends AnyRef extest.Cov17[_ <: AnyRef, _ <: List[_]] -abstract trait Cov18[-A <: AnyRef, B <: List[_]] extends Object +abstract trait Cov18[-A <: AnyRef, B <: List[_]] extends AnyRef extest.Cov18[_ <: AnyRef, _ <: List[_]] -abstract trait Cov19[-A <: AnyRef, -B <: List[_]] extends Object +abstract trait Cov19[-A <: AnyRef, -B <: List[_]] extends AnyRef extest.Cov19[_ <: AnyRef, _ <: List[_]] -abstract trait Cov21[+A, +B] extends Object +abstract trait Cov21[+A, +B] extends AnyRef extest.Cov21[_, _] -abstract trait Cov22[+A, B] extends Object +abstract trait Cov22[+A, B] extends AnyRef extest.Cov22[_, _] -abstract trait Cov23[+A, -B] extends Object +abstract trait Cov23[+A, -B] extends AnyRef extest.Cov23[_, _] -abstract trait Cov24[A, +B] extends Object +abstract trait Cov24[A, +B] extends AnyRef extest.Cov24[_, _] -abstract trait Cov25[A, B] extends Object +abstract trait Cov25[A, B] extends AnyRef extest.Cov25[_, _] -abstract trait Cov26[A, -B] extends Object +abstract trait Cov26[A, -B] extends AnyRef extest.Cov26[_, _] -abstract trait Cov27[-A, +B] extends Object +abstract trait Cov27[-A, +B] extends AnyRef extest.Cov27[_, _] -abstract trait Cov28[-A, B] extends Object +abstract trait Cov28[-A, B] extends AnyRef extest.Cov28[_, _] -abstract trait Cov29[-A, -B] extends Object +abstract trait Cov29[-A, -B] extends AnyRef extest.Cov29[_, _] -abstract trait Cov31[+A, +B, C <: (A, B)] extends Object +abstract trait Cov31[+A, +B, C <: (A, B)] extends AnyRef extest.Cov31[A,B,C] forSome { +A; +B; C <: (A, B) } -abstract trait Cov32[+A, B, C <: (A, B)] extends Object +abstract trait Cov32[+A, B, C <: (A, B)] extends AnyRef extest.Cov32[A,B,C] forSome { +A; B; C <: (A, B) } -abstract trait Cov33[+A, -B, C <: Tuple2[A, _]] extends Object +abstract trait Cov33[+A, -B, C <: Tuple2[A, _]] extends AnyRef extest.Cov33[A,B,C] forSome { +A; -B; C <: Tuple2[A, _] } -abstract trait Cov34[A, +B, C <: (A, B)] extends Object +abstract trait Cov34[A, +B, C <: (A, B)] extends AnyRef extest.Cov34[A,B,C] forSome { A; +B; C <: (A, B) } -abstract trait Cov35[A, B, C <: (A, B)] extends Object +abstract trait Cov35[A, B, C <: (A, B)] extends AnyRef extest.Cov35[A,B,C] forSome { A; B; C <: (A, B) } -abstract trait Cov36[A, -B, C <: Tuple2[A, _]] extends Object +abstract trait Cov36[A, -B, C <: Tuple2[A, _]] extends AnyRef extest.Cov36[A,B,C] forSome { A; -B; C <: Tuple2[A, _] } -abstract trait Cov37[-A, +B, C <: Tuple2[_, B]] extends Object +abstract trait Cov37[-A, +B, C <: Tuple2[_, B]] extends AnyRef extest.Cov37[A,B,C] forSome { -A; +B; C <: Tuple2[_, B] } -abstract trait Cov38[-A, B, C <: Tuple2[_, B]] extends Object +abstract trait Cov38[-A, B, C <: Tuple2[_, B]] extends AnyRef extest.Cov38[A,B,C] forSome { -A; B; C <: Tuple2[_, B] } -abstract trait Cov39[-A, -B, C <: Tuple2[_, _]] extends Object +abstract trait Cov39[-A, -B, C <: Tuple2[_, _]] extends AnyRef extest.Cov39[_, _, _ <: Tuple2[_, _]] -abstract trait Cov41[+A >: Null, +B] extends Object +abstract trait Cov41[+A >: Null, +B] extends AnyRef extest.Cov41[_ >: Null, _] -abstract trait Cov42[+A >: Null, B] extends Object +abstract trait Cov42[+A >: Null, B] extends AnyRef extest.Cov42[_ >: Null, _] -abstract trait Cov43[+A >: Null, -B] extends Object +abstract trait Cov43[+A >: Null, -B] extends AnyRef extest.Cov43[_ >: Null, _] -abstract trait Cov44[A >: Null, +B] extends Object +abstract trait Cov44[A >: Null, +B] extends AnyRef extest.Cov44[_ >: Null, _] -abstract trait Cov45[A >: Null, B] extends Object +abstract trait Cov45[A >: Null, B] extends AnyRef extest.Cov45[_ >: Null, _] -abstract trait Cov46[A >: Null, -B] extends Object +abstract trait Cov46[A >: Null, -B] extends AnyRef extest.Cov46[_ >: Null, _] -abstract trait Cov47[-A >: Null, +B] extends Object +abstract trait Cov47[-A >: Null, +B] extends AnyRef extest.Cov47[_ >: Null, _] -abstract trait Cov48[-A >: Null, B] extends Object +abstract trait Cov48[-A >: Null, B] extends AnyRef extest.Cov48[_ >: Null, _] -abstract trait Cov49[-A >: Null, -B] extends Object +abstract trait Cov49[-A >: Null, -B] extends AnyRef extest.Cov49[_ >: Null, _] -abstract trait Covariant[+A <: AnyRef, +B] extends Object +abstract trait Covariant[+A <: AnyRef, +B] extends AnyRef extest.Covariant[_ <: AnyRef, _] -abstract trait CovariantLike[+A <: AnyRef, +B <: List[A], +This <: extest.CovariantLike[A,B,This] with extest.Covariant[A,B]] extends Object +abstract trait CovariantLike[+A <: AnyRef, +B <: List[A], +This <: extest.CovariantLike[A,B,This] with extest.Covariant[A,B]] extends AnyRef extest.CovariantLike[A,B,This] forSome { +A <: AnyRef; +B <: List[A]; +This <: extest.CovariantLike[A,B,This] with extest.Covariant[A,B] } diff --git a/test/files/run/existentials3-new.check b/test/files/run/existentials3-new.check index 00614b19db..8f7dd701ac 100644 --- a/test/files/run/existentials3-new.check +++ b/test/files/run/existentials3-new.check @@ -7,7 +7,7 @@ Test.ToS, t=RefinedType, s=f5 () => Test.ToS, t=TypeRef, s=trait Function0 $anon, t=TypeRef, s=type $anon $anon, t=TypeRef, s=type $anon -List[java.lang.Object{type T1}#T1], t=TypeRef, s=class List +List[AnyRef{type T1}#T1], t=TypeRef, s=class List List[Seq[Int]], t=TypeRef, s=class List List[Seq[U forSome { type U <: Int }]], t=TypeRef, s=class List Bar.type, t=TypeRef, s=type Bar.type @@ -19,6 +19,6 @@ Test.ToS, t=RefinedType, s=g5 () => Test.ToS, t=TypeRef, s=trait Function0 $anon, t=TypeRef, s=type $anon $anon, t=TypeRef, s=type $anon -List[java.lang.Object{type T1}#T1], t=TypeRef, s=class List +List[AnyRef{type T1}#T1], t=TypeRef, s=class List List[Seq[Int]], t=TypeRef, s=class List List[Seq[U forSome { type U <: Int }]], t=TypeRef, s=class List diff --git a/test/files/run/existentials3-old.check b/test/files/run/existentials3-old.check index 72abfac637..36a458dacc 100644 --- a/test/files/run/existentials3-old.check +++ b/test/files/run/existentials3-old.check @@ -5,7 +5,7 @@ Object with Test$ToS Object with Test$ToS scala.Function0[Object with Test$ToS] scala.Function0[Object with Test$ToS] -_ <: Object with _ <: Object with Test$ToS +_ <: Object with _ <: Object with Object with Test$ToS _ <: Object with _ <: Object with _ <: Object with Test$ToS scala.collection.immutable.List[Object with scala.collection.Seq[Int]] scala.collection.immutable.List[Object with scala.collection.Seq[_ <: Int]] @@ -16,7 +16,7 @@ Object with Test$ToS Object with Test$ToS scala.Function0[Object with Test$ToS] scala.Function0[Object with Test$ToS] -_ <: Object with _ <: Object with Test$ToS +_ <: Object with _ <: Object with Object with Test$ToS _ <: Object with _ <: Object with _ <: Object with Test$ToS scala.collection.immutable.List[Object with scala.collection.Seq[Int]] scala.collection.immutable.List[Object with scala.collection.Seq[_ <: Int]] diff --git a/test/files/run/macro-declared-in-trait.check b/test/files/run/macro-declared-in-trait.check index 104ff1e99b..0d70ac74f3 100644 --- a/test/files/run/macro-declared-in-trait.check +++ b/test/files/run/macro-declared-in-trait.check @@ -1,5 +1,5 @@ prefix = Expr[Nothing]({ - final class $anon extends Object with Base { + final class $anon extends AnyRef with Base { def (): anonymous class $anon = { $anon.super.(); () diff --git a/test/files/run/reflection-equality.check b/test/files/run/reflection-equality.check index 17c1f6dd70..65b525731f 100644 --- a/test/files/run/reflection-equality.check +++ b/test/files/run/reflection-equality.check @@ -24,7 +24,7 @@ cs: reflect.runtime.universe.ClassSymbol = class X scala> val ts: Type = cs.typeSignature ts: reflect.runtime.universe.Type = -java.lang.Object { +scala.AnyRef { def (): X def methodIntIntInt(x: scala.Int,y: scala.Int): scala.Int } diff --git a/test/files/run/repl-colon-type.check b/test/files/run/repl-colon-type.check index 35cd04ba87..56ddd74375 100644 --- a/test/files/run/repl-colon-type.check +++ b/test/files/run/repl-colon-type.check @@ -77,10 +77,10 @@ scala> :type -v List(1,2,3) filter _ // Internal Type structure TypeRef( - TypeSymbol(abstract trait Function1[-T1, +R] extends Object) + TypeSymbol(abstract trait Function1[-T1, +R] extends AnyRef) args = List( TypeRef( - TypeSymbol(abstract trait Function1[-T1, +R] extends Object) + TypeSymbol(abstract trait Function1[-T1, +R] extends AnyRef) args = List( TypeRef(TypeSymbol(final abstract class Int extends AnyVal)) TypeRef( @@ -147,7 +147,7 @@ Int => Iterator[List[Nothing]] // Internal Type structure TypeRef( - TypeSymbol(abstract trait Function1[-T1, +R] extends Object) + TypeSymbol(abstract trait Function1[-T1, +R] extends AnyRef) args = List( TypeRef(TypeSymbol(final abstract class Int extends AnyVal)) TypeRef( @@ -180,7 +180,7 @@ PolyType( typeParams = List(TypeParam(T <: AnyVal)) resultType = NullaryMethodType( TypeRef( - TypeSymbol(abstract trait Function1[-T1, +R] extends Object) + TypeSymbol(abstract trait Function1[-T1, +R] extends AnyRef) args = List( TypeRef(TypeSymbol(final abstract class Int extends AnyVal)) TypeRef( diff --git a/test/files/run/repl-parens.check b/test/files/run/repl-parens.check index 4b7ce6b059..15f4b4524a 100644 --- a/test/files/run/repl-parens.check +++ b/test/files/run/repl-parens.check @@ -66,7 +66,7 @@ scala> 55 ; () => 5 res13: () => Int = scala> () => { class X ; new X } -res14: () => Object = +res14: () => AnyRef = scala> diff --git a/test/files/run/t4172.check b/test/files/run/t4172.check index f16c9e5151..94cdff4870 100644 --- a/test/files/run/t4172.check +++ b/test/files/run/t4172.check @@ -5,7 +5,7 @@ scala> scala> val c = { class C { override def toString = "C" }; ((new C, new C { def f = 2 })) } warning: there were 1 feature warnings; re-run with -feature for details -c: (C, C{def f: Int}) forSome { type C <: Object } = (C,C) +c: (C, C{def f: Int}) forSome { type C <: AnyRef } = (C,C) scala> diff --git a/test/files/run/t5256a.check b/test/files/run/t5256a.check index 7e60139db3..09b5a02831 100644 --- a/test/files/run/t5256a.check +++ b/test/files/run/t5256a.check @@ -1,6 +1,6 @@ class A A -Object { +AnyRef { def (): A def foo: Nothing } diff --git a/test/files/run/t5256b.check b/test/files/run/t5256b.check index a80df6eb30..ca93aaa706 100644 --- a/test/files/run/t5256b.check +++ b/test/files/run/t5256b.check @@ -1,6 +1,6 @@ class A Test.A -Object { +AnyRef { def (): Test.A def foo: Nothing } diff --git a/test/files/run/t5256d.check b/test/files/run/t5256d.check index 9742ae572e..b7617e80a2 100644 --- a/test/files/run/t5256d.check +++ b/test/files/run/t5256d.check @@ -22,7 +22,7 @@ scala> println(c.fullName) $line8.$read.$iw.$iw.$iw.$iw.A scala> println(c.typeSignature) -java.lang.Object { +scala.AnyRef { def (): A def foo: scala.Nothing } diff --git a/test/files/run/t5256e.check b/test/files/run/t5256e.check index 011115720c..ed3513183e 100644 --- a/test/files/run/t5256e.check +++ b/test/files/run/t5256e.check @@ -1,6 +1,6 @@ class A Test.C.A -Object { +AnyRef { def (): C.this.A def foo: Nothing } diff --git a/test/files/run/t5256f.check b/test/files/run/t5256f.check index e0fec85596..6a89d0b86a 100644 --- a/test/files/run/t5256f.check +++ b/test/files/run/t5256f.check @@ -1,12 +1,12 @@ class A1 Test.A1 -Object { +AnyRef { def (): Test.A1 def foo: Nothing } class A2 Test.A2 -Object { +AnyRef { def (): Test.this.A2 def foo: Nothing } diff --git a/test/files/scalap/abstractClass/result.test b/test/files/scalap/abstractClass/result.test index 9163346fc6..ef1daac23d 100644 --- a/test/files/scalap/abstractClass/result.test +++ b/test/files/scalap/abstractClass/result.test @@ -1,4 +1,4 @@ -abstract class AbstractClass extends java.lang.Object { +abstract class AbstractClass extends scala.AnyRef { def this() = { /* compiled code */ } def foo : scala.Predef.String } diff --git a/test/files/scalap/abstractMethod/result.test b/test/files/scalap/abstractMethod/result.test index 90f572f258..40fa02d408 100644 --- a/test/files/scalap/abstractMethod/result.test +++ b/test/files/scalap/abstractMethod/result.test @@ -1,4 +1,4 @@ -trait AbstractMethod extends java.lang.Object { +trait AbstractMethod extends scala.AnyRef { def $init$() : scala.Unit = { /* compiled code */ } def arity : scala.Int def isCool : scala.Boolean = { /* compiled code */ } diff --git a/test/files/scalap/cbnParam/result.test b/test/files/scalap/cbnParam/result.test index fbe035d63c..52ecb6ae66 100644 --- a/test/files/scalap/cbnParam/result.test +++ b/test/files/scalap/cbnParam/result.test @@ -1,3 +1,3 @@ -class CbnParam extends java.lang.Object { +class CbnParam extends scala.AnyRef { def this(s : => scala.Predef.String) = { /* compiled code */ } } diff --git a/test/files/scalap/classPrivate/result.test b/test/files/scalap/classPrivate/result.test index 5f2e1cc00e..ab2d40cdaf 100644 --- a/test/files/scalap/classPrivate/result.test +++ b/test/files/scalap/classPrivate/result.test @@ -1,7 +1,7 @@ -class ClassPrivate extends java.lang.Object { +class ClassPrivate extends scala.AnyRef { def this() = { /* compiled code */ } def baz : scala.Int = { /* compiled code */ } - class Outer extends java.lang.Object { + class Outer extends scala.AnyRef { def this() = { /* compiled code */ } private[ClassPrivate] def qux : scala.Int = { /* compiled code */ } } diff --git a/test/files/scalap/classWithExistential/result.test b/test/files/scalap/classWithExistential/result.test index b8ce005da9..caee3fd6de 100644 --- a/test/files/scalap/classWithExistential/result.test +++ b/test/files/scalap/classWithExistential/result.test @@ -1,4 +1,4 @@ -class ClassWithExistential extends java.lang.Object { +class ClassWithExistential extends scala.AnyRef { def this() = { /* compiled code */ } def foo[A, B] : scala.Function1[A, B forSome {type A <: scala.Seq[scala.Int]; type B >: scala.Predef.String}] = { /* compiled code */ } } diff --git a/test/files/scalap/classWithSelfAnnotation/result.test b/test/files/scalap/classWithSelfAnnotation/result.test index df7bd86643..82bbd9e8df 100644 --- a/test/files/scalap/classWithSelfAnnotation/result.test +++ b/test/files/scalap/classWithSelfAnnotation/result.test @@ -1,4 +1,4 @@ -class ClassWithSelfAnnotation extends java.lang.Object { +class ClassWithSelfAnnotation extends scala.AnyRef { this : ClassWithSelfAnnotation with java.lang.CharSequence => def this() = { /* compiled code */ } def foo : scala.Int = { /* compiled code */ } diff --git a/test/files/scalap/covariantParam/result.test b/test/files/scalap/covariantParam/result.test index 2f52f1f28e..f7a3c98966 100644 --- a/test/files/scalap/covariantParam/result.test +++ b/test/files/scalap/covariantParam/result.test @@ -1,4 +1,4 @@ -class CovariantParam[+A] extends java.lang.Object { +class CovariantParam[+A] extends scala.AnyRef { def this() = { /* compiled code */ } def foo[A](a : A) : scala.Int = { /* compiled code */ } } diff --git a/test/files/scalap/defaultParameter/result.test b/test/files/scalap/defaultParameter/result.test index 38bf6ac4e3..0c775ea7b5 100644 --- a/test/files/scalap/defaultParameter/result.test +++ b/test/files/scalap/defaultParameter/result.test @@ -1,3 +1,3 @@ -trait DefaultParameter extends java.lang.Object { +trait DefaultParameter extends scala.AnyRef { def foo(s : scala.Predef.String) : scala.Unit -} \ No newline at end of file +} diff --git a/test/files/scalap/implicitParam/result.test b/test/files/scalap/implicitParam/result.test index 0ea212dda6..a2cfd6092d 100644 --- a/test/files/scalap/implicitParam/result.test +++ b/test/files/scalap/implicitParam/result.test @@ -1,4 +1,4 @@ -class ImplicitParam extends java.lang.Object { +class ImplicitParam extends scala.AnyRef { def this() = { /* compiled code */ } def foo(i : scala.Int)(implicit f : scala.Float, d : scala.Double) : scala.Int = { /* compiled code */ } } diff --git a/test/files/scalap/packageObject/result.test b/test/files/scalap/packageObject/result.test index 94c6a01b08..5732d92958 100644 --- a/test/files/scalap/packageObject/result.test +++ b/test/files/scalap/packageObject/result.test @@ -1,4 +1,4 @@ -package object PackageObject extends java.lang.Object { +package object PackageObject extends scala.AnyRef { def this() = { /* compiled code */ } type A = scala.Predef.String def foo(i : scala.Int) : scala.Int = { /* compiled code */ } diff --git a/test/files/scalap/paramClauses/result.test b/test/files/scalap/paramClauses/result.test index dc4397386c..3a141e8faf 100644 --- a/test/files/scalap/paramClauses/result.test +++ b/test/files/scalap/paramClauses/result.test @@ -1,4 +1,4 @@ -class ParamClauses extends java.lang.Object { +class ParamClauses extends scala.AnyRef { def this() = { /* compiled code */ } def foo(i : scala.Int)(s : scala.Predef.String)(t : scala.Double) : scala.Int = { /* compiled code */ } } diff --git a/test/files/scalap/paramNames/result.test b/test/files/scalap/paramNames/result.test index 4d3c7d0c1e..85e37f858d 100644 --- a/test/files/scalap/paramNames/result.test +++ b/test/files/scalap/paramNames/result.test @@ -1,4 +1,4 @@ -class ParamNames extends java.lang.Object { +class ParamNames extends scala.AnyRef { def this() = { /* compiled code */ } def foo(s : => scala.Seq[scala.Int], s2 : => scala.Seq[scala.Any]) : scala.Unit = { /* compiled code */ } } diff --git a/test/files/scalap/sequenceParam/result.test b/test/files/scalap/sequenceParam/result.test index ed47c094fe..142d92fea3 100644 --- a/test/files/scalap/sequenceParam/result.test +++ b/test/files/scalap/sequenceParam/result.test @@ -1,3 +1,3 @@ -class SequenceParam extends java.lang.Object { +class SequenceParam extends scala.AnyRef { def this(s : scala.Predef.String, i : scala.Int*) = { /* compiled code */ } } diff --git a/test/files/scalap/simpleClass/result.test b/test/files/scalap/simpleClass/result.test index 905046ce52..4fdf25d1cf 100644 --- a/test/files/scalap/simpleClass/result.test +++ b/test/files/scalap/simpleClass/result.test @@ -1,4 +1,4 @@ -class SimpleClass extends java.lang.Object { +class SimpleClass extends scala.AnyRef { def this() = { /* compiled code */ } def foo : scala.Int = { /* compiled code */ } } diff --git a/test/files/scalap/traitObject/result.test b/test/files/scalap/traitObject/result.test index d0521043c8..104ba14f1a 100644 --- a/test/files/scalap/traitObject/result.test +++ b/test/files/scalap/traitObject/result.test @@ -1,8 +1,8 @@ -trait TraitObject extends java.lang.Object { +trait TraitObject extends scala.AnyRef { def $init$() : scala.Unit = { /* compiled code */ } def foo : scala.Int = { /* compiled code */ } } -object TraitObject extends java.lang.Object { +object TraitObject extends scala.AnyRef { def this() = { /* compiled code */ } def bar : scala.Int = { /* compiled code */ } } diff --git a/test/files/scalap/typeAnnotations/result.test b/test/files/scalap/typeAnnotations/result.test index d28712f12b..407b0235c6 100644 --- a/test/files/scalap/typeAnnotations/result.test +++ b/test/files/scalap/typeAnnotations/result.test @@ -1,4 +1,4 @@ -abstract class TypeAnnotations[@scala.specialized R] extends java.lang.Object { +abstract class TypeAnnotations[@scala.specialized R] extends scala.AnyRef { def this() = { /* compiled code */ } @scala.specialized val x : scala.Int = { /* compiled code */ } diff --git a/test/files/scalap/valAndVar/result.test b/test/files/scalap/valAndVar/result.test index 90081acade..e940da9801 100644 --- a/test/files/scalap/valAndVar/result.test +++ b/test/files/scalap/valAndVar/result.test @@ -1,4 +1,4 @@ -class ValAndVar extends java.lang.Object { +class ValAndVar extends scala.AnyRef { def this() = { /* compiled code */ } val foo : java.lang.String = { /* compiled code */ } var bar : scala.Int = { /* compiled code */ } diff --git a/test/files/scalap/wildcardType/result.test b/test/files/scalap/wildcardType/result.test index 28147b6605..e43261db32 100644 --- a/test/files/scalap/wildcardType/result.test +++ b/test/files/scalap/wildcardType/result.test @@ -1,3 +1,3 @@ -class WildcardType extends java.lang.Object { +class WildcardType extends scala.AnyRef { def this(f : scala.Function1[scala.Int, _]) = { /* compiled code */ } } -- cgit v1.2.3 From 38404e80fc008452a96ed521d278590ad7d0f7b4 Mon Sep 17 00:00:00 2001 From: Kato Kazuyoshi Date: Tue, 8 Jan 2013 23:55:44 +0900 Subject: SI-6555 Scaladoc's class filter shouldn't drop the last character The event handler have to wait "keyup", not "keydown". --- src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js index ff73745972..1323a06c01 100644 --- a/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js +++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js @@ -339,7 +339,7 @@ function configureTextFilter() { printAlphabet(); var input = $("#textfilter input"); resizeFilterBlock(); - input.bind("keydown", function(event) { + input.bind('keyup', function(event) { if (event.keyCode == 27) { // escape input.attr("value", ""); } -- cgit v1.2.3 From 8fb19b132579b7ddb9dd12ae829451dcf9d91332 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Wed, 9 Jan 2013 14:44:47 -0800 Subject: SI-5189 detect unsoundness when inferring type of match GADT skolems encode type slack that results from pattern matching on variant type constructors I thought they would not longer be relevant after cases have been typed, and since they caused weird issues with the old pattern matcher, I deskolemized in typedCase however, when we don't have an expected type for the match, we need to keep the skolems around until the skolemized type makes it out of the match and it becomes the result of type inference for that match when you do have an expected type, it will propagate to the case-level and the confrontation will thus already take place when typing individual cases --- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 11 +++++------ test/files/neg/t5189_inferred.check | 6 ++++++ test/files/neg/t5189_inferred.scala | 8 ++++++++ 3 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 test/files/neg/t5189_inferred.check create mode 100644 test/files/neg/t5189_inferred.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 9d390476db..5fe223dde6 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2523,11 +2523,7 @@ trait Typers extends Modes with Adaptations with Tags { } // body1 = checkNoEscaping.locals(context.scope, pt, body1) - val treeWithSkolems = treeCopy.CaseDef(cdef, pat1, guard1, body1) setType body1.tpe - - new TypeMapTreeSubstituter(deskolemizeGADTSkolems).traverse(treeWithSkolems) - - treeWithSkolems // now without skolems, actually + treeCopy.CaseDef(cdef, pat1, guard1, body1) setType body1.tpe } // undo adaptConstrPattern's evil deeds, as they confuse the old pattern matcher @@ -2562,7 +2558,10 @@ trait Typers extends Modes with Adaptations with Tags { val casesAdapted = if (!needAdapt) casesTyped else casesTyped map (adaptCase(_, mode, resTp)) - treeCopy.Match(tree, selector1, casesAdapted) setType resTp + val matchTyped = treeCopy.Match(tree, selector1, casesAdapted) setType resTp + if (!newPatternMatching) // TODO: remove this in 2.11 -- only needed for old pattern matcher + new TypeMapTreeSubstituter(deskolemizeGADTSkolems).traverse(matchTyped) + matchTyped } // match has been typed -- virtualize it if we're feeling experimental diff --git a/test/files/neg/t5189_inferred.check b/test/files/neg/t5189_inferred.check new file mode 100644 index 0000000000..9cc5dcc242 --- /dev/null +++ b/test/files/neg/t5189_inferred.check @@ -0,0 +1,6 @@ +t5189_inferred.scala:7: error: type mismatch; + found : scala.collection.immutable.Nil.type + required: ?A1 where type ?A1 + f(Invariant(arr): Covariant[Any])(0) = Nil + ^ +one error found diff --git a/test/files/neg/t5189_inferred.scala b/test/files/neg/t5189_inferred.scala new file mode 100644 index 0000000000..e4e8765445 --- /dev/null +++ b/test/files/neg/t5189_inferred.scala @@ -0,0 +1,8 @@ +trait Covariant[+A] +case class Invariant[A](xs: Array[A]) extends Covariant[A] + +class Test { + val arr = Array("abc") + def f[A](v: Covariant[A]) /*inferred!*/ = v match { case Invariant(xs) => xs } + f(Invariant(arr): Covariant[Any])(0) = Nil +} \ No newline at end of file -- cgit v1.2.3 From b1cea212f36b27636ef6aab76bf8992210a4426e Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Sun, 6 Jan 2013 01:43:20 -0800 Subject: SI-6925 use concrete type in applyOrElse's match's selector Fix a regression introduced in 28483739c3: PartialFunction synthesis was broken so that we'd get: ``` scala> def f[T](xs: Set[T]) = xs collect { case x => x } f: [T](xs: Set[T])scala.collection.immutable.Set[_ <: T] ``` rather than ``` scala> def f[T](xs: Set[T]) = xs collect { case x => x } f: [T](xs: Set[T])scala.collection.immutable.Set[T] ``` --- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 11 ++++++++++- test/files/pos/t6925.scala | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 test/files/pos/t6925.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 9d390476db..49c7181787 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -996,6 +996,7 @@ trait Typers extends Modes with Adaptations with Tags { object variantToSkolem extends VariantTypeMap { def apply(tp: Type) = mapOver(tp) match { case TypeRef(NoPrefix, tpSym, Nil) if variance != 0 && tpSym.isTypeParameterOrSkolem && tpSym.owner.isTerm => + tpSym.initialize // must initialize or tpSym.tpe might see random type params!! TODO: why is that?? val bounds = if (variance == 1) TypeBounds.upper(tpSym.tpe) else TypeBounds.lower(tpSym.tpe) // origin must be the type param so we can deskolemize val skolem = context.owner.newGADTSkolem(unit.freshTypeName("?"+tpSym.name), tpSym, bounds) @@ -2683,7 +2684,15 @@ trait Typers extends Modes with Adaptations with Tags { val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) paramSyms foreach (methodBodyTyper.context.scope enter _) - val match_ = methodBodyTyper.typedMatch(gen.mkUnchecked(selector), cases, mode, ptRes) + // SI-6925: subsume type of the selector to `argTp` + // we don't want/need the match to see the `A1` type that we must use for variance reasons in the method signature + // the cast is safe: it's an upcast -- the cast is needed because `(x: A1): A` doesn't always type check, even though `A1 <: A` + // specifically, it's needed when dealing with singleton types due to limitations/bugs? with SingletonClass + // (I first tried to use singletonBounds for A1's info when argTp.iStable -- didn't work) + // I decided to always do the cast, as posterasure will detect it's redundant and remove it + val selectorSubsumed = + Typed(gen.mkAsInstanceOf(selector, argTp.withoutAnnotations, true, false), TypeTree(argTp)) // TODO: factor this out -- mkCastTyped? + val match_ = methodBodyTyper.typedMatch(gen.mkUnchecked(selectorSubsumed), cases, mode, ptRes) val resTp = match_.tpe anonClass setInfo ClassInfoType(parentsPartial(List(argTp, resTp)), newScope, anonClass) diff --git a/test/files/pos/t6925.scala b/test/files/pos/t6925.scala new file mode 100644 index 0000000000..862a6e9d0e --- /dev/null +++ b/test/files/pos/t6925.scala @@ -0,0 +1,9 @@ +class Test { + def f[T](xs: Set[T]) /* no expected type to trigger inference */ = + xs collect { case x => x } + + def g[T](xs: Set[T]): Set[T] = f[T](xs) // check that f's inferred type is Set[T] + + // check that this type checks: + List(1).flatMap(n => Set(1).collect { case w => w }) +} \ No newline at end of file -- cgit v1.2.3 From e314ff1621ee26e1e4ec65abc6e360a7731bf488 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Sun, 6 Jan 2013 20:41:23 -0800 Subject: rework partial function synthesis no behavioral changes, just highly overdue cleanup some TODOs for further improvements --- .../scala/tools/nsc/typechecker/Typers.scala | 291 ++++++++++----------- test/files/pos/t6925b.scala | 18 ++ 2 files changed, 163 insertions(+), 146 deletions(-) create mode 100644 test/files/pos/t6925b.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 49c7181787..441ea6898b 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -996,7 +996,10 @@ trait Typers extends Modes with Adaptations with Tags { object variantToSkolem extends VariantTypeMap { def apply(tp: Type) = mapOver(tp) match { case TypeRef(NoPrefix, tpSym, Nil) if variance != 0 && tpSym.isTypeParameterOrSkolem && tpSym.owner.isTerm => - tpSym.initialize // must initialize or tpSym.tpe might see random type params!! TODO: why is that?? + // must initialize or tpSym.tpe might see random type params!! + // without this, we'll get very weird types inferred in test/scaladoc/run/SI-5933.scala + // TODO: why is that?? + tpSym.initialize val bounds = if (variance == 1) TypeBounds.upper(tpSym.tpe) else TypeBounds.lower(tpSym.tpe) // origin must be the type param so we can deskolemize val skolem = context.owner.newGADTSkolem(unit.freshTypeName("?"+tpSym.name), tpSym, bounds) @@ -1019,7 +1022,7 @@ trait Typers extends Modes with Adaptations with Tags { newTyper(ctorContext).infer.inferConstructorInstance(tree1, clazz.typeParams, ptSafe) // simplify types without losing safety, - // so that error messages don't unnecessarily refer to skolems + // so that we get rid of unnecessary type slack, and so that error messages don't unnecessarily refer to skolems val extrapolate = new ExistentialExtrapolation(freeVars) extrapolate (_: Type) val extrapolated = tree1.tpe match { case MethodType(ctorArgs, res) => // ctorArgs are actually in a covariant position, since this is the type of the subpatterns of the pattern represented by this Apply node @@ -2586,182 +2589,174 @@ trait Typers extends Modes with Adaptations with Tags { match_ // will be translated in phase `patmat` } - // synthesize and type check a PartialFunction implementation based on a match specified by `cases` - // Match(EmptyTree, cases) ==> new PartialFunction { def apply(params) = `translateMatch('`(param1,...,paramN)` match { cases }')` } - // for fresh params, the selector of the match we'll translated simply gathers those in a tuple - // NOTE: restricted to PartialFunction -- leave Function trees if the expected type does not demand a partial function - class MatchFunTyper(tree: Tree, cases: List[CaseDef], mode: Int, pt0: Type) { - // TODO: remove FunctionN support -- this is currently designed so that it can emit FunctionN and PartialFunction subclasses - // however, we should leave Function nodes until Uncurry so phases after typer can still detect normal Function trees - // we need to synthesize PartialFunction impls, though, to avoid nastiness in Uncurry in transforming&duplicating generated pattern matcher trees - // TODO: remove PartialFunction support from UnCurry - private val pt = deskolemizeGADTSkolems(pt0) - private val targs = pt.normalize.typeArgs - private val arity = if (isFunctionType(pt)) targs.length - 1 else 1 // TODO pt should always be a (Partial)Function, right? - private val ptRes = if (targs.isEmpty) WildcardType else targs.last // may not be fully defined - - private val isPartial = pt.typeSymbol == PartialFunctionClass - assert(isPartial) - - private val anonClass = context.owner.newAnonymousFunctionClass(tree.pos) - private val funThis = This(anonClass) - - anonClass addAnnotation AnnotationInfo(SerialVersionUIDAttr.tpe, List(Literal(Constant(0))), List()) - - def deriveFormals = - if (targs.isEmpty) Nil - else targs.init - - def mkParams(methodSym: Symbol, formals: List[Type] = deriveFormals) = - if (formals.isEmpty || !formals.forall(isFullyDefined)) { MissingParameterTypeAnonMatchError(tree, pt); Nil } - else methodSym newSyntheticValueParams formals - - def mkSel(params: List[Symbol]) = - if (params.isEmpty) EmptyTree - else { - val ids = params map (p => Ident(p.name)) - atPos(tree.pos.focusStart) { if (arity == 1) ids.head else gen.mkTuple(ids) } - } + /** synthesize and type check a PartialFunction implementation based on the match in `tree` + * + * `param => sel match { cases }` becomes: + * + * new AbstractPartialFunction[$argTp, $matchResTp] { + * def applyOrElse[A1 <: $argTp, B1 >: $matchResTp]($param: A1, default: A1 => B1): B1 = + * $selector match { $cases } + * def isDefinedAt(x: $argTp): Boolean = + * $selector match { $casesTrue } + * } + * + * TODO: it would be nicer to generate the tree specified above at once and type it as a whole, + * there are two gotchas: + * - matchResTp may not be known until we've typed the match (can only use resTp when it's fully defined), + * - if we typed the match in isolation first, you'd know its result type, but would have to re-jig the owner structure + * - could we use a type variable for matchResTp and backpatch it? + * - occurrences of `this` in `cases` or `sel` must resolve to the this of the class originally enclosing the match, + * not of the anonymous partial function subclass + * + * an alternative TODO: add partial function AST node or equivalent and get rid of this synthesis --> do everything in uncurry (or later) + * however, note that pattern matching codegen is designed to run *before* uncurry + */ + def synthesizePartialFunction(paramName: TermName, paramPos: Position, tree: Tree, mode: Int, pt0: Type): Tree = { + assert(pt0.typeSymbol == PartialFunctionClass) - import CODE._ + val pt = deskolemizeGADTSkolems(pt0) + val targs = pt.normalize.typeArgs - // need to duplicate the cases before typing them to generate the apply method, or the symbols will be all messed up - val casesTrue = if (isPartial) cases map (c => deriveCaseDef(c)(x => atPos(x.pos.focus)(TRUE_typed)).duplicate.asInstanceOf[CaseDef]) else Nil - // println("casesTrue "+ casesTrue) - def parentsPartial(targs: List[Type]) = addSerializable(appliedType(AbstractPartialFunctionClass.typeConstructor, targs)) + // if targs.head isn't fully defined, we can't translate --> error + if (targs.isEmpty || !isFullyDefined(targs.head)) { + MissingParameterTypeAnonMatchError(tree, pt) + return setError(tree) + } - def applyMethod = { - // rig the show so we can get started typing the method body -- later we'll correct the infos... - anonClass setInfo ClassInfoType(addSerializable(ObjectClass.tpe, pt), newScope, anonClass) - val methodSym = anonClass.newMethod(nme.apply, tree.pos, if(isPartial) (FINAL | OVERRIDE) else FINAL) - val paramSyms = mkParams(methodSym) - val selector = mkSel(paramSyms) + val argTp = targs.head - if (selector eq EmptyTree) EmptyTree - else { - methodSym setInfoAndEnter MethodType(paramSyms, AnyClass.tpe) + // NOTE: targs.last still might not be fully defined + val resTp = targs.last - val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) - paramSyms foreach (methodBodyTyper.context.scope enter _) + // targs must conform to Any for us to synthesize an applyOrElse (fallback to apply otherwise -- typically for @cps annotated targs) + val targsValidParams = targs forall (_ <:< AnyClass.tpe) - val match_ = methodBodyTyper.typedMatch(gen.mkUnchecked(selector), cases, mode, ptRes) - val resTp = match_.tpe + val anonClass = (context.owner + newAnonymousFunctionClass tree.pos + addAnnotation AnnotationInfo(SerialVersionUIDAttr.tpe, List(Literal(Constant(0))), List())) - val methFormals = paramSyms map (_.tpe) - val parents = ( - if (isPartial) parentsPartial(List(methFormals.head, resTp)) - else addSerializable(abstractFunctionType(methFormals, resTp)) - ) - anonClass setInfo ClassInfoType(parents, newScope, anonClass) - methodSym setInfoAndEnter MethodType(paramSyms, resTp) + import CODE._ - DefDef(methodSym, methodBodyTyper.virtualizedMatch(match_, mode, resTp)) - } - } + val Match(sel, cases) = tree - // def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 => B1): B1 = + // need to duplicate the cases before typing them to generate the apply method, or the symbols will be all messed up + val casesTrue = cases map (c => deriveCaseDef(c)(x => atPos(x.pos.focus)(TRUE_typed)).duplicate.asInstanceOf[CaseDef]) + + // must generate a new tree every time + def selector: Tree = gen.mkUnchecked( + if (sel != EmptyTree) sel.duplicate + else atPos(tree.pos.focusStart)( + // SI-6925: subsume type of the selector to `argTp` + // we don't want/need the match to see the `A1` type that we must use for variance reasons in the method signature + // + // this failed: replace `selector` by `Typed(selector, TypeTree(argTp))` -- as it's an upcast, this should never fail, + // `(x: A1): A` doesn't always type check, even though `A1 <: A`, due to singleton types + // hence the cast, which will be erased in posterasure + Typed(gen.mkAsInstanceOf(Ident(paramName), argTp.withoutAnnotations, true, false), TypeTree(argTp))) + ) + + def mkParam(methodSym: Symbol, tp: Type = argTp) = + methodSym.newValueParameter(paramName, paramPos.focus, SYNTHETIC) setInfo tp + + // `def applyOrElse[A1 <: $argTp, B1 >: $matchResTp](x: A1, default: A1 => B1): B1 = + // ${`$selector match { $cases }` updateAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x)))}` def applyOrElseMethodDef = { - // rig the show so we can get started typing the method body -- later we'll correct the infos... - // targs were type arguments for PartialFunction, so we know they will work for AbstractPartialFunction as well - anonClass setInfo ClassInfoType(parentsPartial(targs), newScope, anonClass) val methodSym = anonClass.newMethod(nme.applyOrElse, tree.pos, FINAL | OVERRIDE) // create the parameter that corresponds to the function's parameter - val List(argTp) = deriveFormals - val A1 = methodSym newTypeParameter(newTypeName("A1")) setInfo TypeBounds.upper(argTp) - val paramSyms@List(x) = mkParams(methodSym, List(A1.tpe)) - val selector = mkSel(paramSyms) - - if (selector eq EmptyTree) EmptyTree - else { - // applyOrElse's default parameter: - val B1 = methodSym newTypeParameter(newTypeName("B1")) setInfo TypeBounds.empty //lower(resTp) - val default = methodSym newValueParameter(newTermName("default"), tree.pos.focus, SYNTHETIC) setInfo functionType(List(A1.tpe), B1.tpe) + val A1 = methodSym newTypeParameter (newTypeName("A1")) setInfo TypeBounds.upper(argTp) + val x = mkParam(methodSym, A1.tpe) - val paramSyms = List(x, default) - methodSym setInfoAndEnter polyType(List(A1, B1), MethodType(paramSyms, B1.tpe)) + // applyOrElse's default parameter: + val B1 = methodSym newTypeParameter (newTypeName("B1")) setInfo TypeBounds.empty //lower(resTp) + val default = methodSym newValueParameter (newTermName("default"), tree.pos.focus, SYNTHETIC) setInfo functionType(List(A1.tpe), B1.tpe) - val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) - paramSyms foreach (methodBodyTyper.context.scope enter _) + val paramSyms = List(x, default) + methodSym setInfo polyType(List(A1, B1), MethodType(paramSyms, B1.tpe)) - // SI-6925: subsume type of the selector to `argTp` - // we don't want/need the match to see the `A1` type that we must use for variance reasons in the method signature - // the cast is safe: it's an upcast -- the cast is needed because `(x: A1): A` doesn't always type check, even though `A1 <: A` - // specifically, it's needed when dealing with singleton types due to limitations/bugs? with SingletonClass - // (I first tried to use singletonBounds for A1's info when argTp.iStable -- didn't work) - // I decided to always do the cast, as posterasure will detect it's redundant and remove it - val selectorSubsumed = - Typed(gen.mkAsInstanceOf(selector, argTp.withoutAnnotations, true, false), TypeTree(argTp)) // TODO: factor this out -- mkCastTyped? - val match_ = methodBodyTyper.typedMatch(gen.mkUnchecked(selectorSubsumed), cases, mode, ptRes) - val resTp = match_.tpe + val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) + // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) + paramSyms foreach (methodBodyTyper.context.scope enter _) - anonClass setInfo ClassInfoType(parentsPartial(List(argTp, resTp)), newScope, anonClass) - B1 setInfo TypeBounds.lower(resTp) - anonClass.info.decls enter methodSym // methodSym's info need not change (B1's bound has been updated instead) + val match_ = methodBodyTyper.typedMatch(selector, cases, mode, resTp) - match_ setType B1.tpe + val matchResTp = match_.tpe + B1 setInfo TypeBounds.lower(matchResTp) // patch info - // the default uses applyOrElse's first parameter since the scrut's type has been widened - val body = methodBodyTyper.virtualizedMatch(match_ updateAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x))), mode, B1.tpe) + match_ setType B1.tpe - DefDef(methodSym, body) - } + // the default uses applyOrElse's first parameter since the scrut's type has been widened + val matchWithDefault = match_ updateAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x))) + (DefDef(methodSym, methodBodyTyper.virtualizedMatch(matchWithDefault, mode, B1.tpe)), matchResTp) } + // `def isDefinedAt(x: $argTp): Boolean = ${`$selector match { $casesTrue ` updateAttachment DefaultOverrideMatchAttachment(FALSE_typed)}` def isDefinedAtMethod = { val methodSym = anonClass.newMethod(nme.isDefinedAt, tree.pos.makeTransparent, FINAL) - val paramSyms = mkParams(methodSym) - val selector = mkSel(paramSyms) + val paramSym = mkParam(methodSym) - if (selector eq EmptyTree) EmptyTree - else { - val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) - paramSyms foreach (methodBodyTyper.context.scope enter _) - methodSym setInfoAndEnter MethodType(paramSyms, BooleanClass.tpe) + val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) + methodBodyTyper.context.scope enter paramSym + methodSym setInfo MethodType(List(paramSym), BooleanClass.tpe) - val match_ = methodBodyTyper.typedMatch(gen.mkUnchecked(selector), casesTrue, mode, BooleanClass.tpe) - val body = methodBodyTyper.virtualizedMatch(match_ updateAttachment DefaultOverrideMatchAttachment(FALSE_typed), mode, BooleanClass.tpe) + val match_ = methodBodyTyper.typedMatch(selector, casesTrue, mode, BooleanClass.tpe) - DefDef(methodSym, body) - } + val matchWithDefault = match_ updateAttachment DefaultOverrideMatchAttachment(FALSE_typed) + DefDef(methodSym, methodBodyTyper.virtualizedMatch(matchWithDefault, mode, BooleanClass.tpe)) } - lazy val members = if (isPartial) { - // somehow @cps annotations upset the typer when looking at applyOrElse's signature, but not apply's - // TODO: figure out the details (T @cps[U] is not a subtype of Any, but then why does it work for the apply method?) - if (targs forall (_ <:< AnyClass.tpe)) List(applyOrElseMethodDef, isDefinedAtMethod) - else List(applyMethod, isDefinedAtMethod) - } else List(applyMethod) + // only used for @cps annotated partial functions + def applyMethod = { + val methodSym = anonClass.newMethod(nme.apply, tree.pos, FINAL | OVERRIDE) + val paramSym = mkParam(methodSym) - def translated = - if (members.head eq EmptyTree) setError(tree) - else { - val typedBlock = typedPos(tree.pos, mode, pt) { - Block(ClassDef(anonClass, NoMods, ListOfNil, members, tree.pos.focus), atPos(tree.pos.focus)(New(anonClass.tpe))) - } - // Don't leak implementation details into the type, see SI-6575 - if (isPartial && !typedBlock.isErrorTyped) - typedPos(tree.pos, mode, pt) { - Typed(typedBlock, TypeTree(typedBlock.tpe baseType PartialFunctionClass)) - } - else typedBlock - } - } + methodSym setInfo MethodType(List(paramSym), AnyClass.tpe) + + val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) + // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) + methodBodyTyper.context.scope enter paramSym + + val match_ = methodBodyTyper.typedMatch(selector, cases, mode, resTp) - // Function(params, Match(sel, cases)) ==> new Function { def apply(params) = `translateMatch('sel match { cases }')` } - class MatchFunTyperBetaReduced(fun: Function, sel: Tree, cases: List[CaseDef], mode: Int, pt: Type) extends MatchFunTyper(fun, cases, mode, pt) { - override def deriveFormals = - fun.vparams map { p => if(p.tpt.tpe == null) typedType(p.tpt).tpe else p.tpt.tpe } + val matchResTp = match_.tpe + methodSym setInfo MethodType(List(paramSym), matchResTp) // patch info - // the only difference from the super class is that we must preserve the names of the parameters - override def mkParams(methodSym: Symbol, formals: List[Type] = deriveFormals) = - (fun.vparams, formals).zipped map { (p, tp) => - methodSym.newValueParameter(p.name, p.pos.focus, SYNTHETIC) setInfo tp + (DefDef(methodSym, methodBodyTyper.virtualizedMatch(match_, mode, matchResTp)), matchResTp) + } + + def parents(resTp: Type) = addSerializable(appliedType(AbstractPartialFunctionClass.typeConstructor, List(argTp, resTp))) + + val members = { + val (applyMeth, matchResTp) = { + // rig the show so we can get started typing the method body -- later we'll correct the infos... + // targs were type arguments for PartialFunction, so we know they will work for AbstractPartialFunction as well + anonClass setInfo ClassInfoType(parents(resTp), newScope, anonClass) + + // somehow @cps annotations upset the typer when looking at applyOrElse's signature, but not apply's + // TODO: figure out the details (T @cps[U] is not a subtype of Any, but then why does it work for the apply method?) + if (targsValidParams) applyOrElseMethodDef + else applyMethod } - override def mkSel(params: List[Symbol]) = sel.duplicate + // patch info to the class's definitive info + anonClass setInfo ClassInfoType(parents(matchResTp), newScope, anonClass) + List(applyMeth, isDefinedAtMethod) + } + + members foreach (m => anonClass.info.decls enter m.symbol) + + val typedBlock = typedPos(tree.pos, mode, pt) { + Block(ClassDef(anonClass, NoMods, ListOfNil, members, tree.pos.focus), atPos(tree.pos.focus)(New(anonClass.tpe))) + } + + if (typedBlock.isErrorTyped) typedBlock + else // Don't leak implementation details into the type, see SI-6575 + typedPos(tree.pos, mode, pt) { + Typed(typedBlock, TypeTree(typedBlock.tpe baseType PartialFunctionClass)) + } } + /** * @param fun ... * @param mode ... @@ -2813,14 +2808,17 @@ trait Typers extends Modes with Adaptations with Tags { } fun.body match { - // later phase indicates scaladoc is calling (where shit is messed up, I tell you) - // -- so fall back to old patmat, which is more forgiving + // translate `x => x match { }` : PartialFunction to + // `new PartialFunction { def applyOrElse(x, default) = x match { } def isDefinedAt(x) = ... }` case Match(sel, cases) if (sel ne EmptyTree) && newPatternMatching && (pt.typeSymbol == PartialFunctionClass) => // go to outer context -- must discard the context that was created for the Function since we're discarding the function // thus, its symbol, which serves as the current context.owner, is not the right owner // you won't know you're using the wrong owner until lambda lift crashes (unless you know better than to use the wrong owner) val outerTyper = newTyper(context.outer) - (new outerTyper.MatchFunTyperBetaReduced(fun, sel, cases, mode, pt)).translated + val p = fun.vparams.head + if (p.tpt.tpe == null) p.tpt setType outerTyper.typedType(p.tpt).tpe + + outerTyper.synthesizePartialFunction(p.name, p.pos, fun.body, mode, pt) case _ => val vparamSyms = fun.vparams map { vparam => enterSym(context, vparam) @@ -4353,7 +4351,8 @@ trait Typers extends Modes with Adaptations with Tags { val selector = tree.selector val cases = tree.cases if (selector == EmptyTree) { - if (newPatternMatching && (pt.typeSymbol == PartialFunctionClass)) (new MatchFunTyper(tree, cases, mode, pt)).translated + if (newPatternMatching && (pt.typeSymbol == PartialFunctionClass)) + synthesizePartialFunction(newTermName(context.unit.fresh.newName("x")), tree.pos, tree, mode, pt) else { val arity = if (isFunctionType(pt)) pt.normalize.typeArgs.length - 1 else 1 val params = for (i <- List.range(0, arity)) yield diff --git a/test/files/pos/t6925b.scala b/test/files/pos/t6925b.scala new file mode 100644 index 0000000000..ca25146dfc --- /dev/null +++ b/test/files/pos/t6925b.scala @@ -0,0 +1,18 @@ +// code *generated* by test/scaladoc/run/SI-5933.scala +// duplicated here because it's related to SI-6925 + +import language.higherKinds + +abstract class Base[M[_, _]] { + def foo[A, B]: M[(A, B), Any] +} + +class Derived extends Base[PartialFunction] { + def foo[AA, BB] /*: PartialFunction[(A, B) => Any]*/ = { case (a, b) => (a: AA, b: BB) } +} + +object Test { + lazy val lx = { println("hello"); 3 } + def test1(x: Int = lx) = ??? + def test2(x: Int = lx match { case 0 => 1; case 3 => 4 }) = ??? +} \ No newline at end of file -- cgit v1.2.3 From 51f574ac9ff0dbcb665f48a8c1a380c59f2bb641 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Thu, 10 Jan 2013 13:25:33 -0800 Subject: clean up synthesizePartialFunction implement the following review comments by @retronym: - [x] Please clothe this naked assert. - [x] Use match to dissect targs and check isFullyDefined. - [x] Instead of `targs.head`/`targs.last`, use `val argTp :: resTp :: Nil = targs`. - [x] Add a quasi-quote-style comment for `apply`. - [x] Factor out mkCastPreservingAnnotations. --- src/compiler/scala/tools/nsc/ast/TreeGen.scala | 5 ++++ .../tools/nsc/typechecker/PatternMatching.scala | 9 ++------ .../scala/tools/nsc/typechecker/Typers.scala | 27 ++++++++++++---------- 3 files changed, 22 insertions(+), 19 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/ast/TreeGen.scala b/src/compiler/scala/tools/nsc/ast/TreeGen.scala index 5cb43575b8..96146b7343 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala @@ -253,6 +253,11 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { } } + // drop annotations generated by CPS plugin etc, since its annotationchecker rejects T @cps[U] <: Any + // let's assume for now annotations don't affect casts, drop them there, and bring them back using the outer Typed tree + def mkCastPreservingAnnotations(tree: Tree, pt: Type) = + Typed(mkCast(tree, pt.withoutAnnotations.dealias), TypeTree(pt)) + /** Generate a cast for tree Tree representing Array with * elem type elemtp to expected type pt. */ diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index fa8aff5cdd..d73fb680f2 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -1478,14 +1478,9 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL def _equals(checker: Tree, binder: Symbol): Tree = checker MEMBER_== REF(binder) // NOTE: checker must be the target of the ==, that's the patmat semantics for ya def and(a: Tree, b: Tree): Tree = a AND b - // drop annotations generated by CPS plugin etc, since its annotationchecker rejects T @cps[U] <: Any - // let's assume for now annotations don't affect casts, drop them there, and bring them back using the outer Typed tree - private def mkCast(t: Tree, tp: Type) = - Typed(gen.mkAsInstanceOf(t, tp.withoutAnnotations, true, false), TypeTree() setType tp) - // the force is needed mainly to deal with the GADT typing hack (we can't detect it otherwise as tp nor pt need contain an abstract type, we're just casting wildly) - def _asInstanceOf(t: Tree, tp: Type): Tree = if (t.tpe != NoType && t.isTyped && typesConform(t.tpe, tp)) t else mkCast(t, tp) - def _asInstanceOf(b: Symbol, tp: Type): Tree = if (typesConform(b.info, tp)) REF(b) else mkCast(REF(b), tp) + def _asInstanceOf(t: Tree, tp: Type): Tree = if (t.tpe != NoType && t.isTyped && typesConform(t.tpe, tp)) t else gen.mkCastPreservingAnnotations(t, tp) + def _asInstanceOf(b: Symbol, tp: Type): Tree = if (typesConform(b.info, tp)) REF(b) else gen.mkCastPreservingAnnotations(REF(b), tp) def _isInstanceOf(b: Symbol, tp: Type): Tree = gen.mkIsInstanceOf(REF(b), tp.withoutAnnotations, true, false) // if (typesConform(b.info, tpX)) { patmatDebug("warning: emitted spurious isInstanceOf: "+(b, tp)); TRUE } diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 441ea6898b..be00aebf1b 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2612,21 +2612,21 @@ trait Typers extends Modes with Adaptations with Tags { * however, note that pattern matching codegen is designed to run *before* uncurry */ def synthesizePartialFunction(paramName: TermName, paramPos: Position, tree: Tree, mode: Int, pt0: Type): Tree = { - assert(pt0.typeSymbol == PartialFunctionClass) + assert(pt0.typeSymbol == PartialFunctionClass, s"PartialFunction synthesis for match in $tree requires PartialFunction expected type, but got $pt0.") val pt = deskolemizeGADTSkolems(pt0) val targs = pt.normalize.typeArgs - // if targs.head isn't fully defined, we can't translate --> error - if (targs.isEmpty || !isFullyDefined(targs.head)) { - MissingParameterTypeAnonMatchError(tree, pt) - return setError(tree) + // if targs.head isn't fully defined, we can translate --> error + targs match { + case argTp :: _ if isFullyDefined(argTp) => // ok + case _ => // uh-oh + MissingParameterTypeAnonMatchError(tree, pt) + return setError(tree) } - val argTp = targs.head - - // NOTE: targs.last still might not be fully defined - val resTp = targs.last + // NOTE: resTp still might not be fully defined + val argTp :: resTp :: Nil = targs // targs must conform to Any for us to synthesize an applyOrElse (fallback to apply otherwise -- typically for @cps annotated targs) val targsValidParams = targs forall (_ <:< AnyClass.tpe) @@ -2650,10 +2650,12 @@ trait Typers extends Modes with Adaptations with Tags { // we don't want/need the match to see the `A1` type that we must use for variance reasons in the method signature // // this failed: replace `selector` by `Typed(selector, TypeTree(argTp))` -- as it's an upcast, this should never fail, - // `(x: A1): A` doesn't always type check, even though `A1 <: A`, due to singleton types + // `(x: A1): A` doesn't always type check, even though `A1 <: A`, due to singleton types (test/files/pos/t4269.scala) // hence the cast, which will be erased in posterasure - Typed(gen.mkAsInstanceOf(Ident(paramName), argTp.withoutAnnotations, true, false), TypeTree(argTp))) - ) + // (the cast originally caused extremely weird types to show up + // in test/scaladoc/run/SI-5933.scala because `variantToSkolem` was missing `tpSym.initialize`) + gen.mkCastPreservingAnnotations(Ident(paramName), argTp) + )) def mkParam(methodSym: Symbol, tp: Type = argTp) = methodSym.newValueParameter(paramName, paramPos.focus, SYNTHETIC) setInfo tp @@ -2706,6 +2708,7 @@ trait Typers extends Modes with Adaptations with Tags { } // only used for @cps annotated partial functions + // `def apply(x: $argTp): $matchResTp = $selector match { $cases }` def applyMethod = { val methodSym = anonClass.newMethod(nme.apply, tree.pos, FINAL | OVERRIDE) val paramSym = mkParam(methodSym) -- cgit v1.2.3 From 8475807f540a698c8456bc113b9c5b9186ee2cf5 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Thu, 10 Jan 2013 14:43:00 -0800 Subject: SI-6955 switch emission no longer foiled by type alias dealias the type of the scrutinee before checking it's switchable now with tests! (using IcodeTest since javap is not available everywhere) --- .../tools/nsc/typechecker/PatternMatching.scala | 2 +- test/files/run/t6955.check | 1 + test/files/run/t6955.scala | 26 ++++++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 test/files/run/t6955.check create mode 100644 test/files/run/t6955.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index fa8aff5cdd..044201b1d7 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -3527,7 +3527,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL override def emitSwitch(scrut: Tree, scrutSym: Symbol, cases: List[List[TreeMaker]], pt: Type, matchFailGenOverride: Option[Tree => Tree], unchecked: Boolean): Option[Tree] = { import CODE._ val regularSwitchMaker = new RegularSwitchMaker(scrutSym, matchFailGenOverride, unchecked) // TODO: if patterns allow switch but the type of the scrutinee doesn't, cast (type-test) the scrutinee to the corresponding switchable type and switch on the result - if (regularSwitchMaker.switchableTpe(scrutSym.tpe)) { + if (regularSwitchMaker.switchableTpe(scrutSym.tpe.dealias)) { // TODO: switch to dealiasWiden in 2.11 val caseDefsWithDefault = regularSwitchMaker(cases map {c => (scrutSym, c)}, pt) if (caseDefsWithDefault isEmpty) None // not worth emitting a switch. else { diff --git a/test/files/run/t6955.check b/test/files/run/t6955.check new file mode 100644 index 0000000000..0cfbf08886 --- /dev/null +++ b/test/files/run/t6955.check @@ -0,0 +1 @@ +2 diff --git a/test/files/run/t6955.scala b/test/files/run/t6955.scala new file mode 100644 index 0000000000..2610acdec4 --- /dev/null +++ b/test/files/run/t6955.scala @@ -0,0 +1,26 @@ +import scala.tools.partest.IcodeTest + +class Switches { + type Tag = Byte + + def switchBad(i: Tag): Int = i match { // notice type of i is Tag = Byte + case 1 => 1 + case 2 => 2 + case 3 => 3 + case _ => 0 + } + + def switchOkay(i: Byte): Int = i match { // notice type of i is Byte + case 1 => 1 + case 2 => 2 + case 3 => 3 + case _ => 0 + } +} + +object Test extends IcodeTest { + // ensure we get two switches out of this -- ignore the rest of the output for robustness + // exclude the constant we emit for the "SWITCH ..." string below (we get the icode for all the code you see in this file) + override def show() = println(collectIcode("").filter(x => x.indexOf("SWITCH ...") >= 0 && x.indexOf("CONSTANT(") == -1).size) +} + -- cgit v1.2.3 From 1212af48f474bc392b73d29f4719b5ff8d0a66fa Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Sun, 13 Jan 2013 13:07:52 +0100 Subject: SI-5340 Change println to log An esoteric implicit search could trigger an "amb prefix ..." message to standard out. Now the message has been improved and sent to the logger. --- .../scala/tools/nsc/typechecker/Implicits.scala | 2 +- test/files/neg/t5340.check | 6 +++++ test/files/neg/t5340.scala | 29 ++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 test/files/neg/t5340.check create mode 100644 test/files/neg/t5340.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index 10003723fd..ec3a0a0ef7 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -956,7 +956,7 @@ trait Implicits { infoMap get sym match { case Some(infos1) => if (infos1.nonEmpty && !(pre =:= infos1.head.pre.prefix)) { - println("amb prefix: "+pre+"#"+sym+" "+infos1.head.pre.prefix+"#"+sym) + log(s"Ignoring implicit members of $pre#$sym as it is also visible via another prefix: ${infos1.head.pre.prefix}") infoMap(sym) = List() // ambiguous prefix - ignore implicit members } case None => diff --git a/test/files/neg/t5340.check b/test/files/neg/t5340.check new file mode 100644 index 0000000000..2de19293c4 --- /dev/null +++ b/test/files/neg/t5340.check @@ -0,0 +1,6 @@ +t5340.scala:17: error: type mismatch; + found : MyApp.r.E + required: MyApp.s.E + println(b: s.E) + ^ +one error found diff --git a/test/files/neg/t5340.scala b/test/files/neg/t5340.scala new file mode 100644 index 0000000000..b283f13338 --- /dev/null +++ b/test/files/neg/t5340.scala @@ -0,0 +1,29 @@ +class Poly { + class E + object E { + implicit def conv(value: Any): E = sys.error("") + } +} + +object MyApp { + val r: Poly = sys.error("") + val s: Poly = sys.error("") + val b: r.E = sys.error("") + + // okay + s.E.conv(b): s.E + + // compilation fails with error below + println(b: s.E) + + // amb prefix: MyApp.s.type#class E MyApp.r.type#class E + // amb prefix: MyApp.s.type#class E MyApp.r.type#class E + // ../test/pending/run/t5310.scala:17: error: type mismatch; + // found : MyApp.r.E + // required: MyApp.s.E + // println(b: s.E) + // ^ + + // The type error is as expected, but the `amb prefix` should be logged, + // rather than printed to standard out. +} -- cgit v1.2.3 From 39352fe0f3048e86b339db4b40851a9f27c7a6ef Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Sun, 13 Jan 2013 14:28:33 +0100 Subject: SI-6082 Conditionally expand @ann(x) to @ann(value = x) ... if the annotation has an argument with the name `value`. Doing so unconditionally obscures error messages. We still require that arguments to ClassFileAnnotations are named, other than for this special case. --- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 11 +++++++---- test/files/neg/t6082.check | 13 +++++++++++++ test/files/neg/t6082.scala | 2 ++ 3 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 test/files/neg/t6082.check create mode 100644 test/files/neg/t6082.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 386eec207a..0ca1e01114 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -3637,15 +3637,18 @@ trait Typers extends Modes with Adaptations with Tags { } else if (argss.length > 1) { reportAnnotationError(MultipleArgumentListForAnnotationError(ann)) } else { - val args = - if (argss.head.length == 1 && !isNamed(argss.head.head)) - List(new AssignOrNamedArg(Ident(nme.value), argss.head.head)) - else argss.head val annScope = annType.decls .filter(sym => sym.isMethod && !sym.isConstructor && sym.isJavaDefined) val names = new scala.collection.mutable.HashSet[Symbol] + def hasValue = names exists (_.name == nme.value) names ++= (if (isJava) annScope.iterator else typedFun.tpe.params.iterator) + val args = argss match { + case List(List(arg)) if !isNamed(arg) && hasValue => + List(new AssignOrNamedArg(Ident(nme.value), arg)) + case as :: _ => as + } + val nvPairs = args map { case arg @ AssignOrNamedArg(Ident(name), rhs) => val sym = if (isJava) annScope.lookup(name) diff --git a/test/files/neg/t6082.check b/test/files/neg/t6082.check new file mode 100644 index 0000000000..b68de5ce08 --- /dev/null +++ b/test/files/neg/t6082.check @@ -0,0 +1,13 @@ +t6082.scala:1: warning: Implementation restriction: subclassing Classfile does not +make your annotation visible at runtime. If that is what +you want, you must write the annotation class in Java. +class annot(notValue: String) extends annotation.ClassfileAnnotation + ^ +t6082.scala:2: error: classfile annotation arguments have to be supplied as named arguments +@annot("") class C + ^ +t6082.scala:2: error: annotation annot is missing argument notValue +@annot("") class C + ^ +one warning found +two errors found diff --git a/test/files/neg/t6082.scala b/test/files/neg/t6082.scala new file mode 100644 index 0000000000..30de91a4c9 --- /dev/null +++ b/test/files/neg/t6082.scala @@ -0,0 +1,2 @@ +class annot(notValue: String) extends annotation.ClassfileAnnotation +@annot("") class C \ No newline at end of file -- cgit v1.2.3 From 9cc61f310ef5f80e598956bee20156b7bc472e84 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Sun, 13 Jan 2013 15:07:31 +0100 Subject: SI-6479 Don't lift try exprs in label arguments. The new pattern matcher uses label jumps to GOTO the next case. Uncurry treated these like regular method arguments, and performed the liftedTree() transformation, which ensures that try expressions are only used in a statement position. Even try in statement position of a block used as such an argument are subject to the same transform. This transform stems from the JVM limitation, that try/catch does not leave a value on the stack. See b194446. This commit changes Uncurry to avoid this transform for arguments to label jumps. This avoids needlessly indirect code, and enables tail call elimination in more cases. As an example, Scala 2.10.0 transforms the last method of the enclosed test case to: try { case val x1: Int = 1; case5(){ if (2.==(x1)) { val x2: Int = x1; matchEnd4({ { def liftedTree2(): Unit = try { throw new scala.runtime.NonLocalReturnControl[Unit](nonLocalReturnKey1, ()) } catch { case (e @ (_: ClassNotFoundException)) => () }; liftedTree2() }; TailrecAfterTryCatch.this.bad() }) } else case6() }; case6(){ matchEnd4(throw new MatchError(x1)) }; matchEnd4(x: Unit){ x } } catch { case (ex @ (_: scala.runtime.NonLocalReturnControl[Unit @unchecked])) => if (ex.key().eq(nonLocalReturnKey1)) ex.value() else throw ex } After this patch: @scala.annotation.tailrec final def bad(): Unit = { case val x1: Int = 1; case5(){ if (2.==(x1)) { val x2: Int = x1; matchEnd4({ try { return () } catch { case (e @ (_: ClassNotFoundException)) => () }; TailrecAfterTryCatch.this.bad() }) } else case6() }; case6(){ matchEnd4(throw new MatchError(x1)) }; matchEnd4(x: Unit){ x } } --- .../scala/tools/nsc/transform/UnCurry.scala | 6 ++- test/files/pos/t6479.scala | 56 ++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 test/files/pos/t6479.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 838ea7d5a0..55230f9685 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -621,11 +621,13 @@ abstract class UnCurry extends InfoTransform case Apply(fn, args) => if (fn.symbol == Object_synchronized && shouldBeLiftedAnyway(args.head)) transform(treeCopy.Apply(tree, fn, List(liftTree(args.head)))) - else - withNeedLift(true) { + else { + val needLift = needTryLift || !fn.symbol.isLabel // SI-6749, no need to lift in args to label jumps. + withNeedLift(needLift) { val formals = fn.tpe.paramTypes treeCopy.Apply(tree, transform(fn), transformTrees(transformArgs(tree.pos, fn.symbol, args, formals))) } + } case Assign(Select(_, _), _) => withNeedLift(true) { super.transform(tree) } diff --git a/test/files/pos/t6479.scala b/test/files/pos/t6479.scala new file mode 100644 index 0000000000..c463bc5ab0 --- /dev/null +++ b/test/files/pos/t6479.scala @@ -0,0 +1,56 @@ +object TailrecAfterTryCatch { + + @annotation.tailrec + final def good1() { + 1 match { + case 2 => { + try { + // return + } catch { + case e: ClassNotFoundException => + } + good1() + } + } + } + + @annotation.tailrec + final def good2() { + //1 match { + // case 2 => { + try { + return + } catch { + case e: ClassNotFoundException => + } + good2() + // } + //} + } + + @annotation.tailrec + final def good3() { + val 1 = 2 + try { + return + } catch { + case e: ClassNotFoundException => + } + good3() + } + + @annotation.tailrec + final def bad() { + 1 match { + case 2 => { + try { + return + } catch { + case e: ClassNotFoundException => + } + bad() + } + } + } + +} \ No newline at end of file -- cgit v1.2.3 From 3ef487ecb6733bfe3c13d89780ebcfc81f9a5ea0 Mon Sep 17 00:00:00 2001 From: James Iry Date: Sun, 13 Jan 2013 20:33:52 -0800 Subject: SI-5954 Implementation restriction preventing companions in package objs Companion objects (and thus also case classes) in package objects caused an assert about an overloaded symbol when everything was compiled twice. It's a hairy problem that doesn't fit in 2.10.1. So this fix adds an implementation restriction. It also has a test to make sure the error messages are clean and reasonably friendly, and does not catch other things defined in package objects. The test includes a commented out test in case somebody thinks they've solved the underlying problem. A handful of tests were falling afoul of the new implementation restriction. I verified that they do in fact fail on second compile so they aren't false casualties. But they do test real things we'd like to work once the re-compile issue is fixed. So I added a -X flag to disable the implementation restriction and made all the tests accidentally clobbered by the restriction use that flag. --- .../scala/tools/nsc/settings/ScalaSettings.scala | 1 + .../scala/tools/nsc/typechecker/Typers.scala | 26 ++++++++++++ .../internal/settings/MutableSettings.scala | 2 + src/reflect/scala/reflect/runtime/Settings.scala | 1 + test/files/neg/t5954.check | 16 ++++++++ test/files/neg/t5954.scala | 46 ++++++++++++++++++++++ test/files/pos/package-case.flags | 1 + test/files/pos/t2130-1.flags | 1 + test/files/pos/t2130-2.flags | 1 + test/files/pos/t3999b.flags | 1 + test/files/pos/t4052.flags | 1 + 11 files changed, 97 insertions(+) create mode 100644 test/files/neg/t5954.check create mode 100644 test/files/neg/t5954.scala create mode 100644 test/files/pos/package-case.flags create mode 100644 test/files/pos/t2130-1.flags create mode 100644 test/files/pos/t2130-2.flags create mode 100644 test/files/pos/t3999b.flags create mode 100644 test/files/pos/t4052.flags (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index cfc7f14210..517b91dca8 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala @@ -174,6 +174,7 @@ trait ScalaSettings extends AbsScalaSettings val etaExpandKeepsStar = BooleanSetting ("-Yeta-expand-keeps-star", "Eta-expand varargs methods to T* rather than Seq[T]. This is a temporary option to ease transition.") val Yinvalidate = StringSetting ("-Yinvalidate", "classpath-entry", "Invalidate classpath entry before run", "") val noSelfCheck = BooleanSetting ("-Yno-self-type-checks", "Suppress check for self-type conformance among inherited members.") + val companionsInPkgObjs = BooleanSetting("-Ycompanions-in-pkg-objs", "Allow companion objects and case classes in package objects. See issue SI-5954.") val YvirtClasses = false // too embryonic to even expose as a -Y //BooleanSetting ("-Yvirtual-classes", "Support virtual classes") val exposeEmptyPackage = BooleanSetting("-Yexpose-empty-package", "Internal only: expose the empty package.").internalOnly() diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 386eec207a..e3fd83f388 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -1891,7 +1891,33 @@ trait Typers extends Modes with Adaptations with Tags { }) } val impl2 = finishMethodSynthesis(impl1, clazz, context) + + // SI-5954. On second compile of a companion class contained in a package object we end up + // with some confusion of names which leads to having two symbols with the same name in the + // same owner. Until that can be straightened out we can't allow companion objects in package + // objects. But this code also tries to be friendly by distinguishing between case classes and + // user written companion pairs + def restrictPackageObjectMembers(mdef : ModuleDef) = for (m <- mdef.symbol.info.members) { + // ignore synthetic objects, because the "companion" object to a case class is synthetic and + // we only want one error per case class + if (!m.isSynthetic) { + // can't handle case classes in package objects + if (m.isCaseClass) pkgObjectRestriction(m, mdef, "case") + // can't handle companion class/object pairs in package objects + else if ((m.isClass && m.companionModule != NoSymbol && !m.companionModule.isSynthetic) || + (m.isModule && m.companionClass != NoSymbol && !m.companionClass.isSynthetic)) + pkgObjectRestriction(m, mdef, "companion") + } + + def pkgObjectRestriction(m : Symbol, mdef : ModuleDef, restricted : String) = { + val pkgName = mdef.symbol.ownerChain find (_.isPackage) map (_.decodedName) getOrElse mdef.symbol.toString + context.error(if (m.pos.isDefined) m.pos else mdef.pos, s"implementation restriction: package object ${pkgName} cannot contain ${restricted} ${m}. Instead, ${m} should be placed directly in package ${pkgName}.") + } + } + if (!settings.companionsInPkgObjs.value && mdef.symbol.isPackageObject) + restrictPackageObjectMembers(mdef) + treeCopy.ModuleDef(mdef, typedMods, mdef.name, impl2) setType NoType } /** In order to override this in the TreeCheckers Typer so synthetics aren't re-added diff --git a/src/reflect/scala/reflect/internal/settings/MutableSettings.scala b/src/reflect/scala/reflect/internal/settings/MutableSettings.scala index 81368df7a6..ec3501d5bc 100644 --- a/src/reflect/scala/reflect/internal/settings/MutableSettings.scala +++ b/src/reflect/scala/reflect/internal/settings/MutableSettings.scala @@ -47,4 +47,6 @@ abstract class MutableSettings extends AbsSettings { def XoldPatmat: BooleanSetting def XnoPatmatAnalysis: BooleanSetting def XfullLubs: BooleanSetting + def companionsInPkgObjs: BooleanSetting + } diff --git a/src/reflect/scala/reflect/runtime/Settings.scala b/src/reflect/scala/reflect/runtime/Settings.scala index 0e0cf3fc40..2d5b76f094 100644 --- a/src/reflect/scala/reflect/runtime/Settings.scala +++ b/src/reflect/scala/reflect/runtime/Settings.scala @@ -43,6 +43,7 @@ private[reflect] class Settings extends MutableSettings { val printtypes = new BooleanSetting(false) val uniqid = new BooleanSetting(false) val verbose = new BooleanSetting(false) + val companionsInPkgObjs = new BooleanSetting(false) val Yrecursion = new IntSetting(0) val maxClassfileName = new IntSetting(255) diff --git a/test/files/neg/t5954.check b/test/files/neg/t5954.check new file mode 100644 index 0000000000..3ca47cd430 --- /dev/null +++ b/test/files/neg/t5954.check @@ -0,0 +1,16 @@ +t5954.scala:36: error: implementation restriction: package object A cannot contain case class D. Instead, class D should be placed directly in package A. + case class D() + ^ +t5954.scala:35: error: implementation restriction: package object A cannot contain companion object C. Instead, object C should be placed directly in package A. + object C + ^ +t5954.scala:34: error: implementation restriction: package object A cannot contain companion trait C. Instead, trait C should be placed directly in package A. + trait C + ^ +t5954.scala:33: error: implementation restriction: package object A cannot contain companion object B. Instead, object B should be placed directly in package A. + object B + ^ +t5954.scala:32: error: implementation restriction: package object A cannot contain companion class B. Instead, class B should be placed directly in package A. + class B + ^ +5 errors found diff --git a/test/files/neg/t5954.scala b/test/files/neg/t5954.scala new file mode 100644 index 0000000000..9e6f5392c7 --- /dev/null +++ b/test/files/neg/t5954.scala @@ -0,0 +1,46 @@ +// if you ever think you've fixed the underlying reason for the implementation restrictions +// imposed by SI-5954, then here's a test that should pass with two "succes"es +// +//import scala.tools.partest._ +// +//object Test extends DirectTest { +// def code = ??? +// +// def problemCode = """ +// package object A { +// class B +// object B +// case class C() +// } +// """ +// +// def compileProblemCode() = { +// val classpath = List(sys.props("partest.lib"), testOutput.path) mkString sys.props("path.separator") +// compileString(newCompiler("-cp", classpath, "-d", testOutput.path))(problemCode) +// } +// +// def show() : Unit = { +// for (i <- 0 until 2) { +// compileProblemCode() +// println(s"success ${i + 1}") +// } +// } +//} + +package object A { + // these should be prevented by the implementation restriction + class B + object B + trait C + object C + case class D() + // all the rest of these should be ok + class E + object F + val g = "omg" + var h = "wtf" + def i = "lol" + type j = String + class K(val k : Int) extends AnyVal + implicit class L(val l : Int) +} diff --git a/test/files/pos/package-case.flags b/test/files/pos/package-case.flags new file mode 100644 index 0000000000..2f174c4732 --- /dev/null +++ b/test/files/pos/package-case.flags @@ -0,0 +1 @@ +-Ycompanions-in-pkg-objs diff --git a/test/files/pos/t2130-1.flags b/test/files/pos/t2130-1.flags new file mode 100644 index 0000000000..2f174c4732 --- /dev/null +++ b/test/files/pos/t2130-1.flags @@ -0,0 +1 @@ +-Ycompanions-in-pkg-objs diff --git a/test/files/pos/t2130-2.flags b/test/files/pos/t2130-2.flags new file mode 100644 index 0000000000..2f174c4732 --- /dev/null +++ b/test/files/pos/t2130-2.flags @@ -0,0 +1 @@ +-Ycompanions-in-pkg-objs diff --git a/test/files/pos/t3999b.flags b/test/files/pos/t3999b.flags new file mode 100644 index 0000000000..2f174c4732 --- /dev/null +++ b/test/files/pos/t3999b.flags @@ -0,0 +1 @@ +-Ycompanions-in-pkg-objs diff --git a/test/files/pos/t4052.flags b/test/files/pos/t4052.flags new file mode 100644 index 0000000000..2f174c4732 --- /dev/null +++ b/test/files/pos/t4052.flags @@ -0,0 +1 @@ +-Ycompanions-in-pkg-objs -- cgit v1.2.3 From 0c2e8842036876c6b824fbbb68fc7100ef62e02d Mon Sep 17 00:00:00 2001 From: James Iry Date: Mon, 14 Jan 2013 06:55:23 -0800 Subject: SI-6963 Deprecates -Xmigration switch -Xmigration is specific to the 2.7 to 2.8 upgrade and is no longer relevant. There is no plan to maintain it so it will be removed. This commit deprecates it in anticipation. --- src/compiler/scala/tools/nsc/settings/ScalaSettings.scala | 3 ++- test/files/neg/t6963.check | 2 ++ test/files/neg/t6963.flags | 1 + test/files/neg/t6963.scala | 3 +++ 4 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 test/files/neg/t6963.check create mode 100644 test/files/neg/t6963.flags create mode 100644 test/files/neg/t6963.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index cfc7f14210..b2aa0ec6a5 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala @@ -85,7 +85,8 @@ trait ScalaSettings extends AbsScalaSettings val logFreeTerms = BooleanSetting ("-Xlog-free-terms", "Print a message when reification creates a free term.") val logFreeTypes = BooleanSetting ("-Xlog-free-types", "Print a message when reification resorts to generating a free type.") val maxClassfileName = IntSetting ("-Xmax-classfile-name", "Maximum filename length for generated classes", 255, Some((72, 255)), _ => None) - val Xmigration28 = BooleanSetting ("-Xmigration", "Warn about constructs whose behavior may have changed between 2.7 and 2.8.") + val Xmigration28 = BooleanSetting ("-Xmigration", "Warn about constructs whose behavior may have changed between 2.7 and 2.8."). + withDeprecationMessage("This setting is no longer useful and will be removed. Please remove it from your build.") val nouescape = BooleanSetting ("-Xno-uescape", "Disable handling of \\u unicode escapes.") val Xnojline = BooleanSetting ("-Xnojline", "Do not use JLine for editing.") val Xverify = BooleanSetting ("-Xverify", "Verify generic signatures in generated bytecode (asm backend only.)") diff --git a/test/files/neg/t6963.check b/test/files/neg/t6963.check new file mode 100644 index 0000000000..41cb796b0b --- /dev/null +++ b/test/files/neg/t6963.check @@ -0,0 +1,2 @@ +error: -Xmigration is deprecated: This setting is no longer useful and will be removed. Please remove it from your build. +one error found diff --git a/test/files/neg/t6963.flags b/test/files/neg/t6963.flags new file mode 100644 index 0000000000..0b6d71496a --- /dev/null +++ b/test/files/neg/t6963.flags @@ -0,0 +1 @@ +-Xmigration -deprecation -Xfatal-warnings \ No newline at end of file diff --git a/test/files/neg/t6963.scala b/test/files/neg/t6963.scala new file mode 100644 index 0000000000..4da52764f5 --- /dev/null +++ b/test/files/neg/t6963.scala @@ -0,0 +1,3 @@ + +object test { +} -- cgit v1.2.3 From 692372ce1d82d0ba41461b9539fdc85238477464 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Sun, 13 Jan 2013 12:36:36 +0100 Subject: SI-6675 -Xlint arity enforcement for extractors Extractor Patterns changed in 2.10.0 to implement the letter of the spec, which allows a single binding to capture an entire TupleN. But this can hide arity mismatches, especially if the case body uses the bound value as an `Any`. This change warns when this happens under -Xlint. --- src/compiler/scala/tools/nsc/matching/Patterns.scala | 2 +- src/compiler/scala/tools/nsc/transform/UnCurry.scala | 2 +- src/compiler/scala/tools/nsc/typechecker/Infer.scala | 15 +++++++++++---- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 4 ++-- src/compiler/scala/tools/nsc/typechecker/Unapplies.scala | 4 ++-- test/files/neg/t6675.check | 4 ++++ test/files/neg/t6675.flags | 1 + test/files/neg/t6675.scala | 13 +++++++++++++ 8 files changed, 35 insertions(+), 10 deletions(-) create mode 100644 test/files/neg/t6675.check create mode 100644 test/files/neg/t6675.flags create mode 100644 test/files/neg/t6675.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala index 99b72fa26e..f116a7c4c7 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, args.length) + def resTypes = analyzer.unapplyTypeList(unfn.pos, 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 838ea7d5a0..ff08fe4ffa 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -613,7 +613,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.unapplyTypeList(fn.symbol, fn.tpe, args.length)) + case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeList(fn.pos, 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 0f52687c75..a3c0f10612 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -73,7 +73,7 @@ trait Infer extends Checkable { * 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]) = { + def extractorFormalTypes(pos: Position, resTp: Type, nbSubPats: Int, unappSym: Symbol): (List[Type], List[Type]) = { val isUnapplySeq = unappSym.name == nme.unapplySeq val booleanExtractor = resTp.typeSymbolDirect == BooleanClass @@ -87,11 +87,18 @@ trait Infer extends Checkable { if (nbSubPats == 0 && booleanExtractor && !isUnapplySeq) Nil else resTp.baseType(OptionClass).typeArgs match { case optionTArg :: Nil => - if (nbSubPats == 1) + def productArgs = getProductArgs(optionTArg) + if (nbSubPats == 1) { if (isUnapplySeq) List(seqToRepeatedChecked(optionTArg)) - else List(optionTArg) + else { + val productArity = productArgs.size + if (productArity > 1 && settings.lint.value) + global.currentUnit.warning(pos, s"extractor pattern binds a single value to a Product${productArity} of type ${optionTArg}") + List(optionTArg) + } + } // TODO: update spec to reflect we allow any ProductN, not just TupleN - else getProductArgs(optionTArg) match { + else productArgs match { case Nil if isUnapplySeq => List(seqToRepeatedChecked(optionTArg)) case tps if isUnapplySeq => tps.init :+ seqToRepeatedChecked(tps.last) case tps => tps diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 386eec207a..f2f02ba54e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -3465,7 +3465,7 @@ trait Typers extends Modes with Adaptations with Tags { val resTp = fun1.tpe.finalResultType.normalize val nbSubPats = args.length - val (formals, formalsExpanded) = extractorFormalTypes(resTp, nbSubPats, fun1.symbol) + val (formals, formalsExpanded) = extractorFormalTypes(fun0.pos, resTp, nbSubPats, fun1.symbol) if (formals == null) duplErrorTree(WrongNumberOfArgsError(tree, fun)) else { val args1 = typedArgs(args, mode, formals, formalsExpanded) @@ -5311,7 +5311,7 @@ trait Typers extends Modes with Adaptations with Tags { def typedUnApply(tree: UnApply) = { val fun1 = typed(tree.fun) - val tpes = formalTypes(unapplyTypeList(tree.fun.symbol, fun1.tpe, tree.args.length), tree.args.length) + val tpes = formalTypes(unapplyTypeList(tree.fun.pos, tree.fun.symbol, fun1.tpe, tree.args.length), tree.args.length) val args1 = map2(tree.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 a34d7389bf..5782d7bbca 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala @@ -34,12 +34,12 @@ trait Unapplies extends ast.TreeDSL /** returns type list for return type of the extraction * @see extractorFormalTypes */ - def unapplyTypeList(ufn: Symbol, ufntpe: Type, nbSubPats: Int) = { + def unapplyTypeList(pos: Position, ufn: Symbol, ufntpe: Type, nbSubPats: Int) = { assert(ufn.isMethod, ufn) //Console.println("utl "+ufntpe+" "+ufntpe.typeSymbol) ufn.name match { case nme.unapply | nme.unapplySeq => - val (formals, _) = extractorFormalTypes(unapplyUnwrap(ufntpe), nbSubPats, ufn) + val (formals, _) = extractorFormalTypes(pos, 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/test/files/neg/t6675.check b/test/files/neg/t6675.check new file mode 100644 index 0000000000..7b271de213 --- /dev/null +++ b/test/files/neg/t6675.check @@ -0,0 +1,4 @@ +t6675.scala:10: error: extractor pattern binds a single value to a Product3 of type (Int, Int, Int) + "" match { case X(b) => b } // should warn under -Xlint. Not an error because of SI-6111 + ^ +one error found diff --git a/test/files/neg/t6675.flags b/test/files/neg/t6675.flags new file mode 100644 index 0000000000..e93641e931 --- /dev/null +++ b/test/files/neg/t6675.flags @@ -0,0 +1 @@ +-Xlint -Xfatal-warnings \ No newline at end of file diff --git a/test/files/neg/t6675.scala b/test/files/neg/t6675.scala new file mode 100644 index 0000000000..4d500b77ba --- /dev/null +++ b/test/files/neg/t6675.scala @@ -0,0 +1,13 @@ +object X { + def unapply(s: String): Option[(Int,Int,Int)] = Some((1,2,3)) +} + +object Y { + def unapplySeq(s: String): Option[Seq[(Int,Int,Int)]] = Some(Seq((1,2,3))) +} + +object Test { + "" match { case X(b) => b } // should warn under -Xlint. Not an error because of SI-6111 + + "" match { case Y(b) => b } // no warning +} -- cgit v1.2.3