0
# Core Scripting Host
1
2
The core scripting host provides the main entry point for Kotlin script execution with template-based configuration and comprehensive error handling.
3
4
## Capabilities
5
6
### BasicJvmScriptingHost
7
8
Main JVM scripting host implementation that extends BasicScriptingHost with JVM-specific functionality.
9
10
```kotlin { .api }
11
/**
12
* Main JVM scripting host for executing Kotlin scripts with configurable compiler and evaluator
13
* @param baseHostConfiguration Optional base host configuration
14
* @param compiler JVM script compiler instance
15
* @param evaluator Script evaluator instance
16
*/
17
open class BasicJvmScriptingHost(
18
val baseHostConfiguration: ScriptingHostConfiguration? = null,
19
compiler: JvmScriptCompiler = JvmScriptCompiler(baseHostConfiguration.withDefaultsFrom(defaultJvmScriptingHostConfiguration)),
20
evaluator: ScriptEvaluator = BasicJvmScriptEvaluator()
21
) : BasicScriptingHost(compiler, evaluator) {
22
23
/**
24
* Evaluates a script using a template-based configuration
25
* @param script Source code to evaluate
26
* @param compilation Compilation configuration builder
27
* @param evaluation Evaluation configuration builder
28
* @returns Result with diagnostics containing evaluation result or errors
29
*/
30
inline fun <reified T : Any> evalWithTemplate(
31
script: SourceCode,
32
noinline compilation: ScriptCompilationConfiguration.Builder.() -> Unit = {},
33
noinline evaluation: ScriptEvaluationConfiguration.Builder.() -> Unit = {}
34
): ResultWithDiagnostics<EvaluationResult>
35
}
36
```
37
38
**Usage Examples:**
39
40
```kotlin
41
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
42
import kotlin.script.experimental.api.*
43
44
// Basic host creation
45
val host = BasicJvmScriptingHost()
46
47
// Script execution with simple template
48
@KotlinScript(fileExtension = "kts")
49
class SimpleScript
50
51
val script = "val x = 42; println(\"Result: \$x\")"
52
val result = host.evalWithTemplate<SimpleScript>(script.toScriptSource())
53
54
// Handle result
55
when (result) {
56
is ResultWithDiagnostics.Success -> {
57
val evaluationResult = result.value
58
when (val returnValue = evaluationResult.returnValue) {
59
is ResultValue.Value -> println("Script returned: ${returnValue.value}")
60
is ResultValue.Unit -> println("Script executed successfully")
61
is ResultValue.Error -> println("Execution error: ${returnValue.error.message}")
62
else -> println("Script not evaluated")
63
}
64
}
65
is ResultWithDiagnostics.Failure -> {
66
result.reports.forEach { report ->
67
println("${report.severity}: ${report.message}")
68
}
69
}
70
}
71
72
// Advanced usage with custom configuration
73
val customHost = BasicJvmScriptingHost(
74
baseHostConfiguration = ScriptingHostConfiguration {
75
// Custom host configuration
76
}
77
)
78
79
val advancedResult = customHost.evalWithTemplate<SimpleScript>(
80
script = script.toScriptSource(),
81
compilation = {
82
// Compilation configuration
83
dependencies(JvmDependency(File("/path/to/library.jar")))
84
importScripts(FileBasedScriptSource(File("common.kts")))
85
},
86
evaluation = {
87
// Evaluation configuration
88
constructorArgs("arg1", "arg2")
89
providedProperties("contextVar" to "contextValue")
90
}
91
)
92
```
93
94
### Template Configuration Functions
95
96
Utility functions for creating configuration objects from template types with type-safe builders.
97
98
#### createJvmCompilationConfigurationFromTemplate
99
100
Creates JVM compilation configuration from a template type with optional customization.
101
102
```kotlin { .api }
103
/**
104
* Creates JVM compilation configuration from template type
105
* @param baseHostConfiguration Optional base host configuration
106
* @param body Configuration builder function
107
* @returns Configured ScriptCompilationConfiguration
108
*/
109
inline fun <reified T : Any> createJvmCompilationConfigurationFromTemplate(
110
baseHostConfiguration: ScriptingHostConfiguration? = null,
111
noinline body: ScriptCompilationConfiguration.Builder.() -> Unit = {}
112
): ScriptCompilationConfiguration
113
```
114
115
**Usage Example:**
116
117
```kotlin
118
@KotlinScript(fileExtension = "script.kts")
119
class MyScriptTemplate
120
121
val compilationConfig = createJvmCompilationConfigurationFromTemplate<MyScriptTemplate> {
122
dependencies(JvmDependency(File("lib.jar")))
123
importScripts(FileBasedScriptSource(File("common.kts")))
124
compilerOptions.append("-opt-in=kotlin.RequiresOptIn")
125
}
126
```
127
128
#### createJvmEvaluationConfigurationFromTemplate
129
130
Creates JVM evaluation configuration from a template type with optional customization.
131
132
```kotlin { .api }
133
/**
134
* Creates JVM evaluation configuration from template type
135
* @param baseHostConfiguration Optional base host configuration
136
* @param body Configuration builder function
137
* @returns Configured ScriptEvaluationConfiguration
138
*/
139
inline fun <reified T : Any> createJvmEvaluationConfigurationFromTemplate(
140
baseHostConfiguration: ScriptingHostConfiguration? = null,
141
noinline body: ScriptEvaluationConfiguration.Builder.() -> Unit = {}
142
): ScriptEvaluationConfiguration
143
```
144
145
**Usage Example:**
146
147
```kotlin
148
val evaluationConfig = createJvmEvaluationConfigurationFromTemplate<MyScriptTemplate> {
149
constructorArgs("arg1", 42, true)
150
providedProperties(
151
"database" to DatabaseConnection(),
152
"logger" to LoggerFactory.getLogger("script")
153
)
154
jvm {
155
baseClassLoader(MyClass::class.java.classLoader)
156
}
157
}
158
```
159
160
#### createJvmScriptDefinitionFromTemplate
161
162
Creates a complete script definition combining compilation and evaluation configurations from a template type.
163
164
```kotlin { .api }
165
/**
166
* Creates complete script definition from template type
167
* @param baseHostConfiguration Optional base host configuration
168
* @param compilation Compilation configuration builder
169
* @param evaluation Evaluation configuration builder
170
* @returns Complete ScriptDefinition
171
*/
172
inline fun <reified T : Any> createJvmScriptDefinitionFromTemplate(
173
baseHostConfiguration: ScriptingHostConfiguration? = null,
174
noinline compilation: ScriptCompilationConfiguration.Builder.() -> Unit = {},
175
noinline evaluation: ScriptEvaluationConfiguration.Builder.() -> Unit = {}
176
): ScriptDefinition
177
```
178
179
**Usage Example:**
180
181
```kotlin
182
val scriptDefinition = createJvmScriptDefinitionFromTemplate<MyScriptTemplate>(
183
compilation = {
184
dependencies(JvmDependency(File("runtime.jar")))
185
compilerOptions.append("-Xmulti-platform")
186
},
187
evaluation = {
188
constructorArgs("contextData")
189
enableScriptsInstancesSharing()
190
}
191
)
192
193
// Use with compiler directly
194
val compiler = JvmScriptCompiler()
195
val compilationResult = compiler(
196
script.toScriptSource(),
197
scriptDefinition.compilationConfiguration
198
)
199
```
200
201
## Error Handling
202
203
The core scripting host provides comprehensive error reporting through the `ResultWithDiagnostics` system:
204
205
### Diagnostic Types
206
207
```kotlin { .api }
208
enum class ScriptDiagnostic.Severity {
209
DEBUG, INFO, WARNING, ERROR, FATAL
210
}
211
212
data class ScriptDiagnostic(
213
val code: Int,
214
val message: String,
215
val severity: Severity,
216
val location: SourceCode.Location? = null,
217
val exception: Throwable? = null
218
)
219
```
220
221
### Common Error Scenarios
222
223
- **Compilation Errors**: Syntax errors, type mismatches, unresolved dependencies
224
- **Runtime Errors**: Exceptions during script execution, class loading issues
225
- **Configuration Errors**: Invalid host configuration, missing dependencies
226
- **Template Errors**: Invalid template annotations, incompatible template types
227
228
**Error Handling Example:**
229
230
```kotlin
231
val result = host.evalWithTemplate<MyTemplate>(script.toScriptSource())
232
233
when (result) {
234
is ResultWithDiagnostics.Success -> {
235
// Handle successful evaluation
236
val evaluationResult = result.value
237
if (result.reports.isNotEmpty()) {
238
// Handle warnings
239
result.reports.filter { it.severity == ScriptDiagnostic.Severity.WARNING }
240
.forEach { println("Warning: ${it.message}") }
241
}
242
}
243
is ResultWithDiagnostics.Failure -> {
244
// Handle compilation or evaluation failure
245
result.reports.forEach { diagnostic ->
246
val location = diagnostic.location?.let { " at line ${it.start.line}" } ?: ""
247
println("${diagnostic.severity}$location: ${diagnostic.message}")
248
diagnostic.exception?.let {
249
println("Caused by: ${it.javaClass.simpleName}: ${it.message}")
250
}
251
}
252
}
253
}
254
```