/
Environment.swift
60 lines (47 loc) · 1.52 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
50
51
52
53
54
55
56
57
58
59
60
//
// Environment.swift
// slox
//
// Created by Danielle Kefford on 2/27/24.
//
class Environment: Equatable {
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 assignAtDepth(name: String, value: LoxValue, depth: Int) throws {
let ancestor = try ancestor(depth: depth)
if ancestor.values.keys.contains(name) {
ancestor.values[name] = value
return
}
throw RuntimeError.undefinedVariable(name)
}
func getValueAtDepth(name: String, depth: Int) throws -> LoxValue {
let ancestor = try ancestor(depth: depth)
if let value = ancestor.values[name] {
return value
}
throw RuntimeError.undefinedVariable(name)
}
private func ancestor(depth: Int) throws -> Environment {
var i = 0
var ancestor: Environment = self
while i < depth {
guard let parent = ancestor.enclosingEnvironment else {
// NOTA BENE: This should not happen but it _is_ possible
throw RuntimeError.couldNotFindAncestorEnvironmentAtDepth(depth)
}
ancestor = parent
i = i + 1
}
return ancestor
}
static func == (lhs: Environment, rhs: Environment) -> Bool {
return lhs === rhs
}
}