or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

error-handling.mdhost-integration.mdindex.mdrepl-system.mdscript-annotations.mdscript-compilation.mdscript-evaluation.mdsource-code.mdtype-system.md

script-evaluation.mddocs/

0

# Script Evaluation

1

2

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

3

4

## Capabilities

5

6

### ScriptEvaluator Interface

7

8

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

9

10

```kotlin { .api }

11

/**

12

* Interface for evaluating compiled scripts

13

*/

14

interface ScriptEvaluator {

15

/**

16

* Evaluate a compiled script using the provided configuration

17

* @param compiledScript Previously compiled script to evaluate

18

* @param scriptEvaluationConfiguration Evaluation configuration

19

* @return Result containing evaluation results or runtime errors

20

*/

21

suspend operator fun invoke(

22

compiledScript: CompiledScript,

23

scriptEvaluationConfiguration: ScriptEvaluationConfiguration = ScriptEvaluationConfiguration.Default

24

): ResultWithDiagnostics<EvaluationResult>

25

}

26

```

27

28

### ScriptEvaluationConfiguration

29

30

Configuration container for controlling script evaluation behavior and runtime environment.

31

32

```kotlin { .api }

33

/**

34

* Configuration for script evaluation

35

*/

36

class ScriptEvaluationConfiguration : PropertiesCollection {

37

companion object {

38

val Default = ScriptEvaluationConfiguration()

39

}

40

}

41

```

42

43

### Evaluation Results

44

45

Data structures representing the results of script evaluation.

46

47

```kotlin { .api }

48

/**

49

* Result of script evaluation

50

*/

51

data class EvaluationResult(

52

val returnValue: ResultValue,

53

val configuration: ScriptEvaluationConfiguration?

54

)

55

56

/**

57

* Sealed class representing different types of evaluation results

58

*/

59

sealed class ResultValue(

60

val scriptClass: KClass<*>? = null,

61

val scriptInstance: Any? = null

62

) {

63

/**

64

* Successful evaluation with a value

65

*/

66

class Value(

67

val name: String,

68

val value: Any?,

69

val type: String,

70

scriptClass: KClass<*>?,

71

scriptInstance: Any?

72

) : ResultValue(scriptClass, scriptInstance)

73

74

/**

75

* Successful evaluation with Unit result

76

*/

77

class Unit(

78

scriptClass: KClass<*>,

79

scriptInstance: Any?

80

) : ResultValue(scriptClass, scriptInstance)

81

82

/**

83

* Evaluation failed with an error

84

*/

85

class Error(

86

val error: Throwable,

87

val wrappingException: Throwable? = null,

88

scriptClass: KClass<*>? = null

89

) : ResultValue(scriptClass)

90

91

/**

92

* Script was not evaluated

93

*/

94

object NotEvaluated : ResultValue()

95

}

96

```

97

98

### Configuration Keys

99

100

Key interfaces defining available configuration options for script evaluation.

101

102

```kotlin { .api }

103

/**

104

* Keys for script evaluation configuration properties

105

*/

106

interface ScriptEvaluationConfigurationKeys {

107

val scriptArgs: PropertiesCollection.Key<List<Any?>>

108

val implicitReceivers: PropertiesCollection.Key<List<Any>>

109

val providedProperties: PropertiesCollection.Key<Map<String, Any?>>

110

val constructorArgs: PropertiesCollection.Key<List<Any?>>

111

val contextVariables: PropertiesCollection.Key<Map<String, Any?>>

112

val enabledEvaluationFeatures: PropertiesCollection.Key<List<EvaluationFeature>>

113

val executionWrapper: PropertiesCollection.Key<ScriptExecutionWrapper<*>>

114

val refineConfigurationBeforeEvaluate: PropertiesCollection.Key<List<RefineScriptEvaluationConfigurationHandler>>

115

}

116

```

117

118

### Configuration Refinement

119

120

System for dynamically refining evaluation configuration before script execution.

121

122

