用Scalameta提升弦

时间:2017-12-26 15:37:25

标签: scala scala-quasiquotes scala-meta quasiquotes

我想注入一个方法'toCSV'来将一个类解析成CSV String。我的功能有两个参数:

  • Seq [String]:header
  • Seq [Seq [Any]]:fields

我的宏:

class model extends scala.annotation.StaticAnnotation {

  inline def apply(defn: Any): Any = meta {
    defn match {
      case cls @ Defn.Class(_, _, _, Ctor.Primary(_, _, paramss), template) =>

        def createToCSV(paramss: Seq[Seq[Term.Param]]): Defn.Def = {

          val names = paramss.flatten.map(param => param.name.syntax)
          val fields = paramss.map(_.map(param => Term.Name(param.name.value)))

          q"""def toCSV =
             CSVTools.toCSV(Seq(...$names), Seq(Seq(...$fields)))"""
        }

        val toCSVImpl = createToCSV(paramss)

        val templateStats: Seq[Stat] = toCSVImpl +: template.stats.getOrElse(Nil)
        cls.copy(templ = template.copy(stats = Some(templateStats)))
      case _ =>
        println(defn.structure)
        abort("@model must annotate a class.")
    }
  }
}

变量Term是Seq [String],quasiquotes语法只接受Term。 因此,发生以下错误:

[error] /home/xxxxx/intellij/workspace/heroes-scala-meta/macros/src/main/scala/examples/model.scala:18: type mismatch when unquoting;
[error]  found   : scala.collection.immutable.Seq[String]
[error]  required: scala.collection.immutable.Seq[scala.collection.immutable.Seq[scala.meta.Term.Arg]]
[error]              CSVTools.toCSV(Seq(...$names), Seq(Seq(...$fields)))"""
[error]                                    ^
[error] one error found
[error] (macros/compile:compileIncremental) Compilation failed

你有解决方案吗?

提前感谢,

1 个答案:

答案 0 :(得分:1)

这可能有点hacky但似乎有效:明确将names映射到字符串文字

class model extends scala.annotation.StaticAnnotation {

  inline def apply(defn: Any): Any = meta {
    defn match {
      case cls@Defn.Class(_, _, _, Ctor.Primary(_, _, paramss), template) =>

        def createToCSV(paramss: Seq[Seq[Term.Param]]): Defn.Def = {

          val names: Seq[String] = paramss.flatten.map(param => param.name.syntax)
          val fields = paramss.map(_.map(param => Term.Name(param.name.value)))

          val nameLiterals: Seq[Lit.String] = names.map(n => q"$n".asInstanceOf[Lit.String])

          q"""def toCSV =
              CSVTools.toCSV(scala.collection.immutable.Seq(..$nameLiterals),
                             scala.collection.immutable.Seq(scala.collection.immutable.Seq(...$fields)))"""
        }

        val toCSVImpl = createToCSV(paramss)

        val templateStats: Seq[Stat] = toCSVImpl +: template.stats.getOrElse(Nil)
        cls.copy(templ = template.copy(stats = Some(templateStats)))
      case _ =>
        println(defn.structure)
        abort("@model must annotate a class.")
    }
  }
}