Skip to content

Add isExprOf and toExprOf to allow safe expression casting #10204

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
Nov 6, 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
16 changes: 9 additions & 7 deletions library/src-bootstrapped/scala/quoted/Expr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,19 @@ abstract class Expr[+T] private[scala] {
/** Checked cast to a `quoted.Expr[U]` */
def cast[U](using tp: scala.quoted.Type[U])(using qctx: QuoteContext): scala.quoted.Expr[U] = asExprOf[U]

/** Checks is the `quoted.Expr[?]` is valid expression of type `X` */
def isExprOf[X](using tp: scala.quoted.Type[X])(using qctx: QuoteContext): Boolean =
this.unseal.tpe <:< tp.unseal.tpe

/** Convert this to an `quoted.Expr[X]` if this expression is a valid expression of type `X` or throws */
def asExprOf[X](using tp: scala.quoted.Type[X])(using qctx: QuoteContext): scala.quoted.Expr[X] = {
val tree = this.unseal
val expectedType = tp.unseal.tpe
if (tree.tpe <:< expectedType)
if isExprOf[X] then
this.asInstanceOf[scala.quoted.Expr[X]]
else
throw new scala.tasty.reflect.ExprCastError(
s"""Expr: ${tree.show}
|of type: ${tree.tpe.show}
|did not conform to type: ${expectedType.show}
throw new tasty.reflect.ExprCastError(
s"""Expr: ${this.show}
|of type: ${this.unseal.tpe.show}
|did not conform to type: ${tp.unseal.tpe.show}
|""".stripMargin
)
}
Expand Down
1 change: 0 additions & 1 deletion tests/run-staging/staged-streams_1.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import scala.quoted._
import scala.quoted.staging._
import scala.quoted.util._
import language.experimental.namedTypeArguments

/**
Expand Down