summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/block-scoped-var.js
blob: 6b23167fd1f6ab198e524e4b529ce78784afcf2d (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
/**
 * @fileoverview Rule to check for "block scoped" variables by binding context
 * @author Matt DuVall <http://www.mattduvall.com>
 */
"use strict";

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

module.exports = function(context) {

    var scopeStack = [];

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

    /**
     * Determines whether an identifier is in declaration position or is a non-declaration reference.
     * @param {ASTNode} id The identifier.
     * @param {ASTNode} parent The identifier's parent AST node.
     * @returns {Boolean} true when the identifier is in declaration position.
     */
    function isDeclaration(id, parent) {
        switch (parent.type) {
            case "FunctionDeclaration":
            case "FunctionExpression":
                return parent.params.indexOf(id) > -1 || id === parent.id;

            case "VariableDeclarator":
                return id === parent.id;

            case "CatchClause":
                return id === parent.param;

            default:
                return false;
        }
    }

    /**
     * Determines whether an identifier is in property position.
     * @param {ASTNode} id The identifier.
     * @param {ASTNode} parent The identifier's parent AST node.
     * @returns {Boolean} true when the identifier is in property position.
     */
    function isProperty(id, parent) {
        switch (parent.type) {
            case "MemberExpression":
                return id === parent.property && !parent.computed;

            case "Property":
                return id === parent.key;

            default:
                return false;
        }
    }

    /**
     * Pushes a new scope object on the scope stack.
     * @returns {void}
     */
    function pushScope() {
        scopeStack.push([]);
    }

    /**
     * Removes the topmost scope object from the scope stack.
     * @returns {void}
     */
    function popScope() {
        scopeStack.pop();
    }

    /**
     * Declares the given names in the topmost scope object.
     * @param {[String]} names A list of names to declare.
     * @returns {void}
     */
    function declare(names) {
        [].push.apply(scopeStack[scopeStack.length - 1], names);
    }

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

    /**
     * Declares all relevant identifiers for module imports.
     * @param {ASTNode} node The AST node representing an import.
     * @returns {void}
     * @private
     */
    function declareImports(node) {
        declare([node.local.name]);

        if (node.imported && node.imported.name !== node.local.name) {
            declare([node.imported.name]);
        }
    }

    /**
     * Declares all relevant identifiers for classes.
     * @param {ASTNode} node The AST node representing a class.
     * @returns {void}
     * @private
     */
    function declareClass(node) {

        if (node.id) {
            declare([node.id.name]);
        }

        pushScope();
    }

    /**
     * Declares all relevant identifiers for classes.
     * @param {ASTNode} node The AST node representing a class.
     * @returns {void}
     * @private
     */
    function declareClassMethod(node) {
        pushScope();

        declare([node.key.name]);
    }

    /**
     * Add declarations based on the type of node being passed.
     * @param {ASTNode} node The node containing declarations.
     * @returns {void}
     * @private
     */
    function declareByNodeType(node) {

        var declarations = [];

        switch (node.type) {
            case "Identifier":
                declarations.push(node.name);
                break;

            case "ObjectPattern":
                node.properties.forEach(function(property) {
                    declarations.push(property.key.name);
                    if (property.value) {
                        declarations.push(property.value.name);
                    }
                });
                break;

            case "ArrayPattern":
                node.elements.forEach(function(element) {
                    if (element) {
                        declarations.push(element.name);
                    }
                });
                break;

            case "AssignmentPattern":
                declareByNodeType(node.left);
                break;

            case "RestElement":
                declareByNodeType(node.argument);
                break;

            // no default
        }

        declare(declarations);

    }

    /**
     * Adds declarations of the function parameters and pushes the scope
     * @param {ASTNode} node The node containing declarations.
     * @returns {void}
     * @private
     */
    function functionHandler(node) {
        pushScope();

        node.params.forEach(function(param) {
            declareByNodeType(param);
        });

        declare(node.rest ? [node.rest.name] : []);
        declare(["arguments"]);
    }

    /**
     * Adds declaration of the function name in its parent scope then process the function
     * @param {ASTNode} node The node containing declarations.
     * @returns {void}
     * @private
     */
    function functionDeclarationHandler(node) {
        declare(node.id ? [node.id.name] : []);
        functionHandler(node);
    }

    /**
     * Process function declarations and declares its name in its own scope
     * @param {ASTNode} node The node containing declarations.
     * @returns {void}
     * @private
     */
    function functionExpressionHandler(node) {
        functionHandler(node);
        declare(node.id ? [node.id.name] : []);
    }

    function variableDeclarationHandler(node) {
        node.declarations.forEach(function(declaration) {
            declareByNodeType(declaration.id);
        });

    }

    return {
        "Program": function() {
            var scope = context.getScope();
            scopeStack = [scope.variables.map(function(v) {
                return v.name;
            })];

            // global return creates another scope
            if (context.ecmaFeatures.globalReturn) {
                scope = scope.childScopes[0];
                scopeStack.push(scope.variables.map(function(v) {
                    return v.name;
                }));
            }
        },

        "ImportSpecifier": declareImports,
        "ImportDefaultSpecifier": declareImports,
        "ImportNamespaceSpecifier": declareImports,

        "BlockStatement": function(node) {
            var statements = node.body;
            pushScope();
            statements.forEach(function(stmt) {
                if (stmt.type === "VariableDeclaration") {
                    variableDeclarationHandler(stmt);
                } else if (stmt.type === "FunctionDeclaration") {
                    declare([stmt.id.name]);
                }
            });
        },

        "VariableDeclaration": function (node) {
            variableDeclarationHandler(node);
        },

        "BlockStatement:exit": popScope,

        "CatchClause": function(node) {
            pushScope();
            declare([node.param.name]);
        },
        "CatchClause:exit": popScope,

        "FunctionDeclaration": functionDeclarationHandler,
        "FunctionDeclaration:exit": popScope,

        "ClassDeclaration": declareClass,
        "ClassDeclaration:exit": popScope,

        "ClassExpression": declareClass,
        "ClassExpression:exit": popScope,

        "MethodDefinition": declareClassMethod,
        "MethodDefinition:exit": popScope,

        "FunctionExpression": functionExpressionHandler,
        "FunctionExpression:exit": popScope,

        // Arrow functions cannot have names
        "ArrowFunctionExpression": functionHandler,
        "ArrowFunctionExpression:exit": popScope,

        "ForStatement": function() {
            pushScope();
        },
        "ForStatement:exit": popScope,

        "ForInStatement": function() {
            pushScope();
        },
        "ForInStatement:exit": popScope,

        "ForOfStatement": function() {
            pushScope();
        },
        "ForOfStatement:exit": popScope,

        "Identifier": function(node) {
            var ancestor = context.getAncestors().pop();
            if (isDeclaration(node, ancestor) || isProperty(node, ancestor) || ancestor.type === "LabeledStatement") {
                return;
            }

            for (var i = 0, l = scopeStack.length; i < l; i++) {
                if (scopeStack[i].indexOf(node.name) > -1) {
                    return;
                }
            }

            context.report(node, "\"" + node.name + "\" used outside of binding context.");
        }
    };

};