]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/arrow-body-style.js
3a3f544444e99c69ced5af94a9e368f28d470c5e
[pve-eslint.git] / eslint / lib / rules / arrow-body-style.js
1 /**
2 * @fileoverview Rule to require braces in arrow function body.
3 * @author Alberto Rodríguez
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: "require braces around arrow function bodies",
23 recommended: false,
24 url: "https://eslint.org/docs/rules/arrow-body-style"
25 },
26
27 schema: {
28 anyOf: [
29 {
30 type: "array",
31 items: [
32 {
33 enum: ["always", "never"]
34 }
35 ],
36 minItems: 0,
37 maxItems: 1
38 },
39 {
40 type: "array",
41 items: [
42 {
43 enum: ["as-needed"]
44 },
45 {
46 type: "object",
47 properties: {
48 requireReturnForObjectLiteral: { type: "boolean" }
49 },
50 additionalProperties: false
51 }
52 ],
53 minItems: 0,
54 maxItems: 2
55 }
56 ]
57 },
58
59 fixable: "code",
60
61 messages: {
62 unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.",
63 unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.",
64 unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.",
65 unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.",
66 expectedBlock: "Expected block statement surrounding arrow body."
67 }
68 },
69
70 create(context) {
71 const options = context.options;
72 const always = options[0] === "always";
73 const asNeeded = !options[0] || options[0] === "as-needed";
74 const never = options[0] === "never";
75 const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
76 const sourceCode = context.getSourceCode();
77 let funcInfo = null;
78
79 /**
80 * Checks whether the given node has ASI problem or not.
81 * @param {Token} token The token to check.
82 * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed.
83 */
84 function hasASIProblem(token) {
85 return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value);
86 }
87
88 /**
89 * Gets the closing parenthesis by the given node.
90 * @param {ASTNode} node first node after an opening parenthesis.
91 * @returns {Token} The found closing parenthesis token.
92 */
93 function findClosingParen(node) {
94 let nodeToCheck = node;
95
96 while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) {
97 nodeToCheck = nodeToCheck.parent;
98 }
99 return sourceCode.getTokenAfter(nodeToCheck);
100 }
101
102 /**
103 * Check whether the node is inside of a for loop's init
104 * @param {ASTNode} node node is inside for loop
105 * @returns {boolean} `true` if the node is inside of a for loop, else `false`
106 */
107 function isInsideForLoopInitializer(node) {
108 if (node && node.parent) {
109 if (node.parent.type === "ForStatement" && node.parent.init === node) {
110 return true;
111 }
112 return isInsideForLoopInitializer(node.parent);
113 }
114 return false;
115 }
116
117 /**
118 * Determines whether a arrow function body needs braces
119 * @param {ASTNode} node The arrow function node.
120 * @returns {void}
121 */
122 function validate(node) {
123 const arrowBody = node.body;
124
125 if (arrowBody.type === "BlockStatement") {
126 const blockBody = arrowBody.body;
127
128 if (blockBody.length !== 1 && !never) {
129 return;
130 }
131
132 if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" &&
133 blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") {
134 return;
135 }
136
137 if (never || asNeeded && blockBody[0].type === "ReturnStatement") {
138 let messageId;
139
140 if (blockBody.length === 0) {
141 messageId = "unexpectedEmptyBlock";
142 } else if (blockBody.length > 1) {
143 messageId = "unexpectedOtherBlock";
144 } else if (blockBody[0].argument === null) {
145 messageId = "unexpectedSingleBlock";
146 } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], { skip: 1 }))) {
147 messageId = "unexpectedObjectBlock";
148 } else {
149 messageId = "unexpectedSingleBlock";
150 }
151
152 context.report({
153 node,
154 loc: arrowBody.loc,
155 messageId,
156 fix(fixer) {
157 const fixes = [];
158
159 if (blockBody.length !== 1 ||
160 blockBody[0].type !== "ReturnStatement" ||
161 !blockBody[0].argument ||
162 hasASIProblem(sourceCode.getTokenAfter(arrowBody))
163 ) {
164 return fixes;
165 }
166
167 const openingBrace = sourceCode.getFirstToken(arrowBody);
168 const closingBrace = sourceCode.getLastToken(arrowBody);
169 const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1);
170 const lastValueToken = sourceCode.getLastToken(blockBody[0]);
171 const commentsExist =
172 sourceCode.commentsExistBetween(openingBrace, firstValueToken) ||
173 sourceCode.commentsExistBetween(lastValueToken, closingBrace);
174
175 /*
176 * Remove tokens around the return value.
177 * If comments don't exist, remove extra spaces as well.
178 */
179 if (commentsExist) {
180 fixes.push(
181 fixer.remove(openingBrace),
182 fixer.remove(closingBrace),
183 fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword
184 );
185 } else {
186 fixes.push(
187 fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]),
188 fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]])
189 );
190 }
191
192 /*
193 * If the first token of the return value is `{` or the return value is a sequence expression,
194 * enclose the return value by parentheses to avoid syntax error.
195 */
196 if (astUtils.isOpeningBraceToken(firstValueToken) || blockBody[0].argument.type === "SequenceExpression" || (funcInfo.hasInOperator && isInsideForLoopInitializer(node))) {
197 if (!astUtils.isParenthesised(sourceCode, blockBody[0].argument)) {
198 fixes.push(
199 fixer.insertTextBefore(firstValueToken, "("),
200 fixer.insertTextAfter(lastValueToken, ")")
201 );
202 }
203 }
204
205 /*
206 * If the last token of the return statement is semicolon, remove it.
207 * Non-block arrow body is an expression, not a statement.
208 */
209 if (astUtils.isSemicolonToken(lastValueToken)) {
210 fixes.push(fixer.remove(lastValueToken));
211 }
212
213 return fixes;
214 }
215 });
216 }
217 } else {
218 if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) {
219 context.report({
220 node,
221 loc: arrowBody.loc,
222 messageId: "expectedBlock",
223 fix(fixer) {
224 const fixes = [];
225 const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken);
226 const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, { count: 2 });
227 const lastToken = sourceCode.getLastToken(node);
228
229 let parenthesisedObjectLiteral = null;
230
231 if (
232 astUtils.isOpeningParenToken(firstTokenAfterArrow) &&
233 astUtils.isOpeningBraceToken(secondTokenAfterArrow)
234 ) {
235 const braceNode = sourceCode.getNodeByRangeIndex(secondTokenAfterArrow.range[0]);
236
237 if (braceNode.type === "ObjectExpression") {
238 parenthesisedObjectLiteral = braceNode;
239 }
240 }
241
242 // If the value is object literal, remove parentheses which were forced by syntax.
243 if (parenthesisedObjectLiteral) {
244 const openingParenToken = firstTokenAfterArrow;
245 const openingBraceToken = secondTokenAfterArrow;
246
247 if (astUtils.isTokenOnSameLine(openingParenToken, openingBraceToken)) {
248 fixes.push(fixer.replaceText(openingParenToken, "{return "));
249 } else {
250
251 // Avoid ASI
252 fixes.push(
253 fixer.replaceText(openingParenToken, "{"),
254 fixer.insertTextBefore(openingBraceToken, "return ")
255 );
256 }
257
258 // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo()
259 fixes.push(fixer.remove(findClosingParen(parenthesisedObjectLiteral)));
260 fixes.push(fixer.insertTextAfter(lastToken, "}"));
261
262 } else {
263 fixes.push(fixer.insertTextBefore(firstTokenAfterArrow, "{return "));
264 fixes.push(fixer.insertTextAfter(lastToken, "}"));
265 }
266
267 return fixes;
268 }
269 });
270 }
271 }
272 }
273
274 return {
275 "BinaryExpression[operator='in']"() {
276 let info = funcInfo;
277
278 while (info) {
279 info.hasInOperator = true;
280 info = info.upper;
281 }
282 },
283 ArrowFunctionExpression() {
284 funcInfo = {
285 upper: funcInfo,
286 hasInOperator: false
287 };
288 },
289 "ArrowFunctionExpression:exit"(node) {
290 validate(node);
291 funcInfo = funcInfo.upper;
292 }
293 };
294 }
295 };