https://kotlinlang.org logo
#k2-early-adopters
Title
# k2-early-adopters
j

Johann Pardanaud

10/23/2023, 2:33 PM
Would it be possible, with a K2 compiler plugin, to find all the instanciations of a specific class when compiling? Currently I'm using KSP and annotations, but it's quiet error-prone since you can sometimes forget to add the annotations. An important thing: I would like to find all the instanciations, even those inside expressions.
j

jvmusin

10/23/2023, 2:58 PM
I guess you won't be able to find instantiations when you pass constructor reference to some method
f
which accepts a function like
(parameters) -> T
, and
f
method calls the constructor through the passed constructor reference
j

Johann Pardanaud

10/23/2023, 3:06 PM
oh right, however I guess I can live with this limitation ^^
Let's take an example. Say I want to find all the instanciations of
SomeClass
, is it possible to find them in the following code?
Copy code
val topVar = SomeClass()

fun main() {
    SomeClass()
}
Is it possible with K2 to find both instanciations?
I suppose it could be done with some kind of visitor?
j

jvmusin

10/23/2023, 3:10 PM
I do it using a visitor in K1 on IR level with
IrElementTransformerVoidWithContext*.*visitConstructorCall
. See here: https://github.com/jvmusin/naked/blob/main/naked-kotlin-plugin/src/main/kotlin/io/github/jvmusin/naked/NakedIrGenerationExtension.kt#L142C50-L142C50
d

dmitriy.novozhilov

10/23/2023, 3:10 PM
It's possible with IR plugin (this part of compiler API is common for K1 and K2)
j

Johann Pardanaud

10/23/2023, 3:11 PM
Amazing, thanks! And I suppose we can do the same with function calls?
👌 2