Generate Kotlin source by IDEA Plugin
Answered
I am writing an IDEA plug-in to generate data classes by json.I've done some work, but I don't know how to generate kotlin source files.
I learned about PsiFile. So I can create new Kotlin File, but I don't know how to inflate code to file.
This is my ”build.gradle.kts“(added kotlin dependence):
intellij {
version.set("2023.1.5")
type.set("IC") // Target IDE Platform
//plugins.set(listOf(/* Plugin Dependencies */))
plugins.set(listOf("com.intellij.java","org.jetbrains.kotlin"))
}
I tried kotlinpoet, But the generated code has a lot of redundancy.
So I think maybe I should use KtPsiFactory, and i tried use it, But I can't generate documentation comments using KtPsiFactory.
This is my code about KtPsiFactory:
val factory: KtPsiFactory = KtPsiFactory(event.project!!)
val ktFile: KtFile = factory.createFile(classNameField.text + ".kt", "package $packageName")
ktFile.add(factory.createNewLine())
val ktClass: KtClass = factory.createClass("class ${classNameField.text}")
val ktClassBody: KtClassBody = ktClass.getOrCreateBody()
ktClassBody.addBefore(factory.createNewLine(), ktClassBody.rBrace)
val dataClassOne: KtClass = factory.createClass("data class DataOne")
dataClassOne.createPrimaryConstructorParameterListIfAbsent().apply {
add(factory.createNewLine())
addParameter(factory.createParameter("var id:Long"))
.let {
it.add(factory.createComment("this is id")) // This throw NoSuchElementException
it.addAnnotationEntry(
factory.createAnnotationEntry("@SerializedName(\"id\")")
.apply { add(factory.createNewLine()) })
}
addParameter(factory.createParameter("var name:String"))
}
ktClassBody.addBefore(dataClassOne, ktClassBody.rBrace)
ktFile.add(ktClass)
ApplicationManager.getApplication().runWriteAction {
directory.add(ktFile)
}
Can anyone tell me how to use KtPsiFactory ? or where is the documentation about KtPsiFactory?
Thanks to everyone who helped
Please sign in to leave a comment.
There is little to no docs on KtPsiFactory. https://github.com/JetBrains/kotlin/blob/master/compiler/psi/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt
See org.jetbrains.kotlin.psi.KtPsiFactory#createComment to create comment PSI element.
https://github.com/JetBrains/kotlin/blob/master/compiler/psi/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt.
⬆️ this link, 404 page not found
I found this place of the file (without the point at the end of the link):
https://github.com/JetBrains/kotlin/blob/master/compiler/psi/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt