Implemented Blocks and Assignments
parent
72f48b75bb
commit
16e28c07b5
@ -0,0 +1,47 @@
|
|||||||
|
package fr.celticinfo.lox
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Environment class is used to store the variables and their values.
|
||||||
|
*/
|
||||||
|
class Environment {
|
||||||
|
private val enclosing: Environment?
|
||||||
|
private val values = mutableMapOf<String, Any?>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
enclosing = null
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(enclosing: Environment) {
|
||||||
|
this.enclosing = enclosing
|
||||||
|
}
|
||||||
|
|
||||||
|
fun define(name: String, value: Any?) {
|
||||||
|
values[name] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
fun get(name: Token): Any? {
|
||||||
|
if (values.containsKey(name.lexeme)) {
|
||||||
|
return values[name.lexeme]
|
||||||
|
}
|
||||||
|
|
||||||
|
if (enclosing != null) {
|
||||||
|
return enclosing.get(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
throw RuntimeError(name, "Undefined variable '${name.lexeme}'.")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun assign(name: Token, value: Any?) {
|
||||||
|
if (values.containsKey(name.lexeme)) {
|
||||||
|
values[name.lexeme] = value
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (enclosing != null) {
|
||||||
|
enclosing.assign(name, value)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
throw RuntimeError(name, "Undefined variable '${name.lexeme}'.")
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue