Kotlin Analysis API Documentation
 

In-memory file analysis

Last modified: 26 February 2025

Parsing a Kotlin file does not require any knowledge about the project it belongs to. On the other hand, for semantic code analysis, understanding dependencies and compilation options of a file is crucial.

In most cases, source files — whether written by a user or auto-generated — are stored on disk and belong to a specific module. The build system understands the project layout and instructs the compiler or the IDE to use appropriate dependencies for all files in that module. For script files, such as build.gradle.kts, the situation is more complex since scripts technically do not belong to any module. However, in such cases, the build system also provides the necessary context. For example, Gradle build scripts include the Gradle API and all libraries Gradle depends on in their classpath.

In certain cases, it might be useful to analyze a file without storing it in the file system. For example, an IDE inspection may use in-memory files to verify whether code will remain valid after applying a proposed change. Specifically, the inspection might create a copy of the KtFile, apply the change to the copy, and check for new compilation errors. In such scenarios, the inspection needs to supply the correct analysis context for the in-memory KtFile.

The Analysis API provides multiple approaches for analyzing in-memory files and attaching context to them. Below, we explore these options and their differences.