Eric Mariacher
Eric Mariacher

Reputation: 349

get calling class

I want to get the calling class of a macro, but my code does not work:

def __CLASS__(c: Context) = {
    import c.universe._
    c.enclosingClass match {
    case ClassDef(mods, name, tparams, impl) =>
    c.universe.reify(println(
            "\n  mods "+c.literal(mods.toString).splice
            +"\n  name "+c.literal(name.toString).splice
            +"\n  tparams "+c.literal(tparams.toString).splice
            +"\n  impl "+c.literal(impl.toString).splice
            ))
    case _ => c.abort(c.enclosingPosition, "NoEnclosingClass")
    }
}

Thanks in advance for your help.

Upvotes: 4

Views: 775

Answers (1)

Travis Brown
Travis Brown

Reputation: 139058

This will work as-is when called from inside an ordinary instance of a class, so I'll assume you're trying it from inside an object, in which case you'll need to match against ModuleDef as well as ClassDef:

case ModuleDef(mods, name, impl) => c.universe.reify(
  printf(
    "\n  mods %s\n  name %s\n  impl %s\n",
    c.literal(mods.toString).splice,
    c.literal(name.toString).splice,
    c.literal(impl.toString).splice
  )
)

Note that one easy way to debug something like this is to print out the raw representation of whatever unexpected thing you're getting:

case x => c.abort(c.enclosingPosition, "NoEnclosingClass: " + showRaw(x))

This would print the following when called inside a singleton object:

<console>:7: error: NoEnclosingClass: ModuleDef(Modifiers(), ...

Which gives us a pretty good idea of where we need to start.

Upvotes: 5

Related Questions