CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Core interfaces and data structures for Kotlin script compilation, evaluation, and IDE integration

Pending
Overview
Eval results
Files

script-evaluation.mddocs/

Script Evaluation

Evaluation system for executing compiled scripts with configuration, result handling, and context management. Provides the runtime environment for script execution and result collection.

Capabilities

ScriptEvaluator Interface

Main interface for evaluating compiled scripts in a configured runtime environment.

/**
 * Interface for evaluating compiled scripts
 */
interface ScriptEvaluator {
    /**
     * Evaluate a compiled script using the provided configuration
     * @param compiledScript Previously compiled script to evaluate
     * @param scriptEvaluationConfiguration Evaluation configuration
     * @return Result containing evaluation results or runtime errors
     */
    suspend operator fun invoke(
        compiledScript: CompiledScript,
        scriptEvaluationConfiguration: ScriptEvaluationConfiguration = ScriptEvaluationConfiguration.Default
    ): ResultWithDiagnostics<EvaluationResult>
}

ScriptEvaluationConfiguration

Configuration container for controlling script evaluation behavior and runtime environment.

/**
 * Configuration for script evaluation
 */
class ScriptEvaluationConfiguration : PropertiesCollection {
    companion object {
        val Default = ScriptEvaluationConfiguration()
    }
}

Evaluation Results

Data structures representing the results of script evaluation.

/**
 * Result of script evaluation
 */
data class EvaluationResult(
    val returnValue: ResultValue,
    val configuration: ScriptEvaluationConfiguration?
)

/**
 * Sealed class representing different types of evaluation results
 */
sealed class ResultValue(
    val scriptClass: KClass<*>? = null,
    val scriptInstance: Any? = null
) {
    /**
     * Successful evaluation with a value
     */
    class Value(
        val name: String,
        val value: Any?,
        val type: String,
        scriptClass: KClass<*>?,
        scriptInstance: Any?
    ) : ResultValue(scriptClass, scriptInstance)
    
    /**
     * Successful evaluation with Unit result
     */
    class Unit(
        scriptClass: KClass<*>,
        scriptInstance: Any?
    ) : ResultValue(scriptClass, scriptInstance)
    
    /**
     * Evaluation failed with an error
     */
    class Error(
        val error: Throwable,
        val wrappingException: Throwable? = null,
        scriptClass: KClass<*>? = null
    ) : ResultValue(scriptClass)
    
    /**
     * Script was not evaluated
     */
    object NotEvaluated : ResultValue()
}

Configuration Keys

Key interfaces defining available configuration options for script evaluation.

/**
 * Keys for script evaluation configuration properties
 */
interface ScriptEvaluationConfigurationKeys {
    val scriptArgs: PropertiesCollection.Key<List<Any?>>
    val implicitReceivers: PropertiesCollection.Key<List<Any>>
    val providedProperties: PropertiesCollection.Key<Map<String, Any?>>
    val constructorArgs: PropertiesCollection.Key<List<Any?>>
    val contextVariables: PropertiesCollection.Key<Map<String, Any?>>
    val enabledEvaluationFeatures: PropertiesCollection.Key<List<EvaluationFeature>>
    val executionWrapper: PropertiesCollection.Key<ScriptExecutionWrapper<*>>
    val refineConfigurationBeforeEvaluate: PropertiesCollection.Key<List<RefineScriptEvaluationConfigurationHandler>>
}

Configuration Refinement

System for dynamically refining evaluation configuration before script execution.

/**
 * Handler for refining script evaluation configuration
 */
typealias RefineScriptEvaluationConfigurationHandler = 
    suspend (ScriptEvaluationConfigurationRefinementContext) -> ResultWithDiagnostics<ScriptEvaluationConfiguration>

/**
 * Context provided to evaluation refinement handlers
 */
data class ScriptEvaluationConfigurationRefinementContext(
    val script: CompiledScript,
    val evaluationConfiguration: ScriptEvaluationConfiguration,
    val compilationConfiguration: ScriptCompilationConfiguration
)

/**
 * Data for evaluation configuration refinement
 */
data class RefineEvaluationConfigurationData(
    val handler: RefineScriptEvaluationConfigurationHandler
)

Script Execution Wrapper

Interface for wrapping script execution with custom behavior.

/**
 * Wrapper for script execution allowing custom execution behavior
 */
interface ScriptExecutionWrapper<T> {
    /**
     * Execute the provided script evaluation action
     * @param body Script evaluation action to execute
     * @return Result of the wrapped execution
     */
    suspend operator fun invoke(body: suspend () -> T): T
}

Context Data Management

System for managing evaluation context data and variables.

/**
 * Keys for script evaluation context data
 */
interface ScriptEvaluationContextDataKeys {
    val contextVariables: PropertiesCollection.Key<Map<String, Any?>>
    val sharedContext: PropertiesCollection.Key<Map<String, Any?>>
}

/**
 * Container for evaluation context data
 */
class ScriptEvaluationContextData : PropertiesCollection

Usage Examples:

import kotlin.script.experimental.api.*

// Basic evaluation configuration
val evaluationConfig = ScriptEvaluationConfiguration {
    // Provide script arguments
    scriptArgs(listOf("arg1", "arg2", 42))
    
    // Set context variables available in the script
    contextVariables(mapOf(
        "workingDir" to File("."),
        "version" to "1.0.0",
        "debug" to true
    ))
    
    // Provide implicit receiver objects
    implicitReceivers(File("."))
}

