This commit is contained in:
Horis
2024-07-31 17:42:19 +08:00
parent beb561a052
commit 7e6a1e4749
18 changed files with 117 additions and 40 deletions
+2 -1
View File
@@ -35,7 +35,8 @@ android {
}
dependencies {
api(fileTree(dir: 'lib', include: ['rhino-1.7.14.jar']))
// api(fileTree(dir: 'lib', include: ['rhino-1.7.14.jar']))
api libs.mozilla.rhino
implementation(libs.kotlinx.coroutines.core)
@@ -81,6 +81,11 @@ abstract class AbstractScriptEngine(val bindings: Bindings? = null) : ScriptEngi
return this.eval(script, getScriptContext(bindings))
}
@Throws(ScriptException::class)
override fun eval(script: String, bindings: ScriptBindings): Any? {
return this.eval(script, getRuntimeScope(bindings))
}
@Throws(ScriptException::class)
override fun eval(reader: Reader): Any? {
return this.eval(reader, context)
@@ -0,0 +1,42 @@
package com.script
import org.mozilla.javascript.Context
import org.mozilla.javascript.NativeObject
import org.mozilla.javascript.ScriptableObject
class ScriptBindings : NativeObject() {
companion object {
private val topLevelScope: ScriptableObject by lazy {
val cx = Context.enter()
try {
cx.initStandardObjects()
} finally {
Context.exit()
}
}
}
init {
prototype = topLevelScope
}
operator fun set(key: String, value: Any?) {
Context.enter()
try {
put(key, this, Context.javaToJS(value, this))
} finally {
Context.exit()
}
}
operator fun set(index: Int, value: Any?) {
Context.enter()
try {
put(index, this, Context.javaToJS(value, this))
} finally {
Context.exit()
}
}
}
@@ -45,9 +45,14 @@ interface ScriptEngine {
@Throws(ScriptException::class)
fun eval(script: String, bindings: Bindings): Any?
@Throws(ScriptException::class)
fun eval(script: String, bindings: ScriptBindings): Any?
@Throws(ScriptException::class)
fun eval(script: String, context: ScriptContext): Any?
fun getRuntimeScope(bindings: ScriptBindings): Scriptable
fun getRuntimeScope(context: ScriptContext): Scriptable
fun getScriptContext(bindings: Bindings): ScriptContext
@@ -53,8 +53,8 @@ object RhinoScriptEngine : AbstractScriptEngine(), Invocable, Compilable {
private val indexedProps: MutableMap<Any, Any?>
private val implementor: InterfaceImplementor
fun eval(js: String, bindingsConfig: SimpleBindings.() -> Unit = {}): Any? {
val bindings = SimpleBindings()
fun eval(js: String, bindingsConfig: ScriptBindings.() -> Unit = {}): Any? {
val bindings = ScriptBindings()
bindings.apply(bindingsConfig)
return eval(js, bindings)
}
@@ -249,6 +249,16 @@ object RhinoScriptEngine : AbstractScriptEngine(), Invocable, Compilable {
return newScope
}
override fun getRuntimeScope(bindings: ScriptBindings): ScriptBindings {
val cx = Context.enter()
try {
bindings.prototype = cx.initStandardObjects()
} finally {
Context.exit()
}
return bindings
}
@Throws(ScriptException::class)
override fun compile(script: String): CompiledScript {
return this.compile(StringReader(script) as Reader)