Scala macro modify object

2019-08-07 00:51发布

问题:

I have a next macro annotation

 class Foo(obj: String) extends StaticAnnotation {
    def macroTransform(annottees: Any*) = macro MacroImpl.impl
 }

 object MacroImpl {
    def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
      import c.universe._

      // i want find `obj` and modify body
    } 

 }

 // usage
 @Foo("pkg.myObject") class SomeClass {}

Is it possible with macro find object by name and modify body of object?

回答1:

This is currently impossible, because macros in Scala can't modify anything outside their scope. E.g. def macros can only rewrite their applications, not the code around, and macro annotations can only rewrite their annottees, not the code around.