UNPKG

2.07 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag use of variables before they are defined
3 * @author Ilya Volodin
4 */
5
6//------------------------------------------------------------------------------
7// Rule Definition
8//------------------------------------------------------------------------------
9
10module.exports = function(context) {
11
12 "use strict";
13
14 function findDeclaration(name, scope) {
15 //try searching in the current scope first
16 for (var i = 0, l = scope.variables.length; i < l; i++) {
17 if (scope.variables[i].name === name) {
18 return scope.variables[i];
19 }
20 }
21 //check if there's upper scope and call recursivly till we find the variable
22 if (scope.upper) {
23 return findDeclaration(name, scope.upper);
24 }
25 }
26
27 function findVariables() {
28 var scope = context.getScope();
29
30 function checkLocationAndReport(reference, declaration) {
31 if (declaration.identifiers[0].range[1] > reference.identifier.range[1]) {
32 context.report(reference.identifier, "{{a}} was used before it was defined", {a: reference.identifier.name});
33 }
34 }
35
36 scope.references.forEach(function(reference) {
37 //if the reference is resolved check for declaration location
38 //if not, it could be function invocation, try to find manually
39 if (reference.resolved && reference.resolved.identifiers.length > 0) {
40 checkLocationAndReport(reference, reference.resolved);
41 } else {
42 var declaration = findDeclaration(reference.identifier.name, scope);
43 //if there're no identifiers, this is a global environment variable
44 if (declaration && declaration.identifiers.length !== 0) {
45 checkLocationAndReport(reference, declaration);
46 }
47 }
48 });
49 }
50
51 return {
52 "Program": findVariables,
53 "FunctionExpression": findVariables,
54 "FunctionDeclaration": findVariables
55 };
56};