no-undef.js 2.3 KB

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