0
# Kotlin Scripting JVM Host
1
2
Kotlin Scripting JVM Host provides comprehensive JVM host capabilities for Kotlin's experimental scripting API, enabling execution and compilation of Kotlin scripts in JVM environments. It includes the BasicJvmScriptingHost class for script evaluation, JvmScriptCompiler for script compilation, JSR-223 script engine implementations for Java scripting API integration, and comprehensive caching mechanisms for compiled script artifacts.
3
4
The library serves as a bridge between Kotlin's scripting infrastructure and JVM runtime environments, offering both direct API access for programmatic script execution and standardized JSR-223 integration for compatibility with existing Java scripting frameworks. It supports template-based script configuration, custom evaluation contexts, and embeddable deployment scenarios where the full Kotlin compiler distribution is embedded within host applications.
5
6
## Package Information
7
8
- **Package Name**: kotlin-scripting-jvm-host
9
- **Group ID**: org.jetbrains.kotlin
10
- **Package Type**: maven
11
- **Language**: Kotlin
12
- **Installation**: Add dependency: `org.jetbrains.kotlin:kotlin-scripting-jvm-host:2.2.0`
13
14
## Core Imports
15
16
```kotlin
17
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
18
import kotlin.script.experimental.jvmhost.JvmScriptCompiler
19
import kotlin.script.experimental.jvmhost.CompiledScriptJarsCache
20
import kotlin.script.experimental.api.*
21
```
22
23
## Basic Usage
24
25
```kotlin
26
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
27
import kotlin.script.experimental.jvmhost.createJvmScriptDefinitionFromTemplate
28
import kotlin.script.experimental.api.*
29
30
// Create a basic scripting host
31
val host = BasicJvmScriptingHost()
32
33
// Define a simple script template
34
@KotlinScript(fileExtension = "kts")
35
class SimpleScript
36
37
// Evaluate a script with template
38
val script = "println(\"Hello from script!\")"
39
val result = host.evalWithTemplate<SimpleScript>(script.toScriptSource())
40
41
when (result) {
42
is ResultWithDiagnostics.Success -> {
43
println("Script executed successfully")
44
}
45
is ResultWithDiagnostics.Failure -> {
46
result.reports.forEach { println("Error: ${it.message}") }
47
}
48
}
49
```
50
51
## Architecture
52
53
Kotlin Scripting JVM Host is built around several key components:
54
55
- **Host Layer**: `BasicJvmScriptingHost` provides the main entry point for script execution with template-based configuration
56
- **Compilation Layer**: `JvmScriptCompiler` handles script compilation using the Kotlin compiler infrastructure
57
- **Caching Layer**: `CompiledScriptJarsCache` provides persistent caching of compiled scripts to JAR files
58
- **JSR-223 Integration**: Complete JSR-223 (Java Scripting API) compatible script engines for seamless Java integration
59
- **REPL Support**: Legacy REPL API compatibility layer for interactive script evaluation
60
- **Script Persistence**: Utilities for saving compiled scripts as executable JARs or class files
61
62
## Capabilities
63
64
### Core Scripting Host
65
66
Main scripting host implementation providing script compilation and evaluation with template-based configuration.
67
68
```kotlin { .api }
69
open class BasicJvmScriptingHost(
70
val baseHostConfiguration: ScriptingHostConfiguration? = null,
71
compiler: JvmScriptCompiler = JvmScriptCompiler(baseHostConfiguration.withDefaultsFrom(defaultJvmScriptingHostConfiguration)),
72
evaluator: ScriptEvaluator = BasicJvmScriptEvaluator()
73
) : BasicScriptingHost(compiler, evaluator) {
74
75
inline fun <reified T : Any> evalWithTemplate(
76
script: SourceCode,
77
noinline compilation: ScriptCompilationConfiguration.Builder.() -> Unit = {},
78
noinline evaluation: ScriptEvaluationConfiguration.Builder.() -> Unit = {}
79
): ResultWithDiagnostics<EvaluationResult>
80
}
81
```
82
83
[Core Scripting Host](./core-scripting-host.md)
84
85
### Script Compilation
86
87
JVM script compiler implementation for compiling Kotlin scripts with comprehensive configuration support.
88
89
```kotlin { .api }
90
open class JvmScriptCompiler(
91
baseHostConfiguration: ScriptingHostConfiguration = defaultJvmScriptingHostConfiguration,
92
compilerProxy: ScriptCompilerProxy? = null
93
) : ScriptCompiler {
94
95
val hostConfiguration: ScriptingHostConfiguration
96
val compilerProxy: ScriptCompilerProxy
97
98
override suspend operator fun invoke(
99
script: SourceCode,
100
scriptCompilationConfiguration: ScriptCompilationConfiguration
101
): ResultWithDiagnostics<CompiledScript>
102
}
103
```
104
105
[Script Compilation](./script-compilation.md)
106
107
### Script Caching
108
109
Caching mechanisms for compiled scripts to improve performance through persistent storage of compiled artifacts.
110
111
```kotlin { .api }
112
open class CompiledScriptJarsCache(
113
val scriptToFile: (SourceCode, ScriptCompilationConfiguration) -> File?
114
) : CompiledJvmScriptsCache {
115
116
override fun get(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration): CompiledScript?
117
override fun store(compiledScript: CompiledScript, script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration)
118
}
119
```
120
121
[Script Caching](./script-caching.md)
122
123
### Script Persistence
124
125
Utilities for saving compiled scripts as executable JARs or individual class files for deployment and distribution.
126
127
```kotlin { .api }
128
open class BasicJvmScriptJarGenerator(val outputJar: File) : ScriptEvaluator {
129
override suspend operator fun invoke(
130
compiledScript: CompiledScript,
131
scriptEvaluationConfiguration: ScriptEvaluationConfiguration
132
): ResultWithDiagnostics<EvaluationResult>
133
}
134
135
open class BasicJvmScriptClassFilesGenerator(val outputDir: File) : ScriptEvaluator {
136
override suspend operator fun invoke(
137
compiledScript: CompiledScript,
138
scriptEvaluationConfiguration: ScriptEvaluationConfiguration
139
): ResultWithDiagnostics<EvaluationResult>
140
}
141
```
142
143
[Script Persistence](./script-persistence.md)
144
145
### JSR-223 Integration
146
147
Complete JSR-223 (Java Scripting API) compatible implementation for seamless integration with existing Java scripting frameworks.
148
149
```kotlin { .api }
150
interface KotlinJsr223InvocableScriptEngine : Invocable {
151
val invokeWrapper: InvokeWrapper?
152
val backwardInstancesHistory: Sequence<Any>
153
val baseClassLoader: ClassLoader
154
155
override fun invokeFunction(name: String?, vararg args: Any?): Any?
156
override fun invokeMethod(thiz: Any?, name: String?, vararg args: Any?): Any?
157
override fun <T : Any> getInterface(clasz: Class<T>?): T?
158
override fun <T : Any> getInterface(thiz: Any?, clasz: Class<T>?): T?
159
}
160
161
class KotlinJsr223ScriptEngineImpl(
162
factory: ScriptEngineFactory,
163
baseCompilationConfiguration: ScriptCompilationConfiguration,
164
baseEvaluationConfiguration: ScriptEvaluationConfiguration,
165
val getScriptArgs: (context: ScriptContext) -> ScriptArgsWithTypes?
166
) : KotlinJsr223JvmScriptEngineBase(factory), KotlinJsr223InvocableScriptEngine
167
```
168
169
[JSR-223 Integration](./jsr223-integration.md)
170
171
### REPL Support
172
173
Legacy REPL API compatibility layer for interactive script evaluation and compilation.
174
175
```kotlin { .api }
176
class JvmReplCompiler(
177
val scriptCompilationConfiguration: ScriptCompilationConfiguration,
178
val hostConfiguration: ScriptingHostConfiguration = defaultJvmScriptingHostConfiguration
179
) : ReplCompilerWithoutCheck {
180
181
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*>
182
override fun compile(state: IReplStageState<*>, codeLine: ReplCodeLine): ReplCompileResult
183
}
184
185
class JvmReplEvaluator(
186
val baseScriptEvaluationConfiguration: ScriptEvaluationConfiguration,
187
val scriptEvaluator: ScriptEvaluator = BasicJvmScriptEvaluator()
188
) : ReplEvaluator {
189
190
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*>
191
override fun eval(
192
state: IReplStageState<*>,
193
compileResult: ReplCompileResult.CompiledClasses,
194
scriptArgs: ScriptArgsWithTypes?,
195
invokeWrapper: InvokeWrapper?
196
): ReplEvalResult
197
}
198
```
199
200
[REPL Support](./repl-support.md)
201
202
## Template Configuration
203
204
Template-based configuration utilities for creating script definitions with type-safe configuration builders.
205
206
```kotlin { .api }
207
inline fun <reified T : Any> createJvmCompilationConfigurationFromTemplate(
208
baseHostConfiguration: ScriptingHostConfiguration? = null,
209
noinline body: ScriptCompilationConfiguration.Builder.() -> Unit = {}
210
): ScriptCompilationConfiguration
211
212
inline fun <reified T : Any> createJvmEvaluationConfigurationFromTemplate(
213
baseHostConfiguration: ScriptingHostConfiguration? = null,
214
noinline body: ScriptEvaluationConfiguration.Builder.() -> Unit = {}
215
): ScriptEvaluationConfiguration
216
217
inline fun <reified T : Any> createJvmScriptDefinitionFromTemplate(
218
baseHostConfiguration: ScriptingHostConfiguration? = null,
219
noinline compilation: ScriptCompilationConfiguration.Builder.() -> Unit = {},
220
noinline evaluation: ScriptEvaluationConfiguration.Builder.() -> Unit = {}
221
): ScriptDefinition
222
```
223
224
## Types
225
226
### Core Result Types
227
228
```kotlin { .api }
229
// Imported from kotlin.script.experimental.api
230
sealed class ResultWithDiagnostics<out T> {
231
data class Success<T>(val value: T, val reports: List<ScriptDiagnostic> = emptyList()) : ResultWithDiagnostics<T>()
232
data class Failure(val reports: List<ScriptDiagnostic>) : ResultWithDiagnostics<Nothing>()
233
}
234
235
data class EvaluationResult(
236
val returnValue: ResultValue,
237
val configuration: ScriptEvaluationConfiguration
238
)
239
240
sealed class ResultValue {
241
object Unit : ResultValue()
242
data class Value(val name: String?, val value: Any?, val type: String?, val scriptClass: KClass<*>?, val scriptInstance: Any?) : ResultValue()
243
data class Error(val error: Throwable, val wrappingException: Throwable? = null, val scriptClass: KClass<*>? = null, val scriptInstance: Any? = null) : ResultValue()
244
object NotEvaluated : ResultValue()
245
}
246
```
247
248
### Script Source Types
249
250
```kotlin { .api }
251
// Imported from kotlin.script.experimental.api
252
interface SourceCode {
253
val text: String
254
val name: String?
255
val locationId: String?
256
}
257
258
interface CompiledScript {
259
val compilationConfiguration: ScriptCompilationConfiguration
260
val sourceLocationId: String?
261
val otherScripts: List<CompiledScript>
262
val resultField: Pair<String, KotlinType>?
263
suspend fun getClass(scriptEvaluationConfiguration: ScriptEvaluationConfiguration? = null): ResultWithDiagnostics<KClass<*>>
264
}
265
```
266
267
### Configuration Types
268
269
```kotlin { .api }
270
// Imported from kotlin.script.experimental.api
271
class ScriptCompilationConfiguration(
272
baseConfiguration: ScriptCompilationConfiguration? = null,
273
body: Builder.() -> Unit = {}
274
) : PropertiesCollection(Builder().apply(body).build())
275
276
class ScriptEvaluationConfiguration(
277
baseConfiguration: ScriptEvaluationConfiguration? = null,
278
body: Builder.() -> Unit = {}
279
) : PropertiesCollection(Builder().apply(body).build())
280
281
class ScriptingHostConfiguration(
282
baseConfiguration: ScriptingHostConfiguration? = null,
283
body: Builder.() -> Unit = {}
284
) : PropertiesCollection(Builder().apply(body).build())
285
```
286
287
## Migration from Deprecated APIs
288
289
Several APIs in this package have been deprecated and moved to the `kotlin.script.experimental.jvm` package. The deprecated APIs provide redirection to the new implementations:
290
291
### Deprecated Classes and Interfaces
292
293
```kotlin { .api }
294
// Deprecated in kotlin.script.experimental.jvmhost.obsoleteJvmScriptEvaluation
295
296
@Deprecated("Use JvmScriptEvaluationConfigurationKeys from kotlin.script.experimental.jvm", level = DeprecationLevel.WARNING)
297
interface JvmScriptEvaluationConfigurationKeys
298
299
@Deprecated("Use JvmScriptEvaluationConfigurationBuilder from kotlin.script.experimental.jvm", level = DeprecationLevel.WARNING)
300
class JvmScriptEvaluationConfigurationBuilder
301
302
@Deprecated("Use BasicJvmScriptEvaluator from kotlin.script.experimental.jvm", level = DeprecationLevel.ERROR)
303
class BasicJvmScriptEvaluator
304
```
305
306
### Deprecated Extension Properties
307
308
```kotlin { .api }
309
@Deprecated("Use baseClassLoader from kotlin.script.experimental.jvm", level = DeprecationLevel.ERROR)
310
val ScriptEvaluationConfigurationKeys.baseClassLoader: ScriptEvaluationConfigurationKeys.Key<ClassLoader?>
311
312
@Deprecated("Use jvm from kotlin.script.experimental.jvm", level = DeprecationLevel.ERROR)
313
val ScriptEvaluationConfigurationKeys.jvm: JvmScriptEvaluationConfigurationBuilder
314
```
315
316
### Migration Examples
317
318
```kotlin
319
// Old (deprecated)
320
import kotlin.script.experimental.jvmhost.BasicJvmScriptEvaluator
321
import kotlin.script.experimental.jvmhost.jvm
322
323
// New (recommended)
324
import kotlin.script.experimental.jvm.BasicJvmScriptEvaluator
325
import kotlin.script.experimental.jvm.jvm
326
327
// Migration pattern
328
val oldConfig = ScriptEvaluationConfiguration {
329
// Old way (deprecated)
330
jvm {
331
baseClassLoader(MyClass::class.java.classLoader)
332
}
333
}
334
335
val newConfig = ScriptEvaluationConfiguration {
336
// New way (recommended)
337
jvm {
338
baseClassLoader(MyClass::class.java.classLoader)
339
}
340
}
341
// Configuration is identical, just import from kotlin.script.experimental.jvm instead
342
```
343
344
For detailed migration information, see the [Kotlin Scripting Migration Guide](https://kotlinlang.org/docs/scripting.html).