no-new-symbol.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @fileoverview Rule to disallow use of the new operator with the `Symbol` object
  3. * @author Alberto Rodríguez
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "problem",
  13. docs: {
  14. description: "Disallow `new` operators with the `Symbol` object",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-new-symbol"
  17. },
  18. schema: [],
  19. messages: {
  20. noNewSymbol: "`Symbol` cannot be called as a constructor."
  21. }
  22. },
  23. create(context) {
  24. return {
  25. "Program:exit"() {
  26. const globalScope = context.getScope();
  27. const variable = globalScope.set.get("Symbol");
  28. if (variable && variable.defs.length === 0) {
  29. variable.references.forEach(ref => {
  30. const node = ref.identifier;
  31. const parent = node.parent;
  32. if (parent && parent.type === "NewExpression" && parent.callee === node) {
  33. context.report({
  34. node,
  35. messageId: "noNewSymbol"
  36. });
  37. }
  38. });
  39. }
  40. }
  41. };
  42. }
  43. };