我可以在要注释的变量(val / var)的主体中访问注释的自变量的值吗?

时间:2019-06-11 15:15:19

标签: scala macros annotations var scala-macros

在我的项目中,程序员可以通过以下方式将类的某些字段注释为预测

class Foo() {
  @prediction('p1) var quality = // access 'p1 here
}

在预测注释的定义中给出了一个符号,该符号表示其ID(在这种情况下, quality 的ID为'p1 )。

我的问题:我想在实现 quality 变量时访问该Symbol的值。我认为可以通过使用宏来实现,但我无法实现。

我的问题:如何实现此目的(允许使用宏)?

1 个答案:

答案 0 :(得分:2)

是的,可以。尝试将prediction设为macro annotation

class Foo() {
  @prediction('p1) var quality = {
    println(access) //'p1
  }
}

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.whitebox

@compileTimeOnly("enable macro paradise to expand macro annotations")
class prediction(s: Symbol) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro predictionMacro.impl
}

object predictionMacro {
  def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._
    val symb = c.prefix.tree match {
      case q"new prediction($s)" => s
    }
    annottees match {
      case q"$mods var $tname: $tpt = $expr" :: _ =>
        q"""$mods var $tname: $tpt = {
            val access = $symb
            $expr
          }"""
    }
  }
}