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