or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

compiler-entry-points.mdconfiguration-system.mdhigh-level-api.mdincremental-compilation.mdindex.mdmessage-collection.mdplugin-system.md

index.mddocs/

0

# Kotlin Compiler Embeddable

1

2

The 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.

3

4

## Package Information

5

6

- **Package Name**: kotlin-compiler-embeddable

7

- **Package Type**: maven

8

- **Language**: Kotlin/Java

9

- **Group ID**: org.jetbrains.kotlin

10

- **Artifact ID**: kotlin-compiler-embeddable

11

- **Version**: 2.2.0

12

- **Installation**:

13

```gradle

14

implementation 'org.jetbrains.kotlin:kotlin-compiler-embeddable:2.2.0'

15

```

16

```xml

17

<!-- Maven -->

18

<dependency>

19

<groupId>org.jetbrains.kotlin</groupId>

20

<artifactId>kotlin-compiler-embeddable</artifactId>

21

<version>2.2.0</version>

22

</dependency>

23

```

24

25

## Core Imports

26

27

```kotlin

28

import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler

29

import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments

30

import org.jetbrains.kotlin.cli.common.messages.MessageCollector

31

import org.jetbrains.kotlin.config.Services

32

```

33

34

For high-level API:

35

36

```kotlin

37

import org.jetbrains.kotlin.buildtools.api.CompilationService

38

import org.jetbrains.kotlin.buildtools.api.jvm.JvmCompilationConfiguration

39

```

40

41

## Basic Usage

42

43

```kotlin

44

// High-level API approach (recommended)

45

val classLoader = this::class.java.classLoader

46

val service = CompilationService.loadImplementation(classLoader)

47

val executionConfig = service.makeCompilerExecutionStrategyConfiguration()

48

val compilationConfig = service.makeJvmCompilationConfiguration().apply {

49

// Configure compilation settings

50

}

51

52

val result = service.compileJvm(

53

projectId = "my-project",

54

strategyConfig = executionConfig,

55

compilationConfig = compilationConfig,

56

sources = listOf(sourceFile),

57

arguments = emptyList()

58

)

59

60

// Low-level CLI API approach

61

val compiler = K2JVMCompiler()

62

val arguments = K2JVMCompilerArguments().apply {

63

destination = "output/classes"

64

classpath = "path/to/classpath"

65

jvmTarget = "17"

66

}

67

68

val messageCollector = object : MessageCollector {

69

override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) {

70

println("[$severity] $message")

71

}

72

override fun hasErrors(): Boolean = false

73

override fun clear() {}

74

}

75

76

val exitCode = compiler.exec(messageCollector, Services.EMPTY, arguments)

77

```

78

79

## Architecture

80

81

The Kotlin Compiler Embeddable is built around several key components with special emphasis on avoiding classpath conflicts:

82

83

- **Compiler Frontend**: Core compilation entry points (`K2JVMCompiler`, `CLICompiler`) for programmatic compilation

84

- **Configuration System**: Thread-safe configuration management (`CompilerConfiguration`) with type-safe key-value storage

85

- **Message Collection**: Comprehensive diagnostic and error reporting system with customizable output

86

- **High-level API**: Modern build tools integration API (`CompilationService`) for simplified usage

87

- **Plugin System**: Extension points for compiler plugins and custom compilation phases

88

- **Incremental Compilation**: Support for incremental builds with change tracking and optimization

89

- **Services Framework**: Dependency injection container for compiler extensions and services

90

- **Shaded Dependencies**: All IntelliJ platform and third-party dependencies are relocated under `org.jetbrains.kotlin.*` package prefixes to prevent classpath conflicts with host applications

91

92

### Dependency Shading

93

94

The embeddable compiler differs from the regular compiler by relocating potentially conflicting dependencies:

95

96

**Relocated packages include:**

97

- `com.intellij.*``org.jetbrains.kotlin.com.intellij.*`

98

- `com.google.protobuf.*``org.jetbrains.kotlin.protobuf.*`

99

- `javax.inject.*``org.jetbrains.kotlin.javax.inject.*`

100

- And many more third-party libraries (Guava, Apache Commons, etc.)

101

102

**Excluded packages:**

103

- JNA native libraries (`com/sun/jna/**`)

104

- JetBrains annotations to avoid version conflicts

105

106

This makes the embeddable compiler safe to use in applications that may have their own versions of these dependencies.

107

108

## Capabilities

109

110

### Compiler Entry Points

111

112

Main compiler classes providing programmatic access to Kotlin compilation with support for both K1 and K2 compiler backends.

113

114

