UNPKG

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