fd82d55cebb58f52807e37f0b31af88ec64e228f
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview A rule to ensure the use of a single variable declaration.
3  * @author Ian Christian Myers
4  * @copyright 2015 Danny Fritz. All rights reserved.
5  * @copyright 2013 Ian Christian Myers. All rights reserved.
6  */
7
8 "use strict";
9
10 //------------------------------------------------------------------------------
11 // Rule Definition
12 //------------------------------------------------------------------------------
13
14 module.exports = function(context) {
15
16     var MODE = context.options[0] || "always";
17
18     //--------------------------------------------------------------------------
19     // Helpers
20     //--------------------------------------------------------------------------
21
22     var functionStack = [];
23
24     /**
25      * Increments the functionStack counter.
26      * @returns {void}
27      * @private
28      */
29     function startFunction() {
30         functionStack.push(false);
31     }
32
33     /**
34      * Decrements the functionStack counter.
35      * @returns {void}
36      * @private
37      */
38     function endFunction() {
39         functionStack.pop();
40     }
41
42     /**
43      * Determines if there is more than one var statement in the current scope.
44      * @returns {boolean} Returns true if it is the first var declaration, false if not.
45      * @private
46      */
47     function hasOnlyOneVar() {
48         if (functionStack[functionStack.length - 1]) {
49             return true;
50         } else {
51             functionStack[functionStack.length - 1] = true;
52             return false;
53         }
54     }
55
56     //--------------------------------------------------------------------------
57     // Public API
58     //--------------------------------------------------------------------------
59
60     return {
61         "Program": startFunction,
62         "FunctionDeclaration": startFunction,
63         "FunctionExpression": startFunction,
64         "ArrowFunctionExpression": startFunction,
65
66         "VariableDeclaration": function(node) {
67             var declarationCount = node.declarations.length;
68             if (MODE === "never") {
69                 if (declarationCount > 1) {
70                     context.report(node, "Split 'var' declaration into multiple statements.");
71                 }
72             } else {
73                 if (hasOnlyOneVar()) {
74                     context.report(node, "Combine this with the previous 'var' statement.");
75                 }
76             }
77         },
78
79         "Program:exit": endFunction,
80         "FunctionDeclaration:exit": endFunction,
81         "FunctionExpression:exit": endFunction,
82         "ArrowFunctionExpression:exit": endFunction
83     };
84
85 };