```kotlin { .api }

123

/**

124

* Handler for refining script evaluation configuration

125

*/

126

typealias RefineScriptEvaluationConfigurationHandler =

127

suspend (ScriptEvaluationConfigurationRefinementContext) -> ResultWithDiagnostics<ScriptEvaluationConfiguration>

128

129

/**

130

* Context provided to evaluation refinement handlers

131

*/

132

data class ScriptEvaluationConfigurationRefinementContext(

133

val script: CompiledScript,

134

val evaluationConfiguration: ScriptEvaluationConfiguration,

135

val compilationConfiguration: ScriptCompilationConfiguration

136

)

137

138

/**

139

* Data for evaluation configuration refinement

140

*/

141

data class RefineEvaluationConfigurationData(

142

val handler: RefineScriptEvaluationConfigurationHandler

143

)

144

```

145

146

### Script Execution Wrapper

147

148

Interface for wrapping script execution with custom behavior.

149

150

```kotlin { .api }

151

/**

152

* Wrapper for script execution allowing custom execution behavior

153

*/

154

interface ScriptExecutionWrapper<T> {

155

/**

156

* Execute the provided script evaluation action

157

* @param body Script evaluation action to execute

158

* @return Result of the wrapped execution

159

*/

160

suspend operator fun invoke(body: suspend () -> T): T

161

}

162

```

163

164

### Context Data Management

165

166

System for managing evaluation context data and variables.

167

168

```kotlin { .api }

169

/**

170

* Keys for script evaluation context data

171

*/

172

interface ScriptEvaluationContextDataKeys {

173

val contextVariables: PropertiesCollection.Key<Map<String, Any?>>

174

val sharedContext: PropertiesCollection.Key<Map<String, Any?>>

175

}

176

177

/**

178

* Container for evaluation context data

179

*/

180

class ScriptEvaluationContextData : PropertiesCollection

181

```

182

183

**Usage Examples:**

184

185

```kotlin

186

import kotlin.script.experimental.api.*

187

188

// Basic evaluation configuration

189

val evaluationConfig = ScriptEvaluationConfiguration {

190

// Provide script arguments

191

scriptArgs(listOf("arg1", "arg2", 42))

192

193

// Set context variables available in the script

194

contextVariables(mapOf(

195

"workingDir" to File("."),

196

"version" to "1.0.0",

197

"debug" to true

198

))

199

200

// Provide implicit receiver objects

201

implicitReceivers(File("."))

202

}

203

204

// Evaluate a compiled script

205

class MyScriptEvaluator : ScriptEvaluator {

206

override suspend fun invoke(

207

compiledScript: CompiledScript,

208

configuration: ScriptEvaluationConfiguration

209

): ResultWithDiagnostics<EvaluationResult> {

210

// Implementation would use Kotlin reflection and execution APIs

211

// This is a simplified example

212

TODO("Implementation depends on specific evaluation backend")

213

}

214

}

215

216

// Using the evaluator

217

val evaluator = MyScriptEvaluator()

218

val result = evaluator(compiledScript, evaluationConfig)

219

220

when (result) {

221

is ResultWithDiagnostics.Success -> {

222

val evaluationResult = result.value

223

when (val returnValue = evaluationResult.returnValue) {

224

is ResultValue.Value -> {

225

println("Script returned: ${returnValue.value}")

226

println("Return type: ${returnValue.type}")

227

}

228

is ResultValue.Unit -> {

229

println("Script executed successfully (Unit result)")

230

}

231

is ResultValue.Error -> {

232

println("Script execution error: ${returnValue.error.message}")

233

returnValue.location?.let { loc ->

234

println("Error location: line ${loc.start.line}, col ${loc.start.col}")

235

}

236

}

237

is ResultValue.NotEvaluated -> {

238

println("Script was not evaluated")

239

}

240

}

241

}

242

is ResultWithDiagnostics.Failure -> {

243

result.reports.forEach { diagnostic ->

244

println("${diagnostic.severity}: ${diagnostic.message}")

245

}

246

}

247

}

248

```

