Skip to content

Match Types: implement cantPossiblyMatch #5996

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 20 commits into from
Mar 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
c1b7e84
Minor TypeTestsCasts refactoring
OlivierBlanvillain Feb 11, 2019
6e39fcb
Rename evalOnce to letBind
OlivierBlanvillain Feb 11, 2019
eef623a
Rename cmp to typeComparer
OlivierBlanvillain Feb 11, 2019
6755f52
Remove reduceParallel
OlivierBlanvillain Feb 18, 2019
88cfb7e
Fix spacing for TypeComparer comments
OlivierBlanvillain Feb 21, 2019
bb1515e
Flag ChildrenQueried in hasAnonymousChild
OlivierBlanvillain Feb 22, 2019
f79d937
Implement cantPossiblyMatch
OlivierBlanvillain Mar 1, 2019
60d0e20
Replace Space.inhabited by typeComparer.intersecting
OlivierBlanvillain Feb 28, 2019
d1180cc
Move refineUsingParent to Typer
OlivierBlanvillain Feb 26, 2019
b0c1e7b
Check inhabitation of children in Space
OlivierBlanvillain Feb 28, 2019
c3d23fe
Only trust isSameType for fully instanciated types
OlivierBlanvillain Feb 28, 2019
4f934ad
Use derivesFrom instead of isSubType for classes
OlivierBlanvillain Mar 1, 2019
80c25e3
Handle type parameters using symbol.is(TypeParam)
OlivierBlanvillain Mar 4, 2019
ab74827
Fix AppliedType logic
OlivierBlanvillain Mar 4, 2019
1df0d8b
Revert "Rename evalOnce to letBind"
OlivierBlanvillain Mar 6, 2019
8827eff
Revert "Flag ChildrenQueried in hasAnonymousChild"
OlivierBlanvillain Mar 6, 2019
ffa8acf
Address review
OlivierBlanvillain Mar 6, 2019
e7f6049
Move refineUsingParent to TypeOps
OlivierBlanvillain Mar 6, 2019
f4df58d
Factor out cov. test and use it in the inv. case
OlivierBlanvillain Mar 6, 2019
ea04343
Update inhabited check in Space
OlivierBlanvillain Mar 6, 2019
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
275 changes: 215 additions & 60 deletions compiler/src/dotty/tools/dotc/core/TypeComparer.scala

Large diffs are not rendered by default.

153 changes: 153 additions & 0 deletions compiler/src/dotty/tools/dotc/core/TypeOps.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import collection.mutable
import ast.tpd._
import reporting.trace
import reporting.diagnostic.Message
import config.Printers.{gadts, typr}
import typer.Applications._
import typer.ProtoTypes._
import typer.ForceDegree
import typer.Inferencing.isFullyDefined

import scala.annotation.internal.sharable

