UNPKG

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