evaluator: cache native function resolution

This commit is contained in:
Alex Zenla 2023-09-09 01:51:04 -04:00
parent e8766323ee
commit 3a43b56fcd
Signed by: alex
GPG Key ID: C0780728420EBFE5
2 changed files with 25 additions and 8 deletions

View File

@ -3,20 +3,27 @@ package gay.pizza.pork.evaluator
import gay.pizza.pork.ast.FunctionDefinition
class FunctionContext(val compilationUnitContext: CompilationUnitContext, val node: FunctionDefinition) : CallableFunction {
private fun resolveMaybeNative(): CallableFunction? = if (node.native == null) {
null
} else {
val native = node.native!!
val nativeFunctionProvider =
compilationUnitContext.evaluator.nativeFunctionProvider(native.form.id)
nativeFunctionProvider.provideNativeFunction(native.definition.text)
}
private val nativeCached by lazy { resolveMaybeNative() }
override fun call(arguments: Arguments): Any {
if (nativeCached != null) {
return nativeCached!!.call(arguments)
}
val scope = compilationUnitContext.internalScope.fork()
for ((index, argumentSymbol) in node.arguments.withIndex()) {
scope.define(argumentSymbol.id, arguments.values[index])
}
if (node.native != null) {
val native = node.native!!
val nativeFunctionProvider =
compilationUnitContext.evaluator.nativeFunctionProvider(native.form.id)
val nativeFunction = nativeFunctionProvider.provideNativeFunction(native.definition.text)
return nativeFunction.call(arguments)
}
if (node.block == null) {
throw RuntimeException("Native or Block is required for FunctionDefinition")
}

10
examples/java-speed.pork Normal file
View File

@ -0,0 +1,10 @@
import java java.lang.Math
import java java.lang.System
import java java.io.PrintStream
export func main() {
while true {
let pi = java_lang_Math_PI_get()
println(pi)
}
}