我正在尝试创建一个宏注释,但我需要传递它的参数。
class ToPojo(param1: String, param2: String) extends StaticAnnotation {
inline def apply(defn: Any): Any = meta {
...
}
}
用作
@ToPojo("p1", "p2")
case class Entity(a: Int, m: Map[Long, Boolean])
上述代码存在的问题是,Entity
已被apply
作为defn
已经删除了注释 - 因此我无法从那里获取参数。此外,param1
和param2
字段无法通过apply
方法访问,因为它已内联。
你能指点我使用scala meta克服这个问题的最简单方法吗?我想过使用两个注释
@ToPojo
@ToPojoParams("p1", "p2")
case class Entity(a: Int, m: Map[Long, Boolean])
但那很丑陋和丑陋。
非常感谢
答案 0 :(得分:1)
如How do I pass an argument to the macro annotation?部分
下的ScalaMeta Paradise说明中所述您在
this
上匹配Scalameta树
package scalaworld.macros
import scala.meta._
class Argument(arg: Int) extends scala.annotation.StaticAnnotation {
inline def apply(defn: Any): Any = meta {
// `this` is a scala.meta tree.
println(this.structure)
val arg = this match {
// The argument needs to be a literal like `1` or a string like `"foobar"`.
// You can't pass in a variable name.
case q"new $_(${Lit.Int(arg)})" => arg
// Example if you have more than one argument.
case q"new $_(${Lit.Int(arg)}, ${Lit.String(foo)})" => arg
case _ => ??? // default value
}
println(s"Arg is $arg")
defn.asInstanceOf[Stat]
}
}
请注意,此代码有点天真并且不处理命名参数。如果你有很多参数,那么编写通常命名和命名参数的所有可能组合都很无聊。所以你可以尝试这样的事情:
package examples
import scala.collection.immutable
import scala.meta._
class MyMacro(p1: String, p2: Int) extends scala.annotation.StaticAnnotation {
inline def apply(defn: Any): Any = meta {
val params = Params.extractParams(this)
//some implementation
...
}
}
case class Params(p1: String, p2: Int) {
def update(name: String, value: Any): Params = name match {
case "p1" => copy(p1 = value.asInstanceOf[String])
case "p2" => copy(p2 = value.asInstanceOf[Int])
case _ => ???
}
}
object Params {
private val paramsNames = List("p1", "p2")
def extractParams(tree: Stat): Params = {
val args: immutable.Seq[Term.Arg] = tree.asInstanceOf[Term.New].templ.parents.head.asInstanceOf[Term.Apply].args
args.zipWithIndex.foldLeft(Params(null, 0))((acc, argAndIndex) => argAndIndex._1 match {
case q"${Lit(value)}" => acc.update(paramsNames(argAndIndex._2), value)
case q"${Term.Arg.Named(name, Lit(value))}" => acc.update(name.value, value)
})
}
}