249

250

### Advanced Evaluation Configuration

251

252

```kotlin

253

// Complex evaluation configuration with all features

254

val advancedEvaluationConfig = ScriptEvaluationConfiguration {

255

// Script constructor arguments

256

constructorArgs(listOf("constructor", "arguments"))

257

258

// Properties available directly in script scope

259

providedProperties(mapOf(

260

"logger" to getLogger("script"),

261

"config" to loadConfiguration(),

262

"database" to getDatabaseConnection()

263

))

264

265

// Context variables accessible via context

266

contextVariables(mapOf(

267

"environment" to "production",

268

"features" to listOf("feature1", "feature2"),

269

"settings" to mapOf("timeout" to 30000, "retries" to 3)

270

))

271

272

// Implicit receivers (this references in script)

273

implicitReceivers(listOf(

274

File(System.getProperty("user.dir")),

275

System.getProperties()

276

))

277

278

// Enable specific evaluation features

279

enabledEvaluationFeatures(listOf(

280

EvaluationFeature.COROUTINES,

281

EvaluationFeature.REFLECTION

282

))

283

284

// Custom execution wrapper

285

executionWrapper(object : ScriptExecutionWrapper<Any?> {

286

override suspend fun invoke(body: suspend () -> Any?): Any? {

287

println("Starting script execution...")

288

val start = System.currentTimeMillis()

289

try {

290

return body()

291

} finally {

292

val duration = System.currentTimeMillis() - start

293

println("Script execution completed in ${duration}ms")

294

}

295

}

296

})

297

298

// Configuration refinement

299

refineConfigurationBeforeEvaluate { context ->

300

// Add dynamic configuration based on script content

301

ScriptEvaluationConfiguration(context.evaluationConfiguration) {

302

contextVariables.put("scriptClass", context.script.getClass().valueOrNull()?.simpleName)

303

}.asSuccess()

304

}

305

}

306

```

307

308

### Custom Execution Wrappers

309

310

```kotlin

311

// Timeout wrapper

312

class TimeoutExecutionWrapper(private val timeoutMs: Long) : ScriptExecutionWrapper<Any?> {

313

override suspend fun invoke(body: suspend () -> Any?): Any? {

314

return withTimeout(timeoutMs) {

315

body()

316

}

317

}

318

}

319

320

// Security wrapper

321

class SecurityExecutionWrapper(private val permissions: Set<String>) : ScriptExecutionWrapper<Any?> {

322

override suspend fun invoke(body: suspend () -> Any?): Any? {

323

return withSecurityContext(permissions) {

324

body()

325

}

326

}

327

}

328

329

// Logging wrapper

330

class LoggingExecutionWrapper(private val logger: Logger) : ScriptExecutionWrapper<Any?> {

331

override suspend fun invoke(body: suspend () -> Any?): Any? {

332

logger.info("Script execution starting")

333

try {

334

val result = body()

335

logger.info("Script execution completed successfully")

336

return result

337

} catch (e: Exception) {

338

logger.error("Script execution failed", e)

339

throw e

340

}

341

}

342

}

343

344

// Using custom wrappers

345

val configWithWrapper = ScriptEvaluationConfiguration {

346

executionWrapper(TimeoutExecutionWrapper(30000)) // 30 second timeout

347

}

348

```

349

350

### Context Variable Access

351

352

```kotlin

353

// In the script being evaluated, context variables can be accessed:

354

// (This would be the content of the script being evaluated)

355

356

/*

357

// Context variables are available in the script

358

val env = contextVariables["environment"] as String

359

val features = contextVariables["features"] as List<String>

360

val settings = contextVariables["settings"] as Map<String, Any>

361

362

println("Running in environment: $env")

363

println("Available features: $features")

364

println("Timeout setting: ${settings["timeout"]}")

365

366

// Implicit receivers can be used directly

367

println("Current directory: $absolutePath") // File receiver

368

println("Java version: ${getProperty("java.version")}") // Properties receiver

369

*/

370

```