gpt4 book ai didi

Scala 宏 : how to read an annotation object

转载 作者:行者123 更新时间:2023-12-04 18:08:24 27 4
gpt4 key购买 nike

我想做一个和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 = ???

我如何获得值(value) 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 分开了)

最佳答案

在这种情况下:

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

关于Scala 宏 : how to read an annotation object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com