/
Scope.js
94 lines (77 loc) · 1.89 KB
/
Scope.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
define([ 'dojo/_base/lang', './env', './Variable' ], function (lang, env, Variable) {
/**
* A variable scope.
*/
function Scope(parent) {
if (!(this instanceof Scope)) {
return new Scope(parent);
}
if (!parent) {
parent = env.scope;
}
this.parent = parent;
this.children = [];
this.vars = {};
return this; // strict mode
}
Scope.prototype = {
constructor: Scope,
/**
* If a scope has no parent, it is the global scope.
* @type Scope?
*/
parent: undefined,
/**
* Child scopes.
* @type Array.<Scope>
*/
children: [],
/**
* @type Array.<ScopeVariable>
*/
vars: {},
/**
* Creates a new variable in the local scope. Called from var x, ….
*/
addVariable: function (/**string*/ name) {
if (this.vars[name]) {
console.warn('Variable ' + name + ' already defined in current scope');
return this.vars[name];
}
console.info('Adding variable ' + name + ' to scope');
return this.vars[name] = new Variable();
},
/**
* Sets the property of a variable in the nearest declared scope.
* @param name An array of accessors, or a dot-separated accessor string like a.b.c.
*/
setVariableValue: function (/**Array|string*/ name, /**Value?*/ value) {
if (!lang.isArray(name)) {
name = name.split('.');
}
var scope = this, variable;
// find variable in nearest scope
do {
if ((variable = scope.vars[name[0]])) {
break;
}
} while ((scope = this.parent));
if (!variable) {
console.warn(name.join('.') + ': Implicit global variable declaration');
variable = env.globalScope.addVariable(name[0]);
}
if (name.length === 1) {
if (variable.value) {
console.info(name.join('.') + ': Changing value reference');
}
variable.value = value;
}
else {
variable.setProperty(name.slice(1), value);
}
},
resolveVariables: function () {
}
};
return Scope;
});