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",
24 url
: "https://eslint.org/docs/rules/arrow-body-style"
33 enum: ["always", "never"]
48 requireReturnForObjectLiteral
: { type
: "boolean" }
50 additionalProperties
: false
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."
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();
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.
84 function hasASIProblem(token
) {
85 return token
&& token
.type
=== "Punctuator" && /^[([/`+-]/u.test(token.value);
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.
93 function findClosingParen(node) {
94 let nodeToCheck = node;
96 while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) {
97 nodeToCheck = nodeToCheck.parent;
99 return sourceCode.getTokenAfter(nodeToCheck);
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`
107 function isInsideForLoopInitializer(node) {
108 if (node && node.parent) {
109 if (node.parent.type === "ForStatement" && node.parent.init === node) {
112 return isInsideForLoopInitializer(node.parent);
118 * Determines whether a arrow function body needs braces
119 * @param {ASTNode} node The arrow function node.
122 function validate(node) {
123 const arrowBody = node.body;
125 if (arrowBody.type === "BlockStatement") {
126 const blockBody = arrowBody.body;
128 if (blockBody.length !== 1 && !never) {
132 if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" &&
133 blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") {
137 if (never || asNeeded && blockBody[0].type === "ReturnStatement") {
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";
149 messageId = "unexpectedSingleBlock";
159 if (blockBody.length !== 1 ||
160 blockBody[0].type !== "ReturnStatement" ||
161 !blockBody[0].argument ||
162 hasASIProblem(sourceCode.getTokenAfter(arrowBody))
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);
176 * Remove tokens around the return value.
177 * If comments don't exist, remove extra spaces as well.
181 fixer.remove(openingBrace),
182 fixer.remove(closingBrace),
183 fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword
187 fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]),
188 fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]])
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.
196 if (astUtils.isOpeningBraceToken(firstValueToken) || blockBody[0].argument.type === "SequenceExpression" || (funcInfo.hasInOperator && isInsideForLoopInitializer(node))) {
197 if (!astUtils.isParenthesised(sourceCode, blockBody[0].argument)) {
199 fixer.insertTextBefore(firstValueToken, "("),
200 fixer.insertTextAfter(lastValueToken, ")")
206 * If the last token of the return statement is semicolon, remove it.
207 * Non-block arrow body is an expression, not a statement.
209 if (astUtils.isSemicolonToken(lastValueToken)) {
210 fixes.push(fixer.remove(lastValueToken));
218 if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) {
222 messageId: "expectedBlock",
225 const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken);
226 const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, { count: 2 });
227 const lastToken = sourceCode.getLastToken(node);
229 let parenthesisedObjectLiteral = null;
232 astUtils.isOpeningParenToken(firstTokenAfterArrow) &&
233 astUtils.isOpeningBraceToken(secondTokenAfterArrow)
235 const braceNode = sourceCode.getNodeByRangeIndex(secondTokenAfterArrow.range[0]);
237 if (braceNode.type === "ObjectExpression") {
238 parenthesisedObjectLiteral = braceNode;
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;
247 if (astUtils.isTokenOnSameLine(openingParenToken, openingBraceToken)) {
248 fixes.push(fixer.replaceText(openingParenToken, "{return "));
253 fixer.replaceText(openingParenToken, "{"),
254 fixer.insertTextBefore(openingBraceToken, "return ")
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, "}"));
263 fixes.push(fixer.insertTextBefore(firstTokenAfterArrow, "{return "));
264 fixes.push(fixer.insertTextAfter(lastToken, "}"));
275 "BinaryExpression[operator='in']"() {
279 info.hasInOperator = true;
283 ArrowFunctionExpression() {
289 "ArrowFunctionExpression:exit"(node) {
291 funcInfo = funcInfo.upper;