no-undefined.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @fileoverview Rule to flag references to the undefined variable.
  3. * @author Michael Ficarra
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "Disallow the use of `undefined` as an identifier",
  15. recommended: false,
  16. url: "https://eslint.org/docs/latest/rules/no-undefined"
  17. },
  18. schema: [],
  19. messages: {
  20. unexpectedUndefined: "Unexpected use of undefined."
  21. }
  22. },
  23. create(context) {
  24. const sourceCode = context.sourceCode;
  25. /**
  26. * Report an invalid "undefined" identifier node.
  27. * @param {ASTNode} node The node to report.
  28. * @returns {void}
  29. */
  30. function report(node) {
  31. context.report({
  32. node,
  33. messageId: "unexpectedUndefined"
  34. });
  35. }
  36. /**
  37. * Checks the given scope for references to `undefined` and reports
  38. * all references found.
  39. * @param {eslint-scope.Scope} scope The scope to check.
  40. * @returns {void}
  41. */
  42. function checkScope(scope) {
  43. const undefinedVar = scope.set.get("undefined");
  44. if (!undefinedVar) {
  45. return;
  46. }
  47. const references = undefinedVar.references;
  48. const defs = undefinedVar.defs;
  49. // Report non-initializing references (those are covered in defs below)
  50. references
  51. .filter(ref => !ref.init)
  52. .forEach(ref => report(ref.identifier));
  53. defs.forEach(def => report(def.name));
  54. }
  55. return {
  56. "Program:exit"(node) {
  57. const globalScope = sourceCode.getScope(node);
  58. const stack = [globalScope];
  59. while (stack.length) {
  60. const scope = stack.pop();
  61. stack.push(...scope.childScopes);
  62. checkScope(scope);
  63. }
  64. }
  65. };
  66. }
  67. };