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

high-level-api.mddocs/

High-Level Compilation API

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.

Capabilities

CompilationService

Primary high-level interface for build tools integration providing simplified compilation functionality.

/**
 * High-level compilation service interface for build tools integration
 * Provides simplified access to Kotlin compilation functionality
 */
interface CompilationService {
    /** Compile JVM sources with specified configuration */
    fun compileJvm(
        projectId: String,
        strategyConfig: CompilerExecutionStrategyConfiguration,
        compilationConfig: JvmCompilationConfiguration,
        sources: List<File>,
        arguments: List<String>
    ): CompilationResult
    
    /** Create execution strategy configuration */
    fun makeCompilerExecutionStrategyConfiguration(): CompilerExecutionStrategyConfiguration
    
    /** Create JVM compilation configuration */
    fun makeJvmCompilationConfiguration(): JvmCompilationConfiguration
    
    /** Calculate classpath snapshot for incremental compilation */
    fun calculateClasspathSnapshot(
        classpathEntries: List<File>,
        lookupSymbols: Set<String>
    ): ClasspathSnapshot
    
    /** Finalize project compilation and cleanup resources */
    fun finishProjectCompilation(projectId: String): Unit
    
    companion object {
        /** Load compilation service implementation */
        fun loadImplementation(classLoader: ClassLoader): CompilationService
    }
}

Usage Examples:

// Basic high-level compilation
val classLoader = this::class.java.classLoader
val service = CompilationService.loadImplementation(classLoader)

val executionConfig = service.makeCompilerExecutionStrategyConfiguration()
val compilationConfig = service.makeJvmCompilationConfiguration().apply {
    moduleName = "my-module"
    outputDirectory = File("build/classes")
    classpath = listOf(File("libs/kotlin-stdlib.jar"))
    jvmTarget = "17"
}

val sources = listOf(
    File("src/main/kotlin/Main.kt"),
    File("src/main/kotlin/Utils.kt")
)

val result = service.compileJvm(
    projectId = "my-project",
    strategyConfig = executionConfig,
    compilationConfig = compilationConfig,
    sources = sources,
    arguments = emptyList()
)

if (result.isSuccessful) {
    println("Compilation successful")
} else {
    println("Compilation failed: ${result.errors}")
}

// Cleanup
service.finishProjectCompilation("my-project")

JvmCompilationConfiguration

Configuration interface for JVM compilation settings.

/**
 * JVM compilation configuration interface
 * Provides fluent API for configuring JVM compilation
 */
interface JvmCompilationConfiguration {
    /** Module name for the compilation */
    var moduleName: String?
    
    /** Output directory for compiled classes */
    var outputDirectory: File?
    
    /** Classpath entries for compilation */
    var classpath: List<File>
    
    /** JVM target version */
    var jvmTarget: String
    
    /** Include Kotlin runtime in output */
    var includeRuntime: Boolean
    
    /** Enable/disable incremental compilation */
    var incrementalCompilation: Boolean
    
    /** Source directories */
    var sourceRoots: List<File>
    
    /** Java source directories */
    var javaSourceRoots: List<File>
    
    /** Friend modules for internal visibility */
    var friendModules: List<String>
    
    /** Language version */
    var languageVersion: String?
    
    /** API version */
    var apiVersion: String?
    
    /** Compiler plugin configurations */
    var pluginConfigurations: List<PluginConfiguration>
    
    /** Free-form compiler arguments */
    var freeCompilerArgs: List<String>
}

CompilerExecutionStrategyConfiguration

Configuration for compiler execution strategy and performance settings.

/**
 * Configuration for compiler execution strategy
 * Controls how compilation is executed and performance characteristics
 */
interface CompilerExecutionStrategyConfiguration {
    /** Use in-process compilation (faster but less isolated) */
    var useInProcessCompilation: Boolean
    
    /** Use daemon compilation (persistent compiler process) */
    var useDaemonCompilation: Boolean
    
