no-undef.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. /** @type {import('../types').Rule.RuleModule} */
  22. module.exports = {
  23. meta: {
  24. type: "problem",
  25. defaultOptions: [
  26. {
  27. typeof: false,
  28. },
  29. ],
  30. docs: {
  31. description:
  32. "Disallow the use of undeclared variables unless mentioned in `/*global */` comments",
  33. recommended: true,
  34. url: "https://eslint.org/docs/latest/rules/no-undef",
  35. },
  36. schema: [
  37. {
  38. type: "object",
  39. properties: {
  40. typeof: {
  41. type: "boolean",
  42. },
  43. },
  44. additionalProperties: false,
  45. },
  46. ],
  47. messages: {
  48. undef: "'{{name}}' is not defined.",
  49. },
  50. },
  51. create(context) {
  52. const [{ typeof: considerTypeOf }] = context.options;
  53. const sourceCode = context.sourceCode;
  54. return {
  55. "Program:exit"(node) {
  56. const globalScope = sourceCode.getScope(node);
  57. globalScope.through.forEach(ref => {
  58. const identifier = ref.identifier;
  59. if (!considerTypeOf && hasTypeOfOperator(identifier)) {
  60. return;
  61. }
  62. context.report({
  63. node: identifier,
  64. messageId: "undef",
  65. data: identifier,
  66. });
  67. });
  68. },
  69. };
  70. },
  71. };