From 3a43b56fcdf71891d34582124fb02cbc83ecccfc Mon Sep 17 00:00:00 2001 From: Alex Zenla Date: Sat, 9 Sep 2023 01:51:04 -0400 Subject: [PATCH] evaluator: cache native function resolution --- .../pizza/pork/evaluator/FunctionContext.kt | 23 ++++++++++++------- examples/java-speed.pork | 10 ++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) create mode 100644 examples/java-speed.pork diff --git a/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FunctionContext.kt b/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FunctionContext.kt index 9584c1c..ba05df3 100644 --- a/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FunctionContext.kt +++ b/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FunctionContext.kt @@ -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") } diff --git a/examples/java-speed.pork b/examples/java-speed.pork new file mode 100644 index 0000000..196283c --- /dev/null +++ b/examples/java-speed.pork @@ -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) + } +}