Skip to content

More precise type for typed patterns, less precise for literal patterns #8710

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 1 commit into from
Apr 12, 2020
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
12 changes: 9 additions & 3 deletions compiler/src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1718,10 +1718,16 @@ class Typer extends Namer
}
if (name == nme.WILDCARD) body1
else {
// for a singleton pattern like `x @ Nil`, `x` should get the type from the scrutinee
// see tests/neg/i3200b.scala and SI-1503
// In `x @ Nil`, `Nil` is a _stable identifier pattern_ and will be compiled
// to an `==` test, so the type of `x` is unrelated to the type of `Nil`.
// Similarly, in `x @ 1`, `1` is a _literal pattern_ and will also be compiled
// to an `==` test.
// See i3200*.scala and https://github.com/scala/bug/issues/1503.
val isStableIdentifierOrLiteral =
body1.isInstanceOf[RefTree] && !isWildcardArg(body1)
|| body1.isInstanceOf[Literal]
val symTp =
if body1.tpe.isInstanceOf[TermRef] then pt
if isStableIdentifierOrLiteral then pt
else if isWildcardStarArg(body1)
|| pt == defn.ImplicitScrutineeTypeRef
|| body1.tpe <:< pt // There is some strange interaction with gadt matching.
Expand Down
5 changes: 4 additions & 1 deletion tests/neg/i3200b.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
object Test {
def main(args: Array[String]): Unit = {
val a : Nil.type = (Vector(): Any) match { case n @ Nil => n } // error
val a: Nil.type = (Vector(): Any) match { case n @ Nil => n } // error
val b: Nil.type = (Vector(): Any) match { case n @ (m @ Nil) => n } // error
val c: Int = (1.0: Any) match { case n @ 1 => n } // error
val d: Int = (1.0: Any) match { case n @ (m @ 1) => n } // error
}
}
28 changes: 28 additions & 0 deletions tests/run/i3200c.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
sealed trait X
case object Y extends X

object Test {
def yIs1(proof: Y.type): Int = 1

def test(x: X) = x match {
case y: Y.type => yIs1(y)
}

def test2(x: X) = x match {
case y @ (yy: Y.type) =>
yIs1(y)
yIs1(yy)
}

def main(args: Array[String]): Unit = {
test(Y)

val a: Nil.type = (Vector(): Any) match {
case n: Nil.type =>
assert(false, "should not be reached")
n
case _ =>
Nil
}
}
}