Skip to content

Commit a4fd829

Browse files
authored
Merge pull request #11768 from dotty-staging/fix-11178
Fix #11178: remove unsound tweak for F-bounds in isInstanceOf check
2 parents da7aae2 + aa296ba commit a4fd829

File tree

8 files changed

+92
-47
lines changed

8 files changed

+92
-47
lines changed

compiler/src/dotty/tools/dotc/core/PatternTypeConstrainer.scala

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ trait PatternTypeConstrainer { self: TypeComparer =>
7373
* scrutinee and pattern types. This does not apply if the pattern type is only applied to type variables,
7474
* in which case the subtyping relationship "heals" the type.
7575
*/
76-
def constrainPatternType(pat: Type, scrut: Type): Boolean = trace(i"constrainPatternType($scrut, $pat)", gadts) {
76+
def constrainPatternType(pat: Type, scrut: Type, widenParams: Boolean = true): Boolean = trace(i"constrainPatternType($scrut, $pat)", gadts) {
7777

7878
def classesMayBeCompatible: Boolean = {
7979
import Flags._
@@ -135,7 +135,7 @@ trait PatternTypeConstrainer { self: TypeComparer =>
135135
case _ => NoType
136136
}
137137
if (upcasted.exists)
138-
constrainSimplePatternType(pat, upcasted) || constrainUpcasted(upcasted)
138+
constrainSimplePatternType(pat, upcasted, widenParams) || constrainUpcasted(upcasted)
139139
else true
140140
}
141141
}
@@ -155,7 +155,7 @@ trait PatternTypeConstrainer { self: TypeComparer =>
155155
case pat: RefinedOrRecType =>
156156
constrainPatternType(stripRefinement(pat), scrut)
157157
case pat =>
158-
constrainSimplePatternType(pat, scrut) || classesMayBeCompatible && constrainUpcasted(scrut)
158+
constrainSimplePatternType(pat, scrut, widenParams) || classesMayBeCompatible && constrainUpcasted(scrut)
159159
}
160160
}
161161
}
@@ -194,7 +194,7 @@ trait PatternTypeConstrainer { self: TypeComparer =>
194194
* case classes without also appropriately extending the relevant case class
195195
* (see `RefChecks#checkCaseClassInheritanceInvariant`).
196196
*/
197-
def constrainSimplePatternType(patternTp: Type, scrutineeTp: Type): Boolean = {
197+
def constrainSimplePatternType(patternTp: Type, scrutineeTp: Type, widenParams: Boolean): Boolean = {
198198
def refinementIsInvariant(tp: Type): Boolean = tp match {
199199
case tp: ClassInfo => tp.cls.is(Final) || tp.cls.is(Case)
200200
case tp: TypeProxy => refinementIsInvariant(tp.underlying)
@@ -213,7 +213,8 @@ trait PatternTypeConstrainer { self: TypeComparer =>
213213

214214
val widePt =
215215
if migrateTo3 || refinementIsInvariant(patternTp) then scrutineeTp
216-
else widenVariantParams(scrutineeTp)
216+
else if widenParams then widenVariantParams(scrutineeTp)
217+
else scrutineeTp
217218
val narrowTp = SkolemType(patternTp)
218219
trace(i"constraining simple pattern type $narrowTp <:< $widePt", gadts, res => s"$res\ngadt = ${ctx.gadt.debugBoundsDescription}") {
219220
isSubType(narrowTp, widePt)

compiler/src/dotty/tools/dotc/core/TypeComparer.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2687,8 +2687,8 @@ object TypeComparer {
26872687
def dropTransparentTraits(tp: Type, bound: Type)(using Context): Type =
26882688
comparing(_.dropTransparentTraits(tp, bound))
26892689

2690-
def constrainPatternType(pat: Type, scrut: Type)(using Context): Boolean =
2691-
comparing(_.constrainPatternType(pat, scrut))
2690+
def constrainPatternType(pat: Type, scrut: Type, widenParams: Boolean = true)(using Context): Boolean =
2691+
comparing(_.constrainPatternType(pat, scrut, widenParams))
26922692

26932693
def explained[T](op: ExplainingTypeComparer => T, header: String = "Subtype trace:")(using Context): String =
26942694
comparing(_.explained(op, header))

compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala

Lines changed: 23 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,6 @@ object TypeTestsCasts {
3434
*
3535
* First do the following substitution:
3636
* (a) replace `T @unchecked` and pattern binder types (e.g., `_$1`) in P with WildcardType
37-
* (b) replace pattern binder types (e.g., `_$1`) in X:
38-
* - variance = 1 : hiBound
39-
* - variance = -1 : loBound
40-
* - variance = 0 : OrType(Any, Nothing) // TODO: use original type param bounds
4137
*
4238
* Then check:
4339
*
@@ -67,29 +63,6 @@ object TypeTestsCasts {
6763
}
6864
}.apply(tp)
6965

70-
def replaceX(tp: Type)(using Context) = new TypeMap {
71-
def apply(tp: Type) = tp match {
72-
case tref: TypeRef if tref.typeSymbol.isPatternBound =>
73-
if (variance == 1) tref.info.hiBound
74-
else if (variance == -1) tref.info.loBound
75-
else OrType(defn.AnyType, defn.NothingType, soft = true) // TODO: what does this line do?
76-
case _ => mapOver(tp)
77-
}
78-
}.apply(tp)
79-
80-
/** Approximate type parameters depending on variance */
81-
def stripTypeParam(tp: Type)(using Context) = new ApproximatingTypeMap {
82-
val boundTypeParams = util.HashMap[TypeRef, TypeVar]()
83-
def apply(tp: Type): Type = tp match {
84-
case _: MatchType =>
85-
tp // break cycles
86-
case tp: TypeRef if !tp.symbol.isClass =>
87-
boundTypeParams.getOrElseUpdate(tp, newTypeVar(tp.underlying.toBounds))
88-
case _ =>
89-
mapOver(tp)
90-
}
91-
}.apply(tp)
92-
9366
/** Returns true if the type arguments of `P` can be determined from `X` */
9467
def typeArgsTrivial(X: Type, P: AppliedType)(using Context) = inContext(ctx.fresh.setExploreTyperState().setFreshGADTBounds) {
9568
val AppliedType(tycon, _) = P
@@ -102,27 +75,43 @@ object TypeTestsCasts {
10275
val tvars = constrained(typeLambda, untpd.EmptyTree, alwaysAddTypeVars = true)._2.map(_.tpe)
10376
val P1 = tycon.appliedTo(tvars)
10477

78+
debug.println("before " + ctx.typerState.constraint.show)
10579
debug.println("P : " + P.show)
10680
debug.println("P1 : " + P1.show)
10781
debug.println("X : " + X.show)
10882

109-
// It does not matter if P1 is not a subtype of X.
83+
// It does not matter whether P1 is a subtype of X or not.
11084
// It just tries to infer type arguments of P1 from X if the value x
11185
// conforms to the type skeleton pre.F[_]. Then it goes on to check
11286
// if P1 <: P, which means the type arguments in P are trivial,
11387
// thus no runtime checks are needed for them.
114-
P1 <:< X
88+
withMode(Mode.GadtConstraintInference) {
89+
// Why not widen type arguments here? Given the following program
90+
//
91+
// trait Tree[-T] class Ident[-T] extends Tree[T] def foo1(tree:
92+
// Tree[Int]) = tree.isInstanceOf[Ident[Int]]
93+
//
94+
// In checking whether the test tree.isInstanceOf[Ident[Int]]
95+
// is realizable, we want to constrain Ident[X] <: Tree[Int],
96+
// such that we can infer X = Int and Ident[X] <:< Ident[Int].
97+
//
98+
// If we perform widening, we will get X = Nothing, and we don't have
99+
// Ident[X] <:< Ident[Int] any more.
100+
TypeComparer.constrainPatternType(P1, X, widenParams = false)
101+
debug.println(TypeComparer.explained(_.constrainPatternType(P1, X, widenParams = false)))
102+
}
115103

116104
// Maximization of the type means we try to cover all possible values
117105
// which conform to the skeleton pre.F[_] and X. Then we have to make
118106
// sure all of them are actually of the type P, which implies that the
119107
// type arguments in P are trivial (no runtime check needed).
120108
maximizeType(P1, span, fromScala2x = false)
121109

110+
debug.println("after " + ctx.typerState.constraint.show)
111+
122112
val res = P1 <:< P
123113

124114
debug.println(TypeComparer.explained(_.isSubType(P1, P)))
125-
126115
debug.println("P1 : " + P1.show)
127116
debug.println("P1 <:< P = " + res)
128117

@@ -140,7 +129,7 @@ object TypeTestsCasts {
140129
case _ => recur(defn.AnyType, tpT)
141130
}
142131
case tpe: AppliedType =>
143-
X.widen match {
132+
X.widenDealias match {
144133
case OrType(tp1, tp2) =>
145134
// This case is required to retrofit type inference,
146135
// which cut constraints in the following two cases:
@@ -151,10 +140,8 @@ object TypeTestsCasts {
151140
case _ =>
152141
// always false test warnings are emitted elsewhere
153142
X.classSymbol.exists && P.classSymbol.exists &&
154-
!X.classSymbol.asClass.mayHaveCommonChild(P.classSymbol.asClass) ||
155-
// first try without striping type parameters for performance
156-
typeArgsTrivial(X, tpe) ||
157-
typeArgsTrivial(stripTypeParam(X), tpe)
143+
!X.classSymbol.asClass.mayHaveCommonChild(P.classSymbol.asClass)
144+
|| typeArgsTrivial(X, tpe)
158145
}
159146
case AndType(tp1, tp2) => recur(X, tp1) && recur(X, tp2)
160147
case OrType(tp1, tp2) => recur(X, tp1) && recur(X, tp2)
@@ -163,7 +150,7 @@ object TypeTestsCasts {
163150
case _ => true
164151
})
165152

166-
val res = recur(replaceX(X.widen), replaceP(P))
153+
val res = recur(X.widen, replaceP(P))
167154

168155
debug.println(i"checking ${X.show} isInstanceOf ${P} = $res")
169156

compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -746,7 +746,7 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
746746
tpd.Closure(meth, tss => xCheckMacroedOwners(xCheckMacroValidExpr(rhsFn(meth, tss.head.map(withDefaultPos))), meth))
747747

748748
def unapply(tree: Block): Option[(List[ValDef], Term)] = tree match {
749-
case Block((ddef @ DefDef(_, TermParamClause(params) :: Nil, _, Some(body))) :: Nil, Closure(meth, _))
749+
case Block((ddef @ DefDef(_, tpd.ValDefs(params) :: Nil, _, Some(body))) :: Nil, Closure(meth, _))
750750
if ddef.symbol == meth.symbol =>
751751
Some((params, body))
752752
case _ => None

compiler/test/dotty/tools/dotc/parsing/StringInterpolationPositionTest.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ class StringInterpolationPositionTest extends ParserTest {
2323
def interpolationLiteralPosition: Unit = {
2424
val t = parseText(program)
2525
t match {
26-
case PackageDef(_, List(TypeDef(_, Template(_, _, _, statements: List[Tree])))) => {
27-
val interpolations = statements.collect{ case ValDef(_, _, InterpolatedString(_, int)) => int }
26+
case PackageDef(_, List(TypeDef(_, tpl: Template))) => {
27+
val interpolations = tpl.body.collect{ case ValDef(_, _, InterpolatedString(_, int)) => int }
2828
val lits = interpolations.flatten.flatMap {
2929
case l @ Literal(_) => List(l)
3030
case Thicket(trees) => trees.collect { case l @ Literal(_) => l }

scaladoc/src/dotty/tools/scaladoc/renderers/WikiDocRenderer.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ class DocRender(signatureRenderer: SignatureRenderer)(using DocContext):
1313
case md: MdNode => renderMarkdown(md)
1414
case Nil => raw("")
1515
case Seq(elem: WikiDocElement) => renderElement(elem)
16-
case list: Seq[WikiDocElement] => div(list.map(renderElement))
16+
case list: Seq[WikiDocElement @unchecked] => div(list.map(renderElement))
1717

1818
private def renderMarkdown(el: MdNode): AppliedTag =
1919
raw(DocFlexmarkRenderer.render(el)( (link,name) =>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
object HTML:
2+
type AttrArg = AppliedAttr | Seq[AppliedAttr]
3+
opaque type AppliedAttr = String
4+
opaque type AppliedTag = StringBuilder
5+
6+
case class Tag(name: String):
7+
def apply(attrs: AttrArg*): AppliedTag = {
8+
val sb = StringBuilder()
9+
sb.append(s"<$name")
10+
attrs.filter(_ != Nil).foreach{
11+
case s: Seq[AppliedAttr] =>
12+
s.foreach(sb.append(" ").append)
13+
case s: Seq[Int] => // error
14+
case e: AppliedAttr =>
15+
sb.append(" ").append(e)
16+
}
17+
sb
18+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
trait Box[+T]
2+
case class Foo[+S](s: S) extends Box[S]
3+
4+
def unwrap2[A](b: Box[A]): A =
5+
b match
6+
case _: Foo[Int] => 0 // error
7+
8+
object Test1 {
9+
// Invariant case, OK
10+
sealed trait Bar[A]
11+
12+
def test[A](bar: Bar[A]) =
13+
bar match {
14+
case _: Bar[Boolean] => ??? // error
15+
case _ => ???
16+
}
17+
}
18+
19+
object Test2 {
20+
// Covariant case
21+
sealed trait Bar[+A]
22+
23+
def test[A](bar: Bar[A]) =
24+
bar match {
25+
case _: Bar[Boolean] => ??? // error
26+
case _ => ???
27+
}
28+
}
29+
30+
object Test3 {
31+
// Contravariant case
32+
sealed trait Bar[-A]
33+
34+
def test[A](bar: Bar[A]) =
35+
bar match {
36+
case _: Bar[Boolean] => ??? // error
37+
case _ => ???
38+
}
39+
}

0 commit comments

Comments
 (0)