new-parens.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @fileoverview Rule to flag when using constructor without parentheses
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. //------------------------------------------------------------------------------
  14. // Rule Definition
  15. //------------------------------------------------------------------------------
  16. module.exports = {
  17. meta: {
  18. type: "layout",
  19. docs: {
  20. description: "require parentheses when invoking a constructor with no arguments",
  21. category: "Stylistic Issues",
  22. recommended: false,
  23. url: "https://eslint.org/docs/rules/new-parens"
  24. },
  25. fixable: "code",
  26. schema: [],
  27. messages: {
  28. missing: "Missing '()' invoking a constructor."
  29. }
  30. },
  31. create(context) {
  32. const sourceCode = context.getSourceCode();
  33. return {
  34. NewExpression(node) {
  35. if (node.arguments.length !== 0) {
  36. return; // shortcut: if there are arguments, there have to be parens
  37. }
  38. const lastToken = sourceCode.getLastToken(node);
  39. const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken);
  40. const hasParens = hasLastParen && astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken));
  41. if (!hasParens) {
  42. context.report({
  43. node,
  44. messageId: "missing",
  45. fix: fixer => fixer.insertTextAfter(node, "()")
  46. });
  47. }
  48. }
  49. };
  50. }
  51. };