Expand Down Expand Up @@ -334,6 +339,154 @@ trait TypeOps { this: Context => // TODO: Make standalone object.
* This test is used when we are too early in the pipeline to consider imports.
*/
def scala2Setting = ctx.settings.language.value.contains(nme.Scala2.toString)

/** Refine child based on parent
*
* In child class definition, we have:
*
* class Child[Ts] extends path.Parent[Us] with Es
* object Child extends path.Parent[Us] with Es
* val child = new path.Parent[Us] with Es // enum values
*
* Given a parent type `parent` and a child symbol `child`, we infer the prefix
* and type parameters for the child:
*
* prefix.child[Vs] <:< parent
*
* where `Vs` are fresh type variables and `prefix` is the symbol prefix with all
* non-module and non-package `ThisType` replaced by fresh type variables.
*
* If the subtyping is true, the instantiated type `p.child[Vs]` is
* returned. Otherwise, `NoType` is returned.
*/
def refineUsingParent(parent: Type, child: Symbol)(implicit ctx: Context): Type = {
if (child.isTerm && child.is(Case, butNot = Module)) return child.termRef // enum vals always match

// <local child> is a place holder from Scalac, it is hopeless to instantiate it.
//
// Quote from scalac (from nsc/symtab/classfile/Pickler.scala):
//
// ...When a sealed class/trait has local subclasses, a single
// <local child> class symbol is added as pickled child
// (instead of a reference to the anonymous class; that was done
// initially, but seems not to work, ...).
//
if (child.name == tpnme.LOCAL_CHILD) return child.typeRef

val childTp = if (child.isTerm) child.termRef else child.typeRef

instantiate(childTp, parent)(ctx.fresh.setNewTyperState()).dealias
}

/** Instantiate type `tp1` to be a subtype of `tp2`
*
* Return the instantiated type if type parameters and this type
* in `tp1` can be instantiated such that `tp1 <:< tp2`.
*
* Otherwise, return NoType.
*/
private def instantiate(tp1: NamedType, tp2: Type)(implicit ctx: Context): Type = {
/** expose abstract type references to their bounds or tvars according to variance */
class AbstractTypeMap(maximize: Boolean)(implicit ctx: Context) extends TypeMap {
def expose(lo: Type, hi: Type): Type =
if (variance == 0)
newTypeVar(TypeBounds(lo, hi))
else if (variance == 1)
if (maximize) hi else lo
else
if (maximize) lo else hi

def apply(tp: Type): Type = tp match {
case tp: TypeRef if isBounds(tp.underlying) =>
val lo = this(tp.info.loBound)
val hi = this(tp.info.hiBound)
// See tests/patmat/gadt.scala tests/patmat/exhausting.scala tests/patmat/t9657.scala
val exposed = expose(lo, hi)
typr.println(s"$tp exposed to =====> $exposed")
exposed

case AppliedType(tycon: TypeRef, args) if isBounds(tycon.underlying) =>
val args2 = args.map(this)
val lo = this(tycon.info.loBound).applyIfParameterized(args2)
val hi = this(tycon.info.hiBound).applyIfParameterized(args2)
val exposed = expose(lo, hi)
typr.println(s"$tp exposed to =====> $exposed")
exposed

case _ =>
mapOver(tp)
}
}

def minTypeMap(implicit ctx: Context) = new AbstractTypeMap(maximize = false)
def maxTypeMap(implicit ctx: Context) = new AbstractTypeMap(maximize = true)

// Fix subtype checking for child instantiation,
// such that `Foo(Test.this.foo) <:< Foo(Foo.this)`
// See tests/patmat/i3938.scala
class RemoveThisMap extends TypeMap {
var prefixTVar: Type = null
def apply(tp: Type): Type = tp match {
case ThisType(tref: TypeRef) if !tref.symbol.isStaticOwner =>
if (tref.symbol.is(Module))
TermRef(this(tref.prefix), tref.symbol.sourceModule)
else if (prefixTVar != null)
this(tref)
else {
prefixTVar = WildcardType // prevent recursive call from assigning it
prefixTVar = newTypeVar(TypeBounds.upper(this(tref)))
prefixTVar
}
case tp => mapOver(tp)
}
}

// replace uninstantiated type vars with WildcardType, check tests/patmat/3333.scala
def instUndetMap(implicit ctx: Context) = new TypeMap {
def apply(t: Type): Type = t match {
case tvar: TypeVar if !tvar.isInstantiated => WildcardType(tvar.origin.underlying.bounds)
case _ => mapOver(t)
}
}

val removeThisType = new RemoveThisMap
val tvars = tp1.typeParams.map { tparam => newTypeVar(tparam.paramInfo.bounds) }
val protoTp1 = removeThisType.apply(tp1).appliedTo(tvars)

val force = new ForceDegree.Value(
tvar =>
!(ctx.typerState.constraint.entry(tvar.origin) `eq` tvar.origin.underlying) ||
(tvar `eq` removeThisType.prefixTVar),
minimizeAll = false,
allowBottom = false
)

// If parent contains a reference to an abstract type, then we should
// refine subtype checking to eliminate abstract types according to
// variance. As this logic is only needed in exhaustivity check,
// we manually patch subtyping check instead of changing TypeComparer.
// See tests/patmat/i3645b.scala
def parentQualify = tp1.widen.classSymbol.info.parents.exists { parent =>
implicit val ictx = ctx.fresh.setNewTyperState()
parent.argInfos.nonEmpty && minTypeMap.apply(parent) <:< maxTypeMap.apply(tp2)
}

if (protoTp1 <:< tp2) {
if (isFullyDefined(protoTp1, force)) protoTp1
else instUndetMap.apply(protoTp1)
}
else {
val protoTp2 = maxTypeMap.apply(tp2)
if (protoTp1 <:< protoTp2 || parentQualify) {
if (isFullyDefined(AndType(protoTp1, protoTp2), force)) protoTp1
else instUndetMap.apply(protoTp1)
}
else {
typr.println(s"$protoTp1 <:< $protoTp2 = false")
NoType
}
}
}
}

object TypeOps {
Expand Down
50 changes: 8 additions & 42 deletions compiler/src/dotty/tools/dotc/core/Types.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2415,7 +2415,7 @@ object Types {
}
}

