Kotlin JVM scripting support library that provides core functionality for executing and evaluating Kotlin scripts on the JVM platform
—
Comprehensive utilities for classpath extraction, ClassLoader management, source code position tracking, error reporting, and JVM-specific operations. These utilities provide essential support functionality for the scripting framework.
Utility object for finding and managing Kotlin runtime JAR files required for script compilation and execution.
/**
* Utility for finding Kotlin runtime JARs
* Provides access to standard Kotlin libraries and compiler components
*/
object KotlinJars {
/** Full compiler classpath including all compiler dependencies */
val compilerClasspath: List<File>
/** Compiler classpath with scripting support libraries */
val compilerWithScriptingClasspath: List<File>
/** Kotlin standard library JAR (nullable) */
val stdlibOrNull: File?
/** Kotlin standard library JAR (throws if not found) */
val stdlib: File
/** Kotlin reflection library JAR (nullable) */
val reflectOrNull: File?
/** Kotlin script runtime JAR (nullable) */
val scriptRuntimeOrNull: File?
/** Kotlin script runtime JAR (throws if not found) */
val scriptRuntime: File
/** Standard Kotlin JARs for scripting */
val kotlinScriptStandardJars: List<File>
/** Standard Kotlin JARs with reflection support */
val kotlinScriptStandardJarsWithReflect: List<File>
/**
* Get library JAR by name and marker class
* @param propertyName System property name for JAR location
* @param jarName Expected JAR file name
* @param markerClass Class that should exist in the JAR
* @param classLoader ClassLoader to search in (default: caller's ClassLoader)
* @return File pointing to JAR or null if not found
*/
fun getLib(
propertyName: String,
jarName: String,
markerClass: KClass<*>,
classLoader: ClassLoader? = null
): File?
/**
* Get library JAR by name and marker class name
* @param propertyName System property name for JAR location
* @param jarName Expected JAR file name
* @param markerClassName Fully qualified class name that should exist in JAR
* @param classLoader ClassLoader to search in (default: caller's ClassLoader)
* @return File pointing to JAR or null if not found
*/
fun getLib(
propertyName: String,
jarName: String,
markerClassName: String,
classLoader: ClassLoader? = null
): File?
}Usage Examples:
import kotlin.script.experimental.jvm.util.KotlinJars
// Get standard Kotlin libraries
val stdlibJar = KotlinJars.stdlib
println("Kotlin stdlib: ${stdlibJar.absolutePath}")
val scriptJars = KotlinJars.kotlinScriptStandardJars
println("Script JARs: ${scriptJars.map { it.name }}")
// Use in compilation configuration
val compilationConfig = ScriptCompilationConfiguration {
dependencies(JvmDependency(KotlinJars.kotlinScriptStandardJarsWithReflect))
}
// Custom library detection
val myLibJar = KotlinJars.getLib(
"my.lib.path",
"my-library.jar",
MyLibraryClass::class
)Functions for extracting classpath information from various sources including ClassLoaders, system properties, and execution context.
/**
* Extract classpath from ClassLoader
* @param currentClassLoader ClassLoader to analyze
* @param unpackJarCollections Whether to unpack nested JAR collections
* @return List of classpath files or null if extraction fails
*/
fun classpathFromClassloader(
currentClassLoader: ClassLoader,
unpackJarCollections: Boolean = false
): List<File>?
/**
* Extract classpath from system property
* @return List of classpath files from java.class.path property
*/
fun classpathFromClasspathProperty(): List<File>?
/**
* Extract classpath from specific class location
* @param classLoader ClassLoader containing the class
* @param klass Class to find classpath for
* @return List of files containing the class
*/
fun classpathFromClass(
classLoader: ClassLoader,
klass: KClass<out Any>
): List<File>?
/**
* Extract classpath from class using its ClassLoader
* @param klass Class to find classpath for
* @return List of files containing the class
*/
fun classpathFromClass(klass: KClass<out Any>): List<File>?
/**
* Extract classpath from class by reified type
* @return List of files containing the class
*/
inline fun <reified T : Any> classpathFromClass(): List<File>?
/**
* Extract classpath from fully qualified class name
* @param classLoader ClassLoader to search in
* @param fqn Fully qualified class name
* @return List of files containing the class
*/
fun classpathFromFQN(
classLoader: ClassLoader,
fqn: String
): List<File>?Usage Examples:
// Extract from current ClassLoader
val currentClasspath = classpathFromClassloader(
Thread.currentThread().contextClassLoader,
unpackJarCollections = true
)
// Extract from system property
val systemClasspath = classpathFromClasspathProperty()
// Extract from specific class
val kotlinClasspath = classpathFromClass<String>()
val myClasspath = classpathFromClass(MyClass::class)
// Use in script configuration
val detectedClasspath = classpathFromClassloader(
MyApp::class.java.classLoader
) ?: emptyList()
val config = ScriptCompilationConfiguration {
dependencies(JvmDependency(detectedClasspath))
}Specialized functions for determining appropriate classpath for script compilation based on context.
/**
* Get script compilation classpath from context or null
* @param wholeClasspath Whether to include entire classpath
* @param unpackJarCollections Whether to unpack JAR collections
* @param classLoader Optional specific ClassLoader
* @return Classpath files or null if unable to determine
*/
fun scriptCompilationClasspathFromContextOrNull(
wholeClasspath: Boolean = false,
unpackJarCollections: Boolean = true,
classLoader: ClassLoader? = Thread.currentThread().contextClassLoader
): List<File>?
/**
* Get script compilation classpath from context with stdlib fallback
* @param wholeClasspath Whether to include entire classpath
* @param unpackJarCollections Whether to unpack JAR collections
* @param classLoader Optional specific ClassLoader
* @return Classpath files or Kotlin standard libraries if context unavailable
*/
fun scriptCompilationClasspathFromContextOrStdlib(
wholeClasspath: Boolean = false,
unpackJarCollections: Boolean = true,
classLoader: ClassLoader? = Thread.currentThread().contextClassLoader
): List<File>
/**
* Get script compilation classpath from context (throws on failure)
* @param wholeClasspath Whether to include entire classpath
* @param unpackJarCollections Whether to unpack JAR collections
* @param classLoader Optional specific ClassLoader
* @return Classpath files
* @throws IllegalStateException if unable to determine classpath
*/
fun scriptCompilationClasspathFromContext(
wholeClasspath: Boolean = false,
unpackJarCollections: Boolean = true,
classLoader: ClassLoader? = Thread.currentThread().contextClassLoader
): List<File>Usage Examples:
// Safe classpath detection with fallback
val classpath = scriptCompilationClasspathFromContextOrStdlib(
wholeClasspath = true,
unpackJarCollections = false
)
// Use in configuration
val config = ScriptCompilationConfiguration {
jvm {
val scriptClasspath = scriptCompilationClasspathFromContext(wholeClasspath = false)
dependencies(JvmDependency(scriptClasspath))
}
}Utilities for file pattern matching and path analysis.
/**
* Check if file matches possibly versioned filename
* @param baseName Base name to match (without version)
* @return True if file matches pattern with optional version suffix
*/
fun File.matchMaybeVersionedFile(baseName: String): Boolean
/**
* Check if file has parent directory with given name
* @param baseName Parent directory name to check
* @return True if any parent directory matches the name
*/
fun File.hasParentNamed(baseName: String): BooleanUsage Examples:
import java.io.File
val jarFile = File("/path/to/kotlin-stdlib-1.8.0.jar")
val matches = jarFile.matchMaybeVersionedFile("kotlin-stdlib")
// Returns: true
val sourceFile = File("/project/src/main/kotlin/MyScript.kt")
val hasKotlinParent = sourceFile.hasParentNamed("kotlin")
// Returns: trueAdvanced ClassLoader operations for resource discovery and classpath analysis.
/**
* Process all matching files in ClassLoader
* @param namePattern Pattern to match file names
* @param keyResourcePaths Key resource paths to search
* @param body Function to process each matching file
*/
fun ClassLoader.forAllMatchingFiles(
namePattern: String,
vararg keyResourcePaths: String,
body: (String, InputStream) -> Unit
)
/**
* Extract classpath from typical resource URLs
* @return Sequence of File objects representing classpath entries
*/
fun ClassLoader.classPathFromTypicalResourceUrls(): Sequence<File>Usage Examples:
// Process all matching resource files
MyClass::class.java.classLoader.forAllMatchingFiles(
"*.properties",
"META-INF",
"config"
) { fileName, inputStream ->
println("Processing: $fileName")
val properties = Properties()
properties.load(inputStream)
// Process properties...
}
// Extract classpath from ClassLoader
val classLoader = Thread.currentThread().contextClassLoader
val classpathFiles = classLoader.classPathFromTypicalResourceUrls().toList()Utilities for working with JVM identifiers and string manipulation.
/**
* Convert string to valid JVM identifier
* Replaces invalid characters with valid alternatives
* @return Valid JVM identifier string
*/
fun String.toValidJvmIdentifier(): StringUsage Example:
val invalidId = "my-script@version:1.0"
val validId = invalidId.toValidJvmIdentifier()
// Returns: "my_script_version_1_0"
// Use for generating class names
val scriptClassName = "Script_${sourceFileName.toValidJvmIdentifier()}"Utilities for working with source code positions and location mapping.
/**
* Absolute position in source code
* @param line Line number (1-based)
* @param col Column number (1-based)
* @param absolutePos Absolute character position (0-based)
*/
data class AbsSourceCodePosition(
val line: Int,
val col: Int,
val absolutePos: Int
) : Serializable
/**
* Convert absolute position to source code position
* @param code Source code to map position in
* @return SourceCode.Position object
*/
fun Int.toSourceCodePosition(code: SourceCode): SourceCode.Position
/**
* Determine line separator used in string
* @return Line separator string ("\n", "\r\n", or "\r")
*/
fun String.determineSep(): String
/**
* Calculate absolute position from source code position
* @param code Source code containing the position
* @return Absolute character position
*/
fun SourceCode.Position.calcAbsolute(code: SourceCode): IntUsage Examples:
import kotlin.script.experimental.api.SourceCode
// Create absolute position
val position = AbsSourceCodePosition(line = 10, col = 5, absolutePos = 145)
// Convert position types
val sourceCode = "line1\nline2\nline3".toScriptSource()
val absolutePos = 8
val sourcePosition = absolutePos.toSourceCodePosition(sourceCode)
// Determine line separator
val windowsCode = "line1\r\nline2\r\nline3"
val separator = windowsCode.determineSep() // Returns: "\r\n"
// Calculate absolute position
val pos = SourceCode.Position(2, 3)
val absolute = pos.calcAbsolute(sourceCode)Utilities for rendering errors and diagnostic information in user-friendly formats.
/**
* Render error to PrintStream
* @param stream PrintStream to write error information
*/
fun ResultValue.Error.renderError(stream: PrintStream)
/**
* Render error to string
* @return Formatted error message string
*/
fun ResultValue.Error.renderError(): StringUsage Examples:
import kotlin.script.experimental.api.ResultValue
// Handle script execution error
val evaluationResult: ResultValue = // ... from script evaluation
when (evaluationResult) {
is ResultValue.Error -> {
// Print to console
evaluationResult.renderError(System.out)
// Get as string for logging
val errorMessage = evaluationResult.renderError()
logger.error("Script execution failed: $errorMessage")
}
is ResultValue.Value -> {
println("Success: ${evaluationResult.value}")
}
}Utilities for working with diagnostic results and error conditions.
/**
* Check if result represents incomplete compilation/evaluation
* @return True if result is incomplete
*/
fun <T> ResultWithDiagnostics<T>.isIncomplete(): Boolean
/**
* Check if result represents an error condition
* @return True if result contains errors
*/
fun <T> ResultWithDiagnostics<T>.isError(): BooleanUsage Examples:
import kotlin.script.experimental.api.ResultWithDiagnostics
// Check compilation results
val compilationResult: ResultWithDiagnostics<CompiledScript> = // ... from compilation
when {
compilationResult.isError() -> {
println("Compilation failed with errors")
compilationResult.reports.forEach { report ->
println("${report.severity}: ${report.message}")
}
}
compilationResult.isIncomplete() -> {
println("Compilation incomplete, missing dependencies or context")
}
else -> {
println("Compilation successful")
val script = compilationResult.valueOrNull()
}
}/**
* Exception thrown when classpath extraction fails
* @param message Error description
*/
class ClasspathExtractionException(message: String) : ExceptionUsage Example:
try {
val classpath = classpathFromClassloader(someClassLoader)
?: throw ClasspathExtractionException("Unable to extract classpath from ClassLoader")
} catch (e: ClasspathExtractionException) {
logger.warn("Classpath extraction failed: ${e.message}")
// Fallback to standard libraries
val fallbackClasspath = KotlinJars.kotlinScriptStandardJars
}val KOTLIN_JAVA_STDLIB_JAR: String
val KOTLIN_JAVA_REFLECT_JAR: String
// ... additional JAR name constantsval KOTLIN_SCRIPT_CLASSPATH_PROPERTY: String
val KOTLIN_COMPILER_CLASSPATH_PROPERTY: String
// ... additional property name constantsInstall with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-scripting-jvm