Skip to content

How to write a Kotlin Compiler Plugin

Jens Klingenberg edited this page Apr 20, 2022 · 3 revisions

ℹ️ Please be aware that the Kotlin Compiler still doesn’t have any stable API and there is no backwards compatibility guaranteed. Kotlin versions above 1.6.21 can have a totally different API.

  1. Create a normal Kotlin-Jvm Project with Gradle
  2. 1)Add the compiler as dependency
repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
   SEE BELOW
    compileOnly "com.google.auto.service:auto-service:1.0-rc6"
    kapt "com.google.auto.service:auto-service:1.0-rc6"
}

If you want to write a plugin for JS/JVM compiler, add:

       compileOnly "org.jetbrains.kotlin:kotlin-compiler-embeddable"

If you want to write a plugin for Native compiler, add:

        compileOnly "org.jetbrains.kotlin:kotlin-compiler"

2.2) Add AutoService https://github.com/google/auto/tree/master/service

You don't have use it, but AutoService will generate the META-INF file for you

    compileOnly "com.google.auto.service:auto-service:1.0-rc6"
    kapt "com.google.auto.service:auto-service:1.0-rc6"

Remember to also add Kapt apply plugin: "kotlin-kapt"

2.3) Add maven plugin

    apply plugin: "maven"

Add the configuration, and set your group,archivesBaseName and version:

group = "de.jensklingenberg"
archivesBaseName = "kotlin-compiler-plugin"
version = "0.0.1"

install {
    repositories.mavenInstaller {
        pom.artifactId = archivesBaseName
    }
}
  1. Create a ComponentRegistrar Create a new Kotlin Class which implements org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar

The ComponentRegistrar is the first entry class of your compiler plugin

     @AutoService(ComponentRegistrar::class)
open class CommonComponentRegistrar : ComponentRegistrar {

    override fun registerProjectComponents(
            project: MockProject,
            configuration: CompilerConfiguration
    ) {
...

If you are using AutoService add @AutoService(ComponentRegistrar::class) on top of your class

  1. Use the "install" gradle task, to build your compiler plugin.

If you want to use your plugin from a Gradle plugin, take a look at * How to use a Kotlin Compiler from Gradle Plugin

Clone this wiki locally