-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEnvironment.js
63 lines (50 loc) · 1.4 KB
/
Environment.js
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
61
62
63
const RuntimeError = require('./RuntimeError');
class Environment {
constructor(enclosing) {
this.values = new Map();
this.enclosing = enclosing;
this.define = this.define.bind(this);
this.get = this.get.bind(this);
this.assign = this.assign.bind(this);
this.getAt = this.getAt.bind(this);
this.ancestor = this.ancestor.bind(this);
this.assignAt = this.assignAt.bind(this);
}
define(name, value) {
this.values.set(name, value);
}
ancestor(distance) {
let environment = this;
for (let i = 0; i < distance; i += 1) {
environment = environment.enclosing;
}
return environment;
}
getAt(distance, name) {
return this.ancestor(distance).values.get(name);
}
assignAt(distance, name, value) {
this.ancestor(distance).values.set(name.lexeme, value);
}
get(name) {
if (this.values.has(name.lexeme)) {
return this.values.get(name.lexeme);
}
if (this.enclosing !== null) return this.enclosing.get(name);
throw new RuntimeError(name,
`Undefined variable '${name.lexeme}'.`);
}
assign(name, value) {
if (this.values.has(name.lexeme)) {
this.values.set(name.lexeme, value);
return;
}
if (this.enclosing !== null) {
this.enclosing.assign(name, value);
return;
}
throw new RuntimeError(name,
`Undefined variable '${name.lexeme}'.`);
}
}
module.exports = Environment;