39f81b8271562d09fdd8d06990cc26ef4e989003
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Rule to flag on declaring variables already declared in the outer scope
3  * @author Ilya Volodin
4  * @copyright 2013 Ilya Volodin. All rights reserved.
5  */
6
7 "use strict";
8
9 //------------------------------------------------------------------------------
10 // Rule Definition
11 //------------------------------------------------------------------------------
12
13 module.exports = function(context) {
14
15     /**
16      * Checks if a variable is contained in the list of given scope variables.
17      * @param {Object} variable The variable to check.
18      * @param {Array} scopeVars The scope variables to look for.
19      * @returns {boolean} Whether or not the variable is contains in the list of scope variables.
20      */
21     function isContainedInScopeVars(variable, scopeVars) {
22         return scopeVars.some(function (scopeVar) {
23             if (scopeVar.identifiers.length > 0) {
24                 return variable.name === scopeVar.name;
25             }
26             return false;
27         });
28     }
29
30     /**
31      * Checks if the given variables are shadowed in the given scope.
32      * @param {Array} variables The variables to look for
33      * @param {Object} scope The scope to be checked.
34      * @returns {void}
35      */
36     function checkShadowsInScope(variables, scope) {
37         variables.forEach(function (variable) {
38             if (isContainedInScopeVars(variable, scope.variables) &&
39                     // "arguments" is a special case that has no identifiers (#1759)
40                     variable.identifiers.length > 0
41             ) {
42
43                 context.report(variable.identifiers[0], "{{a}} is already declared in the upper scope.", {a: variable.name});
44             }
45         });
46     }
47
48     /**
49      * Checks the current context for shadowed variables.
50      * @returns {void}
51      */
52     function checkForShadows() {
53         var scope = context.getScope(),
54             variables = scope.variables;
55
56         // iterate through the array of variables and find duplicates with the upper scope
57         var upper = scope.upper;
58         while (upper) {
59             checkShadowsInScope(variables, upper);
60             upper = upper.upper;
61         }
62     }
63
64     return {
65         "FunctionDeclaration": checkForShadows,
66         "FunctionExpression": checkForShadows
67     };
68
69 };