Scala macros Type or Symbol lifted

2019-09-06 18:59发布

I'm trying to use the fields of a type in a macro, and pass the symbol or typesigs for the fields to a method so I can do some operations that require concrete information about the type.

I have code like this (played about with variations):

object Macros {

  import scala.reflect.runtime.universe._

  def foo(t: Symbol) : String = t.name.decoded

  def materializeWriterImpl[T: c.WeakTypeTag](c: Context): c.Expr[List[String]] = {
    import c.universe._

    val tpe = weakTypeOf[T]

    val fields = tpe.declarations.collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor => m
    }.get.paramss.head

    c.Expr[List[String]] { q"""
      val q = $fields
      val names = q.map(Macros.foo)
      List(names)
    """
    }
  }
}

The error I get is

Error:(53, 24) Can't unquote List[c.universe.Symbol], consider using .. or providing an implicit instance of Liftable[List[c.universe.Symbol]] val names = foo($fields) ^

So, perhaps its not possible to lift symbol / type using qquotes. But I can see methods to do this in StandardLiftableApi:

implicit def liftScalaSymbol : U#Liftable[scala.Symbol]
implicit def liftType[T <: U#Type] : U#Liftable[T]

I can get this working if I pass strings, just as a test, but I really need something more substantial passed out.

1条回答
等我变得足够好
2楼-- · 2019-09-06 19:41

Following your comments about what you're actually trying to achieve, here's a rather comprehensive example that shows how to generate schemas (for a totally made up schema description language).

import scala.language.experimental.macros
import scala.reflect.macros._

implicit class Schema[T](val value: String) extends AnyVal {
  override def toString = value
}; object Schema {
  implicit val intSchema: Schema[Int] = "int"
  implicit val floatSchema: Schema[Float] = "float"
  implicit val stringSchema: Schema[String] = "string"
  // ... and so on for all the base types you need to support

  implicit def optionSchema[T:Schema]: Schema[Option[T]] = "optional[" + implicitly[Schema[T]] + "]"
  implicit def listSchema[T:Schema]: Schema[List[T]] = "list_of[" + implicitly[Schema[T]] + "]"
  implicit def classSchema[T]: Schema[T] = macro classSchema_impl[T]

  def classSchema_impl[T:c.WeakTypeTag](c: Context): c.Expr[Schema[T]] = {
    import c.universe._
    val T = weakTypeOf[T]
    val fields = T.declarations.collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor => m
    }.get.paramss.head
    val fieldSchemaPartTrees: Seq[Tree] = fields.map{ f =>
      q"""${f.name.decoded} + ": " + implicitly[Schema[${f.typeSignature}]]"""
    }
    c.Expr[Schema[T]](q"""
      new Schema[$T](
        "{" +
        Seq(..$fieldSchemaPartTrees).mkString(", ") +
        "}"
      )
    """)
  }
}

And some REPL test:

scala> case class Foo(ab: Option[String], cd: Int)
defined class Foo

scala> case class Bar(ef: List[Foo], gh: Float)
defined class Bar

scala> implicitly[Schema[Bar]]
res7: Schema[Bar] = {ef: list_of[{ab: optional[string], cd: int}], gh: float}
查看更多
登录 后发表回答