-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvironment.js
More file actions
53 lines (41 loc) · 1.09 KB
/
Copy pathenvironment.js
File metadata and controls
53 lines (41 loc) · 1.09 KB
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
import {RuntimeError} from './runtime-error.js';
export default class Environment {
constructor(enclosing = undefined) {
this.values = new Map();
this.enclosing = enclosing;
}
define(key, value) {
this.values.set(key.lexeme, value); //ugh, idk where we get lexeme lol
}
get(name) {
if (this.values.has(name.lexeme)) {
return this.values.get(name.lexeme);
}
if (this.enclosing) 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) {
this.enclosing.assign(name, value);
return;
}
throw new RuntimeError(name, `Undefined variable '${name.lexeme}'`);
}
getAt(distance, name) {
this.ancestor(distance).get(name.lexeme);
}
ancestor(distance) {
let environment = this;
for (let i = 0; i < distance; i++) {
environment = environment.enclosing;
}
return environment;
}
assignAt(distance, name, value) {
this.ancestor(distance).values.put(name.lexeme, value);
}
}