0
# High-Level Compilation API
1
2
Modern build tools integration API providing simplified access to compilation functionality with reduced complexity. The high-level API abstracts away low-level compiler details and provides a clean interface for build tools and automation systems.
3
4
## Capabilities
5
6
### CompilationService
7
8
Primary high-level interface for build tools integration providing simplified compilation functionality.
9
10
```kotlin { .api }
11
/**
12
* High-level compilation service interface for build tools integration
13
* Provides simplified access to Kotlin compilation functionality
14
*/
15
interface CompilationService {
16
/** Compile JVM sources with specified configuration */
17
fun compileJvm(
18
projectId: String,
19
strategyConfig: CompilerExecutionStrategyConfiguration,
20
compilationConfig: JvmCompilationConfiguration,
21
sources: List<File>,
22
arguments: List<String>
23
): CompilationResult
24
25
/** Create execution strategy configuration */
26
fun makeCompilerExecutionStrategyConfiguration(): CompilerExecutionStrategyConfiguration
27
28
/** Create JVM compilation configuration */
29
fun makeJvmCompilationConfiguration(): JvmCompilationConfiguration
30
31
/** Calculate classpath snapshot for incremental compilation */
32
fun calculateClasspathSnapshot(
33
classpathEntries: List<File>,
34
lookupSymbols: Set<String>
35
): ClasspathSnapshot
36
37
/** Finalize project compilation and cleanup resources */
38
fun finishProjectCompilation(projectId: String): Unit
39
40
companion object {
41
/** Load compilation service implementation */
42
fun loadImplementation(classLoader: ClassLoader): CompilationService
43
}
44
}
45
```
46
47
**Usage Examples:**
48
49
```kotlin
50
// Basic high-level compilation
51
val classLoader = this::class.java.classLoader
52
val service = CompilationService.loadImplementation(classLoader)
53
54
val executionConfig = service.makeCompilerExecutionStrategyConfiguration()
55
val compilationConfig = service.makeJvmCompilationConfiguration().apply {
56
moduleName = "my-module"
57
outputDirectory = File("build/classes")
58
classpath = listOf(File("libs/kotlin-stdlib.jar"))
59
jvmTarget = "17"
60
}
61
62
val sources = listOf(
63
File("src/main/kotlin/Main.kt"),
64
File("src/main/kotlin/Utils.kt")
65
)
66
67
val result = service.compileJvm(
68
projectId = "my-project",
69
strategyConfig = executionConfig,
70
compilationConfig = compilationConfig,
71
sources = sources,
72
arguments = emptyList()
73
)
74
75
if (result.isSuccessful) {
76
println("Compilation successful")
77
} else {
78
println("Compilation failed: ${result.errors}")
79
}
80
81
// Cleanup
82
service.finishProjectCompilation("my-project")
83
```
84
85
### JvmCompilationConfiguration
86
87
Configuration interface for JVM compilation settings.
88
89
```kotlin { .api }
90
/**
91
* JVM compilation configuration interface
92
* Provides fluent API for configuring JVM compilation
93
*/
94
interface JvmCompilationConfiguration {
95
/** Module name for the compilation */
96
var moduleName: String?
97
98
/** Output directory for compiled classes */
99
var outputDirectory: File?
100
101
/** Classpath entries for compilation */
102
var classpath: List<File>
103
104
/** JVM target version */
105
var jvmTarget: String
106
107
/** Include Kotlin runtime in output */
108
var includeRuntime: Boolean
109
110
/** Enable/disable incremental compilation */
111
var incrementalCompilation: Boolean
112
113
/** Source directories */
114
var sourceRoots: List<File>
115
116
/** Java source directories */
117
var javaSourceRoots: List<File>
118
119
/** Friend modules for internal visibility */
120
var friendModules: List<String>
121
122
/** Language version */
123
var languageVersion: String?
124
125
/** API version */
126
var apiVersion: String?
127
128
/** Compiler plugin configurations */
129
var pluginConfigurations: List<PluginConfiguration>
130
131
/** Free-form compiler arguments */
132
var freeCompilerArgs: List<String>
133
}
134
```
135
136
### CompilerExecutionStrategyConfiguration
137
138
Configuration for compiler execution strategy and performance settings.
139
140
```kotlin { .api }
141
/**
142
* Configuration for compiler execution strategy
143
* Controls how compilation is executed and performance characteristics
144
*/
145
interface CompilerExecutionStrategyConfiguration {
146
/** Use in-process compilation (faster but less isolated) */
147
var useInProcessCompilation: Boolean
148
149
/** Use daemon compilation (persistent compiler process) */
150
var useDaemonCompilation: Boolean
151
152
/** Maximum heap size for compilation process */
153
var maxHeapSize: String?
154
155
/** JVM arguments for compilation process */
156
var jvmArgs: List<String>
157
158
/** Enable parallel compilation */
159
var parallelCompilation: Boolean
160
161
/** Number of worker threads for parallel compilation */
162
var workerThreads: Int
163
164
/** Enable compilation performance reporting */
165
var reportPerformance: Boolean
166
167
/** Compilation timeout in milliseconds */
168
var compilationTimeout: Long
169
}
170
```
171
172
### CompilationResult
173
174
Result interface providing compilation outcome and diagnostic information.
175
176
```kotlin { .api }
177
/**
178
* Result of a compilation operation
179
* Provides success status and diagnostic information
180
*/
181
interface CompilationResult {
182
/** Whether compilation completed successfully */
183
val isSuccessful: Boolean
184
185
/** Whether compilation had any errors */
186
val hasErrors: Boolean
187
188
/** Whether compilation had any warnings */
189
val hasWarnings: Boolean
190
191
/** Exit code from compilation */
192
val exitCode: ExitCode
193
194
/** List of compilation errors */
195
val errors: List<CompilationMessage>
196
197
/** List of compilation warnings */
198
val warnings: List<CompilationMessage>
199
200
/** All compilation messages */
201
val messages: List<CompilationMessage>
202
203
/** Compilation duration in milliseconds */
204
val compilationDuration: Long
205
206
/** Number of files compiled */
207
val filesCompiled: Int
208
209
/** Generated output files */
210
val outputFiles: List<File>
211
}
212
213
/**
214
* Individual compilation message with severity and location
215
*/
216
data class CompilationMessage(
217
val severity: CompilerMessageSeverity,
218
val message: String,
219
val sourceLocation: CompilerMessageSourceLocation?
220
)
221
```
222
223
### Classpath Management
224
225
Support for incremental compilation through classpath snapshots.
226
227
```kotlin { .api }
228
/**
229
* Snapshot of classpath state for incremental compilation
230
* Tracks changes to dependencies for optimization
231
*/
232
interface ClasspathSnapshot {
233
/** Classpath entries included in this snapshot */
234
val classpathEntries: List<ClasspathEntrySnapshot>
235
236
/** Lookup symbols used in this compilation */
237
val lookupSymbols: Set<String>
238
239
/** Timestamp when snapshot was created */
240
val timestamp: Long
241
242
/** Check if classpath has changed since this snapshot */
243
fun hasChanged(currentClasspath: List<File>): Boolean
244
245
/** Get changed classpath entries */
246
fun getChangedEntries(currentClasspath: List<File>): List<ClasspathEntrySnapshot>
247
}
248
249
/**
250
* Individual classpath entry snapshot
251
*/
252
interface ClasspathEntrySnapshot {
253
/** File path of the classpath entry */
254
val file: File
255
256
/** Hash of the file content */
257
val contentHash: String
258
259
/** Last modified timestamp */
260
val lastModified: Long
261
262
/** Size of the file */
263
val size: Long
264
265
/** Exported symbols from this entry */
266
val exportedSymbols: Set<String>
267
}
268
```
269
270
**Advanced Usage Examples:**
271
272
```kotlin
273
// Incremental compilation with classpath tracking
274
val service = CompilationService.loadImplementation(classLoader)
275
276
val classpathEntries = listOf(
277
File("libs/kotlin-stdlib.jar"),
278
File("libs/kotlinx-coroutines-core.jar")
279
)
280
281
// Calculate initial classpath snapshot
282
val initialSnapshot = service.calculateClasspathSnapshot(
283
classpathEntries = classpathEntries,
284
lookupSymbols = setOf("kotlin.String", "kotlinx.coroutines.launch")
285
)
286
287
val compilationConfig = service.makeJvmCompilationConfiguration().apply {
288
moduleName = "incremental-example"
289
outputDirectory = File("build/classes")
290
classpath = classpathEntries
291
incrementalCompilation = true
292
jvmTarget = "17"
293
}
294
295
val executionConfig = service.makeCompilerExecutionStrategyConfiguration().apply {
296
useInProcessCompilation = true
297
parallelCompilation = true
298
workerThreads = 4
299
reportPerformance = true
300
}
301
302
// First compilation
303
val result1 = service.compileJvm(
304
projectId = "incremental-project",
305
strategyConfig = executionConfig,
306
compilationConfig = compilationConfig,
307
sources = listOf(File("src/Main.kt")),
308
arguments = emptyList()
309
)
310
311
println("First compilation: ${result1.compilationDuration}ms, ${result1.filesCompiled} files")
312
313
// Check for classpath changes
314
if (!initialSnapshot.hasChanged(classpathEntries)) {
315
println("Classpath unchanged, incremental compilation will be more efficient")
316
}
317
318
// Second compilation (should be faster due to incremental)
319
val result2 = service.compileJvm(
320
projectId = "incremental-project",
321
strategyConfig = executionConfig,
322
compilationConfig = compilationConfig,
323
sources = listOf(File("src/Main.kt"), File("src/NewFile.kt")),
324
arguments = emptyList()
325
)
326
327
println("Second compilation: ${result2.compilationDuration}ms, ${result2.filesCompiled} files")
328
329
// Plugin configuration example
330
compilationConfig.pluginConfigurations = listOf(
331
PluginConfiguration(
332
pluginId = "org.jetbrains.kotlin.plugin.serialization",
333
options = mapOf("enabled" to "true")
334
)
335
)
336
337
// Daemon compilation for better performance
338
executionConfig.apply {
339
useDaemonCompilation = true
340
maxHeapSize = "2g"
341
jvmArgs = listOf("-XX:+UseG1GC", "-XX:MaxMetaspaceSize=512m")
342
compilationTimeout = 300_000 // 5 minutes
343
}
344
345
service.finishProjectCompilation("incremental-project")
346
```
347
348
### Plugin Configuration
349
350
Support for compiler plugins through the high-level API.
351
352
```kotlin { .api }
353
/**
354
* Configuration for compiler plugins
355
*/
356
data class PluginConfiguration(
357
/** Plugin identifier */
358
val pluginId: String,
359
360
/** Plugin options as key-value pairs */
361
val options: Map<String, String>,
362
363
/** Plugin classpath entries */
364
val classpath: List<File> = emptyList(),
365
366
/** Plugin version (optional) */
367
val version: String? = null
368
)
369
```
370
371
### Error Handling and Diagnostics
372
373
```kotlin { .api }
374
/**
375
* Exception thrown when compilation service encounters errors
376
*/
377
class CompilationServiceException(
378
message: String,
379
cause: Throwable? = null
380
) : Exception(message, cause)
381
382
/**
383
* Exception thrown when compilation configuration is invalid
384
*/
385
class InvalidCompilationConfigurationException(
386
message: String,
387
val configurationErrors: List<String>
388
) : Exception(message)
389
390
/**
391
* Performance metrics for compilation
392
*/
393
interface CompilationMetrics {
394
/** Total compilation time */
395
val totalTime: Long
396
397
/** Analysis phase time */
398
val analysisTime: Long
399
400
/** Code generation time */
401
val codeGenerationTime: Long
402
403
/** I/O time */
404
val ioTime: Long
405
406
/** Memory usage statistics */
407
val memoryUsage: MemoryUsage
408
409
/** GC statistics */
410
val gcStatistics: GcStatistics
411
}
412
```
413
414
## Integration Patterns
415
416
```kotlin
417
// Build tool integration
418
class KotlinCompilationTask {
419
private val compilationService = CompilationService.loadImplementation(
420
KotlinCompilationTask::class.java.classLoader
421
)
422
423
fun execute() {
424
try {
425
val config = createCompilationConfiguration()
426
val executionConfig = createExecutionConfiguration()
427
428
val result = compilationService.compileJvm(
429
projectId = project.name,
430
strategyConfig = executionConfig,
431
compilationConfig = config,
432
sources = sourceFiles,
433
arguments = compilerArgs
434
)
435
436
handleResult(result)
437
438
} catch (e: CompilationServiceException) {
439
logger.error("Compilation service error", e)
440
throw BuildException("Kotlin compilation failed", e)
441
} finally {
442
compilationService.finishProjectCompilation(project.name)
443
}
444
}
445
446
private fun handleResult(result: CompilationResult) {
447
result.errors.forEach { error ->
448
logger.error("${error.sourceLocation}: ${error.message}")
449
}
450
451
result.warnings.forEach { warning ->
452
logger.warn("${warning.sourceLocation}: ${warning.message}")
453
}
454
455
if (result.isSuccessful) {
456
logger.info("Compilation completed successfully in ${result.compilationDuration}ms")
457
logger.info("Compiled ${result.filesCompiled} files")
458
logger.info("Generated ${result.outputFiles.size} output files")
459
} else {
460
throw BuildException("Compilation failed with ${result.errors.size} errors")
461
}
462
}
463
}
464
```