Hello, I am trying to write a compiler plugin whic...
# compiler
k
Hello, I am trying to write a compiler plugin which generates a new class. So far I have written a class extending
IrGenerationExtension
and can see the generated .class file as a result. I then created a .kt file which references that class, but when trying to compile with kotlinc (the .class file is on the classpath with
-cp
) I get
unresolved reference
. I opened the .class file in a decompiler and when comparing it to a .class file that was created from a .kt file, I see my generated .class file has missing
d1
and
d2
metadata properties, plus
k = 3
, whereas the other class has
k = 1
. Does this matter? Is there any other reason why this might not be working?
b
Not the answer you're looking for, but if you're only generating new code, I'd strongly recommend going with #ksp rather than direct compiler plugin. It does a lot of heavy lifting for you.
k
Thank you for your reply, I'm certainly open to using ksp if it helps. Would it allow me to do the following? Start with this class
Copy code
class Foo {
    val abc = "abc"

    fun hello() = "Hello World"
}
and generate a new class with just the
hello
function?
Copy code
class Bar {
    fun hello(name: String) = "Hello World"
}
My understanding was ksp does not have the details of function bodies
b
Ah, no. Ksp only has access to the api, not the bodies
But can't you somehow delegate the implementation to initial method?
k
Can I change the function signature in ksp? I don't need to modify the function body but I need to add parameters or change their types
b
No, ksp has 2 main limitations: • Existing sources are read-only so you can only generete new stuff • It can only see the API, but not the implementation bodies
You might want to look at #arrow-meta as well. That one is a lot closer to being actual compiler plugin.
b
Sorry for pushing you sideways. It's just that compiler API is so unstable now that I always try to avoid interracting with it directly.
k
Yep that's understandable and no problem, I appreciate your advice.
j
@Karim Houari: I think you need to move the declaration of the class and its methods into an implementation of
SyntheticResolveExtension
. The
IrGenerationExtension
implementation then only adds the bodies. BTW: You can reference the
SyntheticResolveExtension
implementation in an IntelliJ plugin and then Inntelij will also know about the generated classes.