1 | /**
|
2 | * @fileoverview Rule to flag references to the undefined variable.
|
3 | * @author Michael Ficarra
|
4 | */
|
5 | ;
|
6 |
|
7 | //------------------------------------------------------------------------------
|
8 | // Rule Definition
|
9 | //------------------------------------------------------------------------------
|
10 |
|
11 | module.exports = {
|
12 | meta: {
|
13 | docs: {
|
14 | description: "disallow the use of `undefined` as an identifier",
|
15 | category: "Variables",
|
16 | recommended: false
|
17 | },
|
18 |
|
19 | schema: []
|
20 | },
|
21 |
|
22 | create(context) {
|
23 |
|
24 | /**
|
25 | * Report an invalid "undefined" identifier node.
|
26 | * @param {ASTNode} node The node to report.
|
27 | * @returns {void}
|
28 | */
|
29 | function report(node) {
|
30 | context.report({
|
31 | node,
|
32 | message: "Unexpected use of undefined."
|
33 | });
|
34 | }
|
35 |
|
36 | /**
|
37 | * Checks the given scope for references to `undefined` and reports
|
38 | * all references found.
|
39 | * @param {eslint-scope.Scope} scope The scope to check.
|
40 | * @returns {void}
|
41 | */
|
42 | function checkScope(scope) {
|
43 | const undefinedVar = scope.set.get("undefined");
|
44 |
|
45 | if (!undefinedVar) {
|
46 | return;
|
47 | }
|
48 |
|
49 | const references = undefinedVar.references;
|
50 |
|
51 | const defs = undefinedVar.defs;
|
52 |
|
53 | // Report non-initializing references (those are covered in defs below)
|
54 | references
|
55 | .filter(ref => !ref.init)
|
56 | .forEach(ref => report(ref.identifier));
|
57 |
|
58 | defs.forEach(def => report(def.name));
|
59 | }
|
60 |
|
61 | return {
|
62 | "Program:exit"() {
|
63 | const globalScope = context.getScope();
|
64 |
|
65 | const stack = [globalScope];
|
66 |
|
67 | while (stack.length) {
|
68 | const scope = stack.pop();
|
69 |
|
70 | stack.push.apply(stack, scope.childScopes);
|
71 | checkScope(scope);
|
72 | }
|
73 | }
|
74 | };
|
75 |
|
76 | }
|
77 | };
|