Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

239 řádky
10 KiB

  1. /**
  2. * @fileoverview Rule to require braces in arrow function body.
  3. * @author Alberto Rodríguez
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. docs: {
  16. description: "require braces around arrow function bodies",
  17. category: "ECMAScript 6",
  18. recommended: false,
  19. url: "https://eslint.org/docs/rules/arrow-body-style"
  20. },
  21. schema: {
  22. anyOf: [
  23. {
  24. type: "array",
  25. items: [
  26. {
  27. enum: ["always", "never"]
  28. }
  29. ],
  30. minItems: 0,
  31. maxItems: 1
  32. },
  33. {
  34. type: "array",
  35. items: [
  36. {
  37. enum: ["as-needed"]
  38. },
  39. {
  40. type: "object",
  41. properties: {
  42. requireReturnForObjectLiteral: { type: "boolean" }
  43. },
  44. additionalProperties: false
  45. }
  46. ],
  47. minItems: 0,
  48. maxItems: 2
  49. }
  50. ]
  51. },
  52. fixable: "code",
  53. messages: {
  54. unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.",
  55. unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.",
  56. unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.",
  57. unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.",
  58. expectedBlock: "Expected block statement surrounding arrow body."
  59. }
  60. },
  61. create(context) {
  62. const options = context.options;
  63. const always = options[0] === "always";
  64. const asNeeded = !options[0] || options[0] === "as-needed";
  65. const never = options[0] === "never";
  66. const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
  67. const sourceCode = context.getSourceCode();
  68. /**
  69. * Checks whether the given node has ASI problem or not.
  70. * @param {Token} token The token to check.
  71. * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed.
  72. */
  73. function hasASIProblem(token) {
  74. return token && token.type === "Punctuator" && /^[([/`+-]/.test(token.value);
  75. }
  76. /**
  77. * Gets the closing parenthesis which is the pair of the given opening parenthesis.
  78. * @param {Token} token The opening parenthesis token to get.
  79. * @returns {Token} The found closing parenthesis token.
  80. */
  81. function findClosingParen(token) {
  82. let node = sourceCode.getNodeByRangeIndex(token.range[1]);
  83. while (!astUtils.isParenthesised(sourceCode, node)) {
  84. node = node.parent;
  85. }
  86. return sourceCode.getTokenAfter(node);
  87. }
  88. /**
  89. * Determines whether a arrow function body needs braces
  90. * @param {ASTNode} node The arrow function node.
  91. * @returns {void}
  92. */
  93. function validate(node) {
  94. const arrowBody = node.body;
  95. if (arrowBody.type === "BlockStatement") {
  96. const blockBody = arrowBody.body;
  97. if (blockBody.length !== 1 && !never) {
  98. return;
  99. }
  100. if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" &&
  101. blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") {
  102. return;
  103. }
  104. if (never || asNeeded && blockBody[0].type === "ReturnStatement") {
  105. let messageId;
  106. if (blockBody.length === 0) {
  107. messageId = "unexpectedEmptyBlock";
  108. } else if (blockBody.length > 1) {
  109. messageId = "unexpectedOtherBlock";
  110. } else if (blockBody[0].argument === null) {
  111. messageId = "unexpectedSingleBlock";
  112. } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], { skip: 1 }))) {
  113. messageId = "unexpectedObjectBlock";
  114. } else {
  115. messageId = "unexpectedSingleBlock";
  116. }
  117. context.report({
  118. node,
  119. loc: arrowBody.loc.start,
  120. messageId,
  121. fix(fixer) {
  122. const fixes = [];
  123. if (blockBody.length !== 1 ||
  124. blockBody[0].type !== "ReturnStatement" ||
  125. !blockBody[0].argument ||
  126. hasASIProblem(sourceCode.getTokenAfter(arrowBody))
  127. ) {
  128. return fixes;
  129. }
  130. const openingBrace = sourceCode.getFirstToken(arrowBody);
  131. const closingBrace = sourceCode.getLastToken(arrowBody);
  132. const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1);
  133. const lastValueToken = sourceCode.getLastToken(blockBody[0]);
  134. const commentsExist =
  135. sourceCode.commentsExistBetween(openingBrace, firstValueToken) ||
  136. sourceCode.commentsExistBetween(lastValueToken, closingBrace);
  137. /*
  138. * Remove tokens around the return value.
  139. * If comments don't exist, remove extra spaces as well.
  140. */
  141. if (commentsExist) {
  142. fixes.push(
  143. fixer.remove(openingBrace),
  144. fixer.remove(closingBrace),
  145. fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword
  146. );
  147. } else {
  148. fixes.push(
  149. fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]),
  150. fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]])
  151. );
  152. }
  153. /*
  154. * If the first token of the reutrn value is `{`,
  155. * enclose the return value by parentheses to avoid syntax error.
  156. */
  157. if (astUtils.isOpeningBraceToken(firstValueToken)) {
  158. fixes.push(
  159. fixer.insertTextBefore(firstValueToken, "("),
  160. fixer.insertTextAfter(lastValueToken, ")")
  161. );
  162. }
  163. /*
  164. * If the last token of the return statement is semicolon, remove it.
  165. * Non-block arrow body is an expression, not a statement.
  166. */
  167. if (astUtils.isSemicolonToken(lastValueToken)) {
  168. fixes.push(fixer.remove(lastValueToken));
  169. }
  170. return fixes;
  171. }
  172. });
  173. }
  174. } else {
  175. if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) {
  176. context.report({
  177. node,
  178. loc: arrowBody.loc.start,
  179. messageId: "expectedBlock",
  180. fix(fixer) {
  181. const fixes = [];
  182. const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken);
  183. const firstBodyToken = sourceCode.getTokenAfter(arrowToken);
  184. const lastBodyToken = sourceCode.getLastToken(node);
  185. const isParenthesisedObjectLiteral =
  186. astUtils.isOpeningParenToken(firstBodyToken) &&
  187. astUtils.isOpeningBraceToken(sourceCode.getTokenAfter(firstBodyToken));
  188. // Wrap the value by a block and a return statement.
  189. fixes.push(
  190. fixer.insertTextBefore(firstBodyToken, "{return "),
  191. fixer.insertTextAfter(lastBodyToken, "}")
  192. );
  193. // If the value is object literal, remove parentheses which were forced by syntax.
  194. if (isParenthesisedObjectLiteral) {
  195. fixes.push(
  196. fixer.remove(firstBodyToken),
  197. fixer.remove(findClosingParen(firstBodyToken))
  198. );
  199. }
  200. return fixes;
  201. }
  202. });
  203. }
  204. }
  205. }
  206. return {
  207. "ArrowFunctionExpression:exit": validate
  208. };
  209. }
  210. };