如果您想使用具有可选命名参数的静态注释,这是一个显示Federico技术变体的答案。在这种情况下,您需要考虑case匹配语句中可能的调用表达式。可选参数可能是显式命名的,可能是没有名称的,也可能是不存在的。其中的每一个都在编译时显示为
c.prefix.tree
,如下所示。
@compileTimeOnly("Must enable the Scala macro paradise compiler plugin to expand static annotations")
class noop(arg1: Int, arg2: Int = 0) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro AnnotationMacros.noop
}
class AnnotationMacros(val c: whitebox.Context) {
import c.universe._
// an annotation that doesn't do anything:
def noop(annottees: c.Expr[Any]*): c.Expr[Any] = {
// cases for handling optional arguments
val (arg1q, arg2q) = c.prefix.tree match {
case q"new noop($arg1, arg2 = $arg2)" => (arg1, arg2) // user gave named arg2
case q"new noop($arg1, $arg2)" => (arg1, arg2) // arg2 without name
case q"new noop($arg1)" => (arg1, q"0") // arg2 defaulted
case _ => c.abort(c.enclosingPosition, "unexpected annotation pattern!")
}
// print out the values
println(s"arg1= ${evalTree[Int](arg1q)} arg2= ${evalTree[Int](arg2q)}")
// just return the original annotee:
annottees.length match {
case 1 => c.Expr(q"{ ${annottees(0)} }")
case _ => c.abort(c.enclosingPosition, "Only one annottee!")
}
}
def evalTree[T](tree: Tree) = c.eval(c.Expr[T](c.untypecheck(tree.duplicate)))
}
下面是一个示例调用
arg2
,因此它将匹配第一个模式-
case q"new noop($arg1, arg2 = $arg2)"
-以上:
object demo {
// I will match this pattern: case q"new noop($arg1, arg2 = $arg2)"
@noop(1, arg2 = 2)
trait someDeclarationToAnnotate
}
还要注意,由于这些模式的工作方式,您必须在宏代码中显式地提供默认的参数值,这很不幸,但最终计算的类不可用。
作为一个实验,我尝试通过调用
evalTree[scope.of.class.noop](c.prefix.tree)
,但Scala编译器抛出一个错误,因为它认为对注释宏代码中的注释的引用是非法的。