forked from airportyh/esprima_fun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
detect_leaks_lineno.js
62 lines (55 loc) · 1.44 KB
/
detect_leaks_lineno.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
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), {loc: true});
var scopeChain = [];
var assignments = [];
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);
}
if (node.type === 'AssignmentExpression'){
assignments.push(node);
}
}
function leave(node){
if (createsNewScope(node)){
checkForLeaks(assignments, scopeChain);
scopeChain.pop();
assignments = [];
}
}
function isVarDefined(varname, scopeChain){
for (var i = 0; i < scopeChain.length; i++){
var scope = scopeChain[i];
if (scope.indexOf(varname) !== -1){
return true;
}
}
return false;
}
function checkForLeaks(assignments, scopeChain){
for (var i = 0; i < assignments.length; i++){
var assignment = assignments[i];
var varname = assignment.left.name;
if (!isVarDefined(varname, scopeChain)){
console.log('Leaked global', varname,
'on line', assignment.loc.start.line);
}
}
}
function createsNewScope(node){
return node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'Program';
}