UNPKG

3.07 kBJavaScriptView Raw
1/**
2 * @fileoverview A rule to set the maximum depth block can be nested in a function.
3 * @author Ian Christian Myers
4 * @copyright 2013 Ian Christian Myers. All rights reserved.
5 */
6
7"use strict";
8
9//------------------------------------------------------------------------------
10// Rule Definition
11//------------------------------------------------------------------------------
12
13module.exports = function(context) {
14
15 //--------------------------------------------------------------------------
16 // Helpers
17 //--------------------------------------------------------------------------
18
19 var functionStack = [],
20 maxDepth = context.options[0] || 4;
21
22 /**
23 * When parsing a new function, store it in our function stack
24 * @returns {void}
25 * @private
26 */
27 function startFunction() {
28 functionStack.push(0);
29 }
30
31 /**
32 * When parsing is done then pop out the reference
33 * @returns {void}
34 * @private
35 */
36 function endFunction() {
37 functionStack.pop();
38 }
39
40 /**
41 * Save the block and Evaluate the node
42 * @param {ASTNode} node node to evaluate
43 * @returns {void}
44 * @private
45 */
46 function pushBlock(node) {
47 var len = ++functionStack[functionStack.length - 1];
48
49 if (len > maxDepth) {
50 context.report(node, "Blocks are nested too deeply ({{depth}}).",
51 { depth: len });
52 }
53 }
54
55 /**
56 * Pop the saved block
57 * @returns {void}
58 * @private
59 */
60 function popBlock() {
61 functionStack[functionStack.length - 1]--;
62 }
63
64 //--------------------------------------------------------------------------
65 // Public API
66 //--------------------------------------------------------------------------
67
68 return {
69 "Program": startFunction,
70 "FunctionDeclaration": startFunction,
71 "FunctionExpression": startFunction,
72 "ArrowFunctionExpression": startFunction,
73
74 "IfStatement": function(node) {
75 if (node.parent.type !== "IfStatement") {
76 pushBlock(node);
77 }
78 },
79 "SwitchStatement": pushBlock,
80 "TryStatement": pushBlock,
81 "DoWhileStatement": pushBlock,
82 "WhileStatement": pushBlock,
83 "WithStatement": pushBlock,
84 "ForStatement": pushBlock,
85 "ForInStatement": pushBlock,
86 "ForOfStatement": pushBlock,
87
88 "IfStatement:exit": popBlock,
89 "SwitchStatement:exit": popBlock,
90 "TryStatement:exit": popBlock,
91 "DoWhileStatement:exit": popBlock,
92 "WhileStatement:exit": popBlock,
93 "WithStatement:exit": popBlock,
94 "ForStatement:exit": popBlock,
95 "ForInStatement:exit": popBlock,
96 "ForOfStatement:exit": popBlock,
97
98 "FunctionDeclaration:exit": endFunction,
99 "FunctionExpression:exit": endFunction,
100 "ArrowFunctionExpression:exit": endFunction,
101 "Program:exit": endFunction
102 };
103
104};
105
106module.exports.schema = [
107 {
108 "type": "integer",
109 "minimum": 0
110 }
111];