我在探索Scala宏时遇到了麻烦

时间:2015-10-14 09:27:13

标签: scala reflection macros

当我尝试使用Scala宏进行一些操作时,我遇到了一些麻烦:

object MacroTest {

  def apply(x: ClassDef): ClassDef = macro impl

  def impl(c: Context)(x: c.Tree): c.Tree = {
    import c.universe._
    val q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" = x
    println(tpname)
    x
  }

}

编译成功,但我收到以下错误:

scala> MacroTest(q"class a")
<console>:30: error: exception during macro expansion:
scala.MatchError: scala.reflect.runtime.`package`.universe.internal.reificationSupport.SyntacticClassDef.apply(scala.reflect.runtime.`package`.universe.NoMods, scala.reflect.runtime.`package`.universe.TypeName.apply("a"), immutable.this.Nil, scala.reflect.runtime.`package`.universe.NoMods, scala.collection.immutable.List.apply[List[Nothing]](immutable.this.Nil), immutable.this.Nil, scala.collection.immutable.List.apply[reflect.runtime.universe.Tree](scala.reflect.runtime.`package`.universe.internal.reificationSupport.ScalaDot.apply(scala.reflect.runtime.`package`.universe.TypeName.apply("AnyRef"))), scala.reflect.runtime.`package`.universe.noSelfType, immutable.this.Nil) (of class scala.reflect.internal.Trees$Apply)
    at MacroTest$.impl(<console>:32)

       MacroTest(q"class a")
                ^

但是,如果我在控制台中运行此代码,它将起作用:

scala> val q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" = q"class a"
mods: reflect.runtime.universe.Modifiers = Modifiers(, , Map())
tpname: reflect.runtime.universe.TypeName = a
tparams: List[reflect.runtime.universe.TypeDef] = List()
ctorMods: reflect.runtime.universe.Modifiers = Modifiers(, , Map())
paramss: List[List[reflect.runtime.universe.ValDef]] = List(List())
earlydefns: List[reflect.runtime.universe.Tree] = List()
parents: List[reflect.runtime.universe.Tree] = List(scala.AnyRef)
self: reflect.runtime.universe.ValDef = private val _ = _
stats: List[reflect.runtime.universe.Tree] = List()

我感到困惑并被困在这里,有人可以帮忙吗?

0 个答案:

没有答案