本文介绍了从Scala宏注释中获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

所以我在一个函数(DefDef)上有一个注释.该注释具有参数.但是,我对如何从构造函数获取参数感到困惑.

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.

用法示例:

class TestMacro {
  @Foo(true)
  def foo(): String = ""
  foo
}

这是注释的代码:

class Foo(b: Boolean) extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro Foo.impl
}

object Foo {
  def impl(c: whitebox.Context)(annottees: c.Tree*): c.Expr[Any] = {
    import c.universe._
    //how do I get value of `b` here???
    c.abort(c.enclosingPosition, "message")
  }
}

推荐答案

这是怎么回事:

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")
  }
}

这篇关于从Scala宏注释中获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:07