我正在尝试使用宏创建一个匹配语句,该语句匹配给定类型的所有子类。但是我在提取案例类的字段值时遇到问题。例如:
sealed abstract class Foobar
case class Foo(x:Int,f:Foobar) extends Foobar
case class Bar(s:String, f:Foobar) extends Foobar
现在我想创建如下所示的代码,当给出 Foobar 时:
e1 match {
case Foo(args) => args.toString
case Bar(args) => args.toString
}
这就是我到目前为止得到的:
def eqImpl[A: c.WeakTypeTag](c: Context)(e1: c.Expr[A], e2: c.Expr[A]): c.Expr[Boolean] = {
import c.universe._
val tpe = c.weakTypeOf[A].typeSymbol.asClass
tpe.typeSignature // SI-7046
val subclasses = tpe.knownDirectSubclasses
val cases =
subclasses.map{ clazz =>
cq"x: $clazz => x "
}
println(cases)
reify(true)
}
此代码将匹配 Foo 和 Bar,但我无法提取我需要在右侧的字段。
所以我让它大部分工作,这里有一个例子:
def eqImpl[A: c.WeakTypeTag](c: Context)(e1: c.Expr[A], e2: c.Expr[A]): c.Expr[Boolean] = {
import c.universe._
val tpe = c.weakTypeOf[A].typeSymbol.asClass
tpe.typeSignature // SI-7046 workaround
val subclasses = tpe.knownDirectSubclasses
val cases =
subclasses.map{ case clazz : ClassSymbol =>
require (clazz.isCaseClass)
val name = clazz.companionSymbol.name
val fields = clazz.typeSignature.declarations.collect {
case m: MethodSymbol if m.isCaseAccessor => m.name}
//pattern for the fields of the left and right side side
val lFields = fields.map{ m => pq"""${m+"L":TermName}"""}
val rFields = fields.map{ m => pq"""${m+"R":TermName}"""} side
//right hand side of the case statment
val eqFields =
fields.map{ m => q"""${m+"R":TermName} == ${m+"L":TermName}"""}.reduce[Tree]{
case (acc,n) => q"$acc && $n"}
cq"($name(..$lFields),$name(..$rFields)) => $eqFields "
}
val matchStmt = q"""Tuple2[$tpe,$tpe]($e1,$e2) match {
case ..$cases
case _ => false }"""
c.Expr[Boolean](matchStmt)
}
}
此代码创建一个匹配元组的匹配语句。如果元组的两边都是同一案例类的实例,则比较字段。如果所有字段相等,则返回 True。我知道这不是一个特别现实的例子,但我希望它有所帮助。对于问题中的示例,这将生成:
Tuple2[Foobar,Foobar](e1,e2) match {
case (Foo(xL,fL),Foo(xR,fR) => xL == xR && fL == fR
case (Bar(sL,fL),Bar(sR,fR) => sL == sR && fL == fR
case _ => false
}