-
Notifications
You must be signed in to change notification settings - Fork 1
/
SchemeEnvironment.js
executable file
·74 lines (69 loc) · 2.56 KB
/
SchemeEnvironment.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
64
65
66
67
68
69
70
71
72
73
var envId = 0;
/**
* Represents an environment, which is a set of variable names and binidngs. An environment
* also has a parent unless it is the global environment.
*
* @constructor
* @param {SchemeEnvironment} parent the parent environment. This environment will look up
* any unknown variables in its parent.
*/
function SchemeEnvironment(parent) {
var bindings = {};
this._id = envId++;
/**
* Returns the value corresponding to the given given variable name in this environment.
*
* @param {SchemeExpression} name the variable name to look up.
* @return {SchemeExpression} the expression bound to the given name in this environment.
* If the given name does not have a binding, false is returned.
*/
this.lookup = function (name) {
if (name in bindings) {
return bindings[name];
} else if (parent) {
return parent.lookup(name);
} else {
return false;
}
};
/**
* Binds the given value to the given name in this environment. If the variable name already
* has a binding in the parent environment, that binding will be overshadowed but not
* changed. The name will be coerced to a string but the value will not be changed. If an
* invalid value (not a SchemeExpression, for example) is passed in, that value will be
* returned by the appropriate lookup and may cause problems further down the line.
*
* @param {SchemeExpression} name the name to bind in this environment.
* @param {SchemeExpression} value the expression to bind to the given name.
*/
this.bind = function (name, value) {
bindings[name] = value;
};
/**
* Sets the binding with the given name to the given value. If the binding exists in the
* parent environment but not in this one, it will be set in the parent. If the variable
* does not exist, it will be created.
*
* @param {SchemeExpression} name the name of the variable to set.
* @param {SchemeExpression} value the value to set the variable to.
*/
this.set = function (name, value) {
if (name in bindings) {
bindings[name] = value;
} else if (parent) {
parent.set(name, value);
} else {
bindings[name] = value;
}
};
/**
* Returns a string containg all of the bindings in the environment.
*/
this.toString = function () {
if (this._id == 0) {
return "env#0";
} else {
return "env#" + this._id + " → " + parent;
}
};
}