Compiler plugins
- Kotlin course
- Expert
- Lesson 13/47
- 5 min
Learn the Kotlin compiler plugin concept.
What is a compiler plugin?
A compiler plugin hooks into the Kotlin compiler and can transform code during compilation. Unlike KSP, it has access to the full AST.
The plugin can make classes open, add synthetic constructors, or transform the IR (Intermediate Representation) at compile time. In Kotlin 2.x all official plugins work this way: all-open, no-arg, compose and kotlinx.serialization. A plugin is added in Gradle as a compilerPlugin dependency; the output is modified bytecode. In this lesson you will set up the basic plugin skeleton.
Plugin lifecycle
A compiler plugin hooks into specific phases of the compile lifecycle: Frontend (parsing and resolution), IR (intermediate representation), and Backend (code generation).
Example: the all-open plugin makes classes with certain annotations open in the frontend phase. The compose plugin transforms @Composable functions in the IR phase. Each phase has its own APIs; the most common is IR. Writing a plugin involves implementing ComponentRegistrar and registering an extension that hooks the relevant phase.
Practice Write the CompilerPlugin skeleton
Define class CompilerPlugin. Method fun load() should call println("plugin loaded"). In main, call CompilerPlugin().load().
Starter code
// add the CompilerPlugin class
fun main() {
// load the plugin
}Sample solution
class CompilerPlugin {
fun load() {
println("plugin loaded")
}
}
fun main() {
CompilerPlugin().load()
}Expected output
plugin loaded
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What can a compiler plugin access?
- Only annotations
- Only runtime data
- The full AST Correct answer
- Only the source file name
Explanation: A compiler plugin has access to the full AST; KSP only sees symbols.
2 Complete the load method
class CompilerPlugin {
fun ____() {
println("plugin loaded")
}
}
class CompilerPlugin {
fun load() {
println("plugin loaded")
}
}
Explanation: load() is the plugin's entry point.
3 Match plugin parts
| Term | Meaning |
|---|---|
ComponentRegistrar |
Plugin registration |
extension |
Phase hook |
frontend |
Parsing and resolution |
backend |
Code generation |