以下是使用2.10.0-M6版本的宏的工作示例:
(更新:要使此示例在2.10.0-M7中工作,您需要将c.TypeTag替换为c.AbsTypeTag; 要使此示例在2.10.0-RC1中工作,需要将c.AbsTypeTag替换为c.WeakTypeTag)
import scala.reflect.makro.Context
object SealednessMacros {
def exhaustive[P](ps: Seq[P]): Seq[P] = macro exhaustive_impl[P]
def exhaustive_impl[P: c.TypeTag](c: Context)(ps: c.Expr[Seq[P]]) = {
import c.universe._
val symbol = typeOf[P].typeSymbol
val seen = ps.tree match {
case Apply(_, xs) => xs.map {
case Select(_, name) => symbol.owner.typeSignature.member(name)
case _ => throw new Exception("Can't check this expression!")
}
case _ => throw new Exception("Can't check this expression!")
}
val internal = symbol.asInstanceOf[scala.reflect.internal.Symbols#Symbol]
if (!internal.isSealed) throw new Exception("This isn't a sealed type.")
val descendants = internal.sealedDescendants.map(_.asInstanceOf[Symbol])
val objs = (descendants - symbol).map(
s => s.owner.typeSignature.member(s.name.toTermName)
)
if (seen.toSet == objs) ps else throw new Exception("Not exhaustive!")
}
}
很明显,这个方案不够健壮(例如,它假设你的层次结构中只有对象,并且在 A :: B :: C :: Nil
上会失败),仍然需要一些不愉快的强制转换,但作为一个快速概念验证,它是有效的。
首先,我们启用宏编译此文件:
scalac -language:experimental.macros SealednessMacros.scala
现在,如果我们尝试编译像这样的文件:
object MyADT {
sealed trait Parent
case object A extends Parent
case object B extends Parent
case object C extends Parent
}
object Test extends App {
import MyADT._
import SealednessMacros._
exhaustive[Parent](Seq(A, B, C))
exhaustive[Parent](Seq(C, A, B))
exhaustive[Parent](Seq(A, B))
}
如果缺少 C
,我们在带有 Seq
的编译时会出现错误:
Test.scala:14: error: exception during macro expansion:
java.lang.Exception: Not exhaustive!
at SealednessMacros$.exhaustive_impl(SealednessMacros.scala:29)
exhaustive[Parent](Seq(A, B))
^
one error found
请注意,我们需要通过显式类型参数指示父级来帮助编译器。