```kotlin { .api }

115

class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {

116

fun exec(messageCollector: MessageCollector, services: Services, arguments: K2JVMCompilerArguments): ExitCode

117

fun exec(errStream: PrintStream, services: Services, messageRenderer: MessageRenderer, args: Array<String>): ExitCode

118

119

companion object {

120

@JvmStatic fun main(args: Array<String>): Unit

121

}

122

}

123

124

abstract class CLICompiler<A : CommonCompilerArguments> {

125

fun exec(errStream: PrintStream, services: Services, messageRenderer: MessageRenderer, args: Array<String>): ExitCode

126

fun execAndOutputXml(errStream: PrintStream, services: Services, vararg args: String): ExitCode

127

}

128

```

129

130

[Compiler Entry Points](./compiler-entry-points.md)

131

132

### Configuration System

133

134

Comprehensive configuration management providing type-safe, thread-safe storage for compiler settings and options.

135

136

```kotlin { .api }

137

class CompilerConfiguration {

138

fun <T> get(key: CompilerConfigurationKey<T>): T?

139

fun <T> put(key: CompilerConfigurationKey<T>, value: T): Unit

140

fun <T> getNotNull(key: CompilerConfigurationKey<T>): T

141

fun <T> add(key: CompilerConfigurationKey<List<T>>, value: T): Unit

142

fun <T> getBoolean(key: CompilerConfigurationKey<Boolean>): Boolean

143

fun <T> getList(key: CompilerConfigurationKey<List<T>>): List<T>

144

fun <K, V> getMap(key: CompilerConfigurationKey<Map<K, V>>): Map<K, V>

145

fun copy(): CompilerConfiguration

146

fun setReadOnly(readOnly: Boolean): Unit

147

fun isReadOnly(): Boolean

148

}

149

150

class CompilerConfigurationKey<T> private constructor(val name: String) {

151

companion object {

152

fun <T> create(debugName: String): CompilerConfigurationKey<T>

153

}

154

}

155

156

class K2JVMCompilerArguments : CommonCompilerArguments() {

157

var destination: String?

158

var classpath: String?

159

var jvmTarget: String?

160

var javaParameters: Boolean

161

}

162

```

163

164

[Configuration System](./configuration-system.md)

165

166

### Message Collection and Diagnostics

167

168

Comprehensive diagnostic collection system for compilation errors, warnings, and informational messages with customizable output formatting.

169

170

```kotlin { .api }

171

interface MessageCollector {

172

fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?): Unit

173

fun hasErrors(): Boolean

174

fun clear(): Unit

175

}

176

177

enum class CompilerMessageSeverity {

178

EXCEPTION, ERROR, STRONG_WARNING, WARNING, INFO, LOGGING, OUTPUT

179

}

180

```

181

182

[Message Collection](./message-collection.md)

183

184

### High-Level Compilation API

185

186

Modern build tools integration API providing simplified access to compilation functionality with reduced complexity.

187

188

```kotlin { .api }

189

interface CompilationService {

190

fun compileJvm(

191

projectId: String,

192

strategyConfig: CompilerExecutionStrategyConfiguration,

193

compilationConfig: JvmCompilationConfiguration,

194

sources: List<File>,

195

arguments: List<String>

196

): CompilationResult

197

198

fun makeCompilerExecutionStrategyConfiguration(): CompilerExecutionStrategyConfiguration

199

fun makeJvmCompilationConfiguration(): JvmCompilationConfiguration

200

fun calculateClasspathSnapshot(classpathEntry: File, granularity: ClassSnapshotGranularity): ClasspathEntrySnapshot

201

fun finishProjectCompilation(projectId: String): Unit

202

fun getCustomKotlinScriptFilenameExtensions(classpath: List<File>): Collection<String>

203

fun getCompilerVersion(): String

204

205

companion object {

206

fun loadImplementation(classLoader: ClassLoader): CompilationService

207

}

208

}

209

```

210

211

[High-Level Compilation API](./high-level-api.md)

212

213

### Plugin System and Extensions

214

215

Extension framework for compiler plugins, custom compilation phases, and code generation hooks.

216

217

```kotlin { .api }

218

interface CompilerPluginRegistrar {

219

fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration): Unit

220

}

221

222

interface ComponentRegistrar {

223

fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration): Unit

224

}

225

```

226

227

[Plugin System](./plugin-system.md)

228

229

### Incremental Compilation Support

230

231

Advanced incremental compilation capabilities with change tracking, dependency analysis, and compilation optimization.

232

233

