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. module.exports = {
  10. meta: {
  11. type: "problem",
  12. docs: {
  13. description: "disallow `new` operators with the `Symbol` object",
  14. category: "ECMAScript 6",
  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. };