Get the calling class

I want to get the calling macro class, 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.

+4
source share
1 answer

This will work as it is when called from a regular instance of the class, so I assume that you are trying to do it from within the object, in which case you will need to map to 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 ) ) 

Please note: one easy way to debug something like this is to print out the raw idea that the unexpected is what you get:

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

When called inside a singleton object, the following will be displayed:

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

This gives us a pretty good idea of โ€‹โ€‹where we need to start.

+5
source

All Articles