UNPKG

1.79 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag labels that are the same as an identifier
3 * @author Ian Christian Myers
4 */
5
6//------------------------------------------------------------------------------
7// Rule Definition
8//------------------------------------------------------------------------------
9
10module.exports = function(context) {
11
12 "use strict";
13
14 //--------------------------------------------------------------------------
15 // Helpers
16 //--------------------------------------------------------------------------
17
18 function findIdentifier(scope, identifier) {
19 var found = false;
20
21 scope.variables.forEach(function(variable) {
22 if (variable.name === identifier) {
23 found = true;
24 }
25 });
26
27 scope.references.forEach(function(reference) {
28 if (reference.identifier.name === identifier) {
29 found = true;
30 }
31 });
32
33 // If we have not found the identifier in this scope, check the parent
34 // scope.
35 if (scope.upper && !found) {
36 return findIdentifier(scope.upper, identifier);
37 }
38
39 return found;
40 }
41
42 //--------------------------------------------------------------------------
43 // Public API
44 //--------------------------------------------------------------------------
45
46 return {
47
48 "LabeledStatement": function(node) {
49
50 // Fetch the innermost scope.
51 var scope = context.getScope();
52
53 // Recursively find the identifier walking up the scope, starting
54 // with the innermost scope.
55 if (findIdentifier(scope, node.label.name)) {
56 context.report(node, "Found identifier with same name as label.");
57 }
58 }
59
60 };
61
62};