scala宏:如何读取注释对象

时间:2014-01-03 16:51:02

标签: scala annotations scala-macros

我想做与Scala Macros: Checking for a certain annotation类似的事情 我的注释看起来像:

class extract(val name: String) extends StaticAnnotation

我正在使用它:

case class MainClass(@extract("strings") foo: String, bar: Int)

我正在尝试获取foo参数Symbol,因为它有一个@extract注释:

val extrList = params.map { param: Symbol =>
  param.annotations.collect {
    case extr if extr.tpe  <:< c.weakTypeOf[extract] =>
      val args = extr.scalaArgs
      if (args.size != 1)
        abort("@extract() should have exactly 1 parameter")
      getExtractValue(args.head) -> param
  }
}

getExtractValue方法如下所示:

def getExtractValue(tree: Tree): String = ???

如何获取name注释

的值@extract

更新

我从scalaArgs获得的树似乎无法被c.eval()

使用
param: Symbol =>
    param.annotations.collect {
      case ann if ann.tpe <:< c.weakTypeOf[extract] =>
        val args = ann.scalaArgs
        val arg0 = args.head
        val name: String = c.eval(c.Expr(arg0))
        echo(s"args @extract(name = $name)")
        name -> param
    }

给出错误

[error] exception during macro expansion:
[error] scala.tools.reflect.ToolBoxError: reflective toolbox has failed: cannot
operate on trees that are already typed
[error]         at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.
verify(ToolBoxFactory.scala:74)

完整的堆栈跟踪指向c.eval(我将c.eval与c.Expr分开)

1 个答案:

答案 0 :(得分:7)

在这种情况下:

def getExtractValue(tree: Tree) = tree match {
  case Literal(Constant(str: String)) => str
}