斯卡拉宏:如何阅读注释对象 [英] scala macros: how to read an annotation object

查看:227
本文介绍了斯卡拉宏:如何阅读注释对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做类似的事情为<一个href=\"http://stackoverflow.com/questions/17236066/scala-macros-checking-for-a-certain-annotation\">Scala宏:检查一定注释
我的注释是这样的:

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

和我使用的是这样的:

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

我试图让富参数符号,因为它有一个 @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 = ???

我如何获取值名称 @extract 注释

更新

树我从scalaArgs得到显得过于被c.eval无法使用()

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
    }

给出了错误

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

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

推荐答案

在这种情况下:

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

这篇关于斯卡拉宏:如何阅读注释对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