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