0
# Compiler Entry Points
1
2
Main compiler classes providing programmatic access to Kotlin compilation with support for both K1 and K2 compiler backends. These classes serve as the primary interface for invoking compilation programmatically.
3
4
## Capabilities
5
6
### K2JVMCompiler
7
8
Primary JVM compiler entry point supporting both command-line and programmatic compilation.
9
10
```kotlin { .api }
11
/**
12
* Primary JVM compiler entry point for Kotlin 2.0+ (K2) compilation
13
* Extends CLICompiler to provide JVM-specific compilation functionality
14
*/
15
class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
16
/** Command-line entry point for compilation */
17
fun main(args: Array<String>): Unit
18
19
/** Execute compilation with custom message collector and services */
20
fun exec(
21
messageCollector: MessageCollector,
22
services: Services,
23
arguments: K2JVMCompilerArguments
24
): ExitCode
25
26
/** Execute compilation with error stream output */
27
fun exec(
28
errStream: PrintStream,
29
services: Services,
30
messageRenderer: MessageRenderer,
31
args: Array<String>
32
): ExitCode
33
34
/** Create default compiler arguments instance */
35
fun createArguments(): K2JVMCompilerArguments
36
37
/** Check if K2 compiler should be used based on language version */
38
fun shouldRunK2(messageCollector: MessageCollector, arguments: K2JVMCompilerArguments): Boolean
39
40
/** Execute compilation using phased K2 pipeline */
41
fun doExecutePhased(
42
arguments: K2JVMCompilerArguments,
43
services: Services,
44
basicMessageCollector: MessageCollector
45
): ExitCode?
46
47
/** Execute legacy compilation pipeline */
48
fun doExecute(
49
arguments: K2JVMCompilerArguments,
50
configuration: CompilerConfiguration,
51
rootDisposable: Disposable,
52
paths: KotlinPaths?
53
): ExitCode
54
}
55
```
56
57
**Usage Examples:**
58
59
```kotlin
60
// Basic compilation
61
val compiler = K2JVMCompiler()
62
val arguments = K2JVMCompilerArguments().apply {
63
destination = "build/classes"
64
classpath = System.getProperty("java.class.path")
65
jvmTarget = "17"
66
}
67
68
val messageCollector = PrintingMessageCollector(System.err, MessageRenderer.PLAIN, false)
69
val exitCode = compiler.exec(messageCollector, Services.EMPTY, arguments)
70
71
if (exitCode == ExitCode.OK) {
72
println("Compilation successful")
73
} else {
74
println("Compilation failed with code: $exitCode")
75
}
76
77
// Command-line style compilation
78
val args = arrayOf(
79
"-d", "build/classes",
80
"-cp", "libs/kotlin-stdlib.jar",
81
"src/main.kt"
82
)
83
K2JVMCompiler.main(args)
84
```
85
86
### CLICompiler
87
88
Abstract base compiler providing common CLI functionality for all Kotlin compilation targets.
89
90
```kotlin { .api }
91
/**
92
* Abstract base compiler providing common CLI functionality
93
* Extended by platform-specific compilers like K2JVMCompiler
94
*/
95
abstract class CLICompiler<A : CommonCompilerArguments> {
96
/** Default performance manager for compilation metrics */
97
abstract val defaultPerformanceManager: PerformanceManager
98
99
/** Execute compilation with XML output format */
100
fun execAndOutputXml(errStream: PrintStream, services: Services, vararg args: String): ExitCode
101
102
/** Execute compilation with full file paths in messages */
103
fun execFullPathsInMessages(errStream: PrintStream, args: Array<String>): ExitCode
104
105
/** Determine if K2 compiler should be used based on language version */
106
protected open fun shouldRunK2(messageCollector: MessageCollector, arguments: A): Boolean
107
108
/** Create performance manager for compilation tracking */
109
protected open fun createPerformanceManager(arguments: A, services: Services): PerformanceManager
110
111
/** Load compiler plugins based on configuration */
112
protected fun loadPlugins(
113
paths: KotlinPaths?,
114
arguments: A,
115
configuration: CompilerConfiguration,
116
rootDisposable: Disposable
117
): ExitCode
118
119
/** Create arguments parser for command-line parsing */
120
protected abstract fun createArguments(): A
121
122
/** Perform compilation with given configuration */
123
protected abstract fun doExecute(
124
arguments: A,
125
configuration: CompilerConfiguration,
126
rootDisposable: Disposable,
127
paths: KotlinPaths?
128
): ExitCode
129
}
130
```
131
132
### Compiler Execution Results
133
134
```kotlin { .api }
135
/**
136
* Compilation result codes indicating success or failure reasons
137
*/
138
enum class ExitCode {
139
/** Compilation completed successfully */
140
OK,
141
/** Compilation failed due to compilation errors */
142
COMPILATION_ERROR,
143
/** Compilation failed due to internal compiler error */
144
INTERNAL_ERROR,
145
/** Compilation failed due to out of memory error */
146
OOM_ERROR
147
}
148
```
149
150
### Performance Management
151
152
```kotlin { .api }
153
/**
154
* Interface for tracking compilation performance metrics
155
*/
156
interface PerformanceManager {
157
/** Enable performance statistics collection */
158
fun enableCollectingPerformanceStatistics(isK2: Boolean): Unit
159
160
/** Get collected performance statistics */
161
fun getPerformanceStatistics(): Map<String, Long>
162
163
/** Reset performance counters */
164
fun resetPerformanceCounters(): Unit
165
}
166
167
/**
168
* Performance manager with profiling capabilities
169
*/
170
class ProfilingCompilerPerformanceManager : PerformanceManager {
171
/** Start timing a specific operation */
172
fun startTiming(operationName: String): Unit
173
174
/** End timing a specific operation */
175
fun endTiming(operationName: String): Unit
176
177
/** Get timing results for all operations */
178
fun getTimingResults(): Map<String, Duration>
179
}
180
```
181
182
### KotlinCoreEnvironment
183
184
Core compilation environment setup and management providing project context and resource management.
185
186
```kotlin { .api }
187
/**
188
* Core compilation environment providing project context and resource management
189
* Essential for setting up compilation infrastructure and managing resources
190
*/
191
class KotlinCoreEnvironment private constructor() {
192
/** Create production environment for compilation */
193
companion object {
194
fun createForProduction(
195
parentDisposable: Disposable,
196
configuration: CompilerConfiguration,
197
configFiles: EnvironmentConfigFiles
198
): KotlinCoreEnvironment
199
200
/** Get or create application environment */
201
fun getOrCreateApplicationEnvironmentForProduction(
202
parentDisposable: Disposable,
203
configuration: CompilerConfiguration
204
): ApplicationEnvironment
205
}
206
207
/** Get project instance for compilation */
208
val project: Project
209
210
/** Get source files for compilation */
211
val getSourceFiles(): List<KtFile>
212
213
/** Register source roots */
214
fun registerSourceRoots(sourceRoots: List<File>): Unit
215
216
/** Dispose resources and cleanup */
217
fun dispose(): Unit
218
}
219
220
/**
221
* Environment configuration files enum
222
*/
223
enum class EnvironmentConfigFiles {
224
/** JVM configuration files */
225
JVM_CONFIG_FILES,
226
/** Metadata configuration files */
227
METADATA_CONFIG_FILES,
228
/** Native configuration files */
229
NATIVE_CONFIG_FILES
230
}
231
```
232
233
### KotlinToJVMBytecodeCompiler
234
235
Main JVM bytecode generation object providing high-level compilation functionality.
236
237
```kotlin { .api }
238
/**
239
* Main JVM bytecode generation object
240
* Provides high-level compilation functionality for generating JVM bytecode
241
*/
242
object KotlinToJVMBytecodeCompiler {
243
/** Compile modules to JVM bytecode */
244
fun compileModules(
245
environment: KotlinCoreEnvironment,
246
buildFile: GenerationState.GenerationStateEventCallback?,
247
chunk: ModuleChunk
248
): Boolean
249
250
/** Analyze and compile sources */
251
fun analyzeAndGenerate(
252
environment: KotlinCoreEnvironment
253
): GenerationState?
254
255
/** Create generation state for compilation */
256
fun createGenerationState(
257
environment: KotlinCoreEnvironment,
258
configuration: CompilerConfiguration
259
): GenerationState
260
}
261
262
/**
263
* Generation state containing compilation results and bytecode
264
*/
265
interface GenerationState {
266
/** Generated class files */
267
val factory: ClassFileFactory
268
269
/** Compilation diagnostics */
270
val collectedExtraJvmDiagnostics: Collection<Diagnostic>
271
272
/** Generation state event callback interface */
273
interface GenerationStateEventCallback {
274
fun beforeCompile(environment: KotlinCoreEnvironment): Unit
275
fun afterAnalysis(environment: KotlinCoreEnvironment, analysisResult: AnalysisResult): Unit
276
fun afterGeneration(environment: KotlinCoreEnvironment, state: GenerationState): Unit
277
}
278
}
279
```
280
281
**Integration Examples:**
282
283
```kotlin
284
// Custom performance tracking
285
val performanceManager = ProfilingCompilerPerformanceManager()
286
val compiler = K2JVMCompiler()
287
288
val arguments = K2JVMCompilerArguments().apply {
289
reportPerf = true // Enable performance reporting
290
}
291
292
val configuration = CompilerConfiguration().apply {
293
put(CLIConfigurationKeys.PERF_MANAGER, performanceManager)
294
}
295
296
val exitCode = compiler.doExecute(arguments, configuration, Disposer.newDisposable(), null)
297
val stats = performanceManager.getPerformanceStatistics()
298
println("Compilation took: ${stats["total"]}ms")
299
300
// Plugin loading with error handling
301
val pluginResult = compiler.loadPlugins(kotlinPaths, arguments, configuration, disposable)
302
if (pluginResult != ExitCode.OK) {
303
println("Failed to load plugins: $pluginResult")
304
}
305
```
306
307
## Error Handling
308
309
The compiler entry points use `ExitCode` to indicate compilation results:
310
311
- **OK**: Compilation completed successfully
312
- **COMPILATION_ERROR**: Source code contains compilation errors
313
- **INTERNAL_ERROR**: Internal compiler error occurred
314
- **OOM_ERROR**: Out of memory during compilation
315
316
All diagnostic messages are reported through the `MessageCollector` interface for consistent error handling and reporting.