-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Fix #7554: Add TypeTest for sound pattern type test #7555
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
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
--- | ||
layout: doc-page | ||
title: "TypeTest" | ||
--- | ||
|
||
TypeTest | ||
-------- | ||
|
||
When pattern matching there are two situations where were a runtime type test must be performed. | ||
The first is kind is an explicit type test using the ascription pattern notation. | ||
```scala | ||
(x: X) match | ||
case y: Y => | ||
``` | ||
The second is when an extractor takes an argument that is not a subtype of the scrutinee type. | ||
```scala | ||
(x: X) match | ||
case y @ Y(n) => | ||
|
||
object Y: | ||
def unapply(x: Y): Some[Int] = ... | ||
``` | ||
|
||
In both cases, a class test will be performed at runtime. | ||
But when the type test is on an abstract type (type parameter or type member), the test cannot be performed because the type is erased at runtime. | ||
|
||
A `TypeTest` can be provided to make this test possible. | ||
|
||
```scala | ||
package scala.reflect | ||
|
||
trait TypeTest[-S, T]: | ||
def unapply(s: S): Option[s.type & T] | ||
``` | ||
|
||
It provides an extractor that returns its argument typed as a `T` if the argument is a `T`. | ||
It can be used to encode a type test. | ||
```scala | ||
def f[X, Y](x: X)(using tt: TypeTest[X, Y]): Option[Y] = | ||
x match | ||
case tt(x @ Y(1)) => Some(x) | ||
case tt(x) => Some(x) | ||
case _ => None | ||
``` | ||
|
||
To avoid the syntactic overhead the compiler will look for a type test automatically if it detects that the type test is on abstract types. | ||
This means that `x: Y` is transformed to `tt(x)` and `x @ Y(_)` to `tt(x @ Y(_))` if there is a contextual `TypeTest[X, Y]` in scope. | ||
The previous code is equivalent to | ||
|
||
```scala | ||
def f[X, Y](x: X)(using TypeTest[X, Y]): Option[Y] = | ||
x match | ||
case x @ Y(1) => Some(x) | ||
case x: Y => Some(x) | ||
case _ => None | ||
``` | ||
|
||
We could create a type test at call site where the type test can be performed with runtime class tests directly as follows | ||
|
||
```scala | ||
val tt: TypeTest[Any, String] = | ||
new TypeTest[Any, String] | ||
def unapply(s: Any): Option[s.type & String] = | ||
s match | ||
case s: String => Some(s) | ||
case _ => None | ||
|
||
f[AnyRef, String]("acb")(using tt) | ||
``` | ||
|
||
The compiler will synthesize a new instance of a type test if non is found in scope as | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
```scala | ||
new TypeTest[A, B]: | ||
def unapply(s: A): Option[s.type & B] = | ||
s match | ||
case s: B => Some(s) | ||
case _ => None | ||
``` | ||
If the type tests cannot be done there will be an unchecked warning that will be raised on the `case s: B =>` test. | ||
|
||
The most common `TypeTest` are the ones that take any parameters (i.e. `TypeTest[Any, T]`). | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
To make it possible to use this directly in context bounds we provide the alias | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
```scala | ||
package scala.reflect | ||
|
||
type Typeable[T] = TypeTest[Any, T] | ||
``` | ||
|
||
This alias can be used as | ||
|
||
```scala | ||
def f[T: Typeable]: Boolean = | ||
"abc" match | ||
case x: T => true | ||
case _ => false | ||
|
||
f[String] // true | ||
f[Int] // fasle | ||
``` | ||
|
||
### TypeTest and ClassTag | ||
`TypeTest` is a replacemnt for the same functionallity performed by the `ClassTag.unaplly`. | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Using `ClassTag` instances happend to be unsound. | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
`TypeTest` fixes that unsoundess and adds extra flexibility with the `S` type. | ||
`ClassTag` type tests will still be supported but a warining will be emitted after 3.0. | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
Examples | ||
-------- | ||
|
||
Given the following abstract definition of `Peano` numbers that provides `TypeTest[Nat, Zero]` and `TypeTest[Nat, Succ]` | ||
|
||
```scala | ||
trait Peano: | ||
type Nat | ||
type Zero <: Nat | ||
type Succ <: Nat | ||
def safeDiv(m: Nat, n: Succ): (Nat, Nat) | ||
val Zero: Zero | ||
val Succ: SuccExtractor | ||
trait SuccExtractor { | ||
def apply(nat: Nat): Succ | ||
def unapply(nat: Succ): Option[Nat] | ||
} | ||
given TypeTest[Nat, Zero] = typeTestOfZero | ||
protected def typeTestOfZero: TypeTest[Nat, Zero] | ||
given TypeTest[Nat, Succ] | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
protected def typeTestOfSucc: TypeTest[Nat, Succ] | ||
``` | ||
|
||
it will be possible to write the following program | ||
|
||
```scala | ||
val peano: Peano = ... | ||
import peano.{_, given _} | ||
def divOpt(m: Nat, n: Nat): Option[(Nat, Nat)] = | ||
n match | ||
case Zero => None | ||
case s @ Succ(_) => Some(safeDiv(m, s)) | ||
|
||
val two = Succ(Succ(Zero)) | ||
val five = Succ(Succ(Succ(two))) | ||
println(divOpt(five, two)) | ||
``` | ||
|
||
Note that without the `TypeTest[Nat, Succ]` the pattern `Succ.unapply(nat: Succ)` would be unchecked. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package scala.reflect | ||
|
||
/** A `TypeTest[S, T] contains the logic needed to know at runtime if a value of | ||
* type `S` can be downcasted to `T`. | ||
* | ||
* If a pattern match is performed on a term of type `s: S` that is uncheckable with `s.isInstanceOf[T]` and | ||
* the pattern are of the form: | ||
* - `t: T` | ||
* - `t @ X()` where the `X.unapply` has takes an argument of type `T` | ||
* then a given instance of `TypeTest[S, T]` is summoned and used to perform the test. | ||
*/ | ||
@scala.annotation.implicitNotFound(msg = "No TypeTest available for [${S}, ${T}]") | ||
trait TypeTest[-S, T] extends Serializable: | ||
|
||
/** A TypeTest[S, T] can serve as an extractor that matches only S of type T. | ||
* | ||
* The compiler tries to turn unchecked type tests in pattern matches into checked ones | ||
* by wrapping a `(_: T)` type pattern as `tt(_: T)`, where `tt` is the `TypeTest[S, T]` instance. | ||
* Type tests necessary before calling other extractors are treated similarly. | ||
* `SomeExtractor(...)` is turned into `tt(SomeExtractor(...))` if `T` in `SomeExtractor.unapply(x: T)` | ||
nicolasstucki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* is uncheckable, but we have an instance of `TypeTest[S, T]`. | ||
*/ | ||
def unapply(x: S): Option[x.type & T] | ||
|
||
object TypeTest: | ||
|
||
/** Trivial type test that always succeeds */ | ||
def identity[T]: TypeTest[T, T] = Some(_) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package scala.reflect | ||
|
||
/** A shorhand for `TypeTest[Any, T]`. A `Typeable[T] contains the logic needed to | ||
* know at runtime if a value can be downcasted to `T`. | ||
* | ||
* If a pattern match is performed on a term of type `s: Any` that is uncheckable with `s.isInstanceOf[T]` and | ||
* the pattern are of the form: | ||
* - `t: T` | ||
* - `t @ X()` where the `X.unapply` has takes an argument of type `T` | ||
* then a given instance of `Typeable[T]` (`TypeTest[Any, T]`) is summoned and used to perform the test. | ||
*/ | ||
type Typeable[T] = TypeTest[Any, T] |
24 changes: 24 additions & 0 deletions
24
tests/neg-custom-args/fatal-warnings/IsInstanceOfClassTag.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import scala.reflect.ClassTag | ||
|
||
object IsInstanceOfClassTag { | ||
def safeCast[T: ClassTag](x: Any): Option[T] = { | ||
x match { | ||
case x: T => Some(x) // TODO error: deprecation waring | ||
case _ => None | ||
} | ||
} | ||
|
||
def main(args: Array[String]): Unit = { | ||
safeCast[List[String]](List[Int](1)) match { | ||
case None => | ||
case Some(xs) => | ||
xs.head.substring(0) | ||
} | ||
|
||
safeCast[List[_]](List[Int](1)) match { | ||
case None => | ||
case Some(xs) => | ||
xs.head.substring(0) // error | ||
} | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
tests/neg-custom-args/fatal-warnings/IsInstanceOfClassTag2.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import scala.reflect.TypeTest | ||
|
||
object IsInstanceOfClassTag { | ||
def safeCast[T](x: Any)(using TypeTest[Any, T]): Option[T] = { | ||
x match { | ||
case x: T => Some(x) | ||
case _ => None | ||
} | ||
} | ||
|
||
def main(args: Array[String]): Unit = { | ||
safeCast[List[String]](List[Int](1)) match { // error | ||
case None => | ||
case Some(xs) => | ||
} | ||
|
||
safeCast[List[_]](List[Int](1)) match { | ||
case None => | ||
case Some(xs) => | ||
} | ||
} | ||
} |
6 changes: 6 additions & 0 deletions
6
tests/neg-custom-args/fatal-warnings/classtag-typetest/3_0-migration.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import scala.language.`3.0-migration` | ||
import scala.reflect.ClassTag | ||
|
||
def f3_0m[T: ClassTag](x: Any): Unit = | ||
x match | ||
case _: T => |
6 changes: 6 additions & 0 deletions
6
tests/neg-custom-args/fatal-warnings/classtag-typetest/3_0.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import scala.language.`3.0` | ||
import scala.reflect.ClassTag | ||
|
||
def f3_0[T: ClassTag](x: Any): Unit = | ||
x match | ||
case _: T => |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.