in Updates

Kotlin K2 FIR Quickstart Guide

I wrote this Kotlin K2 FIR guide because I was not able to find any guides or examples to get started with FIR for static analysis. K2 is now finally stable in Kotlin 2.0.0 and future versions, so FIR will be the recommended way of doing static analysis.


Starting Kotlin 1.x you could only use PSI (Program Structure Interface) to create an AST (Abstract Syntax Tree) to run static analysis.

Kotlin’s K2 Compiler is powered by a new Frontend Intermediate Representation (FIR). It still uses PSI to create the initial model, but transforms that into FIR which is a semantic model that is independent from any compiler backend (JVM, JS, Native, etc).

Step 1

Add the Kotlin Embedded Compiler Dependency


Step 2

Use the code in the Gist:

Yes, this is a really short post, but it’s more so here so that you’ll discover the Gist from a search and be able to get started using K2’s FIR model!


FIR is much more useful in understanding what the code is instead of the original syntax. That being said, you can still reach back into the code that the FIR model is derived from to gain more context as needed. If you are building any Static Analysis tooling, it’s HIGHLY suggested to start building it on FIR going forward.


This implementation is based on: