Skip to content

Commit 3c46a50

Browse files
Backport "Improve asExprOf cast error formatting" to LTS (#20787)
Backports #19195 to the LTS branch. PR submitted by the release tooling. [skip ci]
2 parents 50d380e + 09061ce commit 3c46a50

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package scala.quoted.runtime.impl
2+
3+
import dotty.tools.dotc.ast.tpd.Tree
4+
import dotty.tools.dotc.core.Contexts.*
5+
6+
class ExprCastException(msg: String) extends Exception(msg)
7+
8+
9+
object ExprCastException:
10+
def apply(expectedType: String, actualType: String, exprCode: String): ExprCastException =
11+
new ExprCastException(
12+
s"""|
13+
| Expected type: ${formatLines(expectedType)}
14+
| Actual type: ${formatLines(actualType)}
15+
| Expression: ${formatLines(exprCode)}
16+
|""".stripMargin)
17+
18+
private def formatLines(str: String): String =
19+
if !str.contains("\n") then str
20+
else str.linesIterator.mkString("\n ", "\n ", "\n")

compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import scala.quoted.runtime.{QuoteUnpickler, QuoteMatching}
2222
import scala.quoted.runtime.impl.printers.*
2323

2424
import scala.reflect.TypeTest
25+
import dotty.tools.dotc.core.NameKinds.ExceptionBinderName
2526

2627
object QuotesImpl {
2728

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

0 commit comments

Comments
 (0)