UNPKG

2.14 kBJavaScriptView Raw
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("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Rule Definition
16//------------------------------------------------------------------------------
17
18module.exports = {
19 meta: {
20 docs: {
21 description: "disallow labels that share a name with a variable",
22 category: "Variables",
23 recommended: false,
24 url: "https://eslint.org/docs/rules/no-label-var"
25 },
26
27 schema: []
28 },
29
30 create(context) {
31
32 //--------------------------------------------------------------------------
33 // Helpers
34 //--------------------------------------------------------------------------
35
36 /**
37 * Check if the identifier is present inside current scope
38 * @param {Object} scope current scope
39 * @param {string} name To evaluate
40 * @returns {boolean} True if its present
41 * @private
42 */
43 function findIdentifier(scope, name) {
44 return astUtils.getVariableByName(scope, name) !== null;
45 }
46
47 //--------------------------------------------------------------------------
48 // Public API
49 //--------------------------------------------------------------------------
50
51 return {
52
53 LabeledStatement(node) {
54
55 // Fetch the innermost scope.
56 const scope = context.getScope();
57
58 /*
59 * Recursively find the identifier walking up the scope, starting
60 * with the innermost scope.
61 */
62 if (findIdentifier(scope, node.label.name)) {
63 context.report({ node, message: "Found identifier with same name as label." });
64 }
65 }
66
67 };
68
69 }
70};