    /** Maximum heap size for compilation process */
    var maxHeapSize: String?
    
    /** JVM arguments for compilation process */
    var jvmArgs: List<String>
    
    /** Enable parallel compilation */
    var parallelCompilation: Boolean
    
    /** Number of worker threads for parallel compilation */
    var workerThreads: Int
    
    /** Enable compilation performance reporting */
    var reportPerformance: Boolean
    
    /** Compilation timeout in milliseconds */
    var compilationTimeout: Long
}

CompilationResult

Result interface providing compilation outcome and diagnostic information.

/**
 * Result of a compilation operation
 * Provides success status and diagnostic information
 */
interface CompilationResult {
    /** Whether compilation completed successfully */
    val isSuccessful: Boolean
    
    /** Whether compilation had any errors */
    val hasErrors: Boolean
    
    /** Whether compilation had any warnings */
    val hasWarnings: Boolean
    
    /** Exit code from compilation */
    val exitCode: ExitCode
    
    /** List of compilation errors */
    val errors: List<CompilationMessage>
    
    /** List of compilation warnings */
    val warnings: List<CompilationMessage>
    
    /** All compilation messages */
    val messages: List<CompilationMessage>
    
    /** Compilation duration in milliseconds */
    val compilationDuration: Long
    
    /** Number of files compiled */
    val filesCompiled: Int
    
    /** Generated output files */
    val outputFiles: List<File>
}

/**
 * Individual compilation message with severity and location
 */
data class CompilationMessage(
    val severity: CompilerMessageSeverity,
    val message: String,
    val sourceLocation: CompilerMessageSourceLocation?
)

Classpath Management

Support for incremental compilation through classpath snapshots.

/**
 * Snapshot of classpath state for incremental compilation
 * Tracks changes to dependencies for optimization
 */
interface ClasspathSnapshot {
    /** Classpath entries included in this snapshot */
    val classpathEntries: List<ClasspathEntrySnapshot>
    
    /** Lookup symbols used in this compilation */
    val lookupSymbols: Set<String>
    
    /** Timestamp when snapshot was created */
    val timestamp: Long
    
    /** Check if classpath has changed since this snapshot */
    fun hasChanged(currentClasspath: List<File>): Boolean
    
    /** Get changed classpath entries */
    fun getChangedEntries(currentClasspath: List<File>): List<ClasspathEntrySnapshot>
}

/**
 * Individual classpath entry snapshot
 */
interface ClasspathEntrySnapshot {
    /** File path of the classpath entry */
    val file: File
    
    /** Hash of the file content */
    val contentHash: String
    
    /** Last modified timestamp */
    val lastModified: Long
    
    /** Size of the file */
    val size: Long
    
    /** Exported symbols from this entry */
    val exportedSymbols: Set<String>
}

Advanced Usage Examples:

// Incremental compilation with classpath tracking
val service = CompilationService.loadImplementation(classLoader)

val classpathEntries = listOf(
    File("libs/kotlin-stdlib.jar"),
    File("libs/kotlinx-coroutines-core.jar")
)

// Calculate initial classpath snapshot
val initialSnapshot = service.calculateClasspathSnapshot(
    classpathEntries = classpathEntries,
    lookupSymbols = setOf("kotlin.String", "kotlinx.coroutines.launch")
)

val compilationConfig = service.makeJvmCompilationConfiguration().apply {
    moduleName = "incremental-example"
    outputDirectory = File("build/classes")
    classpath = classpathEntries
    incrementalCompilation = true
    jvmTarget = "17"
}

val executionConfig = service.makeCompilerExecutionStrategyConfiguration().apply {
    useInProcessCompilation = true
    parallelCompilation = true
    workerThreads = 4
    reportPerformance = true
}

// First compilation
val result1 = service.compileJvm(
    projectId = "incremental-project",
    strategyConfig = executionConfig,
    compilationConfig = compilationConfig,
    sources = listOf(File("src/Main.kt")),
    arguments = emptyList()
)

