-
Notifications
You must be signed in to change notification settings - Fork 4
/
Scope.js
682 lines (606 loc) · 22.8 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define(function (require, exports, module) {
"use strict";
/*
* Performs a binary search among an array of scope objects for one with a
* range that contains pos. The array must be non-empty and sorted
* ascending according to the objects' (disjoint) ranges.
*
* @param {Array.<Object>} arr - the sorted array of scope objects to
* search
* @param {number} pos - the position to search for in arr
* @return {Object} - the scope object containing pos
*/
function binaryRangeSearch(arr, pos) {
var low = 0,
high = arr.length,
middle = Math.floor(high / 2);
// binary search for the position among the sorted ranges
while (low < middle && middle < high) {
if (arr[middle].range.end < pos) {
low = middle;
middle += Math.floor((high - middle) / 2);
} else if (arr[middle].range.start > pos) {
high = middle;
middle = low + Math.floor((middle - low) / 2);
} else {
break;
}
}
return arr[middle];
}
/**
* Build a scope object from AST tree as a child of the given parent.
*
* @constructor
* @param {AST} tree - an AST as described at
https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
* @param {?Scope=} parent - the (optional) parent of the new Scope
*/
function Scope(tree, parent) {
/*
* Given a member expression, try to add a target-property association
* to the given scope.
*
* @param {AST} object - the lookup object
* @param {AST} property - the property being looked up
* @param {Scope} parent - the Scope object in which the association
* occurs.
*/
function _buildAssociations(object, property, parent) {
if (property.type === "Identifier") {
if (object.type === "Identifier") {
parent.addAssociation(object, property);
} else if (object.type === "MemberExpression") {
if (object.computed === false) {
_buildAssociations(object.property, property, parent);
}
} else if (object.type === "CallExpression") {
_buildAssociations(object.callee, property, parent);
} else if (object.type === "ThisExpression") {
object.name = "this";
parent.addAssociation(object, property);
} else {
// most likely a literal
return;
}
} else {
// Because we restrict to non-computed property lookups, this
// should be unreachable
throw "Expected identifier but found " + property.type;
}
}
/*
* Walk a given AST and add scope information to a given parent scope,
* including new child Scope objects.
*
* @param {AST} tree - the AST from which the Scope is constructed
* @param {Scope} parent - the parent of the Scope to be constructed
*/
function _buildScope(tree, parent) {
var child;
if (tree === undefined || tree === null) {
return;
}
switch (tree.type) {
case "Program":
case "BlockStatement":
tree.body.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "FunctionDeclaration":
parent.addDeclaration(tree.id);
_buildScope(tree.id, parent);
child = new Scope(tree, parent);
child.addAllDeclarations(tree.params);
tree.params.forEach(function (t) {
_buildScope(t, child);
});
parent.addChildScope(child);
_buildScope(tree.body, child);
break;
case "VariableDeclaration":
// FIXME handle let scoping
tree.declarations.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "VariableDeclarator":
parent.addDeclaration(tree.id);
_buildScope(tree.id, parent);
if (tree.init !== null) {
_buildScope(tree.init, parent);
}
break;
case "ExpressionStatement":
_buildScope(tree.expression, parent);
break;
case "SwitchStatement":
_buildScope(tree.discriminant, parent);
if (tree.cases) {
tree.cases.forEach(function (t) {
_buildScope(t, parent);
});
}
break;
case "SwitchCase":
tree.consequent.forEach(function (t) {
_buildScope(t, parent);
});
if (tree.test) {
_buildScope(tree.test, parent);
}
break;
case "TryStatement":
tree.handlers.forEach(function (t) {
_buildScope(t, parent);
});
_buildScope(tree.block, parent);
if (tree.finalizer) {
_buildScope(tree.finalizer, parent);
}
break;
case "ThrowStatement":
_buildScope(tree.argument, parent);
break;
case "WithStatement":
_buildScope(tree.object, parent);
_buildScope(tree.body, parent);
break;
case "CatchClause":
if (tree.guard) {
_buildScope(tree.guard, parent);
}
// FIXME: Is this the correct way to handle catch?
child = new Scope(tree, parent);
child.addDeclaration(tree.param);
_buildScope(tree.param, child);
parent.addChildScope(child);
_buildScope(tree.body, child);
break;
case "ReturnStatement":
if (tree.argument) {
_buildScope(tree.argument, parent);
}
break;
case "ForStatement":
_buildScope(tree.body, parent);
if (tree.init) {
_buildScope(tree.init, parent);
}
if (tree.test) {
_buildScope(tree.test, parent);
}
if (tree.update) {
_buildScope(tree.update, parent);
}
break;
case "ForInStatement":
_buildScope(tree.left, parent);
_buildScope(tree.right, parent);
_buildScope(tree.body, parent);
break;
case "LabeledStatement":
_buildScope(tree.body, parent);
break;
case "BreakStatement":
case "ContinueStatement":
if (tree.label) {
_buildScope(tree.label, parent);
}
break;
case "UpdateExpression":
case "UnaryExpression":
_buildScope(tree.argument, parent);
break;
case "IfStatement":
case "ConditionalExpression":
_buildScope(tree.test, parent);
_buildScope(tree.consequent, parent);
if (tree.alternate) {
_buildScope(tree.alternate, parent);
}
break;
case "WhileStatement":
case "DoWhileStatement":
_buildScope(tree.test, parent);
_buildScope(tree.body, parent);
break;
case "SequenceExpression":
tree.expressions.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "ObjectExpression":
tree.properties.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "ArrayExpression":
tree.elements.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "NewExpression":
if (tree["arguments"]) { // pacifies JSLint
tree["arguments"].forEach(function (t) {
_buildScope(t, parent);
});
}
_buildScope(tree.callee, parent);
break;
case "BinaryExpression":
case "AssignmentExpression":
case "LogicalExpression":
_buildScope(tree.left, parent);
_buildScope(tree.right, parent);
break;
case "MemberExpression":
_buildScope(tree.object, parent);
_buildScope(tree.property, parent);
if (tree.property && tree.property.type === "Identifier") {
parent.addProperty(tree.property);
}
if (tree.computed === false) {
_buildAssociations(tree.object, tree.property, parent);
}
break;
case "CallExpression":
tree["arguments"].forEach(function (t) {
_buildScope(t, parent);
});
_buildScope(tree.callee, parent);
break;
case "FunctionExpression":
if (tree.id) {
parent.addDeclaration(tree.id);
_buildScope(tree.id, parent);
}
child = new Scope(tree, parent);
parent.addChildScope(child);
child.addAllDeclarations(tree.params);
tree.params.forEach(function (t) {
_buildScope(t, child);
});
_buildScope(tree.body, child);
break;
case "Property":
// Undocumented or Esprima-specific?
parent.addProperty(tree.key);
_buildScope(tree.value, parent);
break;
case "Identifier":
parent.addIdOccurrence(tree);
break;
case "Literal":
if (tree.value && typeof tree.value === "string") {
parent.addLiteralOccurrence(tree);
}
break;
case "DebuggerStatement":
case "EmptyStatement":
case "ThisExpression":
break;
default:
throw "Unknown node type: " + tree.type;
}
}
if (parent === undefined) {
this.parent = null;
} else {
this.parent = parent;
}
this.idDeclarations = {};
this.idOccurrences = [];
this.propOccurrences = [];
this.associations = [];
this.literals = [];
this.children = []; // disjoint ranges, ordered by range start
this.range = {
start: tree.range[0],
end: tree.range[1]
};
// if parent is null, walk the AST
if (!this.parent) {
_buildScope(tree, this);
}
}
/*
* Rebuild a Scope object from an object that has all the necessary data
* but the wrong prototype. Such objects may be created as a result of
* e.g., JSON-marshalling and unmarshalling a scope.
*
* @param {Object} data - an object that contains all data of a Scope object
* but none of the methods
* @return {Scope} - the same object with Scope methods added
*/
Scope.rebuild = function (data) {
var memberName,
member;
for (memberName in Scope.prototype) {
if (Scope.prototype.hasOwnProperty(memberName)) {
member = Scope.prototype[memberName];
if (typeof member === "function") {
data[memberName] = member;
}
}
}
data.children.forEach(function (child) {
Scope.rebuild(child);
});
return data;
};
/*
* Add an identifier occurrence.
*
* @param {AST} id - an identifier AST node
*/
Scope.prototype.addIdOccurrence = function (id) {
this.idOccurrences.push(id);
};
/*
* Add an identifier declaration
*
* @param {AST} id - an identifier AST node
*/
Scope.prototype.addDeclaration = function (id) {
this.idDeclarations[id.name] = id;
this.addIdOccurrence(id);
};
/*
* Add a list of identifier declarations
*
* @param {Array.<AST>} ids - a list of identifier AST nodes
*/
Scope.prototype.addAllDeclarations = function (ids) {
var that = this;
ids.forEach(function (i) {
that.addDeclaration(i);
});
};
/*
* Add a property occurrence
*
* @param {AST} prop - a property AST node
*/
Scope.prototype.addProperty = function (prop) {
this.propOccurrences.push(prop);
};
/*
* Add an association object
*
* @param {AST} obj - an identifier AST node
* @param {AST} prop - a property AST node
*/
Scope.prototype.addAssociation = function (obj, prop) {
this.associations.push({object: obj, property: prop});
};
/*
* Add a literal occurrence
*
* @param {AST} lit - a literal AST node
*/
Scope.prototype.addLiteralOccurrence = function (lit) {
this.literals.push(lit);
};
/*
* Attach a new child scope to the current scope. Inserts the child scope
* in range-sorted order w.r.t. the other children of the current scope.
*
* @param {Scope} child - the child to be added
*/
Scope.prototype.addChildScope = function (child) {
var i = 0;
while (i < this.children.length &&
child.range.start > this.children[i].range.end) {
i++;
}
this.children.splice(i, 0, child);
};
/*
* Is the symbol declared in this scope?
*
* @param {string} sym - a symbol name
* @return {boolean} - whether a symbol with that name is declared in this
* immediate scope
*/
Scope.prototype.member = function (sym) {
return Object.prototype.hasOwnProperty.call(this.idDeclarations, sym);
};
/*
* Is the symbol declared in this scope or a parent scope?
*
* @param {string} sym - a symbol name
* @return {boolean} - whether a symbol with that name is declared in this
* immediate scope or a parent scope
*/
Scope.prototype.contains = function (sym) {
var depth = 0,
child = this;
do {
if (child.member(sym)) {
return depth;
} else {
child = child.parent;
depth++;
}
} while (child !== null);
return undefined;
};
/*
* Does this scope, or its children, contain the given position?
*
* @param {number} pos - the position to test for inclusion in the scope
* @return {boolean} - is the position included in the scope?
*/
Scope.prototype.containsPosition = function (pos) {
return this.range.start <= pos && pos <= this.range.end;
};
/*
* Does this scope, but not its children, contain the given position?
*
* @param {number} pos - the position to test for inclusion in the scope
* @return {boolean} - is the position directly included in the scope?
*/
Scope.prototype.containsPositionImmediate = function (pos) {
if (this.containsPosition(pos)) {
if (this.children.length === 0) {
// contains the position and there are no children
return true;
} else {
var child = binaryRangeSearch(this.children, pos);
// contains the position if the nearest child does not
return !child.containsPosition(pos);
}
} else {
// does not contain the position
return false;
}
};
/*
* Find the child scope of the current scope for a given position
*
* @param {number} pos - the position at which to find a child scope
* @return {?Scope} - the child scope for the given position, or null
* if none exists
*/
Scope.prototype.findChild = function (pos) {
if (this.containsPosition(pos)) {
if (this.children.length === 0) {
// there are no children, so this is the most precise scope
return this;
} else {
var child = binaryRangeSearch(this.children, pos);
// the most precise scope is the most precise scope of the child,
// unless no child contains the position, in which case this is
// the most precise scope
return child.findChild(pos) || this;
}
} else {
return null;
}
};
/**
* Traverse the scope down via children in pre-order.
*
* @param {Function} add - the Scope accumulation function
* @param {Object} init - an initial value for the accumulation function
* @return {Object} - the result of accumulating the current scope along
* with all of its children
*/
Scope.prototype.walkDown = function (add, init) {
var result = add(this, init);
this.children.forEach(function (child) {
result = child.walkDown(add, result);
});
return result;
};
/*
* Traverse a particular list in the scope down via children
*
* @param {Function} addItem - the item accumulation function
* @param {Object} init - an initial value for the accumulation function
* @param {string} listName - the name of a Scope property
* @return {Object} - the result of accumulating the given property for
* the current scope along with all of its children
*/
Scope.prototype.walkDownList = function (addItem, init, listName) {
function addList(scope, init) {
var list = scope[listName];
return list.reduce(function (prev, curr) {
return addItem(prev, curr);
}, init);
}
return this.walkDown(addList, init);
};
/*
* Traverse identifier occurrences in the scope down via children
*
* @param {Function} add - the identifier accumulation function
* @param {Object} init - an initial value for the accumulation function
* @return {Object} - the result of accumulating identifier occurrences
* for the current scope along with all of its children
*/
Scope.prototype.walkDownIdentifiers = function (add, init) {
return this.walkDownList(add, init, "idOccurrences");
};
/*
* Traverse property occurrences in the scope down via children
*
* @param {Function} add - the property accumulation function
* @param {Object} init - an initial value for the accumulation function
* @return {Object} - the result of of accumulating property occurrences
* for the current scope along with all of its children
*/
Scope.prototype.walkDownProperties = function (add, init) {
return this.walkDownList(add, init, "propOccurrences");
};
/*
* Traverse associations in the scope down via children
*
* @param {Function} add - the association accumulation function
* @param {Object} init - an initial value for the accumulation function
* @return {Object} - the result of of accumulating association occurrences
* for the current scope along with all of its children
*/
Scope.prototype.walkDownAssociations = function (add, init) {
return this.walkDownList(add, init, "associations");
};
/*
* Traverse literals in the scope down via children
*
* @param {Function} add - the literal accumulation function
* @param {Object} init - an initial value for the accumulation function
* @return {Object} - the result of of accumulating literal occurrences
* for the current scope along with all of its children
*/
Scope.prototype.walkDownLiterals = function (add, init) {
return this.walkDownList(add, init, "literals");
};
/**
* Traverse the scope up via the parent
*
* @param {Function} add - the Scope accumulation function
* @param {Object} init - an initial value for the accumulation function
* @param {string} prop - the property name to combine scope information for
* @return {Object} - the result of of accumulating the current scope along
* with its parents
*/
Scope.prototype.walkUp = function (add, init, prop) {
var scope = this,
result = init,
combine = function (elem) {
result = add(result, elem);
};
while (scope !== null) {
this[prop].forEach(combine);
scope = scope.parent;
}
return result;
};
module.exports = Scope;
});