Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit c5dfa75

Browse files
authoredNov 6, 2020
Merge pull request #10204 from dotty-staging/add-Expr-isExprOf
Add `isExprOf` and `toExprOf` to allow safe expression casting
2 parents 7b5cdba + 27617b1 commit c5dfa75

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed
 

‎library/src-bootstrapped/scala/quoted/Expr.scala

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,19 @@ abstract class Expr[+T] private[scala] {
2323
/** Checked cast to a `quoted.Expr[U]` */
2424
def cast[U](using tp: scala.quoted.Type[U])(using qctx: QuoteContext): scala.quoted.Expr[U] = asExprOf[U]
2525

26+
/** Checks is the `quoted.Expr[?]` is valid expression of type `X` */
27+
def isExprOf[X](using tp: scala.quoted.Type[X])(using qctx: QuoteContext): Boolean =
28+
this.unseal.tpe <:< tp.unseal.tpe
29+
2630
/** Convert this to an `quoted.Expr[X]` if this expression is a valid expression of type `X` or throws */
2731
def asExprOf[X](using tp: scala.quoted.Type[X])(using qctx: QuoteContext): scala.quoted.Expr[X] = {
28-
val tree = this.unseal
29-
val expectedType = tp.unseal.tpe
30-
if (tree.tpe <:< expectedType)
32+
if isExprOf[X] then
3133
this.asInstanceOf[scala.quoted.Expr[X]]
3234
else
33-
throw new scala.tasty.reflect.ExprCastError(
34-
s"""Expr: ${tree.show}
35-
|of type: ${tree.tpe.show}
36-
|did not conform to type: ${expectedType.show}
35+
throw new tasty.reflect.ExprCastError(
36+
s"""Expr: ${this.show}
37+
|of type: ${this.unseal.tpe.show}
38+
|did not conform to type: ${tp.unseal.tpe.show}
3739
|""".stripMargin
3840
)
3941
}

‎tests/run-staging/staged-streams_1.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import scala.quoted._
22
import scala.quoted.staging._
3-
import scala.quoted.util._
43
import language.experimental.namedTypeArguments
54

65
/**

0 commit comments

Comments
 (0)
Please sign in to comment.