如何使用宏扩展将参数传递给注释
How to pass parameters to annotation with macro expansions
我正在使用 macros annotation 生成代码。我想根据其他字符串参数更改其行为。所以它会为相同的代码产生不同的结果。我严格遵循了仅涵盖最简单用法的宏注释指南。
@myMacros
class MyClass {
}
这就是我现在使用 macroses 的方式。我想达到的目标:
@myMacros(name : String)
class MyClass {
}
你可以使用 macroApplication
class AnnotationPassVal(val name: String) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro AnnotationPassValImpl.apply
}
class AnnotationPassValImpl(val c: Context) {
import c.universe._
def showInfo(s: String) =
c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true)
def apply(annottees: c.Expr[Any]*) = {
val a = c.macroApplication
//look macroApplication is what
showInfo(show(a))
val AnnotationName: Tree = a match {
case q"new AnnotationPassVal(name = $name).macroTransform(..$a)" =>
name: Tree
}
showInfo(show(AnnotationName))
q"""{..$annottees}"""
}
}
测试
@AnnotationPassVal(name = "hello")
class AnnotationPassValTest //when show info "hello"
我正在使用 macros annotation 生成代码。我想根据其他字符串参数更改其行为。所以它会为相同的代码产生不同的结果。我严格遵循了仅涵盖最简单用法的宏注释指南。
@myMacros
class MyClass {
}
这就是我现在使用 macroses 的方式。我想达到的目标:
@myMacros(name : String)
class MyClass {
}
你可以使用 macroApplication
class AnnotationPassVal(val name: String) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro AnnotationPassValImpl.apply
}
class AnnotationPassValImpl(val c: Context) {
import c.universe._
def showInfo(s: String) =
c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true)
def apply(annottees: c.Expr[Any]*) = {
val a = c.macroApplication
//look macroApplication is what
showInfo(show(a))
val AnnotationName: Tree = a match {
case q"new AnnotationPassVal(name = $name).macroTransform(..$a)" =>
name: Tree
}
showInfo(show(AnnotationName))
q"""{..$annottees}"""
}
}
测试
@AnnotationPassVal(name = "hello")
class AnnotationPassValTest //when show info "hello"