function-paren-newline.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /**
  2. * @fileoverview enforce consistent line breaks inside function parentheses
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. docs: {
  16. description: "enforce consistent line breaks inside function parentheses",
  17. category: "Stylistic Issues",
  18. recommended: false,
  19. url: "https://eslint.org/docs/rules/function-paren-newline"
  20. },
  21. fixable: "whitespace",
  22. schema: [
  23. {
  24. oneOf: [
  25. {
  26. enum: ["always", "never", "consistent", "multiline"]
  27. },
  28. {
  29. type: "object",
  30. properties: {
  31. minItems: {
  32. type: "integer",
  33. minimum: 0
  34. }
  35. },
  36. additionalProperties: false
  37. }
  38. ]
  39. }
  40. ]
  41. },
  42. create(context) {
  43. const sourceCode = context.getSourceCode();
  44. const rawOption = context.options[0] || "multiline";
  45. const multilineOption = rawOption === "multiline";
  46. const consistentOption = rawOption === "consistent";
  47. let minItems;
  48. if (typeof rawOption === "object") {
  49. minItems = rawOption.minItems;
  50. } else if (rawOption === "always") {
  51. minItems = 0;
  52. } else if (rawOption === "never") {
  53. minItems = Infinity;
  54. } else {
  55. minItems = null;
  56. }
  57. //----------------------------------------------------------------------
  58. // Helpers
  59. //----------------------------------------------------------------------
  60. /**
  61. * Determines whether there should be newlines inside function parens
  62. * @param {ASTNode[]} elements The arguments or parameters in the list
  63. * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code.
  64. * @returns {boolean} `true` if there should be newlines inside the function parens
  65. */
  66. function shouldHaveNewlines(elements, hasLeftNewline) {
  67. if (multilineOption) {
  68. return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line);
  69. }
  70. if (consistentOption) {
  71. return hasLeftNewline;
  72. }
  73. return elements.length >= minItems;
  74. }
  75. /**
  76. * Validates a list of arguments or parameters
  77. * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
  78. * @param {ASTNode[]} elements The arguments or parameters in the list
  79. * @returns {void}
  80. */
  81. function validateParens(parens, elements) {
  82. const leftParen = parens.leftParen;
  83. const rightParen = parens.rightParen;
  84. const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
  85. const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen);
  86. const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
  87. const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen);
  88. const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
  89. if (hasLeftNewline && !needsNewlines) {
  90. context.report({
  91. node: leftParen,
  92. message: "Unexpected newline after '('.",
  93. fix(fixer) {
  94. return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim()
  95. // If there is a comment between the ( and the first element, don't do a fix.
  96. ? null
  97. : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]);
  98. }
  99. });
  100. } else if (!hasLeftNewline && needsNewlines) {
  101. context.report({
  102. node: leftParen,
  103. message: "Expected a newline after '('.",
  104. fix: fixer => fixer.insertTextAfter(leftParen, "\n")
  105. });
  106. }
  107. if (hasRightNewline && !needsNewlines) {
  108. context.report({
  109. node: rightParen,
  110. message: "Unexpected newline before ')'.",
  111. fix(fixer) {
  112. return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim()
  113. // If there is a comment between the last element and the ), don't do a fix.
  114. ? null
  115. : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]);
  116. }
  117. });
  118. } else if (!hasRightNewline && needsNewlines) {
  119. context.report({
  120. node: rightParen,
  121. message: "Expected a newline before ')'.",
  122. fix: fixer => fixer.insertTextBefore(rightParen, "\n")
  123. });
  124. }
  125. }
  126. /**
  127. * Gets the left paren and right paren tokens of a node.
  128. * @param {ASTNode} node The node with parens
  129. * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
  130. * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
  131. * with a single parameter)
  132. */
  133. function getParenTokens(node) {
  134. switch (node.type) {
  135. case "NewExpression":
  136. if (!node.arguments.length && !(
  137. astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) &&
  138. astUtils.isClosingParenToken(sourceCode.getLastToken(node))
  139. )) {
  140. // If the NewExpression does not have parens (e.g. `new Foo`), return null.
  141. return null;
  142. }
  143. // falls through
  144. case "CallExpression":
  145. return {
  146. leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
  147. rightParen: sourceCode.getLastToken(node)
  148. };
  149. case "FunctionDeclaration":
  150. case "FunctionExpression": {
  151. const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
  152. const rightParen = node.params.length
  153. ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
  154. : sourceCode.getTokenAfter(leftParen);
  155. return { leftParen, rightParen };
  156. }
  157. case "ArrowFunctionExpression": {
  158. const firstToken = sourceCode.getFirstToken(node);
  159. if (!astUtils.isOpeningParenToken(firstToken)) {
  160. // If the ArrowFunctionExpression has a single param without parens, return null.
  161. return null;
  162. }
  163. return {
  164. leftParen: firstToken,
  165. rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken)
  166. };
  167. }
  168. default:
  169. throw new TypeError(`unexpected node with type ${node.type}`);
  170. }
  171. }
  172. /**
  173. * Validates the parentheses for a node
  174. * @param {ASTNode} node The node with parens
  175. * @returns {void}
  176. */
  177. function validateNode(node) {
  178. const parens = getParenTokens(node);
  179. if (parens) {
  180. validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments);
  181. }
  182. }
  183. //----------------------------------------------------------------------
  184. // Public
  185. //----------------------------------------------------------------------
  186. return {
  187. ArrowFunctionExpression: validateNode,
  188. CallExpression: validateNode,
  189. FunctionDeclaration: validateNode,
  190. FunctionExpression: validateNode,
  191. NewExpression: validateNode
  192. };
  193. }
  194. };