Kotlin Script Host - Embedded script compilation

Hello all. Very quick question here, I hope.

I’ve gone through the challenges in the past of using the jsr223 api for script compilation “on demand” in my server application for taking code out as configuration.

One of the limitations I never found a workaround for is the passing of compiler extension args (“-XX”), so I have never been able to use the new type inference or inline classes in my scripts. Recently, I switched to the experimental ScriptCompiler from jetbrains, but I still can’t see hte mechanism for specifying compiler args. Anyone have any suggestions?

In short, I want/need to be able ot compile a script that relies upon new type inference.

Managed to find a solution.

I switched to the experimental scripting engine, and managed to find the following solution.

val SCRIPT_ENGINE_CONFIG by lazy {
    createJvmCompilationConfigurationFromTemplate<SimpleScript> {
        jvm {
            // wow, just...wow
            compilerOptions.append("-jvm-target")
            compilerOptions.append("1.8")
            compilerOptions.append("-Xnew-inference")
            compilerOptions.append("-Xinline-classes")
            dependenciesFromCurrentContext(
                    wholeClasspath = true
            )
        }
    }
}

val SCRIPT_HOST = BasicJvmScriptingHost()

@KotlinScript(fileExtension = "simplescript.kts")
abstract class SimpleScript

… and then using it like so…

val compileResult = SCRIPT_HOST.eval(StringScriptSource(finalScript), SCRIPT_ENGINE_CONFIG, null)

I don’t fully understand the purpose of the SimpleScript type…my gut tells me that the above could somehow be simplified further.

This is the correct way to specify compiler options. Take into account though, that not all options are possible to set this way. But the proper warning should be generated and added to the compilation diagnostics if you’ll try to use a non-supported option.

Two minor recommendations.

First, you can use the more concise syntax in the configuration dsl, e.g.:

compilerOptions.append("-jvm-target", "1.8", "-Xnew-inference", "-Xinline-classes")

or even

compilerOptions("-jvm-target", "1.8", "-Xnew-inference", "-Xinline-classes")

for the initial configuration.
And also compilerOprions could be specified on the top level, not inside jvm.

Second - it is recommended to attach the configuration to the KotlinScript annotation, like here - kotlin-script-examples/scriptDef.kt at master · Kotlin/kotlin-script-examples · GitHub
This way you can get IDE support as well as discovery functionality.