CodeBlanks Logo Icon CodeBlanks

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.

Practice 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(...).

Starter code

Main.kt
// add the IrElement and IrTransformer classes

fun main() {
    // create IrElement("main") and print transform
}

Sample solution

Main.kt
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")))
}

Expected output

ir:main

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the transform method

Question
class IrTransformer {
    fun ____(el: IrElement): String = "ir:${'$'}{el.name}"
}
Answer
class IrTransformer {
    fun transform(el: IrElement): String = "ir:${'$'}{el.name}"
}

Explanation: transform(el) transforms an IR node.

2 Match IR parts

Term Meaning
IrElement Node base
IrTransformer Transformer
visitCall Call visit
IrCall Call node

3 Which pattern do IR transformers use?

  • Singleton
  • Factory
  • Observer
  • Visitor Correct answer

Explanation: IR transformers use the visitor pattern to handle each node type.

All lessons in Expert