How can I modify Kotlin code with PSI?

Answered

I'm trying to create a plugin for IntelliJ IDEA that functions similarly to lombok, this is what I'm trying to do, with an existing kotlin interface:

```kotlin
interface TestInterface {
    var testProperty: Int
}
```

I want to modify the PSI so that the IntelliJ IDEA can recognize it as:

```kotlin
interface TestInterface {
    var testProperty: Int

    companion object: TestInterface {
        override var testProperty: Int
            get() {
                TODO("Do something")
            }
            set(value) {
                TODO("Do something")
            }
    }
}
```

Here is my code: [Github](https://github.com/mhmzx/ExspPlugin/tree/b50ae79ad72431aca8e368072e0d0b4b18336a08/src/main/kotlin/io/github/sgpublic/exspplugin/core/kt), but it dosen't work.

So what is the correct way? Thank you!

0
3 comments

Hi! Unfortunately, generating the Kotlin PSI on the fly for use by the Kotlin resolve is impossible. Java resolution in the IDE uses PSI to resolve things, and that's why it works for Java. Kotlin resolution in the IDE uses the Kotlin compiler, so creating PSI on the fly and using PsiAugmentProvider will not work. 


Could you please explain how the compilation should work for the Kotlin project which uses your plugin?

Generally, such things are solved by the Kotlin compiler plugins. The support for such plugins usually consists of two parts: one for the compiler and one for the IDE. You may see how compiler plugins support works for some Kotlin plugins in the IDE: https://github.com/JetBrains/intellij-community/tree/master/plugins/kotlin/compiler-plugins. And here they are for the compiler https://github.com/JetBrains/kotlin/tree/master/plugins.

0

Hi, Ilya Kirillov! Thanks a lot for your responses. The behavior of my project in Java is to utilize AnnotationProcessor, ie:

Create a private member variable in the Java class, then use AnnotationProcessor to create static getter and setter methods for it, and complete the logic I need (that is, only the name of the member variable is required, and the variable is not actually used), so I need to use PsiAugmentProvider to make these methods can be shown correctly, the same as the Lombok plugin does.

Now I want to do the same thing in Kotlin, and I thought of the method in the post, which is to add a companion object to an interface and implement this interface.

So how should I make it with the Kotlin compiler? Thank you!

0

Sorry for the long reply. You should be able to compile the project which will use your extensions. Kotlin compiler knows nothing about them, so you need to write either a compiler plugin (I've provided the link with compiler plugins examples) or you need to implement some kind of code-generation. For the second option, you may use the Kotlin Symbol Processor https://kotlinlang.org/docs/ksp-overview.html

0

Please sign in to leave a comment.