println("First compilation: ${result1.compilationDuration}ms, ${result1.filesCompiled} files")

// Check for classpath changes
if (!initialSnapshot.hasChanged(classpathEntries)) {
    println("Classpath unchanged, incremental compilation will be more efficient")
}

// Second compilation (should be faster due to incremental)
val result2 = service.compileJvm(
    projectId = "incremental-project",
    strategyConfig = executionConfig,
    compilationConfig = compilationConfig,
    sources = listOf(File("src/Main.kt"), File("src/NewFile.kt")),
    arguments = emptyList()
)

println("Second compilation: ${result2.compilationDuration}ms, ${result2.filesCompiled} files")

// Plugin configuration example
compilationConfig.pluginConfigurations = listOf(
    PluginConfiguration(
        pluginId = "org.jetbrains.kotlin.plugin.serialization",
        options = mapOf("enabled" to "true")
    )
)

// Daemon compilation for better performance
executionConfig.apply {
    useDaemonCompilation = true
    maxHeapSize = "2g"
    jvmArgs = listOf("-XX:+UseG1GC", "-XX:MaxMetaspaceSize=512m")
    compilationTimeout = 300_000 // 5 minutes
}

service.finishProjectCompilation("incremental-project")

Plugin Configuration

Support for compiler plugins through the high-level API.

/**
 * Configuration for compiler plugins
 */
data class PluginConfiguration(
    /** Plugin identifier */
    val pluginId: String,
    
    /** Plugin options as key-value pairs */
    val options: Map<String, String>,
    
    /** Plugin classpath entries */
    val classpath: List<File> = emptyList(),
    
    /** Plugin version (optional) */
    val version: String? = null
)

Error Handling and Diagnostics

/**
 * Exception thrown when compilation service encounters errors
 */
class CompilationServiceException(
    message: String,
    cause: Throwable? = null
) : Exception(message, cause)

/**
 * Exception thrown when compilation configuration is invalid
 */
class InvalidCompilationConfigurationException(
    message: String,
    val configurationErrors: List<String>
) : Exception(message)

/**
 * Performance metrics for compilation
 */
interface CompilationMetrics {
    /** Total compilation time */
    val totalTime: Long
    
    /** Analysis phase time */
    val analysisTime: Long
    
    /** Code generation time */
    val codeGenerationTime: Long
    
    /** I/O time */
    val ioTime: Long
    
    /** Memory usage statistics */
    val memoryUsage: MemoryUsage
    
    /** GC statistics */
    val gcStatistics: GcStatistics
}

Integration Patterns

// Build tool integration
class KotlinCompilationTask {
    private val compilationService = CompilationService.loadImplementation(
        KotlinCompilationTask::class.java.classLoader
    )
    
    fun execute() {
        try {
            val config = createCompilationConfiguration()
            val executionConfig = createExecutionConfiguration()
            
            val result = compilationService.compileJvm(
                projectId = project.name,
                strategyConfig = executionConfig,
                compilationConfig = config,
                sources = sourceFiles,
                arguments = compilerArgs
            )
            
            handleResult(result)
            
        } catch (e: CompilationServiceException) {
            logger.error("Compilation service error", e)
            throw BuildException("Kotlin compilation failed", e)
        } finally {
            compilationService.finishProjectCompilation(project.name)
        }
    }
    
    private fun handleResult(result: CompilationResult) {
        result.errors.forEach { error ->
            logger.error("${error.sourceLocation}: ${error.message}")
        }
        
        result.warnings.forEach { warning ->
            logger.warn("${warning.sourceLocation}: ${warning.message}")
        }
        
        if (result.isSuccessful) {
            logger.info("Compilation completed successfully in ${result.compilationDuration}ms")
            logger.info("Compiled ${result.filesCompiled} files")
            logger.info("Generated ${result.outputFiles.size} output files")
        } else {
            throw BuildException("Compilation failed with ${result.errors.size} errors")
        }
    }
}

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