// Evaluate a compiled script
class MyScriptEvaluator : ScriptEvaluator {
    override suspend fun invoke(
        compiledScript: CompiledScript,
        configuration: ScriptEvaluationConfiguration
    ): ResultWithDiagnostics<EvaluationResult> {
        // Implementation would use Kotlin reflection and execution APIs
        // This is a simplified example
        TODO("Implementation depends on specific evaluation backend")
    }
}

// Using the evaluator
val evaluator = MyScriptEvaluator()
val result = evaluator(compiledScript, evaluationConfig)

when (result) {
    is ResultWithDiagnostics.Success -> {
        val evaluationResult = result.value
        when (val returnValue = evaluationResult.returnValue) {
            is ResultValue.Value -> {
                println("Script returned: ${returnValue.value}")
                println("Return type: ${returnValue.type}")
            }
            is ResultValue.Unit -> {
                println("Script executed successfully (Unit result)")
            }
            is ResultValue.Error -> {
                println("Script execution error: ${returnValue.error.message}")
                returnValue.location?.let { loc ->
                    println("Error location: line ${loc.start.line}, col ${loc.start.col}")
                }
            }
            is ResultValue.NotEvaluated -> {
                println("Script was not evaluated")
            }
        }
    }
    is ResultWithDiagnostics.Failure -> {
        result.reports.forEach { diagnostic ->
            println("${diagnostic.severity}: ${diagnostic.message}")
        }
    }
}

Advanced Evaluation Configuration

// Complex evaluation configuration with all features
val advancedEvaluationConfig = ScriptEvaluationConfiguration {
    // Script constructor arguments
    constructorArgs(listOf("constructor", "arguments"))
    
    // Properties available directly in script scope
    providedProperties(mapOf(
        "logger" to getLogger("script"),
        "config" to loadConfiguration(),
        "database" to getDatabaseConnection()
    ))
    
    // Context variables accessible via context
    contextVariables(mapOf(
        "environment" to "production",
        "features" to listOf("feature1", "feature2"),
        "settings" to mapOf("timeout" to 30000, "retries" to 3)
    ))
    
    // Implicit receivers (this references in script)
    implicitReceivers(listOf(
        File(System.getProperty("user.dir")),
        System.getProperties()
    ))
    
    // Enable specific evaluation features
    enabledEvaluationFeatures(listOf(
        EvaluationFeature.COROUTINES,
        EvaluationFeature.REFLECTION
    ))
    
    // Custom execution wrapper
    executionWrapper(object : ScriptExecutionWrapper<Any?> {
        override suspend fun invoke(body: suspend () -> Any?): Any? {
            println("Starting script execution...")
            val start = System.currentTimeMillis()
            try {
                return body()
            } finally {
                val duration = System.currentTimeMillis() - start
                println("Script execution completed in ${duration}ms")
            }
        }
    })
    
    // Configuration refinement
    refineConfigurationBeforeEvaluate { context ->
        // Add dynamic configuration based on script content
        ScriptEvaluationConfiguration(context.evaluationConfiguration) {
            contextVariables.put("scriptClass", context.script.getClass().valueOrNull()?.simpleName)
        }.asSuccess()
    }
}

Custom Execution Wrappers

// Timeout wrapper
class TimeoutExecutionWrapper(private val timeoutMs: Long) : ScriptExecutionWrapper<Any?> {
    override suspend fun invoke(body: suspend () -> Any?): Any? {
        return withTimeout(timeoutMs) {
            body()
        }
    }
}

// Security wrapper
class SecurityExecutionWrapper(private val permissions: Set<String>) : ScriptExecutionWrapper<Any?> {
    override suspend fun invoke(body: suspend () -> Any?): Any? {
        return withSecurityContext(permissions) {
            body()
        }
    }
}

// Logging wrapper
class LoggingExecutionWrapper(private val logger: Logger) : ScriptExecutionWrapper<Any?> {
    override suspend fun invoke(body: suspend () -> Any?): Any? {
        logger.info("Script execution starting")
        try {
            val result = body()
            logger.info("Script execution completed successfully")
            return result
        } catch (e: Exception) {
            logger.error("Script execution failed", e)
            throw e
        }
    }
}

// Using custom wrappers
val configWithWrapper = ScriptEvaluationConfiguration {
    executionWrapper(TimeoutExecutionWrapper(30000)) // 30 second timeout
}

Context Variable Access

// In the script being evaluated, context variables can be accessed:
// (This would be the content of the script being evaluated)

/*
// Context variables are available in the script
val env = contextVariables["environment"] as String
val features = contextVariables["features"] as List<String>
val settings = contextVariables["settings"] as Map<String, Any>

println("Running in environment: $env")
println("Available features: $features")
println("Timeout setting: ${settings["timeout"]}")

// Implicit receivers can be used directly
println("Current directory: $absolutePath") // File receiver
println("Java version: ${getProperty("java.version")}") // Properties receiver
*/

Install with Tessl CLI

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

docs

error-handling.md

host-integration.md

index.md

repl-system.md

script-annotations.md

script-compilation.md

script-evaluation.md

source-code.md

type-system.md

tile.json