Kotlin
IR
Learn Kotlin IR (Intermediate Representation).
What is IR?
IR (Intermediate Representation) is the Kotlin compiler's internal form; it is a tree-shaped model of the source code. All backends (JVM, JS, Native) share the same IR.
An IR transformer extends classes like IrElementTransformerVoidWithContext. The transformer visits each node and can change it. Example: override fun visitCall(expression: IrCall): IrExpression. This structure is the standard path for compiler plugins; the Compose plugin works with IR. IR transforms are complex but powerful; they can change behaviour at compile time.
The IR visitor pattern
IR transformers work with the visitor pattern. A separate visitX method is called for each node type.
Example: visitCall handles function calls, visitProperty properties, visitClass class declarations. During transform, returning a new node instead of mutating the original is common; this reduces side effects. IR's type safety catches wrong transforms at compile time. In this lesson's simple model we show what a transform looks like with IrElement and IrTransformer classes.
Exercise Write IrTransformer
Define class IrElement(val name: String). Inside class IrTransformer add fun transform(el: IrElement): String that returns "ir:${'$'}{el.name}". In main, create an IrElement("main") and print IrTransformer().transform(...).
Show example solution
class IrElement(val name: String)
class IrTransformer {
fun transform(el: IrElement): String = "ir:${el.name}"
}
fun main() {
val t = IrTransformer()
println(t.transform(IrElement("main")))
}
Test yourself
-
Complete the transform method
class IrTransformer {
fun ____(el: IrElement): String = "ir:${'$'}{el.name}"
}
Show answer
class IrTransformer {
fun transform(el: IrElement): String = "ir:${'$'}{el.name}"
}
-
Match IR parts
- IrElement
- Node base
- IrTransformer
- Transformer
- visitCall
- Call visit
- IrCall
- Call node
-
Which pattern do IR transformers use?
- Singleton
- Factory
- Observer
- Visitor
Show answer
Visitor — IR transformers use the visitor pattern to handle each node type.
Next lesson: Plugin vs KSP