Skip to content
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

Improve asExprOf cast error formatting #19195

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions compiler/src/scala/quoted/runtime/impl/ExprCastException.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package scala.quoted.runtime.impl

import dotty.tools.dotc.ast.tpd.Tree
import dotty.tools.dotc.core.Contexts.*

class ExprCastException(msg: String) extends Exception(msg)


object ExprCastException:
def apply(expectedType: String, actualType: String, exprCode: String): ExprCastException =
new ExprCastException(
s"""|
| Expected type: ${formatLines(expectedType)}
| Actual type: ${formatLines(actualType)}
| Expression: ${formatLines(exprCode)}
|""".stripMargin)

private def formatLines(str: String): String =
if !str.contains("\n") then str
else str.linesIterator.mkString("\n ", "\n ", "\n")
10 changes: 5 additions & 5 deletions compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import scala.quoted.runtime.{QuoteUnpickler, QuoteMatching}
import scala.quoted.runtime.impl.printers.*

import scala.reflect.TypeTest
import dotty.tools.dotc.core.NameKinds.ExceptionBinderName

object QuotesImpl {

Expand Down Expand Up @@ -70,11 +71,10 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
if self.isExprOf[X] then
self.asInstanceOf[scala.quoted.Expr[X]]
else
throw Exception(
s"""Expr cast exception: ${self.show}
|of type: ${reflect.Printer.TypeReprCode.show(reflect.asTerm(self).tpe)}
|did not conform to type: ${reflect.Printer.TypeReprCode.show(reflect.TypeRepr.of[X])}
|""".stripMargin
throw ExprCastException(
expectedType = reflect.Printer.TypeReprCode.show(reflect.TypeRepr.of[X]),
actualType = reflect.Printer.TypeReprCode.show(reflect.asTerm(self).tpe),
exprCode = self.show
)
}
end extension
Expand Down