no-undef.js 2.1 KB

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