用Scalameta举起字符串



我想注入一个方法'tocsv'将类解析为CSV字符串。我的功能需要两个参数:

  • seq [string]:标题
  • seq [seq [any]]:字段

我的宏:

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

变量术语是一个seq [string],而Quasiquotes语法仅接受术语。因此,下面发生了以下错误:

[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

您有解决方案吗?

预先感谢

这可能有点黑,但似乎有效:明确将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.")
    }
  }
}

相关内容

  • 没有找到相关文章

最新更新