2 * @fileoverview Comma style - enforces comma styles of two types: last and first
3 * @author Vignesh Anand aka vegetableman
8 const astUtils = require("./utils/ast-utils");
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
19 description: "enforce consistent comma style",
20 category: "Stylistic Issues",
22 url: "https://eslint.org/docs/rules/comma-style"
29 enum: ["first", "last"]
36 additionalProperties: {
41 additionalProperties: false
46 unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.",
47 expectedCommaFirst: "',' should be placed first.",
48 expectedCommaLast: "',' should be placed last."
53 const style = context.options[0] || "last",
54 sourceCode = context.getSourceCode();
57 ArrowFunctionExpression: true,
59 FunctionDeclaration: true,
60 FunctionExpression: true,
61 ImportDeclaration: true,
66 if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) {
67 const keys = Object.keys(context.options[1].exceptions);
69 for (let i = 0; i < keys.length; i++) {
70 exceptions[keys[i]] = context.options[1].exceptions[keys[i]];
74 //--------------------------------------------------------------------------
76 //--------------------------------------------------------------------------
79 * Modified text based on the style
80 * @param {string} styleType Style type
81 * @param {string} text Source code text
82 * @returns {string} modified text
85 function getReplacedText(styleType, text) {
88 return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`;
102 * Determines the fixer function for a given style.
103 * @param {string} styleType comma style
104 * @param {ASTNode} previousItemToken The token to check.
105 * @param {ASTNode} commaToken The token to check.
106 * @param {ASTNode} currentItemToken The token to check.
107 * @returns {Function} Fixer function
110 function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
112 sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
113 sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
114 const range = [previousItemToken.range[1], currentItemToken.range[0]];
116 return function(fixer) {
117 return fixer.replaceTextRange(range, getReplacedText(styleType, text));
122 * Validates the spacing around single items in lists.
123 * @param {Token} previousItemToken The last token from the previous item.
124 * @param {Token} commaToken The token representing the comma.
125 * @param {Token} currentItemToken The first token of the current item.
126 * @param {Token} reportItem The item to use when reporting an error.
130 function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
133 if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
134 astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
138 } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
139 !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
141 const comment = sourceCode.getCommentsAfter(commaToken)[0];
142 const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment)
150 line: commaToken.loc.end.line,
151 column: commaToken.loc.start.column
153 messageId: "unexpectedLineBeforeAndAfterComma",
154 fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
157 } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
161 messageId: "expectedCommaFirst",
162 fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
165 } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
170 line: commaToken.loc.end.line,
171 column: commaToken.loc.end.column
173 messageId: "expectedCommaLast",
174 fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
180 * Checks the comma placement with regards to a declaration/property/element
181 * @param {ASTNode} node The binary expression node to check
182 * @param {string} property The property of the node containing child nodes.
186 function validateComma(node, property) {
187 const items = node[property],
188 arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern");
190 if (items.length > 1 || arrayLiteral) {
193 let previousItemToken = sourceCode.getFirstToken(node);
195 items.forEach(item => {
196 const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken,
197 currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken),
198 reportItem = item || currentItemToken;
201 * This works by comparing three token locations:
202 * - previousItemToken is the last token of the previous item
203 * - commaToken is the location of the comma before the current item
204 * - currentItemToken is the first token of the current item
206 * These values get switched around if item is undefined.
207 * previousItemToken will refer to the last token not belonging
208 * to the current item, which could be a comma or an opening
209 * square bracket. currentItemToken could be a comma.
211 * All comparisons are done based on these tokens directly, so
212 * they are always valid regardless of an undefined item.
214 if (astUtils.isCommaToken(commaToken)) {
215 validateCommaItemSpacing(previousItemToken, commaToken,
216 currentItemToken, reportItem);
220 const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken);
222 previousItemToken = tokenAfterItem
223 ? sourceCode.getTokenBefore(tokenAfterItem)
224 : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1];
229 * Special case for array literals that have empty last items, such
230 * as [ 1, 2, ]. These arrays only have two items show up in the
231 * AST, so we need to look at the token to verify that there's no
236 const lastToken = sourceCode.getLastToken(node),
237 nextToLastToken = sourceCode.getTokenBefore(lastToken);
239 if (astUtils.isCommaToken(nextToLastToken)) {
240 validateCommaItemSpacing(
241 sourceCode.getTokenBefore(nextToLastToken),
251 //--------------------------------------------------------------------------
253 //--------------------------------------------------------------------------
257 if (!exceptions.VariableDeclaration) {
258 nodes.VariableDeclaration = function(node) {
259 validateComma(node, "declarations");
262 if (!exceptions.ObjectExpression) {
263 nodes.ObjectExpression = function(node) {
264 validateComma(node, "properties");
267 if (!exceptions.ObjectPattern) {
268 nodes.ObjectPattern = function(node) {
269 validateComma(node, "properties");
272 if (!exceptions.ArrayExpression) {
273 nodes.ArrayExpression = function(node) {
274 validateComma(node, "elements");
277 if (!exceptions.ArrayPattern) {
278 nodes.ArrayPattern = function(node) {
279 validateComma(node, "elements");
282 if (!exceptions.FunctionDeclaration) {
283 nodes.FunctionDeclaration = function(node) {
284 validateComma(node, "params");
287 if (!exceptions.FunctionExpression) {
288 nodes.FunctionExpression = function(node) {
289 validateComma(node, "params");
292 if (!exceptions.ArrowFunctionExpression) {
293 nodes.ArrowFunctionExpression = function(node) {
294 validateComma(node, "params");
297 if (!exceptions.CallExpression) {
298 nodes.CallExpression = function(node) {
299 validateComma(node, "arguments");
302 if (!exceptions.ImportDeclaration) {
303 nodes.ImportDeclaration = function(node) {
304 validateComma(node, "specifiers");
307 if (!exceptions.NewExpression) {
308 nodes.NewExpression = function(node) {
309 validateComma(node, "arguments");