Use the DevKit to build Kotlin compiler plugins that support many Kotlin compiler versions from one source tree. It publishes Gradle plugins and runtime/test libraries.
Compiler internals are unstable across versions, so the DevKit models a supported Kotlin version as a KMP target. The
same commonMain sources compile against every version's compiler, with expect/actual only where declarations
genuinely differ. A breaking change appears as a compile error, together with that version's deprecations and opt-ins.
One multi-release jar then holds every version, and the DevKit picks the matching one at Gradle build time and at
compiler and IDE runtime.
- Functional test
- A Gradle integration test that uses Gradle TestKit.
- Gradle support plugin
- A
KotlinCompilerPluginSupportPlugin. - Companion library
- A library that the compiler plugin needs on the classpath of the user's code. The Gradle support plugin adds it. Such a library usually has annotations, and can also have types and utilities.
- Version
- A Kotlin version (
KotlinToolingVersion), including-dev-and-ijXYZ-versions. - CLI version
- A version that is available on Maven Central or in the
devorbootstraprepository. Command-line builds use it to compile code. - IDE version
- A version that is available in the
intellij-dependenciesrepository. IDEs use it for analysis, and sometimes to compile JVM code forEvaluate ExpressionandShow Kotlin Bytecode. An IDE version is always a-dev-or an-ijXYZ-version. - By default, every
-dev-version is considered an IDE version by `testAgainst`. A build can override this by setting `forIde = false`. - All
-ijXYZ-versions with the sameXYZcome from the same major IDE release. For example,263is 2026.3. - Branch point
- The
-dev-version that an-ijXYZ-version branched from. Git ancestry gives the exact branch point. In practice, the newest recordedXYZbuild that maps to a plaindevversion gives the branch point.ide-mappings.txtrecords it. A release line whose recorded builds all map to-ijversions has no branch point. - Base version
- A Kotlin version (
KotlinVersion) without a classifier, for example1.9.0or2.4.21. Each Kotlin version has a base version. To compare a version with a base version, convert the version to its base version. - Target name
- The Gradle target name of a version:
k+ the version, lowercased, with.removed and-replaced by_. For example,2.4.20-dev-7885→k2420_dev_7885. - IDE stability
- Release, RC, or EAP, in IntelliJ terms. For Android Studio, Beta counts as RC, and Canary counts as EAP.
- IDE channel
- An IDE stability and a product (IntelliJ IDEA or Android Studio).
- Sibling dependency
- A dependency on a project with the same
groupand the sameversion. Composite builds use it. - Entry point
- A class of a plugin that the Kotlin compiler instantiates:
CommandLineProcessororCompilerPluginRegistrar. - Classified dump
- A dump (golden data) file with classifiers that tell it apart from similar dumps. For example, a version classifier gives one dump for each compiler version.
version-resolution: picks a compatible Kotlin version, maps IDE build numbers to IDE versions, and parses the DevKit jar format.- Gradle plugins:
- Settings plugin
pluginDevKit("compiler-plugin"): for the compiler plugin. Usesversion-resolution.pluginDevKit("gradle-plugin"): for the Gradle support plugin.-
pluginDevKit("functional-test-publishing"): for all projects.
- Runtime libraries:
compiler-plugin-runtime: compiler plugin utilities and entry point classes. Usesversion-resolutionandcompiler-plugin-runtime-compatcompiler-plugin-runtime-compat: backported compiler plugins compatibility declarations. It avoids usingexpect/actual, instead preserving source compatibility for renamed/missing declarations.compiler-plugin-test: compiler plugin test utilities, including classified dumps. Usescompiler-plugin-test-compatcompiler-plugin-test-compat: Likecompiler-plugin-runtime-compat, it preserves source compatibility for renamed/missing test infrastructure declarations.compiler-plugin-test-generator: the test generator API, for examplegenerateDevKitTestsWithJUnit5.gradle-plugin-runtime: Gradle support plugin utilities. Its test fixtures help with functional tests.
All DevKit artifacts share the group org.jetbrains.kotlin.compiler.plugin.devkit. The id of a Gradle plugin is
<group>.<variant>, for example org.jetbrains.kotlin.compiler.plugin.devkit.compiler-plugin. The settings plugin's id
is the group itself, so a settings script applies it as kotlin("compiler.plugin.devkit"). The settings plugin project
also has the pluginDevKit(<variant>) accessors, in the org.gradle.kotlin.dsl package. So build scripts can write
pluginDevKit("compiler-plugin") inside plugins { } and pluginDevKit("version-resolution") as a dependency
notation.
A typical compiler plugin has these parts:
- One compiler plugin
- One Gradle support plugin
- Support plugins for other build tools, for example Maven or Amper
- Zero or more companion libraries
The DevKit supports three build structures:
- A single build. This is the simplest structure, but it supports the smallest range of versions.
- A composite build. The companion libraries use an older KGP, and everything else uses a newer KGP. This is the recommended structure, and the compiler-plugin-template uses it.
- Three builds. Use this structure to apply the compiler plugin to its own companion libraries. The Gradle support plugin gets a separate build, because Isolated Projects doesn't support cyclic included builds.
One build limits the range of versions for these reasons:
- KLIBs aren't forward compatible. For example, a
2.3consumer can't use a KMP library that the2.4compiler built. - An older KGP doesn't help, because the compiler plugin must compile against newer compiler versions.
- So the maximum range is 3 major versions (+2), with the experimental BTA
kotlin.compilerVersion. Other structures can support 5 major versions (-3 +1).- For example, using KGP
2.4.0, one can setkotlin.compilerVersion = "2.5.0", and thus support2.4.0-2.6.0. For the composite build structure, using KGP2.7.0for compiler plugin, and2.4.0for companion libraries, one can support2.4.0-2.8.0
- For example, using KGP
Each setting is available both as a DSL function of pluginDevKit { } and as a Gradle property, in
Properties.kt. Both forms add
their versions together, and the DevKit registers no version twice. A list property separates entries with
commas or whitespace. A boolean property counts as true only when its value is exactly true.
| DSL | Gradle property |
|---|---|
testAgainst("2.x.y") |
testAgainst |
cliVersions(min, max, betaAndRc) |
minCliVersion, maxCliVersion, includeBetaAndRc |
ideaVersions(min, max, includeRc, includeEap) |
minIdeaVersion, maxIdeaVersion, includeIdeaRc, includeIdeaEap |
useLatestDev(), useLatestBootstrap() |
useLatestDev, useLatestBootstrap |
defaultTestVersion("2.x.y") |
defaultTestVersion |
pluginId = "foo.bar" |
pluginId |
generatedClassesPackage = "foo.bar" |
generatedClassesPackage |
companionLibrary(...) |
companionLibraries |
-
testAgainst("2.x.y")adds a version to compile for and test against. -
cliVersions(min, max, betaAndRc)adds Release, Beta, and RC CLI versions frommintomax.minandmaxare base versions. The range compares by base version, so a bound of2.4.20also takes in2.4.20-Beta1.- Open-ended ranges are supported.
- The DevKit plugins have a built-in list of known non-dev CLI versions of
KnownVersions(#15 tracks dynamic version resolution). - The default for
betaAndRcisBetaAndRc.LATEST betaAndRcis aBetaAndRc, an enum with 3 values:NONE: Release versions in the range.LATEST: Release versions in the range, and the Beta and RC versions of the latest base version in the range. The latest base version is the next release, so it can have no Release version yet. For example, if2.5.0-Beta1exists,LATESTadds it, and no Beta or RC of an earlier base version.ALL: Release, Beta, and RC versions in the range.
-
ideaVersions(min, max, includeRc, includeEap)adds Release, RC, and EAP IDE versions.minis anIdeBuildNumber, andmaxis anInt. This matchessinceBuildanduntilBuild.- Open-ended ranges are supported
includeRcandincludeEapdefault tofalse.- It uses the IDE build mapping of Version resolution
(#15). The DevKit skips a build that
ide-mappings.txtdoesn't map to a version. - The DevKit plugins have a built-in list of known IDE builds in
ide-versions.txt, grouped by product and IDE channel (#15). The DevKit registers only the newest recorded build of each release line, so the number of targets stays reasonable. - For each IDE marketing version, for example
2026.3.3, only the latest build of each IDE channel is used. In practice, only the latest EAP of a version is used (known problem, #70). - The bounds also set the manifest attributes
Kotlin-Compiler-Plugin-Since-BuildandKotlin-Compiler-Plugin-Until-Buildof the surrogate jar.Until-Buildis<max>.*, so the jar supports every build of that series. - The function also adds Android Studio builds. Android Studio uses a stable IntelliJ IDEA release as its base.
useLatestDev/useLatestBootstrapget the latest Kotlin version from thedev/bootstraprepository and add it as a CLI version. They help automated CI checks find breaking changes.-
defaultTestVersion("2.x.y")sets the version that thedefault*Testtasks run against (possibly not useful, #71).- If the other properties don't add this version,
defaultTestVersionadds it liketestAgainstdoes. - If no default is set, the task falls back to the build's own Kotlin version if the build registers it. Otherwise it falls back to an arbitrary registered version.
- If the other properties don't add this version,
- If none of the properties above add a version, the DevKit adds the
kotlinToolingVersionof KGP as a CLI version. So the build always has at least 1 version. -
pluginId = "foo.bar"sets the plugin ID: the ID that the entry point classes report to the compiler, and the ID that the Gradle support plugin reports to Gradle.- The default is the
groupof the project.
- The default is the
-
generatedClassesPackage = "foo.bar"sets the package of the classes that the DevKit generates: the buildConfig classes and the entry point classes.- The default is
pluginId.
- The default is
-
companionLibrary(notation)adds a companion library.- Compiler plugin test data can use the library.
- The Gradle support plugin adds it as a dependency of its users.
- The DevKit reads
notationas the first format in this list that matches:- A project dependency, if it starts with
:. - A normal dependency notation, if it has
:. - A sibling dependency.
- A project dependency, if it starts with
-
companionLibrariesKotlinVersionskips KMP tests for incompatible versions. The reason is in Expected build structure.- The default is the highest
compiler_versionthe libraries' klib manifests record, so it also covers external companion libraries. - If no library has a klib, the default is the lowest registered version, so the DevKit skips no tests.
- The default is the highest
- Adds the
bootstrap,dev, andintellij-dependenciesrepositories todependencyResolutionManagement. - Applies
functional-test-publishingto every project. That plugin appliescom.autonomousapps.testkit, without thetestKitSupportFor*publication. - Has utilities for a composite build setup:
-
createVersionCatalogFrom(pathToRoot, pathToVersionCatalog, name)makes anameversion catalog from the file atpathToRoot/pathToVersionCatalog. -
includeBuildWithCheckscallsincludeBuild, and makes thechecktask of the root project depend on thechecktask of the included build.
-
- Applies
functional-test-publishing,buildconfig, andjava-gradle-plugin. - Ignores all IDE versions.
- Adds
gradle-plugin-runtimeand its test fixtures. - Registers a functional test task,
<versionName>FunctionalTest, for each CLI version (#54):- The registration logic is a copy of the testkit logic.
- The build compiles the testkit
functionalTestsource set a single time. Every task runs it against its own version. - All tasks use the
gradleUserHomeDirof the build, so the tests use dependencies that are already in its cache. No test task makes a separate Gradle cache.
- Registers an
allVersionedFunctionalTeststask, like theallTeststask of KGP. Thechecktask depends on it. - Registers a lifecycle
defaultFunctionalTesttask, which depends on the functional test task of thedefaultTestVersion. The testkit'sfunctionalTesttask also becomes a lifecycle task, runningdefaultFunctionalTest. - Publishes all project companion libraries for functional tests, and adds
them to the test runtime classpath, so reflective calls succeed.
- If a companion library comes from a project in an included build, this plugin's
installForFunctionalTesttask depends on that project'sinstallForFunctionalTesttask. - The functional test gets the
functionalTestRepoof that build through thecom.autonomousapps.plugin-under-test.repos-includedproperty. The gradle plugin test runtime reads the property, and adds the repository to the test build.
- If a companion library comes from a project in an included build, this plugin's
- Generates a
PluginInfoobject withbuildconfig, in the package ofgeneratedClassesPackage. The object has the plugin ID, the plugin coordinates, and the companion library coordinates. - Has these properties beyond the shared properties:
-
functionalTestProperties: lines that functional tests add togradle.properties. kmpTarget: the KMP target that multiplatform IC functional tests test (should just be an env var #85). The value is one of these:- A standard target name.
native_host: the native target that the current OS supports.all.
compilerPlugin: the compiler plugin thatDevKitSupportPluginapplies. The Gradle property iskotlin.compiler.plugin.devkit.compilerPlugin. The value is one of these:LocalProject: a project with the coordinates of a sibling dependency. It is published for functional tests. A value that starts with:is a project path.External: explicit coordinates. A value of the form<group>:<artifact>:<version>isExternal.Sibling: a sibling dependency. Any other value is aSibling.- Convenience functions set
LocalProjectwithcompilerPlugin(project(...)), andSiblingorExternalwithcompilerPlugin("...")
-
- Applies the Kotlin
multiplatformplugin,buildconfig,node-gradle,idea,D8Plugin, andfunctional-test-publishing. - Adds the
ExperimentalCompilerApiandUnsafeDuringIrConstructionAPIopt-ins to every compilation. - Has two variants:
compiler-pluginfor a compiler plugin, andcompiler-libraryfor the compiler plugin runtime libraries. - Features of
compiler-pluginonly:- Fails if
commandLineProcessororcomponentRegistrarisn't set. - Generates the entry point classes from
DevKitEntryPoint.template.kt. See In the compiler: plugin loading. - Embeds the dependencies into
META-INF/kotlin/plugin/<classloader-id>/dependencies. It unpacks each jar into its own subdirectory. - Embeds the entry point runtime and version resolution into
META-INF/kotlin/plugin/<classloader-id>/entryPoint. Nothing DevKit-related stays on the normal classpath except the generated entry point classes, so plugins can safely use different DevKit versions. Their package comes fromgeneratedClassesPackage, so it should be kept unique
- Fails if
- Registers a
DevKitTargetfor each version:- The target name is the target name of the version, for example
k2420_dev_7885. DevKitTargetuses theExternalKotlinTargetApi.- Most of its configuration is a copy of the Kotlin JVM target and the Android target configuration.
- A
DevKitTargethas 3 default compilations:main,testFixtures, andtest.testFixturesworks likejava-test-fixtures. - It has its own
DevKitTestRun. It is almost the same asJvmTestRun, but it setstargetNameto the version string. - The test run registers a
<targetName>Testtask, and passes it to KGP'sKotlinTestsRegistry. SoallTestsaggregates the test tasks, andcheckruns them. - A lifecycle
defaultTesttask runs the test task of thedefaultTestVersion. - With
compiler-plugin, the published POM declares no dependencies. Withcompiler-library, the published POM declares the dependencies of themaincompilation of the surrogate target. - The compilations have resources and Java support (TODO: Java support has little use here, and possibly the versions can't share Java sources).
- For IDE import, each source set gets the highest version that it supports. The
preferredVersionForSharedSourceSetsInIdeproperty overrides this for the source sets that support that version. So different source sets see different versions of the compiler, the stdlib, and the test framework. - The DevKit forces the dependencies of each target to the matching Kotlin version. It forces only the
org.jetbrains.kotlinmodules thatkotlin-modules.txtlists, the modules of thedevandintellij-dependenciesrepositories- A CLI version keeps the module names and forces their versions.
- An IDE version also maps each module to the name that it goes by in
intellij-dependencies. - The mapping
UNRELATEDrecords a module with a versioning scheme unrelated to Kotlin, so the DevKit doesn't force it. For example, the temporary Analysis API standalone artifacts - The mappings
UNSUPPORTEDandDEADrecord that no reasonable IDE equivalent exists. For an IDE version, the DevKit fails the build on them.
- The target name is the target name of the version, for example
- Has a
versionHierarchyDSL:- The
common,ide,cli, andjsgroups are registered automatically. Thejsgroup holds the CLI versions from2.3.0on, because the JS test infrastructure needs that version. It covers only thetestFixturesandtestsource set trees. -
groupVersions("name") { version -> condition }groups the versions that matchcondition. If the branch point is known,versionis the branch point. pre/post/splitgroup the versions before, from, and around a version.preDev/postDev/splitDevdo the same for a base version.- If we have
2.5.20-Beta1,2.5.20-dev-1234,2.5.0, and2.5.20registeredpre(“2.5.20”)matches2.5.20-Beta1,2.5.20-dev-1234, and2.5.0togetherpreDev(2, 5, 20)matches2.5.0alone
- If we have
versionHierarchy { }applies the groups to themain,testFixtures, andtestsource set trees. So versions share test fixtures and tests exactly like main code.
- The
- Publishes everything in one jar with a "surrogate target":
- The surrogate target is the first registered target. Its jar and its publications get the classes of all versions
in
META-INF/kotlin/plugin/<classloader-id>/versions/. - The manifest has the
Kotlin-Compiler-Plugin-Multi-Releaseattribute. For IDE support, it also hasKotlin-Compiler-Plugin-Since-BuildandKotlin-Compiler-Plugin-Until-Build. - The DevKit generates the entry point classes into a separate
entry-pointcompilation of the surrogate target.
- The surrogate target is the first registered target. Its jar and its publications get the classes of all versions
in
- Generates tests into
generatedTestsDir, defaultbuild/test-gen:-
The generator is the class that
generateTestsClassnames, in thegenerateTests*source set. The default is<generatedClassesPackage>.GenerateTestsKt. -
The generator API, for example
generateDevKitTestsWithJUnit5, comes fromcompiler-plugin-test-generator. The DevKit adds it as anapidependency of thegenerateTestssource set. -
The
generateTestsEnabledproperty turns generation off. Default is true forcompiler-plugin, and false forcompiler-library. -
All generator compilations use the newest known Kotlin version, so the generator never compiles against
compiler-tests-for-ide, which has no test generator. -
internal-test-frameworkisn't published for IDE versions. The DevKit maps it tocompiler-tests-for-ide, which has no JS test infrastructure. Also, all Kotlin versions below2.3.0have no JS test infrastructure. So the generator has 3 mutually-exclusive compilations:Task Generates for every target that… Sees the source sets… generateTestsCliNonJsis a CLI version before 2.3.0generateTests,generateTestsCli,generateTestsCliNonJsgenerateTestsJsis a CLI version from 2.3.0ongenerateTests,generateTestsCli,generateTestsJsgenerateTestsIdeis an IDE version generateTests,generateTestsIdeThe DevKit adds each compilation on the first matching target, and associates it with the
testFixturescompilation of that target. -
The DevKit marks generated tests as generated sources for IDEA, so IDEA ignores them (workaround for IDEA-339729).
-
-
classLoaderId = "foo.bar"sets the directory insideMETA-INF/kotlin/plugin/that holds the plugin's code, dependencies, and entry point runtime, so its classloaders don't see other plugins'. Only the entry point classes read it.- The default is
pluginId.
- The default is
- The resources of every test source set come from
src/<sourceSetName>/data. - Supports companion libraries, and "conditional" libraries through the
testDataLibrariesDSL:- It has the
common,jvm, andjsDependencyCollectors. - It can register named library collections.
- The DevKit passes all libraries to the compiler plugin test runtime. Tests get them through the generated
buildconfig class
TestDataLibraries.
- It has the
- Passes the libraries that
internal-test-frameworkneeds as system properties. They always match the target version. For JS tests, it also passes thed8executable and a generatedrepl.js. - Registers an artifact transform, so each compilation sees a version-specific jar of
the compiler plugin and of each
compiler-library.
- Has the interfaces for compiler plugin entry points:
-
DevKitComponentRegistrar(mimickingCompilerPluginRegistrar): hasregisterExtensionsonly. -
DevKitCLP(mimickingCommandLineProcessor): hasprocessOptionandpluginOptionsonly.
-
- Each implementation must have a public no-arg constructor, because the entry point instantiates it with reflection (add static check #86).
- The interfaces have no
pluginIdand nosupportsK2. The entry point setspluginIdto the plugin ID, andsupportsK2totrue. -
DevKitCompat.kthas compatibility functions for compiler APIs that differ between versions, for exampleKtFakeSourceElementKind.PluginGenerated. - The
entryPointcompilation hasDevKitCompilerPluginRegistrar,DevKitCommandLineProcessor, andVersionedPluginClassLoading. It compiles against the newest known CLI version, so its classes can overrideCompilerPluginRegistrar.pluginId. The property exists only from 2.3 on. On older runtimes, the extra getter is an inert new method. The classes must call only compiler APIs that every version has, because they run before the version is resolved. In the compiler: plugin loading describes these classes.
Holds the compatibility declarations that re-expose a compiler API under the name of another
version, always in the compiler's own package, so consumer code works across multiple versions with no import changes.
expect/actual can be used to avoid code duplication
The compiler-plugin and
compiler-library plugins add it as an api dependency of
commonTestFixtures. They also add junit-bom there: kotlin-test-junit5 pins JUnit Jupiter 5.10.1, but the
kotlin-compiler-internal-test-framework of Kotlin 2.4.0 and later needs 5.12.
The test bases are in the package
org.jetbrains.kotlin.compiler.plugin.devkit.runners:
-
DevKitTestis the base of every other DevKit test base:- Its constructors take configuration lambdas as a
vararg, alongside other arguments liketargetBackendor anAbstractKotlinCompilerTestto wrap - Every test gets the version classifier,
firIdenticalCompat(),configureDefaultTestDataLibraries(), andDevKitTestConfigurator. - It reads the standard library paths from the system properties that the
<target>Testtask sets. configure(builder)is final. A subclass adds configuration through the constructor or the protectedconfigurefunctions.
- Its constructors take configuration lambdas as a
- The
Backported*bases are copies ofinternal-test-frameworkbases, changed to compile against every version that they support. They use the DevKit dump handlers. The migration guide has a table mapping eachinternal-test-frameworkbase to its copy. - The
DevKit*Testrunners add default directives to a base. By default, they all use the LightTree parser.- These defaults match the compiler-plugin-template.
| Runner | Base | Default directives |
|---|---|---|
DevKitJvmBoxTest |
BackportedFirBlackBoxCodegenTestSpecBase |
DUMP_IR, FIR_DUMP, FULL_JDK, IGNORE_DEXING |
DevKitJvmDiagnosticTest |
BackportedFirPhasedDiagnosticTest |
FIR_DUMP, DISABLE_GENERATED_FIR_TAGS, FULL_JDK, IGNORE_DEXING |
DevKitJsBoxTest |
MultiVersionJsTest |
DUMP_IR, FIR_DUMP |
DevKitJsDiagnosticTest |
BackportedJsDiagnosticWithBackendTestBase |
FIR_DUMP, DISABLE_GENERATED_FIR_TAGS |
The services are in the package
org.jetbrains.kotlin.compiler.plugin.devkit.services:
-
configurePlugin(registrar)registers the extensions of aDevKitComponentRegistrar. -
configureTestDataLibrary(library) { module -> condition }adds aTestDataLibraryto the compile and runtime classpaths of the modules that match. -
DevKitTestConfiguratorskips JS tests ifTEST_COMPILER_VERSIONis lower thanBUILD_COMPILER_VERSION, because KLIBs aren't forward compatible.TEST_COMPILER_VERSIONis the version of the test task.BUILD_COMPILER_VERSIONiscompanionLibrariesKotlinVersion.
-
DevKitTestCompat.kthas compatibility declarations for test framework APIs that differ between versions.
src/jsMain compiles only for CLI versions from 2.3.0 on. It
has the JS runners:
BackportedJsTest,
MultiVersionJsTest,
BackportedJsDiagnosticWithBackendTestBase,
DevKitJsBoxTest,
and
DevKitJsDiagnosticTest.
IDE versions get no JS tests. The IDE uses only the JVM backend (for Evaluate Expression/Show Kotlin Bytecode), and
Analysis API tests cover JS diagnostics better than compiler tests.
A classified dump has classifiers in its file name, between the test name and the dump extension. For the test data file
foo.kt and the extension .fir.txt, foo.fir.txt is the unclassified dump, and foo.2420_dev_7885.fir.txt is the
dump for 2.4.20-dev-7885. A design discussion
justifies the ambiguity and fixed-classifier rules.
The model:
-
TestDumpRoot: one dimension of classifiers, for exampleversion.calculateClassifiers()lists its classifiers. -
TestDumpClassifier: one value of a root. Itsextensionis its part of the file name. ItscompatibleWithis the classifier to fall back to, ornullto fall back to no classifier of this root. ThecompatibleWithchain must have no cycles. So the classifiers of each root form a tree. -
SingleTestDumpClassifier: a root with one classifier. -
TestDumpRoot.fixedClassifiers(directives): limits a root to some of its classifiers. A classifier collapses along itscompatibleWithchain to the first fixed classifier, and the test always needs the file of that classifier. If the chain has no fixed classifier, the file name gets no classifier of this root.- Usually a directive lists the fixed classifiers.
- A file name has at most one classifier for each root, sorted by the
uniqueNameof the root. The sorting affects only the file name, not the fallback.
The directives of
TestDumpDirectives:
DUMP_CLASSIFIER: the classifiers of a test. Only the test configuration can set it, not a test data file. It must have the wholecompatibleWithchain of each classifier.- Every classifier in the chain needs a test runner that writes its file directly. This includes the last classifier of the chain. Then no fallback file is out of date.
DUMP_AS_DIFF: write each classified dump as a unified diff against the unclassified dump. The dump extension.fir.txtbecomes.fir.patch.
The DevKit dump handlers,
BackportedFirDumpHandler
and
BackportedIrTextDumpHandler,
check their dumps with
assertEqualsToDump.
assertEqualsToDump uses two files:
- The fully classified file has all classifiers of the test.
- The fallback file is the existing file with the most specific classifiers that the classifiers of the test fall back
to. If no such file exists, the fallback file is the unclassified dump.
- If the fallback is ambiguous, only the fully classified file counts. For example, a test with the classifiers
a,b, andc, one for each root, and with bothfoo.a.fir.txtandfoo.b.c.fir.txtpresent, uses neither. The most specific classifier combination isa.b.c, which matches no existing file.
- If the fallback is ambiguous, only the fully classified file counts. For example, a test with the classifiers
The first rule that matches applies:
- If the dump is empty, the fully classified file must not exist.
- If the dump is the same as the fallback file, and no classifier is fixed, the fully classified file must not exist.
- Otherwise, the dump must be the same as the fully classified file.
The version classifier:
-
classifiedDumpVersionssets the versions that get a classifier. The Gradle propertykotlin.compiler.plugin.devkit.classifiedDumpVersionssets it, and the default is every registered version.- Use it on CI, where each shard registers a single version, so no test runs twice. With this property, the version tree has a classifier for each version in the list, so each shard writes its own dump file.
- It has one classifier for each version of
classifiedDumpVersionsexcept the highest. The<target>Testtask gives these versions in the system propertykotlin.compiler.plugin.devkit.versions. - The name of a classifier is its target name without the
kprefix. - A classifier falls back to the classifier of the next higher version. The highest version writes directly to the unclassified dump.
-
DevKitTestsetsDUMP_CLASSIFIERto the chain of the version of the current compiler. Every version runs its own tests, so every classifier in the chain has a test runner that writes its file directly.
So the highest listed version uses the unclassified dump. A lower version uses the dump of the nearest higher version that has its own file. It needs its own file only if its dump is different. If a build lists a new highest version, the previous highest version can need its own files.
The classifier chain covers only the versions of classifiedDumpVersions. So a dump file for a version that is no
longer listed doesn't fail the test (#64).
-PupdateTestData sets the system property kotlin.test.update.test.data, so the test framework writes each dump that
doesn't match.
Holds the compatibility declarations that give every version the same test framework API under the name of another version, always in the test framework's own package.
Typealiases in org.jetbrains.kotlin.test.builders give every version both
NonGroupingPhaseTestConfigurationBuilder
and
NonGroupingStageTestConfigurationBuilder.
- They exist for the IDE: expect/actual with TestConfigurationBuilder confuses the IDE, because the IDE
immediately expands a typealias to a different class in each version. With these type aliases, the expanded type
is then re-expanded into the proper TestConfigurationBuilder for this version. This also helps in CLI by allowing all versions to use NonGrouping* to refer to TestConfigurationBuilder
A typealias in org.jetbrains.kotlin.test.services gives the 2.2.0 IDE versions the TestPhase
name, which their compiler spells TestPhaseLabel.
The
compiler-plugin and
compiler-library plugins add it as an api dependency of
the generateTests source set. addRuntimeDependency gates this dependency too.
It is a plain Kotlin JVM project, not a multi-version
DevKitTarget project. The
generateTests* compilations always run the generator on the newest known Kotlin version. The project
compiles it once, against the internal-test-framework of that version.
generateDevKitTestsWithJUnit5 { }
calls testGroup for each test data directory:
- The
generateTests*task gives the directories in the system propertykotlin.compiler.plugin.devkit.roots. Its value is pairs of an output directory and a comma-separated list of data directories, all separated by;. - The generated suites need different FQNs, because otherwise the Kotlin Compiler DevKit IDE plugin can't tell them
apart. Each suite is in the package
<package of the test base>.<target name>{_<index>}. The<target name>is the target name of the version that the suite tests. The generator adds_<index>for each data directory after the first.
A JVM library for the Gradle support plugin. pluginDevKit("gradle-plugin") adds it and its
test fixtures.
DevKitSupportPlugin(info)
is an abstract KotlinCompilerPluginSupportPlugin. A Gradle support plugin extends it, and gives it the generated
PluginInfo.PLUGIN_INFO, a DevKitPluginInfo(id, artifact, companionLibraryCoordinates):
isApplicablereturnstruefor every compilation.getCompilerPluginIdandgetPluginArtifactreturninfo.idandinfo.artifact.applyToCompilationis final. It adds each companion library as animplementationdependency of the default source set of the compilation, only ifProject.shouldAddRuntimeDependency().- The plugin options come from the overload
Project.applyToCompilation(kotlinCompilation), which defaults to an empty list
- The plugin options come from the overload
The test fixtures, in the package
org.jetbrains.kotlin.compiler.plugin.devkit.test,
help with functional tests. Each <versionName>FunctionalTest task gives them these system
properties:
| System property | Value | Read by |
|---|---|---|
kotlin.compiler.plugin.devkit.test.kotlin-version |
The version of the task | TEST_COMPILER_VERSION |
kotlin.compiler.plugin.devkit.build.kotlin-version |
companionLibrariesKotlinVersion |
BUILD_COMPILER_VERSION |
kotlin.compiler.plugin.devkit.test.gradle-properties |
functionalTestProperties |
AbstractDevKitGradleProject |
kotlin.compiler.plugin.devkit.gradle.test.kmpTarget |
kmpTarget |
KmpTarget.selectedTargets() |
The main fixtures:
-
AbstractDevKitGradleProject: the base class of a generated TestKit build that applies the plugin under test. A subclass setspluginUnderTest. The build has one module or several:- Its
gradle.propertieshas DevKit defaults, for example a read-only configuration cache, and thenfunctionalTestProperties. - Its settings add the
bootstrap,dev,intellij-dependencies, and DevKit EAP repositories. - The fixture skips a multiplatform build if
TEST_COMPILER_VERSIONis lower thanBUILD_COMPILER_VERSION, because KLIBs aren't forward compatible.
- Its
-
AbstractIncrementalCompilationTest: a JUnit 4 base class for incremental compilation tests of a KMP build, for oneKmpTarget. By default, it skips versions lower than2.3.21, the lowest version with working KMP incremental compilation. It skips non-JVM targets ifTEST_COMPILER_VERSIONis lower thanBUILD_COMPILER_VERSION. -
KotlinPlugins.jvm()andKotlinPlugins.multiplatform(): the Kotlin plugin of the generated build. The default version isTEST_COMPILER_VERSION. -
assertOutputContainsOnDifferentKotlinVersions(map): finds the expected text forTEST_COMPILER_VERSIONin the build output. If the map has no entry for that version, it uses the entry of the nearest lower base version.
The jar of a compiler plugin or of a compiler-library holds the classes of every version. The DevKit
selects a version at Gradle build time and at compiler and IDE runtime. Both paths use
Version resolution.
version-resolution has these parts:
-
ide-mappings.txtmaps IDE builds to IDE versions (#15). The DevKit uses it to find the correct version on Android Studio, and to find the branch point of an IDE version. -
IdeBuildNumber, a simplified version of the IntelliJBuildNumber. It sorts build numbers lexicographically by theirIntsegments. -
A function
VersionResolution.resolveVersionthat chooses a compatible version from a list of versions, for acurrentVersion. The first rule that matches applies:- If
currentVersionis in the list, return it. This is the most frequent case. - If
currentVersionis an EAP or a Release version, returnversions.filter { !it.isDev && it <= currentVersion }.maxOrNull(). - If
currentVersionis an IDE version of the form-ijXYZ-, try these steps in order:versions.filter { it.idePlatform == currentVersion.idePlatform && it <= currentVersion }.max(), that is, an earlier version from the same IDE release.- Run the algorithm again with the branch point of
XYZ, over the versions that aren't-ijversions. An-ijversion still in the list is ahead ofcurrentVersionor from another IDE release, so the rerun must not take it. versions.filter { it.hasSameBaseVersionAs(currentVersion) }.min().
- If
currentVersionis a-dev-version, or an-ijversion that rule 3 didn't resolve, try these steps in order:versions.filter { it.isDev && it.hasSameBaseVersionAs(currentVersion) && it <= currentVersion }.max().versions.filter { if (it.isDev) it <= currentVersion else it.baseVersion <= currentVersion.baseVersion }.maxOrNull(). The Release version of the base version ofcurrentVersionwins this step when the list has it.
Usually the list holds the exact version or a close one (maybe simplify #82). When it doesn't, the experience is already bad. When no rule matches,
resolveVersionreturns null. - If
The jar holds the plugin code for each version and the embedded dependencies:
- Plugin code is in
META-INF/kotlin/plugin/<classloader-id>/versions/<version>. Dependencies are inMETA-INF/kotlin/plugin/<classloader-id>/dependencies. The entry point runtime is inMETA-INF/kotlin/plugin/<classloader-id>/entryPoint. <classloader-id>in the path tells compiler plugins apart without an inspection of each jar. The DevKit inspects the jars anyway, but the path lets a customClassLoaderfind a plugin withgetResourceAsStream.- Each
<version>underversionsmust be a valid version. - Each directory under
dependenciesmust be an unpacked jar. The DevKit resolves the version of each dependency separately.
addOverlayAndDependencies
rebuilds the classpath of a plugin from its resolved version and its dependencies. It takes a classloader isolation ID,
a jar path, and the currentVersion. It adds the classpath roots to a list, and returns the resolved version, or null
when the jar has none:
- If the jar doesn't have the
Kotlin-Compiler-Plugin-Multi-Releaseattribute, return null. - List the versions in
META-INF/kotlin/plugin/<classloader-id>/versions. If the directory is empty or missing, return null. - Resolve the version with the version resolution function above.
- Add the classpath roots of each dependency, recursively, with no ID: each dependency uses the only directory under
its own
META-INF/kotlin/plugin. If a dependency has no version to select, the whole dependency directory is one classpath root. - Add
META-INF/kotlin/plugin/<classloader-id>/versions/<version>. - Add the jar root.
MultiReleasePluginTransform
selects the version for the compilations of each DevKitTarget. It is an artifact transform on the attribute
org.jetbrains.kotlin.compiler.version (
KotlinCompilerVersion):
- Every artifact type has the value
noVersion. - The compile and runtime classpaths of each compilation request the version of its target. These compilations are
exceptions:
- The
generateTests*compilations request the newest known CLI version. - The
entryPointcompilation also requests the newest known CLI version. Its classes overrideCompilerPluginRegistrar.pluginId. The property exists only from 2.3 on, so they can't compile against an older original.
- The
- The DevKit registers one transform from
noVersionto each requested version.
Two more cases get the original artifacts:
includedDependenciesandincludedEntryPointofcompiler-pluginrequestnoVersion. Thus the plugin jar embeds its dependencies with all their versions, and the compiler selects one at runtime (investigate #77).- For a project dependency, the IDE import requests
noVersion, because IDEA can't identify the project from a transformed artifact.
The transform:
- Runs the
addOverlayAndDependenciesfunction with no ID, so it uses the only directory underMETA-INF/kotlin/plugin. - Returns the artifact unchanged if the function returns no version. So the transform changes only multi-version jars, and every other dependency passes through.
- Copies the classpath roots into one artifact, in classpath order, ignoring
META-INF/kotlin/plugin. If two roots have a file with the same path, the first root wins, as in a class loader. - Names the output
<input name>-mv-<version>, where<version>is the resolved version.
The apiElements, runtimeElements, and sourcesElements variants of the non-surrogate targets (and their
*Published variants) have the extra attribute org.jetbrains.kotlin.compiler.version.fake (
FakeKotlinCompilerVersion).
Gradle prefers a variant without an extra attribute, so it selects the surrogate target (TODO disable them instead).
During IDE import,
IdeMultiVersionDependencyResolver
maps each dependency:
- If the file of a binary dependency ends with
-mv-<version>, the resolver sets thesourceSetNameof its coordinates to the target name of that version. Without it, IDEA makes one library for each GAV, and reuses one version of it in unrelated modules. - If the resolved version isn't the requested version, the suffix doesn't match, and the resolver doesn't change the coordinates (known problem).
- A project dependency that holds a multiversion jar becomes one
IdeaKotlinSourceDependencyfor each source set. The version is worked out with version resolution, and the source sets are the ones recorded for that version, including its fulldependsOnclosure. - The source set names come from the producing project's
devkitIdeSourceSetsvariant: a secondary variant of the surrogate target'sapiElements, with aUsageattribute that no real resolution requests, whose artifact is thewriteMultiVersionSourceSetsoutput. That task writes one plain file per version, holding the source set list. - The resolver also implements
IdeDependencyResolver.WithBuildDependencies: IDE import andresolveIdeDependenciesrun the producing projects'writeMultiVersionSourceSetstasks before the resolvers.
For a compiler-plugin, the generateEntryPointSource task generates the file
<generatedClassesPackage>/DevKitEntryPoint.kt in the entryPoint compilation of the surrogate target, from
DevKitEntryPoint.template.kt.
generateServices
writes the META-INF/services files for CompilerPluginRegistrar and CommandLineProcessor. They name the classes
<generatedClassesPackage>.DevKitRegistrar and <generatedClassesPackage>.DevKitProcessor. These names depend on the
shape of the template. If the template changes them, generateServices must change too.
On the first call to registerExtensions, processOption, or pluginOptions, the entry point loads the plugin:
DevKitEntryPointbuilds its own class loader. Its parent is the parent of the class loader of the generated class. Thus, the DevKit classes see the compiler, but no other plugin. The loader reads every class and resource as a resource of the plugin's class loader, withMETA-INF/kotlin/plugin/<classloader-id>/entryPoint/prepended.DevKitEntryPointloadsDevKitCompilerPluginRegistrarorDevKitCommandLineProcessorfrom that class loader, with the classloader isolation ID.- The DevKit class calls
VersionedPluginClassLoading.resolvewith the classloader isolation ID.resolvefinds the current version (see below), and the URLs of the class loader. For a class loader that isn't aURLClassLoader, it calls a publicgetUrls()method with reflection. The IntelliJUrlClassLoaderhas one. - If the version or the URLs are unknown,
resolvereturns null, and the plugin doesn't load. - Otherwise,
resolveruns theaddOverlayAndDependenciesfunction on each URL, with the classloader isolation ID.resolveignores a jar that doesn't match that ID, so other plugins don't interfere with this one. resolvemakes aURLClassLoaderover the result. Its parent is the parent of the class loader of the entry point. Thus, the plugin sees the compiler and its own classpath only. It doesn't see other plugins.resolvecaches the class loader for each classloader isolation ID.CommandLineProcessorandComponentRegistrarthen exchange the same classes throughCompilerConfiguration.- The DevKit class loads the
componentRegistrarorcommandLineProcessorclass from that class loader, makes an instance, and calls it with reflection.
The current version:
resolvegets it fromKotlinCompilerVersion.getVersion(), then maps it withCompilerVersionAliases.map.mapchanges only the placeholder version of an Android Studio Canary build,<major>.<minor>.255-dev-<n>. For this version,mapgets the IDE build number fromApplicationInfowith reflection. ThenforIdeBuildmaps the build number throughide-mappings.txt.- A build number without an entry gets the highest entry below it with the same baseline (the first number of the build number).
- Outside an IDE, or with no matching entry, the version doesn't change.
fetch-all.sh regenerates every checked-in data file, with one Python script for each file. It
aborts on the first failure: fetch-all-kotlin-modules.py exits with code 2 when a module mapping needs a human, and
fetch-all-ide-kotlin-versions.py exits with code 1 without an authenticated gh.
| File | Script | Content |
|---|---|---|
kotlin-versions.txt |
fetch-all-kotlin-versions.py |
Every Kotlin release published to Maven Central, one release on each line. |
ide-versions.txt |
fetch-all-ide-versions.py |
The known IDE builds, keyed on the platform build, grouped by product and IDE channel. |
kotlin-modules.txt |
fetch-all-kotlin-modules.py |
The org.jetbrains.kotlin modules whose versions the DevKit forces, mapped to the name that the module goes by in intellij-dependencies. |
ide-mappings.txt |
fetch-all-ide-kotlin-versions.py |
The Kotlin version that each recorded IDE build bundles. |
kotlin-versions.txthas nodevversions.ide-versions.txtuses the same key space aside-mappings.txt. The file records the channel with the build. The DevKit plugins use the channel to register the IDE versions in range.kotlin-modules.txtis hand-curated. The script only finds modules, fromdevandintellij-dependencies, and writesfoo=for a module with no mapping. The run fails when a mapping is blank, until a human fills it in.ide-mappings.txttakes each IDE build's Kotlin version from the IDE's own library declaration. The script reads the newestidea/*tag at or below that build. The apt artifacts are available inintellij-dependencies.