Frage

Edit: I found my mistake - there was an error in the quasiquotes for my recursive case that was causing it to return a malformed sequence


I am trying to create a macro that will turn a case class T into an 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])), where the map's keys are the case class's field names - the idea being that given a JsObject("key" -> JsValue) we can retrieve the appropriate update method from updateMap using the key and then apply the update using the JsValue. I have this working in the non-recursive case, i.e. given a case class that does not have any other case classes as fields. However, I would like to expand this macro so that it can generate an updateMap for case classes that contain other case classes, for example

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

In other words, given updateMap[Outer], I would be able to directly update the object's outerStr field, or else I would be able to update the object's inner.innerStr field, in either case getting back a Try[Outer].

The code works correctly for the non-recursive case (copyMapRec[Inner]()), but the recursive case (copyMapRec[Outer]()) is giving me a "error: missing parameter type" error - I'm assuming that I either need to provide an implicit parameter somewhere or else that I have a fundamental misunderstanding about splicing.

The code below uses a (String) => Try[(T) => T] instead of a (JsValue) => Try[(T) => T] so that I don't need to import the play framework into my REPL. I use implicit conversions to convert the JsValue (or String) into the appropriate type (this occurs in the val x: $fieldType = str line in the base case quasi quotes; if an appropriate implicit conversion isn't available then I get a compiler error).

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]
War es hilfreich?

Lösung

I fixed the problem - originally in my recursiveMethods quasiquotes had innerMap.toSeq(...) instead of innerMap.toSeq.map(...) - I had neglected to test the code in the REPL first

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top