• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
12const astUtils = require("./utils/ast-utils");
13
14//------------------------------------------------------------------------------
15// Rule Definition
16//------------------------------------------------------------------------------
17
18module.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        messages: {
32            identifierClashWithLabel: "Found identifier with same name as label."
33        }
34    },
35
36    create(context) {
37
38        //--------------------------------------------------------------------------
39        // Helpers
40        //--------------------------------------------------------------------------
41
42        /**
43         * Check if the identifier is present inside current scope
44         * @param {Object} scope current scope
45         * @param {string} name To evaluate
46         * @returns {boolean} True if its present
47         * @private
48         */
49        function findIdentifier(scope, name) {
50            return astUtils.getVariableByName(scope, name) !== null;
51        }
52
53        //--------------------------------------------------------------------------
54        // Public API
55        //--------------------------------------------------------------------------
56
57        return {
58
59            LabeledStatement(node) {
60
61                // Fetch the innermost scope.
62                const scope = context.getScope();
63
64                /*
65                 * Recursively find the identifier walking up the scope, starting
66                 * with the innermost scope.
67                 */
68                if (findIdentifier(scope, node.label.name)) {
69                    context.report({
70                        node,
71                        messageId: "identifierClashWithLabel"
72                    });
73                }
74            }
75
76        };
77
78    }
79};
80