簡體   English   中英

編寫模式匹配宏

[英]Writing a pattern matching macro

我需要一些幫助來編寫一個產生模式匹配的宏。

這是我得到的:

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 => ???
}

在我看來,它可能看起來像case x: Class[Bar] => ??? 現在。 所以我的猜測是我需要使用reifyType而不是reifyRuntimeClass 基本上,我如何從Type獲取樹?

以下似乎工作,或至少編譯:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM