|
| 1 | +import scala.quoted._ |
| 2 | + |
| 3 | +object Test { |
| 4 | + |
| 5 | + implicit val toolbox: scala.quoted.Toolbox = scala.quoted.Toolbox.make(getClass.getClassLoader) |
| 6 | + |
| 7 | + def main(args: Array[String]): Unit = withQuoteContext { |
| 8 | + |
| 9 | + implicit def ValueOfExprInt: ValueOfExpr[Int] = new { |
| 10 | + def apply(n: Expr[Int]) given QuoteContext: Option[Int] = n match { |
| 11 | + case '{ 0 } => Some(0) |
| 12 | + case '{ 1 } => Some(1) |
| 13 | + case '{ 2 } => Some(1) |
| 14 | + case _ => None |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + implicit def ValueOfExprBoolean: ValueOfExpr[Boolean] = new ValueOfExpr[Boolean] { |
| 19 | + def apply(b: Expr[Boolean]) given QuoteContext: Option[Boolean] = b match { |
| 20 | + case '{ true } => Some(true) |
| 21 | + case '{ false } => Some(false) |
| 22 | + case _ => None |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + implicit def ValueOfExprList[T: ValueOfExpr: Type]: ValueOfExpr[List[T]] = new { |
| 27 | + def apply(xs: Expr[List[T]]) given QuoteContext: Option[List[T]] = (xs: Expr[Any]) match { |
| 28 | + case '{ ($xs1: List[T]).::($x) } => |
| 29 | + for { head <- x.getValue; tail <- xs1.getValue } |
| 30 | + yield head :: tail |
| 31 | + case '{ Nil } => Some(Nil) |
| 32 | + case _ => None |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + implicit def ValueOfExprOption[T: ValueOfExpr: Type]: ValueOfExpr[Option[T]] = new { |
| 37 | + def apply(expr: Expr[Option[T]]) given QuoteContext: Option[Option[T]] = expr match { |
| 38 | + case '{ Some[T]($x) } => for (v <- x.getValue) yield Some(v) |
| 39 | + case '{ None } => Some(None) |
| 40 | + case _ => None |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + println(('{0}).getValue) |
| 45 | + println(('{1}).getValue) |
| 46 | + println(('{ println(); 1 }).getValue) |
| 47 | + |
| 48 | + println(('{true}).getValue) |
| 49 | + println(('{false}).getValue) |
| 50 | + println(('{ println(); false }).getValue) |
| 51 | + |
| 52 | + println(('{ Nil }: Expr[List[String]]).getValue) |
| 53 | + println(('{ "a" :: "b" :: "c" :: Nil }: Expr[List[String]]).getValue) |
| 54 | + |
| 55 | + println(('{ None }: Expr[Option[Int]]).getValue) |
| 56 | + println(('{ Some("abc") }: Expr[Option[String]]).getValue) |
| 57 | + |
| 58 | + } |
| 59 | +} |
0 commit comments