Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

no-else-return.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /**
  2. * @fileoverview Rule to flag `else` after a `return` in `if`
  3. * @author Ian Christian Myers
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. const FixTracker = require("../util/fix-tracker");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "disallow `else` blocks after `return` statements in `if` statements",
  19. category: "Best Practices",
  20. recommended: false,
  21. url: "https://eslint.org/docs/rules/no-else-return"
  22. },
  23. schema: [{
  24. type: "object",
  25. properties: {
  26. allowElseIf: {
  27. type: "boolean"
  28. }
  29. },
  30. additionalProperties: false
  31. }],
  32. fixable: "code",
  33. messages: {
  34. unexpected: "Unnecessary 'else' after 'return'."
  35. }
  36. },
  37. create(context) {
  38. //--------------------------------------------------------------------------
  39. // Helpers
  40. //--------------------------------------------------------------------------
  41. /**
  42. * Display the context report if rule is violated
  43. *
  44. * @param {Node} node The 'else' node
  45. * @returns {void}
  46. */
  47. function displayReport(node) {
  48. context.report({
  49. node,
  50. messageId: "unexpected",
  51. fix: fixer => {
  52. const sourceCode = context.getSourceCode();
  53. const startToken = sourceCode.getFirstToken(node);
  54. const elseToken = sourceCode.getTokenBefore(startToken);
  55. const source = sourceCode.getText(node);
  56. const lastIfToken = sourceCode.getTokenBefore(elseToken);
  57. let fixedSource, firstTokenOfElseBlock;
  58. if (startToken.type === "Punctuator" && startToken.value === "{") {
  59. firstTokenOfElseBlock = sourceCode.getTokenAfter(startToken);
  60. } else {
  61. firstTokenOfElseBlock = startToken;
  62. }
  63. /*
  64. * If the if block does not have curly braces and does not end in a semicolon
  65. * and the else block starts with (, [, /, +, ` or -, then it is not
  66. * safe to remove the else keyword, because ASI will not add a semicolon
  67. * after the if block
  68. */
  69. const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";";
  70. const elseBlockUnsafe = /^[([/+`-]/.test(firstTokenOfElseBlock.value);
  71. if (ifBlockMaybeUnsafe && elseBlockUnsafe) {
  72. return null;
  73. }
  74. const endToken = sourceCode.getLastToken(node);
  75. const lastTokenOfElseBlock = sourceCode.getTokenBefore(endToken);
  76. if (lastTokenOfElseBlock.value !== ";") {
  77. const nextToken = sourceCode.getTokenAfter(endToken);
  78. const nextTokenUnsafe = nextToken && /^[([/+`-]/.test(nextToken.value);
  79. const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line;
  80. /*
  81. * If the else block contents does not end in a semicolon,
  82. * and the else block starts with (, [, /, +, ` or -, then it is not
  83. * safe to remove the else block, because ASI will not add a semicolon
  84. * after the remaining else block contents
  85. */
  86. if (nextTokenUnsafe || (nextTokenOnSameLine && nextToken.value !== "}")) {
  87. return null;
  88. }
  89. }
  90. if (startToken.type === "Punctuator" && startToken.value === "{") {
  91. fixedSource = source.slice(1, -1);
  92. } else {
  93. fixedSource = source;
  94. }
  95. /*
  96. * Extend the replacement range to include the entire
  97. * function to avoid conflicting with no-useless-return.
  98. * https://github.com/eslint/eslint/issues/8026
  99. */
  100. return new FixTracker(fixer, sourceCode)
  101. .retainEnclosingFunction(node)
  102. .replaceTextRange([elseToken.range[0], node.range[1]], fixedSource);
  103. }
  104. });
  105. }
  106. /**
  107. * Check to see if the node is a ReturnStatement
  108. *
  109. * @param {Node} node The node being evaluated
  110. * @returns {boolean} True if node is a return
  111. */
  112. function checkForReturn(node) {
  113. return node.type === "ReturnStatement";
  114. }
  115. /**
  116. * Naive return checking, does not iterate through the whole
  117. * BlockStatement because we make the assumption that the ReturnStatement
  118. * will be the last node in the body of the BlockStatement.
  119. *
  120. * @param {Node} node The consequent/alternate node
  121. * @returns {boolean} True if it has a return
  122. */
  123. function naiveHasReturn(node) {
  124. if (node.type === "BlockStatement") {
  125. const body = node.body,
  126. lastChildNode = body[body.length - 1];
  127. return lastChildNode && checkForReturn(lastChildNode);
  128. }
  129. return checkForReturn(node);
  130. }
  131. /**
  132. * Check to see if the node is valid for evaluation,
  133. * meaning it has an else.
  134. *
  135. * @param {Node} node The node being evaluated
  136. * @returns {boolean} True if the node is valid
  137. */
  138. function hasElse(node) {
  139. return node.alternate && node.consequent;
  140. }
  141. /**
  142. * If the consequent is an IfStatement, check to see if it has an else
  143. * and both its consequent and alternate path return, meaning this is
  144. * a nested case of rule violation. If-Else not considered currently.
  145. *
  146. * @param {Node} node The consequent node
  147. * @returns {boolean} True if this is a nested rule violation
  148. */
  149. function checkForIf(node) {
  150. return node.type === "IfStatement" && hasElse(node) &&
  151. naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent);
  152. }
  153. /**
  154. * Check the consequent/body node to make sure it is not
  155. * a ReturnStatement or an IfStatement that returns on both
  156. * code paths.
  157. *
  158. * @param {Node} node The consequent or body node
  159. * @param {Node} alternate The alternate node
  160. * @returns {boolean} `true` if it is a Return/If node that always returns.
  161. */
  162. function checkForReturnOrIf(node) {
  163. return checkForReturn(node) || checkForIf(node);
  164. }
  165. /**
  166. * Check whether a node returns in every codepath.
  167. * @param {Node} node The node to be checked
  168. * @returns {boolean} `true` if it returns on every codepath.
  169. */
  170. function alwaysReturns(node) {
  171. if (node.type === "BlockStatement") {
  172. // If we have a BlockStatement, check each consequent body node.
  173. return node.body.some(checkForReturnOrIf);
  174. }
  175. /*
  176. * If not a block statement, make sure the consequent isn't a
  177. * ReturnStatement or an IfStatement with returns on both paths.
  178. */
  179. return checkForReturnOrIf(node);
  180. }
  181. /**
  182. * Check the if statement, but don't catch else-if blocks.
  183. * @returns {void}
  184. * @param {Node} node The node for the if statement to check
  185. * @private
  186. */
  187. function checkIfWithoutElse(node) {
  188. const parent = node.parent;
  189. /*
  190. * Fixing this would require splitting one statement into two, so no error should
  191. * be reported if this node is in a position where only one statement is allowed.
  192. */
  193. if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
  194. return;
  195. }
  196. const consequents = [];
  197. let alternate;
  198. for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) {
  199. if (!currentNode.alternate) {
  200. return;
  201. }
  202. consequents.push(currentNode.consequent);
  203. alternate = currentNode.alternate;
  204. }
  205. if (consequents.every(alwaysReturns)) {
  206. displayReport(alternate);
  207. }
  208. }
  209. /**
  210. * Check the if statement
  211. * @returns {void}
  212. * @param {Node} node The node for the if statement to check
  213. * @private
  214. */
  215. function checkIfWithElse(node) {
  216. const parent = node.parent;
  217. /*
  218. * Fixing this would require splitting one statement into two, so no error should
  219. * be reported if this node is in a position where only one statement is allowed.
  220. */
  221. if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
  222. return;
  223. }
  224. const alternate = node.alternate;
  225. if (alternate && alwaysReturns(node.consequent)) {
  226. displayReport(alternate);
  227. }
  228. }
  229. const allowElseIf = !(context.options[0] && context.options[0].allowElseIf === false);
  230. //--------------------------------------------------------------------------
  231. // Public API
  232. //--------------------------------------------------------------------------
  233. return {
  234. "IfStatement:exit": allowElseIf ? checkIfWithoutElse : checkIfWithElse
  235. };
  236. }
  237. };