r/Kotlin • u/Content-Jaguar-578 • 11d ago
Exploring Kotlin static analysis inside an IntelliJ Platform plugin using UAST
I've been exploring static code analysis for Android projects while building an IntelliJ-based developer tool.
One interesting challenge has been identifying potential lifecycle and memory-related issues by analyzing Kotlin source code rather than relying entirely on runtime heap analysis.
For example, consider patterns such as:
- A singleton retaining an Activity or Fragment reference.
- Coroutine scopes that outlive the lifecycle of the component that launched them.
- Long-lived callbacks retaining UI-related objects.
- Incorrect ownership of objects across lifecycle boundaries.
The tricky part is that detecting these patterns reliably isn't always straightforward.
Kotlin introduces several language features that make source analysis interesting: extension functions, lambdas, inline functions, delegated properties, higher-order functions, and coroutine scopes.
I've been experimenting with UAST-based inspections to analyze these patterns within the IntelliJ Platform.
A few questions for Kotlin developers who have worked on static analysis:
- How do you approach analyzing Kotlin-specific language constructs when building inspections?
- Do you prefer PSI directly, UAST, or a combination of both for Kotlin analysis?
- How do you handle false positives when detecting lifecycle or object-retention patterns through source code?
- Are there Kotlin compiler APIs or analysis tools you'd recommend exploring for this kind of work?
I'm particularly interested in approaches that go beyond simple syntax matching and can reason about object ownership and lifecycle relationships.
2
u/paulhasreadittoo 11d ago
You can take a look at Detekt which also does static code analysis for Kotlin/Android. With Kotlin 2.5 you will get access to the Kotlin Analysis Api which might be helpful, but I don't know any specifics about it
1
u/ClassKlutzy7633 11d ago
Worth reading the source of Android Lint's StaticFieldLeak check, since Lint is built on UAST and already deals with the singleton-holding-a-Context case. For false positives I'd start narrow: only flag when the field's resolved type is a subtype of Activity, Fragment or View and the holder is an object declaration or companion object, and skip anything that comes from applicationContext. The coroutine scope cases are much harder from source alone, so I'd report those as weak warnings rather than errors until you've seen how noisy they are on a few real projects.