summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/one-var.js
blob: 9e40d4ea6f26c1d717157d576346c7dec68fa6f3 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/**
 * @fileoverview A rule to control the use of single variable declarations.
 * @author Ian Christian Myers
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "enforce variables to be declared either together or separately in functions",
            category: "Stylistic Issues",
            recommended: false
        },

        schema: [
            {
                oneOf: [
                    {
                        enum: ["always", "never"]
                    },
                    {
                        type: "object",
                        properties: {
                            var: {
                                enum: ["always", "never"]
                            },
                            let: {
                                enum: ["always", "never"]
                            },
                            const: {
                                enum: ["always", "never"]
                            }
                        },
                        additionalProperties: false
                    },
                    {
                        type: "object",
                        properties: {
                            initialized: {
                                enum: ["always", "never"]
                            },
                            uninitialized: {
                                enum: ["always", "never"]
                            }
                        },
                        additionalProperties: false
                    }
                ]
            }
        ]
    },

    create(context) {

        const MODE_ALWAYS = "always",
            MODE_NEVER = "never";

        const mode = context.options[0] || MODE_ALWAYS;

        const options = {
        };

        if (typeof mode === "string") { // simple options configuration with just a string
            options.var = { uninitialized: mode, initialized: mode };
            options.let = { uninitialized: mode, initialized: mode };
            options.const = { uninitialized: mode, initialized: mode };
        } else if (typeof mode === "object") { // options configuration is an object
            if (mode.hasOwnProperty("var") && typeof mode.var === "string") {
                options.var = { uninitialized: mode.var, initialized: mode.var };
            }
            if (mode.hasOwnProperty("let") && typeof mode.let === "string") {
                options.let = { uninitialized: mode.let, initialized: mode.let };
            }
            if (mode.hasOwnProperty("const") && typeof mode.const === "string") {
                options.const = { uninitialized: mode.const, initialized: mode.const };
            }
            if (mode.hasOwnProperty("uninitialized")) {
                if (!options.var) {
                    options.var = {};
                }
                if (!options.let) {
                    options.let = {};
                }
                if (!options.const) {
                    options.const = {};
                }
                options.var.uninitialized = mode.uninitialized;
                options.let.uninitialized = mode.uninitialized;
                options.const.uninitialized = mode.uninitialized;
            }
            if (mode.hasOwnProperty("initialized")) {
                if (!options.var) {
                    options.var = {};
                }
                if (!options.let) {
                    options.let = {};
                }
                if (!options.const) {
                    options.const = {};
                }
                options.var.initialized = mode.initialized;
                options.let.initialized = mode.initialized;
                options.const.initialized = mode.initialized;
            }
        }

        //--------------------------------------------------------------------------
        // Helpers
        //--------------------------------------------------------------------------

        const functionStack = [];
        const blockStack = [];

        /**
         * Increments the blockStack counter.
         * @returns {void}
         * @private
         */
        function startBlock() {
            blockStack.push({
                let: { initialized: false, uninitialized: false },
                const: { initialized: false, uninitialized: false }
            });
        }

        /**
         * Increments the functionStack counter.
         * @returns {void}
         * @private
         */
        function startFunction() {
            functionStack.push({ initialized: false, uninitialized: false });
            startBlock();
        }

        /**
         * Decrements the blockStack counter.
         * @returns {void}
         * @private
         */
        function endBlock() {
            blockStack.pop();
        }

        /**
         * Decrements the functionStack counter.
         * @returns {void}
         * @private
         */
        function endFunction() {
            functionStack.pop();
            endBlock();
        }

        /**
         * Records whether initialized or uninitialized variables are defined in current scope.
         * @param {string} statementType node.kind, one of: "var", "let", or "const"
         * @param {ASTNode[]} declarations List of declarations
         * @param {Object} currentScope The scope being investigated
         * @returns {void}
         * @private
         */
        function recordTypes(statementType, declarations, currentScope) {
            for (let i = 0; i < declarations.length; i++) {
                if (declarations[i].init === null) {
                    if (options[statementType] && options[statementType].uninitialized === MODE_ALWAYS) {
                        currentScope.uninitialized = true;
                    }
                } else {
                    if (options[statementType] && options[statementType].initialized === MODE_ALWAYS) {
                        currentScope.initialized = true;
                    }
                }
            }
        }

        /**
         * Determines the current scope (function or block)
         * @param  {string} statementType node.kind, one of: "var", "let", or "const"
         * @returns {Object} The scope associated with statementType
         */
        function getCurrentScope(statementType) {
            let currentScope;

            if (statementType === "var") {
                currentScope = functionStack[functionStack.length - 1];
            } else if (statementType === "let") {
                currentScope = blockStack[blockStack.length - 1].let;
            } else if (statementType === "const") {
                currentScope = blockStack[blockStack.length - 1].const;
            }
            return currentScope;
        }

        /**
         * Counts the number of initialized and uninitialized declarations in a list of declarations
         * @param {ASTNode[]} declarations List of declarations
         * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations
         * @private
         */
        function countDeclarations(declarations) {
            const counts = { uninitialized: 0, initialized: 0 };

            for (let i = 0; i < declarations.length; i++) {
                if (declarations[i].init === null) {
                    counts.uninitialized++;
                } else {
                    counts.initialized++;
                }
            }
            return counts;
        }

        /**
         * Determines if there is more than one var statement in the current scope.
         * @param {string} statementType node.kind, one of: "var", "let", or "const"
         * @param {ASTNode[]} declarations List of declarations
         * @returns {boolean} Returns true if it is the first var declaration, false if not.
         * @private
         */
        function hasOnlyOneStatement(statementType, declarations) {

            const declarationCounts = countDeclarations(declarations);
            const currentOptions = options[statementType] || {};
            const currentScope = getCurrentScope(statementType);

            if (currentOptions.uninitialized === MODE_ALWAYS && currentOptions.initialized === MODE_ALWAYS) {
                if (currentScope.uninitialized || currentScope.initialized) {
                    return false;
                }
            }

            if (declarationCounts.uninitialized > 0) {
                if (currentOptions.uninitialized === MODE_ALWAYS && currentScope.uninitialized) {
                    return false;
                }
            }
            if (declarationCounts.initialized > 0) {
                if (currentOptions.initialized === MODE_ALWAYS && currentScope.initialized) {
                    return false;
                }
            }
            recordTypes(statementType, declarations, currentScope);
            return true;
        }


        //--------------------------------------------------------------------------
        // Public API
        //--------------------------------------------------------------------------

        return {
            Program: startFunction,
            FunctionDeclaration: startFunction,
            FunctionExpression: startFunction,
            ArrowFunctionExpression: startFunction,
            BlockStatement: startBlock,
            ForStatement: startBlock,
            ForInStatement: startBlock,
            ForOfStatement: startBlock,
            SwitchStatement: startBlock,

            VariableDeclaration(node) {
                const parent = node.parent;
                const type = node.kind;

                if (!options[type]) {
                    return;
                }

                const declarations = node.declarations;
                const declarationCounts = countDeclarations(declarations);

                // always
                if (!hasOnlyOneStatement(type, declarations)) {
                    if (options[type].initialized === MODE_ALWAYS && options[type].uninitialized === MODE_ALWAYS) {
                        context.report({
                            node,
                            message: "Combine this with the previous '{{type}}' statement.",
                            data: {
                                type
                            }
                        });
                    } else {
                        if (options[type].initialized === MODE_ALWAYS) {
                            context.report({
                                node,
                                message: "Combine this with the previous '{{type}}' statement with initialized variables.",
                                data: {
                                    type
                                }
                            });
                        }
                        if (options[type].uninitialized === MODE_ALWAYS) {
                            if (node.parent.left === node && (node.parent.type === "ForInStatement" || node.parent.type === "ForOfStatement")) {
                                return;
                            }
                            context.report({
                                node,
                                message: "Combine this with the previous '{{type}}' statement with uninitialized variables.",
                                data: {
                                    type
                                }
                            });
                        }
                    }
                }

                // never
                if (parent.type !== "ForStatement" || parent.init !== node) {
                    const totalDeclarations = declarationCounts.uninitialized + declarationCounts.initialized;

                    if (totalDeclarations > 1) {

                        if (options[type].initialized === MODE_NEVER && options[type].uninitialized === MODE_NEVER) {

                            // both initialized and uninitialized
                            context.report({
                                node,
                                message: "Split '{{type}}' declarations into multiple statements.",
                                data: {
                                    type
                                }
                            });
                        } else if (options[type].initialized === MODE_NEVER && declarationCounts.initialized > 0) {

                            // initialized
                            context.report({
                                node,
                                message: "Split initialized '{{type}}' declarations into multiple statements.",
                                data: {
                                    type
                                }
                            });
                        } else if (options[type].uninitialized === MODE_NEVER && declarationCounts.uninitialized > 0) {

                            // uninitialized
                            context.report({
                                node,
                                message: "Split uninitialized '{{type}}' declarations into multiple statements.",
                                data: {
                                    type
                                }
                            });
                        }
                    }
                }
            },

            "ForStatement:exit": endBlock,
            "ForOfStatement:exit": endBlock,
            "ForInStatement:exit": endBlock,
            "SwitchStatement:exit": endBlock,
            "BlockStatement:exit": endBlock,
            "Program:exit": endFunction,
            "FunctionDeclaration:exit": endFunction,
            "FunctionExpression:exit": endFunction,
            "ArrowFunctionExpression:exit": endFunction
        };

    }
};