mercredi 14 octobre 2015

I got into trouble while exploring Scala macro

When I was trying to do some manipulation with scala macro, got some trouble:

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
  }
}

It got compiled successfully.But I got error like below:

scala> MacroTest(q"class a") :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.applyList[Nothing], immutable.this.Nil, scala.collection.immutable.List.applyreflect.runtime.universe.Tree, scala.reflect.runtime.package.universe.noSelfType, immutable.this.Nil) (of class scala.reflect.internal.Trees$Apply) at MacroTest$.impl(:32)

   MacroTest(q"class a")
            ^

But if I run this code in console, it would work:

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()

I got confused and stuck here,could someone help?





Aucun commentaire:

Enregistrer un commentaire