UNPKG

2.11 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag references to undeclared variables.
3 * @author Mark Macdonald
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Helpers
9//------------------------------------------------------------------------------
10
11/**
12 * Checks if the given node is the argument of a typeof operator.
13 * @param {ASTNode} node The AST node being checked.
14 * @returns {boolean} Whether or not the node is the argument of a typeof operator.
15 */
16function hasTypeOfOperator(node) {
17 const parent = node.parent;
18
19 return parent.type === "UnaryExpression" && parent.operator === "typeof";
20}
21
22//------------------------------------------------------------------------------
23// Rule Definition
24//------------------------------------------------------------------------------
25
26module.exports = {
27 meta: {
28 docs: {
29 description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments",
30 category: "Variables",
31 recommended: true
32 },
33
34 schema: [
35 {
36 type: "object",
37 properties: {
38 typeof: {
39 type: "boolean"
40 }
41 },
42 additionalProperties: false
43 }
44 ]
45 },
46
47 create(context) {
48 const options = context.options[0];
49 const considerTypeOf = options && options.typeof === true || false;
50
51 return {
52 "Program:exit"(/* node */) {
53 const globalScope = context.getScope();
54
55 globalScope.through.forEach(function(ref) {
56 const identifier = ref.identifier;
57
58 if (!considerTypeOf && hasTypeOfOperator(identifier)) {
59 return;
60 }
61
62 context.report({
63 node: identifier,
64 message: "'{{name}}' is not defined.",
65 data: identifier
66 });
67 });
68 }
69 };
70 }
71};