Skip to content

Commit 693b818

Browse files
committed
Patch implementation of Const.unapply
* Make sure the extrators does not match classes. This should be done using reflection. * Do not match `'{null}` to avoid accidental NPEs. * Do not match `'{}` as there is no value to extract. ```diff - case Const(null) => + case '{null} => - case Const(()) => + case '{} => ``` We specialize use the old, faster, implemtation for `Unliftable` as there it it correct by construction of the available `Unliftable`s.
1 parent 8a3f063 commit 693b818

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

library/src-bootstrapped/scala/quoted/Unliftable.scala

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,16 @@ object Unliftable {
8080

8181
/** Lift a quoted primitive value `'{ x }` into `x` */
8282
private class PrimitiveUnliftable[T <: Int | Boolean | Byte | Short | Int | Long | Float | Double | Char | String] extends Unliftable[T] {
83-
def fromExpr(x: Expr[T]) = Const.unapply(x)
83+
def fromExpr(expr: Expr[T]) =
84+
import quotes.reflect._
85+
def rec(tree: Term): Option[T] = tree match {
86+
case Literal(c) => Some(c.value.asInstanceOf[T])
87+
case Block(Nil, e) => rec(e)
88+
case Typed(e, _) => rec(e)
89+
case Inlined(_, Nil, e) => rec(e)
90+
case _ => None
91+
}
92+
rec(Term.of(expr))
8493
}
8594

8695
/** Default unliftable for Option

library/src/scala/quoted/Const.scala

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,12 @@ object Const {
2121
def unapply[T](expr: Expr[T])(using Quotes): Option[T] = {
2222
import quotes.reflect._
2323
def rec(tree: Term): Option[T] = tree match {
24-
case Literal(c) => Some(c.value.asInstanceOf[T])
24+
case Literal(c) =>
25+
c match
26+
case Constant.Null() => None
27+
case Constant.Unit() => None
28+
case Constant.ClassOf(_) => None
29+
case _ => Some(c.value.asInstanceOf[T])
2530
case Block(Nil, e) => rec(e)
2631
case Typed(e, _) => rec(e)
2732
case Inlined(_, Nil, e) => rec(e)

tests/run-macros/tasty-extractors-constants-1/quoted_1.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ object Macros {
1414
Expr(3) match { case Const(n) => stagedPrintln(n) }
1515
'{4} match { case Const(n) => stagedPrintln(n) }
1616
'{"abc"} match { case Const(n) => stagedPrintln(n) }
17-
'{null} match { case Const(n) => stagedPrintln(n) }
17+
'{null} match { case '{null} => stagedPrintln(null) }
1818

1919
'{new Object} match { case Const(n) => println(n); case _ => stagedPrintln("OK") }
2020

0 commit comments

Comments
 (0)