有没有办法在我的宏中使用宏实现代码进行“f”字符串插值?

时间:2013-06-12 15:32:18

标签: scala macros scala-2.10

目前,我尝试过以下操作:

def macroImpl(cx: Context)(...) = {
  new MacroImplementations { val c = cx }
}

但它抱怨c中的MacroImplementations类型为scala.reflect.macros.runtime.Context,而cx类型为scala.reflect.macros.Context

这两种情境之间有什么区别?

1 个答案:

答案 0 :(得分:0)

我最终得到了以下解决方案 - 它非常难看,但它确实有效:

import scala.language.experimental.macros
import scala.reflect.macros.Context
import scala.reflect.macros.runtime.{Context => ContextR}
import scala.tools.reflect.MacroImplementations


def putfImpl(cx: Context)(args: cx.Expr[Any]*): cx.Expr[Unit] = {
  val cx2 = cx.asInstanceOf[ContextR]
  val args2 = args.toList.asInstanceOf[List[cx2.Expr[Any]]]
  import cx2.universe._
  val Apply(_, List(Apply(_, partsE))) = cx2.prefix.tree
  val mi = new { val c : cx2.type = cx2 } with MacroImplementations
  val res = mi.macro_StringInterpolation_f(partsE, args2.map(_.tree), cx2.enclosingPosition)
  reify(println(cx2.Expr[String](res).splice)).asInstanceOf[cx.Expr[Unit]]
}