scala macros: how to read an annotation object

本秂侑毒 提交于 2019-12-10 14:14:04

问题


I want to do a similar thing as Scala Macros: Checking for a certain annotation My annotation looks like:

class extract(val name: String) extends StaticAnnotation

And I'm using it like this:

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

I'm trying to get foo parameter Symbol because it has an @extract annotation:

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
  }
}

The getExtractValue method looks like this:

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

How do I get the value name of the @extract annotation

Update

The Tree I get from scalaArgs seems too be unusable by 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
    }

Gives the error

[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)

the full stacktrace points to c.eval (I separated c.eval and c.Expr)


回答1:


In this case:

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


来源:https://stackoverflow.com/questions/20908671/scala-macros-how-to-read-an-annotation-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!