Cleanup warnings in scripting code
This commit is contained in:
@@ -45,7 +45,7 @@ public class XmlMessageRenderer implements MessageRenderer {
|
||||
}
|
||||
|
||||
private static String e(String str) {
|
||||
return StringUtil.escapeXml(str);
|
||||
return StringUtil.escapeXmlEntities(str);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -9,6 +9,7 @@ jvmTarget = "1.6"
|
||||
dependencies {
|
||||
compile(kotlinStdlib())
|
||||
compile(commonDep("org.jetbrains.kotlinx", "kotlinx-coroutines-core")) { isTransitive = false }
|
||||
compileOnly(project(":kotlin-reflect-api"))
|
||||
testCompile(commonDep("junit"))
|
||||
}
|
||||
|
||||
|
||||
+38
-35
@@ -50,19 +50,19 @@ open class PropertiesCollection(protected var properties: Map<Key<*>, Any?> = em
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
operator fun <T> get(key: PropertiesCollection.Key<T>): T? =
|
||||
operator fun <T> get(key: Key<T>): T? =
|
||||
(properties[key] ?: if (properties.containsKey(key)) null else key.getDefaultValue(this)) as? T
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun <T> getNoDefault(key: PropertiesCollection.Key<T>): T? =
|
||||
fun <T> getNoDefault(key: Key<T>): T? =
|
||||
properties[key]?.let { it as T }
|
||||
|
||||
fun <T> containsKey(key: PropertiesCollection.Key<T>): Boolean =
|
||||
fun <T> containsKey(key: Key<T>): Boolean =
|
||||
properties.containsKey(key)
|
||||
|
||||
fun entries(): Set<Map.Entry<Key<*>, Any?>> = properties.entries
|
||||
|
||||
val notTransientData: Map<Key<*>, Any?> get() = properties.filterKeys { it !is TransientKey<*>}
|
||||
val notTransientData: Map<Key<*>, Any?> get() = properties.filterKeys { it !is TransientKey<*> }
|
||||
|
||||
fun isEmpty(): Boolean = properties.isEmpty()
|
||||
|
||||
@@ -97,159 +97,162 @@ open class PropertiesCollection(protected var properties: Map<Key<*>, Any?> = em
|
||||
|
||||
open class Builder(baseProperties: Iterable<PropertiesCollection> = emptyList()) {
|
||||
|
||||
val data: MutableMap<PropertiesCollection.Key<*>, Any?> = LinkedHashMap<PropertiesCollection.Key<*>, Any?>().apply {
|
||||
val data: MutableMap<Key<*>, Any?> = LinkedHashMap<Key<*>, Any?>().apply {
|
||||
baseProperties.forEach { putAll(it.properties) }
|
||||
}
|
||||
|
||||
// generic for all properties
|
||||
|
||||
operator fun <T> PropertiesCollection.Key<T>.invoke(v: T) {
|
||||
operator fun <T> Key<T>.invoke(v: T) {
|
||||
data[this] = v
|
||||
}
|
||||
|
||||
fun <T> PropertiesCollection.Key<T>.put(v: T) {
|
||||
fun <T> Key<T>.put(v: T) {
|
||||
data[this] = v
|
||||
}
|
||||
|
||||
fun <T> PropertiesCollection.Key<T>.putIfNotNull(v: T?) {
|
||||
fun <T> Key<T>.putIfNotNull(v: T?) {
|
||||
if (v != null) {
|
||||
data[this] = v
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> PropertiesCollection.Key<T>.replaceOnlyDefault(v: T?) {
|
||||
fun <T> Key<T>.replaceOnlyDefault(v: T?) {
|
||||
if (!data.containsKey(this) || data[this] == this.getDefaultValue(PropertiesCollection(data))) {
|
||||
data[this] = v
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> PropertiesCollection.Key<T>.update(body: (T?) -> T?) {
|
||||
putIfNotNull(body(data[this]?.let { it as T }))
|
||||
fun <T> Key<T>.update(body: (T?) -> T?) {
|
||||
putIfNotNull(body(data[this]?.let {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
it as T
|
||||
}))
|
||||
}
|
||||
|
||||
// generic for lists
|
||||
|
||||
fun <T> PropertiesCollection.Key<in List<T>>.putIfAny(vals: Iterable<T>?) {
|
||||
fun <T> Key<in List<T>>.putIfAny(vals: Iterable<T>?) {
|
||||
if (vals?.any() == true) {
|
||||
data[this] = if (vals is List) vals else vals.toList()
|
||||
}
|
||||
}
|
||||
|
||||
operator fun <T> PropertiesCollection.Key<in List<T>>.invoke(vararg vals: T) {
|
||||
operator fun <T> Key<in List<T>>.invoke(vararg vals: T) {
|
||||
append(vals.asIterable())
|
||||
}
|
||||
|
||||
// generic for maps:
|
||||
|
||||
@JvmName("putIfAny_map")
|
||||
fun <K, V> PropertiesCollection.Key<in Map<K, V>>.putIfAny(vals: Iterable<Pair<K, V>>?) {
|
||||
fun <K, V> Key<in Map<K, V>>.putIfAny(vals: Iterable<Pair<K, V>>?) {
|
||||
if (vals?.any() == true) {
|
||||
data[this] = vals.toMap()
|
||||
}
|
||||
}
|
||||
|
||||
fun <K, V> PropertiesCollection.Key<in Map<K, V>>.putIfAny(vals: Map<K, V>?) {
|
||||
fun <K, V> Key<in Map<K, V>>.putIfAny(vals: Map<K, V>?) {
|
||||
if (vals?.isNotEmpty() == true) {
|
||||
data[this] = vals
|
||||
}
|
||||
}
|
||||
|
||||
operator fun <K, V> PropertiesCollection.Key<Map<K, V>>.invoke(vararg vs: Pair<K, V>) {
|
||||
operator fun <K, V> Key<Map<K, V>>.invoke(vararg vs: Pair<K, V>) {
|
||||
append(vs.asIterable())
|
||||
}
|
||||
|
||||
// for strings and list of strings that could be converted from other types
|
||||
|
||||
@JvmName("invoke_string_fqn_from_reflected_class")
|
||||
operator fun PropertiesCollection.Key<String>.invoke(kclass: KClass<*>) {
|
||||
operator fun Key<String>.invoke(kclass: KClass<*>) {
|
||||
data[this] = kclass.java.name
|
||||
}
|
||||
|
||||
@JvmName("invoke_string_list_fqn_from_reflected_class")
|
||||
operator fun PropertiesCollection.Key<in List<String>>.invoke(vararg kclasses: KClass<*>) {
|
||||
operator fun Key<in List<String>>.invoke(vararg kclasses: KClass<*>) {
|
||||
append(kclasses.map { it.java.name })
|
||||
}
|
||||
|
||||
// for KotlinType:
|
||||
|
||||
operator fun PropertiesCollection.Key<KotlinType>.invoke(kclass: KClass<*>) {
|
||||
operator fun Key<KotlinType>.invoke(kclass: KClass<*>) {
|
||||
data[this] = KotlinType(kclass)
|
||||
}
|
||||
|
||||
operator fun PropertiesCollection.Key<KotlinType>.invoke(ktype: KType) {
|
||||
operator fun Key<KotlinType>.invoke(ktype: KType) {
|
||||
data[this] = KotlinType(ktype)
|
||||
}
|
||||
|
||||
operator fun PropertiesCollection.Key<KotlinType>.invoke(fqname: String) {
|
||||
operator fun Key<KotlinType>.invoke(fqname: String) {
|
||||
data[this] = KotlinType(fqname)
|
||||
}
|
||||
|
||||
// for list of KotlinTypes
|
||||
|
||||
operator fun PropertiesCollection.Key<List<KotlinType>>.invoke(vararg classes: KClass<*>) {
|
||||
operator fun Key<List<KotlinType>>.invoke(vararg classes: KClass<*>) {
|
||||
append(classes.map { KotlinType(it) })
|
||||
}
|
||||
|
||||
operator fun PropertiesCollection.Key<List<KotlinType>>.invoke(vararg types: KType) {
|
||||
operator fun Key<List<KotlinType>>.invoke(vararg types: KType) {
|
||||
append(types.map { KotlinType(it) })
|
||||
}
|
||||
|
||||
operator fun PropertiesCollection.Key<List<KotlinType>>.invoke(vararg fqnames: String) {
|
||||
operator fun Key<List<KotlinType>>.invoke(vararg fqnames: String) {
|
||||
append(fqnames.map { KotlinType(it) })
|
||||
}
|
||||
|
||||
// for map of generic keys to KotlinTypes:
|
||||
|
||||
@JvmName("invoke_kotlintype_map_from_kclass")
|
||||
operator fun <K> PropertiesCollection.Key<Map<K, KotlinType>>.invoke(vararg classes: Pair<K, KClass<*>>) {
|
||||
operator fun <K> Key<Map<K, KotlinType>>.invoke(vararg classes: Pair<K, KClass<*>>) {
|
||||
append(classes.map { (k, v) -> k to KotlinType(v) })
|
||||
}
|
||||
|
||||
@JvmName("invoke_kotlintype_map_from_ktype")
|
||||
operator fun <K> PropertiesCollection.Key<Map<K, KotlinType>>.invoke(vararg types: Pair<K, KType>) {
|
||||
operator fun <K> Key<Map<K, KotlinType>>.invoke(vararg types: Pair<K, KType>) {
|
||||
append(types.map { (k, v) -> k to KotlinType(v) })
|
||||
}
|
||||
|
||||
@JvmName("invoke_kotlintype_map_from_fqname")
|
||||
operator fun <K> PropertiesCollection.Key<Map<K, KotlinType>>.invoke(vararg fqnames: Pair<K, String>) {
|
||||
operator fun <K> Key<Map<K, KotlinType>>.invoke(vararg fqnames: Pair<K, String>) {
|
||||
append(fqnames.map { (k, v) -> k to KotlinType(v) })
|
||||
}
|
||||
|
||||
// direct manipulation - public - for usage in inline dsl methods and for extending dsl
|
||||
|
||||
operator fun <T> set(key: PropertiesCollection.Key<in T>, value: T) {
|
||||
operator fun <T> set(key: Key<in T>, value: T) {
|
||||
data[key] = value
|
||||
}
|
||||
|
||||
fun <T> reset(key: PropertiesCollection.Key<in T>) {
|
||||
fun <T> reset(key: Key<in T>) {
|
||||
data.remove(key)
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
operator fun <T : Any> get(key: PropertiesCollection.Key<in T>): T? = data[key]?.let { it as T }
|
||||
operator fun <T : Any> get(key: Key<in T>): T? = data[key]?.let { it as T }
|
||||
|
||||
operator fun <T : Any> PropertiesCollection.Key<T>.invoke(): T? = get(this)
|
||||
operator fun <T : Any> Key<T>.invoke(): T? = get(this)
|
||||
|
||||
// appenders to list and map properties
|
||||
|
||||
@JvmName("appendToList")
|
||||
fun <V> PropertiesCollection.Key<in List<V>>.append(values: Iterable<V>) {
|
||||
fun <V> Key<in List<V>>.append(values: Iterable<V>) {
|
||||
val newValues = get(this)?.let { it + values } ?: values.toList()
|
||||
data[this] = newValues
|
||||
}
|
||||
|
||||
fun <V> PropertiesCollection.Key<in List<V>>.append(vararg values: V) {
|
||||
fun <V> Key<in List<V>>.append(vararg values: V) {
|
||||
val newValues = get(this)?.let { it + values } ?: values.toList()
|
||||
data[this] = newValues
|
||||
}
|
||||
|
||||
fun <K, V> PropertiesCollection.Key<in Map<K, V>>.append(values: Map<K, V>) {
|
||||
fun <K, V> Key<in Map<K, V>>.append(values: Map<K, V>) {
|
||||
val newValues = get(this)?.let { it + values } ?: values
|
||||
data[this] = newValues
|
||||
}
|
||||
|
||||
@JvmName("appendToMap")
|
||||
fun <K, V> PropertiesCollection.Key<in Map<K, V>>.append(values: Iterable<Pair<K, V>>) {
|
||||
fun <K, V> Key<in Map<K, V>>.append(values: Iterable<Pair<K, V>>) {
|
||||
val newValues = get(this)?.let { it + values } ?: values.toMap()
|
||||
data[this] = newValues
|
||||
}
|
||||
|
||||
+1
-1
@@ -155,7 +155,7 @@ obj
|
||||
// assertThrows(NoSuchMethodException::class.java) {
|
||||
// invocator!!.invokeMethod(res1, "fn", 3)
|
||||
// }
|
||||
val res3 = invocator!!.invokeMethod(res1, "fn1", 3)
|
||||
val res3 = invocator.invokeMethod(res1, "fn1", 3)
|
||||
Assert.assertEquals(6, res3)
|
||||
}
|
||||
|
||||
|
||||
+12
-12
@@ -52,7 +52,7 @@ class CachingTest : TestCase() {
|
||||
fun testFileCache() {
|
||||
withTempDir("scriptingTestCache") { cacheDir ->
|
||||
val cache = FileBasedScriptCache(cacheDir)
|
||||
Assert.assertTrue(cache.baseDir.listFiles().isEmpty())
|
||||
Assert.assertEquals(true, cache.baseDir.listFiles()?.isEmpty())
|
||||
|
||||
checkWithCache(cache, simpleScript, simpleScriptExpectedOutput)
|
||||
}
|
||||
@@ -62,7 +62,7 @@ class CachingTest : TestCase() {
|
||||
fun testSimpleImportWithFileCache() {
|
||||
withTempDir("scriptingTestCache") { cacheDir ->
|
||||
val cache = FileBasedScriptCache(cacheDir)
|
||||
Assert.assertTrue(cache.baseDir.listFiles().isEmpty())
|
||||
Assert.assertEquals(true, cache.baseDir.listFiles()?.isEmpty())
|
||||
|
||||
checkWithCache(
|
||||
cache, scriptWithImport, scriptWithImportExpectedOutput,
|
||||
@@ -190,9 +190,7 @@ class CachingTest : TestCase() {
|
||||
}
|
||||
}
|
||||
|
||||
object Implicit {
|
||||
val ix = 0
|
||||
}
|
||||
object Implicit
|
||||
|
||||
private interface ScriptingCacheWithCounters : CompiledJvmScriptsCache {
|
||||
|
||||
@@ -230,7 +228,7 @@ private class FileBasedScriptCache(val baseDir: File) : ScriptingCacheWithCounte
|
||||
|
||||
override fun get(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration): CompiledScript? {
|
||||
val file = File(baseDir, uniqueScriptHash(script, scriptCompilationConfiguration))
|
||||
return if (!file.exists()) null else file.readCompiledScript(scriptCompilationConfiguration)?.also { retrievedScripts++ }
|
||||
return if (!file.exists()) null else file.readCompiledScript().also { retrievedScripts++ }
|
||||
}
|
||||
|
||||
override fun store(
|
||||
@@ -254,11 +252,13 @@ private class FileBasedScriptCache(val baseDir: File) : ScriptingCacheWithCounte
|
||||
private set
|
||||
}
|
||||
|
||||
class TestCompiledScriptJarsCache(val baseDir: File) : CompiledScriptJarsCache(
|
||||
{ script, scriptCompilationConfiguration ->
|
||||
File(baseDir, uniqueScriptHash(script, scriptCompilationConfiguration) + ".jar")
|
||||
}), ScriptingCacheWithCounters
|
||||
{
|
||||
class TestCompiledScriptJarsCache(val baseDir: File) :
|
||||
CompiledScriptJarsCache(
|
||||
{ script, scriptCompilationConfiguration ->
|
||||
File(baseDir, uniqueScriptHash(script, scriptCompilationConfiguration) + ".jar")
|
||||
}
|
||||
), ScriptingCacheWithCounters {
|
||||
|
||||
override fun get(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration): CompiledScript? =
|
||||
super.get(script, scriptCompilationConfiguration)?.also { retrievedScripts++ }
|
||||
|
||||
@@ -289,7 +289,7 @@ internal fun uniqueScriptHash(script: SourceCode, scriptCompilationConfiguration
|
||||
return digestWrapper.digest().toHexString()
|
||||
}
|
||||
|
||||
private fun File.readCompiledScript(scriptCompilationConfiguration: ScriptCompilationConfiguration): CompiledScript {
|
||||
private fun File.readCompiledScript(): CompiledScript {
|
||||
return inputStream().use { fs ->
|
||||
ObjectInputStream(fs).use {
|
||||
it.readObject() as KJvmCompiledScript
|
||||
|
||||
+3
-3
@@ -379,7 +379,7 @@ class ScriptingHostTest : TestCase() {
|
||||
val res = compiler(script.toScriptSource(), scriptCompilationConfiguration).throwOnFailure()
|
||||
(res as ResultWithDiagnostics.Success<CompiledScript>).value
|
||||
}
|
||||
val compiledScriptClass = runBlocking { compiledScript.getClass(null).throwOnFailure().valueOrNull()!! as KClass<*> }
|
||||
val compiledScriptClass = runBlocking { compiledScript.getClass(null).throwOnFailure().valueOrNull()!! }
|
||||
val classLoader = compiledScriptClass.java.classLoader
|
||||
|
||||
Assert.assertTrue(classLoader is CompiledScriptClassLoader)
|
||||
@@ -394,8 +394,8 @@ class ScriptingHostTest : TestCase() {
|
||||
Assert.assertNotNull(classAsResourceUrl)
|
||||
Assert.assertNotNull(classAssResourceStream)
|
||||
|
||||
val classAsResourceData = classAsResourceUrl.openConnection().getInputStream().readBytes()
|
||||
val classAsResourceStreamData = classAssResourceStream.readBytes()
|
||||
val classAsResourceData = classAsResourceUrl!!.openConnection().getInputStream().readBytes()
|
||||
val classAsResourceStreamData = classAssResourceStream!!.readBytes()
|
||||
|
||||
Assert.assertArrayEquals(classAsResourceData, classAsResourceStreamData)
|
||||
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ class JvmReplEvaluator(
|
||||
}
|
||||
|
||||
open class JvmReplEvaluatorState(
|
||||
scriptEvaluationConfiguration: ScriptEvaluationConfiguration,
|
||||
@Suppress("UNUSED_PARAMETER") scriptEvaluationConfiguration: ScriptEvaluationConfiguration,
|
||||
override val lock: ReentrantReadWriteLock = ReentrantReadWriteLock()
|
||||
) : IReplStageState<Pair<KClass<*>?, Any?>> {
|
||||
override val history: IReplStageHistory<Pair<KClass<*>?, Any?>> = ReplStageHistoryWithReplace(lock)
|
||||
|
||||
+1
-1
@@ -5,12 +5,12 @@
|
||||
|
||||
package org.jetbrains.kotlin.mainKts.test
|
||||
|
||||
import junit.framework.Assert
|
||||
import org.jetbrains.kotlin.mainKts.COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR
|
||||
import org.jetbrains.kotlin.mainKts.COMPILED_SCRIPTS_CACHE_DIR_PROPERTY
|
||||
import org.jetbrains.kotlin.scripting.compiler.plugin.runWithK2JVMCompiler
|
||||
import org.jetbrains.kotlin.scripting.compiler.plugin.runWithKotlinLauncherScript
|
||||
import org.jetbrains.kotlin.scripting.compiler.plugin.runWithKotlinc
|
||||
import org.junit.Assert
|
||||
import org.junit.Ignore
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
+1
@@ -141,6 +141,7 @@ class MainKtsTest {
|
||||
DataInputStream(ByteArrayInputStream(scriptClassResource.readBytes())).use { stream ->
|
||||
val header = stream.readInt()
|
||||
if (0xCAFEBABE.toInt() != header) throw IOException("Invalid header class header: $header")
|
||||
@Suppress("UNUSED_VARIABLE")
|
||||
val minor = stream.readUnsignedShort()
|
||||
val major = stream.readUnsignedShort()
|
||||
Assert.assertTrue(major == 50)
|
||||
|
||||
@@ -29,7 +29,7 @@ suspend fun resolveFromAnnotations(resolver: ExternalDependenciesResolver, annot
|
||||
return annotations.filterIsInstance(DependsOn::class.java).flatMapSuccess { dep ->
|
||||
val artifactCoordinates =
|
||||
if (dep.value.isNotBlank()) dep.value
|
||||
else listOf(dep.groupId, dep.artifactId, dep.version).filter { it?.isNotBlank() ?: false }.joinToString(":")
|
||||
else listOf(dep.groupId, dep.artifactId, dep.version).filter { it.isNotBlank() }.joinToString(":")
|
||||
resolver.resolve(artifactCoordinates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ class MainKtsConfigurator : RefineScriptCompilationConfigurationHandler {
|
||||
|
||||
return resolveResult.onSuccess { resolvedClassPath ->
|
||||
ScriptCompilationConfiguration(context.compilationConfiguration) {
|
||||
if (resolvedClassPath != null) updateClasspath(resolvedClassPath)
|
||||
updateClasspath(resolvedClassPath)
|
||||
if (importedSources.isNotEmpty()) importScripts.append(importedSources)
|
||||
if (compileOptions.isNotEmpty()) compilerOptions.append(compileOptions)
|
||||
}.asSuccess()
|
||||
|
||||
+17
-16
@@ -20,33 +20,34 @@ package org.jetbrains.kotlin.script.jsr223
|
||||
|
||||
import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBase
|
||||
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
|
||||
import org.jetbrains.kotlin.script.util.*
|
||||
import javax.script.Bindings
|
||||
import javax.script.ScriptContext
|
||||
import javax.script.ScriptEngine
|
||||
import kotlin.script.experimental.jvm.util.KotlinJars
|
||||
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
|
||||
|
||||
class KotlinJsr223JvmLocalScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {
|
||||
|
||||
override fun getScriptEngine(): ScriptEngine =
|
||||
KotlinJsr223JvmLocalScriptEngine(
|
||||
this,
|
||||
scriptCompilationClasspathFromContextOrStlib("kotlin-script-util.jar", wholeClasspath = true),
|
||||
KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
|
||||
{ ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
|
||||
arrayOf(Bindings::class)
|
||||
)
|
||||
KotlinJsr223JvmLocalScriptEngine(
|
||||
this,
|
||||
scriptCompilationClasspathFromContext("kotlin-script-util.jar", wholeClasspath = true),
|
||||
KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
|
||||
{ ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
|
||||
arrayOf(Bindings::class)
|
||||
)
|
||||
}
|
||||
|
||||
class KotlinJsr223JvmDaemonLocalEvalScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {
|
||||
|
||||
override fun getScriptEngine(): ScriptEngine =
|
||||
KotlinJsr223JvmDaemonCompileScriptEngine(
|
||||
this,
|
||||
KotlinJars.compilerWithScriptingClasspath,
|
||||
scriptCompilationClasspathFromContextOrStlib("kotlin-script-util.jar", wholeClasspath = true),
|
||||
KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
|
||||
{ ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
|
||||
arrayOf(Bindings::class)
|
||||
)
|
||||
KotlinJsr223JvmDaemonCompileScriptEngine(
|
||||
this,
|
||||
KotlinJars.compilerWithScriptingClasspath,
|
||||
scriptCompilationClasspathFromContext("kotlin-script-util.jar", wholeClasspath = true),
|
||||
KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
|
||||
{ ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
|
||||
arrayOf(Bindings::class)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+28
-22
@@ -56,6 +56,7 @@ import kotlin.script.experimental.api.onSuccess
|
||||
import kotlin.script.experimental.api.valueOr
|
||||
import kotlin.script.experimental.host.toScriptSource
|
||||
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
|
||||
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
|
||||
|
||||
const val KOTLIN_JAVA_RUNTIME_JAR = "kotlin-stdlib.jar"
|
||||
|
||||
@@ -63,12 +64,12 @@ class ScriptUtilIT {
|
||||
|
||||
companion object {
|
||||
private val argsHelloWorldOutput =
|
||||
"""Hello, world!
|
||||
"""Hello, world!
|
||||
a1
|
||||
done
|
||||
"""
|
||||
private val bindingsHelloWorldOutput =
|
||||
"""Hello, world!
|
||||
"""Hello, world!
|
||||
a1 = 42
|
||||
done
|
||||
"""
|
||||
@@ -107,8 +108,7 @@ done
|
||||
try {
|
||||
System.setErr(PrintStream(NullOutputStream()))
|
||||
Assert.assertNull(compileScript("args-junit-hello-world.kts", StandardArgsScriptTemplateWithLocalResolving::class))
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
System.setErr(savedErr)
|
||||
}
|
||||
|
||||
@@ -127,23 +127,28 @@ done
|
||||
val (out, err) = captureOutAndErr {
|
||||
Assert.assertNull(compileScript("args-junit-dynver-error.kts", StandardArgsScriptTemplateWithMavenResolving::class))
|
||||
}
|
||||
Assert.assertTrue("Expecting error: unresolved reference: assertThrows, got:\nOUT:\n$out\nERR:\n$err", err.contains("error: unresolved reference: assertThrows"))
|
||||
Assert.assertTrue(
|
||||
"Expecting error: unresolved reference: assertThrows, got:\nOUT:\n$out\nERR:\n$err",
|
||||
err.contains("error: unresolved reference: assertThrows")
|
||||
)
|
||||
|
||||
val scriptClass = compileScript("args-junit-dynver.kts", StandardArgsScriptTemplateWithMavenResolving::class)
|
||||
Assert.assertNotNull(scriptClass)
|
||||
}
|
||||
|
||||
private fun compileScript(
|
||||
scriptFileName: String,
|
||||
scriptTemplate: KClass<out Any>,
|
||||
environment: Map<String, Any?>? = null,
|
||||
suppressOutput: Boolean = false
|
||||
scriptFileName: String,
|
||||
scriptTemplate: KClass<out Any>,
|
||||
environment: Map<String, Any?>? = null,
|
||||
suppressOutput: Boolean = false
|
||||
): Class<*>? =
|
||||
compileScriptImpl("libraries/tools/kotlin-script-util/src/test/resources/scripts/" + scriptFileName,
|
||||
KotlinScriptDefinitionFromAnnotatedTemplate(
|
||||
scriptTemplate,
|
||||
environment
|
||||
), suppressOutput)
|
||||
compileScriptImpl(
|
||||
"libraries/tools/kotlin-script-util/src/test/resources/scripts/$scriptFileName",
|
||||
KotlinScriptDefinitionFromAnnotatedTemplate(
|
||||
scriptTemplate,
|
||||
environment
|
||||
), suppressOutput
|
||||
)
|
||||
|
||||
private fun compileScriptImpl(
|
||||
scriptPath: String,
|
||||
@@ -157,9 +162,7 @@ done
|
||||
val rootDisposable = Disposer.newDisposable()
|
||||
try {
|
||||
val configuration = CompilerConfiguration().apply {
|
||||
scriptCompilationClasspathFromContextOrNull(KOTLIN_JAVA_RUNTIME_JAR)?.let {
|
||||
addJvmClasspathRoots(it)
|
||||
}
|
||||
addJvmClasspathRoots(scriptCompilationClasspathFromContext(KOTLIN_JAVA_RUNTIME_JAR))
|
||||
|
||||
put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector)
|
||||
addKotlinSourceRoot(scriptPath)
|
||||
@@ -185,7 +188,10 @@ done
|
||||
environment.getSourceFiles().forEach {
|
||||
messageCollector.report(CompilerMessageSeverity.LOGGING, "file: $it -> script def: ${it.findScriptDefinition()?.name}")
|
||||
}
|
||||
messageCollector.report(CompilerMessageSeverity.LOGGING, "compilation classpath:\n ${environment.configuration.jvmClasspathRoots.joinToString("\n ")}")
|
||||
messageCollector.report(
|
||||
CompilerMessageSeverity.LOGGING,
|
||||
"compilation classpath:\n ${environment.configuration.jvmClasspathRoots.joinToString("\n ")}"
|
||||
)
|
||||
|
||||
val scriptCompiler = ScriptJvmCompilerFromEnvironment(environment)
|
||||
|
||||
@@ -223,7 +229,7 @@ done
|
||||
}
|
||||
|
||||
private fun String.linesSplitTrim() =
|
||||
split('\n','\r').map(String::trim).filter(String::isNotBlank)
|
||||
split('\n', '\r').map(String::trim).filter(String::isNotBlank)
|
||||
|
||||
private fun captureOut(body: () -> Unit): String = captureOutAndErr(body).first
|
||||
|
||||
@@ -247,8 +253,8 @@ done
|
||||
}
|
||||
|
||||
private class NullOutputStream : OutputStream() {
|
||||
override fun write(b: Int) { }
|
||||
override fun write(b: ByteArray) { }
|
||||
override fun write(b: ByteArray, off: Int, len: Int) { }
|
||||
override fun write(b: Int) {}
|
||||
override fun write(b: ByteArray) {}
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -300,8 +300,7 @@ internal fun makeScriptContents(
|
||||
fun SourceCode.getVirtualFile(definition: ScriptDefinition): VirtualFile {
|
||||
if (this is VirtualFileScriptSource) return virtualFile
|
||||
if (this is KtFileScriptSource) {
|
||||
val vFile = virtualFile
|
||||
if (vFile != null) return vFile
|
||||
return virtualFile
|
||||
}
|
||||
if (this is FileScriptSource) {
|
||||
val vFile = LocalFileSystem.getInstance().findFileByIoFile(file)
|
||||
@@ -351,6 +350,7 @@ fun getScriptCollectedData(
|
||||
val acceptedAnnotations =
|
||||
compilationConfiguration[ScriptCompilationConfiguration.refineConfigurationOnAnnotations]?.flatMap {
|
||||
it.annotations.mapNotNull { ann ->
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
jvmGetScriptingClass(ann, contextClassLoader, hostConfiguration) as? KClass<Annotation> // TODO errors
|
||||
}
|
||||
}.orEmpty()
|
||||
|
||||
-4
@@ -31,7 +31,3 @@ fun configureScriptDefinitions(
|
||||
configuration.addAll(ScriptingConfigurationKeys.SCRIPT_DEFINITIONS, templatesFromClasspath.toList())
|
||||
}
|
||||
|
||||
fun makeHostConfiguration(project: Project, configuration: CompilerConfiguration): ScriptingHostConfiguration =
|
||||
ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
|
||||
// TODO: add jdk path and other params if needed
|
||||
}
|
||||
+5
-1
@@ -30,6 +30,8 @@ import org.jetbrains.kotlin.scripting.extensions.ScriptExtraImportsProviderExten
|
||||
import org.jetbrains.kotlin.scripting.extensions.ScriptingResolveExtension
|
||||
import org.jetbrains.kotlin.scripting.resolve.ScriptReportSink
|
||||
import java.net.URLClassLoader
|
||||
import kotlin.script.experimental.host.ScriptingHostConfiguration
|
||||
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
|
||||
|
||||
private fun <T : Any> ProjectExtensionDescriptor<T>.registerExtensionIfRequired(project: MockProject, extension: T) {
|
||||
try {
|
||||
@@ -42,7 +44,9 @@ private fun <T : Any> ProjectExtensionDescriptor<T>.registerExtensionIfRequired(
|
||||
class ScriptingCompilerConfigurationComponentRegistrar : ComponentRegistrar {
|
||||
override fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration) {
|
||||
val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
|
||||
val hostConfiguration = makeHostConfiguration(project, configuration)
|
||||
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
|
||||
// TODO: add jdk path and other params if needed
|
||||
}
|
||||
withClassloadingProblemsReporting(messageCollector) {
|
||||
CompilerConfigurationExtension.registerExtension(project, ScriptingCompilerConfigurationExtension(project, hostConfiguration))
|
||||
CollectAdditionalSourcesExtension.registerExtension(project,
|
||||
|
||||
+1
@@ -68,6 +68,7 @@ open class GenericReplCompiler(
|
||||
Pair(compilerState.lastLineState!!.psiFile, compilerState.lastLineState!!.errorHolder)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
val newDependencies =
|
||||
ScriptDependenciesProvider.getInstance(checker.environment.project)?.getScriptConfiguration(psiFile)
|
||||
?.legacyDependencies
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ class IdeDiagnosticMessageHolder : DiagnosticMessageHolder {
|
||||
reportEntry.setAttribute("severity", diagnostic.severity.toString())
|
||||
reportEntry.setAttribute("rangeStart", errorRange.startOffset.toString())
|
||||
reportEntry.setAttribute("rangeEnd", errorRange.endOffset.toString())
|
||||
reportEntry.appendChild(errorReport.createTextNode(StringUtil.escapeXml(message)))
|
||||
reportEntry.appendChild(errorReport.createTextNode(StringUtil.escapeXmlEntities(message)))
|
||||
|
||||
rootElement.appendChild(reportEntry)
|
||||
}
|
||||
|
||||
+19
-16
@@ -33,13 +33,15 @@ class ScriptProviderTest {
|
||||
val shadedDef = FakeScriptDefinition(".x.kts")
|
||||
val provider = TestCliScriptDefinitionProvider(standardDef).apply {
|
||||
setScriptDefinitions(listOf(shadedDef, standardDef))
|
||||
setScriptDefinitionsSources(listOf(
|
||||
TestScriptDefinitionSource(
|
||||
genDefCounter,
|
||||
".y.kts",
|
||||
".x.kts"
|
||||
setScriptDefinitionsSources(
|
||||
listOf(
|
||||
TestScriptDefinitionSource(
|
||||
genDefCounter,
|
||||
".y.kts",
|
||||
".x.kts"
|
||||
)
|
||||
)
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
Assert.assertEquals(0, genDefCounter.get())
|
||||
@@ -74,11 +76,10 @@ class ScriptProviderTest {
|
||||
}
|
||||
|
||||
private open class FakeScriptDefinition(val suffix: String = ".kts") :
|
||||
ScriptDefinition.FromLegacy(defaultJvmScriptingHostConfiguration, KotlinScriptDefinition(ScriptTemplateWithArgs::class))
|
||||
{
|
||||
ScriptDefinition.FromLegacy(defaultJvmScriptingHostConfiguration, KotlinScriptDefinition(ScriptTemplateWithArgs::class)) {
|
||||
val matchCounter = AtomicInteger()
|
||||
override fun isScript(script: SourceCode): Boolean {
|
||||
val path =script.locationId ?: return false
|
||||
val path = script.locationId ?: return false
|
||||
return path.endsWith(suffix).also {
|
||||
if (it) matchCounter.incrementAndGet()
|
||||
}
|
||||
@@ -89,13 +90,14 @@ private open class FakeScriptDefinition(val suffix: String = ".kts") :
|
||||
}
|
||||
|
||||
private class TestScriptDefinitionSource(val counter: AtomicInteger, val defGens: Iterable<() -> FakeScriptDefinition>) :
|
||||
ScriptDefinitionsSource
|
||||
{
|
||||
constructor(counter: AtomicInteger, vararg suffixes: String) : this(counter, suffixes.map { {
|
||||
FakeScriptDefinition(
|
||||
it
|
||||
)
|
||||
} })
|
||||
ScriptDefinitionsSource {
|
||||
constructor(counter: AtomicInteger, vararg suffixes: String) : this(counter, suffixes.map {
|
||||
{
|
||||
FakeScriptDefinition(
|
||||
it
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
override val definitions: Sequence<ScriptDefinition> = sequence {
|
||||
for (gen in defGens) {
|
||||
@@ -106,5 +108,6 @@ private class TestScriptDefinitionSource(val counter: AtomicInteger, val defGens
|
||||
}
|
||||
|
||||
private class TestCliScriptDefinitionProvider(private val standardDef: ScriptDefinition) : CliScriptDefinitionProvider() {
|
||||
@Suppress("DEPRECATION", "OverridingDeprecatedMember")
|
||||
override fun getDefaultScriptDefinition(): KotlinScriptDefinition = standardDef.legacyDefinition
|
||||
}
|
||||
-1
@@ -54,7 +54,6 @@ class ScriptingCompilerPluginTest : TestCase() {
|
||||
paths
|
||||
}
|
||||
|
||||
val compilerClasspath = listOf(kotlinPaths.compilerPath)
|
||||
val runtimeClasspath = listOf( kotlinPaths.stdlibPath, kotlinPaths.scriptRuntimePath, kotlinPaths.reflectPath)
|
||||
val scriptingClasspath = listOf("kotlin-scripting-common.jar").map { File(kotlinPaths.libPath, it) }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user