function-paren-newline.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "layout",
  17. docs: {
  18. description: "Enforce consistent line breaks inside function parentheses",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/function-paren-newline"
  21. },
  22. fixable: "whitespace",
  23. schema: [
  24. {
  25. oneOf: [
  26. {
  27. enum: ["always", "never", "consistent", "multiline", "multiline-arguments"]
  28. },
  29. {
  30. type: "object",
  31. properties: {
  32. minItems: {
  33. type: "integer",
  34. minimum: 0
  35. }
  36. },
  37. additionalProperties: false
  38. }
  39. ]
  40. }
  41. ],
  42. messages: {
  43. expectedBefore: "Expected newline before ')'.",
  44. expectedAfter: "Expected newline after '('.",
  45. expectedBetween: "Expected newline between arguments/params.",
  46. unexpectedBefore: "Unexpected newline before ')'.",
  47. unexpectedAfter: "Unexpected newline after '('."
  48. }
  49. },
  50. create(context) {
  51. const sourceCode = context.getSourceCode();
  52. const rawOption = context.options[0] || "multiline";
  53. const multilineOption = rawOption === "multiline";
  54. const multilineArgumentsOption = rawOption === "multiline-arguments";
  55. const consistentOption = rawOption === "consistent";
  56. let minItems;
  57. if (typeof rawOption === "object") {
  58. minItems = rawOption.minItems;
  59. } else if (rawOption === "always") {
  60. minItems = 0;
  61. } else if (rawOption === "never") {
  62. minItems = Infinity;
  63. } else {
  64. minItems = null;
  65. }
  66. //----------------------------------------------------------------------
  67. // Helpers
  68. //----------------------------------------------------------------------
  69. /**
  70. * Determines whether there should be newlines inside function parens
  71. * @param {ASTNode[]} elements The arguments or parameters in the list
  72. * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code.
  73. * @returns {boolean} `true` if there should be newlines inside the function parens
  74. */
  75. function shouldHaveNewlines(elements, hasLeftNewline) {
  76. if (multilineArgumentsOption && elements.length === 1) {
  77. return hasLeftNewline;
  78. }
  79. if (multilineOption || multilineArgumentsOption) {
  80. return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line);
  81. }
  82. if (consistentOption) {
  83. return hasLeftNewline;
  84. }
  85. return elements.length >= minItems;
  86. }
  87. /**
  88. * Validates parens
  89. * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
  90. * @param {ASTNode[]} elements The arguments or parameters in the list
  91. * @returns {void}
  92. */
  93. function validateParens(parens, elements) {
  94. const leftParen = parens.leftParen;
  95. const rightParen = parens.rightParen;
  96. const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
  97. const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen);
  98. const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
  99. const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen);
  100. const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
  101. if (hasLeftNewline && !needsNewlines) {
  102. context.report({
  103. node: leftParen,
  104. messageId: "unexpectedAfter",
  105. fix(fixer) {
  106. return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim()
  107. // If there is a comment between the ( and the first element, don't do a fix.
  108. ? null
  109. : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]);
  110. }
  111. });
  112. } else if (!hasLeftNewline && needsNewlines) {
  113. context.report({
  114. node: leftParen,
  115. messageId: "expectedAfter",
  116. fix: fixer => fixer.insertTextAfter(leftParen, "\n")
  117. });
  118. }
  119. if (hasRightNewline && !needsNewlines) {
  120. context.report({
  121. node: rightParen,
  122. messageId: "unexpectedBefore",
  123. fix(fixer) {
  124. return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim()
  125. // If there is a comment between the last element and the ), don't do a fix.
  126. ? null
  127. : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]);
  128. }
  129. });
  130. } else if (!hasRightNewline && needsNewlines) {
  131. context.report({
  132. node: rightParen,
  133. messageId: "expectedBefore",
  134. fix: fixer => fixer.insertTextBefore(rightParen, "\n")
  135. });
  136. }
  137. }
  138. /**
  139. * Validates a list of arguments or parameters
  140. * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
  141. * @param {ASTNode[]} elements The arguments or parameters in the list
  142. * @returns {void}
  143. */
  144. function validateArguments(parens, elements) {
  145. const leftParen = parens.leftParen;
  146. const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
  147. const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
  148. const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
  149. for (let i = 0; i <= elements.length - 2; i++) {
  150. const currentElement = elements[i];
  151. const nextElement = elements[i + 1];
  152. const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line;
  153. if (!hasNewLine && needsNewlines) {
  154. context.report({
  155. node: currentElement,
  156. messageId: "expectedBetween",
  157. fix: fixer => fixer.insertTextBefore(nextElement, "\n")
  158. });
  159. }
  160. }
  161. }
  162. /**
  163. * Gets the left paren and right paren tokens of a node.
  164. * @param {ASTNode} node The node with parens
  165. * @throws {TypeError} Unexpected node type.
  166. * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
  167. * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
  168. * with a single parameter)
  169. */
  170. function getParenTokens(node) {
  171. switch (node.type) {
  172. case "NewExpression":
  173. if (!node.arguments.length &&
  174. !(
  175. astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) &&
  176. astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
  177. node.callee.range[1] < node.range[1]
  178. )
  179. ) {
  180. // If the NewExpression does not have parens (e.g. `new Foo`), return null.
  181. return null;
  182. }
  183. // falls through
  184. case "CallExpression":
  185. return {
  186. leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
  187. rightParen: sourceCode.getLastToken(node)
  188. };
  189. case "FunctionDeclaration":
  190. case "FunctionExpression": {
  191. const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
  192. const rightParen = node.params.length
  193. ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
  194. : sourceCode.getTokenAfter(leftParen);
  195. return { leftParen, rightParen };
  196. }
  197. case "ArrowFunctionExpression": {
  198. const firstToken = sourceCode.getFirstToken(node, { skip: (node.async ? 1 : 0) });
  199. if (!astUtils.isOpeningParenToken(firstToken)) {
  200. // If the ArrowFunctionExpression has a single param without parens, return null.
  201. return null;
  202. }
  203. const rightParen = node.params.length
  204. ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
  205. : sourceCode.getTokenAfter(firstToken);
  206. return {
  207. leftParen: firstToken,
  208. rightParen
  209. };
  210. }
  211. case "ImportExpression": {
  212. const leftParen = sourceCode.getFirstToken(node, 1);
  213. const rightParen = sourceCode.getLastToken(node);
  214. return { leftParen, rightParen };
  215. }
  216. default:
  217. throw new TypeError(`unexpected node with type ${node.type}`);
  218. }
  219. }
  220. //----------------------------------------------------------------------
  221. // Public
  222. //----------------------------------------------------------------------
  223. return {
  224. [[
  225. "ArrowFunctionExpression",
  226. "CallExpression",
  227. "FunctionDeclaration",
  228. "FunctionExpression",
  229. "ImportExpression",
  230. "NewExpression"
  231. ]](node) {
  232. const parens = getParenTokens(node);
  233. let params;
  234. if (node.type === "ImportExpression") {
  235. params = [node.source];
  236. } else if (astUtils.isFunction(node)) {
  237. params = node.params;
  238. } else {
  239. params = node.arguments;
  240. }
  241. if (parens) {
  242. validateParens(parens, params);
  243. if (multilineArgumentsOption) {
  244. validateArguments(parens, params);
  245. }
  246. }
  247. }
  248. };
  249. }
  250. };