1
votes

Imagine i have a macro annotation that annotates case class:

class message(`type`: String) extends StaticAnnotation {
    def macroTransform(annottees: Any*) = macro message.impl
}

...

@message("SearchReq")
case class SearchReq(req: String)

I have MessageRegister object that located in another package. In annotation @message body message.impl i need to add type of message in register.

I have no idea how to do that. The first thing that came to mind is get the tree of MessageRegister object and add code into its body that executes in runtime. The next idea is that somehow @message annotation executes in runtime and i simply execute MessageRegister.registerMessage(msg).

How can i solve this problem ?

1

1 Answers

0
votes

It is currently impossible for macros to modify anything outside their scope. I mean, it's possible, but it: 1) requires deep knowledge of compiler internals, 2) will most likely be incompatible within even minor releases of the compiler, 3) will most likely not work robustly (because it will make assumptions about compilation order).

Speaking of invoking MessageRegister.registerMessage(msg), you could make a macro annotation generate this piece of code is a companion object of SearchReq. However, that code doesn't have guaranteed time of execution (because it will only be called once someone triggers the constructor of the SearchReq object), which means that it's not going to be robust (again, assumptions about execution order).