4

我想使用一个使用“type”关键字定义的类型的宏。我如何引用它?

我的起始代码是

import scala.reflect.macros.Context
import scala.language.experimental.macros

trait Demo6 {
  type T

  def add(param: Any): T = macro Demo6.addImpl[T]

  def fullAdd(param: Any, toStringBasedOnAST: String): T = {
    doesSomeThing_and_returnsSomething_OfTypeT
  }
  def doesSomeThing_and_returnsSomething_OfTypeT: T //just to allow compilation
}

object Demo6 {
  def addImpl[T: c.WeakTypeTag](c: Context)(param: c.Expr[Any]): c.Expr[T] = {
    import c.universe._
    reify { (c.Expr[Demo6](c.prefix.tree)).splice.fullAdd(param.splice, 
                                        c.literal(show(param.tree)).splice) }
    //        ^ - type mismatch; found : org.autotdd.scalamacros.Demo6#T 
    //                           required: T
  }
}

我在示例中标记了编译器错误。很清楚发生了什么:关键字定义的类型 T 与我传入的类型 T 不同。

我尝试过的事情 关于 scala-macros 的文档还不是很多。http://docs.scala-lang.org/overviews/macros/overview.html中的部分非常有助于让我走到这一步,但它的示例使用了类级别和方法级别的泛型。我浏览了 Expecty 和 macrocosm 的代码,它们是文档中引用的项目,但找不到这样的代码。

4

1 回答 1

4

Your code is almost correct, just change type parameter of Expr:

val expr = reify { ... }
c.Expr[T](expr.tree)

Without reify you should return this:

c.Expr[T](Apply(Select(c.prefix.tree, newTermName("fullAdd")),
                List(param.tree, Literal(Constant(show(param.tree))))))

reify creates the same, but with wrong type parameter.

See this answer for showRaw usage.

In this case:

scala> import reflect.runtime.universe._
import reflect.runtime.universe._

scala> {
     |   object Demo { def fullAdd(param1: Any, param2: String): String = "result" }
     |   showRaw{ reify { Demo.fullAdd("param1", "param2") } }
     | }
res0: String = Expr(Apply(Select(Ident(newTermName("Demo")), newTermName("fullAdd")), List(Literal(Constant("param1")), Literal(Constant("param2")))))

Replace Ident(newTermName("Demo")) with c.prefix.tree, Literal(Constant("param1")) with param.tree and "param2" with show(param.tree) and you'll get your result.

于 2013-05-08T10:39:50.837 回答