Skip to content

Fix #5494: Spurious unchecked warning when type testing an alias #8808

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Apr 29, 2020
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions compiler/src/dotty/tools/dotc/ast/Trees.scala
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ object Trees {
type ThisTree[-T >: Untyped] = If[T]
def isInline = false
}
class InlineIf[T >: Untyped] private[ast] (cond: Tree[T], thenp: Tree[T], elsep: Tree[T])(implicit @constructorOnly src: SourceFile)
class InlineIf[-T >: Untyped] private[ast] (cond: Tree[T], thenp: Tree[T], elsep: Tree[T])(implicit @constructorOnly src: SourceFile)
extends If(cond, thenp, elsep) {
override def isInline = true
override def toString = s"InlineIf($cond, $thenp, $elsep)"
Expand All @@ -529,7 +529,7 @@ object Trees {
type ThisTree[-T >: Untyped] = Match[T]
def isInline = false
}
class InlineMatch[T >: Untyped] private[ast] (selector: Tree[T], cases: List[CaseDef[T]])(implicit @constructorOnly src: SourceFile)
class InlineMatch[-T >: Untyped] private[ast] (selector: Tree[T], cases: List[CaseDef[T]])(implicit @constructorOnly src: SourceFile)
extends Match(selector, cases) {
override def isInline = true
override def toString = s"InlineMatch($selector, $cases)"
Expand Down Expand Up @@ -579,7 +579,7 @@ object Trees {
}

/** Array(elems) */
class JavaSeqLiteral[T >: Untyped] private[ast] (elems: List[Tree[T]], elemtpt: Tree[T])(implicit @constructorOnly src: SourceFile)
class JavaSeqLiteral[-T >: Untyped] private[ast] (elems: List[Tree[T]], elemtpt: Tree[T])(implicit @constructorOnly src: SourceFile)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good for uniformity but why would this make any difference for type test safety warnings ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The following code shows why it matters:

trait Tree[-T]

class JavaSeqLiteral[T] extends Tree[T]

trait Type

class DummyTree extends JavaSeqLiteral[Any]

def foo1(tree: Tree[Type]) =
  tree.isInstanceOf[JavaSeqLiteral[Type]]   // error

foo1(new DummyTree)

extends SeqLiteral(elems, elemtpt) {
override def toString: String = s"JavaSeqLiteral($elems, $elemtpt)"
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/dotc/core/Annotations.scala
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ object Annotations {
myTree.asInstanceOf[Tree]

override def isEvaluating: Boolean = myTree == null
override def isEvaluated: Boolean = myTree.isInstanceOf[Tree]
override def isEvaluated: Boolean = myTree.isInstanceOf[Tree @unchecked]
}

/** An annotation indicating the body of a right-hand side,
Expand Down Expand Up @@ -119,7 +119,7 @@ object Annotations {
myTree.asInstanceOf[Tree]

override def isEvaluating: Boolean = myTree == null
override def isEvaluated: Boolean = myTree.isInstanceOf[Tree]
override def isEvaluated: Boolean = myTree.isInstanceOf[Tree @unchecked]
}

object LazyBodyAnnotation {
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/interactive/Completion.scala
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ object Completion {
completionPrefix(selector :: Nil, pos)
}.getOrElse("")

case (ref: RefTree) :: _ =>
case (ref: untpd.RefTree) :: _ =>
if (ref.name == nme.ERROR) ""
else ref.name.toString.take(pos.span.point - ref.span.point)

Expand Down

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/dotc/transform/Erasure.scala
Original file line number Diff line number Diff line change
Expand Up @@ -907,7 +907,7 @@ object Erasure {
*/
private def addRetainedInlineBodies(stats: List[untpd.Tree])(using Context): List[untpd.Tree] =
lazy val retainerDef: Map[Symbol, DefDef] = stats.collect {
case stat: DefDef if stat.symbol.name.is(BodyRetainerName) =>
case stat: DefDef @unchecked if stat.symbol.name.is(BodyRetainerName) =>
val retainer = stat.symbol
val origName = retainer.name.asTermName.exclude(BodyRetainerName)
val inlineMeth = ctx.atPhase(ctx.typerPhase) {
Expand All @@ -918,7 +918,7 @@ object Erasure {
(inlineMeth, stat)
}.toMap
stats.mapConserve {
case stat: DefDef if stat.symbol.isRetainedInlineMethod =>
case stat: DefDef @unchecked if stat.symbol.isRetainedInlineMethod =>
val rdef = retainerDef(stat.symbol)
val fromParams = untpd.allParamSyms(rdef)
val toParams = untpd.allParamSyms(stat)
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/transform/TreeChecker.scala
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ class TreeChecker extends Phase with SymTransformer {

override def typedClosure(tree: untpd.Closure, pt: Type)(using Context): Tree = {
if (!ctx.phase.lambdaLifted) nestingBlock match {
case block @ Block((meth : DefDef) :: Nil, closure: Closure) =>
case block @ Block((meth : untpd.DefDef) :: Nil, closure: untpd.Closure) =>
assert(meth.symbol == closure.meth.symbol, "closure.meth symbol not equal to method symbol. Block: " + block.show)

case block: untpd.Block =>
Expand Down
25 changes: 17 additions & 8 deletions compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ object TypeTestsCasts {
* 5. if `P` is `pre.F[Ts]` and `pre.F` refers to a class which is not `Array`:
* (a) replace `Ts` with fresh type variables `Xs`
* (b) constrain `Xs` with `pre.F[Xs] <:< X`
* (c) instantiate Xs and check `pre.F[Xs] <:< P`
* (c) maximize `pre.F[Xs]` and check `pre.F[Xs] <:< P`
* 6. if `P = T1 | T2` or `P = T1 & T2`, checkable(X, T1) && checkable(X, T2).
* 7. if `P` is a refinement type, FALSE
* 8. otherwise, TRUE
Expand Down Expand Up @@ -105,10 +105,18 @@ object TypeTestsCasts {
debug.println("P1 : " + P1.show)
debug.println("X : " + X.show)

P1 <:< X // constraint P1
// It does not matter if P1 is not a subtype of X.
// It just tries to infer type arguments of P1 from X if the value x
// conforms to the type skeleton pre.F[_]. Then it goes on to check
// if P1 <: P, which means the type arguments in P are trivial,
// thus no runtime checks are needed for them.
P1 <:< X

// use fromScala2x to avoid generating pattern bound symbols
maximizeType(P1, span, fromScala2x = true)
// Maximization of the type means we try to cover all possible values
// which conform to the skeleton pre.F[_] and X. Then we have to make
// sure all of them are actually of the type P, which implies that the
// type arguments in P are trivial (no runtime check needed).
maximizeType(P1, span, fromScala2x = false)

val res = P1 <:< P
debug.println("P1 : " + P1.show)
Expand All @@ -117,7 +125,7 @@ object TypeTestsCasts {
res
}

def recur(X: Type, P: Type): Boolean = (X <:< P) || (P match {
def recur(X: Type, P: Type): Boolean = (X <:< P) || (P.dealias match {
case _: SingletonType => true
case _: TypeProxy
if isAbstract(P) => false
Expand All @@ -136,10 +144,11 @@ object TypeTestsCasts {
// See TypeComparer#either
recur(tp1, P) && recur(tp2, P)
case _ =>
// first try withou striping type parameters for performance
// always false test warnings are emitted elsewhere
X.classSymbol.exists && P.classSymbol.exists && !X.classSymbol.asClass.mayHaveCommonChild(P.classSymbol.asClass) ||
isClassDetermined(X, tpe)(ctx.fresh.setNewTyperState()) ||
isClassDetermined(stripTypeParam(X), tpe)(ctx.fresh.setNewTyperState())
// first try without striping type parameters for performance
isClassDetermined(X, tpe)(ctx.fresh.setNewTyperState().setFreshGADTBounds) ||
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method is called isClassDetermined but actually I don't think it's specific to classes: P could be an application of a type lambda for example.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The case for non-class type constructors is tested in the case TypeProxy, where we assume it cannot be checked at runtime. It seems the assumption is practical enough to cover use cases we know of. When the need emerges, we may relax the check a little bit to make it more expressive.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The case for non-class type constructors is tested in the case TypeProxy, where we assume it cannot be checked at runtime.

Ah I see, but this is incomplete: it doesn't handle situation where a type lambda is directly applied (or appears behind an alias):

trait A[T]
trait B[T] extends A[T]

object Test {
  def foo(x: ([X] =>> A[X])[Any]) = x match {
    case x: ([X] =>> B[X])[Any] =>
    case _ =>
  }
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we haven't seen use cases like this (though the example above type checks). When valid use cases emerge we can easily support them using the method typeArgsTrivial.

isClassDetermined(stripTypeParam(X), tpe)(ctx.fresh.setNewTyperState().setFreshGADTBounds)
}
case AndType(tp1, tp2) => recur(X, tp1) && recur(X, tp2)
case OrType(tp1, tp2) => recur(X, tp1) && recur(X, tp2)
Expand Down
4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/dotc/typer/Applications.scala
Original file line number Diff line number Diff line change
Expand Up @@ -910,8 +910,8 @@ trait Applications extends Compatibility {
tree.args match {
case (arg @ Match(EmptyTree, cases)) :: Nil =>
cases.foreach {
case CaseDef(Typed(_: Ident, _), _, _) => // OK
case CaseDef(Bind(_, Typed(_: Ident, _)), _, _) => // OK
case CaseDef(Typed(_: untpd.Ident, _), _, _) => // OK
case CaseDef(Bind(_, Typed(_: untpd.Ident, _)), _, _) => // OK
case CaseDef(Ident(name), _, _) if name == nme.WILDCARD => // Ok
case CaseDef(pat, _, _) =>
ctx.error(UnexpectedPatternForSummonFrom(pat), pat.sourcePos)
Expand Down
4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/dotc/typer/Nullables.scala
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,8 @@ object Nullables:

object retyper extends ReTyper:
override def typedUnadapted(t: untpd.Tree, pt: Type, locked: TypeVars)(using Context): Tree = t match
case t: ValDef if !t.symbol.is(Lazy) => super.typedUnadapted(t, pt, locked)
case t: MemberDef => promote(t)
case t: untpd.ValDef if !t.symbol.is(Lazy) => super.typedUnadapted(t, pt, locked)
case t: untpd.MemberDef => promote(t)
case _ => super.typedUnadapted(t, pt, locked)

def postProcess(formal: Type, arg: Tree): Tree =
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1264,7 +1264,7 @@ class Typer extends Namer
.map(cas => untpd.unbind(untpd.unsplice(cas.pat)))
.zip(mt.cases)
.forall {
case (pat: Typed, pt) =>
case (pat: untpd.Typed, pt) =>
// To check that pattern types correspond we need to type
// check `pat` here and throw away the result.
val gadtCtx: Context = ctx.fresh.setFreshGADTBounds
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ class DottyLanguageServer extends LanguageServer
val refs =
path match {
// Selected a renaming in an import node
case untpd.ImportSelector(_, rename: Ident, _) :: (_: Import) :: rest if rename.span.contains(pos.span) =>
case untpd.ImportSelector(_, rename: untpd.Ident, _) :: (_: Import) :: rest if rename.span.contains(pos.span) =>
findRenamedReferences(uriTrees, syms, rename.name)

// Selected a reference that has been renamed
Expand Down
2 changes: 1 addition & 1 deletion tests/neg-custom-args/isInstanceOf/3324g.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Test {
}

def quux[T](a: A[T]): Unit = a match {
case _: B[T] => // should be an error!!
case _: B[T] => // error!!
}

quux(new C[Int])
Expand Down
29 changes: 29 additions & 0 deletions tests/neg-custom-args/isInstanceOf/JavaSeqLiteral.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
object Test1 {
trait Tree[-T]

class JavaSeqLiteral[T] extends Tree[T]

trait Type

class DummyTree extends JavaSeqLiteral[Any]

def foo1(tree: Tree[Type]) =
tree.isInstanceOf[JavaSeqLiteral[Type]] // error

foo1(new DummyTree)
}

object Test2 {
trait Tree[-T]

class JavaSeqLiteral[-T] extends Tree[T]

trait Type

class DummyTree extends JavaSeqLiteral[Any]

def foo1(tree: Tree[Type]) =
tree.isInstanceOf[JavaSeqLiteral[Type]]

foo1(new DummyTree)
}
13 changes: 13 additions & 0 deletions tests/neg-custom-args/isInstanceOf/gadt.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Test {
trait A[+T]
class B[T] extends A[T]

class C
class D extends C

def quux(a: A[C]): Unit = a match {
case _: B[C] => // error!!
}

quux(new B[D])
}
12 changes: 12 additions & 0 deletions tests/neg-custom-args/isInstanceOf/i5495.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class A
class B

type AorB = A | B

def foo(any: Any) = any match {
case aorb: AorB =>
case _ =>
}

def bar[T](x: List[T]) = x.isInstanceof[List[Int]] // error

38 changes: 38 additions & 0 deletions tests/neg-custom-args/isInstanceOf/or-type-trees.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
object Test1 {
trait Tree
trait Context

def foo1(myTree: Tree | (Context => Tree)) =
println(myTree.isInstanceOf[Tree])

def foo2(myTree: Tree | (Context => Tree)) =
myTree match
case treeFn: (Context => Tree) => // error
case _ =>

def foo3(myTree: Tree | (Context => Tree)) =
myTree match
case treeFn: (_ => _) => // ok
case _ =>
}

object Test2 {
trait Tree[-T]
trait Context

trait Type

def foo1(myTree: Tree[Type] | (Context => Tree[Type])) =
println(myTree.isInstanceOf[Tree[Type]]) // error
/* class DummyTree extends Tree[Nothing] with (Context => Tree[Type]) */

def foo2(myTree: Tree[Type] | (Context => Tree[Type])) =
myTree match
case treeFn: (Context => Tree[Type]) => // error
case _ =>

def foo3(myTree: Tree[Type] | (Context => Tree[Type])) =
myTree match
case treeFn: (_ => _) => // ok
case _ =>
}
11 changes: 11 additions & 0 deletions tests/neg-custom-args/isInstanceOf/patmat-applied.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class A[-T]
class B[T] extends A[T]

object Test {
def foo(x: A[Null]) = x match {
case x: B[Null] =>
case _ =>
}
}

def bar[T](x: List[T]) = x.isInstanceof[List[Int]] // error