?? Scala3 Macro 實現(xiàn) Type Class Derivation

本文將通過 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

最終完全代碼見: 完全代碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容