CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-scripting-jvm

Kotlin JVM scripting support library that provides core functionality for executing and evaluating Kotlin scripts on the JVM platform

Pending
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

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.

Capabilities

Kotlin Runtime JAR Management

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
)

Classpath Extraction Utilities

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))
}

Script Compilation Classpath Utilities

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))
    }
}

File Matching Utilities

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): Boolean

Usage 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: true

ClassLoader Resource Utilities

Advanced 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()

String and Identifier Utilities

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(): String

Usage 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()}"

Source Code Position Utilities

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): Int

Usage 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)

Error Reporting Utilities

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(): String

Usage 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}")
    }
}

Diagnostic Utilities

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(): Boolean

Usage 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 Types

/**
 * Exception thrown when classpath extraction fails
 * @param message Error description
 */
class ClasspathExtractionException(message: String) : Exception

Usage 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
}

Constants

JAR File Names

val KOTLIN_JAVA_STDLIB_JAR: String
val KOTLIN_JAVA_REFLECT_JAR: String
// ... additional JAR name constants

System Properties

val KOTLIN_SCRIPT_CLASSPATH_PROPERTY: String
val KOTLIN_COMPILER_CLASSPATH_PROPERTY: String
// ... additional property name constants

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-scripting-jvm

docs

caching.md

compiled-scripts.md

configuration.md

dependencies.md

evaluators.md

index.md

utilities.md

tile.json