宏拼接期间出现“错误:缺少参数类型”

时间:2014-01-18 17:35:31

标签: scala implicit scala-macros

编辑:我发现了我的错误 - 我的递归案例的quasiquotes中出现错误导致它返回格式错误的序列


我正在尝试创建一个将案例类T转换为updateMap: Map[String, (play.api.libs.json.JsValue) => Try[(T) => T]]How to use scala macros to create a function object (to create a Map[String, (T) => T]))的宏,其中地图的键是案例类的字段名称 - 这个想法是给定JsObject("key" -> JsValue)后,我们可以使用updateMapkey检索相应的更新方法,然后使用JsValue应用更新。我在非递归的情况下工作,即给定一个没有任何其他案例类作为字段的案例类。但是,我想扩展这个宏,以便它可以为包含其他案例类的案例类生成updateMap,例如

case class Inner(innerStr: String)
case class Outer(outerStr: String, inner: Inner)

updateMap[Outer] = {
  // updateMap[Inner]
  val innerMap = Map("innerStr" -> (str: String) => 
    Try { (i: Inner) => i.copy(innerStr = str) } )

  // updateMap[Outer]
  Map("outerStr" -> (str: String) => 
    Try { (o: Outer) => o.copy(outerStr = str) },
  "inner.innerStr" -> (str: String) => 
    Try { (o: Outer) => innerMap.get("innerStr").get(str).flatMap(lens => o.copy(inner = lens(o.inner))) })}

换句话说,给定updateMap[Outer],我可以直接更新对象的outerStr字段,否则我将能够更新对象的inner.innerStr字段,在任何一种情况下取回Try[Outer]

代码适用于非递归情况(copyMapRec[Inner]()),但递归情况(copyMapRec[Outer]())给我一个“错误:缺少参数类型”错误 - 我假设我需要在某处提供隐式参数,否则我对拼接有一个基本的误解。

下面的代码使用(String) => Try[(T) => T]而不是(JsValue) => Try[(T) => T],因此我无需将播放框架导入到我的REPL中。我使用隐式转换将JsValue(或String)转换为适当的类型(这发生在基本情况准引号的val x: $fieldType = str行中;如果没有适当的隐式转换然后我得到编译器错误。)

import scala.language.experimental.macros

def copyMapImplRec[T: c.WeakTypeTag](c: scala.reflect.macros.Context)(blacklist: c.Expr[String]*): c.Expr[Map[String, (String) => scala.util.Try[(T) => T]]] = {
  import c.universe._

  // Fields that should be omitted from the map
  val blacklistList: Seq[String] = blacklist.map(e => c.eval(c.Expr[String](c.resetAllAttrs(e.tree))))

  def rec(tpe: Type): c.Expr[Map[String, (String) => scala.util.Try[(T) => T]]] = {
    val typeName = tpe.typeSymbol.name.decoded

    // All fields in the case class's primary constructor, minus the blacklisted fields
    val fields = tpe.declarations.collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor => m
    }.get.paramss.head.filterNot(field => blacklistList.contains(typeName + "." + field.name.decoded))

    // Split the fields into case classes and non case classes
    val recursive = fields.filter(f => f.typeSignature.typeSymbol.isClass && f.typeSignature.typeSymbol.asClass.isCaseClass)
    val nonRecursive = fields.filterNot(f => f.typeSignature.typeSymbol.isClass && f.typeSignature.typeSymbol.asClass.isCaseClass)

    val recursiveMethods = recursive.map {
      field => {
        val fieldName = field.name
        val fieldNameDecoded = fieldName.decoded
        // Get the c.Expr[Map] for this case class
        val map = rec(field.typeSignature)
        // Construct an "inner.innerStr -> " seq of tuples from the "innerStr -> " seq of tuples
      q"""{
          val innerMap = $map
          innerMap.toSeq.map(tuple => ($fieldNameDecoded + "." + tuple._1) -> {
          (str: String) => {
            val innerUpdate = tuple._2(str)
            innerUpdate.map(innerUpdate => (outer: $tpe) => outer.copy($fieldName = innerUpdate(outer.$fieldName)))
          }
      })}"""
      }
    }

    val nonRecursiveMethods = nonRecursive.map {
      field => {
        val fieldName = field.name
        val fieldNameDecoded = fieldName.decoded
        val fieldType = field.typeSignature
        val fieldTypeName = fieldType.toString
        q"""{
          $fieldNameDecoded -> {
            (str: String) => scala.util.Try {
              val x: $fieldType = str
              (t: $tpe) => t.copy($fieldName = x)
            }.recoverWith {
              case e: Exception => scala.util.Failure(new IllegalArgumentException("Failed to parse " + str + " as " + $typeName + "." + $fieldNameDecoded + ": " + $fieldTypeName))
            }
         }}"""
      }
    }

    // Splice in all of the sequences of tuples, flatten the sequence, and construct a map
    c.Expr[Map[String, (String) => scala.util.Try[(T) => T]]] {
      q"""{ Map((List(..$recursiveMethods).flatten ++ List(..$nonRecursiveMethods)):_*) }"""
    }
  }

  rec(weakTypeOf[T])

}

def copyMapRec[T](blacklist: String*) = macro copyMapImplRec[T]

1 个答案:

答案 0 :(得分:0)

我修复了问题 - 最初在我的recursiveMethods quasiquotes中innerMap.toSeq(...)而不是innerMap.toSeq.map(...) - 我忽略了首先在REPL中测试代码