a9fd042a39022517ad3f86db5378ea3e0dc91c9d
[dotfiles/.git] / no-label-var.js
1 /**
2  * @fileoverview Rule to flag labels that are the same as an identifier
3  * @author Ian Christian Myers
4  */
5
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Requirements
10 //------------------------------------------------------------------------------
11
12 const astUtils = require("./utils/ast-utils");
13
14 //------------------------------------------------------------------------------
15 // Rule Definition
16 //------------------------------------------------------------------------------
17
18 module.exports = {
19     meta: {
20         type: "suggestion",
21
22         docs: {
23             description: "disallow labels that share a name with a variable",
24             category: "Variables",
25             recommended: false,
26             url: "https://eslint.org/docs/rules/no-label-var"
27         },
28
29         schema: []
30     },
31
32     create(context) {
33
34         //--------------------------------------------------------------------------
35         // Helpers
36         //--------------------------------------------------------------------------
37
38         /**
39          * Check if the identifier is present inside current scope
40          * @param {Object} scope current scope
41          * @param {string} name To evaluate
42          * @returns {boolean} True if its present
43          * @private
44          */
45         function findIdentifier(scope, name) {
46             return astUtils.getVariableByName(scope, name) !== null;
47         }
48
49         //--------------------------------------------------------------------------
50         // Public API
51         //--------------------------------------------------------------------------
52
53         return {
54
55             LabeledStatement(node) {
56
57                 // Fetch the innermost scope.
58                 const scope = context.getScope();
59
60                 /*
61                  * Recursively find the identifier walking up the scope, starting
62                  * with the innermost scope.
63                  */
64                 if (findIdentifier(scope, node.label.name)) {
65                     context.report({ node, message: "Found identifier with same name as label." });
66                 }
67             }
68
69         };
70
71     }
72 };