Scala递归宏?

时间:2015-03-03 07:13:26

标签: scala scala-macros lenses scala-macro-paradise scala-meta

我想知道Scala是否支持递归宏扩展,例如我trying to write a lens library使用镜头宏来执行此操作:

case class C(d: Int)
case class B(c: C)
case class A(b: B)

val a = A(B(C(10))
val aa = lens(a)(_.b.c.d)(_ + 12)
assert(aa.b.c.d == 22)

鉴于lens(a)(_.b.c.d)(f),我想将其转换为a.copy(b = lens(a.b)(_.c.d)(f))

编辑: I made some decent progress here

但是,我无法找出从List[TermName]创建访问者的通用方法,例如对于上面的例子,假设我有List(TermName('b'), TermName('c'), TermName('d'))),我想生成一个匿名函数_.b.c.d,即(x: A) => x.b.c.d。我该怎么做?

基本上,我如何以通用方式编写these lines

1 个答案:

答案 0 :(得分:2)

实际上我设法让它发挥作用:https://github.com/pathikrit/sauron/blob/master/src/main/scala/com/github/pathikrit/sauron/package.scala

以下是完整的来源:

package com.github.pathikrit

import scala.reflect.macros.blackbox

package object sauron {

  def lens[A, B](obj: A)(path: A => B)(modifier: B => B): A = macro lensImpl[A, B]

  def lensImpl[A, B](c: blackbox.Context)(obj: c.Expr[A])(path: c.Expr[A => B])(modifier: c.Expr[B => B]): c.Tree = {
    import c.universe._

    def split(accessor: c.Tree): List[c.TermName] = accessor match {    // (_.p.q.r) -> List(p, q, r)
      case q"$pq.$r" => split(pq) :+ r
      case _: Ident => Nil
      case _ => c.abort(c.enclosingPosition, s"Unsupported path element: $accessor")
    }

    def join(pathTerms: List[TermName]): c.Tree = (q"(x => x)" /: pathTerms) {    // List(p, q, r) -> (_.p.q.r)
      case (q"($arg) => $pq", r) => q"($arg) => $pq.$r"
    }

    path.tree match {
      case q"($_) => $accessor" => split(accessor) match {
        case p :: ps => q"$obj.copy($p = lens($obj.$p)(${join(ps)})($modifier))"  // lens(a)(_.b.c)(f) = a.copy(b = lens(a.b)(_.c)(f))
        case Nil => q"$modifier($obj)"                                            // lens(x)(_)(f) = f(x)
      }
      case _ => c.abort(c.enclosingPosition, s"Path must have shape: _.a.b.c.(...), got: ${path.tree}")
    }
  }
}

而且,是的,Scala会递归地应用相同的宏。