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

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

问题描述

我想做一个类似于 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)

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

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

getExtractValue 方法如下所示:

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

如何获取@extract注解的name

更新

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

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

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