CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-compiler-embeddable

Self-contained embeddable Kotlin compiler with shaded dependencies for integration into applications without classpath conflicts

Pending
Overview
Eval results
Files

compiler-entry-points.mddocs/

Compiler Entry Points

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.

Capabilities

K2JVMCompiler

Primary JVM compiler entry point supporting both command-line and programmatic compilation.

/**
 * Primary JVM compiler entry point for Kotlin 2.0+ (K2) compilation
 * Extends CLICompiler to provide JVM-specific compilation functionality
 */
class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
    /** Command-line entry point for compilation */
    fun main(args: Array<String>): Unit
    
    /** Execute compilation with custom message collector and services */
    fun exec(
        messageCollector: MessageCollector, 
        services: Services, 
        arguments: K2JVMCompilerArguments
    ): ExitCode
    
    /** Execute compilation with error stream output */
    fun exec(
        errStream: PrintStream, 
        services: Services, 
        messageRenderer: MessageRenderer, 
        args: Array<String>
    ): ExitCode
    
    /** Create default compiler arguments instance */
    fun createArguments(): K2JVMCompilerArguments
    
    /** Check if K2 compiler should be used based on language version */
    fun shouldRunK2(messageCollector: MessageCollector, arguments: K2JVMCompilerArguments): Boolean
    
    /** Execute compilation using phased K2 pipeline */
    fun doExecutePhased(
        arguments: K2JVMCompilerArguments,
        services: Services,
        basicMessageCollector: MessageCollector
    ): ExitCode?
    
    /** Execute legacy compilation pipeline */
    fun doExecute(
        arguments: K2JVMCompilerArguments,
        configuration: CompilerConfiguration,
        rootDisposable: Disposable,
        paths: KotlinPaths?
    ): ExitCode
}

Usage Examples:

// Basic compilation
val compiler = K2JVMCompiler()
val arguments = K2JVMCompilerArguments().apply {
    destination = "build/classes"
    classpath = System.getProperty("java.class.path")
    jvmTarget = "17"
}

val messageCollector = PrintingMessageCollector(System.err, MessageRenderer.PLAIN, false)
val exitCode = compiler.exec(messageCollector, Services.EMPTY, arguments)

if (exitCode == ExitCode.OK) {
    println("Compilation successful")
} else {
    println("Compilation failed with code: $exitCode")
}

// Command-line style compilation
val args = arrayOf(
    "-d", "build/classes",
    "-cp", "libs/kotlin-stdlib.jar", 
    "src/main.kt"
)
K2JVMCompiler.main(args)

CLICompiler

Abstract base compiler providing common CLI functionality for all Kotlin compilation targets.

/**
 * Abstract base compiler providing common CLI functionality
 * Extended by platform-specific compilers like K2JVMCompiler
 */
abstract class CLICompiler<A : CommonCompilerArguments> {
    /** Default performance manager for compilation metrics */
    abstract val defaultPerformanceManager: PerformanceManager
    
    /** Execute compilation with XML output format */
    fun execAndOutputXml(errStream: PrintStream, services: Services, vararg args: String): ExitCode
    
    /** Execute compilation with full file paths in messages */
    fun execFullPathsInMessages(errStream: PrintStream, args: Array<String>): ExitCode
    
    /** Determine if K2 compiler should be used based on language version */
    protected open fun shouldRunK2(messageCollector: MessageCollector, arguments: A): Boolean
    
    /** Create performance manager for compilation tracking */
    protected open fun createPerformanceManager(arguments: A, services: Services): PerformanceManager
    
    /** Load compiler plugins based on configuration */
    protected fun loadPlugins(
        paths: KotlinPaths?, 
        arguments: A, 
        configuration: CompilerConfiguration,
        rootDisposable: Disposable
    ): ExitCode
    
    /** Create arguments parser for command-line parsing */
    protected abstract fun createArguments(): A
    
    /** Perform compilation with given configuration */
    protected abstract fun doExecute(
        arguments: A,
        configuration: CompilerConfiguration,
        rootDisposable: Disposable,
        paths: KotlinPaths?
    ): ExitCode
}

Compiler Execution Results

/**
 * Compilation result codes indicating success or failure reasons
 */
enum class ExitCode {
    /** Compilation completed successfully */
    OK,
    /** Compilation failed due to compilation errors */
    COMPILATION_ERROR,
    /** Compilation failed due to internal compiler error */
    INTERNAL_ERROR,
    /** Compilation failed due to out of memory error */
    OOM_ERROR
}

Performance Management

/**
 * Interface for tracking compilation performance metrics
 */
interface PerformanceManager {
    /** Enable performance statistics collection */
    fun enableCollectingPerformanceStatistics(isK2: Boolean): Unit
    
