将参数传递给scalameta天堂宏

时间:2017-12-25 15:50:17

标签: scala macros scala-macros scala-meta

我正在尝试创建一个宏注释,但我需要传递它的参数。

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已经删除了注释 - 因此我无法从那里获取参数。此外,param1param2字段无法通过apply方法访问,因为它已内联。

你能指点我使用scala meta克服这个问题的最简单方法吗?我想过使用两个注释

@ToPojo
@ToPojoParams("p1", "p2")
case class Entity(a: Int, m: Map[Long, Boolean])

但那很丑陋和丑陋。

非常感谢

1 个答案:

答案 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)
    })
  }
}