Skip to content

Commit effb9d1

Browse files
committed
Don't optimize explicitly written isInstanceOf tests away.
Do it only for tests generated during pattern matching. Fixes #14707. See the issue for a rationale of the change.
1 parent 5587767 commit effb9d1

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -243,11 +243,8 @@ object TypeTestsCasts {
243243
else foundClasses.exists(check)
244244
end checkSensical
245245

246-
if (expr.tpe <:< testType)
247-
if (expr.tpe.isNotNull) {
248-
if (!inMatch) report.warning(TypeTestAlwaysSucceeds(expr.tpe, testType), tree.srcPos)
249-
constant(expr, Literal(Constant(true)))
250-
}
246+
if (expr.tpe <:< testType) && inMatch then
247+
if expr.tpe.isNotNull then constant(expr, Literal(Constant(true)))
251248
else expr.testNotNull
252249
else {
253250
val nestedCtx = ctx.fresh.setNewTyperState()

tests/run/i14705.scala

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
trait Fruit
2+
case class Apple() extends Fruit
3+
case class Orange() extends Fruit
4+
5+
case class Box[C](fruit: C) extends Fruit
6+
7+
val apple = Box(fruit = Apple())
8+
val orange = Box(fruit = Orange())
9+
10+
11+
val result = List(apple, orange).map {
12+
case appleBox: Box[Apple] @unchecked if appleBox.fruit.isInstanceOf[Apple] => //contains apple
13+
"apple"
14+
case _ =>
15+
"orange"
16+
}
17+
18+
@main def Test =
19+
assert(result == List("apple", "orange"))

0 commit comments

Comments
 (0)