    /** Get collected performance statistics */
    fun getPerformanceStatistics(): Map<String, Long>
    
    /** Reset performance counters */
    fun resetPerformanceCounters(): Unit
}

/**
 * Performance manager with profiling capabilities
 */
class ProfilingCompilerPerformanceManager : PerformanceManager {
    /** Start timing a specific operation */
    fun startTiming(operationName: String): Unit
    
    /** End timing a specific operation */
    fun endTiming(operationName: String): Unit
    
    /** Get timing results for all operations */
    fun getTimingResults(): Map<String, Duration>
}

KotlinCoreEnvironment

Core compilation environment setup and management providing project context and resource management.

/**
 * Core compilation environment providing project context and resource management
 * Essential for setting up compilation infrastructure and managing resources
 */
class KotlinCoreEnvironment private constructor() {
    /** Create production environment for compilation */
    companion object {
        fun createForProduction(
            parentDisposable: Disposable,
            configuration: CompilerConfiguration,
            configFiles: EnvironmentConfigFiles
        ): KotlinCoreEnvironment
        
        /** Get or create application environment */
        fun getOrCreateApplicationEnvironmentForProduction(
            parentDisposable: Disposable,
            configuration: CompilerConfiguration
        ): ApplicationEnvironment
    }
    
    /** Get project instance for compilation */
    val project: Project
    
    /** Get source files for compilation */
    val getSourceFiles(): List<KtFile>
    
    /** Register source roots */
    fun registerSourceRoots(sourceRoots: List<File>): Unit
    
    /** Dispose resources and cleanup */
    fun dispose(): Unit
}

/**
 * Environment configuration files enum
 */
enum class EnvironmentConfigFiles {
    /** JVM configuration files */
    JVM_CONFIG_FILES,
    /** Metadata configuration files */
    METADATA_CONFIG_FILES,
    /** Native configuration files */
    NATIVE_CONFIG_FILES
}

KotlinToJVMBytecodeCompiler

Main JVM bytecode generation object providing high-level compilation functionality.

/**
 * Main JVM bytecode generation object
 * Provides high-level compilation functionality for generating JVM bytecode
 */
object KotlinToJVMBytecodeCompiler {
    /** Compile modules to JVM bytecode */
    fun compileModules(
        environment: KotlinCoreEnvironment,
        buildFile: GenerationState.GenerationStateEventCallback?,
        chunk: ModuleChunk
    ): Boolean
    
    /** Analyze and compile sources */
    fun analyzeAndGenerate(
        environment: KotlinCoreEnvironment
    ): GenerationState?
    
    /** Create generation state for compilation */
    fun createGenerationState(
        environment: KotlinCoreEnvironment,
        configuration: CompilerConfiguration
    ): GenerationState
}

/**
 * Generation state containing compilation results and bytecode
 */
interface GenerationState {
    /** Generated class files */
    val factory: ClassFileFactory
    
    /** Compilation diagnostics */
    val collectedExtraJvmDiagnostics: Collection<Diagnostic>
    
    /** Generation state event callback interface */
    interface GenerationStateEventCallback {
        fun beforeCompile(environment: KotlinCoreEnvironment): Unit
        fun afterAnalysis(environment: KotlinCoreEnvironment, analysisResult: AnalysisResult): Unit
        fun afterGeneration(environment: KotlinCoreEnvironment, state: GenerationState): Unit
    }
}

Integration Examples:

// Custom performance tracking
val performanceManager = ProfilingCompilerPerformanceManager()
val compiler = K2JVMCompiler()

val arguments = K2JVMCompilerArguments().apply {
    reportPerf = true // Enable performance reporting
}

val configuration = CompilerConfiguration().apply {
    put(CLIConfigurationKeys.PERF_MANAGER, performanceManager)
}

val exitCode = compiler.doExecute(arguments, configuration, Disposer.newDisposable(), null)
val stats = performanceManager.getPerformanceStatistics()
println("Compilation took: ${stats["total"]}ms")

// Plugin loading with error handling
val pluginResult = compiler.loadPlugins(kotlinPaths, arguments, configuration, disposable)
if (pluginResult != ExitCode.OK) {
    println("Failed to load plugins: $pluginResult")
}

Error Handling

The compiler entry points use ExitCode to indicate compilation results:

  • OK: Compilation completed successfully
  • COMPILATION_ERROR: Source code contains compilation errors
  • INTERNAL_ERROR: Internal compiler error occurred
  • OOM_ERROR: Out of memory during compilation

All diagnostic messages are reported through the MessageCollector interface for consistent error handling and reporting.

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-compiler-embeddable

docs

compiler-entry-points.md

configuration-system.md

high-level-api.md

incremental-compilation.md

index.md

message-collection.md

plugin-system.md

tile.json