Blame view

node_modules/eslint/lib/rules/no-restricted-globals.js 2.32 KB
f7563de62   Palak Handa   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  /**
   * @fileoverview Restrict usage of specified globals.
   * @author BenoƮt Zugmeyer
   */
  "use strict";
  
  //------------------------------------------------------------------------------
  // Rule Definition
  //------------------------------------------------------------------------------
  
  module.exports = {
      meta: {
          docs: {
              description: "disallow specified global variables",
              category: "Variables",
              recommended: false
          },
  
          schema: {
              type: "array",
              items: {
                  type: "string"
              },
              uniqueItems: true
          }
      },
  
      create(context) {
          const restrictedGlobals = context.options;
  
          // if no globals are restricted we don't need to check
          if (restrictedGlobals.length === 0) {
              return {};
          }
  
          /**
           * Report a variable to be used as a restricted global.
           * @param {Reference} reference the variable reference
           * @returns {void}
           * @private
           */
          function reportReference(reference) {
              context.report({ node: reference.identifier, message: "Unexpected use of '{{name}}'.", data: {
                  name: reference.identifier.name
              } });
          }
  
          /**
           * Check if the given name is a restricted global name.
           * @param {string} name name of a variable
           * @returns {boolean} whether the variable is a restricted global or not
           * @private
           */
          function isRestricted(name) {
              return restrictedGlobals.indexOf(name) >= 0;
          }
  
          return {
              Program() {
                  const scope = context.getScope();
  
                  // Report variables declared elsewhere (ex: variables defined as "global" by eslint)
                  scope.variables.forEach(variable => {
                      if (!variable.defs.length && isRestricted(variable.name)) {
                          variable.references.forEach(reportReference);
                      }
                  });
  
                  // Report variables not declared at all
                  scope.through.forEach(reference => {
                      if (isRestricted(reference.identifier.name)) {
                          reportReference(reference);
                      }
                  });
  
              }
          };
      }
  };