|
| 1 | +import scala.quoted._ |
| 2 | +import scala.tasty.Tasty |
| 3 | + |
| 4 | +case class Xml(parts: String, arg: Any) |
| 5 | + |
| 6 | +class XmlQuote(ctx: StringContext) { |
| 7 | + rewrite def xml(args: => Any*): Xml = ~XmlQuote.impl('(ctx), '(args)) |
| 8 | +} |
| 9 | + |
| 10 | +object XmlQuote { |
| 11 | + implicit rewrite def XmlQuote(ctx: => StringContext): XmlQuote = new XmlQuote(ctx) |
| 12 | + |
| 13 | + def impl(ctx: Expr[StringContext], args: Expr[Seq[Any]])(implicit tasty: Tasty): Expr[Xml] = { |
| 14 | + import tasty._ |
| 15 | + import Term._ |
| 16 | + |
| 17 | + // for debugging purpose |
| 18 | + def pp(tree: Tree): Unit = { |
| 19 | + println(tasty.showSourceCode.showTree(tree)) |
| 20 | + } |
| 21 | + |
| 22 | + def isStringConstant(tree: Term) = tree match { |
| 23 | + case Literal(_) => true |
| 24 | + case _ => false |
| 25 | + } |
| 26 | + |
| 27 | + // _root_.scala.StringContext.apply(("p0", "p1": scala.<repeated>[scala#Predef.String])) |
| 28 | + val parts = ctx.toTasty match { |
| 29 | + case Inlined(_, _, |
| 30 | + Apply( |
| 31 | + Select(Select(Select(Ident("_root_"), "scala", _), "StringContext", _), "apply", _), |
| 32 | + List(Typed(Repeated(values), _)))) if values.forall(isStringConstant) => |
| 33 | + values.collect { case Literal(Constant.String(value)) => value } |
| 34 | + case _ => |
| 35 | + ??? |
| 36 | + } |
| 37 | + |
| 38 | + // (a0, a1: scala.<repeated>[scala.Any]) |
| 39 | + val args0: List[Term] = args.toTasty match { |
| 40 | + case Inlined(_, _, Typed(Repeated(values), _)) => |
| 41 | + values |
| 42 | + case _ => |
| 43 | + ??? |
| 44 | + } |
| 45 | + |
| 46 | + val string = parts.mkString |
| 47 | + // first one for test purpose |
| 48 | + val arg0 = args0.head.toExpr[Any] |
| 49 | + |
| 50 | + '(new Xml(~string.toExpr, ~arg0)) |
| 51 | + } |
| 52 | +} |
0 commit comments