no-new-native-nonconstructor.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * @fileoverview Rule to disallow use of the new operator with global non-constructor functions
  3. * @author Sosuke Suzuki
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"];
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "problem",
  17. docs: {
  18. description: "Disallow `new` operators with global non-constructor functions",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-new-native-nonconstructor"
  21. },
  22. schema: [],
  23. messages: {
  24. noNewNonconstructor: "`{{name}}` cannot be called as a constructor."
  25. }
  26. },
  27. create(context) {
  28. return {
  29. "Program:exit"() {
  30. const globalScope = context.getScope();
  31. for (const nonConstructorName of nonConstructorGlobalFunctionNames) {
  32. const variable = globalScope.set.get(nonConstructorName);
  33. if (variable && variable.defs.length === 0) {
  34. variable.references.forEach(ref => {
  35. const node = ref.identifier;
  36. const parent = node.parent;
  37. if (parent && parent.type === "NewExpression" && parent.callee === node) {
  38. context.report({
  39. node,
  40. messageId: "noNewNonconstructor",
  41. data: { name: nonConstructorName }
  42. });
  43. }
  44. });
  45. }
  46. }
  47. }
  48. };
  49. }
  50. };