evaluator: optimize the cost of defining a variable in a scope

This commit is contained in:
Alex Zenla 2023-09-05 03:13:43 -07:00
parent 63a90a599c
commit 290d8d0f0a
Signed by: alex
GPG Key ID: C0780728420EBFE5
2 changed files with 3 additions and 20 deletions

View File

@ -1,18 +0,0 @@
package gay.pizza.pork.evaluator
class FastVariableCache {
private val cache = mutableMapOf<String, Any>()
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
}

View File

@ -5,10 +5,11 @@ class Scope(val parent: Scope? = null, inherits: List<Scope> = emptyList()) {
private val variables = mutableMapOf<String, Any>()
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 {