no-new-native-nonconstructor.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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('../types').Rule.RuleModule} */
  14. module.exports = {
  15. meta: {
  16. type: "problem",
  17. docs: {
  18. description:
  19. "Disallow `new` operators with global non-constructor functions",
  20. recommended: true,
  21. url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor",
  22. },
  23. schema: [],
  24. messages: {
  25. noNewNonconstructor:
  26. "`{{name}}` cannot be called as a constructor.",
  27. },
  28. },
  29. create(context) {
  30. const sourceCode = context.sourceCode;
  31. return {
  32. "Program:exit"(node) {
  33. const globalScope = sourceCode.getScope(node);
  34. for (const nonConstructorName of nonConstructorGlobalFunctionNames) {
  35. const variable = globalScope.set.get(nonConstructorName);
  36. if (variable && variable.defs.length === 0) {
  37. variable.references.forEach(ref => {
  38. const idNode = ref.identifier;
  39. const parent = idNode.parent;
  40. if (
  41. parent &&
  42. parent.type === "NewExpression" &&
  43. parent.callee === idNode
  44. ) {
  45. context.report({
  46. node: idNode,
  47. messageId: "noNewNonconstructor",
  48. data: { name: nonConstructorName },
  49. });
  50. }
  51. });
  52. }
  53. }
  54. },
  55. };
  56. },
  57. };