Macros: path dependent type inference confusion

2020-03-26 05:21发布

问题:

I tried to simplify the creation of ASTs, but got a weird error message:

case class Box(i: Int)
object M {
  import language.experimental.macros
  import scala.reflect.makro.Context
  case class meth(obj: String, method: String)(implicit val c: Context) {
    import c.universe._

    def apply(xs: Tree*) =
      Apply(Select(Ident(obj), newTermName(method)), xs.toList)
  }

  def box(n: Int): Box = macro boxImpl

  def boxImpl(c: Context)(n: c.Expr[Int]): c.Expr[Box] = {
    import c.universe._
    implicit val cc: c.type = c
    n.tree match {
      case arg @ Literal(Constant(_)) =>
        meth("Box", "apply").apply(arg)
    }
  }
}

Error:

<console>:26: error: type mismatch;
 found   : c.universe.Literal
 required: _2.c.universe.Tree where val _2: M.meth
 possible cause: missing arguments for method or constructor
               meth("Box", "apply").apply(arg)
                                          ^

Is it possible to infer the correct types into class meth? Or is there a workaround for the problem?

EDIT: Based on @retronyms answer I got this to work:

object M {
  import language.experimental.macros
  import scala.reflect.makro.Context

  def meth(implicit c: Context) = new Meth[c.type](c)

  class Meth[C <: Context](val c: C) {
    import c.universe._

    def apply(obj: String, method: String, xs: Tree*) =
      Apply(Select(Ident(obj), newTermName(method)), xs.toList)
  }

  def box(n: Int): Box = macro boxImpl

  def boxImpl(c: Context)(n: c.Expr[Int]): c.Expr[Box] = {
    import c.universe._
    implicit val cc: c.type = c
    n.tree match {
      case arg @ Literal(Constant(_)) =>
        c.Expr(meth.apply("Box", "apply", arg))
    }
  }
}

回答1:

Constructors are not currently allowed to have dependent method types (SI-5712). It's on the radar to be fixed, hopefully for 2.10.1 or 2.11.

In the meantime, you can follow the pattern I used in macrocosm to reuse code within macro implementations.