Skip to content

Fix #9166: Harden check for values in patterns based on class inheritance info #11784

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 2 commits into from
Mar 17, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 17 additions & 4 deletions compiler/src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3808,10 +3808,23 @@ class Typer extends Namer
mapOver(tp)
}

if tree.symbol.isOneOf(Module | Enum)
&& !(tree.tpe frozen_<:< pt) // fast track
&& !(tree.tpe frozen_<:< approx(pt))
then
// Is it certain that a value of `tree.tpe` is never a subtype of `pt`?
// It is true if either
// - the class of `tree.tpe` and class of `pt` cannot have common subclass, or
// - `tree` is an object or enum value, which cannot possibly be a subtype of `pt`
val isDefiniteNotSubtype = {
val clsA = tree.tpe.widenDealias.classSymbol
val clsB = pt.dealias.classSymbol
clsA.exists && clsB.exists
&& clsA != defn.NullClass
&& (!clsA.isNumericValueClass && !clsB.isNumericValueClass) // approximation for numeric conversion and boxing
&& !clsA.asClass.mayHaveCommonChild(clsB.asClass)
|| tree.symbol.isOneOf(Module | Enum)
&& !(tree.tpe frozen_<:< pt) // fast track
&& !(tree.tpe frozen_<:< approx(pt))
}

if isDefiniteNotSubtype then
// We could check whether `equals` is overriden.
// Reasons for not doing so:
// - it complicates the protocol
Expand Down
6 changes: 6 additions & 0 deletions tests/neg/i9166.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
object UnitTest extends App {
def foo(m: Unit) = m match {
case runtime.BoxedUnit.UNIT => println("ok") // error
}
foo(())
}