]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
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", | |
eb39fafa DC |
24 | recommended: false, |
25 | url: "https://eslint.org/docs/rules/no-label-var" | |
26 | }, | |
27 | ||
28 | schema: [], | |
29 | ||
30 | messages: { | |
31 | identifierClashWithLabel: "Found identifier with same name as label." | |
32 | } | |
33 | }, | |
34 | ||
35 | create(context) { | |
36 | ||
37 | //-------------------------------------------------------------------------- | |
38 | // Helpers | |
39 | //-------------------------------------------------------------------------- | |
40 | ||
41 | /** | |
42 | * Check if the identifier is present inside current scope | |
43 | * @param {Object} scope current scope | |
44 | * @param {string} name To evaluate | |
45 | * @returns {boolean} True if its present | |
46 | * @private | |
47 | */ | |
48 | function findIdentifier(scope, name) { | |
49 | return astUtils.getVariableByName(scope, name) !== null; | |
50 | } | |
51 | ||
52 | //-------------------------------------------------------------------------- | |
53 | // Public API | |
54 | //-------------------------------------------------------------------------- | |
55 | ||
56 | return { | |
57 | ||
58 | LabeledStatement(node) { | |
59 | ||
60 | // Fetch the innermost scope. | |
61 | const scope = context.getScope(); | |
62 | ||
63 | /* | |
64 | * Recursively find the identifier walking up the scope, starting | |
65 | * with the innermost scope. | |
66 | */ | |
67 | if (findIdentifier(scope, node.label.name)) { | |
68 | context.report({ | |
69 | node, | |
70 | messageId: "identifierClashWithLabel" | |
71 | }); | |
72 | } | |
73 | } | |
74 | ||
75 | }; | |
76 | ||
77 | } | |
78 | }; |