本文將通過 macro 的方式來實現(xiàn)類型類的派生方法的實現(xiàn)。代碼樣例詳見:
derive_macros
1.定義 Equal trait 和 伴生對象
trait Equal[T]:
def equal(x: T, y: T): Boolean
object Equal:
// 比較,以下是根據(jù) inline 的實現(xiàn) signature.
// inline given derived[T]: (m: Mirror.Of[T]) => Eq[T] = ???
// 請注意,由于在后續(xù)階段使用 a type ,因此需要通過使用相應(yīng)的上下文綁定將其提升為 Type 。
given derived[T: Type](using q: Quotes): Expr[Equal[T]] =
和 low level 派生類 derived 方法對比:
//low level
inline given derived[T](using m: Mirror.Of[T]): Equal[T] = ???
//macro level
given derived[T: Type](using q: Quotes): Expr[Equal[T]] =
- low level 直接返回的 Equal[T],而 Macro 返回的則是 Expr 對象。
- macro level 不需要顯示 using Mirror,該信息可以在 quotes 層面獲取到,因此需要 using Quotes。
2.實現(xiàn) derived
代碼核心邏輯分為3步:
- a.從 Quotes 上下文中獲取 Mirror.Of[T] 對象
- b.判斷 Mirror.Of[T] 具體子類,屬于 Mirror.ProductOf 還是 Mirror.SumOf
- c.針對不同的Mirror 類型,實現(xiàn)對應(yīng)的 equals 方法。
given derived[T: Type](using q: Quotes): Expr[Equal[T]] =
//獲取 Mirror
val ev: Expr[Mirror.Of[T]] = Expr.summon[Mirror.Of[T]].get
//判斷 ev 是 Mirror.ProductOf 還是 Mirror.SumOf
ev match
case '{ $m: Mirror.ProductOf[T] {type MirroredElemTypes = elementTypes } } ? {
val elemInstances: List[Expr[Equal[?]]] = summonAll[elementTypes]
val eqProductBody: (Expr[T], Expr[T]) => Expr[Boolean] = (x, y) =>
elemInstances.zipWithIndex.foldLeft(Expr(true: Boolean)) { case (acc, (elem, index)) =>
val e1 = '{$x.asInstanceOf[Product].productElement(${Expr(index)})}
val e2 = '{$y.asInstanceOf[Product].productElement($ {Expr(index)})}
'{$acc && $elem.asInstanceOf[Equal[Any]].equal($e1, $e2)}
}
'{eqProduct((x: T, y: T) => $ {eqProductBody('x, 'y)})}
}
case '{$m: Mirror.SumOf[T] {type MirroredElemTypes = elementTypes}} => {
val elemInstances = summonAll[elementTypes]
val eqSumBody: (Expr[T], Expr[T]) => Expr[Boolean] = (x, y) => {
val ordx = '{$m.ordinal($x)}
val ordy = '{$m.ordinal($y)}
val elements = Expr.ofList(elemInstances)
'{$ordx == $ordy && $elements($ordx).asInstanceOf[Equal[Any]].equal($x, $y)}
}
'{eqSum((x: T, y: T) => $ {eqSumBody('x, 'y)})}
}
上述代碼均有使用到 Splices 和 Quotes 的特性,這塊特性為 Scala3 的全新 Macro 系統(tǒng),以及 TASTY 模型,筆者會在之后的 Macro 篇章進行詳細介紹。
實現(xiàn) summonAll
與 low level 不同的是,此處實現(xiàn) summonAll 采用的也是 Macro 級別的 Splice 和 Quotes,代碼如下:
def summonAll[T: Type](using Quotes): List[Expr[Equal[_]]] =
import quotes.reflect.*
val tpe = TypeRepr.of[T]
println(s"param tpe(typeRepr):" + tpe.show(using Printer.TypeReprCode))
//Quote pattern can only match scrutinees of type scala.quoted.Type
Type.of[T] match
case '[String *: tpes] ? '{summon[Equal[String]]} :: summonAll[tpes]
case '[Int *: tpes] => '{ summon[Equal[Int]] } :: summonAll[tpes]
case '[tpe *: tpes] => derived[tpe] :: summonAll[tpes]
case '[EmptyTuple] => Nil
最終完全代碼見: 完全代碼