Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

306 lignes
12 KiB

  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("../util/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description: "enforce consistent comma style",
  14. category: "Stylistic Issues",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/comma-style"
  17. },
  18. fixable: "code",
  19. schema: [
  20. {
  21. enum: ["first", "last"]
  22. },
  23. {
  24. type: "object",
  25. properties: {
  26. exceptions: {
  27. type: "object",
  28. additionalProperties: {
  29. type: "boolean"
  30. }
  31. }
  32. },
  33. additionalProperties: false
  34. }
  35. ],
  36. messages: {
  37. unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.",
  38. expectedCommaFirst: "',' should be placed first.",
  39. expectedCommaLast: "',' should be placed last."
  40. }
  41. },
  42. create(context) {
  43. const style = context.options[0] || "last",
  44. sourceCode = context.getSourceCode();
  45. const exceptions = {
  46. ArrayPattern: true,
  47. ArrowFunctionExpression: true,
  48. CallExpression: true,
  49. FunctionDeclaration: true,
  50. FunctionExpression: true,
  51. ImportDeclaration: true,
  52. ObjectPattern: true,
  53. NewExpression: true
  54. };
  55. if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) {
  56. const keys = Object.keys(context.options[1].exceptions);
  57. for (let i = 0; i < keys.length; i++) {
  58. exceptions[keys[i]] = context.options[1].exceptions[keys[i]];
  59. }
  60. }
  61. //--------------------------------------------------------------------------
  62. // Helpers
  63. //--------------------------------------------------------------------------
  64. /**
  65. * Modified text based on the style
  66. * @param {string} styleType Style type
  67. * @param {string} text Source code text
  68. * @returns {string} modified text
  69. * @private
  70. */
  71. function getReplacedText(styleType, text) {
  72. switch (styleType) {
  73. case "between":
  74. return `,${text.replace("\n", "")}`;
  75. case "first":
  76. return `${text},`;
  77. case "last":
  78. return `,${text}`;
  79. default:
  80. return "";
  81. }
  82. }
  83. /**
  84. * Determines the fixer function for a given style.
  85. * @param {string} styleType comma style
  86. * @param {ASTNode} previousItemToken The token to check.
  87. * @param {ASTNode} commaToken The token to check.
  88. * @param {ASTNode} currentItemToken The token to check.
  89. * @returns {Function} Fixer function
  90. * @private
  91. */
  92. function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
  93. const text =
  94. sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
  95. sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
  96. const range = [previousItemToken.range[1], currentItemToken.range[0]];
  97. return function(fixer) {
  98. return fixer.replaceTextRange(range, getReplacedText(styleType, text));
  99. };
  100. }
  101. /**
  102. * Validates the spacing around single items in lists.
  103. * @param {Token} previousItemToken The last token from the previous item.
  104. * @param {Token} commaToken The token representing the comma.
  105. * @param {Token} currentItemToken The first token of the current item.
  106. * @param {Token} reportItem The item to use when reporting an error.
  107. * @returns {void}
  108. * @private
  109. */
  110. function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
  111. // if single line
  112. if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
  113. astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
  114. // do nothing.
  115. } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
  116. !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
  117. // lone comma
  118. context.report({
  119. node: reportItem,
  120. loc: {
  121. line: commaToken.loc.end.line,
  122. column: commaToken.loc.start.column
  123. },
  124. messageId: "unexpectedLineBeforeAndAfterComma",
  125. fix: getFixerFunction("between", previousItemToken, commaToken, currentItemToken)
  126. });
  127. } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
  128. context.report({
  129. node: reportItem,
  130. messageId: "expectedCommaFirst",
  131. fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
  132. });
  133. } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
  134. context.report({
  135. node: reportItem,
  136. loc: {
  137. line: commaToken.loc.end.line,
  138. column: commaToken.loc.end.column
  139. },
  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. };