-
Notifications
You must be signed in to change notification settings - Fork 5
/
scope_chain.js
52 lines (46 loc) · 1.23 KB
/
scope_chain.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
var fs = require('fs');
var esprima = require('esprima');
var estraverse = require('estraverse');
var filename = process.argv[2];
console.log('Processing', filename);
var ast = esprima.parse(fs.readFileSync(filename));
var scopeChain = [];
estraverse.traverse(ast, {
enter: enter,
leave: leave
});
function enter(node){
if (createsNewScope(node)){
scopeChain.push([]);
}
if (node.type === 'VariableDeclarator'){
var currentScope = scopeChain[scopeChain.length - 1];
currentScope.push(node.id.name);
}
}
function leave(node){
if (createsNewScope(node)){
var currentScope = scopeChain.pop();
printScope(currentScope, node);
}
}
function printScope(scope, node){
var varsDisplay = scope.join(', ');
if (node.type === 'Program'){
console.log('Variables declared in the global scope:',
varsDisplay);
}else{
if (node.id && node.id.name){
console.log('Variables declared in the function ' + node.id.name + '():',
varsDisplay);
}else{
console.log('Variables declared in anonymous function:',
varsDisplay);
}
}
}
function createsNewScope(node){
return node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'Program';
}