Skip to content

Commit d868b56

Browse files
authored
Merge pull request #11784 from dotty-staging/fix-9166
Fix #9166: Harden check for values in patterns based on class inheritance info
2 parents 06202fd + 5dd58bf commit d868b56

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3804,10 +3804,23 @@ class Typer extends Namer
38043804
mapOver(tp)
38053805
}
38063806

3807-
if tree.symbol.isOneOf(Module | Enum)
3808-
&& !(tree.tpe frozen_<:< pt) // fast track
3809-
&& !(tree.tpe frozen_<:< approx(pt))
3810-
then
3807+
// Is it certain that a value of `tree.tpe` is never a subtype of `pt`?
3808+
// It is true if either
3809+
// - the class of `tree.tpe` and class of `pt` cannot have common subclass, or
3810+
// - `tree` is an object or enum value, which cannot possibly be a subtype of `pt`
3811+
val isDefiniteNotSubtype = {
3812+
val clsA = tree.tpe.widenDealias.classSymbol
3813+
val clsB = pt.dealias.classSymbol
3814+
clsA.exists && clsB.exists
3815+
&& clsA != defn.NullClass
3816+
&& (!clsA.isNumericValueClass && !clsB.isNumericValueClass) // approximation for numeric conversion and boxing
3817+
&& !clsA.asClass.mayHaveCommonChild(clsB.asClass)
3818+
|| tree.symbol.isOneOf(Module | Enum)
3819+
&& !(tree.tpe frozen_<:< pt) // fast track
3820+
&& !(tree.tpe frozen_<:< approx(pt))
3821+
}
3822+
3823+
if isDefiniteNotSubtype then
38113824
// We could check whether `equals` is overriden.
38123825
// Reasons for not doing so:
38133826
// - it complicates the protocol

tests/neg/i9166.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
object UnitTest extends App {
2+
def foo(m: Unit) = m match {
3+
case runtime.BoxedUnit.UNIT => println("ok") // error
4+
}
5+
foo(())
6+
}

0 commit comments

Comments
 (0)