https://kotlinlang.org logo
#compiler
Title
# compiler
m

Mendess

08/01/2022, 11:07 AM
Hey! I have never written a compiler plugin and I was wondering if I it's possible to write one that adds an annotation like this
Copy code
@MustUse
class Foo
and every function that returns a Foo will issue a warning at call site the returned value is not used in some way
t

Tóth István Zoltán

08/04/2022, 3:43 AM
Hi! It is quite possible. I think your best bet is the KSP (Kotlin Symbol Processing API). I have no experience with it, but my guess is it can do what you would like to do. It is documented in the Kotlin documentation. It is also possible to do it with an IR plugin. That might be a lot harder compared to the KSP but it gives you access to everything. With IR you have to go to code the of the Kotlin compiler and other plugins (Compose, kotlinx.serialization for example) frequently as there is not much documentation. On the other hand, it is quite logical and once you get hang of it quite easy. You can check this article as a starting point: https://bnorm.medium.com/writing-your-second-kotlin-compiler-plugin-part-1-project-setup-7b05c7d93f6c The downside of IR is the warning reporting. I haven't yet found out how to get the warnings into IDEA, I can write them to the console, but the UI doesn't highlight the problems. The third possibility is to write an IDEA plugin or play around with the FIR. Writing an IDEA plugin is quite well documented. FIR is experimental. With these it might be easier to show the warnings on the UI. I have no real experience in this area, so I don't know the details. Hope this helps.
3 Views