From 290d8d0f0af985767f197b6cef1157409de1adab Mon Sep 17 00:00:00 2001 From: Alex Zenla Date: Tue, 5 Sep 2023 03:13:43 -0700 Subject: [PATCH] evaluator: optimize the cost of defining a variable in a scope --- .../pizza/pork/evaluator/FastVariableCache.kt | 18 ------------------ .../kotlin/gay/pizza/pork/evaluator/Scope.kt | 5 +++-- 2 files changed, 3 insertions(+), 20 deletions(-) delete mode 100644 evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FastVariableCache.kt diff --git a/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FastVariableCache.kt b/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FastVariableCache.kt deleted file mode 100644 index 96c7bbf..0000000 --- a/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/FastVariableCache.kt +++ /dev/null @@ -1,18 +0,0 @@ -package gay.pizza.pork.evaluator - -class FastVariableCache { - private val cache = mutableMapOf() - - fun put(key: String, value: Any) { - cache[key] = value - } - - fun lookup(key: String): Any = cache[key] ?: NotFound - fun has(key: String): Boolean = cache.containsKey(key) - - fun invalidate(key: String) { - cache.remove(key) - } - - object NotFound -} diff --git a/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/Scope.kt b/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/Scope.kt index 296bfff..25df9bd 100644 --- a/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/Scope.kt +++ b/evaluator/src/main/kotlin/gay/pizza/pork/evaluator/Scope.kt @@ -5,10 +5,11 @@ class Scope(val parent: Scope? = null, inherits: List = emptyList()) { private val variables = mutableMapOf() fun define(name: String, value: Any) { - if (variables.containsKey(name)) { + val previous = variables.put(name, value) + if (previous != null) { + variables[name] = previous throw RuntimeException("Variable '${name}' is already defined") } - variables[name] = value } fun value(name: String): Any {