array-bracket-newline.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /**
  2. * @fileoverview Rule to enforce linebreaks after open and before close array brackets
  3. * @author Jan Peer Stöcklmair <https://github.com/JPeer264>
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "layout",
  13. docs: {
  14. description: "enforce linebreaks after opening and before closing array brackets",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/array-bracket-newline"
  18. },
  19. fixable: "whitespace",
  20. schema: [
  21. {
  22. oneOf: [
  23. {
  24. enum: ["always", "never", "consistent"]
  25. },
  26. {
  27. type: "object",
  28. properties: {
  29. multiline: {
  30. type: "boolean"
  31. },
  32. minItems: {
  33. type: ["integer", "null"],
  34. minimum: 0
  35. }
  36. },
  37. additionalProperties: false
  38. }
  39. ]
  40. }
  41. ],
  42. messages: {
  43. unexpectedOpeningLinebreak: "There should be no linebreak after '['.",
  44. unexpectedClosingLinebreak: "There should be no linebreak before ']'.",
  45. missingOpeningLinebreak: "A linebreak is required after '['.",
  46. missingClosingLinebreak: "A linebreak is required before ']'."
  47. }
  48. },
  49. create(context) {
  50. const sourceCode = context.getSourceCode();
  51. //----------------------------------------------------------------------
  52. // Helpers
  53. //----------------------------------------------------------------------
  54. /**
  55. * Normalizes a given option value.
  56. * @param {string|Object|undefined} option An option value to parse.
  57. * @returns {{multiline: boolean, minItems: number}} Normalized option object.
  58. */
  59. function normalizeOptionValue(option) {
  60. let consistent = false;
  61. let multiline = false;
  62. let minItems = 0;
  63. if (option) {
  64. if (option === "consistent") {
  65. consistent = true;
  66. minItems = Number.POSITIVE_INFINITY;
  67. } else if (option === "always" || option.minItems === 0) {
  68. minItems = 0;
  69. } else if (option === "never") {
  70. minItems = Number.POSITIVE_INFINITY;
  71. } else {
  72. multiline = Boolean(option.multiline);
  73. minItems = option.minItems || Number.POSITIVE_INFINITY;
  74. }
  75. } else {
  76. consistent = false;
  77. multiline = true;
  78. minItems = Number.POSITIVE_INFINITY;
  79. }
  80. return { consistent, multiline, minItems };
  81. }
  82. /**
  83. * Normalizes a given option value.
  84. * @param {string|Object|undefined} options An option value to parse.
  85. * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
  86. */
  87. function normalizeOptions(options) {
  88. const value = normalizeOptionValue(options);
  89. return { ArrayExpression: value, ArrayPattern: value };
  90. }
  91. /**
  92. * Reports that there shouldn't be a linebreak after the first token
  93. * @param {ASTNode} node The node to report in the event of an error.
  94. * @param {Token} token The token to use for the report.
  95. * @returns {void}
  96. */
  97. function reportNoBeginningLinebreak(node, token) {
  98. context.report({
  99. node,
  100. loc: token.loc,
  101. messageId: "unexpectedOpeningLinebreak",
  102. fix(fixer) {
  103. const nextToken = sourceCode.getTokenAfter(token, { includeComments: true });
  104. if (astUtils.isCommentToken(nextToken)) {
  105. return null;
  106. }
  107. return fixer.removeRange([token.range[1], nextToken.range[0]]);
  108. }
  109. });
  110. }
  111. /**
  112. * Reports that there shouldn't be a linebreak before the last token
  113. * @param {ASTNode} node The node to report in the event of an error.
  114. * @param {Token} token The token to use for the report.
  115. * @returns {void}
  116. */
  117. function reportNoEndingLinebreak(node, token) {
  118. context.report({
  119. node,
  120. loc: token.loc,
  121. messageId: "unexpectedClosingLinebreak",
  122. fix(fixer) {
  123. const previousToken = sourceCode.getTokenBefore(token, { includeComments: true });
  124. if (astUtils.isCommentToken(previousToken)) {
  125. return null;
  126. }
  127. return fixer.removeRange([previousToken.range[1], token.range[0]]);
  128. }
  129. });
  130. }
  131. /**
  132. * Reports that there should be a linebreak after the first token
  133. * @param {ASTNode} node The node to report in the event of an error.
  134. * @param {Token} token The token to use for the report.
  135. * @returns {void}
  136. */
  137. function reportRequiredBeginningLinebreak(node, token) {
  138. context.report({
  139. node,
  140. loc: token.loc,
  141. messageId: "missingOpeningLinebreak",
  142. fix(fixer) {
  143. return fixer.insertTextAfter(token, "\n");
  144. }
  145. });
  146. }
  147. /**
  148. * Reports that there should be a linebreak before the last token
  149. * @param {ASTNode} node The node to report in the event of an error.
  150. * @param {Token} token The token to use for the report.
  151. * @returns {void}
  152. */
  153. function reportRequiredEndingLinebreak(node, token) {
  154. context.report({
  155. node,
  156. loc: token.loc,
  157. messageId: "missingClosingLinebreak",
  158. fix(fixer) {
  159. return fixer.insertTextBefore(token, "\n");
  160. }
  161. });
  162. }
  163. /**
  164. * Reports a given node if it violated this rule.
  165. * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node.
  166. * @returns {void}
  167. */
  168. function check(node) {
  169. const elements = node.elements;
  170. const normalizedOptions = normalizeOptions(context.options[0]);
  171. const options = normalizedOptions[node.type];
  172. const openBracket = sourceCode.getFirstToken(node);
  173. const closeBracket = sourceCode.getLastToken(node);
  174. const firstIncComment = sourceCode.getTokenAfter(openBracket, { includeComments: true });
  175. const lastIncComment = sourceCode.getTokenBefore(closeBracket, { includeComments: true });
  176. const first = sourceCode.getTokenAfter(openBracket);
  177. const last = sourceCode.getTokenBefore(closeBracket);
  178. const needsLinebreaks = (
  179. elements.length >= options.minItems ||
  180. (
  181. options.multiline &&
  182. elements.length > 0 &&
  183. firstIncComment.loc.start.line !== lastIncComment.loc.end.line
  184. ) ||
  185. (
  186. elements.length === 0 &&
  187. firstIncComment.type === "Block" &&
  188. firstIncComment.loc.start.line !== lastIncComment.loc.end.line &&
  189. firstIncComment === lastIncComment
  190. ) ||
  191. (
  192. options.consistent &&
  193. openBracket.loc.end.line !== first.loc.start.line
  194. )
  195. );
  196. /*
  197. * Use tokens or comments to check multiline or not.
  198. * But use only tokens to check whether linebreaks are needed.
  199. * This allows:
  200. * var arr = [ // eslint-disable-line foo
  201. * 'a'
  202. * ]
  203. */
  204. if (needsLinebreaks) {
  205. if (astUtils.isTokenOnSameLine(openBracket, first)) {
  206. reportRequiredBeginningLinebreak(node, openBracket);
  207. }
  208. if (astUtils.isTokenOnSameLine(last, closeBracket)) {
  209. reportRequiredEndingLinebreak(node, closeBracket);
  210. }
  211. } else {
  212. if (!astUtils.isTokenOnSameLine(openBracket, first)) {
  213. reportNoBeginningLinebreak(node, openBracket);
  214. }
  215. if (!astUtils.isTokenOnSameLine(last, closeBracket)) {
  216. reportNoEndingLinebreak(node, closeBracket);
  217. }
  218. }
  219. }
  220. //----------------------------------------------------------------------
  221. // Public
  222. //----------------------------------------------------------------------
  223. return {
  224. ArrayPattern: check,
  225. ArrayExpression: check
  226. };
  227. }
  228. };