comma-style.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /**
  2. * @fileoverview Comma style - enforces comma styles of two types: last and first
  3. * @author Vignesh Anand aka vegetableman
  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 consistent comma style",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/comma-style"
  18. },
  19. fixable: "code",
  20. schema: [
  21. {
  22. enum: ["first", "last"]
  23. },
  24. {
  25. type: "object",
  26. properties: {
  27. exceptions: {
  28. type: "object",
  29. additionalProperties: {
  30. type: "boolean"
  31. }
  32. }
  33. },
  34. additionalProperties: false
  35. }
  36. ],
  37. messages: {
  38. unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.",
  39. expectedCommaFirst: "',' should be placed first.",
  40. expectedCommaLast: "',' should be placed last."
  41. }
  42. },
  43. create(context) {
  44. const style = context.options[0] || "last",
  45. sourceCode = context.getSourceCode();
  46. const exceptions = {
  47. ArrayPattern: true,
  48. ArrowFunctionExpression: true,
  49. CallExpression: true,
  50. FunctionDeclaration: true,
  51. FunctionExpression: true,
  52. ImportDeclaration: true,
  53. ObjectPattern: true,
  54. NewExpression: true
  55. };
  56. if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) {
  57. const keys = Object.keys(context.options[1].exceptions);
  58. for (let i = 0; i < keys.length; i++) {
  59. exceptions[keys[i]] = context.options[1].exceptions[keys[i]];
  60. }
  61. }
  62. //--------------------------------------------------------------------------
  63. // Helpers
  64. //--------------------------------------------------------------------------
  65. /**
  66. * Modified text based on the style
  67. * @param {string} styleType Style type
  68. * @param {string} text Source code text
  69. * @returns {string} modified text
  70. * @private
  71. */
  72. function getReplacedText(styleType, text) {
  73. switch (styleType) {
  74. case "between":
  75. return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`;
  76. case "first":
  77. return `${text},`;
  78. case "last":
  79. return `,${text}`;
  80. default:
  81. return "";
  82. }
  83. }
  84. /**
  85. * Determines the fixer function for a given style.
  86. * @param {string} styleType comma style
  87. * @param {ASTNode} previousItemToken The token to check.
  88. * @param {ASTNode} commaToken The token to check.
  89. * @param {ASTNode} currentItemToken The token to check.
  90. * @returns {Function} Fixer function
  91. * @private
  92. */
  93. function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
  94. const text =
  95. sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
  96. sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
  97. const range = [previousItemToken.range[1], currentItemToken.range[0]];
  98. return function(fixer) {
  99. return fixer.replaceTextRange(range, getReplacedText(styleType, text));
  100. };
  101. }
  102. /**
  103. * Validates the spacing around single items in lists.
  104. * @param {Token} previousItemToken The last token from the previous item.
  105. * @param {Token} commaToken The token representing the comma.
  106. * @param {Token} currentItemToken The first token of the current item.
  107. * @param {Token} reportItem The item to use when reporting an error.
  108. * @returns {void}
  109. * @private
  110. */
  111. function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
  112. // if single line
  113. if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
  114. astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
  115. // do nothing.
  116. } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
  117. !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
  118. const comment = sourceCode.getCommentsAfter(commaToken)[0];
  119. const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment)
  120. ? style
  121. : "between";
  122. // lone comma
  123. context.report({
  124. node: reportItem,
  125. loc: commaToken.loc,
  126. messageId: "unexpectedLineBeforeAndAfterComma",
  127. fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
  128. });
  129. } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
  130. context.report({
  131. node: reportItem,
  132. loc: commaToken.loc,
  133. messageId: "expectedCommaFirst",
  134. fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
  135. });
  136. } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
  137. context.report({
  138. node: reportItem,
  139. loc: commaToken.loc,
  140. messageId: "expectedCommaLast",
  141. fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
  142. });
  143. }
  144. }
  145. /**
  146. * Checks the comma placement with regards to a declaration/property/element
  147. * @param {ASTNode} node The binary expression node to check
  148. * @param {string} property The property of the node containing child nodes.
  149. * @private
  150. * @returns {void}
  151. */
  152. function validateComma(node, property) {
  153. const items = node[property],
  154. arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern");
  155. if (items.length > 1 || arrayLiteral) {
  156. // seed as opening [
  157. let previousItemToken = sourceCode.getFirstToken(node);
  158. items.forEach(item => {
  159. const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken,
  160. currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken),
  161. reportItem = item || currentItemToken;
  162. /*
  163. * This works by comparing three token locations:
  164. * - previousItemToken is the last token of the previous item
  165. * - commaToken is the location of the comma before the current item
  166. * - currentItemToken is the first token of the current item
  167. *
  168. * These values get switched around if item is undefined.
  169. * previousItemToken will refer to the last token not belonging
  170. * to the current item, which could be a comma or an opening
  171. * square bracket. currentItemToken could be a comma.
  172. *
  173. * All comparisons are done based on these tokens directly, so
  174. * they are always valid regardless of an undefined item.
  175. */
  176. if (astUtils.isCommaToken(commaToken)) {
  177. validateCommaItemSpacing(previousItemToken, commaToken,
  178. currentItemToken, reportItem);
  179. }
  180. if (item) {
  181. const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken);
  182. previousItemToken = tokenAfterItem
  183. ? sourceCode.getTokenBefore(tokenAfterItem)
  184. : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1];
  185. }
  186. });
  187. /*
  188. * Special case for array literals that have empty last items, such
  189. * as [ 1, 2, ]. These arrays only have two items show up in the
  190. * AST, so we need to look at the token to verify that there's no
  191. * dangling comma.
  192. */
  193. if (arrayLiteral) {
  194. const lastToken = sourceCode.getLastToken(node),
  195. nextToLastToken = sourceCode.getTokenBefore(lastToken);
  196. if (astUtils.isCommaToken(nextToLastToken)) {
  197. validateCommaItemSpacing(
  198. sourceCode.getTokenBefore(nextToLastToken),
  199. nextToLastToken,
  200. lastToken,
  201. lastToken
  202. );
  203. }
  204. }
  205. }
  206. }
  207. //--------------------------------------------------------------------------
  208. // Public
  209. //--------------------------------------------------------------------------
  210. const nodes = {};
  211. if (!exceptions.VariableDeclaration) {
  212. nodes.VariableDeclaration = function(node) {
  213. validateComma(node, "declarations");
  214. };
  215. }
  216. if (!exceptions.ObjectExpression) {
  217. nodes.ObjectExpression = function(node) {
  218. validateComma(node, "properties");
  219. };
  220. }
  221. if (!exceptions.ObjectPattern) {
  222. nodes.ObjectPattern = function(node) {
  223. validateComma(node, "properties");
  224. };
  225. }
  226. if (!exceptions.ArrayExpression) {
  227. nodes.ArrayExpression = function(node) {
  228. validateComma(node, "elements");
  229. };
  230. }
  231. if (!exceptions.ArrayPattern) {
  232. nodes.ArrayPattern = function(node) {
  233. validateComma(node, "elements");
  234. };
  235. }
  236. if (!exceptions.FunctionDeclaration) {
  237. nodes.FunctionDeclaration = function(node) {
  238. validateComma(node, "params");
  239. };
  240. }
  241. if (!exceptions.FunctionExpression) {
  242. nodes.FunctionExpression = function(node) {
  243. validateComma(node, "params");
  244. };
  245. }
  246. if (!exceptions.ArrowFunctionExpression) {
  247. nodes.ArrowFunctionExpression = function(node) {
  248. validateComma(node, "params");
  249. };
  250. }
  251. if (!exceptions.CallExpression) {
  252. nodes.CallExpression = function(node) {
  253. validateComma(node, "arguments");
  254. };
  255. }
  256. if (!exceptions.ImportDeclaration) {
  257. nodes.ImportDeclaration = function(node) {
  258. validateComma(node, "specifiers");
  259. };
  260. }
  261. if (!exceptions.NewExpression) {
  262. nodes.NewExpression = function(node) {
  263. validateComma(node, "arguments");
  264. };
  265. }
  266. return nodes;
  267. }
  268. };