no-undef.js 2.2 KB

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