Scala 编写模式匹配宏

Scala 编写模式匹配宏,scala,macros,pattern-matching,scala-macros,Scala,Macros,Pattern Matching,Scala Macros,我需要一些帮助来编写生成模式匹配的宏 就我所知: import scala.reflect.macros.Context import language.experimental.macros trait JsValue object SealedTraitFormat { def writesImpl[A: c.WeakTypeTag](c: Context)(value: c.Expr[A]): c.Expr[JsValue] = { val aTpeW = c.weak

我需要一些帮助来编写生成模式匹配的宏

就我所知:

import scala.reflect.macros.Context
import language.experimental.macros

trait JsValue

object SealedTraitFormat {
  def writesImpl[A: c.WeakTypeTag](c: Context)(value: c.Expr[A]): c.Expr[JsValue] = {
    val aTpeW   = c.weakTypeOf[A]
    val aClazz  = aTpeW.typeSymbol.asClass
    require(aClazz.isSealed, s"Type $aTpeW is not sealed")
    val subs    = aClazz.knownDirectSubclasses
    require(subs.nonEmpty  , s"Type $aTpeW does not have known direct subclasses")
    import c.universe._

    val cases = subs.toList.map { sub =>
      val pat   = Bind(newTermName("x"), Typed(Ident("_"),
        c.reifyRuntimeClass(sub.asClass.toType)))
      val body  = Ident("???") // TODO
      CaseDef(pat, body)
    }
    val m = Match(value.tree, cases)
    c.Expr[JsValue](m)
  }
}
trait SealedTraitFormat[A] {
  def writes(value: A): JsValue = macro SealedTraitFormat.writesImpl[A]
}
以下是一个例子:

sealed trait Foo
case class Bar() extends Foo
case class Baz() extends Foo

object FooFmt extends SealedTraitFormat[Foo] {
  val test = writes(Bar())
}
当前错误为:

[warn] .../FooTest.scala:8: fruitless type test: a value of type play.api.libs.json.Bar cannot also be a Class[play.api.libs.json.Bar]
[warn]   val test = writes(Bar())
[warn]                    ^
[error] .../FooTest.scala:8: pattern type is incompatible with expected type;
[error]  found   : Class[play.api.libs.json.Bar](classOf[play.api.libs.json.Bar])
[error]  required: play.api.libs.json.Bar
[error]   val test = writes(Bar())
[error]                    ^
(注意,
play.api.libs.json
是我的包,所以这是正确的)。我不知道该怎么解释这个错误


展开的宏应该如下所示

def writes(value: Foo): JsValue = value match {
  case x: Bar => ???
  case x: Baz => ???
}

在我看来,它现在可能看起来像
案例x:Class[Bar]=>?
。所以我猜我需要使用
reifyType
而不是
reifyRuntimeClass
。基本上,如何从
类型
中获取树?

以下内容似乎可行,或者至少可以编译:

val cases = subs.toList.map { sub =>
  val pat   = Bind(newTermName("x"), Typed(Ident("_"), Ident(sub.asClass)))
  val body  = reify(???).tree  // TODO
  CaseDef(pat, body)
}

这应该行得通,是的。如果您还有其他问题,请告诉我。