/
Environment.swift
49 lines (39 loc) · 1.19 KB
/
Environment.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// Environment.swift
// slox
//
// Created by Danielle Kefford on 2/27/24.
//
class Environment: Equatable {
private var enclosingEnvironment: Environment?
private var values: [String: LoxValue] = [:]
init(enclosingEnvironment: Environment? = nil) {
self.enclosingEnvironment = enclosingEnvironment
}
func define(name: String, value: LoxValue) {
values[name] = value
}
func assign(name: String, value: LoxValue) throws {
if values.keys.contains(name) {
values[name] = value
return
}
if let enclosingEnvironment = enclosingEnvironment {
try enclosingEnvironment.assign(name: name, value: value)
return
}
throw RuntimeError.undefinedVariable(name)
}
func getValue(name: String) throws -> LoxValue {
if let value = values[name] {
return value
}
if let enclosingEnvironment = enclosingEnvironment {
return try enclosingEnvironment.getValue(name: name)
}
throw RuntimeError.undefinedVariable(name)
}
static func == (lhs: Environment, rhs: Environment) -> Bool {
return lhs === rhs
}
}