如何使用宏扩展将参数传递给注释

时间:2015-11-30 07:10:44

标签: scala macros scala-macros scala-macro-paradise

我使用macros annotation生成代码。我想根据其他字符串参数更改其行为。因此它会为相同的代码产生不同的结果。我密切关注宏注释指南,仅涵盖最简单的用法。

@myMacros
class MyClass {
}

这就是我现在使用宏的方式。而我想要实现的目标:

@myMacros(name : String)
class MyClass {
}

1 个答案:

答案 0 :(得分:1)

您可以使用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"