new-parens.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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("../ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. //------------------------------------------------------------------------------
  14. // Rule Definition
  15. //------------------------------------------------------------------------------
  16. module.exports = {
  17. meta: {
  18. docs: {
  19. description: "require parentheses when invoking a constructor with no arguments",
  20. category: "Stylistic Issues",
  21. recommended: false,
  22. url: "https://eslint.org/docs/rules/new-parens"
  23. },
  24. schema: [],
  25. fixable: "code"
  26. },
  27. create(context) {
  28. const sourceCode = context.getSourceCode();
  29. return {
  30. NewExpression(node) {
  31. if (node.arguments.length !== 0) {
  32. return; // shortcut: if there are arguments, there have to be parens
  33. }
  34. const lastToken = sourceCode.getLastToken(node);
  35. const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken);
  36. const hasParens = hasLastParen && astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken));
  37. if (!hasParens) {
  38. context.report({
  39. node,
  40. message: "Missing '()' invoking a constructor.",
  41. fix: fixer => fixer.insertTextAfter(node, "()")
  42. });
  43. }
  44. }
  45. };
  46. }
  47. };