-
Notifications
You must be signed in to change notification settings - Fork 5
/
detect_leaks.js
59 lines (52 loc) · 1.35 KB
/
detect_leaks.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
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 = [];
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.left.name);
}
}
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++){
if (!isVarDefined(assignments[i], scopeChain)){
console.log('Detected leaked global variable:', assignments[i]);
}
}
}
function createsNewScope(node){
return node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'Program';
}