Self-contained embeddable Kotlin compiler with shaded dependencies for integration into applications without classpath conflicts
npx @tessl/cli install tessl/maven-org-jetbrains-kotlin--kotlin-compiler-embeddable@2.2.0The Kotlin Compiler Embeddable provides a self-contained, embeddable version of the Kotlin compiler designed for integration into applications and build tools. It includes all necessary dependencies with shaded/relocated packages to prevent classpath conflicts when used alongside other libraries, making it ideal for IDE plugins, build systems, code analysis tools, and any application that needs to compile Kotlin code programmatically.
implementation 'org.jetbrains.kotlin:kotlin-compiler-embeddable:2.2.0'<!-- Maven -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-compiler-embeddable</artifactId>
<version>2.2.0</version>
</dependency>import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.ServicesFor high-level API:
import org.jetbrains.kotlin.buildtools.api.CompilationService
import org.jetbrains.kotlin.buildtools.api.jvm.JvmCompilationConfiguration// High-level API approach (recommended)
val classLoader = this::class.java.classLoader
val service = CompilationService.loadImplementation(classLoader)
val executionConfig = service.makeCompilerExecutionStrategyConfiguration()
val compilationConfig = service.makeJvmCompilationConfiguration().apply {
// Configure compilation settings
}
val result = service.compileJvm(
projectId = "my-project",
strategyConfig = executionConfig,
compilationConfig = compilationConfig,
sources = listOf(sourceFile),
arguments = emptyList()
)
// Low-level CLI API approach
val compiler = K2JVMCompiler()
val arguments = K2JVMCompilerArguments().apply {
destination = "output/classes"
classpath = "path/to/classpath"
jvmTarget = "17"
}
val messageCollector = object : MessageCollector {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) {
println("[$severity] $message")
}
override fun hasErrors(): Boolean = false
override fun clear() {}
}
val exitCode = compiler.exec(messageCollector, Services.EMPTY, arguments)The Kotlin Compiler Embeddable is built around several key components with special emphasis on avoiding classpath conflicts:
K2JVMCompiler, CLICompiler) for programmatic compilationCompilerConfiguration) with type-safe key-value storageCompilationService) for simplified usageorg.jetbrains.kotlin.* package prefixes to prevent classpath conflicts with host applicationsThe embeddable compiler differs from the regular compiler by relocating potentially conflicting dependencies:
Relocated packages include:
com.intellij.* → org.jetbrains.kotlin.com.intellij.*com.google.protobuf.* → org.jetbrains.kotlin.protobuf.*javax.inject.* → org.jetbrains.kotlin.javax.inject.*Excluded packages:
com/sun/jna/**)This makes the embeddable compiler safe to use in applications that may have their own versions of these dependencies.
Main compiler classes providing programmatic access to Kotlin compilation with support for both K1 and K2 compiler backends.
class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
fun exec(messageCollector: MessageCollector, services: Services, arguments: K2JVMCompilerArguments): ExitCode
fun exec(errStream: PrintStream, services: Services, messageRenderer: MessageRenderer, args: Array<String>): ExitCode
companion object {
@JvmStatic fun main(args: Array<String>): Unit
}
}
abstract class CLICompiler<A : CommonCompilerArguments> {
fun exec(errStream: PrintStream, services: Services, messageRenderer: MessageRenderer, args: Array<String>): ExitCode
fun execAndOutputXml(errStream: PrintStream, services: Services, vararg args: String): ExitCode
}Comprehensive configuration management providing type-safe, thread-safe storage for compiler settings and options.
class CompilerConfiguration {
fun <T> get(key: CompilerConfigurationKey<T>): T?
fun <T> put(key: CompilerConfigurationKey<T>, value: T): Unit
fun <T> getNotNull(key: CompilerConfigurationKey<T>): T
fun <T> add(key: CompilerConfigurationKey<List<T>>, value: T): Unit
fun <T> getBoolean(key: CompilerConfigurationKey<Boolean>): Boolean
fun <T> getList(key: CompilerConfigurationKey<List<T>>): List<T>
fun <K, V> getMap(key: CompilerConfigurationKey<Map<K, V>>): Map<K, V>
fun copy(): CompilerConfiguration
fun setReadOnly(readOnly: Boolean): Unit
fun isReadOnly(): Boolean
}
class CompilerConfigurationKey<T> private constructor(val name: String) {
companion object {
fun <T> create(debugName: String): CompilerConfigurationKey<T>
}
}
class K2JVMCompilerArguments : CommonCompilerArguments() {
var destination: String?
var classpath: String?
var jvmTarget: String?
var javaParameters: Boolean
}Comprehensive diagnostic collection system for compilation errors, warnings, and informational messages with customizable output formatting.
interface MessageCollector {
fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?): Unit
fun hasErrors(): Boolean
fun clear(): Unit
}
enum class CompilerMessageSeverity {
EXCEPTION, ERROR, STRONG_WARNING, WARNING, INFO, LOGGING, OUTPUT
}Modern build tools integration API providing simplified access to compilation functionality with reduced complexity.
interface CompilationService {
fun compileJvm(
projectId: String,
strategyConfig: CompilerExecutionStrategyConfiguration,
compilationConfig: JvmCompilationConfiguration,
sources: List<File>,
arguments: List<String>
): CompilationResult
fun makeCompilerExecutionStrategyConfiguration(): CompilerExecutionStrategyConfiguration
fun makeJvmCompilationConfiguration(): JvmCompilationConfiguration
fun calculateClasspathSnapshot(classpathEntry: File, granularity: ClassSnapshotGranularity): ClasspathEntrySnapshot
fun finishProjectCompilation(projectId: String): Unit
fun getCustomKotlinScriptFilenameExtensions(classpath: List<File>): Collection<String>
fun getCompilerVersion(): String
companion object {
fun loadImplementation(classLoader: ClassLoader): CompilationService
}
}Extension framework for compiler plugins, custom compilation phases, and code generation hooks.
interface CompilerPluginRegistrar {
fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration): Unit
}
interface ComponentRegistrar {
fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration): Unit
}Advanced incremental compilation capabilities with change tracking, dependency analysis, and compilation optimization.
interface IncrementalCompilationComponents {
val lookupTracker: LookupTracker
val expectActualTracker: ExpectActualTracker
val inlineConstTracker: InlineConstTracker
}
interface LookupTracker {
fun record(filePath: String, position: Int, scopeFqName: String, name: String): Unit
}enum class ExitCode {
OK, COMPILATION_ERROR, INTERNAL_ERROR, OOM_ERROR
}
class Services private constructor() {
/** Get service instance by type */
inline fun <reified T : Any> get(): T?
/** Get service instance by class */
fun <T : Any> get(serviceClass: Class<T>): T?
/** Register service instance */
fun <T : Any> register(serviceClass: Class<T>, service: T): Unit
/** Check if service is registered */
fun <T : Any> isRegistered(serviceClass: Class<T>): Boolean
/** Create services builder */
companion object {
val EMPTY: Services
/** Create services builder for registration */
fun builder(): Builder
}
/** Builder for creating Services instances */
class Builder {
fun <T : Any> register(serviceClass: Class<T>, service: T): Builder
inline fun <reified T : Any> register(service: T): Builder
fun build(): Services
}
}
data class CompilerMessageSourceLocation(
val path: String,
val line: Int,
val column: Int,
val lineContent: String? = null
)
interface CompilationResult {
val isSuccessful: Boolean
val hasErrors: Boolean
val hasWarnings: Boolean
}
// Additional core types referenced throughout the API
interface Disposable {
fun dispose(): Unit
}
interface LanguageVersionSettings {
val languageVersion: LanguageVersion
val apiVersion: ApiVersion
val progressiveMode: Boolean
val enabledLanguageFeatures: Set<LanguageFeature>
}
enum class LanguageVersion(val versionString: String) {
KOTLIN_1_4("1.4"),
KOTLIN_1_5("1.5"),
KOTLIN_1_6("1.6"),
KOTLIN_1_7("1.7"),
KOTLIN_1_8("1.8"),
KOTLIN_1_9("1.9"),
KOTLIN_2_0("2.0");
companion object {
val LATEST_STABLE: LanguageVersion = KOTLIN_2_0
}
}
enum class ApiVersion(val versionString: String) {
KOTLIN_1_4("1.4"),
KOTLIN_1_5("1.5"),
KOTLIN_1_6("1.6"),
KOTLIN_1_7("1.7"),
KOTLIN_1_8("1.8"),
KOTLIN_1_9("1.9"),
KOTLIN_2_0("2.0")
}
abstract class BinaryVersion(
val major: Int,
val minor: Int,
val patch: Int
) {
abstract val description: String
fun isCompatible(other: BinaryVersion): Boolean
}
interface KotlinPaths {
val homePath: File
val libPath: File
val stdlibPath: File
val reflectPath: File
val kotlinTestPath: File
}
interface PhaseConfig {
val enabled: Set<String>
val disabled: Set<String>
val verbose: Set<String>
fun isEnabled(phase: String): Boolean
}
abstract class KotlinCoreEnvironment(
parentDisposable: Disposable,
configuration: CompilerConfiguration
) : Disposable {
val configuration: CompilerConfiguration
val project: Project
companion object {
fun createForProduction(
parentDisposable: Disposable,
configuration: CompilerConfiguration,
configFiles: EnvironmentConfigFiles
): KotlinCoreEnvironment
fun createForTests(
parentDisposable: Disposable,
initialConfiguration: CompilerConfiguration,
extensionConfigs: EnvironmentConfigFiles
): KotlinCoreEnvironment
}
}
enum class EnvironmentConfigFiles {
JVM_CONFIG_FILES, JS_CONFIG_FILES, NATIVE_CONFIG_FILES, METADATA_CONFIG_FILES
}
interface ClassSnapshotGranularity
interface ClasspathEntrySnapshot
interface CompilerExecutionStrategyConfiguration
interface JvmCompilationConfiguration