/** A constant type with single `value`. */
/** A constant type with single `value`. */
abstract case class ConstantType(value: Constant) extends CachedProxyType with SingletonType {
override def underlying(implicit ctx: Context): Type = value.tpe

Expand Down Expand Up @@ -3764,42 +3764,9 @@ object Types {

override def tryNormalize(implicit ctx: Context): Type = reduced.normalized

/** Switch to choose parallel or sequential reduction */
private final val reduceInParallel = false

final def cantPossiblyMatch(cas: Type)(implicit ctx: Context): Boolean =
true // should be refined if we allow overlapping cases

def reduced(implicit ctx: Context): Type = {
val trackingCtx = ctx.fresh.setTypeComparerFn(new TrackingTypeComparer(_))
val cmp = trackingCtx.typeComparer.asInstanceOf[TrackingTypeComparer]

def reduceSequential(cases: List[Type])(implicit ctx: Context): Type = cases match {
case Nil => NoType
case cas :: cases1 =>
val r = cmp.matchCase(scrutinee, cas, instantiate = true)
if (r.exists) r
else if (cantPossiblyMatch(cas)) reduceSequential(cases1)
else NoType
}

def reduceParallel(implicit ctx: Context) = {
val applicableBranches = cases
.map(cmp.matchCase(scrutinee, _, instantiate = true)(trackingCtx))
.filter(_.exists)
applicableBranches match {
case Nil => NoType
case applicableBranch :: Nil => applicableBranch
case _ =>
record(i"MatchType.multi-branch")
ctx.typeComparer.glb(applicableBranches)
}
}

def isBounded(tp: Type) = tp match {
case tp: TypeParamRef =>
case tp: TypeRef => ctx.gadt.contains(tp.symbol)
}
val typeComparer = trackingCtx.typeComparer.asInstanceOf[TrackingTypeComparer]

def contextInfo(tp: Type): Type = tp match {
case tp: TypeParamRef =>
Expand All @@ -3813,28 +3780,27 @@ object Types {
tp.underlying
}

def updateReductionContext() = {
def updateReductionContext(): Unit = {
reductionContext = new mutable.HashMap
for (tp <- cmp.footprint)
for (tp <- typeComparer.footprint)
reductionContext(tp) = contextInfo(tp)
typr.println(i"footprint for $this $hashCode: ${cmp.footprint.toList.map(x => (x, contextInfo(x)))}%, %")
typr.println(i"footprint for $this $hashCode: ${typeComparer.footprint.toList.map(x => (x, contextInfo(x)))}%, %")
}

def upToDate =
def isUpToDate: Boolean =
reductionContext.keysIterator.forall { tp =>
reductionContext(tp) `eq` contextInfo(tp)
}

record("MatchType.reduce called")
if (!Config.cacheMatchReduced || myReduced == null || !upToDate) {
if (!Config.cacheMatchReduced || myReduced == null || !isUpToDate) {
record("MatchType.reduce computed")
if (myReduced != null) record("MatchType.reduce cache miss")
myReduced =
trace(i"reduce match type $this $hashCode", typr, show = true) {
try
if (defn.isBottomType(scrutinee)) defn.NothingType
else if (reduceInParallel) reduceParallel(trackingCtx)
else reduceSequential(cases)(trackingCtx)
else typeComparer.matchCases(scrutinee, cases)(trackingCtx)
catch {
case ex: Throwable =>
handleRecursive("reduce type ", i"$scrutinee match ...", ex)
Expand Down
28 changes: 13 additions & 15 deletions compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala
Original file line number Diff line number Diff line change
Expand Up @@ -164,19 +164,20 @@ object TypeTestsCasts {
else tp.classSymbol

def foundCls = effectiveClass(expr.tpe.widen)
// println(i"ta $tree, found = $foundCls")

def inMatch =
fun.symbol == defn.Any_typeTest || // new scheme
expr.symbol.is(Case) // old scheme

def transformIsInstanceOf(expr:Tree, testType: Type, flagUnrelated: Boolean): Tree = {
def transformIsInstanceOf(expr: Tree, testType: Type, flagUnrelated: Boolean): Tree = {
def testCls = effectiveClass(testType.widen)

def unreachable(why: => String) =
def unreachable(why: => String): Boolean = {
if (flagUnrelated)
if (inMatch) ctx.error(em"this case is unreachable since $why", expr.sourcePos)
else ctx.warning(em"this will always yield false since $why", expr.sourcePos)
false
}

/** Are `foundCls` and `testCls` classes that allow checks
* whether a test would be always false?
Expand All @@ -191,25 +192,22 @@ object TypeTestsCasts {
// we don't have the logic to handle derived value classes

/** Check whether a runtime test that a value of `foundCls` can be a `testCls`
* can be true in some cases. Issure a warning or an error if that's not the case.
* can be true in some cases. Issues a warning or an error otherwise.
*/
def checkSensical: Boolean =
if (!isCheckable) true
else if (foundCls.isPrimitiveValueClass && !testCls.isPrimitiveValueClass) {
ctx.error("cannot test if value types are references", tree.sourcePos)
false
}
ctx.error("cannot test if value types are references", tree.sourcePos)
false
}
else if (!foundCls.derivesFrom(testCls)) {
if (foundCls.is(Final)) {
val unrelated = !testCls.derivesFrom(foundCls) && (
testCls.is(Final) || !testCls.is(Trait) && !foundCls.is(Trait)
)
if (foundCls.is(Final))
unreachable(i"$foundCls is not a subclass of $testCls")
false
}
else if (!testCls.derivesFrom(foundCls) &&
(testCls.is(Final) ||
!testCls.is(Trait) && !foundCls.is(Trait))) {
else if (unrelated)
unreachable(i"$foundCls and $testCls are unrelated")
false
}
else true
}
else true
Expand Down
3 changes: 2 additions & 1 deletion compiler/src/dotty/tools/dotc/transform/TypeUtils.scala
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package dotty.tools.dotc
package dotty.tools
package dotc
package transform

import core._
Expand Down
Loading