以下宏是从http://docs.scala-lang.org/overviews/quasiquotes/usecases.html:
粘贴过来的import reflect.macros.Context
import language.experimental.macros
val universe = reflect.runtime.universe; import universe._
import reflect.runtime.currentMirror
import tools.reflect.ToolBox
val toolbox = currentMirror.mkToolBox()
object debug {
def apply[T](x: =>T): T = macro impl
def impl(c: Context)(x: c.Tree) = { import c.universe._
val q"..$stats" = x
val loggedStats = stats.flatMap { stat =>
val msg = "executing " + showCode(stat)
List(q"println($msg)", stat)
}
q"..$loggedStats"
}
}
在Scala 2.11.1中产生如下错误信息:
Q.scala:9: error: macro implementation reference has wrong shape. required:
macro [<static object>].<method name>[[<type args>]] or
macro [<macro bundle>].<method name>[[<type args>]]
def apply[T](x: =>T): T = macro impl
^
我尝试过以多种方式改变代码(import reflect.macros.whitebox.Context
, import reflect.macros.blackbox.Context
,将scala.
放在每次导入的开始,使参数一致地按名称或一致地按值,macro impl[T]
,摆脱类型参数,macro debug.impl
,将apply
放在impl
之后,等等),但没有成功。我做错了什么?是进口的问题吗?这些(大部分)来自一个不同的网页,http://docs.scala-lang.org/overviews/quasiquotes/setup.html。
同样的错误出现在该页的其他两个示例宏上:
object Macro {
def apply(x: Int): Int = macro impl
def impl(c: Context)(x: c.Expr[Int]): c.Expr[Int] = { import c.universe._
c.Expr(q"$x + 1")
}
}
object Macro {
def apply(x: Int): Int = macro impl
def impl(c: Context)(x: c.Tree) = { import c.universe._
q"$x + 1"
}
}
scala Foo.scala
将您提供给它的代码包装在一个匿名类中。因此,类似于:
import scala.reflect.macros.Context
import scala.language.experimental.macros
object debug {
def apply[T](x: T): T = macro impl
def impl(c: Context)(x: c.Tree): c.Tree = ???
}
转换成:
[[syntax trees at end of parser]] // Test.scala
package <empty> {
object Main extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
def main(args: Array[String]): scala.Unit = {
final class $anon extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
import scala.reflect.macros.Context;
import scala.language.experimental.macros;
object debug extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
<macro> def apply[T](x: T): T = impl;
def impl(c: Context)(x: c.Tree): c.Tree = $qmark$qmark$qmark
}
};
new $anon()
}
}
}
但是,宏实现必须在静态对象或捆绑包中定义,这就是错误消息试图说的:
/Users/xeno_by/Projects/211x/sandbox/Test.scala:5: error: macro implementation reference has wrong shape. required:
macro [<static object>].<method name>[[<type args>]] or
macro [<macro bundle>].<method name>[[<type args>]]
def apply[T](x: T): T = macro impl
^
one error found
不幸的是,如果将某些东西放入匿名类中,它就不再是静态的,这意味着scala Foo.scala
风格的开发与宏不兼容。请考虑使用其他选项,例如scalac
或sbt
。