Skip to content

Commit 067cc79

Browse files
Merge pull request #10583 from dotty-staging/path-const-extractor
Patch implementation of `Const.unapply`
2 parents 52e539c + 941410d commit 067cc79

File tree

4 files changed

+18
-4
lines changed

4 files changed

+18
-4
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) if c.value != null => 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

tests/run-staging/unliftables.check

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ Some(Some(3))
3838
Some(None)
3939
Some(Some(3))
4040
Some(Some(3))
41-
Some(None)
41+
None
4242

4343
Some(Left(1))
4444
Some(Right(2))

0 commit comments

Comments
 (0)