From 5a8b937510094d4e92f37dba113c231ec2e69705 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Thu, 14 Jun 2012 17:08:11 -0700 Subject: Fix for java parser edge case. Empty statements are A-OK. Closes SI-5910. Review by @dragos. --- test/files/pos/t5910.java | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 test/files/pos/t5910.java (limited to 'test/files/pos') diff --git a/test/files/pos/t5910.java b/test/files/pos/t5910.java new file mode 100644 index 0000000000..e007a1fbb5 --- /dev/null +++ b/test/files/pos/t5910.java @@ -0,0 +1,2 @@ +class Foo { +};;;;;;; \ No newline at end of file -- cgit v1.2.3 From 6aa5762fa0333625ec93378e2147649a8bafde34 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Sun, 17 Jun 2012 23:23:49 +0200 Subject: SI-4842 Forbid access to in-construction this in self-constructor args The check was already in place for direct calls to the super constructor. Without this additional check, ExplicitOuter crashes, as it doesn't create an $outer pointer for the constructor-arg scoped inner object, but expects one to exist when transforming the Outer.this reference. --- .../tools/nsc/typechecker/ContextErrors.scala | 8 ++- .../scala/tools/nsc/typechecker/Typers.scala | 62 ++++++++++++++++------ test/files/neg/t4842a.check | 4 ++ test/files/neg/t4842a.scala | 3 ++ test/files/neg/t4842b.check | 4 ++ test/files/neg/t4842b.scala | 3 ++ test/files/pos/t4842.scala | 26 +++++++++ 7 files changed, 94 insertions(+), 16 deletions(-) create mode 100644 test/files/neg/t4842a.check create mode 100644 test/files/neg/t4842a.scala create mode 100644 test/files/neg/t4842b.check create mode 100644 test/files/neg/t4842b.scala create mode 100644 test/files/pos/t4842.scala (limited to 'test/files/pos') diff --git a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala index bcf2ba6b71..fcb73f5947 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala @@ -222,7 +222,13 @@ trait ContextErrors { NormalTypeError(tree, "super constructor cannot be passed a self reference unless parameter is declared by-name") def SuperConstrArgsThisReferenceError(tree: Tree) = - NormalTypeError(tree, "super constructor arguments cannot reference unconstructed `this`") + ConstrArgsThisReferenceError("super", tree) + + def SelfConstrArgsThisReferenceError(tree: Tree) = + ConstrArgsThisReferenceError("self", tree) + + private def ConstrArgsThisReferenceError(prefix: String, tree: Tree) = + NormalTypeError(tree, s"$prefix constructor arguments cannot reference unconstructed `this`") def TooManyArgumentListsForConstructor(tree: Tree) = { issueNormalTypeError(tree, "too many argument lists for constructor invocation") diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 2bdae4164a..b58a7832ac 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -1841,16 +1841,13 @@ trait Typers extends Modes with Adaptations with Tags { val pending = ListBuffer[AbsTypeError]() // an object cannot be allowed to pass a reference to itself to a superconstructor // because of initialization issues; bug #473 - for (arg <- superArgs ; tree <- arg) { - val sym = tree.symbol - if (sym != null && (sym.info.baseClasses contains clazz)) { - if (sym.isModule) - pending += SuperConstrReferenceError(tree) - tree match { - case This(qual) => - pending += SuperConstrArgsThisReferenceError(tree) - case _ => () - } + foreachSubTreeBoundTo(superArgs, clazz) { tree => + if (tree.symbol.isModule) + pending += SuperConstrReferenceError(tree) + tree match { + case This(qual) => + pending += SuperConstrArgsThisReferenceError(tree) + case _ => () } } @@ -1884,7 +1881,39 @@ trait Typers extends Modes with Adaptations with Tags { pending.foreach(ErrorUtils.issueTypeError) } - /** Check if a structurally defined method violates implementation restrictions. + // Check for SI-4842. + private def checkSelfConstructorArgs(ddef: DefDef, clazz: Symbol) { + val pending = ListBuffer[AbsTypeError]() + ddef.rhs match { + case Block(stats, expr) => + val selfConstructorCall = stats.headOption.getOrElse(expr) + foreachSubTreeBoundTo(List(selfConstructorCall), clazz) { + case tree @ This(qual) => + pending += SelfConstrArgsThisReferenceError(tree) + case _ => () + } + case _ => + } + pending.foreach(ErrorUtils.issueTypeError) + } + + /** + * Run the provided function for each sub tree of `trees` that + * are bound to a symbol with `clazz` as a base class. + * + * @param f This function can assume that `tree.symbol` is non null + */ + private def foreachSubTreeBoundTo[A](trees: List[Tree], clazz: Symbol)(f: Tree => Unit): Unit = + for { + tree <- trees + subTree <- tree + } { + val sym = subTree.symbol + if (sym != null && sym.info.baseClasses.contains(clazz)) + f(subTree) + } + + /** Check if a structurally defined method violates implementation restrictions. * A method cannot be called if it is a non-private member of a refinement type * and if its parameter's types are any of: * - the self-type of the refinement @@ -2002,11 +2031,14 @@ trait Typers extends Modes with Adaptations with Tags { transformedOrTyped(ddef.rhs, EXPRmode, tpt1.tpe) } - if (meth.isPrimaryConstructor && meth.isClassConstructor && !isPastTyper && !reporter.hasErrors && !meth.owner.isSubClass(AnyValClass)) { - // At this point in AnyVal there is no supercall, which will blow up - // in computeParamAliases; there's nothing to be computed for Anyval anyway. + if (meth.isClassConstructor && !isPastTyper && !reporter.hasErrors && !meth.owner.isSubClass(AnyValClass)) { + // At this point in AnyVal there is no supercall, which will blow up + // in computeParamAliases; there's nothing to be computed for Anyval anyway. + if (meth.isPrimaryConstructor) computeParamAliases(meth.owner, vparamss1, rhs1) - } + else + checkSelfConstructorArgs(ddef, meth.owner) + } if (tpt1.tpe.typeSymbol != NothingClass && !context.returnsSeen && rhs1.tpe.typeSymbol != NothingClass) rhs1 = checkDead(rhs1) diff --git a/test/files/neg/t4842a.check b/test/files/neg/t4842a.check new file mode 100644 index 0000000000..39d77bfc48 --- /dev/null +++ b/test/files/neg/t4842a.check @@ -0,0 +1,4 @@ +t4842a.scala:2: error: self constructor arguments cannot reference unconstructed `this` + def this(x: Int) = this(new { println(Foo.this)}) // error + ^ +one error found diff --git a/test/files/neg/t4842a.scala b/test/files/neg/t4842a.scala new file mode 100644 index 0000000000..78360effb4 --- /dev/null +++ b/test/files/neg/t4842a.scala @@ -0,0 +1,3 @@ +class Foo (x: AnyRef) { + def this(x: Int) = this(new { println(Foo.this)}) // error +} diff --git a/test/files/neg/t4842b.check b/test/files/neg/t4842b.check new file mode 100644 index 0000000000..c7ccd5e059 --- /dev/null +++ b/test/files/neg/t4842b.check @@ -0,0 +1,4 @@ +t4842b.scala:2: error: self constructor arguments cannot reference unconstructed `this` + def this() = { this(???)(new { println(TypeArg.this.x) } ); println("next") } // error + ^ +one error found diff --git a/test/files/neg/t4842b.scala b/test/files/neg/t4842b.scala new file mode 100644 index 0000000000..a7996cc061 --- /dev/null +++ b/test/files/neg/t4842b.scala @@ -0,0 +1,3 @@ +class TypeArg[X](val x: X)(a: AnyRef) { + def this() = { this(???)(new { println(TypeArg.this.x) } ); println("next") } // error +} diff --git a/test/files/pos/t4842.scala b/test/files/pos/t4842.scala new file mode 100644 index 0000000000..17ff684833 --- /dev/null +++ b/test/files/pos/t4842.scala @@ -0,0 +1,26 @@ +class Foo (x: AnyRef) { + def this() = { + this(new { } ) // okay + } +} + + +class Blerg (x: AnyRef) { + def this() = { + this(new { class Bar { println(Bar.this); new { println(Bar.this) } }; new Bar } ) // okay + } +} + + +class Outer { + class Inner (x: AnyRef) { + def this() = { + this(new { class Bar { println(Bar.this); new { println(Bar.this) } }; new Bar } ) // okay + } + + def this(x: Boolean) = { + this(new { println(Outer.this) } ) // okay + } + } +} + -- cgit v1.2.3 From 47fad25adba895e8b27aee479373ea364dd316dd Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 19 Jun 2012 09:45:49 -0700 Subject: Fix for SI-5953, extension methods crasher. As usual, .tpe -> .tpeHK. As a side note following an old theme, if symbols of type parameters knew that they were symbols of type parameters, they could call tpeHK themselves rather than every call site having to do it. It's the operation which injects dummies which should require explicit programmer action, not the operation which faithfully reproduces the unapplied type. Were it that way, errors could be caught much more quickly via ill-kindedness. Seems like an improvement over lurking compiler crashes at every call to tparam.tpe. --- .../scala/tools/nsc/transform/ExtensionMethods.scala | 4 ++-- test/files/pos/t5953.scala | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 test/files/pos/t5953.scala (limited to 'test/files/pos') diff --git a/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala b/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala index 1c97eaad8b..5f66cadbc9 100644 --- a/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala +++ b/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala @@ -107,7 +107,7 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { def extensionMethInfo(extensionMeth: Symbol, origInfo: Type, clazz: Symbol): Type = { var newTypeParams = cloneSymbolsAtOwner(clazz.typeParams, extensionMeth) - val thisParamType = appliedType(clazz.typeConstructor, newTypeParams map (_.tpe)) + val thisParamType = appliedType(clazz.typeConstructor, newTypeParams map (_.tpeHK)) val thisParam = extensionMeth.newValueParameter(nme.SELF, extensionMeth.pos) setInfo thisParamType def transform(clonedType: Type): Type = clonedType match { case MethodType(params, restpe) => @@ -159,7 +159,7 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { .changeOwner((origMeth, extensionMeth)) extensionDefs(companion) += atPos(tree.pos) { DefDef(extensionMeth, extensionBody) } val extensionCallPrefix = Apply( - gen.mkTypeApply(gen.mkAttributedRef(companion), extensionMeth, origTpeParams map (_.tpe)), + gen.mkTypeApply(gen.mkAttributedRef(companion), extensionMeth, origTpeParams map (_.tpeHK)), List(This(currentOwner))) val extensionCall = atOwner(origMeth) { localTyper.typedPos(rhs.pos) { diff --git a/test/files/pos/t5953.scala b/test/files/pos/t5953.scala new file mode 100644 index 0000000000..90e7d84646 --- /dev/null +++ b/test/files/pos/t5953.scala @@ -0,0 +1,16 @@ +import scala.collection.{ mutable, immutable, generic, GenTraversableOnce } + +package object foo { + @inline implicit class TravOps[A, CC[A] <: GenTraversableOnce[A]](val coll: CC[A]) extends AnyVal { + def build[CC2[X]](implicit cbf: generic.CanBuildFrom[Nothing, A, CC2[A]]): CC2[A] = { + cbf() ++= coll.toIterator result + } + } +} + +package foo { + object Test { + def f1[T](xs: Traversable[T]) = xs.convertTo[immutable.Vector] + def f2[T](xs: Traversable[T]) = xs.build[immutable.Vector] + } +} -- cgit v1.2.3 From b29c01b710b67dd329ad418c7d5ef4e61845c6d1 Mon Sep 17 00:00:00 2001 From: Aleksandar Prokopec Date: Tue, 19 Jun 2012 19:54:02 +0200 Subject: Fix SI-5284. The problem was the false assumption that methods specialized on their type parameter, such as this one: class Foo[@spec(Int) T](val x: T) { def bar[@spec(Int) S >: T](f: S => S) = f(x) } have their normalized versions (`bar$mIc$sp`) never called from the base specialization class `Foo`. This meant that the implementation of `bar$mIc$sp` in `Foo` simply threw an exception. This assumption is not true, however. See this: object Baz { def apply[T]() = new Foo[T] } Calling `Baz.apply[Int]()` will create an instance of the base specialization class `Foo` at `Int`. Calling `bar` on this instance will be rewritten by specialization to calling `bar$mIc$sp`, hence the error. So, we have to emit a valid implementation for `bar`, obviously. Problem is, such an implementation would have conflicting type bounds in the base specialization class `Foo`, since we don't know if `T` is a subtype of `S = Int`. In other words, we cannot emit: def bar$mIc$sp(f: Int => Int) = f(x) // x: T without typechecking errors. However, notice that the bounds are valid if and only if `T = Int`. In the same time, invocations of `bar$mIc$sp` will only be emitted in callsites where the type bounds hold. This means we can cast the expressions in method applications to the required specialized type bound. The following changes have been made: 1) The decision of whether or not to create a normalized version of the specialized method is not done on the `conflicting` relation anymore. Instead, it's done based on the `satisfiable` relation, which is true if there is possibly an instantiation of the type parameters where the bounds hold. 2) The `satisfiable` method has a new variant called `satisfiableConstraints`, which does unification to figure out how the type parameters should be instantiated in order to satisfy the bounds. 3) The `Duplicators` are changed to transform a tree using the `castType` method which just returns the tree by default. In specialization, the `castType` in `Duplicators` is overridden, and uses a map from type parameters to types. This map is obtained by `satisfiableConstraints` from 2). If the type of the expression is not equal to the expected type, and this map contains a mapping to the expected type, then the tree is cast, as discussed above. Additional tests added. Review by @dragos Review by @VladUreche Conflicts: src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala src/compiler/scala/tools/nsc/typechecker/Duplicators.scala --- .../scala/tools/nsc/transform/Constructors.scala | 2 +- .../tools/nsc/transform/SpecializeTypes.scala | 85 ++++++++++++++++++---- .../scala/tools/nsc/typechecker/Duplicators.scala | 31 +++++--- test/files/pos/spec-params-new.scala | 2 +- test/files/run/t5284.check | 1 + test/files/run/t5284.scala | 25 +++++++ test/files/run/t5284b.check | 1 + test/files/run/t5284b.scala | 28 +++++++ test/files/run/t5284c.check | 1 + test/files/run/t5284c.scala | 30 ++++++++ 10 files changed, 180 insertions(+), 26 deletions(-) create mode 100644 test/files/run/t5284.check create mode 100644 test/files/run/t5284.scala create mode 100644 test/files/run/t5284b.check create mode 100644 test/files/run/t5284b.scala create mode 100644 test/files/run/t5284c.check create mode 100644 test/files/run/t5284c.scala (limited to 'test/files/pos') diff --git a/src/compiler/scala/tools/nsc/transform/Constructors.scala b/src/compiler/scala/tools/nsc/transform/Constructors.scala index bc4483923a..e5119eac71 100644 --- a/src/compiler/scala/tools/nsc/transform/Constructors.scala +++ b/src/compiler/scala/tools/nsc/transform/Constructors.scala @@ -323,7 +323,7 @@ abstract class Constructors extends Transform with ast.TreeDSL { // statements coming from the original class need retyping in the current context debuglog("retyping " + stat2) - val d = new specializeTypes.Duplicator + val d = new specializeTypes.Duplicator(Map[Symbol, Type]()) d.retyped(localTyper.context1.asInstanceOf[d.Context], stat2, genericClazz, diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala index c4c769d7cf..1d820afe11 100644 --- a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala +++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala @@ -450,7 +450,12 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { /** Type parameters that survive when specializing in the specified environment. */ def survivingParams(params: List[Symbol], env: TypeEnv) = - params.filter(p => !p.isSpecialized || !isPrimitiveValueType(env(p))) + params filter { + p => + !p.isSpecialized || + !env.contains(p) || + !isPrimitiveValueType(env(p)) + } /** Produces the symbols from type parameters `syms` of the original owner, * in the given type environment `env`. The new owner is `nowner`. @@ -1176,7 +1181,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { || specializedTypeVars(t1).nonEmpty || specializedTypeVars(t2).nonEmpty) } - + env forall { case (tvar, tpe) => matches(tvar.info.bounds.lo, tpe) && matches(tpe, tvar.info.bounds.hi) || { if (warnings) @@ -1192,10 +1197,58 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { } } } + + def satisfiabilityConstraints(env: TypeEnv): Option[TypeEnv] = { + val noconstraints = Some(emptyEnv) + def matches(tpe1: Type, tpe2: Type): Option[TypeEnv] = { + val t1 = subst(env, tpe1) + val t2 = subst(env, tpe2) + // log("---------> " + tpe1 + " matches " + tpe2) + // log(t1 + ", " + specializedTypeVars(t1)) + // log(t2 + ", " + specializedTypeVars(t2)) + // log("unify: " + unify(t1, t2, env, false, false) + " in " + env) + if (t1 <:< t2) noconstraints + else if (specializedTypeVars(t1).nonEmpty) Some(unify(t1, t2, env, false, false) -- env.keys) + else if (specializedTypeVars(t2).nonEmpty) Some(unify(t2, t1, env, false, false) -- env.keys) + else None + } + + env.foldLeft[Option[TypeEnv]](noconstraints) { + case (constraints, (tvar, tpe)) => + val loconstraints = matches(tvar.info.bounds.lo, tpe) + val hiconstraints = matches(tpe, tvar.info.bounds.hi) + val allconstraints = for (c <- constraints; l <- loconstraints; h <- hiconstraints) yield c ++ l ++ h + allconstraints + } + } - class Duplicator extends { + /** This duplicator additionally performs casts of expressions if that is allowed by the `casts` map. */ + class Duplicator(casts: Map[Symbol, Type]) extends { val global: SpecializeTypes.this.global.type = SpecializeTypes.this.global - } with typechecker.Duplicators + } with typechecker.Duplicators { + private val (castfrom, castto) = casts.unzip + private object CastMap extends SubstTypeMap(castfrom.toList, castto.toList) + + class BodyDuplicator(_context: Context) extends super.BodyDuplicator(_context) { + override def castType(tree: Tree, pt: Type): Tree = { + // log(" expected type: " + pt) + // log(" tree type: " + tree.tpe) + tree.tpe = if (tree.tpe != null) fixType(tree.tpe) else null + // log(" tree type: " + tree.tpe) + val ntree = if (tree.tpe != null && !(tree.tpe <:< pt)) { + val casttpe = CastMap(tree.tpe) + if (casttpe <:< pt) gen.mkCast(tree, casttpe) + else if (casttpe <:< CastMap(pt)) gen.mkCast(tree, pt) + else tree + } else tree + ntree.tpe = null + ntree + } + } + + protected override def newBodyDuplicator(context: Context) = new BodyDuplicator(context) + + } /** A tree symbol substituter that substitutes on type skolems. * If a type parameter is a skolem, it looks for the original @@ -1475,14 +1528,14 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { deriveDefDef(tree1)(transform) case NormalizedMember(target) => - debuglog("Normalized member: " + symbol + ", target: " + target) - if (target.isDeferred || conflicting(typeEnv(symbol))) { + val constraints = satisfiabilityConstraints(typeEnv(symbol)) + log("constraints: " + constraints) + if (target.isDeferred || constraints == None) { deriveDefDef(tree)(_ => localTyper typed gen.mkSysErrorCall("Fatal error in code generation: this should never be called.")) - } - else { + } else { // we have an rhs, specialize it val tree1 = reportTypeError { - duplicateBody(ddef, target) + duplicateBody(ddef, target, constraints.get) } debuglog("implementation: " + tree1) deriveDefDef(tree1)(transform) @@ -1546,7 +1599,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { val tree1 = deriveValDef(tree)(_ => body(symbol.alias).duplicate) debuglog("now typing: " + tree1 + " in " + tree.symbol.owner.fullName) - val d = new Duplicator + val d = new Duplicator(emptyEnv) val newValDef = d.retyped( localTyper.context1.asInstanceOf[d.Context], tree1, @@ -1571,12 +1624,18 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { super.transform(tree) } } - - private def duplicateBody(tree: DefDef, source: Symbol) = { + + /** Duplicate the body of the given method `tree` to the new symbol `source`. + * + * Knowing that the method can be invoked only in the `castmap` type environment, + * this method will insert casts for all the expressions of types mappend in the + * `castmap`. + */ + private def duplicateBody(tree: DefDef, source: Symbol, castmap: TypeEnv = emptyEnv) = { val symbol = tree.symbol val meth = addBody(tree, source) - val d = new Duplicator + val d = new Duplicator(castmap) debuglog("-->d DUPLICATING: " + meth) d.retyped( localTyper.context1.asInstanceOf[d.Context], diff --git a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala index 6386273c9d..63d1bd0e9f 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala @@ -21,7 +21,7 @@ abstract class Duplicators extends Analyzer { def retyped(context: Context, tree: Tree): Tree = { resetClassOwners - (new BodyDuplicator(context)).typed(tree) + (newBodyDuplicator(context)).typed(tree) } /** Retype the given tree in the given context. Use this method when retyping @@ -37,15 +37,17 @@ abstract class Duplicators extends Analyzer { envSubstitution = new SubstSkolemsTypeMap(env.keysIterator.toList, env.valuesIterator.toList) debuglog("retyped with env: " + env) - (new BodyDuplicator(context)).typed(tree) + newBodyDuplicator(context).typed(tree) } + protected def newBodyDuplicator(context: Context) = new BodyDuplicator(context) + def retypedMethod(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol): Tree = - (new BodyDuplicator(context)).retypedMethod(tree.asInstanceOf[DefDef], oldThis, newThis) + (newBodyDuplicator(context)).retypedMethod(tree.asInstanceOf[DefDef], oldThis, newThis) /** Return the special typer for duplicate method bodies. */ override def newTyper(context: Context): Typer = - new BodyDuplicator(context) + newBodyDuplicator(context) private def resetClassOwners() { oldClassOwner = null @@ -209,6 +211,11 @@ abstract class Duplicators extends Analyzer { } } + /** Optionally cast this tree into some other type, if required. + * Unless overridden, just returns the tree. + */ + def castType(tree: Tree, pt: Type): Tree = tree + /** Special typer method for re-type checking trees. It expects a typed tree. * Returns a typed tree that has fresh symbols for all definitions in the original tree. * @@ -319,10 +326,10 @@ abstract class Duplicators extends Analyzer { super.typed(atPos(tree.pos)(tree1), mode, pt) case This(_) => - // log("selection on this, plain: " + tree) + debuglog("selection on this, plain: " + tree) tree.symbol = updateSym(tree.symbol) - tree.tpe = null - val tree1 = super.typed(tree, mode, pt) + val ntree = castType(tree, pt) + val tree1 = super.typed(ntree, mode, pt) // log("plain this typed to: " + tree1) tree1 /* no longer needed, because Super now contains a This(...) @@ -358,16 +365,18 @@ abstract class Duplicators extends Analyzer { case EmptyTree => // no need to do anything, in particular, don't set the type to null, EmptyTree.tpe_= asserts tree - + case _ => - // log("Duplicators default case: " + tree.summaryString + " -> " + tree) + debuglog("Duplicators default case: " + tree.summaryString) + debuglog(" ---> " + tree) if (tree.hasSymbol && tree.symbol != NoSymbol && (tree.symbol.owner == definitions.AnyClass)) { tree.symbol = NoSymbol // maybe we can find a more specific member in a subclass of Any (see AnyVal members, like ==) } - tree.tpe = null - super.typed(tree, mode, pt) + val ntree = castType(tree, pt) + super.typed(ntree, mode, pt) } } + } } diff --git a/test/files/pos/spec-params-new.scala b/test/files/pos/spec-params-new.scala index 661e686f0e..959ce1591c 100644 --- a/test/files/pos/spec-params-new.scala +++ b/test/files/pos/spec-params-new.scala @@ -31,4 +31,4 @@ class Foo[@specialized A: ClassTag] { val xs = new Array[A](1) xs(0) = x } -} \ No newline at end of file +} diff --git a/test/files/run/t5284.check b/test/files/run/t5284.check new file mode 100644 index 0000000000..0cfbf08886 --- /dev/null +++ b/test/files/run/t5284.check @@ -0,0 +1 @@ +2 diff --git a/test/files/run/t5284.scala b/test/files/run/t5284.scala new file mode 100644 index 0000000000..ba0845fb8e --- /dev/null +++ b/test/files/run/t5284.scala @@ -0,0 +1,25 @@ + + + + + +/** Here we have a situation where a normalized method parameter `W` + * is used in a position which accepts an instance of type `T` - we know we can + * safely cast `T` to `W` whenever type bounds on `W` hold. + */ +object Test { + def main(args: Array[String]) { + val a = Blarg(Array(1, 2, 3)) + println(a.m((x: Int) => x + 1)) + } +} + + +object Blarg { + def apply[T: Manifest](a: Array[T]) = new Blarg(a) +} + + +class Blarg[@specialized(Int) T: Manifest](val a: Array[T]) { + def m[@specialized(Int) W >: T, @specialized(Int) S](f: W => S) = f(a(0)) +} diff --git a/test/files/run/t5284b.check b/test/files/run/t5284b.check new file mode 100644 index 0000000000..98d9bcb75a --- /dev/null +++ b/test/files/run/t5284b.check @@ -0,0 +1 @@ +17 diff --git a/test/files/run/t5284b.scala b/test/files/run/t5284b.scala new file mode 100644 index 0000000000..a9282a895f --- /dev/null +++ b/test/files/run/t5284b.scala @@ -0,0 +1,28 @@ + + + + + + +/** Here we have a situation where a normalized method parameter `W` + * is used in a position which expects a type `T` - we know we can + * safely cast `W` to `T` whenever typebounds of `W` hold. + */ +object Test { + def main(args: Array[String]) { + val foo = Foo.createUnspecialized[Int] + println(foo.bar(17)) + } +} + + +object Foo { + def createUnspecialized[T] = new Foo[T] +} + + +class Foo[@specialized(Int) T] { + val id: T => T = x => x + + def bar[@specialized(Int) W <: T, @specialized(Int) S](w: W) = id(w) +} diff --git a/test/files/run/t5284c.check b/test/files/run/t5284c.check new file mode 100644 index 0000000000..00750edc07 --- /dev/null +++ b/test/files/run/t5284c.check @@ -0,0 +1 @@ +3 diff --git a/test/files/run/t5284c.scala b/test/files/run/t5284c.scala new file mode 100644 index 0000000000..383b84c2cc --- /dev/null +++ b/test/files/run/t5284c.scala @@ -0,0 +1,30 @@ + + + + + + +/** Here we have a compound type `List[W]` used in + * a position where `List[T]` is expected. The cast + * emitted in the normalized `bar` is safe because the + * normalized `bar` can only be called if the type + * bounds hold. + */ +object Test { + def main(args: Array[String]) { + val foo = Foo.createUnspecialized[Int] + println(foo.bar(List(1, 2, 3))) + } +} + + +object Foo { + def createUnspecialized[T] = new Foo[T] +} + + +class Foo[@specialized(Int) T] { + val len: List[T] => Int = xs => xs.length + + def bar[@specialized(Int) W <: T](ws: List[W]) = len(ws) +} -- cgit v1.2.3 From c27e5f0d60c853868b3676f1449e42dd351b0644 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Sat, 23 Jun 2012 22:38:23 +0200 Subject: SI-5968 Eliminate spurious exhaustiveness warning with singleton types. A singleton type is a type ripe for enumeration. --- src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala | 2 ++ test/files/pos/t5968.flags | 1 + test/files/pos/t5968.scala | 8 ++++++++ 3 files changed, 11 insertions(+) create mode 100644 test/files/pos/t5968.flags create mode 100644 test/files/pos/t5968.scala (limited to 'test/files/pos') diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 9b8ddffb49..f99d0e733b 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -2362,6 +2362,8 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // patmatDebug("enum bool "+ tp) Some(List(ConstantType(Constant(true)), ConstantType(Constant(false)))) // TODO case _ if tp.isTupleType => // recurse into component types + case modSym: ModuleClassSymbol => + Some(List(tp)) case sym if !sym.isSealed || isPrimitiveValueClass(sym) => // patmatDebug("enum unsealed "+ (tp, sym, sym.isSealed, isPrimitiveValueClass(sym))) None diff --git a/test/files/pos/t5968.flags b/test/files/pos/t5968.flags new file mode 100644 index 0000000000..e8fb65d50c --- /dev/null +++ b/test/files/pos/t5968.flags @@ -0,0 +1 @@ +-Xfatal-warnings \ No newline at end of file diff --git a/test/files/pos/t5968.scala b/test/files/pos/t5968.scala new file mode 100644 index 0000000000..0093f84fc0 --- /dev/null +++ b/test/files/pos/t5968.scala @@ -0,0 +1,8 @@ +object X { + def f(e: Either[Int, X.type]) = e match { + case Left(i) => i + case Right(X) => 0 + // SI-5986 spurious exhaustivity warning here + } +} + -- cgit v1.2.3 From b7888cc356094138fa79e45bf101be4a893bfd50 Mon Sep 17 00:00:00 2001 From: Hubert Plociniczak Date: Tue, 26 Jun 2012 18:24:51 +0200 Subject: Fix range positions when applying anonymous classes. Review by @dragos or @odersky --- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 2 +- test/files/pos/rangepos-anonapply.flags | 1 + test/files/pos/rangepos-anonapply.scala | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 test/files/pos/rangepos-anonapply.flags create mode 100644 test/files/pos/rangepos-anonapply.scala (limited to 'test/files/pos') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index acf1b3dc59..35127a7571 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -4978,7 +4978,7 @@ trait Typers extends Modes with Adaptations with Tags { typedTypeApply(tree, mode, fun1, args1) case Apply(Block(stats, expr), args) => - typed1(atPos(tree.pos)(Block(stats, Apply(expr, args))), mode, pt) + typed1(atPos(tree.pos)(Block(stats, Apply(expr, args) setPos tree.pos.makeTransparent)), mode, pt) case Apply(fun, args) => typedApply(fun, args) match { diff --git a/test/files/pos/rangepos-anonapply.flags b/test/files/pos/rangepos-anonapply.flags new file mode 100644 index 0000000000..281f0a10cd --- /dev/null +++ b/test/files/pos/rangepos-anonapply.flags @@ -0,0 +1 @@ +-Yrangepos diff --git a/test/files/pos/rangepos-anonapply.scala b/test/files/pos/rangepos-anonapply.scala new file mode 100644 index 0000000000..2f3e4ad6cd --- /dev/null +++ b/test/files/pos/rangepos-anonapply.scala @@ -0,0 +1,9 @@ +class Test { + trait PropTraverser { + def apply(x: Int): Unit = {} + } + + def gather(x: Int) { + (new PropTraverser {})(x) + } +} -- cgit v1.2.3 From 966c9bbebec78b90a79f72c73b55d9de6db34798 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Tue, 26 Jun 2012 11:05:25 +0200 Subject: SI-5899 exhaustiveness for non-class types --- .../tools/nsc/typechecker/PatternMatching.scala | 22 +++++++++++++++++----- test/files/pos/t5899.flags | 1 + test/files/pos/t5899.scala | 19 +++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 test/files/pos/t5899.flags create mode 100644 test/files/pos/t5899.scala (limited to 'test/files/pos') diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 2ee3570905..c466206192 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -2153,6 +2153,21 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // the equals inherited from AnyRef does just this } + // find most precise super-type of tp that is a class + // we skip non-class types (singleton types, abstract types) so that we can + // correctly compute how types relate in terms of the values they rule out + // e.g., when we know some value must be of type T, can it still be of type S? (this is the positive formulation of what `excludes` on Const computes) + // since we're talking values, there must have been a class involved in creating it, so rephrase our types in terms of classes + // (At least conceptually: `true` is an instance of class `Boolean`) + private def widenToClass(tp: Type) = { + // getOrElse to err on the safe side -- all BTS should end in Any, right? + val wideTp = tp.widen + val clsTp = + if (wideTp.typeSymbol.isClass) wideTp + else wideTp.baseTypeSeq.toList.find(_.typeSymbol.isClass).getOrElse(AnyClass.tpe) + // patmatDebug("Widening to class: "+ (tp, clsTp, tp.widen, tp.widen.baseTypeSeq, tp.widen.baseTypeSeq.toList.find(_.typeSymbol.isClass))) + clsTp + } object TypeConst { def apply(tp: Type) = { @@ -2168,7 +2183,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL assert(!(tp =:= NullTp)) private[this] val id: Int = Const.nextTypeId - val wideTp = tp.widen + val wideTp = widenToClass(tp) override def toString = tp.toString //+"#"+ id } @@ -2187,10 +2202,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL val tp = p.tpe.normalize if (tp =:= NullTp) NullConst else { - val wideTp = { - if (p.hasSymbol && p.symbol.isStable) tp.asSeenFrom(tp.prefix, p.symbol.owner).widen - else tp.widen - } + val wideTp = widenToClass(tp) val narrowTp = if (tp.isInstanceOf[SingletonType]) tp diff --git a/test/files/pos/t5899.flags b/test/files/pos/t5899.flags new file mode 100644 index 0000000000..e8fb65d50c --- /dev/null +++ b/test/files/pos/t5899.flags @@ -0,0 +1 @@ +-Xfatal-warnings \ No newline at end of file diff --git a/test/files/pos/t5899.scala b/test/files/pos/t5899.scala new file mode 100644 index 0000000000..b16f1f84fe --- /dev/null +++ b/test/files/pos/t5899.scala @@ -0,0 +1,19 @@ +import scala.tools.nsc._ + +trait Foo { + val global: Global + import global.{Name, Symbol, nme} + + case class Bippy(name: Name) + + def f(x: Bippy, sym: Symbol): Int = { + // no warning (!) for + // val Stable = sym.name.toTermName + + val Stable = sym.name + Bippy(Stable) match { + case Bippy(nme.WILDCARD) => 1 + case Bippy(Stable) => 2 // should not be considered unreachable + } + } +} \ No newline at end of file -- cgit v1.2.3