no-undefined.js 2.2 KB

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