我如何引用在Scala宏中包含"this"?

Raf*_*ira 9 macros scala scala-2.10 scala-macros

从一个更大的例子中提取的下面的宏应该创建一个只有对以下内容的引用的树this:

def echoThisImpl(c:Context): c.Expr[Any] = {
  import c.universe._

  val selfTree = This(c.enclosingClass.symbol)
  c.Expr[AnyRef](selfTree)
}

def echoThis: Any = macro CallMacro.echoThisImpl
Run Code Online (Sandbox Code Playgroud)

然而,对于一个呼叫echoThis

object Testing extends App {
  val thisValue = CallMacro.echoThis
  println(thisValue)
}
Run Code Online (Sandbox Code Playgroud)

无法使用消息进行编译

[error] /home/rafael/dev/scala/goose/goose-macros/src/test/scala/Testing.scala:8: type mismatch;
[error]  found   : <noprefix>
[error]  required: Any
[error]   val thisValue = CallMacro.echoThis
Run Code Online (Sandbox Code Playgroud)

如果我设置-Ymacro-debug-lite标志,则生成的树是This(newTermName("<local Testing>")).

Eug*_*ako 10

有两种方法可以达到你想要的效果:

1)使用This(tpnme.EMPTY).目前这不编译,所以你必须使用This(newTypeName("")),但在RC1这将是固定的.

2)使用This(c.enclosingClass.symbol.asModule.moduleClass).目前这不起作用,因为https://issues.scala-lang.org/browse/SI-6394,但在RC1中这将是固定的.