Actualizacion maquina principal
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / rules / curly.js
1 /**
2  * @fileoverview Rule to flag statements without curly braces
3  * @author Nicholas C. Zakas
4  */
5 "use strict";
6
7 //------------------------------------------------------------------------------
8 // Requirements
9 //------------------------------------------------------------------------------
10
11 const astUtils = require("./utils/ast-utils");
12
13 //------------------------------------------------------------------------------
14 // Rule Definition
15 //------------------------------------------------------------------------------
16
17 module.exports = {
18     meta: {
19         type: "suggestion",
20
21         docs: {
22             description: "enforce consistent brace style for all control statements",
23             category: "Best Practices",
24             recommended: false,
25             url: "https://eslint.org/docs/rules/curly"
26         },
27
28         schema: {
29             anyOf: [
30                 {
31                     type: "array",
32                     items: [
33                         {
34                             enum: ["all"]
35                         }
36                     ],
37                     minItems: 0,
38                     maxItems: 1
39                 },
40                 {
41                     type: "array",
42                     items: [
43                         {
44                             enum: ["multi", "multi-line", "multi-or-nest"]
45                         },
46                         {
47                             enum: ["consistent"]
48                         }
49                     ],
50                     minItems: 0,
51                     maxItems: 2
52                 }
53             ]
54         },
55
56         fixable: "code",
57
58         messages: {
59             missingCurlyAfter: "Expected { after '{{name}}'.",
60             missingCurlyAfterCondition: "Expected { after '{{name}}' condition.",
61             unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.",
62             unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition."
63         }
64     },
65
66     create(context) {
67
68         const multiOnly = (context.options[0] === "multi");
69         const multiLine = (context.options[0] === "multi-line");
70         const multiOrNest = (context.options[0] === "multi-or-nest");
71         const consistent = (context.options[1] === "consistent");
72
73         const sourceCode = context.getSourceCode();
74
75         //--------------------------------------------------------------------------
76         // Helpers
77         //--------------------------------------------------------------------------
78
79         /**
80          * Determines if a given node is a one-liner that's on the same line as it's preceding code.
81          * @param {ASTNode} node The node to check.
82          * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code.
83          * @private
84          */
85         function isCollapsedOneLiner(node) {
86             const before = sourceCode.getTokenBefore(node);
87             const last = sourceCode.getLastToken(node);
88             const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
89
90             return before.loc.start.line === lastExcludingSemicolon.loc.end.line;
91         }
92
93         /**
94          * Determines if a given node is a one-liner.
95          * @param {ASTNode} node The node to check.
96          * @returns {boolean} True if the node is a one-liner.
97          * @private
98          */
99         function isOneLiner(node) {
100             if (node.type === "EmptyStatement") {
101                 return true;
102             }
103
104             const first = sourceCode.getFirstToken(node);
105             const last = sourceCode.getLastToken(node);
106             const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
107
108             return first.loc.start.line === lastExcludingSemicolon.loc.end.line;
109         }
110
111         /**
112          * Determines if the given node is a lexical declaration (let, const, function, or class)
113          * @param {ASTNode} node The node to check
114          * @returns {boolean} True if the node is a lexical declaration
115          * @private
116          */
117         function isLexicalDeclaration(node) {
118             if (node.type === "VariableDeclaration") {
119                 return node.kind === "const" || node.kind === "let";
120             }
121
122             return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration";
123         }
124
125         /**
126          * Checks if the given token is an `else` token or not.
127          * @param {Token} token The token to check.
128          * @returns {boolean} `true` if the token is an `else` token.
129          */
130         function isElseKeywordToken(token) {
131             return token.value === "else" && token.type === "Keyword";
132         }
133
134         /**
135          * Gets the `else` keyword token of a given `IfStatement` node.
136          * @param {ASTNode} node A `IfStatement` node to get.
137          * @returns {Token} The `else` keyword token.
138          */
139         function getElseKeyword(node) {
140             return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
141         }
142
143         /**
144          * Checks a given IfStatement node requires braces of the consequent chunk.
145          * This returns `true` when below:
146          *
147          * 1. The given node has the `alternate` node.
148          * 2. There is a `IfStatement` which doesn't have `alternate` node in the
149          *    trailing statement chain of the `consequent` node.
150          * @param {ASTNode} node A IfStatement node to check.
151          * @returns {boolean} `true` if the node requires braces of the consequent chunk.
152          */
153         function requiresBraceOfConsequent(node) {
154             if (node.alternate && node.consequent.type === "BlockStatement") {
155                 if (node.consequent.body.length >= 2) {
156                     return true;
157                 }
158
159                 for (
160                     let currentNode = node.consequent.body[0];
161                     currentNode;
162                     currentNode = astUtils.getTrailingStatement(currentNode)
163                 ) {
164                     if (currentNode.type === "IfStatement" && !currentNode.alternate) {
165                         return true;
166                     }
167                 }
168             }
169
170             return false;
171         }
172
173         /**
174          * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
175          * @param {Token} closingBracket The } token
176          * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
177          */
178         function needsSemicolon(closingBracket) {
179             const tokenBefore = sourceCode.getTokenBefore(closingBracket);
180             const tokenAfter = sourceCode.getTokenAfter(closingBracket);
181             const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
182
183             if (astUtils.isSemicolonToken(tokenBefore)) {
184
185                 // If the last statement already has a semicolon, don't add another one.
186                 return false;
187             }
188
189             if (!tokenAfter) {
190
191                 // If there are no statements after this block, there is no need to add a semicolon.
192                 return false;
193             }
194
195             if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
196
197                 /*
198                  * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
199                  * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
200                  * a SyntaxError if it was followed by `else`.
201                  */
202                 return false;
203             }
204
205             if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
206
207                 // If the next token is on the same line, insert a semicolon.
208                 return true;
209             }
210
211             if (/^[([/`+-]/u.test(tokenAfter.value)) {
212
213                 // If the next token starts with a character that would disrupt ASI, insert a semicolon.
214                 return true;
215             }
216
217             if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
218
219                 // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
220                 return true;
221             }
222
223             // Otherwise, do not insert a semicolon.
224             return false;
225         }
226
227         /**
228          * Prepares to check the body of a node to see if it's a block statement.
229          * @param {ASTNode} node The node to report if there's a problem.
230          * @param {ASTNode} body The body node to check for blocks.
231          * @param {string} name The name to report if there's a problem.
232          * @param {{ condition: boolean }} opts Options to pass to the report functions
233          * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
234          *   "actual" will be `true` or `false` whether the body is already a block statement.
235          *   "expected" will be `true` or `false` if the body should be a block statement or not, or
236          *   `null` if it doesn't matter, depending on the rule options. It can be modified to change
237          *   the final behavior of "check".
238          *   "check" will be a function reporting appropriate problems depending on the other
239          *   properties.
240          */
241         function prepareCheck(node, body, name, opts) {
242             const hasBlock = (body.type === "BlockStatement");
243             let expected = null;
244
245             if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
246                 expected = true;
247             } else if (multiOnly) {
248                 if (hasBlock && body.body.length === 1 && !isLexicalDeclaration(body.body[0])) {
249                     expected = false;
250                 }
251             } else if (multiLine) {
252                 if (!isCollapsedOneLiner(body)) {
253                     expected = true;
254                 }
255             } else if (multiOrNest) {
256                 if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) {
257                     const leadingComments = sourceCode.getCommentsBefore(body.body[0]);
258                     const isLexDef = isLexicalDeclaration(body.body[0]);
259
260                     if (isLexDef) {
261                         expected = true;
262                     } else {
263                         expected = leadingComments.length > 0;
264                     }
265                 } else if (!isOneLiner(body)) {
266                     expected = true;
267                 }
268             } else {
269                 expected = true;
270             }
271
272             return {
273                 actual: hasBlock,
274                 expected,
275                 check() {
276                     if (this.expected !== null && this.expected !== this.actual) {
277                         if (this.expected) {
278                             context.report({
279                                 node,
280                                 loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
281                                 messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
282                                 data: {
283                                     name
284                                 },
285                                 fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
286                             });
287                         } else {
288                             context.report({
289                                 node,
290                                 loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
291                                 messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
292                                 data: {
293                                     name
294                                 },
295                                 fix(fixer) {
296
297                                     /*
298                                      * `do while` expressions sometimes need a space to be inserted after `do`.
299                                      * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
300                                      */
301                                     const needsPrecedingSpace = node.type === "DoWhileStatement" &&
302                                         sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
303                                         !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
304
305                                     const openingBracket = sourceCode.getFirstToken(body);
306                                     const closingBracket = sourceCode.getLastToken(body);
307                                     const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
308
309                                     if (needsSemicolon(closingBracket)) {
310
311                                         /*
312                                          * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
313                                          * change the semantics of the code due to ASI), don't perform a fix.
314                                          */
315                                         return null;
316                                     }
317
318                                     const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
319                                         sourceCode.getText(lastTokenInBlock) +
320                                         sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
321
322                                     return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
323                                 }
324                             });
325                         }
326                     }
327                 }
328             };
329         }
330
331         /**
332          * Prepares to check the bodies of a "if", "else if" and "else" chain.
333          * @param {ASTNode} node The first IfStatement node of the chain.
334          * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
335          *   information.
336          */
337         function prepareIfChecks(node) {
338             const preparedChecks = [];
339
340             for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
341                 preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
342                 if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
343                     preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
344                     break;
345                 }
346             }
347
348             if (consistent) {
349
350                 /*
351                  * If any node should have or already have braces, make sure they
352                  * all have braces.
353                  * If all nodes shouldn't have braces, make sure they don't.
354                  */
355                 const expected = preparedChecks.some(preparedCheck => {
356                     if (preparedCheck.expected !== null) {
357                         return preparedCheck.expected;
358                     }
359                     return preparedCheck.actual;
360                 });
361
362                 preparedChecks.forEach(preparedCheck => {
363                     preparedCheck.expected = expected;
364                 });
365             }
366
367             return preparedChecks;
368         }
369
370         //--------------------------------------------------------------------------
371         // Public
372         //--------------------------------------------------------------------------
373
374         return {
375             IfStatement(node) {
376                 if (node.parent.type !== "IfStatement") {
377                     prepareIfChecks(node).forEach(preparedCheck => {
378                         preparedCheck.check();
379                     });
380                 }
381             },
382
383             WhileStatement(node) {
384                 prepareCheck(node, node.body, "while", { condition: true }).check();
385             },
386
387             DoWhileStatement(node) {
388                 prepareCheck(node, node.body, "do").check();
389             },
390
391             ForStatement(node) {
392                 prepareCheck(node, node.body, "for", { condition: true }).check();
393             },
394
395             ForInStatement(node) {
396                 prepareCheck(node, node.body, "for-in").check();
397             },
398
399             ForOfStatement(node) {
400                 prepareCheck(node, node.body, "for-of").check();
401             }
402         };
403     }
404 };