简体   繁体   中英

scala macros how to get tree of specific class

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM