Getting Parameters from Scala Macro Annotation

后端 未结 2 771
灰色年华
灰色年华 2020-12-06 06:38

So I have an annotation on a function (DefDef). This annotation has parameters. However, I am confused on how to get the parameters from the constructor.

Usage exa

2条回答
  •  春和景丽
    2020-12-06 07:14

    What about this:

    val b: Boolean = c.prefix.tree match {
        case q"new Foo($b)" => c.eval[Boolean](c.Expr(b))
    }
    

    For sake of completeness this is the full source:

    import scala.reflect.macros.Context
    import scala.language.experimental.macros
    import scala.annotation.StaticAnnotation
    import scala.annotation.compileTimeOnly
    import scala.reflect.api.Trees
    import scala.reflect.runtime.universe._
    
    class Foo(b: Boolean) extends StaticAnnotation {
      def macroTransform(annottees: Any*) :Any = macro FooMacro.impl
    }
    
    object FooMacro {
      def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
        import c.universe._
        val b: Boolean = c.prefix.tree match {
            case q"new Foo($b)" => c.eval[Boolean](c.Expr(b))
        }
        c.abort(c.enclosingPosition, "message")
      }
    }
    

提交回复
热议问题