2 * @fileoverview Rule to require braces in arrow function body.
3 * @author Alberto RodrÃguez
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils = require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
22 description: "require braces around arrow function bodies",
23 category: "ECMAScript 6",
25 url: "https://eslint.org/docs/rules/arrow-body-style"
34 enum: ["always", "never"]
49 requireReturnForObjectLiteral: { type: "boolean" }
51 additionalProperties: false
63 unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.",
64 unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.",
65 unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.",
66 unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.",
67 expectedBlock: "Expected block statement surrounding arrow body."
72 const options = context.options;
73 const always = options[0] === "always";
74 const asNeeded = !options[0] || options[0] === "as-needed";
75 const never = options[0] === "never";
76 const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
77 const sourceCode = context.getSourceCode();
81 * Checks whether the given node has ASI problem or not.
82 * @param {Token} token The token to check.
83 * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed.
85 function hasASIProblem(token) {
86 return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value);
90 * Gets the closing parenthesis by the given node.
91 * @param {ASTNode} node first node after an opening parenthesis.
92 * @returns {Token} The found closing parenthesis token.
94 function findClosingParen(node) {
95 let nodeToCheck = node;
97 while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) {
98 nodeToCheck = nodeToCheck.parent;
100 return sourceCode.getTokenAfter(nodeToCheck);
104 * Check whether the node is inside of a for loop's init
105 * @param {ASTNode} node node is inside for loop
106 * @returns {boolean} `true` if the node is inside of a for loop, else `false`
108 function isInsideForLoopInitializer(node) {
109 if (node && node.parent) {
110 if (node.parent.type === "ForStatement" && node.parent.init === node) {
113 return isInsideForLoopInitializer(node.parent);
119 * Determines whether a arrow function body needs braces
120 * @param {ASTNode} node The arrow function node.
123 function validate(node) {
124 const arrowBody = node.body;
126 if (arrowBody.type === "BlockStatement") {
127 const blockBody = arrowBody.body;
129 if (blockBody.length !== 1 && !never) {
133 if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" &&
134 blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") {
138 if (never || asNeeded && blockBody[0].type === "ReturnStatement") {
141 if (blockBody.length === 0) {
142 messageId = "unexpectedEmptyBlock";
143 } else if (blockBody.length > 1) {
144 messageId = "unexpectedOtherBlock";
145 } else if (blockBody[0].argument === null) {
146 messageId = "unexpectedSingleBlock";
147 } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], { skip: 1 }))) {
148 messageId = "unexpectedObjectBlock";
150 messageId = "unexpectedSingleBlock";
160 if (blockBody.length !== 1 ||
161 blockBody[0].type !== "ReturnStatement" ||
162 !blockBody[0].argument ||
163 hasASIProblem(sourceCode.getTokenAfter(arrowBody))
168 const openingBrace = sourceCode.getFirstToken(arrowBody);
169 const closingBrace = sourceCode.getLastToken(arrowBody);
170 const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1);
171 const lastValueToken = sourceCode.getLastToken(blockBody[0]);
172 const commentsExist =
173 sourceCode.commentsExistBetween(openingBrace, firstValueToken) ||
174 sourceCode.commentsExistBetween(lastValueToken, closingBrace);
177 * Remove tokens around the return value.
178 * If comments don't exist, remove extra spaces as well.
182 fixer.remove(openingBrace),
183 fixer.remove(closingBrace),
184 fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword
188 fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]),
189 fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]])
194 * If the first token of the return value is `{` or the return value is a sequence expression,
195 * enclose the return value by parentheses to avoid syntax error.
197 if (astUtils.isOpeningBraceToken(firstValueToken) || blockBody[0].argument.type === "SequenceExpression" || (funcInfo.hasInOperator && isInsideForLoopInitializer(node))) {
198 if (!astUtils.isParenthesised(sourceCode, blockBody[0].argument)) {
200 fixer.insertTextBefore(firstValueToken, "("),
201 fixer.insertTextAfter(lastValueToken, ")")
207 * If the last token of the return statement is semicolon, remove it.
208 * Non-block arrow body is an expression, not a statement.
210 if (astUtils.isSemicolonToken(lastValueToken)) {
211 fixes.push(fixer.remove(lastValueToken));
219 if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) {
223 messageId: "expectedBlock",
226 const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken);
227 const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, { count: 2 });
228 const lastToken = sourceCode.getLastToken(node);
230 let parenthesisedObjectLiteral = null;
233 astUtils.isOpeningParenToken(firstTokenAfterArrow) &&
234 astUtils.isOpeningBraceToken(secondTokenAfterArrow)
236 const braceNode = sourceCode.getNodeByRangeIndex(secondTokenAfterArrow.range[0]);
238 if (braceNode.type === "ObjectExpression") {
239 parenthesisedObjectLiteral = braceNode;
243 // If the value is object literal, remove parentheses which were forced by syntax.
244 if (parenthesisedObjectLiteral) {
245 const openingParenToken = firstTokenAfterArrow;
246 const openingBraceToken = secondTokenAfterArrow;
248 if (astUtils.isTokenOnSameLine(openingParenToken, openingBraceToken)) {
249 fixes.push(fixer.replaceText(openingParenToken, "{return "));
254 fixer.replaceText(openingParenToken, "{"),
255 fixer.insertTextBefore(openingBraceToken, "return ")
259 // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo()
260 fixes.push(fixer.remove(findClosingParen(parenthesisedObjectLiteral)));
261 fixes.push(fixer.insertTextAfter(lastToken, "}"));
264 fixes.push(fixer.insertTextBefore(firstTokenAfterArrow, "{return "));
265 fixes.push(fixer.insertTextAfter(lastToken, "}"));
276 "BinaryExpression[operator='in']"() {
280 info.hasInOperator = true;
284 ArrowFunctionExpression() {
290 "ArrowFunctionExpression:exit"(node) {
292 funcInfo = funcInfo.upper;