```kotlin { .api }

234

interface IncrementalCompilationComponents {

235

val lookupTracker: LookupTracker

236

val expectActualTracker: ExpectActualTracker

237

val inlineConstTracker: InlineConstTracker

238

}

239

240

interface LookupTracker {

241

fun record(filePath: String, position: Int, scopeFqName: String, name: String): Unit

242

}

243

```

244

245

[Incremental Compilation](./incremental-compilation.md)

246

247

## Common Types

248

249

```kotlin { .api }

250

enum class ExitCode {

251

OK, COMPILATION_ERROR, INTERNAL_ERROR, OOM_ERROR

252

}

253

254

class Services private constructor() {

255

/** Get service instance by type */

256

inline fun <reified T : Any> get(): T?

257

258

/** Get service instance by class */

259

fun <T : Any> get(serviceClass: Class<T>): T?

260

261

/** Register service instance */

262

fun <T : Any> register(serviceClass: Class<T>, service: T): Unit

263

264

/** Check if service is registered */

265

fun <T : Any> isRegistered(serviceClass: Class<T>): Boolean

266

267

/** Create services builder */

268

companion object {

269

val EMPTY: Services

270

271

/** Create services builder for registration */

272

fun builder(): Builder

273

}

274

275

/** Builder for creating Services instances */

276

class Builder {

277

fun <T : Any> register(serviceClass: Class<T>, service: T): Builder

278

inline fun <reified T : Any> register(service: T): Builder

279

fun build(): Services

280

}

281

}

282

283

data class CompilerMessageSourceLocation(

284

val path: String,

285

val line: Int,

286

val column: Int,

287

val lineContent: String? = null

288

)

289

290

interface CompilationResult {

291

val isSuccessful: Boolean

292

val hasErrors: Boolean

293

val hasWarnings: Boolean

294

}

295

296

// Additional core types referenced throughout the API

297

298

interface Disposable {

299

fun dispose(): Unit

300

}

301

302

interface LanguageVersionSettings {

303

val languageVersion: LanguageVersion

304

val apiVersion: ApiVersion

305

val progressiveMode: Boolean

306

val enabledLanguageFeatures: Set<LanguageFeature>

307

}

308

309

enum class LanguageVersion(val versionString: String) {

310

KOTLIN_1_4("1.4"),

311

KOTLIN_1_5("1.5"),

312

KOTLIN_1_6("1.6"),

313

KOTLIN_1_7("1.7"),

314

KOTLIN_1_8("1.8"),

315

KOTLIN_1_9("1.9"),

316

KOTLIN_2_0("2.0");

317

318

companion object {

319

val LATEST_STABLE: LanguageVersion = KOTLIN_2_0

320

}

321

}

322

323

enum class ApiVersion(val versionString: String) {

324

KOTLIN_1_4("1.4"),

325

KOTLIN_1_5("1.5"),

326

KOTLIN_1_6("1.6"),

327

KOTLIN_1_7("1.7"),

328

KOTLIN_1_8("1.8"),

329

KOTLIN_1_9("1.9"),

330

KOTLIN_2_0("2.0")

331

}

332

333

abstract class BinaryVersion(

334

val major: Int,

335

val minor: Int,

336

val patch: Int

337

) {

338

abstract val description: String

339

fun isCompatible(other: BinaryVersion): Boolean

340

}

341

342

interface KotlinPaths {

343

val homePath: File

344

val libPath: File

345

val stdlibPath: File

346

val reflectPath: File

347

val kotlinTestPath: File

348

}

349

350

interface PhaseConfig {

351

val enabled: Set<String>

352

val disabled: Set<String>

353

val verbose: Set<String>

354

fun isEnabled(phase: String): Boolean

355

}

356

357

abstract class KotlinCoreEnvironment(

358

parentDisposable: Disposable,

359

configuration: CompilerConfiguration

360

) : Disposable {

361

val configuration: CompilerConfiguration

362

val project: Project

363

364

companion object {

365

fun createForProduction(

366

parentDisposable: Disposable,

367

configuration: CompilerConfiguration,

368

configFiles: EnvironmentConfigFiles

369

): KotlinCoreEnvironment

370

371

fun createForTests(

372

parentDisposable: Disposable,

373

initialConfiguration: CompilerConfiguration,

374

extensionConfigs: EnvironmentConfigFiles

375

): KotlinCoreEnvironment

376

}

377

}

378

379

enum class EnvironmentConfigFiles {

380

JVM_CONFIG_FILES, JS_CONFIG_FILES, NATIVE_CONFIG_FILES, METADATA_CONFIG_FILES

381

}

382

383

interface ClassSnapshotGranularity

384

interface ClasspathEntrySnapshot

385

interface CompilerExecutionStrategyConfiguration

386

interface JvmCompilationConfiguration

387

```