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